小程序引入whatwg-url,因环境限制,导致编译小程序会报错,现在只能把部分代码放在本地,之后再进行优化处理

This commit is contained in:
wkj 2023-12-09 00:56:36 +08:00
parent 1fd17a6932
commit 9f9a05ad1e
33 changed files with 5755 additions and 12 deletions

View File

@ -146,7 +146,7 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
action: 'create',
type: 'data',
entity,
priority: 10,
priority: 10, // 优先级要高先于真正的data检查进行
checker: (data) => {
if (data instanceof Array) {
data.forEach(ele => {
@ -181,7 +181,7 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
entity,
action: 'create',
type: 'logicalData',
priority: types_1.CHECKER_MAX_PRIORITY,
priority: types_1.CHECKER_MAX_PRIORITY, // 优先级要放在最低所有前置的checker/trigger将数据完整之后再在这里检测
checker: (operation, context) => {
const { data } = operation;
if (data instanceof Array) {
@ -197,9 +197,9 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
}
}, {
entity,
action: 'update',
action: 'update', // 只检查update其它状态转换的action应该不会涉及unique约束的属性
type: 'logicalData',
priority: types_1.CHECKER_MAX_PRIORITY,
priority: types_1.CHECKER_MAX_PRIORITY, // 优先级要放在最低所有前置的checker/trigger将数据完整之后再在这里检测
checker: (operation, context) => {
const { data, filter: operationFilter } = operation;
if (data) {

View File

@ -1,3 +1,4 @@
/// <reference types="node" />
/**
* assert打包体积过大
*/

View File

@ -1,4 +1,3 @@
import { URL, URLSearchParams } from 'whatwg-url';
declare const url: typeof URL;
declare const urlSearchParams: typeof URLSearchParams;
declare const url: URL;
declare const urlSearchParams: URLSearchParams;
export { url, urlSearchParams };

View File

@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.urlSearchParams = exports.url = void 0;
const whatwg_url_1 = require("whatwg-url");
const whatwg_url_1 = require("./whatwg-url");
const url = whatwg_url_1.URL;
exports.url = url;
const urlSearchParams = whatwg_url_1.URLSearchParams;

3
lib/utils/url/whatwg-url/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
declare const URL: URL;
declare const URLSearchParams: URLSearchParams;
export { URL, URLSearchParams };

View File

@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.URLSearchParams = exports.URL = void 0;
/**
* 为了能在小程序中使用URLURLSearchParams
* 但whatwg-url-without-unicode这个库未更新把其的代码放本地进行更新
*/
const whatwgUrl = require('./lib/URL');
const whatwgUrlSearchParams = require('./lib/URLSearchParams');
const sharedGlobalObject = {};
whatwgUrl.install(sharedGlobalObject);
whatwgUrlSearchParams.install(sharedGlobalObject);
const URL = sharedGlobalObject.URL;
exports.URL = URL;
const URLSearchParams = sharedGlobalObject.URLSearchParams;
exports.URLSearchParams = URLSearchParams;

View File

@ -0,0 +1,20 @@
declare const _default: {
implementation: {
new (globalObject: any, constructorArgs: any): {
href: string;
readonly origin: any;
protocol: string;
username: any;
password: any;
host: any;
hostname: any;
port: string;
pathname: any;
search: string;
readonly searchParams: any;
hash: string;
toJSON(): string;
};
};
};
export default _default;

View File

@ -0,0 +1,175 @@
"use strict";
// @ts-nocheck
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const url_state_machine_1 = tslib_1.__importDefault(require("./url-state-machine"));
const urlencoded_1 = tslib_1.__importDefault(require("./urlencoded"));
const URLSearchParams_1 = tslib_1.__importDefault(require("./URLSearchParams"));
const implementation = class URLImpl {
constructor(globalObject, constructorArgs) {
const url = constructorArgs[0];
const base = constructorArgs[1];
let parsedBase = null;
if (base !== undefined) {
parsedBase = url_state_machine_1.default.basicURLParse(base);
if (parsedBase === null) {
throw new TypeError(`Invalid base URL: ${base}`);
}
}
const parsedURL = url_state_machine_1.default.basicURLParse(url, { baseURL: parsedBase });
if (parsedURL === null) {
throw new TypeError(`Invalid URL: ${url}`);
}
const query = parsedURL.query !== null ? parsedURL.query : "";
this._url = parsedURL;
// We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips
// question mark by default. Therefore the doNotStripQMark hack is used.
this._query = URLSearchParams_1.default.createImpl(globalObject, [query], { doNotStripQMark: true });
this._query._url = this;
}
get href() {
return url_state_machine_1.default.serializeURL(this._url);
}
set href(v) {
const parsedURL = url_state_machine_1.default.basicURLParse(v);
if (parsedURL === null) {
throw new TypeError(`Invalid URL: ${v}`);
}
this._url = parsedURL;
this._query._list.splice(0);
const { query } = parsedURL;
if (query !== null) {
this._query._list = urlencoded_1.default.parseUrlencoded(query);
}
}
get origin() {
return url_state_machine_1.default.serializeURLOrigin(this._url);
}
get protocol() {
return this._url.scheme + ":";
}
set protocol(v) {
url_state_machine_1.default.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
}
get username() {
return this._url.username;
}
set username(v) {
if (url_state_machine_1.default.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
url_state_machine_1.default.setTheUsername(this._url, v);
}
get password() {
return this._url.password;
}
set password(v) {
if (url_state_machine_1.default.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
url_state_machine_1.default.setThePassword(this._url, v);
}
get host() {
const url = this._url;
if (url.host === null) {
return "";
}
if (url.port === null) {
return url_state_machine_1.default.serializeHost(url.host);
}
return url_state_machine_1.default.serializeHost(url.host) + ":" + url_state_machine_1.default.serializeInteger(url.port);
}
set host(v) {
if (this._url.cannotBeABaseURL) {
return;
}
url_state_machine_1.default.basicURLParse(v, { url: this._url, stateOverride: "host" });
}
get hostname() {
if (this._url.host === null) {
return "";
}
return url_state_machine_1.default.serializeHost(this._url.host);
}
set hostname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
url_state_machine_1.default.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
}
get port() {
if (this._url.port === null) {
return "";
}
return url_state_machine_1.default.serializeInteger(this._url.port);
}
set port(v) {
if (url_state_machine_1.default.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
if (v === "") {
this._url.port = null;
}
else {
url_state_machine_1.default.basicURLParse(v, { url: this._url, stateOverride: "port" });
}
}
get pathname() {
if (this._url.cannotBeABaseURL) {
return this._url.path[0];
}
if (this._url.path.length === 0) {
return "";
}
return "/" + this._url.path.join("/");
}
set pathname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
this._url.path = [];
url_state_machine_1.default.basicURLParse(v, { url: this._url, stateOverride: "path start" });
}
get search() {
if (this._url.query === null || this._url.query === "") {
return "";
}
return "?" + this._url.query;
}
set search(v) {
const url = this._url;
if (v === "") {
url.query = null;
this._query._list = [];
return;
}
const input = v[0] === "?" ? v.substring(1) : v;
url.query = "";
url_state_machine_1.default.basicURLParse(input, { url, stateOverride: "query" });
this._query._list = urlencoded_1.default.parseUrlencoded(input);
}
get searchParams() {
return this._query;
}
get hash() {
if (this._url.fragment === null || this._url.fragment === "") {
return "";
}
return "#" + this._url.fragment;
}
set hash(v) {
if (v === "") {
this._url.fragment = null;
return;
}
const input = v[0] === "#" ? v.substring(1) : v;
this._url.fragment = "";
url_state_machine_1.default.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
}
toJSON() {
return this.href;
}
};
exports.default = {
implementation
};

1
lib/utils/url/whatwg-url/lib/URL.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,298 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
// @ts-nocheck
const webidl_conversions_1 = tslib_1.__importDefault(require("webidl-conversions"));
const utils_1 = tslib_1.__importDefault(require("./utils"));
const impl = utils_1.default.implSymbol;
const ctorRegistry = utils_1.default.ctorRegistrySymbol;
const iface = {
// When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
// method into this array. It allows objects that directly implements *those* interfaces to be recognized as
// implementing this mixin interface.
_mixedIntoPredicates: [],
is(obj) {
if (obj) {
if (utils_1.default.hasOwn(obj, impl) && obj[impl] instanceof URL_impl_1.default.implementation) {
return true;
}
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof URL_impl_1.default.implementation) {
return true;
}
const wrapper = utils_1.default.wrapperForImpl(obj);
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
},
convert(obj, { context = "The provided value" } = {}) {
if (module.exports.is(obj)) {
return utils_1.default.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'URL'.`);
},
create(globalObject, constructorArgs, privateData) {
if (globalObject[ctorRegistry] === undefined) {
throw new Error("Internal error: invalid global object");
}
const ctor = globalObject[ctorRegistry]["URL"];
if (ctor === undefined) {
throw new Error("Internal error: constructor URL is not installed on the passed global object");
}
let obj = Object.create(ctor.prototype);
obj = iface.setup(obj, globalObject, constructorArgs, privateData);
return obj;
},
createImpl(globalObject, constructorArgs, privateData) {
const obj = iface.create(globalObject, constructorArgs, privateData);
return utils_1.default.implForWrapper(obj);
},
_internalSetup(obj) { },
setup(obj, globalObject, constructorArgs = [], privateData = {}) {
privateData.wrapper = obj;
iface._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new URL_impl_1.default.implementation(globalObject, constructorArgs, privateData),
configurable: true
});
obj[impl][utils_1.default.wrapperSymbol] = obj;
if (URL_impl_1.default.init) {
URL_impl_1.default.init(obj[impl], privateData);
}
return obj;
},
install(globalObject) {
class URL {
constructor(url) {
if (arguments.length < 1) {
throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default["USVString"](curArg, { context: "Failed to construct 'URL': parameter 1" });
args.push(curArg);
}
{
let curArg = arguments[1];
if (curArg !== undefined) {
curArg = webidl_conversions_1.default["USVString"](curArg, { context: "Failed to construct 'URL': parameter 2" });
}
args.push(curArg);
}
return iface.setup(Object.create(this.constructor.prototype), globalObject, args);
}
toJSON() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl].toJSON();
}
get href() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["href"];
}
set href(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" });
this[impl]["href"] = V;
}
toString() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["href"];
}
get origin() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["origin"];
}
get protocol() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["protocol"];
}
set protocol(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'protocol' property on 'URL': The provided value"
});
this[impl]["protocol"] = V;
}
get username() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["username"];
}
set username(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'username' property on 'URL': The provided value"
});
this[impl]["username"] = V;
}
get password() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["password"];
}
set password(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'password' property on 'URL': The provided value"
});
this[impl]["password"] = V;
}
get host() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["host"];
}
set host(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" });
this[impl]["host"] = V;
}
get hostname() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["hostname"];
}
set hostname(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'hostname' property on 'URL': The provided value"
});
this[impl]["hostname"] = V;
}
get port() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["port"];
}
set port(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" });
this[impl]["port"] = V;
}
get pathname() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["pathname"];
}
set pathname(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'pathname' property on 'URL': The provided value"
});
this[impl]["pathname"] = V;
}
get search() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["search"];
}
set search(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, {
context: "Failed to set the 'search' property on 'URL': The provided value"
});
this[impl]["search"] = V;
}
get searchParams() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return utils_1.default.getSameObject(this, "searchParams", () => {
return utils_1.default.tryWrapperForImpl(this[impl]["searchParams"]);
});
}
get hash() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["hash"];
}
set hash(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = webidl_conversions_1.default["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" });
this[impl]["hash"] = V;
}
}
Object.defineProperties(URL.prototype, {
toJSON: { enumerable: true },
href: { enumerable: true },
toString: { enumerable: true },
origin: { enumerable: true },
protocol: { enumerable: true },
username: { enumerable: true },
password: { enumerable: true },
host: { enumerable: true },
hostname: { enumerable: true },
port: { enumerable: true },
pathname: { enumerable: true },
search: { enumerable: true },
searchParams: { enumerable: true },
hash: { enumerable: true },
[Symbol.toStringTag]: { value: "URL", configurable: true }
});
if (globalObject[ctorRegistry] === undefined) {
globalObject[ctorRegistry] = Object.create(null);
}
globalObject[ctorRegistry]["URL"] = URL;
Object.defineProperty(globalObject, "URL", {
configurable: true,
writable: true,
value: URL
});
}
};
// iface
module.exports = iface;
// const Impl = require('./URL-impl');
const URL_impl_1 = tslib_1.__importDefault(require("./URL-impl"));

View File

@ -0,0 +1,19 @@
declare const _default: {
implementation: {
new (globalObject: any, constructorArgs: any, { doNotStripQMark }: {
doNotStripQMark?: boolean | undefined;
}): {
_updateSteps(): void;
append(name: any, value: any): void;
delete(name: any): void;
get(name: any): any;
getAll(name: any): any[];
has(name: any): boolean;
set(name: any, value: any): void;
sort(): void;
toString(): string;
[Symbol.iterator](): any;
};
};
};
export default _default;

View File

@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
// @ts-nocheck
const urlencoded_1 = tslib_1.__importDefault(require("./urlencoded"));
function stableSortBy(arr, compare) {
return arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
}
const implementation = class URLSearchParamsImpl {
constructor(globalObject, constructorArgs, { doNotStripQMark = false }) {
let init = constructorArgs[0];
this._list = [];
this._url = null;
if (!doNotStripQMark && typeof init === 'string' && init[0] === '?') {
init = init.slice(1);
}
if (Array.isArray(init)) {
for (const pair of init) {
if (pair.length !== 2) {
throw new TypeError("Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " +
'contain exactly two elements.');
}
this._list.push([pair[0], pair[1]]);
}
}
else if (typeof init === 'object' &&
Object.getPrototypeOf(init) === null) {
for (const name of Object.keys(init)) {
const value = init[name];
this._list.push([name, value]);
}
}
else {
this._list = urlencoded_1.default.parseUrlencoded(init);
}
}
_updateSteps() {
if (this._url !== null) {
let query = urlencoded_1.default.serializeUrlencoded(this._list);
if (query === '') {
query = null;
}
this._url._url.query = query;
}
}
append(name, value) {
this._list.push([name, value]);
this._updateSteps();
}
delete(name) {
let i = 0;
while (i < this._list.length) {
if (this._list[i][0] === name) {
this._list.splice(i, 1);
}
else {
i++;
}
}
this._updateSteps();
}
get(name) {
for (const tuple of this._list) {
if (tuple[0] === name) {
return tuple[1];
}
}
return null;
}
getAll(name) {
const output = [];
for (const tuple of this._list) {
if (tuple[0] === name) {
output.push(tuple[1]);
}
}
return output;
}
has(name) {
for (const tuple of this._list) {
if (tuple[0] === name) {
return true;
}
}
return false;
}
set(name, value) {
let found = false;
let i = 0;
while (i < this._list.length) {
if (this._list[i][0] === name) {
if (found) {
this._list.splice(i, 1);
}
else {
found = true;
this._list[i][1] = value;
i++;
}
}
else {
i++;
}
}
if (!found) {
this._list.push([name, value]);
}
this._updateSteps();
}
sort() {
this._list = stableSortBy(this._list, (a, b) => a[0] > b[0]);
this._updateSteps();
}
[Symbol.iterator]() {
return this._list[Symbol.iterator]();
}
toString() {
return urlencoded_1.default.serializeUrlencoded(this._list);
}
};
exports.default = {
implementation
};

View File

@ -0,0 +1 @@
export {};

View File

@ -0,0 +1,426 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
// @ts-nocheck
const webidl_conversions_1 = tslib_1.__importDefault(require("webidl-conversions"));
const utils_1 = tslib_1.__importDefault(require("./utils"));
const impl = utils_1.default.implSymbol;
const ctorRegistry = utils_1.default.ctorRegistrySymbol;
const IteratorPrototype = Object.create(utils_1.default.IteratorPrototype, {
next: {
value: function next() {
const internal = this[utils_1.default.iterInternalSymbol];
const { target, kind, index } = internal;
const values = Array.from(target[impl]);
const len = values.length;
if (index >= len) {
return { value: undefined, done: true };
}
const pair = values[index];
internal.index = index + 1;
const [key, value] = pair.map(utils_1.default.tryWrapperForImpl);
let result;
switch (kind) {
case 'key':
result = key;
break;
case 'value':
result = value;
break;
case 'key+value':
result = [key, value];
break;
}
return { value: result, done: false };
},
writable: true,
enumerable: true,
configurable: true,
},
[Symbol.toStringTag]: {
value: 'URLSearchParams Iterator',
configurable: true,
},
});
const iface = {
// When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
// method into this array. It allows objects that directly implements *those* interfaces to be recognized as
// implementing this mixin interface.
_mixedIntoPredicates: [],
is(obj) {
if (obj) {
if (utils_1.default.hasOwn(obj, impl) &&
obj[impl] instanceof URLSearchParams_impl_1.default.implementation) {
return true;
}
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof URLSearchParams_impl_1.default.implementation) {
return true;
}
const wrapper = utils_1.default.wrapperForImpl(obj);
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
},
convert(obj, { context = 'The provided value' } = {}) {
if (module.exports.is(obj)) {
return utils_1.default.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'URLSearchParams'.`);
},
createDefaultIterator(target, kind) {
const iterator = Object.create(IteratorPrototype);
Object.defineProperty(iterator, utils_1.default.iterInternalSymbol, {
value: { target, kind, index: 0 },
configurable: true,
});
return iterator;
},
create(globalObject, constructorArgs, privateData) {
if (globalObject[ctorRegistry] === undefined) {
throw new Error('Internal error: invalid global object');
}
const ctor = globalObject[ctorRegistry]['URLSearchParams'];
if (ctor === undefined) {
throw new Error('Internal error: constructor URLSearchParams is not installed on the passed global object');
}
let obj = Object.create(ctor.prototype);
obj = iface.setup(obj, globalObject, constructorArgs, privateData);
return obj;
},
createImpl(globalObject, constructorArgs, privateData) {
const obj = iface.create(globalObject, constructorArgs, privateData);
return utils_1.default.implForWrapper(obj);
},
_internalSetup(obj) { },
setup(obj, globalObject, constructorArgs = [], privateData = {}) {
privateData.wrapper = obj;
iface._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new URLSearchParams_impl_1.default.implementation(globalObject, constructorArgs, privateData),
configurable: true,
});
obj[impl][utils_1.default.wrapperSymbol] = obj;
if (URLSearchParams_impl_1.default.init) {
URLSearchParams_impl_1.default.init(obj[impl], privateData);
}
return obj;
},
install(globalObject) {
class URLSearchParams {
constructor() {
const args = [];
{
let curArg = arguments[0];
if (curArg !== undefined) {
if (utils_1.default.isObject(curArg)) {
if (curArg[Symbol.iterator] !== undefined) {
if (!utils_1.default.isObject(curArg)) {
throw new TypeError("Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
' is not an iterable object.');
}
else {
const V = [];
const tmp = curArg;
for (let nextItem of tmp) {
if (!utils_1.default.isObject(nextItem)) {
throw new TypeError("Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
"'s element" +
' is not an iterable object.');
}
else {
const V = [];
const tmp = nextItem;
for (let nextItem of tmp) {
nextItem = webidl_conversions_1.default['USVString'](nextItem, {
context: "Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
"'s element" +
"'s element",
});
V.push(nextItem);
}
nextItem = V;
}
V.push(nextItem);
}
curArg = V;
}
}
else {
if (!utils_1.default.isObject(curArg)) {
throw new TypeError("Failed to construct 'URLSearchParams': parameter 1" +
' record' +
' is not an object.');
}
else {
const result = Object.create(null);
for (const key of Reflect.ownKeys(curArg)) {
const desc = Object.getOwnPropertyDescriptor(curArg, key);
if (desc && desc.enumerable) {
let typedKey = key;
typedKey = webidl_conversions_1.default['USVString'](typedKey, {
context: "Failed to construct 'URLSearchParams': parameter 1" +
' record' +
"'s key",
});
let typedValue = curArg[key];
typedValue = webidl_conversions_1.default['USVString'](typedValue, {
context: "Failed to construct 'URLSearchParams': parameter 1" +
' record' +
"'s value",
});
result[typedKey] = typedValue;
}
}
curArg = result;
}
}
}
else {
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to construct 'URLSearchParams': parameter 1",
});
}
}
else {
curArg = '';
}
args.push(curArg);
}
return iface.setup(Object.create(this.constructor.prototype), globalObject, args);
}
append(name, value) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 2) {
throw new TypeError("Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'append' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
{
let curArg = arguments[1];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'append' on 'URLSearchParams': parameter 2",
});
args.push(curArg);
}
return this[impl].append(...args);
}
delete(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'delete' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].delete(...args);
}
get(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'get' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].get(...args);
}
getAll(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'getAll' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return utils_1.default.tryWrapperForImpl(this[impl].getAll(...args));
}
has(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'has' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].has(...args);
}
set(name, value) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 2) {
throw new TypeError("Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only " +
arguments.length +
' present.');
}
const args = [];
{
let curArg = arguments[0];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'set' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
{
let curArg = arguments[1];
curArg = webidl_conversions_1.default['USVString'](curArg, {
context: "Failed to execute 'set' on 'URLSearchParams': parameter 2",
});
args.push(curArg);
}
return this[impl].set(...args);
}
sort() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return this[impl].sort();
}
toString() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return this[impl].toString();
}
keys() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'key');
}
values() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'value');
}
entries() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'key+value');
}
forEach(callback) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError("Failed to execute 'forEach' on 'iterable': 1 argument required, " +
'but only 0 present.');
}
if (typeof callback !== 'function') {
throw new TypeError("Failed to execute 'forEach' on 'iterable': The callback provided " +
'as parameter 1 is not a function.');
}
const thisArg = arguments[1];
let pairs = Array.from(this[impl]);
let i = 0;
while (i < pairs.length) {
const [key, value] = pairs[i].map(utils_1.default.tryWrapperForImpl);
callback.call(thisArg, value, key, this);
pairs = Array.from(this[impl]);
i++;
}
}
}
Object.defineProperties(URLSearchParams.prototype, {
append: { enumerable: true },
delete: { enumerable: true },
get: { enumerable: true },
getAll: { enumerable: true },
has: { enumerable: true },
set: { enumerable: true },
sort: { enumerable: true },
toString: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true },
forEach: { enumerable: true },
[Symbol.toStringTag]: {
value: 'URLSearchParams',
configurable: true,
},
[Symbol.iterator]: {
value: URLSearchParams.prototype.entries,
configurable: true,
writable: true,
},
});
if (globalObject[ctorRegistry] === undefined) {
globalObject[ctorRegistry] = Object.create(null);
}
globalObject[ctorRegistry]['URLSearchParams'] = URLSearchParams;
Object.defineProperty(globalObject, 'URLSearchParams', {
configurable: true,
writable: true,
value: URLSearchParams,
});
},
};
// iface
module.exports = iface;
// const Impl = require('./URLSearchParams-impl')
const URLSearchParams_impl_1 = tslib_1.__importDefault(require("./URLSearchParams-impl"));

