@fedify/uri-template 2.4.5-dev.2462 → 2.4.6-dev.2628

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/README.md CHANGED
@@ -148,6 +148,32 @@ Features
148
148
  - Zero runtime dependencies
149
149
 
150
150
 
151
+ HTTP path compatibility
152
+ -----------------------
153
+
154
+ Some HTTP clients, including Mastodon, decode `%3A` to `:` in request paths.
155
+ Pass `{ allowUnencodedColon: true }` to `Router.route()` to accept literal
156
+ colons in variable values where expansion would produce `%3A`:
157
+
158
+ ~~~~ typescript
159
+ const router = new Router([["/users/{identifier}", "actor"]]);
160
+ router.route("/users/alice:work", { allowUnencodedColon: true });
161
+ // { name: "actor", template: "/users/{identifier}",
162
+ // values: { identifier: "alice:work" } }
163
+ ~~~~
164
+
165
+ Exact matches, including configured trailing-slash retries, take precedence
166
+ over colon-compatible matches. Literal template text still matches exactly,
167
+ and other percent-encoded characters keep their existing matching rules.
168
+ When a template uses colons to separate variables, a decoded colon in a value
169
+ can make the boundary ambiguous; matching follows the existing backtracking
170
+ order.
171
+
172
+ Fedify enables this option for incoming HTTP requests. URI generation and
173
+ `Context.parseUri()` retain their existing behavior. Standalone
174
+ `Template.match()` and `Router.route()` without the option also remain exact.
175
+
176
+
151
177
  Route variable constraints
152
178
  --------------------------
153
179
 
