urlmason 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +239 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +1 -0
- package/dist/locales.json.mjs +18 -0
- package/dist/node_modules/trousse/dist/arrays.mjs +9 -0
- package/dist/node_modules/trousse/dist/is.mjs +20 -0
- package/dist/node_modules/trousse/dist/locales.mjs +8 -0
- package/dist/node_modules/trousse/dist/matching.mjs +52 -0
- package/dist/node_modules/trousse/dist/objects.mjs +32 -0
- package/dist/node_modules/trousse/dist/urls.mjs +218 -0
- package/dist/queries.mjs +92 -0
- package/dist/tables.d.mts +2 -0
- package/dist/tables.mjs +799 -0
- package/dist/templates.mjs +407 -0
- package/dist/types.d.mts +77 -0
- package/package.json +50 -0
package/dist/tables.mjs
ADDED
|
@@ -0,0 +1,799 @@
|
|
|
1
|
+
import { decodePercent, getRegistrableDomain, isHostOf, isHttpUrl, parseUrl, stripWww } from "./node_modules/trousse/dist/urls.mjs";
|
|
2
|
+
import { escapeRegex, isAnyOf, isSameText, startsWithAnyOf } from "./node_modules/trousse/dist/matching.mjs";
|
|
3
|
+
import { isFunction, isPlainObject, isString } from "./node_modules/trousse/dist/is.mjs";
|
|
4
|
+
import { t } from "./node_modules/trousse/dist/locales.mjs";
|
|
5
|
+
import { trimObject } from "./node_modules/trousse/dist/objects.mjs";
|
|
6
|
+
import { errors } from "./locales.json.mjs";
|
|
7
|
+
import { appendValue, decodeQueryValue, encodeText, entityPrefix, isEntityPair, parseQuery, readAmpersandEntities, readUrlQuery, sortPairs, toPair, toUrlQuery, writeQuery } from "./queries.mjs";
|
|
8
|
+
import { basePlaceholder, compileTemplate, decodePath, dotSegmentRegex, encodeLiteral, isMultiSegment, mapTemplate, openTailName, openTailSuffix, parseTemplate, placeholderRegex, sharedPartMaxLength, splitPath, toBareName, toLengthGuard, toRegexSource, toSegments, toStrictPair, toValueText, trailingSlashRegex, writeBase } from "./templates.mjs";
|
|
9
|
+
// src/tables.ts
|
|
10
|
+
const leadingSlashesRegex = /^\/{2,}/;
|
|
11
|
+
const anchorsRegex = /^\^|\$$/g;
|
|
12
|
+
const plainValueRegex = /^[\w.~-]+$/;
|
|
13
|
+
const captureRegex = /\(\?<p\d+>/g;
|
|
14
|
+
const escapeSplitRegex = /(%[0-9a-f]{2})/i;
|
|
15
|
+
const fixedPathTextRegex = /[^/]/;
|
|
16
|
+
const standInOrigin = "https://root.invalid";
|
|
17
|
+
const hostPlaceholder = "{host}";
|
|
18
|
+
const anyDomainSource = "[^./]+(?:\\.[^./]+)+";
|
|
19
|
+
const isNamed = (pair, names) => {
|
|
20
|
+
return isAnyOf(pair.name, names) || isAnyOf(pair.sortName, names);
|
|
21
|
+
};
|
|
22
|
+
const toShapePlaceholder = (_, name) => {
|
|
23
|
+
return name.endsWith("*") ? "{*}" : "{}";
|
|
24
|
+
};
|
|
25
|
+
const toLowerCaseValue = (value) => {
|
|
26
|
+
return value.split(escapeSplitRegex).map((piece, index) => index % 2 === 1 ? piece : piece.toLowerCase()).join("");
|
|
27
|
+
};
|
|
28
|
+
const asciiUpperCaseRegex = /[A-Z]+/g;
|
|
29
|
+
const toAsciiLowerCase = (value) => {
|
|
30
|
+
const lowercase = (text) => {
|
|
31
|
+
return text.replace(asciiUpperCaseRegex, (letters) => letters.toLowerCase());
|
|
32
|
+
};
|
|
33
|
+
if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([name, text]) => [name, lowercase(text)]));
|
|
34
|
+
return Array.isArray(value) ? value.map(lowercase) : lowercase(value);
|
|
35
|
+
};
|
|
36
|
+
const toCheckParams = (params) => {
|
|
37
|
+
return Object.fromEntries(Object.entries(params).map(([name, value]) => [name, toValueText(value)]));
|
|
38
|
+
};
|
|
39
|
+
const isSameValue = (left, right, isSame) => {
|
|
40
|
+
if (left === right) return true;
|
|
41
|
+
if (!Array.isArray(left) || !Array.isArray(right)) return isString(left) && isString(right) && isSame(left, right);
|
|
42
|
+
return left.length === right.length && left.every((segment, index) => isSame(segment, right[index]));
|
|
43
|
+
};
|
|
44
|
+
const portRegex = /:\d+$/;
|
|
45
|
+
const hasFixedPath = (parsed) => {
|
|
46
|
+
return fixedPathTextRegex.test(parsed.path.replace(placeholderRegex, ""));
|
|
47
|
+
};
|
|
48
|
+
const toCheckFunctions = (checks = {}) => {
|
|
49
|
+
const functions = {};
|
|
50
|
+
for (const [name, check] of Object.entries(checks)) {
|
|
51
|
+
if (!check) continue;
|
|
52
|
+
if (isFunction(check)) {
|
|
53
|
+
functions[name] = check;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (check.global || check.sticky) throw new Error(t(errors.statefulCheckRegex, { name }));
|
|
57
|
+
if (!check.source.startsWith("^") || !check.source.endsWith("$")) throw new Error(t(errors.unanchoredCheckRegex, { name }));
|
|
58
|
+
const wholeRegex = new RegExp(`^(?:${check.source})$`, check.flags);
|
|
59
|
+
functions[name] = (value, ..._rest) => wholeRegex.test(value);
|
|
60
|
+
}
|
|
61
|
+
const hostCheck = functions.host;
|
|
62
|
+
if (hostCheck) functions.host = (value, ...rest) => hostCheck(value.replace(portRegex, ""), ...rest);
|
|
63
|
+
return functions;
|
|
64
|
+
};
|
|
65
|
+
const copyRow = (row) => {
|
|
66
|
+
const copy = { ...row };
|
|
67
|
+
if (row.checks) copy.checks = { ...row.checks };
|
|
68
|
+
return copy;
|
|
69
|
+
};
|
|
70
|
+
const toTableUrl = (url) => {
|
|
71
|
+
const path = url.pathname.replace(leadingSlashesRegex, "/");
|
|
72
|
+
const hostPath = url.hostname + decodePath(path);
|
|
73
|
+
return {
|
|
74
|
+
url,
|
|
75
|
+
hostname: url.hostname,
|
|
76
|
+
hostPath: hostPath.replace(trailingSlashRegex, "")
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
const readQuery = (tableUrl) => {
|
|
80
|
+
if (!tableUrl.query) tableUrl.query = readUrlQuery(tableUrl.url);
|
|
81
|
+
return tableUrl.query;
|
|
82
|
+
};
|
|
83
|
+
let lastTableUrl;
|
|
84
|
+
const readTableUrl = (url) => {
|
|
85
|
+
if (lastTableUrl?.url === url) return lastTableUrl.tableUrl;
|
|
86
|
+
const parsedUrl = parseUrl(url);
|
|
87
|
+
const tableUrl = parsedUrl && isHttpUrl(parsedUrl) ? toTableUrl(parsedUrl) : void 0;
|
|
88
|
+
lastTableUrl = {
|
|
89
|
+
url,
|
|
90
|
+
tableUrl
|
|
91
|
+
};
|
|
92
|
+
return tableUrl;
|
|
93
|
+
};
|
|
94
|
+
const joinRegexes = (regexes) => {
|
|
95
|
+
const sources = regexes.map((regex) => `(?:${regex.source.replace(captureRegex, "(?:")})`);
|
|
96
|
+
return new RegExp([...new Set(sources)].join("|") || "(?!)", "i");
|
|
97
|
+
};
|
|
98
|
+
const toEntrySource = (entry) => {
|
|
99
|
+
if (isFunction(entry)) return anyDomainSource;
|
|
100
|
+
return isString(entry) ? escapeRegex(entry) : `(?:${entry.source.replace(anchorsRegex, "")})`;
|
|
101
|
+
};
|
|
102
|
+
const isListedIn = (value, entries = []) => {
|
|
103
|
+
return entries.some((entry) => {
|
|
104
|
+
return isFunction(entry) ? entry(value) : isHostOf(`https://${value}`, entry);
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
const isListedHost = (host, options) => {
|
|
108
|
+
const bareHost = stripWww(host);
|
|
109
|
+
const parentDomains = (options.isWwwTenant ? [host, bareHost] : [bareHost]).map((form) => form.slice(form.indexOf(".") + 1));
|
|
110
|
+
return isListedIn(host, options.hosts?.exact) || isListedIn(bareHost, options.hosts?.exact) || parentDomains.some((domain) => isListedIn(domain, options.hosts?.tenant));
|
|
111
|
+
};
|
|
112
|
+
const getTenantDomain = (host, tenants = []) => {
|
|
113
|
+
for (let index = host.indexOf("."); index !== -1; index = host.indexOf(".", index + 1)) if (isListedIn(host.slice(index + 1), tenants)) return host.slice(index + 1);
|
|
114
|
+
};
|
|
115
|
+
const isApexHost = (host) => {
|
|
116
|
+
return getRegistrableDomain(`https://${host}`) === host;
|
|
117
|
+
};
|
|
118
|
+
const compileRowTemplate = (template, { key, checks: givenRowChecks }, rowIndex, isAlias, options, checks, rowChecks, lenient, hasAmpersandMark) => {
|
|
119
|
+
const built = parseTemplate(template);
|
|
120
|
+
const hasBase = built.path.startsWith(basePlaceholder);
|
|
121
|
+
const parsed = hasBase ? {
|
|
122
|
+
...built,
|
|
123
|
+
text: built.text.replace(basePlaceholder, ""),
|
|
124
|
+
path: built.path.slice(basePlaceholder.length),
|
|
125
|
+
names: built.names.filter((name) => name !== "base*")
|
|
126
|
+
} : built;
|
|
127
|
+
const { scheme, host, path, isOpen, names } = parsed;
|
|
128
|
+
if (`${host}${path}${parsed.search ?? ""}`.includes("{/tail*}")) throw new Error(t(errors.misplacedOpenTail, { key }));
|
|
129
|
+
const ownNames = parsed.params.map((param) => param.name);
|
|
130
|
+
const entityName = ownNames.find((name) => name.startsWith(entityPrefix));
|
|
131
|
+
if (hasAmpersandMark && entityName !== void 0) throw new Error(t(errors.ampersandEntityName, {
|
|
132
|
+
key,
|
|
133
|
+
name: entityName
|
|
134
|
+
}));
|
|
135
|
+
const hosts = options.hosts?.exact ?? [];
|
|
136
|
+
const tenantDomains = (options.hosts?.tenant ?? []).map((domain) => toEntrySource(domain));
|
|
137
|
+
const domainSource = `(?:${tenantDomains.join("|")})`;
|
|
138
|
+
const tenantSource = options.isWwwTenant ? "[^./]+" : "(?!www\\.)[^./]+";
|
|
139
|
+
const hasHosts = hosts.length > 0 || tenantDomains.length > 0;
|
|
140
|
+
const hasHostCheck = [...hosts, ...options.hosts?.tenant ?? []].some(isFunction);
|
|
141
|
+
if (host.includes("{domain}") && tenantDomains.length === 0) throw new Error(t(errors.missingHosts, { key }));
|
|
142
|
+
const multiSegmentName = [...path.matchAll(placeholderRegex)].map(([, name]) => name).find(isMultiSegment);
|
|
143
|
+
if (isOpen && multiSegmentName !== void 0) {
|
|
144
|
+
const name = toBareName(multiSegmentName);
|
|
145
|
+
throw new Error(t(errors.openTailBesideMultiSegment, {
|
|
146
|
+
key,
|
|
147
|
+
name
|
|
148
|
+
}));
|
|
149
|
+
}
|
|
150
|
+
if (isOpen && names.some((name) => toBareName(name) === "tail")) throw new Error(t(errors.openTailName, { key }));
|
|
151
|
+
const sharedName = (names.filter(isMultiSegment).length > 1 ? [parsed.text] : [
|
|
152
|
+
...host.split("."),
|
|
153
|
+
...splitPath(path),
|
|
154
|
+
...parsed.params.map((param) => param.value)
|
|
155
|
+
]).map((piece) => [...piece.matchAll(placeholderRegex)].map(([, name]) => toBareName(name))).filter((pieceNames) => pieceNames.length > 1).flat().find((name) => lenient?.case?.includes(name));
|
|
156
|
+
if (sharedName !== void 0) throw new Error(t(errors.sharedCaseMark, {
|
|
157
|
+
key,
|
|
158
|
+
name: sharedName
|
|
159
|
+
}));
|
|
160
|
+
const pathPatterns = {};
|
|
161
|
+
const writtenPathPatterns = {};
|
|
162
|
+
for (const segment of splitPath(path)) {
|
|
163
|
+
const segmentNames = [...segment.matchAll(placeholderRegex)].map(([, name]) => name);
|
|
164
|
+
for (const name of segmentNames.length > 1 ? segmentNames : []) {
|
|
165
|
+
const check = givenRowChecks?.[name] ?? options.checks?.[name];
|
|
166
|
+
if (check instanceof RegExp && isAnyOf(check.flags, ["", "i"])) pathPatterns[name] = toEntrySource(check);
|
|
167
|
+
if (check instanceof RegExp && !check.flags) writtenPathPatterns[name] = toEntrySource(check);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const compiled = compileTemplate(parsed, pathPatterns, writtenPathPatterns);
|
|
171
|
+
const builtCompiled = hasBase ? compileTemplate(built, pathPatterns, writtenPathPatterns) : compiled;
|
|
172
|
+
const ownParams = compiled.params;
|
|
173
|
+
const { getCaptured } = compiled;
|
|
174
|
+
const hasRowChecks = Object.keys(rowChecks).length > 0;
|
|
175
|
+
const passesChecks = (listParams) => {
|
|
176
|
+
const params = toCheckParams(listParams);
|
|
177
|
+
return Object.entries(params).every(([name, value]) => {
|
|
178
|
+
return (checks[name]?.(value) ?? true) && (rowChecks[name]?.(value, params) ?? true);
|
|
179
|
+
});
|
|
180
|
+
};
|
|
181
|
+
const toHostPathRegex = (isWwwOptional, pathPattern, flags) => {
|
|
182
|
+
const wwwSource = isWwwOptional ? "(?:www\\.)?" : "";
|
|
183
|
+
const tenantWwwSource = options.isWwwTenantPrefix ? wwwSource : "";
|
|
184
|
+
const normalize = (value) => isWwwOptional ? stripWww(value) : value;
|
|
185
|
+
const listedHosts = options.isFallThrough ? hosts.filter(isString) : [];
|
|
186
|
+
const toPageHostSource = (value) => {
|
|
187
|
+
const bare = stripWww(value);
|
|
188
|
+
return isApexHost(bare) ? `${wwwSource}${escapeRegex(bare)}` : escapeRegex(value);
|
|
189
|
+
};
|
|
190
|
+
const hostSources = [...hosts.map((value) => {
|
|
191
|
+
if (options.isFallThrough && isString(value)) return toPageHostSource(value);
|
|
192
|
+
return `${wwwSource}${toEntrySource(isString(value) ? normalize(value) : value)}`;
|
|
193
|
+
}), ...tenantDomains.length > 0 ? [`${tenantWwwSource}${tenantSource}\\.${domainSource}`] : []];
|
|
194
|
+
const isFixedHost = !host.startsWith("{") || host.startsWith("{domain}");
|
|
195
|
+
const bareHost = stripWww(host);
|
|
196
|
+
const listedForms = [bareHost, `www.${bareHost}`].filter((form) => listedHosts.includes(form));
|
|
197
|
+
const isPageFixedHost = Boolean(options.isFallThrough) && isFixedHost && !host.includes("{");
|
|
198
|
+
const fixedPrefixSource = isFixedHost && !isPageFixedHost ? wwwSource : "";
|
|
199
|
+
const tenantPrefixSource = !isFixedHost && !host.startsWith("{host}") ? tenantWwwSource : "";
|
|
200
|
+
const hostCaptures = {
|
|
201
|
+
host: `(?:${hostSources.join("|")})`,
|
|
202
|
+
domain: domainSource
|
|
203
|
+
};
|
|
204
|
+
const hostSource = toRegexSource(normalize(host), compiled.captureIn("host"), {
|
|
205
|
+
source: tenantSource,
|
|
206
|
+
unit: "[^./]"
|
|
207
|
+
}, hostCaptures);
|
|
208
|
+
const prefixSource = `${host.split(".").some((label) => {
|
|
209
|
+
return [...label.matchAll(placeholderRegex)].length > 1;
|
|
210
|
+
}) ? toLengthGuard(sharedPartMaxLength, "/") : ""}${fixedPrefixSource}${tenantPrefixSource}`;
|
|
211
|
+
if (isPageFixedHost) {
|
|
212
|
+
const forms = listedForms.length > 0 ? listedForms : [host];
|
|
213
|
+
const sources = isApexHost(bareHost) ? [toPageHostSource(bareHost)] : forms.map(escapeRegex);
|
|
214
|
+
return new RegExp(`^(?:${sources.join("|")})${pathPattern}$`, flags);
|
|
215
|
+
}
|
|
216
|
+
return new RegExp(`^${prefixSource}${hostSource}${pathPattern}$`, flags);
|
|
217
|
+
};
|
|
218
|
+
const hasSharedSegment = splitPath(path).some((segment) => {
|
|
219
|
+
return [...segment.matchAll(placeholderRegex)].length > 1;
|
|
220
|
+
});
|
|
221
|
+
const toEndingGuard = (text, mapLiteral) => {
|
|
222
|
+
if (!hasSharedSegment || isOpen) return "";
|
|
223
|
+
const ending = mapLiteral(text.split(placeholderRegex).at(-1) ?? "");
|
|
224
|
+
if (!ending) return "";
|
|
225
|
+
return `(?=[^]*${escapeRegex(ending)}$)`;
|
|
226
|
+
};
|
|
227
|
+
const readPathSource = `${toEndingGuard(path.replace(trailingSlashRegex, ""), decodePath)}${compiled.readPathSource}`;
|
|
228
|
+
const rawPathSource = `${toEndingGuard(path, encodeLiteral)}${compiled.rawPathSource}`;
|
|
229
|
+
const asGivenRegex = toHostPathRegex(false, readPathSource, "i");
|
|
230
|
+
const optionalWwwRegex = toHostPathRegex(true, readPathSource, "i");
|
|
231
|
+
const rawAsGivenRegex = toHostPathRegex(false, rawPathSource, "d");
|
|
232
|
+
const rawOptionalWwwRegex = toHostPathRegex(true, rawPathSource, "d");
|
|
233
|
+
const fixedParams = ownParams.filter((param) => !param.value.includes("{"));
|
|
234
|
+
const shapeQuery = ownNames.map((name) => name.toLowerCase()).sort((left, right) => left.localeCompare(right)).join("&");
|
|
235
|
+
const shape = `${`${host}${path}`.replace(placeholderRegex, toShapePlaceholder)}${isOpen ? "#" : ""}?${shapeQuery}`;
|
|
236
|
+
const toHostNames = (value) => {
|
|
237
|
+
const bare = stripWww(value.toLowerCase());
|
|
238
|
+
return [
|
|
239
|
+
value.toLowerCase(),
|
|
240
|
+
bare,
|
|
241
|
+
`www.${bare}`
|
|
242
|
+
];
|
|
243
|
+
};
|
|
244
|
+
const toHostHint = () => {
|
|
245
|
+
const tenantEntries = options.hosts?.tenant ?? [];
|
|
246
|
+
if (!host.includes("{")) return {
|
|
247
|
+
names: toHostNames(host),
|
|
248
|
+
suffixes: []
|
|
249
|
+
};
|
|
250
|
+
if (host === hostPlaceholder || host.includes("{domain}")) {
|
|
251
|
+
const isHostOnly = host === hostPlaceholder;
|
|
252
|
+
if (!tenantEntries.every(isString) || isHostOnly && !hosts.every(isString)) return;
|
|
253
|
+
const domains = tenantEntries.filter(isString).map((domain) => domain.toLowerCase());
|
|
254
|
+
return {
|
|
255
|
+
names: [...isHostOnly ? hosts.filter(isString).flatMap(toHostNames) : [], ...domains.flatMap(toHostNames)],
|
|
256
|
+
suffixes: domains.map((domain) => `.${domain}`)
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const suffix = host.slice(host.lastIndexOf("}") + 1).toLowerCase();
|
|
260
|
+
if (host.includes(hostPlaceholder) || !suffix.startsWith(".")) return;
|
|
261
|
+
return {
|
|
262
|
+
names: [],
|
|
263
|
+
suffixes: [suffix]
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
const claimsUrls = !host.includes(hostPlaceholder) || hasHosts;
|
|
267
|
+
const readParams = (tableUrl, isWwwOptional, base) => {
|
|
268
|
+
const { url, hostPath } = tableUrl;
|
|
269
|
+
const match = claimsUrls && (isWwwOptional ? optionalWwwRegex : asGivenRegex).exec(hostPath);
|
|
270
|
+
if (!match) return;
|
|
271
|
+
const params = compiled.read(match.groups, () => readQuery(tableUrl).searchParams);
|
|
272
|
+
if (!params) return;
|
|
273
|
+
if (hasHostCheck && ("host" in params || "domain" in params)) {
|
|
274
|
+
if (!(isString(params.domain) ? isListedIn(params.domain, options.hosts?.tenant) : isListedHost(url.hostname, options))) return;
|
|
275
|
+
}
|
|
276
|
+
if ("host" in params) params.host = url.host;
|
|
277
|
+
if (scheme === "{scheme}") params.scheme = url.protocol.slice(0, -1);
|
|
278
|
+
if (base) Object.assign(params, base);
|
|
279
|
+
return params;
|
|
280
|
+
};
|
|
281
|
+
const readRawGroups = (rawParams, groups = {}) => {
|
|
282
|
+
return Object.entries(groups).every(([group, value]) => {
|
|
283
|
+
const captured = getCaptured(group);
|
|
284
|
+
if (!captured || value === void 0) return true;
|
|
285
|
+
const { name, part } = captured;
|
|
286
|
+
if (rawParams[name] && rawParams[name].value !== value) return false;
|
|
287
|
+
rawParams[name] = {
|
|
288
|
+
value,
|
|
289
|
+
part
|
|
290
|
+
};
|
|
291
|
+
return true;
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
const decodeValue = (value, part) => {
|
|
295
|
+
if (part === "host") return value;
|
|
296
|
+
return part === "path" ? decodePercent(decodePath(value)) : decodeQueryValue(value).trim();
|
|
297
|
+
};
|
|
298
|
+
const lowercaseValues = (match, listParams) => {
|
|
299
|
+
const params = toCheckParams(listParams);
|
|
300
|
+
const groups = { ...match.groups };
|
|
301
|
+
let text = match.input;
|
|
302
|
+
for (const [group, range] of Object.entries(match.indices?.groups ?? {})) {
|
|
303
|
+
const captured = getCaptured(group);
|
|
304
|
+
if (!range || !captured || !lenient?.case?.includes(captured.name)) continue;
|
|
305
|
+
const value = toLowerCaseValue(text.slice(range[0], range[1]));
|
|
306
|
+
const { name } = captured;
|
|
307
|
+
const decoded = decodeValue(value, captured.part);
|
|
308
|
+
if (checks[name]?.(decoded) === false) continue;
|
|
309
|
+
if (rowChecks[name]?.(decoded, {
|
|
310
|
+
...params,
|
|
311
|
+
[name]: decoded
|
|
312
|
+
}) === false) continue;
|
|
313
|
+
groups[group] = value;
|
|
314
|
+
text = `${text.slice(0, range[0])}${value}${text.slice(range[1])}`;
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
text,
|
|
318
|
+
groups
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
const readRawParams = (tableUrl, isWwwOptional, params) => {
|
|
322
|
+
const { url } = tableUrl;
|
|
323
|
+
const { pairs } = readQuery(tableUrl);
|
|
324
|
+
const match = (isWwwOptional ? rawOptionalWwwRegex : rawAsGivenRegex).exec(url.hostname + url.pathname);
|
|
325
|
+
const rawParams = {};
|
|
326
|
+
if (!match) return;
|
|
327
|
+
const respelledHostPath = lowercaseValues(match, params);
|
|
328
|
+
if (!readRawGroups(rawParams, respelledHostPath.groups)) return;
|
|
329
|
+
const respelledPairs = [...pairs];
|
|
330
|
+
for (const param of ownParams) {
|
|
331
|
+
const [index, ...others] = [...pairs.keys()].filter((pairIndex) => {
|
|
332
|
+
return isNamed(pairs[pairIndex], param.name);
|
|
333
|
+
});
|
|
334
|
+
const { rawName, rawValue } = pairs[index];
|
|
335
|
+
if (others.length > 0 || ![param.writtenName, param.name].includes(rawName)) return;
|
|
336
|
+
if (param.isFlag) {
|
|
337
|
+
if (rawValue) return;
|
|
338
|
+
if (rawValue !== void 0) respelledPairs[index] = toPair(rawName);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const queryMatch = param.rawRegex.exec(rawValue ?? "");
|
|
342
|
+
if (!queryMatch) return;
|
|
343
|
+
const respelledValue = lowercaseValues(queryMatch, params);
|
|
344
|
+
if (!readRawGroups(rawParams, respelledValue.groups)) return;
|
|
345
|
+
if (respelledValue.text !== rawValue) respelledPairs[index] = toPair(`${rawName}=${respelledValue.text}`);
|
|
346
|
+
}
|
|
347
|
+
if ("host" in rawParams) rawParams.host.value = url.host;
|
|
348
|
+
if (scheme === "{scheme}") rawParams.scheme = {
|
|
349
|
+
value: url.protocol.slice(0, -1),
|
|
350
|
+
part: "host"
|
|
351
|
+
};
|
|
352
|
+
return {
|
|
353
|
+
params: rawParams,
|
|
354
|
+
pathname: respelledHostPath.text.slice(url.hostname.length),
|
|
355
|
+
pairs: respelledPairs
|
|
356
|
+
};
|
|
357
|
+
};
|
|
358
|
+
const getRawUrl = (rawParams, keptPairs) => {
|
|
359
|
+
let isFilled = true;
|
|
360
|
+
const fill = (text, part, mapLiteral) => {
|
|
361
|
+
const fillPlaceholder = (placeholder) => {
|
|
362
|
+
const rawParam = rawParams[toBareName(placeholder)];
|
|
363
|
+
if (!rawParam || rawParam.part !== part && !plainValueRegex.test(rawParam.value)) {
|
|
364
|
+
isFilled = false;
|
|
365
|
+
return "";
|
|
366
|
+
}
|
|
367
|
+
return rawParam.value;
|
|
368
|
+
};
|
|
369
|
+
return mapTemplate(text, fillPlaceholder, mapLiteral);
|
|
370
|
+
};
|
|
371
|
+
const origin = `${fill(scheme, "host")}://${fill(host, "host")}`;
|
|
372
|
+
const pairs = ownParams.map((own) => {
|
|
373
|
+
if (!own.isFilled) return own.pair;
|
|
374
|
+
return appendValue(own.pair, fill(own.value, "query", encodeText));
|
|
375
|
+
});
|
|
376
|
+
const filledPath = fill(path, "path", encodeLiteral);
|
|
377
|
+
if (!isFilled || filledPath.split("/").some((segment) => dotSegmentRegex.test(segment))) return;
|
|
378
|
+
const writtenPairs = [...pairs, ...keptPairs];
|
|
379
|
+
return {
|
|
380
|
+
base: writeBase(`${origin}${filledPath}`, writtenPairs),
|
|
381
|
+
pairs: writtenPairs
|
|
382
|
+
};
|
|
383
|
+
};
|
|
384
|
+
const getHttpsOrigin = (rawParams) => {
|
|
385
|
+
if (!isAnyOf(scheme, "https")) return;
|
|
386
|
+
return `https://${mapTemplate(host, (name) => rawParams[toBareName(name)].value)}`;
|
|
387
|
+
};
|
|
388
|
+
const getUrl = (params = {}, encoding = "pretty") => {
|
|
389
|
+
const values = builtCompiled.getValues(params);
|
|
390
|
+
if (!values) return;
|
|
391
|
+
for (const [name, value] of Object.entries(values)) {
|
|
392
|
+
const check = checks[toBareName(name)];
|
|
393
|
+
if (check && !check(toValueText(value))) return;
|
|
394
|
+
const lowercase = lenient?.case?.includes(toBareName(name)) ? toAsciiLowerCase(value) : value;
|
|
395
|
+
values[name] = check && !check(toValueText(lowercase)) ? value : lowercase;
|
|
396
|
+
}
|
|
397
|
+
if (hasRowChecks) {
|
|
398
|
+
const filled = Object.fromEntries(built.names.map((name) => [toBareName(name), toValueText(values[name])]));
|
|
399
|
+
if (Object.entries(filled).some(([name, value]) => {
|
|
400
|
+
return rowChecks[name]?.(value, filled) === false;
|
|
401
|
+
})) return;
|
|
402
|
+
}
|
|
403
|
+
return builtCompiled.fill(values, encoding);
|
|
404
|
+
};
|
|
405
|
+
const getWrittenText = (pair) => {
|
|
406
|
+
const param = ownParams.find((own) => own.name === pair.rawName && own.name === pair.name);
|
|
407
|
+
if (!param) return pair.text;
|
|
408
|
+
return `${param.writtenName}${pair.text.slice(pair.rawName.length)}`;
|
|
409
|
+
};
|
|
410
|
+
return {
|
|
411
|
+
rowIndex,
|
|
412
|
+
isAlias,
|
|
413
|
+
ownNames,
|
|
414
|
+
optionalNames: parsed.optionalNames,
|
|
415
|
+
hostNames: [...host.matchAll(placeholderRegex)].map(([, name]) => name),
|
|
416
|
+
fixedQuery: fixedParams.map((param) => [param.name, param.value]),
|
|
417
|
+
valueNames: ownParams.filter((param) => param.value.includes("{")).map((param) => param.name),
|
|
418
|
+
flagTexts: ownParams.filter((param) => param.isFlag).map((param) => `${param.writtenName}=`),
|
|
419
|
+
getWrittenText,
|
|
420
|
+
asGivenRegex,
|
|
421
|
+
optionalWwwRegex,
|
|
422
|
+
hostHint: toHostHint(),
|
|
423
|
+
readParams,
|
|
424
|
+
readRawParams,
|
|
425
|
+
getRawUrl,
|
|
426
|
+
getHttpsOrigin,
|
|
427
|
+
passesChecks,
|
|
428
|
+
shape,
|
|
429
|
+
openDepth: isOpen ? splitPath(path).length : Number.POSITIVE_INFINITY,
|
|
430
|
+
getUrl
|
|
431
|
+
};
|
|
432
|
+
};
|
|
433
|
+
const createTable = (givenRows, options = {}) => {
|
|
434
|
+
const rows = givenRows.map((row) => copyRow(row));
|
|
435
|
+
const lenient = {
|
|
436
|
+
...options.lenient,
|
|
437
|
+
case: Array.isArray(options.lenient?.case) ? [...options.lenient.case] : void 0
|
|
438
|
+
};
|
|
439
|
+
const hasAmpersandMark = lenient.ampersandEntity === true;
|
|
440
|
+
const checks = toCheckFunctions(options.checks);
|
|
441
|
+
const rowChecks = rows.map((row) => toCheckFunctions(row.checks));
|
|
442
|
+
const compiledRows = rows.map((row, rowIndex) => {
|
|
443
|
+
return [row.main, ...row.aliases ?? []].map((template, index) => {
|
|
444
|
+
return compileRowTemplate(template, row, rowIndex, index > 0, options, checks, rowChecks[rowIndex], lenient, hasAmpersandMark);
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
const compiled = compiledRows.flat();
|
|
448
|
+
const claimed = compiled.filter((candidate) => !rows[candidate.rowIndex].isBuildOnly);
|
|
449
|
+
const bySpecificity = [...claimed].sort((a, b) => {
|
|
450
|
+
if (a.openDepth !== b.openDepth) return b.openDepth - a.openDepth;
|
|
451
|
+
return b.ownNames.length - a.ownNames.length;
|
|
452
|
+
});
|
|
453
|
+
const inReadOrder = options.isFallThrough ? claimed : bySpecificity;
|
|
454
|
+
const hostHints = claimed.map((candidate) => candidate.hostHint);
|
|
455
|
+
const hostNames = new Set(hostHints.flatMap((hint) => hint?.names ?? []));
|
|
456
|
+
const hostSuffixes = [...new Set(hostHints.flatMap((hint) => hint?.suffixes ?? []))];
|
|
457
|
+
const isAnyHostTaken = hostHints.some((hint) => !hint);
|
|
458
|
+
const canTakeHost = (hostname) => {
|
|
459
|
+
if (isAnyHostTaken || hostNames.has(hostname)) return true;
|
|
460
|
+
for (const suffix of hostSuffixes) if (hostname.endsWith(suffix)) return true;
|
|
461
|
+
return false;
|
|
462
|
+
};
|
|
463
|
+
const asGivenRegex = joinRegexes(claimed.map((candidate) => candidate.asGivenRegex));
|
|
464
|
+
const optionalWwwRegex = joinRegexes(claimed.map((candidate) => candidate.optionalWwwRegex));
|
|
465
|
+
const getRowTemplates = (key, select) => {
|
|
466
|
+
if (!rows.some((row) => row.key === key)) throw new Error(t(errors.unknownKey, { key }));
|
|
467
|
+
return compiledRows.filter((_templates, rowIndex) => {
|
|
468
|
+
return rows[rowIndex].key === key && (select?.(copyRow(rows[rowIndex])) ?? true);
|
|
469
|
+
});
|
|
470
|
+
};
|
|
471
|
+
const buildUrl = (key, params, buildOptions) => {
|
|
472
|
+
for (const candidate of getRowTemplates(key, buildOptions?.select).flat()) {
|
|
473
|
+
const url = candidate.getUrl(params, buildOptions?.encoding);
|
|
474
|
+
if (url) return url;
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
const buildUrls = (key, params, buildOptions) => {
|
|
478
|
+
for (const templates of getRowTemplates(key, buildOptions?.select)) {
|
|
479
|
+
const urls = [];
|
|
480
|
+
for (const candidate of templates) {
|
|
481
|
+
const url = candidate.getUrl(params, buildOptions?.encoding);
|
|
482
|
+
if (url) urls.push(url);
|
|
483
|
+
}
|
|
484
|
+
if (urls.length > 0) return urls;
|
|
485
|
+
}
|
|
486
|
+
return [];
|
|
487
|
+
};
|
|
488
|
+
const getSelectorNames = (key) => {
|
|
489
|
+
const keyTemplates = compiledRows.filter((_templates, rowIndex) => rows[rowIndex].key === key).flat();
|
|
490
|
+
const fixedNames = keyTemplates.flatMap((template) => template.fixedQuery.map(([name]) => name));
|
|
491
|
+
const getFixedValues = (template, name) => {
|
|
492
|
+
const values = template.fixedQuery.filter(([fixedName]) => fixedName === name).map(([, value]) => value);
|
|
493
|
+
return JSON.stringify([...values].sort((left, right) => left.localeCompare(right)));
|
|
494
|
+
};
|
|
495
|
+
return [...new Set(fixedNames)].filter((name) => {
|
|
496
|
+
return new Set(keyTemplates.map((template) => getFixedValues(template, name))).size > 1;
|
|
497
|
+
});
|
|
498
|
+
};
|
|
499
|
+
const keys = [...new Set(rows.map((row) => row.key))];
|
|
500
|
+
const keySelectorNames = Object.fromEntries(keys.map((key) => [key, getSelectorNames(key)]));
|
|
501
|
+
const fixedQueryTemplates = compiled.filter((candidate) => candidate.fixedQuery.length > 0);
|
|
502
|
+
const getPathSelectorNames = (template, hostPath, isWwwOptional) => {
|
|
503
|
+
return fixedQueryTemplates.filter((candidate) => {
|
|
504
|
+
return (isWwwOptional ? candidate.optionalWwwRegex : candidate.asGivenRegex).test(hostPath);
|
|
505
|
+
}).flatMap((candidate) => candidate.fixedQuery).filter(([name, value]) => {
|
|
506
|
+
return !template.fixedQuery.some(([ownName, ownValue]) => {
|
|
507
|
+
return isAnyOf(name, ownName) && isAnyOf(value, ownValue);
|
|
508
|
+
});
|
|
509
|
+
}).map(([name]) => name);
|
|
510
|
+
};
|
|
511
|
+
const hasUnlistedSelector = (template, tableUrl, isWwwOptional) => {
|
|
512
|
+
if (!tableUrl.url.search) return false;
|
|
513
|
+
const row = rows[template.rowIndex];
|
|
514
|
+
const names = [...keySelectorNames[row.key], ...getPathSelectorNames(template, tableUrl.hostPath, isWwwOptional)];
|
|
515
|
+
if (names.length === 0) return false;
|
|
516
|
+
const rowFixedQuery = compiledRows[template.rowIndex].flatMap((candidate) => candidate.fixedQuery);
|
|
517
|
+
const openNames = [...template.valueNames, ...template.optionalNames];
|
|
518
|
+
return [...readQuery(tableUrl).searchParams].some(([name, value]) => {
|
|
519
|
+
if (!isAnyOf(name, names) || isAnyOf(name, openNames)) return false;
|
|
520
|
+
return !rowFixedQuery.some(([fixedName, fixedValue]) => {
|
|
521
|
+
return isAnyOf(name, fixedName) && isAnyOf(value, fixedValue);
|
|
522
|
+
});
|
|
523
|
+
});
|
|
524
|
+
};
|
|
525
|
+
const findTemplate = (tableUrl, isWwwOptional, base) => {
|
|
526
|
+
let refused;
|
|
527
|
+
for (const template of inReadOrder) {
|
|
528
|
+
if (refused && !options.isFallThrough && refused.template.shape !== template.shape) continue;
|
|
529
|
+
const params = template.readParams(tableUrl, isWwwOptional, base);
|
|
530
|
+
if (!params) continue;
|
|
531
|
+
const isCheckRefused = !template.passesChecks(params);
|
|
532
|
+
const isSelectorRefused = !isCheckRefused && hasUnlistedSelector(template, tableUrl, isWwwOptional);
|
|
533
|
+
if (!isCheckRefused && !isSelectorRefused) return {
|
|
534
|
+
template,
|
|
535
|
+
params,
|
|
536
|
+
tableUrl,
|
|
537
|
+
isWwwOptional
|
|
538
|
+
};
|
|
539
|
+
if (isSelectorRefused && !options.isFallThrough) return {
|
|
540
|
+
template,
|
|
541
|
+
tableUrl,
|
|
542
|
+
isWwwOptional
|
|
543
|
+
};
|
|
544
|
+
if (!refused) refused = {
|
|
545
|
+
template,
|
|
546
|
+
tableUrl,
|
|
547
|
+
isWwwOptional
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
return refused;
|
|
551
|
+
};
|
|
552
|
+
const readRawParams = ({ template, params, tableUrl, isWwwOptional }) => {
|
|
553
|
+
if (hasAmpersandMark && readQuery(tableUrl).pairs.some((pair) => pair.text.startsWith("amp;"))) return;
|
|
554
|
+
return template.readRawParams(tableUrl, isWwwOptional, params);
|
|
555
|
+
};
|
|
556
|
+
const readTableTemplate = (tableUrl, base) => {
|
|
557
|
+
if (!canTakeHost(tableUrl.hostname)) return;
|
|
558
|
+
const asGiven = options.isWwwTenant && asGivenRegex.test(tableUrl.hostPath) ? findTemplate(tableUrl, false, base) : void 0;
|
|
559
|
+
if (asGiven) return asGiven;
|
|
560
|
+
if (optionalWwwRegex.test(tableUrl.hostPath)) return findTemplate(tableUrl, true, base);
|
|
561
|
+
};
|
|
562
|
+
const readTemplate = (url, base) => {
|
|
563
|
+
const tableUrl = readTableUrl(url);
|
|
564
|
+
if (!tableUrl) return;
|
|
565
|
+
const takesHostPath = () => {
|
|
566
|
+
return [asGivenRegex, optionalWwwRegex].some((regex) => regex.test(tableUrl.hostPath));
|
|
567
|
+
};
|
|
568
|
+
let readableUrl = tableUrl;
|
|
569
|
+
if (hasAmpersandMark && takesHostPath() && readQuery(tableUrl).pairs.some(isEntityPair)) {
|
|
570
|
+
const { pairs, hash } = readQuery(tableUrl);
|
|
571
|
+
readableUrl = {
|
|
572
|
+
...tableUrl,
|
|
573
|
+
query: toUrlQuery(readAmpersandEntities(pairs), hash)
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
const found = readTableTemplate(readableUrl, base);
|
|
577
|
+
if (!found?.params) return;
|
|
578
|
+
return {
|
|
579
|
+
...found,
|
|
580
|
+
params: found.params
|
|
581
|
+
};
|
|
582
|
+
};
|
|
583
|
+
const toMatch = (match) => {
|
|
584
|
+
return match;
|
|
585
|
+
};
|
|
586
|
+
const defineRootUrls = (isBaseNeeded, takesTemplate) => {
|
|
587
|
+
const rootRows = [];
|
|
588
|
+
for (const [rootRowIndex, row] of rows.entries()) {
|
|
589
|
+
const standIns = [];
|
|
590
|
+
let isMainRead = false;
|
|
591
|
+
for (const [index, template] of [row.main, ...row.aliases ?? []].entries()) {
|
|
592
|
+
const parsed = parseTemplate(template);
|
|
593
|
+
const hasBase = parsed.path.startsWith(basePlaceholder);
|
|
594
|
+
const path = hasBase ? parsed.path.slice(basePlaceholder.length) : parsed.path;
|
|
595
|
+
const tail = parsed.isOpen ? openTailSuffix : "";
|
|
596
|
+
const standIn = parseTemplate(`${standInOrigin}${path}${tail}${parsed.search ?? ""}`);
|
|
597
|
+
if (!(isAnyOf(parsed.host, hostPlaceholder) && (hasBase || !isBaseNeeded) && takesTemplate(standIn))) continue;
|
|
598
|
+
standIns.push(standIn.text);
|
|
599
|
+
if (index === 0) isMainRead = true;
|
|
600
|
+
}
|
|
601
|
+
const [main, ...aliases] = standIns;
|
|
602
|
+
if (main !== void 0) rootRows.push({
|
|
603
|
+
...row,
|
|
604
|
+
key: row.key,
|
|
605
|
+
main,
|
|
606
|
+
aliases,
|
|
607
|
+
rootRowIndex,
|
|
608
|
+
isMainRead
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
return createTable(rootRows, {
|
|
612
|
+
...options,
|
|
613
|
+
hosts: void 0
|
|
614
|
+
});
|
|
615
|
+
};
|
|
616
|
+
let rootTables;
|
|
617
|
+
const getRootTables = () => {
|
|
618
|
+
if (!rootTables) rootTables = {
|
|
619
|
+
all: defineRootUrls(false, () => true),
|
|
620
|
+
fixed: defineRootUrls(false, hasFixedPath),
|
|
621
|
+
based: defineRootUrls(true, () => true),
|
|
622
|
+
basedFixed: defineRootUrls(true, hasFixedPath)
|
|
623
|
+
};
|
|
624
|
+
return rootTables;
|
|
625
|
+
};
|
|
626
|
+
const readRooted = (url, readOptions) => {
|
|
627
|
+
const parsedUrl = parseUrl(url);
|
|
628
|
+
if (!parsedUrl || !isHttpUrl(parsedUrl)) return;
|
|
629
|
+
const tables = getRootTables();
|
|
630
|
+
const segments = parsedUrl.pathname.replace(leadingSlashesRegex, "/").split("/");
|
|
631
|
+
const readBehind = (isFixed, baseLength) => {
|
|
632
|
+
const rest = segments.slice(baseLength).map((segment) => `/${segment}`);
|
|
633
|
+
const base = segments.slice(1, baseLength).map(decodePercent);
|
|
634
|
+
const table = baseLength > 1 ? tables[isFixed ? "basedFixed" : "based"] : tables[isFixed ? "fixed" : "all"];
|
|
635
|
+
const readBase = {
|
|
636
|
+
scheme: parsedUrl.protocol.slice(0, -1),
|
|
637
|
+
host: parsedUrl.host,
|
|
638
|
+
...base.length > 0 && { base }
|
|
639
|
+
};
|
|
640
|
+
const match = table.readStandIn(`${standInOrigin}${rest.join("")}${parsedUrl.search}${parsedUrl.hash}`, readBase);
|
|
641
|
+
if (!match) return;
|
|
642
|
+
return {
|
|
643
|
+
match,
|
|
644
|
+
values: {
|
|
645
|
+
...match.values,
|
|
646
|
+
...readBase
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
};
|
|
650
|
+
const readUnder = (baseLength) => {
|
|
651
|
+
const read = readBehind(false, baseLength);
|
|
652
|
+
if (!read) return;
|
|
653
|
+
const row = rows[read.match.row.rootRowIndex];
|
|
654
|
+
return toMatch({
|
|
655
|
+
key: row.key,
|
|
656
|
+
values: read.values,
|
|
657
|
+
row: copyRow(row),
|
|
658
|
+
isAlias: read.match.isAlias || !read.match.row.isMainRead,
|
|
659
|
+
isExact: false
|
|
660
|
+
});
|
|
661
|
+
};
|
|
662
|
+
if (readOptions.base !== void 0) {
|
|
663
|
+
const basePath = toSegments(readOptions.base);
|
|
664
|
+
const baseLength = basePath.length + 1;
|
|
665
|
+
const urlBase = segments.slice(1, baseLength);
|
|
666
|
+
if (!(urlBase.length === basePath.length && urlBase.every((segment, index) => {
|
|
667
|
+
return isSameText(decodePath(segment), decodePath(basePath[index]));
|
|
668
|
+
}))) return;
|
|
669
|
+
return readUnder(baseLength);
|
|
670
|
+
}
|
|
671
|
+
const baseLengths = [];
|
|
672
|
+
const maxBaseLength = Math.min(segments.length, 9);
|
|
673
|
+
for (let baseLength = 1; baseLength <= maxBaseLength; baseLength++) if (!segments.slice(0, baseLength).join("/").endsWith("/")) baseLengths.push(baseLength);
|
|
674
|
+
for (const baseLength of baseLengths) {
|
|
675
|
+
const match = readBehind(true, baseLength) ? readUnder(baseLength) : void 0;
|
|
676
|
+
if (match) return match;
|
|
677
|
+
}
|
|
678
|
+
for (const baseLength of baseLengths) {
|
|
679
|
+
const match = readUnder(baseLength);
|
|
680
|
+
if (match) return match;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
const readOwn = (url, base) => {
|
|
684
|
+
const found = readTemplate(url, base);
|
|
685
|
+
if (!found) return;
|
|
686
|
+
const row = rows[found.template.rowIndex];
|
|
687
|
+
const params = { ...found.params };
|
|
688
|
+
delete params[openTailName];
|
|
689
|
+
return toMatch({
|
|
690
|
+
key: row.key,
|
|
691
|
+
values: params,
|
|
692
|
+
row: copyRow(row),
|
|
693
|
+
isAlias: found.template.isAlias,
|
|
694
|
+
isExact: readRawParams(found) !== void 0
|
|
695
|
+
});
|
|
696
|
+
};
|
|
697
|
+
const readUrl = (url, readOptions) => {
|
|
698
|
+
if (readOptions?.base !== void 0 || readOptions?.isAnyHost) return readRooted(url, readOptions);
|
|
699
|
+
return readOwn(url);
|
|
700
|
+
};
|
|
701
|
+
const writeMainUrl = (template, tableUrl, rawRead) => {
|
|
702
|
+
const { url } = tableUrl;
|
|
703
|
+
const [main] = compiledRows[template.rowIndex];
|
|
704
|
+
const pairs = rawRead.pairs.filter((pair) => pair.text);
|
|
705
|
+
const isKept = (pair) => {
|
|
706
|
+
if (main.optionalNames.length > 0 || options.isQueryKept === false) return isNamed(pair, main.optionalNames);
|
|
707
|
+
return true;
|
|
708
|
+
};
|
|
709
|
+
if (!template.isAlias) {
|
|
710
|
+
const origin = url.port ? void 0 : main.getHttpsOrigin(rawRead.params);
|
|
711
|
+
const stayingPairs = sortPairs(pairs.filter((pair) => isNamed(pair, main.ownNames) || isKept(pair)));
|
|
712
|
+
const rest = writeQuery(stayingPairs) === writeQuery(pairs) ? `${writeQuery(rawRead.pairs)}${readQuery(tableUrl).hash}` : `${writeQuery(stayingPairs)}${url.hash}`;
|
|
713
|
+
return `${origin ?? url.origin}${rawRead.pathname}${rest}`;
|
|
714
|
+
}
|
|
715
|
+
const ownNames = [...template.ownNames, ...main.ownNames];
|
|
716
|
+
const keptPairs = pairs.filter((pair) => !isNamed(pair, ownNames) && isKept(pair));
|
|
717
|
+
const rawUrl = main.getRawUrl(rawRead.params, keptPairs);
|
|
718
|
+
if (!rawUrl) return;
|
|
719
|
+
const mainPairs = sortPairs(rawUrl.pairs);
|
|
720
|
+
const mainUrl = `${rawUrl.base}${writeQuery(mainPairs)}`;
|
|
721
|
+
if (url.port && parseUrl(mainUrl)?.port !== url.port) return;
|
|
722
|
+
if (url.protocol === "https:" && startsWithAnyOf(mainUrl, "http:")) return;
|
|
723
|
+
const mainTexts = /* @__PURE__ */ new Set([...mainPairs.map((pair) => pair.text), ...main.flagTexts]);
|
|
724
|
+
if (pairs.some((pair) => {
|
|
725
|
+
return isNamed(pair, main.ownNames) && !isNamed(pair, template.ownNames) && !mainTexts.has(main.getWrittenText(pair));
|
|
726
|
+
})) return;
|
|
727
|
+
return `${mainUrl}${url.hash}`;
|
|
728
|
+
};
|
|
729
|
+
const writeStrictMainUrl = (readBack, mainUrl) => {
|
|
730
|
+
const [main] = compiledRows[readBack.template.rowIndex];
|
|
731
|
+
const values = { ...readBack.params };
|
|
732
|
+
delete values[openTailName];
|
|
733
|
+
const builtUrl = main.getUrl(values, "strict");
|
|
734
|
+
const parsedMainUrl = parseUrl(mainUrl);
|
|
735
|
+
if (!builtUrl || !parsedMainUrl) return;
|
|
736
|
+
const queryStart = builtUrl.includes("?") ? builtUrl.indexOf("?") : builtUrl.length;
|
|
737
|
+
const keptPairs = parseQuery(parsedMainUrl.search).filter((pair) => pair.text && !isNamed(pair, main.ownNames)).map(toStrictPair);
|
|
738
|
+
const pairs = sortPairs([...parseQuery(builtUrl.slice(queryStart)), ...keptPairs]);
|
|
739
|
+
return `${writeBase(builtUrl.slice(0, queryStart), pairs)}${writeQuery(pairs)}${parsedMainUrl.hash}`;
|
|
740
|
+
};
|
|
741
|
+
const getMainUrl = (url, writeOptions) => {
|
|
742
|
+
const found = readTemplate(url);
|
|
743
|
+
if (!found) return;
|
|
744
|
+
const sourceUrl = found.tableUrl.url;
|
|
745
|
+
if (sourceUrl.username || sourceUrl.password) return;
|
|
746
|
+
if (options.isWwwTenant && found.isWwwOptional) return;
|
|
747
|
+
const rawRead = readRawParams(found);
|
|
748
|
+
if (!rawRead) return;
|
|
749
|
+
const mainUrl = writeMainUrl(found.template, found.tableUrl, rawRead);
|
|
750
|
+
if (!mainUrl) return;
|
|
751
|
+
const isStrict = writeOptions?.encoding === "strict";
|
|
752
|
+
if (!isStrict && mainUrl === sourceUrl.href) return;
|
|
753
|
+
const readBack = readTemplate(mainUrl);
|
|
754
|
+
if (readBack?.template.rowIndex !== found.template.rowIndex) return;
|
|
755
|
+
const caseNames = [...lenient.case ?? [], ...readBack.template.hostNames];
|
|
756
|
+
if (!Object.entries(readBack.params).every(([name, value]) => {
|
|
757
|
+
const sourceValue = found.params[name];
|
|
758
|
+
if (caseNames.includes(name)) return isSameValue(value, sourceValue, isSameText);
|
|
759
|
+
return isSameValue(value, sourceValue, (left, right) => left === right);
|
|
760
|
+
})) return;
|
|
761
|
+
const writtenUrl = isStrict ? writeStrictMainUrl(readBack, mainUrl) : mainUrl;
|
|
762
|
+
if (!writtenUrl || writtenUrl === sourceUrl.href) return;
|
|
763
|
+
return writtenUrl;
|
|
764
|
+
};
|
|
765
|
+
const forSite = (url) => {
|
|
766
|
+
const parsedUrl = parseUrl(url);
|
|
767
|
+
if (!parsedUrl || !isHttpUrl(parsedUrl)) return;
|
|
768
|
+
const urlParams = {
|
|
769
|
+
scheme: parsedUrl.protocol.slice(0, -1),
|
|
770
|
+
host: parsedUrl.host,
|
|
771
|
+
domain: getTenantDomain(parsedUrl.hostname, options.hosts?.tenant)
|
|
772
|
+
};
|
|
773
|
+
const withUrlParams = (params = {}) => {
|
|
774
|
+
return {
|
|
775
|
+
...urlParams,
|
|
776
|
+
...trimObject(params)
|
|
777
|
+
};
|
|
778
|
+
};
|
|
779
|
+
return {
|
|
780
|
+
buildUrl: (key, values, buildOptions) => buildUrl(key, withUrlParams(values), buildOptions),
|
|
781
|
+
buildUrls: (key, values, buildOptions) => buildUrls(key, withUrlParams(values), buildOptions)
|
|
782
|
+
};
|
|
783
|
+
};
|
|
784
|
+
return {
|
|
785
|
+
table: {
|
|
786
|
+
rows: rows.map(copyRow),
|
|
787
|
+
buildUrl,
|
|
788
|
+
buildUrls,
|
|
789
|
+
readUrl,
|
|
790
|
+
getMainUrl,
|
|
791
|
+
forSite
|
|
792
|
+
},
|
|
793
|
+
readStandIn: readOwn
|
|
794
|
+
};
|
|
795
|
+
};
|
|
796
|
+
const defineTable = (givenRows, options = {}) => {
|
|
797
|
+
return createTable(givenRows, options).table;
|
|
798
|
+
};
|
|
799
|
+
export { defineTable };
|