12
lib/utils/url/whatwg-url/lib/infra.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
declare function isASCIIDigit(c: number): boolean;
declare function isASCIIAlpha(c: number): boolean;
declare function isASCIIAlphanumeric(c: number): boolean;
declare function isASCIIHex(c: number): boolean;
export { isASCIIDigit, isASCIIAlpha, isASCIIAlphanumeric, isASCIIHex, };
declare const _default: {
isASCIIDigit: typeof isASCIIDigit;
isASCIIAlpha: typeof isASCIIAlpha;
isASCIIAlphanumeric: typeof isASCIIAlphanumeric;
isASCIIHex: typeof isASCIIHex;
};
export default _default;

View File

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isASCIIHex = exports.isASCIIAlphanumeric = exports.isASCIIAlpha = exports.isASCIIDigit = void 0;
function isASCIIDigit(c) {
return c >= 0x30 && c <= 0x39;
}
exports.isASCIIDigit = isASCIIDigit;
function isASCIIAlpha(c) {
return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
}
exports.isASCIIAlpha = isASCIIAlpha;
function isASCIIAlphanumeric(c) {
return isASCIIAlpha(c) || isASCIIDigit(c);
}
exports.isASCIIAlphanumeric = isASCIIAlphanumeric;
function isASCIIHex(c) {
return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
}
exports.isASCIIHex = isASCIIHex;
exports.default = {
isASCIIDigit,
isASCIIAlpha,
isASCIIAlphanumeric,
isASCIIHex
};

