urlmason 1.0.0 → 1.1.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.
@@ -1,45 +1,71 @@
1
- import { decodePercent, encodePathSegment, getQueryParamValues, isHttpUrl, parseUrl } from "./node_modules/trousse/dist/urls.mjs";
2
- import { escapeRegex } from "./node_modules/trousse/dist/matching.mjs";
3
- import { isPlainObject, isString } from "./node_modules/trousse/dist/is.mjs";
4
- import { omitEmpty } from "./node_modules/trousse/dist/arrays.mjs";
5
- import { t } from "./node_modules/trousse/dist/locales.mjs";
6
- import { errors } from "./locales.json.mjs";
7
- import { appendValue, encodeText, nonAsciiRegex, parseQuery, sortPairs, toPair, toSearchParams, writeQuery } from "./queries.mjs";
1
+ import { coerceArray } from "./node_modules/trousse/dist/coercions.mjs";
2
+ import { decodePath, decodePercent, encodePathSegment, getQueryParamValues, isHttpUrl, parseUrl, toPercentEscape } from "./node_modules/trousse/dist/urls.mjs";
3
+ import { escapeRegex, isAnyOf } from "./node_modules/trousse/dist/matching.mjs";
4
+ import { isBoolean, isNullish, isNumber, isObject, isPlainObject, isPresent, isString } from "./node_modules/trousse/dist/is.mjs";
5
+ import { setKey, trimObject } from "./node_modules/trousse/dist/objects.mjs";
6
+ import { trimArray } from "./node_modules/trousse/dist/arrays.mjs";
7
+ import { validateAdjacentValues, validateBasePlacement, validateBraces, validateDotSegments, validateExpressions, validateFragment, validateHostLabels, validateHostText, validateKeywords, validateListPairs, validateOldSpellings, validateOptionalPlacement, validateParamNames, validatePrototypeNames, validateQueryPlaceholders, validateQueryValueNames, validateReservedNames, validateReservedPlacement, validateTemplateMatch } from "./rules.mjs";
8
+ import { encodeDecoded, encodeStrictValue, singleEscapeRegex } from "./utils/escapes.mjs";
9
+ import { nonAsciiLabelRegex } from "./utils/hosts.mjs";
10
+ import { dotSegmentRegex, toSegments, toWrittenOffset, trailingSlashRegex } from "./utils/paths.mjs";
11
+ import { appendValue, encodeText, entityPrefix, isNamed, nonAsciiRegex, parseQuery, toFlagNames, toPair, toSearchParams, writeBase, writeQuery } from "./utils/queries.mjs";
12
+ import { toLengthGuard, toLiteralSource } from "./utils/regexes.mjs";
13
+ import { toAsciiLowerCaseText } from "./utils/texts.mjs";
8
14
  // src/templates.ts
9
15
  const placeholderRegex = /\{\/?(\w+\*?)\}/g;