package/dist/mod.cjs CHANGED
@@ -631,18 +631,81 @@ function reportPrefixModifierError(varSpec, valueType, { report, strict }) {
631
631
  /**
632
632
  * Matches a URI against a parsed URI template and extracts variable bindings.
633
633
  *
634
- * The inverse of {@link expand}: given the token stream produced by parsing a
635
- * template and a concrete URI, recovers an {@link ExpandContext} such that
636
- * re-expanding the template with that context reproduces the original URI.
634
+ * Recovers variable bindings whose completed context satisfies the caller's
635
+ * roundtrip check. Literal tokens always match the original URI exactly.
637
636
  *
638
637
  * @param tokens The parsed template tokens to match against.
639
638
  * @param uri The concrete URI to decompose.
640
- * @param options Template options shared with the expansion side.
639
+ * @param accept The roundtrip check for a completed variable context.
640
+ * @param equivalent Exact or colon-compatible output comparison, also used by
641
+ * the caller's roundtrip check.
641
642
  * @returns The recovered variable context, or `null` if the URI does not match
642
643
  * the template under any interpretation.
643
644
  */
644
- function match(tokens, uri, options) {
645
- return matchTokens(tokens, uri, options, 0, 0, {});
645
+ function match(tokens, uri, accept, equivalent = (left, right) => left === right) {
646
+ if (!canExpandTo(tokens, uri, equivalent)) return null;
647
+ return matchTokens(tokens, uri, accept, 0, 0, {});
648
+ }
649
+ /**
650
+ * Checks necessary conditions on the whole output, without choosing expression
651
+ * boundaries or bindings. Individual expressions need not round-trip locally:
652
+ * repeated variables can compensate for different consumed lengths elsewhere.
653
+ */
654
+ function canExpandTo(tokens, uri, equivalent) {
655
+ const specs = /* @__PURE__ */ new Set();
656
+ const counts = /* @__PURE__ */ new Map();
657
+ let namedOrExploded = false;
658
+ let verbatimPercent = false;
659
+ const count = (text, delta) => {
660
+ for (let index = 0; index < text.length; index++) {
661
+ const char = text[index];
662
+ counts.set(char, (counts.get(char) ?? 0) + delta);
663
+ }
664
+ };
665
+ for (const token of tokens) if (token.kind === "literal") {
666
+ count(token.text, -1);
667
+ verbatimPercent ||= token.text.includes("%");
668
+ } else {
669
+ if (token.vars.some((variable) => variable.prefix != null)) return true;
670
+ const spec = operatorSpecs[token.operator];
671
+ specs.add(spec);
672
+ namedOrExploded ||= spec.named || token.vars.some((variable) => variable.explode);
673
+ verbatimPercent ||= token.vars.some((variable) => variable.name.includes("%"));
674
+ }
675
+ count(uri, 1);
676
+ for (const [char, difference] of counts) {
677
+ if (difference === 0 || char === "%" || char === "," || char === "=" && namedOrExploded) continue;
678
+ if ([...specs].some((spec) => spec.first.includes(char) || spec.sep.includes(char) || equivalent(encodeValue(spec.allowReserved)(char), char))) continue;
679
+ return false;
680
+ }
681
+ return verbatimPercent || hasPossiblePercentEncoding(uri, [...specs].some((spec) => spec.allowReserved));
682
+ }
683
+ /**
684
+ * With no percent signs supplied by literals or encoded variable names, every
685
+ * percent sign must come from a value encoder. Reserved expansion preserves
686
+ * triplets; other operators emit canonical UTF-8. Folding %3A only splits runs
687
+ * between complete code points, so canonicality also holds in colon mode.
688
+ */
689
+ function hasPossiblePercentEncoding(uri, allowReserved) {
690
+ for (let index = 0; index < uri.length;) {
691
+ if (uri[index] !== "%") {
692
+ index++;
693
+ continue;
694
+ }
695
+ if (!isPctEncodedAt(uri, index)) return false;
696
+ const start = index;
697
+ do
698
+ index += 3;
699
+ while (isPctEncodedAt(uri, index));
700
+ if (allowReserved) continue;
701
+ const run = uri.slice(start, index);
702
+ try {
703
+ if (encodeValue(false)(decodeURIComponent(run)) !== run) return false;
704
+ } catch {
705
+ return false;
706
+ }
707
+ }
708
+ return true;
646
709
  }
647
710
  /**
648
711
  * Walks the token stream and the URI in lockstep, backtracking over every
@@ -650,26 +713,25 @@ function match(tokens, uri, options) {
650
713
  *
651
714
  * Literal tokens advance deterministically; expression tokens fan out across
652
715
  * all viable end positions and value interpretations. When the token stream is
653
- * exhausted, the accumulated bindings are accepted only if re-expanding the
654
- * template with them yields the original URI exactly — this is what filters
655
- * out the spurious interpretations that the permissive parsing stage admits.
716
+ * exhausted, the accumulated bindings must pass the caller's roundtrip check,
717
+ * filtering out spurious interpretations from the permissive parsing stage.
656
718
  *
657
719
  * @returns The first surviving context, or `null` if every branch fails.
658
720
  */
659
- function matchTokens(tokens, uri, options, tokenIndex, uriIndex, bindings) {
721
+ function matchTokens(tokens, uri, accept, tokenIndex, uriIndex, bindings) {
660
722
  if (tokenIndex >= tokens.length) {
661
723
  if (uriIndex !== uri.length) return null;
662
724
  const context = toExpandContext(bindings);
663
- return expand(tokens, context, options) === uri ? context : null;
725
+ return accept(context) ? context : null;
664
726
  }
665
727
  const token = tokens[tokenIndex];
666
- if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, options, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
728
+ if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, accept, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
667
729
  for (const end of expressionEnds(tokens, uri, tokenIndex, uriIndex)) {
668
730
  const expression = uri.slice(uriIndex, end);
669
731
  for (const expressionBindings of matchExpression(token.vars, token.operator, expression)) {
670
732
  const merged = mergeBindings(bindings, expressionBindings);
671
733
  if (merged == null) continue;
672
- const result = matchTokens(tokens, uri, options, tokenIndex + 1, end, merged);
734
+ const result = matchTokens(tokens, uri, accept, tokenIndex + 1, end, merged);
673
735
  if (result != null) return result;
674
736
  }
675
737
  }
@@ -1242,7 +1304,7 @@ var Template = class Template {
1242
1304
  * Matches a URI against this template, returning the variable context if the
1243
1305
  * URI matches or `null` if it does not.
1244
1306
  */
1245
- match = (uri) => match(this.#tokens, uri, this.#fullOptions);
1307
+ match = (uri) => match(this.#tokens, uri, (context) => this.expand(context) === uri);
1246
1308
  toString = () => this.uriTemplate;
1247
1309
  };
1248
1310
  const freezeTokens = (tokens) => Object.freeze(tokens.map(freezeToken));
@@ -1586,7 +1648,7 @@ var StateTrie = class {
1586
1648
  insert = (entry) => fold((node, segment) => isLiteral(segment) ? node.insertLiteral(segment.text) : node.childOrInsertExpression(segment), this.#root, compileSegments(entry.tokens)).insert(entry);
1587
1649
  remove = (entry) => foldWhileDefined((node, segment) => isLiteral(segment) ? node.findLiteral(segment.text) : node.childExpression(segment.key), this.#root, compileSegments(entry.tokens)).remove(entry);
1588
1650
  *candidates(path) {
1589
- yield* stateEntries(this.#root, path, 0);
1651
+ yield* stateEntries(this.#root, path, 0, /* @__PURE__ */ new Map());
1590
1652
  }
1591
1653
  };
1592
1654
  function* compileSegments(tokens) {
@@ -1603,16 +1665,21 @@ const expressionKey = ({ operator, vars: [{ explode, prefix }] }) => [
1603
1665
  explode ? "*" : "",
1604
1666
  prefix ?? ""
1605
1667
  ].join("\0");
1606
- function* stateEntries(node, path, index) {
1668
+ function* stateEntries(node, path, index, visited) {
1669
+ let indexes = visited.get(node);
1670
+ if (indexes == null) visited.set(node, indexes = /* @__PURE__ */ new Set());
1671
+ if (indexes.has(index)) return;
1672
+ indexes.add(index);
1607
1673
  if (index === path.length) yield* node.entries;
1608
- for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length);
1609
- for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index);
1674
+ for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length, visited);
1675
+ for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index, visited);
1610
1676
  }
1611
- function* expressionEntries(edge, path, index) {
1677
+ function* expressionEntries(edge, path, index, visited) {
1612
1678
  for (const end of expressionEndIndexes(edge.node, path, index)) {
1679
+ if (visited.get(edge.node)?.has(end)) continue;
1613
1680
  const expression = path.slice(index, end);
1614
1681
  if (!matchesExpressionShape(edge.operator, expression)) continue;
1615
- yield* stateEntries(edge.node, path, end);
1682
+ yield* stateEntries(edge.node, path, end, visited);
1616
1683
  }
1617
1684
  }
1618
1685
  function* expressionEndIndexes(node, path, index) {
@@ -1771,13 +1838,19 @@ var Router = class Router {
1771
1838
  /**
1772
1839
  * Resolves a path name and values from a URI, if any match.
1773
1840
  * @param url The URI to resolve.
1841
+ * @param options Options for this lookup only.
1774
1842
  * @returns The name of the path and its values, if any match. Otherwise,
1775
1843
  * `null`.
1776
1844
  */
1777
- route = (url) => this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
1778
- #route(url) {
1845
+ route = (url, options = {}) => {
1846
+ const strict = this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
1847
+ if (strict != null || !options.allowUnencodedColon || !url.includes(":")) return strict;
1848
+ return this.#route(url, true) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url), true) : null);
1849
+ };
1850
+ #route(url, allowUnencodedColon = false) {
1779
1851
  for (const entry of this.#trie.candidates(url)) {
1780
- const context = entry.pattern.template.match(url);
1852
+ const template = entry.pattern.template;
1853
+ const context = allowUnencodedColon ? match(template.tokens, url, (values) => equalWithUnencodedColon(template.expand(values), url), equalWithUnencodedColon) : template.match(url);
1781
1854
  if (context == null) continue;
1782
1855
  const values = resolveValues(context, entry);
1783
1856
  if (values == null) continue;
@@ -1810,6 +1883,7 @@ var Router = class Router {
1810
1883
  entry.options
1811
1884
  ]);
1812
1885
  };
1886
+ const equalWithUnencodedColon = (left, right) => left.replaceAll("%3A", ":") === right.replaceAll("%3A", ":");
1813
1887
  const createRouteEntry = ({ index, name, pattern, options }) => ({
1814
1888
  index,
1815
1889
  name,
package/dist/mod.d.cts CHANGED
@@ -517,6 +517,21 @@ interface RouterOptions {
517
517
  */
518
518
  trailingSlashInsensitive?: boolean;
519
519
  }
520
+ /**
521
+ * Options for an individual {@link Router.route} call.
522
+ * @since 2.3.15
523
+ */
524
+ interface RouterRouteOptions {
525
+ /**
526
+ * Accepts literal colons in variable values where expansion produces `%3A`.
527
+ * Exact matches, including trailing-slash retries, always take precedence.
528
+ * Literal template text remains exact. Defaults to `false`.
529
+ *
530
+ * Intended for inbound HTTP compatibility; identity lookups should keep
531
+ * the default strict matching.
532
+ */
533
+ readonly allowUnencodedColon?: boolean;
534
+ }
520
535
  /**
521
536
  * Fully-resolved per-variable matching constraint. Every template variable
522
537
  * is constrained even when it is not listed in {@link RouteOptions.variables};
@@ -753,10 +768,11 @@ declare class Router {
753
768
  /**
754
769
  * Resolves a path name and values from a URI, if any match.
755
770
  * @param url The URI to resolve.
771
+ * @param options Options for this lookup only.
756
772
  * @returns The name of the path and its values, if any match. Otherwise,
757
773
  * `null`.
758
774
  */
759
- route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path) => RouterRouteResult<TConstraints> | null;
775
+ route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path, options?: RouterRouteOptions) => RouterRouteResult<TConstraints> | null;
760
776
  /**
761
777
  * Constructs a URL/path from a path name and values.
762
778
  * @param name The name of the path.
@@ -792,4 +808,4 @@ declare const isExpression: <T extends {
792
808
  declare function isPath(path: string): path is Path;
793
809
  declare function assertPath(path: string): asserts path is Path;
794
810
  //#endregion
795
- export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
811
+ export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteOptions, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
package/dist/mod.d.ts CHANGED
@@ -517,6 +517,21 @@ interface RouterOptions {
517
517
  */
518
518
  trailingSlashInsensitive?: boolean;
519
519
  }
520
+ /**
521
+ * Options for an individual {@link Router.route} call.
522
+ * @since 2.3.15
523
+ */
524
+ interface RouterRouteOptions {
525
+ /**
526
+ * Accepts literal colons in variable values where expansion produces `%3A`.
527
+ * Exact matches, including trailing-slash retries, always take precedence.
528
+ * Literal template text remains exact. Defaults to `false`.
529
+ *
530
+ * Intended for inbound HTTP compatibility; identity lookups should keep
531
+ * the default strict matching.
532
+ */
533
+ readonly allowUnencodedColon?: boolean;
534
+ }
520
535
  /**
521
536
  * Fully-resolved per-variable matching constraint. Every template variable
522
537
  * is constrained even when it is not listed in {@link RouteOptions.variables};
@@ -753,10 +768,11 @@ declare class Router {
753
768
  /**
754
769
  * Resolves a path name and values from a URI, if any match.
755
770
  * @param url The URI to resolve.
771
+ * @param options Options for this lookup only.
756
772
  * @returns The name of the path and its values, if any match. Otherwise,
757
773
  * `null`.
758
774
  */
759
- route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path) => RouterRouteResult<TConstraints> | null;
775
+ route: <TConstraints extends Record<string, MinimalConstraint> = Record<never, never>>(url: Path, options?: RouterRouteOptions) => RouterRouteResult<TConstraints> | null;
760
776
  /**
761
777
  * Constructs a URL/path from a path name and values.
762
778
  * @param name The name of the path.
@@ -792,4 +808,4 @@ declare const isExpression: <T extends {
792
808
  declare function isPath(path: string): path is Path;
793
809
  declare function assertPath(path: string): asserts path is Path;
794
810
  //#endregion
795
- export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
811
+ export { type AssociativeValue, ConflictingVarSpecError, type ConstraintValue, DisallowedOperatorError, DisallowedVarSpecModifierError, DuplicateRouteVariableError, EmptyExpressionError, EmptyVarNameError, type ExpandContext, type ExpandValue, InvalidLiteralError, InvalidPrefixError, InvalidVarNameError, InvalidVarSpecError, NestedOpeningBraceError, type Operator, type Path, PrefixModifierNotApplicableError, type PrimitiveValue, type Reporter, ReservedOperatorError, type RouteOptions, RouteTemplateOptionsNotMatchedError, RouteTemplatePathError, type RouteValues, Router, RouterError, type RouterOptions, type RouterPathPattern, type RouterRoute, type RouterRouteOptions, type RouterRouteResult, StrayClosingBraceError, Template, TemplateExpansionError, type TemplateOptions, TemplateParseError, type Token, TrailingCommaError, UnclosedExpressionError, UnexpectedCharacterError, UnknownOperatorError, type VarSpec, type VariableConstraint, assertPath, isExpression, isPath };
package/dist/mod.js CHANGED
@@ -630,18 +630,81 @@ function reportPrefixModifierError(varSpec, valueType, { report, strict }) {
630
630
  /**
631
631
  * Matches a URI against a parsed URI template and extracts variable bindings.
632
632
  *
633
- * The inverse of {@link expand}: given the token stream produced by parsing a
634
- * template and a concrete URI, recovers an {@link ExpandContext} such that
635
- * re-expanding the template with that context reproduces the original URI.
633
+ * Recovers variable bindings whose completed context satisfies the caller's
634
+ * roundtrip check. Literal tokens always match the original URI exactly.
636
635
  *
637
636
  * @param tokens The parsed template tokens to match against.
638
637
  * @param uri The concrete URI to decompose.
639
- * @param options Template options shared with the expansion side.
638
+ * @param accept The roundtrip check for a completed variable context.
639
+ * @param equivalent Exact or colon-compatible output comparison, also used by
640
+ * the caller's roundtrip check.
640
641
  * @returns The recovered variable context, or `null` if the URI does not match
641
642
  * the template under any interpretation.
642
643
  */
643
- function match(tokens, uri, options) {
644
- return matchTokens(tokens, uri, options, 0, 0, {});
644
+ function match(tokens, uri, accept, equivalent = (left, right) => left === right) {
645
+ if (!canExpandTo(tokens, uri, equivalent)) return null;
646
+ return matchTokens(tokens, uri, accept, 0, 0, {});
647
+ }
648
+ /**
649
+ * Checks necessary conditions on the whole output, without choosing expression
650
+ * boundaries or bindings. Individual expressions need not round-trip locally:
651
+ * repeated variables can compensate for different consumed lengths elsewhere.
652
+ */
653
+ function canExpandTo(tokens, uri, equivalent) {
654
+ const specs = /* @__PURE__ */ new Set();
655
+ const counts = /* @__PURE__ */ new Map();
656
+ let namedOrExploded = false;
657
+ let verbatimPercent = false;
658
+ const count = (text, delta) => {
659
+ for (let index = 0; index < text.length; index++) {
660
+ const char = text[index];
661
+ counts.set(char, (counts.get(char) ?? 0) + delta);
662
+ }
663
+ };
664
+ for (const token of tokens) if (token.kind === "literal") {
665
+ count(token.text, -1);
666
+ verbatimPercent ||= token.text.includes("%");
667
+ } else {
668
+ if (token.vars.some((variable) => variable.prefix != null)) return true;
669
+ const spec = operatorSpecs[token.operator];
670
+ specs.add(spec);
671
+ namedOrExploded ||= spec.named || token.vars.some((variable) => variable.explode);
672
+ verbatimPercent ||= token.vars.some((variable) => variable.name.includes("%"));
673
+ }
674
+ count(uri, 1);
675
+ for (const [char, difference] of counts) {
676
+ if (difference === 0 || char === "%" || char === "," || char === "=" && namedOrExploded) continue;
677
+ if ([...specs].some((spec) => spec.first.includes(char) || spec.sep.includes(char) || equivalent(encodeValue(spec.allowReserved)(char), char))) continue;
678
+ return false;
679
+ }
680
+ return verbatimPercent || hasPossiblePercentEncoding(uri, [...specs].some((spec) => spec.allowReserved));
681
+ }
682
+ /**
683
+ * With no percent signs supplied by literals or encoded variable names, every
684
+ * percent sign must come from a value encoder. Reserved expansion preserves
685
+ * triplets; other operators emit canonical UTF-8. Folding %3A only splits runs
686
+ * between complete code points, so canonicality also holds in colon mode.
687
+ */
688
+ function hasPossiblePercentEncoding(uri, allowReserved) {
689
+ for (let index = 0; index < uri.length;) {
690
+ if (uri[index] !== "%") {
691
+ index++;
692
+ continue;
693
+ }
694
+ if (!isPctEncodedAt(uri, index)) return false;
695
+ const start = index;
696
+ do
697
+ index += 3;
698
+ while (isPctEncodedAt(uri, index));
699
+ if (allowReserved) continue;
700
+ const run = uri.slice(start, index);
701
+ try {
702
+ if (encodeValue(false)(decodeURIComponent(run)) !== run) return false;
703
+ } catch {
704
+ return false;
705
+ }
706
+ }
707
+ return true;
645
708
  }
646
709
  /**
647
710
  * Walks the token stream and the URI in lockstep, backtracking over every
@@ -649,26 +712,25 @@ function match(tokens, uri, options) {
649
712
  *
650
713
  * Literal tokens advance deterministically; expression tokens fan out across
651
714
  * all viable end positions and value interpretations. When the token stream is
652
- * exhausted, the accumulated bindings are accepted only if re-expanding the
653
- * template with them yields the original URI exactly — this is what filters
654
- * out the spurious interpretations that the permissive parsing stage admits.
715
+ * exhausted, the accumulated bindings must pass the caller's roundtrip check,
716
+ * filtering out spurious interpretations from the permissive parsing stage.
655
717
  *
656
718
  * @returns The first surviving context, or `null` if every branch fails.
657
719
  */
658
- function matchTokens(tokens, uri, options, tokenIndex, uriIndex, bindings) {
720
+ function matchTokens(tokens, uri, accept, tokenIndex, uriIndex, bindings) {
659
721
  if (tokenIndex >= tokens.length) {
660
722
  if (uriIndex !== uri.length) return null;
661
723
  const context = toExpandContext(bindings);
662
- return expand(tokens, context, options) === uri ? context : null;
724
+ return accept(context) ? context : null;
663
725
  }
664
726
  const token = tokens[tokenIndex];
665
- if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, options, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
727
+ if (token.kind === "literal") return uri.startsWith(token.text, uriIndex) ? matchTokens(tokens, uri, accept, tokenIndex + 1, uriIndex + token.text.length, bindings) : null;
666
728
  for (const end of expressionEnds(tokens, uri, tokenIndex, uriIndex)) {
667
729
  const expression = uri.slice(uriIndex, end);
668
730
  for (const expressionBindings of matchExpression(token.vars, token.operator, expression)) {
669
731
  const merged = mergeBindings(bindings, expressionBindings);
670
732
  if (merged == null) continue;
671
- const result = matchTokens(tokens, uri, options, tokenIndex + 1, end, merged);
733
+ const result = matchTokens(tokens, uri, accept, tokenIndex + 1, end, merged);
672
734
  if (result != null) return result;
673
735
  }
674
736
  }
@@ -1241,7 +1303,7 @@ var Template = class Template {
1241
1303
  * Matches a URI against this template, returning the variable context if the
1242
1304
  * URI matches or `null` if it does not.
1243
1305
  */
1244
- match = (uri) => match(this.#tokens, uri, this.#fullOptions);
1306
+ match = (uri) => match(this.#tokens, uri, (context) => this.expand(context) === uri);
1245
1307
  toString = () => this.uriTemplate;
1246
1308
  };
1247
1309
  const freezeTokens = (tokens) => Object.freeze(tokens.map(freezeToken));
@@ -1585,7 +1647,7 @@ var StateTrie = class {
1585
1647
  insert = (entry) => fold((node, segment) => isLiteral(segment) ? node.insertLiteral(segment.text) : node.childOrInsertExpression(segment), this.#root, compileSegments(entry.tokens)).insert(entry);
1586
1648
  remove = (entry) => foldWhileDefined((node, segment) => isLiteral(segment) ? node.findLiteral(segment.text) : node.childExpression(segment.key), this.#root, compileSegments(entry.tokens)).remove(entry);
1587
1649
  *candidates(path) {
1588
- yield* stateEntries(this.#root, path, 0);
1650
+ yield* stateEntries(this.#root, path, 0, /* @__PURE__ */ new Map());
1589
1651
  }
1590
1652
  };
1591
1653
  function* compileSegments(tokens) {
@@ -1602,16 +1664,21 @@ const expressionKey = ({ operator, vars: [{ explode, prefix }] }) => [
1602
1664
  explode ? "*" : "",
1603
1665
  prefix ?? ""
1604
1666
  ].join("\0");
1605
- function* stateEntries(node, path, index) {
1667
+ function* stateEntries(node, path, index, visited) {
1668
+ let indexes = visited.get(node);
1669
+ if (indexes == null) visited.set(node, indexes = /* @__PURE__ */ new Set());
1670
+ if (indexes.has(index)) return;
1671
+ indexes.add(index);
1606
1672
  if (index === path.length) yield* node.entries;
1607
- for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length);
1608
- for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index);
1673
+ for (const edge of node.literalEdges) if (path.startsWith(edge.text, index)) yield* stateEntries(edge.node, path, index + edge.text.length, visited);
1674
+ for (const edge of node.expressionEdges.values()) yield* expressionEntries(edge, path, index, visited);
1609
1675
  }
1610
- function* expressionEntries(edge, path, index) {
1676
+ function* expressionEntries(edge, path, index, visited) {
1611
1677
  for (const end of expressionEndIndexes(edge.node, path, index)) {
1678
+ if (visited.get(edge.node)?.has(end)) continue;
1612
1679
  const expression = path.slice(index, end);
1613
1680
  if (!matchesExpressionShape(edge.operator, expression)) continue;
1614
- yield* stateEntries(edge.node, path, end);
1681
+ yield* stateEntries(edge.node, path, end, visited);
1615
1682
  }
1616
1683
  }
1617
1684
  function* expressionEndIndexes(node, path, index) {
@@ -1770,13 +1837,19 @@ var Router = class Router {
1770
1837
  /**
1771
1838
  * Resolves a path name and values from a URI, if any match.
1772
1839
  * @param url The URI to resolve.
1840
+ * @param options Options for this lookup only.
1773
1841
  * @returns The name of the path and its values, if any match. Otherwise,
1774
1842
  * `null`.
1775
1843
  */
1776
- route = (url) => this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
1777
- #route(url) {
1844
+ route = (url, options = {}) => {
1845
+ const strict = this.#route(url) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url)) : null);
1846
+ if (strict != null || !options.allowUnencodedColon || !url.includes(":")) return strict;
1847
+ return this.#route(url, true) ?? (this.trailingSlashInsensitive ? this.#route(toggleTrailingSlash(url), true) : null);
1848
+ };
1849
+ #route(url, allowUnencodedColon = false) {
1778
1850
  for (const entry of this.#trie.candidates(url)) {
1779
- const context = entry.pattern.template.match(url);
1851
+ const template = entry.pattern.template;
1852
+ const context = allowUnencodedColon ? match(template.tokens, url, (values) => equalWithUnencodedColon(template.expand(values), url), equalWithUnencodedColon) : template.match(url);
1780
1853
  if (context == null) continue;
1781
1854
  const values = resolveValues(context, entry);
1782
1855
  if (values == null) continue;
@@ -1809,6 +1882,7 @@ var Router = class Router {
1809
1882
  entry.options
1810
1883
  ]);
1811
1884
  };
1885
+ const equalWithUnencodedColon = (left, right) => left.replaceAll("%3A", ":") === right.replaceAll("%3A", ":");
1812
1886
  const createRouteEntry = ({ index, name, pattern, options }) => ({
1813
1887
  index,
1814
1888
  name,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/uri-template",
3
- "version": "2.4.5-dev.2462+46a3f2c5",
3
+ "version": "2.4.6-dev.2628+2a78382f",
4
4
  "homepage": "https://fedify.dev/",
5
5
  "repository": {
6
6
  "type": "git",