View File

@ -0,0 +1,24 @@
declare function serializeHost(host: any): any;
declare function cannotHaveAUsernamePasswordPort(url: any): any;
declare function serializeURL(url: any, excludeFragment: any): string;
export declare const serializeURL: typeof serializeURL;
export declare const serializeURLOrigin: (url: any) => any;
export declare const basicURLParse: (input: any, options: any) => any;
export declare const setTheUsername: (url: any, username: any) => void;
export declare const setThePassword: (url: any, password: any) => void;
export declare const serializeHost: typeof serializeHost;
export declare const cannotHaveAUsernamePasswordPort: typeof cannotHaveAUsernamePasswordPort;
export declare const serializeInteger: (integer: any) => string;
export declare const parseURL: (input: any, options: any) => any;
declare const _default: {
parseURL: (input: any, options: any) => any;
serializeInteger: (integer: any) => string;
serializeHost: typeof serializeHost;
cannotHaveAUsernamePasswordPort: typeof cannotHaveAUsernamePasswordPort;
setThePassword: (url: any, password: any) => void;
setTheUsername: (url: any, username: any) => void;
basicURLParse: (input: any, options: any) => any;
serializeURLOrigin: (url: any) => any;
serializeURL: typeof serializeURL;
};
export default _default;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,15 @@
/// <reference types="node" />
import { Buffer } from 'buffer';
declare function percentEncode(c: number): string;
declare function percentDecode(input: Buffer): Buffer;
declare function serializeUrlencoded(tuples: any[], encodingOverride?: undefined): string;
declare function parseUrlencoded(input: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>): string[][];
declare function ucs2decode(string: string): number[];
declare const _default: {
percentEncode: typeof percentEncode;
percentDecode: typeof percentDecode;
parseUrlencoded: typeof parseUrlencoded;
serializeUrlencoded: typeof serializeUrlencoded;
ucs2decode: typeof ucs2decode;
};
export default _default;