10
- const trailingSlashRegex = /\/$/;
11
- const templateRegex = /^(https?|\{scheme\}):\/\/((?:[^/?#{]|\{[^/{}]*\})+)((?:\/|\{\/)[^?#]*)?(\?(?!\?)[^#]*)?$/i;
12
- const expressionRegex = /\{([^{}]*)\}/g;
13
- const braceRegex = /[{}]/;
14
- const oldListRegex = /(?<!\/)\/\{(\w*)\*\}/;
15
- const oldTail = "{*}";
16
- const oldQuery = "?{query}";
17
- const plainExpressionRegex = /^(?:\w+|\/\w+\*)$/;
18
- const queryExpressionRegex = /^\?\w+\*$/;
19
- const optionalQueryExpressionRegex = /^[?&][\w-]+(?:,[\w-]+)*$/;
20
- const optionalQueryRegex = /\{([?&])([\w-]+(?:,[\w-]+)*)\}$/;
16
+ const templateRegex = /^(?<scheme>https?|\{\w+\}):\/\/(?<host>(?:[^/?#{]|\{[^/{}]*\})+)(?<path>(?:\/|\{\/)[^?#]*)?(?<search>\?(?!\?)[^#]*)?$/i;
17
+ const optionalQueryRegex = /\{(?<operator>[?&])(?<names>[\w-]+(?:,[\w-]+)*\*?)\}$/;
18
+ const reservedRegex = /\{\+(\w+)\}/g;
19
+ const listSplitRegex = /\{\/(?<list>\w+)\*\}\/\{\+(?<reserved>\w+)\}/;
20
+ const fragmentSuffixRegex = /\{#(\w+)\}$/;
21
+ const unreservedOtherRegex = /[^\w\-.~:/?#[\]@!$&'()*+,;=\P{ASCII}\p{Cc}]/gu;
22
+ const pathRespelledRegex = /[ "<>\\^`{}]/g;
23
+ const queryRespelledRegex = /[ "<>']/g;
24
+ const fragmentRespelledRegex = /[ "<>`]/g;
25
+ const reservedEndRegex = /[?#]/;
26
+ const hashRegex = /#/;
27
+ const placeholderTextRegex = /(\{\/?\w+\*?\})/;
21
28
  const strayPercentRegex = /%(?![0-9a-f]{2})/gi;
22
- const subDelimiterRegex = /[!'()*]/g;
23
- const pathlessBaseRegex = /^[^/]+:\/\/[^/]+$/;
24
- const ownGroupRegex = /^p\d+$/;
25
- const dotSegmentRegex = /^(?:\.|%2e){1,2}$/i;
29
+ const wholePlaceholderRegex = /^\{(\w+)\}$/;
26
30
  const hostDelimiterRegex = /[/?#@\\]/;
27
- const schemePlaceholder = "{scheme}";
31
+ const loneSurrogateRegex = /\p{Cs}/u;
28
32
  const basePlaceholder = "{/base*}";
33
+ const contextLabel = "example";
29
34
  const openTailName = "tail";
30
35
  const openTailSuffix = "{/tail*}";
31
36
  const emptyListNames = ["base*", `${openTailName}*`];
32
37
  const captureGroupPrefix = "p";
33
38
  const multiSegmentCapture = "[^/]+(?:/[^/]+)*";
39
+ const reservedCapture = "[^]+?";
40
+ const shortMultiSegmentCapture = "[^/]+(?:/[^/]+)*?";
34
41
  const sharedPartMaxLength = 1e3;
35
42
  const writtenPartMaxLength = sharedPartMaxLength * 9;
36
- const toLengthGuard = (maxLength, stops) => {
37
- if (!stops) return `(?=[^]{0,${maxLength}}$)`;
38
- return `(?=[^${stops}]{0,${maxLength}}(?:[${stops}]|$))`;
43
+ const toValueParts = (parsed) => {
44
+ return [
45
+ ...parsed.host.split("."),
46
+ ...splitPath(parsed.path),
47
+ ...parsed.params.map((param) => param.value),
48
+ ...parsed.nameFlags,
49
+ ...splitPath(parsed.fragment ?? "")
50
+ ];
51
+ };
52
+ const toEndingGuard = (text, mapLiteral) => {
53
+ const hasSharedSegment = splitPath(text).some((segment) => {
54
+ return [...segment.matchAll(placeholderRegex)].length > 1;
55
+ });
56
+ const ending = mapLiteral(text.split(placeholderRegex).at(-1) ?? "");
57
+ if (!hasSharedSegment || !ending) return "";
58
+ return `(?=[^]*${escapeRegex(ending)}$)`;
39
59
  };
40
60
  const countValues = (pieces) => {
41
61
  return Math.floor(pieces.length / 2);
42
62
  };
63
+ const hasValueBehindReserved = (text, reservedNames) => {
64
+ const pieces = text.split(placeholderRegex);
65
+ return pieces.some((piece, index) => {
66
+ return index % 2 === 1 && index < pieces.length - 2 && reservedNames.includes(piece);
67
+ });
68
+ };
43
69
  const pathCapture = {
44
70
  source: "[^/]+",
45
71
  unit: "[^/]",
@@ -59,23 +85,68 @@ const isMultiSegment = (placeholder) => {
59
85
  const toBareName = (placeholder) => {
60
86
  return isMultiSegment(placeholder) ? placeholder.slice(0, -1) : placeholder;
61
87
  };
88
+ const toGroupValue = (captured, value) => {
89
+ if (captured.part !== "path") return value;
90
+ if (!captured.isList) return decodePercent(value);
91
+ return value.split("/").filter((segment) => segment).map(decodePercent);
92
+ };
93
+ const toJobs = (scheme, host) => {
94
+ const labels = host.split(".");
95
+ const toName = (text) => {
96
+ return wholePlaceholderRegex.exec(text ?? "")?.[1];
97
+ };
98
+ if (labels.length === 1) return {
99
+ schemeName: toName(scheme),
100
+ hostName: toName(host)
101
+ };
102
+ return {
103
+ schemeName: toName(scheme),
104
+ parentName: toName(labels.at(-1))
105
+ };
106
+ };
62
107
  const isEmptyList = (placeholder) => {
63
108
  return emptyListNames.includes(placeholder);
64
109
  };
65
- const toSegments = (value) => {
66
- if (isPlainObject(value)) return [];
67
- return (isString(value) ? value.split("/") : value ?? []).filter((segment) => segment);
68
- };
69
110
  const toMapItems = (map) => {
70
- return Object.entries(map).flat();
111
+ return toMapEntries(map).flat();
71
112
  };
72
- const getPlaceholderValue = (params, placeholder) => {
73
- const value = params[toBareName(placeholder)];
74
- if (isPlainObject(value)) {
75
- if (Object.keys(value).length === 0) return;
76
- return value;
113
+ const toMapEntries = (map) => {
114
+ return Object.entries(map).flatMap(([name, value]) => {
115
+ return coerceArray(value).map((item) => [name, item]);
116
+ });
117
+ };
118
+ const isTypedText = (item) => {
119
+ if (isString(item)) return !loneSurrogateRegex.test(item);
120
+ return isNullish(item) || isNumber(item) || isBoolean(item);
121
+ };
122
+ const isTypedValue = (value) => {
123
+ if (Array.isArray(value)) return value.every(isTypedText);
124
+ if (!isObject(value)) return isTypedText(value);
125
+ return Object.entries(value).every(([name, item]) => {
126
+ return isTypedText(name) && coerceArray(item).every(isTypedText);
127
+ });
128
+ };
129
+ const toTypedValue = (value) => {
130
+ const toTexts = (items) => {
131
+ return items.filter(isPresent).map(String);
132
+ };
133
+ if (isNullish(value)) return;
134
+ if (Array.isArray(value)) return toTexts(value);
135
+ if (!isObject(value)) return String(value);
136
+ const map = {};
137
+ for (const [name, item] of Object.entries(value)) {
138
+ if (Array.isArray(item)) {
139
+ setKey(map, name, toTexts(item));
140
+ continue;
141
+ }
142
+ if (isPresent(item)) setKey(map, name, String(item));
77
143
  }
78
- if (!isMultiSegment(placeholder)) return Array.isArray(value) ? omitEmpty(value) : value;
144
+ return map;
145
+ };
146
+ const getPlaceholderValue = (params, placeholder) => {
147
+ const value = toTypedValue(params[toBareName(placeholder)]);
148
+ if (isPlainObject(value)) return trimObject(value);
149
+ if (!isMultiSegment(placeholder)) return Array.isArray(value) ? trimArray(value) : value;
79
150
  const segments = toSegments(value);
80
151
  if (segments.length === 0 && !isEmptyList(placeholder)) return;
81
152
  return segments;
@@ -83,95 +154,57 @@ const getPlaceholderValue = (params, placeholder) => {
83
154
  const splitPath = (path) => {
84
155
  return path.replaceAll("{/", "/{").split("/");
85
156
  };
157
+ const toSlotText = (value, placeholder) => {
158
+ if (!isMultiSegment(placeholder)) return (isPlainObject(value) ? toMapItems(value) : coerceArray(value)).join(",");
159
+ if (!isPlainObject(value)) return coerceArray(value).join("/");
160
+ return toMapEntries(value).map(([name, item]) => `${name}=${item}`).join("/");
161
+ };
86
162
  const toValueText = (value) => {
87
163
  if (isPlainObject(value)) return toMapItems(value).join(",");
88
164
  return Array.isArray(value) ? value.join("/") : value;
89
165
  };
90
- const decodeEscapes = (value) => {
91
- return decodePercent(String(value));
166
+ const respelledRegexes = {
167
+ path: pathRespelledRegex,
168
+ query: queryRespelledRegex,
169
+ fragment: fragmentRespelledRegex
92
170
  };
93
- const encodePathValue = (value) => {
94
- return encodePathSegment(decodeEscapes(value).replaceAll("%", "%25")).replace(strayPercentRegex, "%25").replace(nonAsciiRegex, encodeURIComponent);
171
+ const encodeParserText = (text, part) => {
172
+ const end = part === "fragment" ? -1 : text.search(part === "path" ? reservedEndRegex : hashRegex);
173
+ if (end === -1) return text.replace(respelledRegexes[part], toPercentEscape);
174
+ const head = text.slice(0, end).replace(respelledRegexes[part], toPercentEscape);
175
+ const rest = encodeParserText(text.slice(end + 1), text[end] === "#" ? "fragment" : "query");
176
+ return `${head}${text[end]}${rest}`;
95
177
  };
96
- const encodeQueryValue = (value) => {
97
- return encodeText(decodeEscapes(value));
178
+ const encodePathText = (text, part) => {
179
+ const segment = encodePathSegment(text.replaceAll("%", "%25")).replace(strayPercentRegex, "%25");
180
+ return encodeParserText(segment, part).replace(nonAsciiRegex, encodeURIComponent);
98
181
  };
99
- const fillQueryValue = (template, values, encodeValue) => {
100
- const runs = [];
101
- const push = (text, kind) => {
102
- const last = runs.at(-1);
103
- if (last && last.kind === kind && kind !== "separator") {
104
- last.text += text;
105
- return;
106
- }
107
- runs.push({
108
- text,
109
- kind
110
- });
111
- };
112
- for (const [index, piece] of template.split(placeholderRegex).entries()) {
113
- if (index % 2 === 0) {
114
- if (piece) push(piece, "literal");
115
- continue;
116
- }
117
- const value = values[piece];
118
- const items = isPlainObject(value) ? toMapItems(value) : value;
119
- if (!Array.isArray(items)) {
120
- push(String(items), "value");
121
- continue;
122
- }
123
- for (const [itemIndex, item] of items.entries()) {
124
- if (itemIndex > 0) push(",", "separator");
125
- for (const [partIndex, part] of item.split(",").entries()) {
126
- if (partIndex > 0) push("%2C", "separator");
127
- push(part, "value");
128
- }
129
- }
130
- }
131
- return runs.map((run) => {
132
- if (run.kind === "separator") return run.text;
133
- return run.kind === "literal" ? encodeText(run.text) : encodeValue(run.text);
134
- }).join("");
182
+ const encodePathValue = (value, part) => {
183
+ return encodeDecoded(value, (text) => encodePathText(text, part));
135
184
  };
136
185
  const encodeSlot = (value, encode) => {
137
186
  const items = isPlainObject(value) ? toMapItems(value) : value;
138
187
  if (!Array.isArray(items)) return encode(items);
139
188
  return items.map((item) => encode(item).replaceAll(",", "%2C")).join(",");
140
189
  };
141
- const encodeMapSegments = (map, encode) => {
142
- return Object.entries(map).map(([name, value]) => `${encode(name)}=${encode(value)}`).join("/");
143
- };
144
- const encodePath = (value) => {
145
- return Array.isArray(value) ? value.map(encodePathValue).join("/") : encodePathValue(value);
146
- };
147
- const encodeLiteral = (text) => {
148
- return text.replace(nonAsciiRegex, encodeURIComponent);
149
- };
150
- const toPercentEscape = (character) => {
151
- return `%${character.charCodeAt(0).toString(16).toUpperCase()}`;
152
- };
153
- const encodeStrictValue = (value) => {
154
- return encodeURIComponent(value).replace(subDelimiterRegex, toPercentEscape);
155
- };
156
- const encodeStrictQueryText = (text) => {
157
- return text.split("+").map((piece) => encodeStrictValue(decodePercent(piece))).join("+");
158
- };
159
- const toStrictPair = (pair) => {
160
- const separator = pair.text.indexOf("=");
161
- if (separator === -1) return toPair(encodeStrictQueryText(pair.text));
162
- const name = encodeStrictQueryText(pair.text.slice(0, separator));
163
- const value = encodeStrictQueryText(pair.text.slice(separator + 1));
164
- return toPair(`${name}=${value}`);
165
- };
166
- const encodeStrict = (value) => {
167
- return Array.isArray(value) ? value.map(encodeStrictValue).join("/") : encodeStrictValue(value);
190
+ const encodeLiteral = (text, part) => {
191
+ return text.split(placeholderTextRegex).map((piece, index) => {
192
+ if (index % 2 === 1) return piece;
193
+ return encodeParserText(piece, part).replace(nonAsciiRegex, encodeURIComponent);
194
+ }).join("");
168
195
  };
169
- const decodePath = (path) => {
170
- if (!path.includes("%")) return path;
171
- return path.split("/").map((segment) => decodePercent(segment).replaceAll("%", "%25").replaceAll("/", "%2F")).join("/");
196
+ const encodeReservedValue = (value, isStrict, part) => {
197
+ if (!isStrict) {
198
+ const written = value.replace(strayPercentRegex, "%25");
199
+ return encodeParserText(written, part).replace(nonAsciiRegex, encodeURIComponent);
200
+ }
201
+ return value.split(singleEscapeRegex).map((piece, index) => {
202
+ if (index % 2 === 1) return piece;
203
+ return piece.replace(unreservedOtherRegex, toPercentEscape).replace(nonAsciiRegex, encodeURIComponent);
204
+ }).join("");
172
205
  };
173
- const writeBase = (base, pairs) => {
174
- return pairs.length > 0 && pathlessBaseRegex.test(base) ? `${base}/` : base;
206
+ const encodeReservedSlot = (value, isStrict, part) => {
207
+ return (isPlainObject(value) ? toMapItems(value) : coerceArray(value)).map((item) => encodeReservedValue(item, isStrict, part)).join(",");
175
208
  };
176
209
  const mapTemplate = (text, mapPlaceholder, mapLiteral = (literal) => literal) => {
177
210
  return text.split(placeholderRegex).map((piece, index) => {
@@ -181,10 +214,10 @@ const mapTemplate = (text, mapPlaceholder, mapLiteral = (literal) => literal) =>
181
214
  }).join("");
182
215
  };
183
216
  const toLaterSource = ({ unit }, separator) => {
184
- if (!unit || !new RegExp(`^(?:${unit})+$`).test(separator)) return;
217
+ if (!new RegExp(`^(?:${unit})+$`).test(separator)) return;
185
218
  return `(?:(?!${escapeRegex(separator)})${unit})*${unit}{1,${separator.length}}`;
186
219
  };
187
- const toRegexSource = (text, wrapCapture, capture, captures = {}, mapLiteral = (literal) => literal, patterns = {}) => {
220
+ const toRegexSource = ({ text, wrapCapture, capture, captures = {}, mapLiteral = (literal) => literal, patterns = {}, shortNames = [] }) => {
188
221
  const pieces = text.split(placeholderRegex).map((piece, index) => index % 2 === 1 ? piece : mapLiteral(piece));
189
222
  const countSegmentValues = (index) => {
190
223
  const end = pieces.findIndex((piece, later) => {
@@ -192,79 +225,156 @@ const toRegexSource = (text, wrapCapture, capture, captures = {}, mapLiteral = (
192
225
  });
193
226
  return countValues(pieces.slice(index, end === -1 ? void 0 : end));
194
227
  };
195
- return pieces.map((piece, index) => {
228
+ let isSegmentOpen = false;
229
+ let isCountKnown = true;
230
+ let slashCount = 0;
231
+ let openCount = 0;
232
+ const closeSegment = () => {
233
+ isSegmentOpen = false;
234
+ return `(?=/|$)(?<=^[^/]*(?:/[^/]*){${openCount}}))[^/]*`;
235
+ };
236
+ const hasCapture = (index) => {
237
+ const end = pieces.findIndex((piece, later) => {
238
+ return later > index && later % 2 === 0 && piece.includes("/");
239
+ });
240
+ return pieces.slice(index, end === -1 ? void 0 : end).some((piece, offset) => {
241
+ return offset % 2 === 1 && captures[piece] !== void 0;
242
+ });
243
+ };
244
+ const source = pieces.map((piece, index) => {
196
245
  if (index % 2 === 0) {
197
- const slash = piece.lastIndexOf("/");
198
- if (!capture.segmentMaxLength || slash === -1 || countSegmentValues(index) < 2) return escapeRegex(piece);
199
- const head = escapeRegex(piece.slice(0, slash + 1));
200
- const tail = escapeRegex(piece.slice(slash + 1));
201
- return `${head}${toLengthGuard(capture.segmentMaxLength, "/")}${tail}`;
246
+ const firstSlash = piece.indexOf("/");
247
+ const isClosing = isSegmentOpen && firstSlash !== -1;
248
+ const closing = isClosing ? `${toLiteralSource(piece.slice(0, firstSlash))}${closeSegment()}` : "";
249
+ const rest = isClosing ? piece.slice(firstSlash) : piece;
250
+ const slash = rest.lastIndexOf("/");
251
+ slashCount += piece.split("/").length - 1;
252
+ if (!capture.segmentMaxLength || slash === -1 && index > 0 || countSegmentValues(index) < 2) return `${closing}${toLiteralSource(rest)}`;
253
+ const head = toLiteralSource(rest.slice(0, slash + 1));
254
+ const tail = toLiteralSource(rest.slice(slash + 1));
255
+ const guard = toLengthGuard(capture.segmentMaxLength, "/");
256
+ isSegmentOpen = isCountKnown && !hasCapture(index);
257
+ openCount = slashCount;
258
+ return `${closing}${head}${guard}${isSegmentOpen ? "(?=" : ""}${tail}`;
202
259
  }
260
+ if (captures[piece] !== void 0) isCountKnown = false;
203
261
  const frontPattern = index > 1 ? patterns[pieces[index - 2]] : void 0;
204
262
  const isFreed = frontPattern !== void 0 && !new RegExp(`^${frontPattern}$`, "i").test(pieces[index - 1]);
205
- const laterSource = index > 1 && !isFreed ? toLaterSource(capture, pieces[index - 1]) : void 0;
206
- const source = wrapCapture(piece, captures[piece] ?? patterns[piece] ?? laterSource ?? capture.source);
207
- if (!isMultiSegment(piece)) return source;
208
- return isEmptyList(piece) ? `(?:/${source})?` : `/${source}`;
263
+ const isBehindShort = shortNames.includes(pieces[index - 2]);
264
+ const laterSource = index > 1 && !isFreed && !isBehindShort ? toLaterSource(capture, pieces[index - 1]) : void 0;
265
+ const pattern = captures[piece] === void 0 ? patterns[piece] : void 0;
266
+ const captureSource = wrapCapture(piece, captures[piece] ?? pattern ?? laterSource ?? capture.source, pattern === void 0 ? void 0 : capture.unit);
267
+ if (!isMultiSegment(piece)) return captureSource;
268
+ return isEmptyList(piece) ? `(?:/${captureSource})?` : `/${captureSource}`;
209
269
  }).join("");
210
- };
211
- const checkExpressions = (template) => {
212
- const throwOldSpelling = (expression, spelling) => {
213
- throw new Error(t(errors.oldTemplateSpelling, {
214
- template,
215
- expression,
216
- spelling
217
- }));
218
- };
219
- const oldList = oldListRegex.exec(template);
220
- if (oldList) throwOldSpelling(oldList[0], `{/${oldList[1] || "tail"}*}`);
221
- if (template.includes(oldQuery)) throw new Error(t(errors.unsupportedPassedQuery, {
222
- template,
223
- expression: oldQuery
224
- }));
225
- if (braceRegex.test(template.replace(expressionRegex, ""))) throw new Error(t(errors.unbalancedBrace, { template }));
226
- for (const [expression, body] of template.matchAll(expressionRegex)) {
227
- if (expression === oldTail) throwOldSpelling(oldTail, openTailSuffix);
228
- if (plainExpressionRegex.test(body) || optionalQueryExpressionRegex.test(body)) continue;
229
- if (queryExpressionRegex.test(body)) throw new Error(t(errors.invalidTemplate, { template }));
230
- throw new Error(t(errors.unsupportedTemplateExpression, {
231
- template,
232
- expression
233
- }));
234
- }
270
+ return isSegmentOpen ? `${source}${closeSegment()}` : source;
271
+ };
272
+ const cutFragment = (template) => {
273
+ const suffix = fragmentSuffixRegex.exec(template);
274
+ if (suffix) return [template.slice(0, suffix.index), `{+${suffix[1]}}`];
275
+ const index = template.indexOf("#");
276
+ return index === -1 ? [template] : [template.slice(0, index), template.slice(index + 1)];
277
+ };
278
+ const toAsciiHost = (host) => {
279
+ const toAsciiLabel = (label) => {
280
+ if (label.includes("{")) return mapTemplate(label, (name) => `{${name}}`, (text) => text.toLowerCase());
281
+ if (!nonAsciiLabelRegex.test(label)) return label.toLowerCase();
282
+ const ascii = parseUrl(`https://${label}.${contextLabel}`)?.hostname;
283
+ if (!ascii?.endsWith(`.${contextLabel}`)) return label;
284
+ const asciiLabel = ascii.slice(0, -8);
285
+ return asciiLabel.includes(".") ? label : asciiLabel;
286
+ };
287
+ return host.split(".").map(toAsciiLabel).join(".");
235
288
  };
236
289
  const parseTemplate = (template) => {
237
- checkExpressions(template);
238
- const optional = optionalQueryRegex.exec(template);
239
- const base = optional ? template.slice(0, optional.index) : template;
290
+ validateOldSpellings(template);
291
+ validateBraces(template);
292
+ validateExpressions(template);
293
+ const [body, givenFragment] = cutFragment(template);
294
+ validateFragment(template, body, givenFragment);
295
+ const optional = optionalQueryRegex.exec(body);
296
+ const base = optional ? body.slice(0, optional.index) : body;
240
297
  const match = templateRegex.exec(base);
241
- if (!match || base.includes("{?") || base.includes("{&")) throw new Error(t(errors.invalidTemplate, { template }));
242
- const [, scheme, host, givenPath = "", search] = match;
243
- if (optional && optional[1] === "?" === Boolean(search)) throw new Error(t(errors.invalidTemplate, { template }));
244
- const optionalNames = optional ? optional[2].split(",") : [];
298
+ validateTemplateMatch(template, base, match);
299
+ const { scheme: givenScheme, host: givenHost, path: givenPath = "", search } = match.groups ?? {};
300
+ validateHostText(template, givenHost);
301
+ const scheme = givenScheme.startsWith("{") ? givenScheme : givenScheme.toLowerCase();
302
+ const host = toAsciiHost(givenHost);
303
+ validateHostLabels(template, host);
304
+ const jobs = toJobs(scheme, host);
305
+ const reservedNames = [...givenPath.matchAll(reservedRegex)].map(([, name]) => name);
306
+ const split = listSplitRegex.exec(givenPath)?.groups;
307
+ const listSplit = split !== void 0 && `{/${split.list}*}` !== "{/base*}" ? {
308
+ list: split.list,
309
+ reserved: split.reserved
310
+ } : void 0;
311
+ const baseNames = givenPath.startsWith("{/base*}") ? ["base*"] : [];
312
+ const splitNames = listSplit ? [`${listSplit.list}*`] : [];
313
+ validateReservedPlacement({
314
+ template,
315
+ base,
316
+ ownText: `${scheme}${host}${search ?? ""}`,
317
+ reservedNames,
318
+ besideNames: [...baseNames, ...splitNames]
319
+ });
320
+ validateOptionalPlacement(template, optional?.groups?.operator, search);
321
+ const queryNames = optional?.groups?.names.split(",") ?? [];
322
+ const passedName = queryNames.at(-1)?.endsWith("*") ? queryNames.pop()?.slice(0, -1) : void 0;
323
+ const optionalNames = queryNames;
245
324
  const isOpen = givenPath.endsWith(openTailSuffix);
246
325
  const entries = search ? [...toSearchParams(parseQuery(search))] : [];
247
- if (entries.some(([name]) => name.includes("{"))) throw new Error(t(errors.invalidTemplate, { template }));
248
- const flagNames = entries.filter(([, value]) => !value).map(([name]) => name);
249
- const params = entries.map(([name, value]) => {
250
- const isFlag = flagNames.includes(name);
251
- const isFilled = !isFlag && value.includes("{");
252
- const writtenName = encodeText(name);
253
- const writtenValue = isFilled ? "" : encodeText(value);
326
+ const isNameFlag = ([name, value]) => {
327
+ return name.includes("{") && !value;
328
+ };
329
+ const nameFlags = entries.filter(isNameFlag).map(([name]) => name);
330
+ const valueEntries = entries.filter((entry) => !isNameFlag(entry));
331
+ validateQueryPlaceholders(template, nameFlags, valueEntries, search);
332
+ const params = valueEntries.map(([name, value]) => {
333
+ const isFlag = !value;
254
334
  return {
255
335
  name,
256
336
  value,
257
337
  isFlag,
258
- writtenName,
259
- pair: toPair(isFlag ? writtenName : `${writtenName}=${writtenValue}`),
260
- isFilled
338
+ isFilled: !isFlag && value.includes("{")
261
339
  };
262
340
  });
263
- const paramNames = [...params.map((param) => param.name), ...optionalNames];
264
- const placeholderNames = [...base.matchAll(placeholderRegex)].map(([, name]) => toBareName(name));
265
- if (optionalNames.some((name) => placeholderNames.includes(name))) throw new Error(t(errors.invalidTemplate, { template }));
266
- if (paramNames.some((name, index) => paramNames.indexOf(name) !== index)) throw new Error(t(errors.invalidTemplate, { template }));
267
- const path = isOpen ? givenPath.slice(0, -8) : givenPath;
341
+ const paramNames = [
342
+ ...params.map((param) => param.name),
343
+ ...optionalNames,
344
+ ...passedName === void 0 ? [] : [passedName]
345
+ ];
346
+ const fragmentText = givenFragment ?? "";
347
+ const fragmentReservedNames = [...fragmentText.matchAll(reservedRegex)].map(([, name]) => name);
348
+ const fragment = givenFragment?.replace(reservedRegex, "{$1}");
349
+ const placeholderNames = [...`${base}${fragmentText}`.matchAll(placeholderRegex)].map(([, name]) => toBareName(name));
350
+ const names = {
351
+ template,
352
+ queryValueNames: paramNames.slice(params.length),
353
+ placeholderNames,
354
+ reservedNames: [...reservedNames, ...fragmentReservedNames]
355
+ };
356
+ validateQueryValueNames(names);
357
+ validateParamNames(template, paramNames);
358
+ validatePrototypeNames(names);
359
+ const plainPath = givenPath.replace(reservedRegex, "{$1}");
360
+ const path = isOpen ? plainPath.slice(0, -8) : plainPath;
361
+ validateReservedNames(names);
362
+ validateAdjacentValues(template);
363
+ validateDotSegments(template, path);
364
+ validateListPairs(template, path);
365
+ const basedPath = givenPath.startsWith("{/base*}") ? givenPath.slice(8) : givenPath;
366
+ const innerPath = isOpen ? basedPath.slice(0, -8) : basedPath;
367
+ validateKeywords(template, [
368
+ givenScheme,
369
+ givenHost,
370
+ innerPath,
371
+ search,
372
+ optional?.[0],
373
+ fragmentText
374
+ ]);
375
+ validateBasePlacement(template, jobs.hostName, givenPath);
376
+ const lastName = reservedNames.at(-1);
377
+ const isRest = !(Boolean(search) || optional !== null || fragment !== void 0) && givenPath.endsWith(`{+${lastName}}`);
268
378
  return {
269
379
  text: template,
270
380
  scheme,
@@ -272,74 +382,309 @@ const parseTemplate = (template) => {
272
382
  path,
273
383
  search,
274
384
  isOpen,
275
- names: [...`${scheme}${host}${path}${search ?? ""}`.matchAll(placeholderRegex)].map(([, name]) => name),
385
+ jobs,
386
+ names: [...`${scheme}${host}${path}${search ?? ""}${fragment ?? ""}`.matchAll(placeholderRegex)].map(([, name]) => name),
276
387
  params,
277
- optionalNames
388
+ optionalNames,
389
+ reservedNames,
390
+ restName: isRest ? lastName : void 0,
391
+ listSplit,
392
+ fragment,
393
+ fragmentReservedNames,
394
+ nameFlags,
395
+ queryOrder: entries.map(([name]) => name),
396
+ passedName
278
397
  };
279
398
  };
280
- const compileTemplate = (parsed, pathPatterns = {}, writtenPathPatterns = pathPatterns) => {
281
- const { scheme, host, path, isOpen, names } = parsed;
399
+ const compileTemplate = ({ parsed, splitPatterns = {}, writtenSplitPatterns = splitPatterns, lenient = {}, isFlagValueChecked = () => true }) => {
400
+ const { scheme, host, path, isOpen, names, reservedNames, restName } = parsed;
282
401
  const captured = [];
283
402
  const captureIn = (part) => {
284
- return (name, source) => {
403
+ return (name, source, patternUnit) => {
285
404
  captured.push({
286
405
  name: toBareName(name),
287
406
  part,
288
- isList: part === "path" && isMultiSegment(name)
407
+ isList: part === "path" && isMultiSegment(name),
408
+ unitRegex: patternUnit === void 0 ? void 0 : new RegExp(`^${patternUnit}*$`)
289
409
  });
290
410
  return `(?<${captureGroupPrefix}${captured.length - 1}>${source})`;
291
411
  };
292
412
  };
293
413
  const getCaptured = (group) => {
294
- if (!ownGroupRegex.test(group)) return;
295
414
  return captured[Number(group.slice(1))];
296
415
  };
297
- const params = parsed.params.map((param) => {
298
- const source = toRegexSource(param.value, captureIn("query"), queryCapture);
299
- const rawSource = toRegexSource(param.value, captureIn("query"), queryCapture, {}, encodeText);
300
- const isShared = countValues(param.value.split(placeholderRegex)) > 1;
416
+ const isSameCopy = (name, copy, other, read) => {
417
+ const copyText = JSON.stringify(copy);
418
+ const otherText = JSON.stringify(other);
419
+ if (copyText === otherText) return true;
420
+ if (!lenient.valueCase?.includes(name)) return false;
421
+ if (toAsciiLowerCaseText(copyText) !== toAsciiLowerCaseText(otherText)) return false;
422
+ read.isCaseBlind = true;
423
+ return true;
424
+ };
425
+ const encodeQueryText = (text) => {
426
+ const written = encodeParserText(encodeText(text), "query");
427
+ return lenient.semicolonSeparator === true ? written.replaceAll(";", "%3B") : written;
428
+ };
429
+ const encodeQueryName = (name) => {
430
+ return encodeQueryText(name).replaceAll("=", "%3D");
431
+ };
432
+ const toWrittenPair = (text) => {
433
+ if (lenient.ampersandEntity === true && text.startsWith("amp;")) return toPair(`amp%3B${text.slice(entityPrefix.length)}`);
434
+ return toPair(text);
435
+ };
436
+ const toQueryRegexes = ({ text, capture, writtenCapture, mapLiteral }) => {
437
+ const source = toRegexSource({
438
+ text,
439
+ wrapCapture: captureIn("query"),
440
+ capture,
441
+ patterns: splitPatterns
442
+ });
443
+ const rawSource = toRegexSource({
444
+ text,
445
+ wrapCapture: captureIn("query"),
446
+ capture: writtenCapture,
447
+ mapLiteral,
448
+ patterns: writtenSplitPatterns
449
+ });
450
+ const isShared = countValues(text.split(placeholderRegex)) > 1;
301
451
  const guard = isShared ? toLengthGuard(sharedPartMaxLength) : "";
302
452
  const rawGuard = isShared ? toLengthGuard(writtenPartMaxLength) : "";
303
453
  return {
304
- ...param,
305
454
  regex: new RegExp(`^${guard}${source}$`, "i"),
306
455
  rawRegex: new RegExp(`^${rawGuard}${rawSource}$`, "d")
307
456
  };
457
+ };
458
+ const params = parsed.params.map((param) => {
459
+ const regexes = toQueryRegexes({
460
+ text: param.value,
461
+ capture: queryCapture,
462
+ writtenCapture: queryCapture,
463
+ mapLiteral: encodeQueryText
464
+ });
465
+ const writtenName = encodeQueryName(param.name);
466
+ const writtenValue = param.isFilled ? "" : encodeQueryText(param.value);
467
+ return {
468
+ ...param,
469
+ writtenName,
470
+ pair: toPair(param.isFlag ? writtenName : `${writtenName}=${writtenValue}`),
471
+ ...regexes
472
+ };
308
473
  });
474
+ const nameFlags = parsed.nameFlags.map((text) => {
475
+ return {
476
+ text,
477
+ ...toQueryRegexes({
478
+ text,
479
+ capture: pathCapture,
480
+ writtenCapture: writtenPathCapture,
481
+ mapLiteral: encodeQueryName
482
+ })
483
+ };
484
+ });
485
+ const takenNames = [...parsed.params.map((param) => param.name), ...parsed.optionalNames];
486
+ const matchFlagPattern = (flag, name) => {
487
+ if (isAnyOf(name, takenNames)) return;
488
+ return flag.regex.exec(name) ?? void 0;
489
+ };
490
+ const matchFlagName = (flag, name, values) => {
491
+ const match = matchFlagPattern(flag, name);
492
+ if (!match) return;
493
+ if (Object.entries(match.groups ?? {}).every(([group, value]) => {
494
+ return isFlagValueChecked(getCaptured(group).name, value, values);
495
+ })) return match;
496
+ };
497
+ const readFlagName = (name, values) => {
498
+ for (const flag of nameFlags) {
499
+ const match = matchFlagName(flag, name, values);
500
+ if (match) return match;
501
+ }
502
+ };
503
+ const claimFlags = (flagNames, values) => {
504
+ const indexes = [];
505
+ for (const flag of nameFlags) {
506
+ const findFree = (match) => {
507
+ return flagNames.findIndex((name, nameIndex) => {
508
+ return name !== void 0 && !indexes.includes(nameIndex) && match(name) !== void 0;
509
+ });
510
+ };
511
+ const checkedIndex = findFree((name) => matchFlagName(flag, name, values));
512
+ const index = checkedIndex === -1 ? findFree((name) => matchFlagPattern(flag, name)) : checkedIndex;
513
+ indexes.push(index);
514
+ }
515
+ return indexes;
516
+ };
517
+ const namedParts = [...parsed.queryOrder.map((name) => parsed.nameFlags.includes(name) ? void 0 : name), ...parsed.optionalNames];
518
+ const flagPlaces = [...namedParts.keys()].filter((place) => namedParts[place] === void 0);
519
+ const orderPairs = (pairs, values) => {
520
+ const flagIndexes = claimFlags(toFlagNames(pairs), values);
521
+ const toQueryPlace = (pair, index) => {
522
+ const flagIndex = flagIndexes.indexOf(index);
523
+ const place = flagIndex === -1 ? namedParts.findIndex((name) => name !== void 0 && isNamed(pair, name)) : flagPlaces[flagIndex];
524
+ return place === -1 ? namedParts.length : place;
525
+ };
526
+ const places = pairs.map(toQueryPlace);
527
+ return [...pairs.keys()].sort((left, right) => places[left] - places[right]).map((index) => pairs[index]);
528
+ };
309
529
  const multiSegmentCaptures = Object.fromEntries(names.filter(isMultiSegment).map((name) => [name, multiSegmentCapture]));
310
- const hasTwoLists = names.filter(isMultiSegment).length > 1;
311
- const pathGuard = hasTwoLists ? toLengthGuard(sharedPartMaxLength) : "";
312
- const rawPathGuard = hasTwoLists ? toLengthGuard(writtenPartMaxLength) : "";
313
- const pathSource = toRegexSource(path.replace(trailingSlashRegex, ""), captureIn("path"), pathCapture, multiSegmentCaptures, decodePath, pathPatterns);
314
- const rawPathSource = path ? toRegexSource(path, captureIn("path"), writtenPathCapture, multiSegmentCaptures, encodeLiteral, writtenPathPatterns) : "/?";
315
- const readPathSource = isOpen ? `${pathGuard}${pathSource}(?:/${captureIn("path")(`${openTailName}*`, ".*")})?` : `${pathGuard}${pathSource}`;
316
- const readGroups = (values, groups = {}) => {
317
- for (const [group, value] of Object.entries(groups)) {
530
+ const splitCaptures = parsed.listSplit ? { [`${parsed.listSplit.list}*`]: shortMultiSegmentCapture } : {};
531
+ const pathCaptures = {
532
+ ...multiSegmentCaptures,
533
+ ...splitCaptures,
534
+ ...Object.fromEntries(reservedNames.map((name) => [name, reservedCapture]))
535
+ };
536
+ const isSharedPath = names.filter(isMultiSegment).length + reservedNames.length > 1 || hasValueBehindReserved(path, reservedNames);
537
+ const pathGuard = isSharedPath ? toLengthGuard(sharedPartMaxLength) : "";
538
+ const rawPathGuard = isSharedPath ? toLengthGuard(writtenPartMaxLength) : "";
539
+ const pathSource = toRegexSource({
540
+ text: path.replace(trailingSlashRegex, ""),
541
+ wrapCapture: captureIn("path"),
542
+ capture: pathCapture,
543
+ captures: pathCaptures,
544
+ mapLiteral: decodePath,
545
+ patterns: splitPatterns,
546
+ shortNames: reservedNames
547
+ });
548
+ const rawPathSource = path ? toRegexSource({
549
+ text: path,
550
+ wrapCapture: captureIn("path"),
551
+ capture: writtenPathCapture,
552
+ captures: pathCaptures,
553
+ mapLiteral: (literal) => encodeLiteral(literal, "path"),
554
+ patterns: writtenSplitPatterns,
555
+ shortNames: reservedNames
556
+ }) : "/?";
557
+ const isOpenEnded = isOpen || restName !== void 0;
558
+ const readEndingGuard = isOpenEnded ? "" : toEndingGuard(path.replace(trailingSlashRegex, ""), decodePath);
559
+ const rawEndingGuard = isOpenEnded ? "" : toEndingGuard(path, (literal) => encodeLiteral(literal, "path"));
560
+ const readPathSource = isOpen ? `${pathGuard}${pathSource}(?:/${captureIn("path")(`${openTailName}*`, "[^]*")})?` : `${readEndingGuard}${pathGuard}${pathSource}`;
561
+ const { fragment, fragmentReservedNames } = parsed;
562
+ const fragmentCaptures = Object.fromEntries(fragmentReservedNames.map((name) => [name, reservedCapture]));
563
+ const toFragmentRegex = ({ capture, mapLiteral, patterns, maxLength, flags }) => {
564
+ if (fragment === void 0) return;
565
+ const source = toRegexSource({
566
+ text: fragment,
567
+ wrapCapture: captureIn("fragment"),
568
+ capture,
569
+ captures: fragmentCaptures,
570
+ mapLiteral,
571
+ patterns,
572
+ shortNames: fragmentReservedNames
573
+ });
574
+ const guard = fragmentReservedNames.length > 1 || hasValueBehindReserved(fragment, fragmentReservedNames) ? toLengthGuard(maxLength) : "";
575
+ return new RegExp(`^${guard}${toEndingGuard(fragment, mapLiteral)}${source}$`, flags);
576
+ };
577
+ const fragmentRegex = toFragmentRegex({
578
+ capture: pathCapture,
579
+ mapLiteral: decodePath,
580
+ patterns: splitPatterns,
581
+ maxLength: sharedPartMaxLength,
582
+ flags: "di"
583
+ });
584
+ const rawFragmentRegex = toFragmentRegex({
585
+ capture: writtenPathCapture,
586
+ mapLiteral: (literal) => encodeLiteral(literal, "fragment"),
587
+ patterns: writtenSplitPatterns,
588
+ maxLength: writtenPartMaxLength,
589
+ flags: "d"
590
+ });
591
+ const readFragment = (hash, known) => {
592
+ const match = fragmentRegex?.exec(decodePath(hash));
593
+ if (!match) return;
594
+ const values = {};
595
+ const copyRead = { isCaseBlind: false };
596
+ for (const [group, [from, to]] of Object.entries(match.indices?.groups ?? {})) {
318
597
  const groupCaptured = getCaptured(group);
319
- if (!groupCaptured || value === void 0 || values[groupCaptured.name] !== void 0) continue;
320
- if (groupCaptured.part !== "path") {
321
- values[groupCaptured.name] = value;
598
+ const { name } = groupCaptured;
599
+ const matched = match.input.slice(from, to);
600
+ if (groupCaptured.unitRegex && !groupCaptured.unitRegex.test(matched)) return;
601
+ let value = decodePercent(matched);
602
+ if (fragmentReservedNames.includes(name)) {
603
+ const start = toWrittenOffset(hash, from);
604
+ const end = toWrittenOffset(hash, to);
605
+ if (start === void 0 || end === void 0) return;
606
+ value = hash.slice(start, end);
607
+ }
608
+ const copy = values[name] ?? known[name];
609
+ if (copy !== void 0 && !isSameCopy(name, copy, value, copyRead)) return;
610
+ values[name] = value;
611
+ }
612
+ return {
613
+ values,
614
+ isCaseBlind: copyRead.isCaseBlind
615
+ };
616
+ };
617
+ const readPassedQuery = (searchParams, values) => {
618
+ const lists = /* @__PURE__ */ new Map();
619
+ for (const [name, value] of searchParams) {
620
+ const isFlag = !value && readFlagName(name, values) !== void 0;
621
+ if (isAnyOf(name, takenNames) || isFlag) continue;
622
+ const list = lists.get(name);
623
+ if (!list) {
624
+ lists.set(name, [value]);
322
625
  continue;
323
626
  }
324
- values[groupCaptured.name] = groupCaptured.isList ? value.split("/").filter((segment) => segment).map(decodePercent) : decodePercent(value);
627
+ list.push(value);
325
628
  }
629
+ return Object.fromEntries([...lists].map(([name, list]) => [name, list.length === 1 ? list[0] : list]));
630
+ };
631
+ const readGroups = (values, copyRead, groups = {}) => {
632
+ return Object.entries(groups).every(([group, value]) => {
633
+ const groupCaptured = getCaptured(group);
634
+ if (value === void 0) return true;
635
+ if (groupCaptured.unitRegex && !groupCaptured.unitRegex.test(value)) return false;
636
+ const groupValue = toGroupValue(groupCaptured, value);
637
+ const known = values[groupCaptured.name];
638
+ if (known !== void 0) return isSameCopy(groupCaptured.name, known, groupValue, copyRead);
639
+ values[groupCaptured.name] = groupValue;
640
+ return true;
641
+ });
642
+ };
643
+ const hasOneValue = (searchParams, name, copyRead) => {
644
+ const [first, ...rest] = getQueryParamValues(searchParams, name, {
645
+ preserveEmptyValues: true,
646
+ trimValues: false
647
+ });
648
+ return rest.every((value) => isSameCopy(name, first, value, copyRead));
326
649
  };
327
650
  const read = (groups, getSearchParams) => {
328
651
  const values = {};
329
- readGroups(values, groups);
652
+ const copyRead = { isCaseBlind: false };
653
+ if (!takenNames.every((name) => hasOneValue(getSearchParams(), name, copyRead))) return;
654
+ if (!readGroups(values, copyRead, groups)) return;
330
655
  if (isOpen && !values["tail"]?.length) delete values[openTailName];
331
656
  for (const { name, isFlag, regex } of params) {
332
- const [value] = getQueryParamValues(getSearchParams(), name, { preserveEmptyValues: isFlag });
657
+ const [value] = getQueryParamValues(getSearchParams(), name, {
658
+ preserveEmptyValues: isFlag,
659
+ trimValues: false
660
+ });
333
661
  if (value === void 0) return;
334
662
  const queryMatch = regex.exec(value);
335
- if (!queryMatch) return;
336
- readGroups(values, queryMatch.groups);
663
+ if (!queryMatch || !readGroups(values, copyRead, queryMatch.groups)) return;
337
664
  }
665
+ const flagNames = [...getSearchParams()].map(([name, value]) => value ? void 0 : name);
666
+ const flagIndexes = claimFlags(flagNames, values);
667
+ for (const [flagIndex, { regex }] of nameFlags.entries()) {
668
+ const flagMatch = regex.exec(flagNames[flagIndexes[flagIndex]] ?? "");
669
+ if (!flagMatch || !readGroups(values, copyRead, flagMatch.groups)) return;
670
+ }
671
+ if (flagNames.some((name, index) => {
672
+ if (name === void 0 || flagIndexes.includes(index)) return false;
673
+ const matches = nameFlags.map((flag) => matchFlagName(flag, name, values)).filter(isPresent);
674
+ return matches.length > 0 && !matches.some((match) => readGroups({ ...values }, copyRead, match.groups));
675
+ })) return;
338
676
  for (const name of parsed.optionalNames) {
339
- const [value] = getQueryParamValues(getSearchParams(), name);
677
+ const [value] = getQueryParamValues(getSearchParams(), name, { trimValues: false });
340
678
  if (value !== void 0) values[name] = value;
341
679
  }
342
- return values;
680
+ if (parsed.passedName !== void 0) {
681
+ const passed = readPassedQuery(getSearchParams(), values);
682
+ if (Object.keys(passed).length > 0) values[parsed.passedName] = passed;
683
+ }
684
+ return {
685
+ values,
686
+ isCaseBlind: copyRead.isCaseBlind
687
+ };
343
688
  };
344
689
  const getValues = (givenParams) => {
345
690
  const values = {};
@@ -348,21 +693,45 @@ const compileTemplate = (parsed, pathPatterns = {}, writtenPathPatterns = pathPa
348
693
  if (!value) return;
349
694
  values[name] = value;
350
695
  }
351
- for (const name of parsed.optionalNames) {
696
+ const passedNames = parsed.passedName === void 0 ? [] : [parsed.passedName];
697
+ for (const name of [...parsed.optionalNames, ...passedNames]) {
352
698
  const value = getPlaceholderValue(givenParams, name);
353
699
  if (value !== void 0) values[name] = value;
354
700
  }
355
701
  return values;
356
702
  };
357
- const writtenPath = encodeLiteral(path);
703
+ const writtenPath = encodeLiteral(path, "path");
704
+ const encodePrettyQueryValue = (value) => {
705
+ return encodeDecoded(value, encodeQueryText);
706
+ };
707
+ const writtenFragment = fragment === void 0 ? void 0 : encodeLiteral(fragment, "fragment");
708
+ const encodeValue = (value, part) => {
709
+ return part === "query" ? encodePrettyQueryValue(value) : encodePathValue(value, part);
710
+ };
358
711
  const fill = (values, encoding = "pretty") => {
359
712
  const isStrict = encoding === "strict";
360
- const fillPlaceholders = (text, encode = toValueText) => {
713
+ const encodeQueryItem = isStrict ? encodeStrictValue : encodePrettyQueryValue;
714
+ const encodeName = isStrict ? encodeStrictValue : encodeQueryName;
715
+ let isMoved = false;
716
+ const fillQueryValue = (text, encodeItem, encodeFixedText) => {
717
+ return mapTemplate(text, (name) => encodeSlot(values[name], encodeItem), encodeFixedText);
718
+ };
719
+ const fillPlaceholders = (text, part) => {
720
+ const encodeItem = (item) => {
721
+ return isStrict ? encodeStrictValue(item) : encodePathValue(item, part);
722
+ };
361
723
  return text.replace(placeholderRegex, (_placeholder, name) => {
362
724
  const value = values[name];
363
- if (!isMultiSegment(name)) return encodeSlot(value, encode);
364
- if (isPlainObject(value)) return `/${encodeMapSegments(value, isStrict ? encodeStrictValue : encodePathValue)}`;
365
- return value.length > 0 ? `/${encode(value)}` : "";
725
+ if (reservedNames.includes(name) || fragmentReservedNames.includes(name)) {
726
+ const written = encodeReservedSlot(value, isStrict, part);
727
+ if (reservedNames.includes(name) && name !== restName && reservedEndRegex.test(written)) isMoved = true;
728
+ return written;
729
+ }
730
+ if (!isMultiSegment(name)) return encodeSlot(value, encodeItem);
731
+ if (isPlainObject(value)) return `/${toMapEntries(value).map(([entryName, item]) => {
732
+ return `${encodeItem(entryName)}=${encodeItem(item)}`;
733
+ }).join("/")}`;
734
+ return value.length > 0 ? `/${coerceArray(value).map(encodeItem).join("/")}` : "";
366
735
  });
367
736
  };
368
737
  const pairs = [];
@@ -371,37 +740,73 @@ const compileTemplate = (parsed, pathPatterns = {}, writtenPathPatterns = pathPa
371
740
  pairs.push(own.pair);
372
741
  continue;
373
742
  }
374
- const text = fillQueryValue(own.value, values, isStrict ? encodeStrictValue : encodeQueryValue);
743
+ const text = fillQueryValue(own.value, encodeQueryItem, encodeQueryText);
375
744
  pairs.push(appendValue(own.pair, text));
376
745
  }
746
+ let hasFlagSlash = false;
747
+ const encodeFlagValue = (value) => {
748
+ if (value.includes("/")) hasFlagSlash = true;
749
+ return encodeQueryItem(value).replaceAll("=", "%3D");
750
+ };
751
+ for (const { text } of nameFlags) pairs.push(toWrittenPair(fillQueryValue(text, encodeFlagValue, encodeQueryName)));
752
+ if (hasFlagSlash) return;
377
753
  for (const name of parsed.optionalNames) {
378
754
  const value = values[name];
379
755
  if (value === void 0) continue;
380
- const writtenName = isStrict ? encodeStrictValue(name) : encodeText(name);
381
- const writtenValue = encodeSlot(value, isStrict ? encodeStrictValue : encodeQueryValue);
756
+ const writtenName = encodeName(name);
757
+ const writtenValue = encodeSlot(value, encodeQueryItem);
382
758
  pairs.push(toPair(`${writtenName}=${writtenValue}`));
383
759
  }
384
- const filledHost = fillPlaceholders(host).toLowerCase();
385
- if (hostDelimiterRegex.test(filledHost)) return;
386
- const filledScheme = fillPlaceholders(scheme);
387
- const filledPath = fillPlaceholders(writtenPath, isStrict ? encodeStrict : encodePath);
388
- if (filledPath.split("/").some((segment) => dotSegmentRegex.test(segment))) return;
389
- const url = `${writeBase(`${filledScheme}://${filledHost}${filledPath}`, pairs)}${writeQuery(sortPairs(pairs))}`;
760
+ const passedName = parsed.passedName ?? "";
761
+ const passed = values[passedName];
762
+ if (passed !== void 0) {
763
+ const map = isPlainObject(passed) ? passed : { [passedName]: passed };
764
+ for (const [name, item] of toMapEntries(map)) {
765
+ if (isAnyOf(name, takenNames)) return;
766
+ const writtenName = encodeName(name);
767
+ const writtenValue = encodeQueryItem(item);
768
+ pairs.push(toWrittenPair(`${writtenName}=${writtenValue}`));
769
+ }
770
+ }
771
+ const fillOrigin = (text) => {
772
+ return text.replace(placeholderRegex, (_placeholder, name) => {
773
+ return encodeSlot(values[name], toValueText);
774
+ });
775
+ };
776
+ const givenHost = fillOrigin(host);
777
+ if (hostDelimiterRegex.test(givenHost)) return;
778
+ const filledHost = toAsciiHost(givenHost);
779
+ const filledScheme = fillOrigin(scheme).toLowerCase();
780
+ const filledPath = fillPlaceholders(writtenPath, "path");
781
+ const [ownPath] = filledPath.split(reservedEndRegex, 1);
782
+ if (isMoved || ownPath.split("/").some((segment) => dotSegmentRegex.test(segment))) return;
783
+ const base = writeBase(`${filledScheme}://${filledHost}${filledPath}`, pairs);
784
+ const filledFragment = writtenFragment === void 0 ? "" : `#${fillPlaceholders(writtenFragment, "fragment")}`;
785
+ const url = `${base}${writeQuery(orderPairs(pairs, values))}${filledFragment}`;
390
786
  const parsedUrl = parseUrl(url);
391
787
  if (!parsedUrl || !isHttpUrl(parsedUrl) || parsedUrl.host !== filledHost) return;
392
- if (parsedUrl.protocol !== `${filledScheme.toLowerCase()}:`) return;
788
+ if (parsedUrl.protocol !== `${filledScheme}:`) return;
393
789
  return url;
394
790
  };
395
791
  return {
396
- ...parsed,
397
792
  params,
793
+ nameFlags,
398
794
  readPathSource,
399
- rawPathSource: `${rawPathGuard}${rawPathSource}`,
795
+ rawPathSource: `${rawEndingGuard}${rawPathGuard}${rawPathSource}`,
400
796
  captureIn,
401
797
  getCaptured,
402
798
  read,
403
799
  getValues,
404
- fill
800
+ fill,
801
+ readFragment,
802
+ rawFragmentRegex,
803
+ readFlagName,
804
+ claimFlags,
805
+ orderPairs,
806
+ encodeValue,
807
+ encodeQueryText,
808
+ encodeQueryName,
809
+ toWrittenPair
405
810
  };
406
811
  };
407
- export { basePlaceholder, compileTemplate, decodePath, dotSegmentRegex, encodeLiteral, isMultiSegment, mapTemplate, openTailName, openTailSuffix, parseTemplate, placeholderRegex, schemePlaceholder, sharedPartMaxLength, splitPath, toBareName, toLengthGuard, toRegexSource, toSegments, toStrictPair, toValueText, trailingSlashRegex, writeBase };
812
+ export { basePlaceholder, compileTemplate, encodeLiteral, encodeParserText, encodeReservedSlot, isMultiSegment, isTypedValue, mapTemplate, openTailName, openTailSuffix, parseTemplate, placeholderRegex, sharedPartMaxLength, splitPath, toAsciiHost, toBareName, toRegexSource, toSlotText, toValueParts, toValueText };