View File

@ -0,0 +1,162 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const buffer_1 = require("buffer");
const infra_1 = require("./infra");
function strictlySplitByteSequence(buf, cp) {
const list = [];
let last = 0;
let i = buf.indexOf(cp);
while (i >= 0) {
list.push(buf.slice(last, i));
last = i + 1;
i = buf.indexOf(cp, last);
}
if (last !== buf.length) {
list.push(buf.slice(last));
}
return list;
}
function replaceByteInByteSequence(buf, from, to) {
let i = buf.indexOf(from);
while (i >= 0) {
buf[i] = to;
i = buf.indexOf(from, i + 1);
}
return buf;
}
function percentEncode(c) {
let hex = c.toString(16).toUpperCase();
if (hex.length === 1) {
hex = '0' + hex;
}
return '%' + hex;
}
function percentDecode(input) {
const output = buffer_1.Buffer.alloc(input.byteLength);
let ptr = 0;
for (let i = 0; i < input.length; ++i) {
if (input[i] !== 37 ||
!(0, infra_1.isASCIIHex)(input[i + 1]) ||
!(0, infra_1.isASCIIHex)(input[i + 2])) {
output[ptr++] = input[i];
}
else {
output[ptr++] = parseInt(input.slice(i + 1, i + 3).toString(), 16);
i += 2;
}
}
return output.slice(0, ptr);
}
function parseUrlencoded2(input) {
const sequences = strictlySplitByteSequence(input, 38);
const output = [];
for (const bytes of sequences) {
if (bytes.length === 0) {
continue;
}
let name;
let value;
const indexOfEqual = bytes.indexOf(61);
if (indexOfEqual >= 0) {
name = bytes.slice(0, indexOfEqual);
value = bytes.slice(indexOfEqual + 1);
}
else {
name = bytes;
value = buffer_1.Buffer.alloc(0);
}
name = replaceByteInByteSequence(buffer_1.Buffer.from(name), 43, 32);
value = replaceByteInByteSequence(buffer_1.Buffer.from(value), 43, 32);
output.push([
percentDecode(name).toString(),
percentDecode(value).toString(),
]);
}
return output;
}
function serializeUrlencodedByte(input) {
let output = '';
for (const byte of input) {
if (byte === 32) {
output += '+';
}
else if (byte === 42 ||
byte === 45 ||
byte === 46 ||
(byte >= 48 && byte <= 57) ||
(byte >= 65 && byte <= 90) ||
byte === 95 ||
(byte >= 97 && byte <= 122)) {
output += String.fromCodePoint(byte);
}
else {
output += percentEncode(byte);
}
}
return output;
}
function serializeUrlencoded(tuples, encodingOverride = undefined) {
let encoding = 'utf-8';
if (encodingOverride !== undefined) {
encoding = encodingOverride;
}
let output = '';
for (const [i, tuple] of tuples.entries()) {
// TODO: handle encoding override
const name = serializeUrlencodedByte(buffer_1.Buffer.from(tuple[0]));
let value = tuple[1];
if (tuple.length > 2 && tuple[2] !== undefined) {
if (tuple[2] === 'hidden' && name === '_charset_') {
value = encoding;
}
else if (tuple[2] === 'file') {
// value is a File object
value = value.name;
}
}
value = serializeUrlencodedByte(buffer_1.Buffer.from(value));
if (i !== 0) {
output += '&';
}
output += `${name}=${value}`;
}
return output;
}
function parseUrlencoded(input) {
return parseUrlencoded2(buffer_1.Buffer.from(input));
}
function ucs2decode(string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 0xd800 && value <= 0xdbff && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 0xfc00) == 0xdc00) {
// Low surrogate.
output.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
}
else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
}
else {
output.push(value);
}
}
return output;
}
exports.default = {
percentEncode,
percentDecode,
// application/x-www-form-urlencoded string parser
parseUrlencoded,
// application/x-www-form-urlencoded serializer
serializeUrlencoded,
ucs2decode,
};

37
lib/utils/url/whatwg-url/lib/utils.d.ts vendored Normal file
View File

@ -0,0 +1,37 @@
declare function isObject(value: null): boolean;
declare function hasOwn(obj: any, prop: PropertyKey): boolean;
declare function getSameObject(wrapper: any, prop: string, creator: () => any): any;
declare function wrapperForImpl(impl: any): any;
declare function implForWrapper(wrapper: any): any;
declare function tryWrapperForImpl(impl: any): any;
declare function tryImplForWrapper(wrapper: any): any;
declare function isArrayIndexPropName(P: any): boolean;
declare function isArrayBuffer(value: any): boolean;
declare const _default: {
isObject: typeof isObject;
hasOwn: typeof hasOwn;
wrapperSymbol: symbol;
implSymbol: symbol;
getSameObject: typeof getSameObject;
ctorRegistrySymbol: symbol;
wrapperForImpl: typeof wrapperForImpl;
implForWrapper: typeof implForWrapper;
tryWrapperForImpl: typeof tryWrapperForImpl;
tryImplForWrapper: typeof tryImplForWrapper;
iterInternalSymbol: symbol;
IteratorPrototype: any;
isArrayBuffer: typeof isArrayBuffer;
isArrayIndexPropName: typeof isArrayIndexPropName;
supportsPropertyIndex: symbol;
supportedPropertyIndices: symbol;
supportsPropertyName: symbol;
supportedPropertyNames: symbol;
indexedGet: symbol;
indexedSetNew: symbol;
indexedSetExisting: symbol;
namedGet: symbol;
namedSetNew: symbol;
namedSetExisting: symbol;
namedDelete: symbol;
};
export default _default;

View File

@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Returns "Type(value) is Object" in ES terminology.
function isObject(value) {
return typeof value === "object" && value !== null || typeof value === "function";
}
function hasOwn(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
const wrapperSymbol = Symbol("wrapper");
const implSymbol = Symbol("impl");
const sameObjectCaches = Symbol("SameObject caches");
const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry");
function getSameObject(wrapper, prop, creator) {
if (!wrapper[sameObjectCaches]) {
wrapper[sameObjectCaches] = Object.create(null);
}
if (prop in wrapper[sameObjectCaches]) {
return wrapper[sameObjectCaches][prop];
}
wrapper[sameObjectCaches][prop] = creator();
return wrapper[sameObjectCaches][prop];
}
function wrapperForImpl(impl) {
return impl ? impl[wrapperSymbol] : null;
}
function implForWrapper(wrapper) {
return wrapper ? wrapper[implSymbol] : null;
}
function tryWrapperForImpl(impl) {
const wrapper = wrapperForImpl(impl);
return wrapper ? wrapper : impl;
}
function tryImplForWrapper(wrapper) {
const impl = implForWrapper(wrapper);
return impl ? impl : wrapper;
}
const iterInternalSymbol = Symbol("internal");
const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
function isArrayIndexPropName(P) {
if (typeof P !== 'string') {
return false;
}
const i = P >>> 0;
if (i === Math.pow(2, 32) - 1) {
return false;
}
const s = `${i}`;
if (P !== s) {
return false;
}
return true;
}
const byteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
function isArrayBuffer(value) {
try {
byteLengthGetter.call(value);
return true;
}
catch (e) {
return false;
}
}
const supportsPropertyIndex = Symbol("supports property index");
const supportedPropertyIndices = Symbol("supported property indices");
const supportsPropertyName = Symbol("supports property name");
const supportedPropertyNames = Symbol("supported property names");
const indexedGet = Symbol("indexed property get");
const indexedSetNew = Symbol("indexed property set new");
const indexedSetExisting = Symbol("indexed property set existing");
const namedGet = Symbol("named property get");
const namedSetNew = Symbol("named property set new");
const namedSetExisting = Symbol("named property set existing");
const namedDelete = Symbol("named property delete");
exports.default = {
isObject,
hasOwn,
wrapperSymbol,
implSymbol,
getSameObject,
ctorRegistrySymbol,
wrapperForImpl,
implForWrapper,
tryWrapperForImpl,
tryImplForWrapper,
iterInternalSymbol,
IteratorPrototype,
isArrayBuffer,
isArrayIndexPropName,
supportsPropertyIndex,
supportedPropertyIndices,
supportsPropertyName,
supportedPropertyNames,
indexedGet,
indexedSetNew,
indexedSetExisting,
namedGet,
namedSetNew,
namedSetExisting,
namedDelete
};

View File

@ -31,7 +31,6 @@
"@types/react": "^17.0.2",
"@types/uuid": "^8.3.0",
"@types/wechat-miniprogram": "^3.4.1",
"@types/whatwg-url": "^11.0.3",
"assert": "^2.0.0",
"cross-env": "^7.0.2",
"cross-spawn": "^7.0.3",
@ -46,6 +45,6 @@
"dayjs": "^1.11.9",
"node-schedule": "^2.1.1",
"uuid": "^9.0.0",
"whatwg-url": "^14.0.0"
"webidl-conversions": "^5.0.0"
}
}

View File

@ -1,6 +1,5 @@
import { URL, URLSearchParams } from 'whatwg-url';
import { URL, URLSearchParams } from './whatwg-url';
const url = URL;
const urlSearchParams = URLSearchParams;

View File

@ -0,0 +1,18 @@
/**
* 使URLURLSearchParams
* whatwg-url-without-unicode这个库未更新
*/
const whatwgUrl = require('./lib/URL');
const whatwgUrlSearchParams = require('./lib/URLSearchParams');
const sharedGlobalObject = {} as { URL: URL; URLSearchParams: URLSearchParams };
whatwgUrl.install(sharedGlobalObject);
whatwgUrlSearchParams.install(sharedGlobalObject);
const URL = sharedGlobalObject.URL;
const URLSearchParams = sharedGlobalObject.URLSearchParams;
export { URL, URLSearchParams };

View File

@ -0,0 +1,223 @@
// @ts-nocheck
import usm from './url-state-machine';
import urlencoded from './urlencoded';
import URLSearchParams from './URLSearchParams';
const implementation = class URLImpl {
constructor(globalObject, constructorArgs) {
const url = constructorArgs[0];
const base = constructorArgs[1];
let parsedBase = null;
if (base !== undefined) {
parsedBase = usm.basicURLParse(base);
if (parsedBase === null) {
throw new TypeError(`Invalid base URL: ${base}`);
}
}
const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase });
if (parsedURL === null) {
throw new TypeError(`Invalid URL: ${url}`);
}
const query = parsedURL.query !== null ? parsedURL.query : "";
this._url = parsedURL;
// We cannot invoke the "new URLSearchParams object" algorithm without going through the constructor, which strips
// question mark by default. Therefore the doNotStripQMark hack is used.
this._query = URLSearchParams.createImpl(globalObject, [query], { doNotStripQMark: true });
this._query._url = this;
}
get href() {
return usm.serializeURL(this._url);
}
set href(v) {
const parsedURL = usm.basicURLParse(v);
if (parsedURL === null) {
throw new TypeError(`Invalid URL: ${v}`);
}
this._url = parsedURL;
this._query._list.splice(0);
const { query } = parsedURL;
if (query !== null) {
this._query._list = urlencoded.parseUrlencoded(query);
}
}
get origin() {
return usm.serializeURLOrigin(this._url);
}
get protocol() {
return this._url.scheme + ":";
}
set protocol(v) {
usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" });
}
get username() {
return this._url.username;
}
set username(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setTheUsername(this._url, v);
}
get password() {
return this._url.password;
}
set password(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
usm.setThePassword(this._url, v);
}
get host() {
const url = this._url;
if (url.host === null) {
return "";
}
if (url.port === null) {
return usm.serializeHost(url.host);
}
return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port);
}
set host(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "host" });
}
get hostname() {
if (this._url.host === null) {
return "";
}
return usm.serializeHost(this._url.host);
}
set hostname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" });
}
get port() {
if (this._url.port === null) {
return "";
}
return usm.serializeInteger(this._url.port);
}
set port(v) {
if (usm.cannotHaveAUsernamePasswordPort(this._url)) {
return;
}
if (v === "") {
this._url.port = null;
} else {
usm.basicURLParse(v, { url: this._url, stateOverride: "port" });
}
}
get pathname() {
if (this._url.cannotBeABaseURL) {
return this._url.path[0];
}
if (this._url.path.length === 0) {
return "";
}
return "/" + this._url.path.join("/");
}
set pathname(v) {
if (this._url.cannotBeABaseURL) {
return;
}
this._url.path = [];
usm.basicURLParse(v, { url: this._url, stateOverride: "path start" });
}
get search() {
if (this._url.query === null || this._url.query === "") {
return "";
}
return "?" + this._url.query;
}
set search(v) {
const url = this._url;
if (v === "") {
url.query = null;
this._query._list = [];
return;
}
const input = v[0] === "?" ? v.substring(1) : v;
url.query = "";
usm.basicURLParse(input, { url, stateOverride: "query" });
this._query._list = urlencoded.parseUrlencoded(input);
}
get searchParams() {
return this._query;
}
get hash() {
if (this._url.fragment === null || this._url.fragment === "") {
return "";
}
return "#" + this._url.fragment;
}
set hash(v) {
if (v === "") {
this._url.fragment = null;
return;
}
const input = v[0] === "#" ? v.substring(1) : v;
this._url.fragment = "";
usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" });
}
toJSON() {
return this.href;
}
};
export default {
implementation
}

View File

@ -0,0 +1,366 @@
// @ts-nocheck
import conversions from 'webidl-conversions';
import utils from './utils';
const impl = utils.implSymbol;
const ctorRegistry = utils.ctorRegistrySymbol;
const iface = {
// When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
// method into this array. It allows objects that directly implements *those* interfaces to be recognized as
// implementing this mixin interface.
_mixedIntoPredicates: [],
is(obj) {
if (obj) {
if (utils.hasOwn(obj, impl) && obj[impl] instanceof Impl.implementation) {
return true;
}
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof Impl.implementation) {
return true;
}
const wrapper = utils.wrapperForImpl(obj);
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
},
convert(obj, { context = "The provided value" } = {}) {
if (module.exports.is(obj)) {
return utils.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'URL'.`);
},
create(globalObject, constructorArgs, privateData) {
if (globalObject[ctorRegistry] === undefined) {
throw new Error("Internal error: invalid global object");
}
const ctor = globalObject[ctorRegistry]["URL"];
if (ctor === undefined) {
throw new Error("Internal error: constructor URL is not installed on the passed global object");
}
let obj = Object.create(ctor.prototype);
obj = iface.setup(obj, globalObject, constructorArgs, privateData);
return obj;
},
createImpl(globalObject, constructorArgs, privateData) {
const obj = iface.create(globalObject, constructorArgs, privateData);
return utils.implForWrapper(obj);
},
_internalSetup(obj) {},
setup(obj, globalObject, constructorArgs = [], privateData = {}) {
privateData.wrapper = obj;
iface._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new Impl.implementation(globalObject, constructorArgs, privateData),
configurable: true });
obj[impl][utils.wrapperSymbol] = obj;
if (Impl.init) {
Impl.init(obj[impl], privateData);
}
return obj;
},
install(globalObject) {
class URL {
constructor(url) {
if (arguments.length < 1) {
throw new TypeError(
"Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present.");
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 1" });
args.push(curArg);
}
{
let curArg = arguments[1];
if (curArg !== undefined) {
curArg = conversions["USVString"](curArg, { context: "Failed to construct 'URL': parameter 2" });
}
args.push(curArg);
}
return iface.setup(Object.create(this.constructor.prototype), globalObject, args);
}
toJSON() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl].toJSON();
}
get href() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["href"];
}
set href(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, { context: "Failed to set the 'href' property on 'URL': The provided value" });
this[impl]["href"] = V;
}
toString() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["href"];
}
get origin() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["origin"];
}
get protocol() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["protocol"];
}
set protocol(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'protocol' property on 'URL': The provided value" });
this[impl]["protocol"] = V;
}
get username() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["username"];
}
set username(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'username' property on 'URL': The provided value" });
this[impl]["username"] = V;
}
get password() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["password"];
}
set password(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'password' property on 'URL': The provided value" });
this[impl]["password"] = V;
}
get host() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["host"];
}
set host(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, { context: "Failed to set the 'host' property on 'URL': The provided value" });
this[impl]["host"] = V;
}
get hostname() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["hostname"];
}
set hostname(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'hostname' property on 'URL': The provided value" });
this[impl]["hostname"] = V;
}
get port() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["port"];
}
set port(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, { context: "Failed to set the 'port' property on 'URL': The provided value" });
this[impl]["port"] = V;
}
get pathname() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["pathname"];
}
set pathname(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'pathname' property on 'URL': The provided value" });
this[impl]["pathname"] = V;
}
get search() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["search"];
}
set search(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, {
context: "Failed to set the 'search' property on 'URL': The provided value" });
this[impl]["search"] = V;
}
get searchParams() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return utils.getSameObject(this, "searchParams", () => {
return utils.tryWrapperForImpl(this[impl]["searchParams"]);
});
}
get hash() {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
return this[impl]["hash"];
}
set hash(V) {
if (!this || !module.exports.is(this)) {
throw new TypeError("Illegal invocation");
}
V = conversions["USVString"](V, { context: "Failed to set the 'hash' property on 'URL': The provided value" });
this[impl]["hash"] = V;
}}
Object.defineProperties(URL.prototype, {
toJSON: { enumerable: true },
href: { enumerable: true },
toString: { enumerable: true },
origin: { enumerable: true },
protocol: { enumerable: true },
username: { enumerable: true },
password: { enumerable: true },
host: { enumerable: true },
hostname: { enumerable: true },
port: { enumerable: true },
pathname: { enumerable: true },
search: { enumerable: true },
searchParams: { enumerable: true },
hash: { enumerable: true },
[Symbol.toStringTag]: { value: "URL", configurable: true } });
if (globalObject[ctorRegistry] === undefined) {
globalObject[ctorRegistry] = Object.create(null);
}
globalObject[ctorRegistry]["URL"] = URL;
Object.defineProperty(globalObject, "URL", {
configurable: true,
writable: true,
value: URL });
} };
// iface
module.exports = iface;
// const Impl = require('./URL-impl');
import Impl from './URL-impl';

View File

@ -0,0 +1,138 @@
// @ts-nocheck
import urlencoded from './urlencoded';
function stableSortBy(arr, compare) {
return arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
}
const implementation = class URLSearchParamsImpl {
constructor(globalObject, constructorArgs, { doNotStripQMark = false }) {
let init = constructorArgs[0];
this._list = [];
this._url = null;
if (!doNotStripQMark && typeof init === 'string' && init[0] === '?') {
init = init.slice(1);
}
if (Array.isArray(init)) {
for (const pair of init) {
if (pair.length !== 2) {
throw new TypeError(
"Failed to construct 'URLSearchParams': parameter 1 sequence's element does not " +
'contain exactly two elements.'
);
}
this._list.push([pair[0], pair[1]]);
}
} else if (
typeof init === 'object' &&
Object.getPrototypeOf(init) === null
) {
for (const name of Object.keys(init)) {
const value = init[name];
this._list.push([name, value]);
}
} else {
this._list = urlencoded.parseUrlencoded(init);
}
}
_updateSteps() {
if (this._url !== null) {
let query = urlencoded.serializeUrlencoded(this._list);
if (query === '') {
query = null;
}
this._url._url.query = query;
}
}
append(name, value) {
this._list.push([name, value]);
this._updateSteps();
}
delete(name) {
let i = 0;
while (i < this._list.length) {
if (this._list[i][0] === name) {
this._list.splice(i, 1);
} else {
i++;
}
}
this._updateSteps();
}
get(name) {
for (const tuple of this._list) {
if (tuple[0] === name) {
return tuple[1];
}
}
return null;
}
getAll(name) {
const output = [];
for (const tuple of this._list) {
if (tuple[0] === name) {
output.push(tuple[1]);
}
}
return output;
}
has(name) {
for (const tuple of this._list) {
if (tuple[0] === name) {
return true;
}
}
return false;
}
set(name, value) {
let found = false;
let i = 0;
while (i < this._list.length) {
if (this._list[i][0] === name) {
if (found) {
this._list.splice(i, 1);
} else {
found = true;
this._list[i][1] = value;
i++;
}
} else {
i++;
}
}
if (!found) {
this._list.push([name, value]);
}
this._updateSteps();
}
sort() {
this._list = stableSortBy(this._list, (a, b) => a[0] > b[0]);
this._updateSteps();
}
[Symbol.iterator]() {
return this._list[Symbol.iterator]();
}
toString() {
return urlencoded.serializeUrlencoded(this._list);
}
};
export default {
implementation
}

View File

@ -0,0 +1,530 @@
// @ts-nocheck
import conversions from 'webidl-conversions';
import utils from './utils';
const impl = utils.implSymbol;
const ctorRegistry = utils.ctorRegistrySymbol;
const IteratorPrototype = Object.create(utils.IteratorPrototype, {
next: {
value: function next() {
const internal = this[utils.iterInternalSymbol];
const { target, kind, index } = internal;
const values = Array.from(target[impl]);
const len = values.length;
if (index >= len) {
return { value: undefined, done: true };
}
const pair = values[index];
internal.index = index + 1;
const [key, value] = pair.map(utils.tryWrapperForImpl);
let result;
switch (kind) {
case 'key':
result = key;
break;
case 'value':
result = value;
break;
case 'key+value':
result = [key, value];
break;
}
return { value: result, done: false };
},
writable: true,
enumerable: true,
configurable: true,
},
[Symbol.toStringTag]: {
value: 'URLSearchParams Iterator',
configurable: true,
},
});
const iface = {
// When an interface-module that implements this interface as a mixin is loaded, it will append its own `.is()`
// method into this array. It allows objects that directly implements *those* interfaces to be recognized as
// implementing this mixin interface.
_mixedIntoPredicates: [],
is(obj) {
if (obj) {
if (
utils.hasOwn(obj, impl) &&
obj[impl] instanceof Impl.implementation
) {
return true;
}
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(obj)) {
return true;
}
}
}
return false;
},
isImpl(obj) {
if (obj) {
if (obj instanceof Impl.implementation) {
return true;
}
const wrapper = utils.wrapperForImpl(obj);
for (const isMixedInto of module.exports._mixedIntoPredicates) {
if (isMixedInto(wrapper)) {
return true;
}
}
}
return false;
},
convert(obj, { context = 'The provided value' } = {}) {
if (module.exports.is(obj)) {
return utils.implForWrapper(obj);
}
throw new TypeError(`${context} is not of type 'URLSearchParams'.`);
},
createDefaultIterator(target, kind) {
const iterator = Object.create(IteratorPrototype);
Object.defineProperty(iterator, utils.iterInternalSymbol, {
value: { target, kind, index: 0 },
configurable: true,
});
return iterator;
},
create(globalObject, constructorArgs, privateData) {
if (globalObject[ctorRegistry] === undefined) {
throw new Error('Internal error: invalid global object');
}
const ctor = globalObject[ctorRegistry]['URLSearchParams'];
if (ctor === undefined) {
throw new Error(
'Internal error: constructor URLSearchParams is not installed on the passed global object'
);
}
let obj = Object.create(ctor.prototype);
obj = iface.setup(obj, globalObject, constructorArgs, privateData);
return obj;
},
createImpl(globalObject, constructorArgs, privateData) {
const obj = iface.create(globalObject, constructorArgs, privateData);
return utils.implForWrapper(obj);
},
_internalSetup(obj) {},
setup(obj, globalObject, constructorArgs = [], privateData = {}) {
privateData.wrapper = obj;
iface._internalSetup(obj);
Object.defineProperty(obj, impl, {
value: new Impl.implementation(
globalObject,
constructorArgs,
privateData
),
configurable: true,
});
obj[impl][utils.wrapperSymbol] = obj;
if (Impl.init) {
Impl.init(obj[impl], privateData);
}
return obj;
},
install(globalObject) {
class URLSearchParams {
constructor() {
const args = [];
{
let curArg = arguments[0];
if (curArg !== undefined) {
if (utils.isObject(curArg)) {
if (curArg[Symbol.iterator] !== undefined) {
if (!utils.isObject(curArg)) {
throw new TypeError(
"Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
' is not an iterable object.'
);
} else {
const V = [];
const tmp = curArg;
for (let nextItem of tmp) {
if (!utils.isObject(nextItem)) {
throw new TypeError(
"Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
"'s element" +
' is not an iterable object.'
);
} else {
const V = [];
const tmp = nextItem;
for (let nextItem of tmp) {
nextItem = conversions[
'USVString'
](nextItem, {
context:
"Failed to construct 'URLSearchParams': parameter 1" +
' sequence' +
"'s element" +
"'s element",
});
V.push(nextItem);
}
nextItem = V;
}
V.push(nextItem);
}
curArg = V;
}
} else {
if (!utils.isObject(curArg)) {
throw new TypeError(
"Failed to construct 'URLSearchParams': parameter 1" +
' record' +
' is not an object.'
);
} else {
const result = Object.create(null);
for (const key of Reflect.ownKeys(curArg)) {
const desc =
Object.getOwnPropertyDescriptor(
curArg,
key
);
if (desc && desc.enumerable) {
let typedKey = key;
typedKey = conversions['USVString'](
typedKey,
{
context:
"Failed to construct 'URLSearchParams': parameter 1" +
' record' +
"'s key",
}
);
let typedValue = curArg[key];
typedValue = conversions[
'USVString'
](typedValue, {
context:
"Failed to construct 'URLSearchParams': parameter 1" +
' record' +
"'s value",
});
result[typedKey] = typedValue;
}
}
curArg = result;
}
}
} else {
curArg = conversions['USVString'](curArg, {
context:
"Failed to construct 'URLSearchParams': parameter 1",
});
}
} else {
curArg = '';
}
args.push(curArg);
}
return iface.setup(
Object.create(this.constructor.prototype),
globalObject,
args
);
}
append(name, value) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 2) {
throw new TypeError(
"Failed to execute 'append' on 'URLSearchParams': 2 arguments required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'append' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
{
let curArg = arguments[1];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'append' on 'URLSearchParams': parameter 2",
});
args.push(curArg);
}
return this[impl].append(...args);
}
delete(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'delete' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'delete' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].delete(...args);
}
get(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'get' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'get' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].get(...args);
}
getAll(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'getAll' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'getAll' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return utils.tryWrapperForImpl(this[impl].getAll(...args));
}
has(name) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'has' on 'URLSearchParams': 1 argument required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'has' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
return this[impl].has(...args);
}
set(name, value) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 2) {
throw new TypeError(
"Failed to execute 'set' on 'URLSearchParams': 2 arguments required, but only " +
arguments.length +
' present.'
);
}
const args = [];
{
let curArg = arguments[0];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'set' on 'URLSearchParams': parameter 1",
});
args.push(curArg);
}
{
let curArg = arguments[1];
curArg = conversions['USVString'](curArg, {
context:
"Failed to execute 'set' on 'URLSearchParams': parameter 2",
});
args.push(curArg);
}
return this[impl].set(...args);
}
sort() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return this[impl].sort();
}
toString() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return this[impl].toString();
}
keys() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'key');
}
values() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'value');
}
entries() {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
return module.exports.createDefaultIterator(this, 'key+value');
}
forEach(callback) {
if (!this || !module.exports.is(this)) {
throw new TypeError('Illegal invocation');
}
if (arguments.length < 1) {
throw new TypeError(
"Failed to execute 'forEach' on 'iterable': 1 argument required, " +
'but only 0 present.'
);
}
if (typeof callback !== 'function') {
throw new TypeError(
"Failed to execute 'forEach' on 'iterable': The callback provided " +
'as parameter 1 is not a function.'
);
}
const thisArg = arguments[1];
let pairs = Array.from(this[impl]);
let i = 0;
while (i < pairs.length) {
const [key, value] = pairs[i].map(utils.tryWrapperForImpl);
callback.call(thisArg, value, key, this);
pairs = Array.from(this[impl]);
i++;
}
}
}
Object.defineProperties(URLSearchParams.prototype, {
append: { enumerable: true },
delete: { enumerable: true },
get: { enumerable: true },
getAll: { enumerable: true },
has: { enumerable: true },
set: { enumerable: true },
sort: { enumerable: true },
toString: { enumerable: true },
keys: { enumerable: true },
values: { enumerable: true },
entries: { enumerable: true },
forEach: { enumerable: true },
[Symbol.toStringTag]: {
value: 'URLSearchParams',
configurable: true,
},
[Symbol.iterator]: {
value: URLSearchParams.prototype.entries,
configurable: true,
writable: true,
},
});
if (globalObject[ctorRegistry] === undefined) {
globalObject[ctorRegistry] = Object.create(null);
}
globalObject[ctorRegistry]['URLSearchParams'] = URLSearchParams;
Object.defineProperty(globalObject, 'URLSearchParams', {
configurable: true,
writable: true,
value: URLSearchParams,
});
},
};
// iface
module.exports = iface;
// const Impl = require('./URLSearchParams-impl')
import Impl from './URLSearchParams-impl';

View File

@ -0,0 +1,30 @@
function isASCIIDigit(c: number) {
return c >= 0x30 && c <= 0x39;
}
function isASCIIAlpha(c: number) {
return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A);
}
function isASCIIAlphanumeric(c: number) {
return isASCIIAlpha(c) || isASCIIDigit(c);
}
function isASCIIHex(c: number) {
return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66);
}
export {
isASCIIDigit,
isASCIIAlpha,
isASCIIAlphanumeric,
isASCIIHex,
};
export default {
isASCIIDigit,
isASCIIAlpha,
isASCIIAlphanumeric,
isASCIIHex
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,180 @@
import { Buffer } from 'buffer';
import { isASCIIHex } from './infra';
function strictlySplitByteSequence(buf: Buffer, cp: number) {
const list = [];
let last = 0;
let i = buf.indexOf(cp);
while (i >= 0) {
list.push(buf.slice(last, i));
last = i + 1;
i = buf.indexOf(cp, last);
}
if (last !== buf.length) {
list.push(buf.slice(last));
}
return list;
}
function replaceByteInByteSequence(buf: Buffer, from: number, to: number) {
let i = buf.indexOf(from);
while (i >= 0) {
buf[i] = to;
i = buf.indexOf(from, i + 1);
}
return buf;
}
function percentEncode(c: number) {
let hex = c.toString(16).toUpperCase();
if (hex.length === 1) {
hex = '0' + hex;
}
return '%' + hex;
}
function percentDecode(input: Buffer) {
const output = Buffer.alloc(input.byteLength);
let ptr = 0;
for (let i = 0; i < input.length; ++i) {
if (
input[i] !== 37 ||
!isASCIIHex(input[i + 1]) ||
!isASCIIHex(input[i + 2])
) {
output[ptr++] = input[i];
} else {
output[ptr++] = parseInt(input.slice(i + 1, i + 3).toString(), 16);
i += 2;
}
}
return output.slice(0, ptr);
}
function parseUrlencoded2(input: Buffer) {
const sequences = strictlySplitByteSequence(input, 38);
const output = [];
for (const bytes of sequences) {
if (bytes.length === 0) {
continue;
}
let name;
let value;
const indexOfEqual = bytes.indexOf(61);
if (indexOfEqual >= 0) {
name = bytes.slice(0, indexOfEqual);
value = bytes.slice(indexOfEqual + 1);
} else {
name = bytes;
value = Buffer.alloc(0);
}
name = replaceByteInByteSequence(Buffer.from(name), 43, 32);
value = replaceByteInByteSequence(Buffer.from(value), 43, 32);
output.push([
percentDecode(name).toString(),
percentDecode(value).toString(),
]);
}
return output;
}
function serializeUrlencodedByte(input: Buffer) {
let output = '';
for (const byte of input) {
if (byte === 32) {
output += '+';
} else if (
byte === 42 ||
byte === 45 ||
byte === 46 ||
(byte >= 48 && byte <= 57) ||
(byte >= 65 && byte <= 90) ||
byte === 95 ||
(byte >= 97 && byte <= 122)
) {
output += String.fromCodePoint(byte);
} else {
output += percentEncode(byte);
}
}
return output;
}
function serializeUrlencoded(tuples: any[], encodingOverride = undefined) {
let encoding = 'utf-8';
if (encodingOverride !== undefined) {
encoding = encodingOverride;
}
let output = '';
for (const [i, tuple] of tuples.entries()) {
// TODO: handle encoding override
const name = serializeUrlencodedByte(Buffer.from(tuple[0]));
let value = tuple[1];
if (tuple.length > 2 && tuple[2] !== undefined) {
if (tuple[2] === 'hidden' && name === '_charset_') {
value = encoding;
} else if (tuple[2] === 'file') {
// value is a File object
value = value.name;
}
}
value = serializeUrlencodedByte(Buffer.from(value));
if (i !== 0) {
output += '&';
}
output += `${name}=${value}`;
}
return output;
}
function parseUrlencoded(
input: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>
) {
return parseUrlencoded2(Buffer.from(input));
}
function ucs2decode(string: string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 0xd800 && value <= 0xdbff && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 0xfc00) == 0xdc00) {
// Low surrogate.
output.push(
((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000
);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
export default {
percentEncode,
percentDecode,
// application/x-www-form-urlencoded string parser
parseUrlencoded,
// application/x-www-form-urlencoded serializer
serializeUrlencoded,
ucs2decode,
};

View File

@ -0,0 +1,114 @@
// Returns "Type(value) is Object" in ES terminology.
function isObject(value: null) {
return typeof value === "object" && value !== null || typeof value === "function";
}
function hasOwn(obj: any, prop: PropertyKey) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
const wrapperSymbol = Symbol("wrapper");
const implSymbol = Symbol("impl");
const sameObjectCaches = Symbol("SameObject caches");
const ctorRegistrySymbol = Symbol.for("[webidl2js] constructor registry");
function getSameObject(wrapper: any, prop: string, creator: () => any) {
if (!wrapper[sameObjectCaches]) {
wrapper[sameObjectCaches] = Object.create(null);
}
if (prop in wrapper[sameObjectCaches]) {
return wrapper[sameObjectCaches][prop];
}
wrapper[sameObjectCaches][prop] = creator();
return wrapper[sameObjectCaches][prop];
}
function wrapperForImpl(impl: any) {
return impl ? impl[wrapperSymbol] : null;
}
function implForWrapper(wrapper: any) {
return wrapper ? wrapper[implSymbol] : null;
}
function tryWrapperForImpl(impl: any) {
const wrapper = wrapperForImpl(impl);
return wrapper ? wrapper : impl;
}
function tryImplForWrapper(wrapper: any) {
const impl = implForWrapper(wrapper);
return impl ? impl : wrapper;
}
const iterInternalSymbol = Symbol("internal");
const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
function isArrayIndexPropName(P: any) {
if (typeof P !== 'string') {
return false;
}
const i = (P as any) >>> 0;
if (i === Math.pow(2, 32) - 1) {
return false;
}
const s = `${i}`;
if (P !== s) {
return false;
}
return true;
}
const byteLengthGetter =
Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")!.get!;
function isArrayBuffer(value: any) {
try {
byteLengthGetter.call(value);
return true;
} catch (e) {
return false;
}
}
const supportsPropertyIndex = Symbol("supports property index");
const supportedPropertyIndices = Symbol("supported property indices");
const supportsPropertyName = Symbol("supports property name");
const supportedPropertyNames = Symbol("supported property names");
const indexedGet = Symbol("indexed property get");
const indexedSetNew = Symbol("indexed property set new");
const indexedSetExisting = Symbol("indexed property set existing");
const namedGet = Symbol("named property get");
const namedSetNew = Symbol("named property set new");
const namedSetExisting = Symbol("named property set existing");
const namedDelete = Symbol("named property delete");
export default {
isObject,
hasOwn,
wrapperSymbol,
implSymbol,
getSameObject,
ctorRegistrySymbol,
wrapperForImpl,
implForWrapper,
tryWrapperForImpl,
tryImplForWrapper,
iterInternalSymbol,
IteratorPrototype,
isArrayBuffer,
isArrayIndexPropName,
supportsPropertyIndex,
supportedPropertyIndices,
supportsPropertyName,
supportedPropertyNames,
indexedGet,
indexedSetNew,
indexedSetExisting,
namedGet,
namedSetNew,
namedSetExisting,
namedDelete
};