@fedify/vocab-runtime 2.4.0-pr.936.41 → 2.4.1

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.
Files changed (152) hide show
  1. package/deno.json +4 -2
  2. package/dist/{tests/docloader-Ck8bcBir.mjs → contexts-B09jb9Pi.cjs} +173 -274
  3. package/dist/{tests/docloader-S_gQZ2tt.cjs → contexts-DWrj4AGR.js} +169 -293
  4. package/dist/{docloader-C_dir7Xb.d.ts → docloader-BMHljyYb.d.cts} +68 -2
  5. package/dist/{docloader-D2DTRiyA.d.cts → docloader-BMHljyYb.d.ts} +68 -2
  6. package/dist/internal/jsonld-cache.cjs +70 -1
  7. package/dist/internal/jsonld-cache.d.cts +35 -2
  8. package/dist/internal/jsonld-cache.d.ts +35 -2
  9. package/dist/internal/jsonld-cache.js +67 -2
  10. package/dist/internal/portable-dereference.cjs +721 -0
  11. package/dist/internal/portable-dereference.d.cts +349 -0
  12. package/dist/internal/portable-dereference.d.ts +349 -0
  13. package/dist/internal/portable-dereference.js +702 -0
  14. package/dist/internal/signed-representation.cjs +378 -0
  15. package/dist/internal/signed-representation.d.cts +144 -0
  16. package/dist/internal/signed-representation.d.ts +144 -0
  17. package/dist/internal/signed-representation.js +371 -0
  18. package/dist/jsonld.cjs +2 -2
  19. package/dist/mod.cjs +762 -4529
  20. package/dist/mod.d.cts +427 -9
  21. package/dist/mod.d.ts +427 -10
  22. package/dist/mod.js +742 -4524
  23. package/dist/portable-6Aj-7dZJ.d.cts +160 -0
  24. package/dist/portable-nkTiqH0w.d.ts +160 -0
  25. package/dist/tests/body-DpC9p-iG.mjs +130 -0
  26. package/dist/tests/body-cKLBprYm.cjs +153 -0
  27. package/dist/tests/body.test.cjs +89 -0
  28. package/dist/tests/body.test.d.cts +1 -0
  29. package/dist/tests/body.test.d.mts +1 -0
  30. package/dist/tests/body.test.mjs +90 -0
  31. package/dist/tests/contexts-C9Lj11SC.cjs +4533 -0
  32. package/dist/tests/contexts-duRA_dDC.mjs +4522 -0
  33. package/dist/tests/decimal.test.cjs +9 -7
  34. package/dist/tests/decimal.test.mjs +9 -6
  35. package/dist/tests/digest-3FeH2Y-Q.cjs +176 -0
  36. package/dist/tests/digest-COC7xDiQ.mjs +141 -0
  37. package/dist/tests/digest.test.cjs +102 -0
  38. package/dist/tests/digest.test.d.cts +1 -0
  39. package/dist/tests/digest.test.d.mts +1 -0
  40. package/dist/tests/digest.test.mjs +103 -0
  41. package/dist/tests/docloader-DyZ1JGIl.cjs +398 -0
  42. package/dist/tests/docloader-tUmMeXjU.mjs +375 -0
  43. package/dist/tests/docloader.test.cjs +816 -39
  44. package/dist/tests/docloader.test.mjs +810 -34
  45. package/dist/tests/internal/multicodec.test.cjs +2 -3
  46. package/dist/tests/internal/multicodec.test.mjs +2 -2
  47. package/dist/tests/internal/portable-dereference.test.cjs +172 -0
  48. package/dist/tests/internal/portable-dereference.test.d.cts +1 -0
  49. package/dist/tests/internal/portable-dereference.test.d.mts +1 -0
  50. package/dist/tests/internal/portable-dereference.test.mjs +173 -0
  51. package/dist/tests/jsonld-CmDhHNTx.cjs +12 -0
  52. package/dist/tests/jsonld-DweIJ07b.mjs +5 -0
  53. package/dist/tests/jsonld-cache-BEXiiM-V.cjs +386 -0
  54. package/dist/tests/jsonld-cache-DFnWsLuZ.mjs +339 -0
  55. package/dist/tests/jsonld-cache.test.cjs +102 -298
  56. package/dist/tests/jsonld-cache.test.mjs +95 -289
  57. package/dist/tests/{key-_wXwomh_.cjs → key-C-AYkdJJ.cjs} +11 -4
  58. package/dist/tests/{key-CDGDH_vC.mjs → key-C2Db_TAJ.mjs} +11 -3
  59. package/dist/tests/key.test.cjs +6 -5
  60. package/dist/tests/key.test.mjs +6 -4
  61. package/dist/tests/{langstr-Di5AvKpB.mjs → langstr-DYRmJqFn.mjs} +5 -2
  62. package/dist/tests/{langstr-CbAxaeEZ.cjs → langstr-_PqsL1ae.cjs} +5 -2
  63. package/dist/tests/langstr.test.cjs +11 -4
  64. package/dist/tests/langstr.test.mjs +9 -2
  65. package/dist/tests/langtag-CUppHs_s.mjs +45 -0
  66. package/dist/tests/langtag-Czjvxfzx.cjs +50 -0
  67. package/dist/tests/langtag.test.cjs +45 -0
  68. package/dist/tests/langtag.test.d.cts +1 -0
  69. package/dist/tests/langtag.test.d.mts +1 -0
  70. package/dist/tests/langtag.test.mjs +46 -0
  71. package/dist/tests/link.test.cjs +2 -3
  72. package/dist/tests/link.test.mjs +2 -2
  73. package/dist/tests/multibase/multibase.test.cjs +8 -9
  74. package/dist/tests/multibase/multibase.test.mjs +6 -6
  75. package/dist/tests/{multibase-Bz_UUDtL.cjs → multibase-B5Mea7Ip.cjs} +19 -2
  76. package/dist/tests/{multibase-B4bvakyA.mjs → multibase-BPnF_L4e.mjs} +12 -1
  77. package/dist/tests/portable-dereference-DmTYDy2p.mjs +250 -0
  78. package/dist/tests/portable-dereference-qTLMqe2_.cjs +279 -0
  79. package/dist/tests/portable-media-5p8azal0.cjs +153 -0
  80. package/dist/tests/portable-media-B_lt9MMA.mjs +148 -0
  81. package/dist/tests/portable-media.test.cjs +222 -0
  82. package/dist/tests/portable-media.test.d.cts +1 -0
  83. package/dist/tests/portable-media.test.d.mts +1 -0
  84. package/dist/tests/portable-media.test.mjs +223 -0
  85. package/dist/tests/portable-workers.test.cjs +36 -0
  86. package/dist/tests/portable-workers.test.d.cts +2 -0
  87. package/dist/tests/portable-workers.test.d.mts +2 -0
  88. package/dist/tests/portable-workers.test.mjs +35 -0
  89. package/dist/tests/{request-uk51rkhO.cjs → request-BgjA9wyl.cjs} +10 -4
  90. package/dist/tests/{request-C8CaGwtt.mjs → request-DodZNukP.mjs} +8 -2
  91. package/dist/tests/request.test.cjs +7 -4
  92. package/dist/tests/request.test.mjs +5 -2
  93. package/dist/tests/signed-representation.test.cjs +588 -0
  94. package/dist/tests/signed-representation.test.d.cts +1 -0
  95. package/dist/tests/signed-representation.test.d.mts +1 -0
  96. package/dist/tests/signed-representation.test.mjs +589 -0
  97. package/dist/tests/temporal.test.cjs +1 -2
  98. package/dist/tests/temporal.test.mjs +1 -1
  99. package/dist/tests/url-BNakuZ8k.cjs +998 -0
  100. package/dist/tests/url-DMxmp7ZG.mjs +859 -0
  101. package/dist/tests/url.test.cjs +489 -6
  102. package/dist/tests/url.test.mjs +489 -5
  103. package/dist/url-DrGTR8yv.cjs +993 -0
  104. package/dist/url-Dzyp-NsC.js +860 -0
  105. package/package.json +27 -4
  106. package/scripts/test-bun.mjs +17 -0
  107. package/src/body.test.ts +125 -0
  108. package/src/body.ts +152 -0
  109. package/src/contexts/cid-v1.json +114 -0
  110. package/src/contexts/fep-22cd.json +21 -0
  111. package/src/contexts/fep-6757.json +12 -0
  112. package/src/contexts/joinmastodon.json +1 -1
  113. package/src/contexts/miscellany.json +17 -0
  114. package/src/contexts.ts +47 -1
  115. package/src/digest.test.ts +220 -0
  116. package/src/digest.ts +229 -0
  117. package/src/docloader.test.ts +1066 -27
  118. package/src/docloader.ts +322 -105
  119. package/src/internal/jsonld-cache.ts +97 -1
  120. package/src/internal/portable-dereference.test.ts +254 -0
  121. package/src/internal/portable-dereference.ts +1000 -0
  122. package/src/internal/signed-representation.ts +565 -0
  123. package/src/jsonld-cache.test.ts +89 -0
  124. package/src/key.test.ts +9 -0
  125. package/src/key.ts +11 -1
  126. package/src/langstr.test.ts +18 -1
  127. package/src/langstr.ts +6 -2
  128. package/src/langtag.test.ts +53 -0
  129. package/src/langtag.ts +76 -0
  130. package/src/mod.ts +29 -0
  131. package/src/multibase/multibase.test.ts +5 -5
  132. package/src/portable-media.test.ts +293 -0
  133. package/src/portable-media.ts +264 -0
  134. package/src/portable-workers.test.ts +81 -0
  135. package/src/portable.ts +180 -0
  136. package/src/preprocessor.ts +7 -0
  137. package/src/request.test.ts +10 -1
  138. package/src/request.ts +9 -1
  139. package/src/signed-representation.test.ts +338 -0
  140. package/src/url.test.ts +823 -3
  141. package/src/url.ts +700 -23
  142. package/tsdown.config.ts +2 -0
  143. package/dist/tests/url-CsOV_B_P.cjs +0 -482
  144. package/dist/tests/url-Du7RQQgP.mjs +0 -392
  145. package/dist/url-DD4F0ULf.cjs +0 -483
  146. package/dist/url-DGVbSVVi.js +0 -393
  147. /package/dist/{chunk-M78iaK0I.cjs → rolldown-runtime-B7lfambq.cjs} +0 -0
  148. /package/dist/tests/{link-NUUWCdnK.mjs → link-Cevmc87v.mjs} +0 -0
  149. /package/dist/tests/{link-FguCydMA.cjs → link-DlKm8bEr.cjs} +0 -0
  150. /package/dist/tests/{multicodec-CxGVGa91.cjs → multicodec-CLRPeW4N.cjs} +0 -0
  151. /package/dist/tests/{multicodec-CyFp54fI.mjs → multicodec-CRIj_05H.mjs} +0 -0
  152. /package/dist/tests/{chunk-C2EiDwsr.cjs → rolldown-runtime-emK7D4bc.cjs} +0 -0
@@ -0,0 +1,860 @@
1
+
2
+ import dns from "node:dns/promises";
3
+ import { isIP } from "node:net";
4
+ //#region src/url.ts
5
+ var UrlError = class extends Error {
6
+ /**
7
+ * The failure category. Defaults to `"disallowed"`.
8
+ * `"dns"` includes lookup errors and results with no usable IP addresses.
9
+ * @since 2.0.29
10
+ */
11
+ reason;
12
+ constructor(message, options) {
13
+ super(message, options);
14
+ this.name = "UrlError";
15
+ this.reason = options?.reason ?? "disallowed";
16
+ }
17
+ };
18
+ const PORTABLE_IRI_PATTERN = /^(ap|ap\+ef61):\/\/([^/?#]*)([^?#]*)(\?[^#]*)?(#.*)?$/i;
19
+ const INVALID_PERCENT_ENCODING_PATTERN = /%(?![0-9A-Fa-f]{2})/;
20
+ const PERCENT_ENCODING_PATTERN = /%[0-9A-Fa-f]{2}/g;
21
+ const DID_SCHEME_PATTERN = /^did:/i;
22
+ const DID_PATTERN = /^did:[a-z0-9]+:[-A-Za-z0-9._%]+(?::[-A-Za-z0-9._%]+)*$/i;
23
+ const DOT_SEGMENT_PATTERN = /(?:^|\/)(?:\.|%2e){1,2}(?=\/|$)/i;
24
+ function prepareUrlInput(iri) {
25
+ let prepared = iri.replace(/[\t\n\r]/g, "");
26
+ while (prepared.length > 0 && prepared.charCodeAt(0) <= 32) prepared = prepared.slice(1);
27
+ while (prepared.length > 0 && prepared.charCodeAt(prepared.length - 1) <= 32) prepared = prepared.slice(0, -1);
28
+ return prepared;
29
+ }
30
+ function assertPortablePathCanBeParsed(iri) {
31
+ const match = prepareUrlInput(iri).match(PORTABLE_IRI_PATTERN);
32
+ if (match != null && DOT_SEGMENT_PATTERN.test(match[3])) throw new TypeError("Portable ActivityPub IRI paths with dot segments cannot be represented as URLs.");
33
+ }
34
+ function assertCompatiblePathCanBeParsed(raw, parsed) {
35
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
36
+ const match = prepareUrlInput(raw).match(/^https?:[\/\\]*[^/?#\\]*([^?#]*)/i);
37
+ if (match == null) return;
38
+ const rawPath = match[1].replace(/\\/g, "/");
39
+ const compatiblePath = parsed.pathname.startsWith(COMPATIBLE_ID_PATH_PREFIX) && COMPATIBLE_ID_DID_PATTERN.test(parsed.pathname.slice(COMPATIBLE_ID_PATH_PREFIX.length));
40
+ const rawCompatiblePath = rawPath.startsWith(COMPATIBLE_ID_PATH_PREFIX) && COMPATIBLE_ID_DID_PATTERN.test(rawPath.slice(COMPATIBLE_ID_PATH_PREFIX.length));
41
+ if ((compatiblePath || rawCompatiblePath) && DOT_SEGMENT_PATTERN.test(rawPath)) throw new TypeError("FEP-ef61 compatible identifier paths with dot segments cannot be represented as URLs.");
42
+ }
43
+ /**
44
+ * Parses a JSON-LD `@id` value as an IRI, including FEP-ef61 portable
45
+ * ActivityPub IRIs. See {@link parseIri} for how IRIs are parsed.
46
+ * @param id The `@id` value.
47
+ * @param base The base IRI to resolve a relative `@id` against.
48
+ * @returns The parsed IRI, or `undefined` if `id` is missing or a blank node
49
+ * identifier.
50
+ * @throws {TypeError} If `id` is not a valid IRI.
51
+ * @since 2.4.0
52
+ */
53
+ function parseJsonLdId(id, base) {
54
+ if (id == null || id.startsWith("_:")) return void 0;
55
+ try {
56
+ return parseIri(id, base);
57
+ } catch {
58
+ throw new TypeError("Invalid @id: " + id);
59
+ }
60
+ }
61
+ /**
62
+ * Parses an IRI as a URL, including FEP-ef61 portable ActivityPub IRIs.
63
+ * Portable URI and FEP-ef61 compatible identifier strings whose path contains
64
+ * a `.` or `..` segment, including percent-encoded spellings, throw a
65
+ * `TypeError`: JavaScript `URL` would otherwise identify a different object.
66
+ * This also applies to compatible identifier strings used as relative bases.
67
+ * A `URL` argument may already have lost such segments before this function
68
+ * receives it.
69
+ *
70
+ * Portable IRIs, e.g., `ap://did:key:z6Mk.../actor`, cannot be represented by
71
+ * JavaScript `URL` as they are, so the returned `URL` keeps the DID authority
72
+ * percent-encoded, e.g., `ap+ef61://did%3Akey%3Az6Mk.../actor`. Use
73
+ * {@link formatIri} to get the canonical string back.
74
+ * @param iri The IRI to parse.
75
+ * @param base The base IRI to resolve a relative IRI against.
76
+ * @returns The parsed IRI.
77
+ * @throws {TypeError} If the IRI is malformed.
78
+ * @since 2.4.0
79
+ */
80
+ function parseIri(iri, base) {
81
+ if (iri instanceof URL) return normalizePortableUrl(iri) ?? new URL(iri.href);
82
+ assertPortablePathCanBeParsed(iri);
83
+ const portable = parsePortableIri(iri);
84
+ if (portable != null) return portable;
85
+ base = normalizeBaseIri(base);
86
+ if (!URL.canParse(iri, base) && iri.startsWith("at://")) return parseAtUri(iri);
87
+ const parsed = new URL(iri, base);
88
+ assertCompatiblePathCanBeParsed(iri, parsed);
89
+ return normalizePortableUrl(parsed) ?? parsed;
90
+ }
91
+ /**
92
+ * Formats a URL as an IRI, including FEP-ef61 portable ActivityPub IRIs.
93
+ * Portable URI and FEP-ef61 compatible identifier strings with dot segments
94
+ * throw a `TypeError` because their paths cannot be represented by JavaScript
95
+ * `URL` without normalization.
96
+ *
97
+ * Portable IRIs are formatted with the `ap+ef61:` scheme and a decoded DID
98
+ * authority, even if they were parsed from `ap:` IRIs. FEP-ef61 currently
99
+ * recommends the `ap:` scheme, so a future major version of Fedify may change
100
+ * the scheme this function produces. Do not compare its results as strings to
101
+ * tell whether two portable IRIs identify the same object; use
102
+ * `arePortableUrisEqual()` instead.
103
+ * @param iri The IRI to format.
104
+ * @returns The formatted IRI. A string that cannot be parsed as a URL at all
105
+ * is returned unchanged.
106
+ * @throws {TypeError} If the IRI is a malformed portable IRI or FEP-ef61
107
+ * compatible identifier, e.g., one with dot segments.
108
+ * @since 2.4.0
109
+ */
110
+ function formatIri(iri) {
111
+ if (typeof iri === "string") assertPortablePathCanBeParsed(iri);
112
+ const parsed = parsePortableIri(iri instanceof URL ? iri.href : iri);
113
+ if (parsed == null) {
114
+ if (iri instanceof URL) return iri.href;
115
+ if (!URL.canParse(iri)) return iri;
116
+ const url = new URL(iri);
117
+ assertCompatiblePathCanBeParsed(iri, url);
118
+ return url.href;
119
+ }
120
+ return `ap+ef61://${decodePortableAuthority(parsed.host)}${parsed.pathname}${parsed.search}${parsed.hash}`;
121
+ }
122
+ /**
123
+ * Canonicalizes a FEP-ef61 portable ActivityPub URI for comparison.
124
+ *
125
+ * This accepts both `ap:` and `ap+ef61:` URI strings with decoded or
126
+ * percent-encoded DID authorities. The returned value uses the `ap+ef61:`
127
+ * scheme, a decoded DID authority, and no query component. Pass the raw URI
128
+ * string, not a `URL` object, because JavaScript `URL` normalizes opaque path
129
+ * segments before Fedify can compare them.
130
+ *
131
+ * The `ap+ef61:` scheme of the result is a choice of Fedify's, whereas
132
+ * FEP-ef61 currently canonicalizes portable URIs with the `ap:` scheme.
133
+ * A future major version of Fedify may change the scheme of the result, so
134
+ * do not persist the result as the only copy of an identifier; keep the
135
+ * original URI, and canonicalize it again when comparing.
136
+ *
137
+ * @param input The raw portable ActivityPub URI string to canonicalize.
138
+ * @returns The canonical portable ActivityPub URI string.
139
+ * @throws {TypeError} If the input is not a valid portable ActivityPub IRI.
140
+ * @since 2.4.0
141
+ */
142
+ function canonicalizePortableUri(input) {
143
+ if (typeof input !== "string") throw new TypeError("Invalid portable ActivityPub IRI.");
144
+ const parsed = parsePortableIri(input);
145
+ if (parsed == null) throw new TypeError("Invalid portable ActivityPub IRI.");
146
+ const match = input.match(PORTABLE_IRI_PATTERN);
147
+ return `ap+ef61://${normalizePortableAuthority(getDidUrlOrigin(decodePortableAuthority(parsed.host)))}${normalizePortableComponent(match[3])}${match[5] == null ? "" : normalizePortableComponent(match[5])}`;
148
+ }
149
+ /**
150
+ * Checks whether two FEP-ef61 portable ActivityPub URIs identify the same
151
+ * portable object.
152
+ *
153
+ * Non-string inputs return `false`. Non-portable URI strings use strict string
154
+ * equality. Portable URI strings are compared through
155
+ * {@link canonicalizePortableUri}; malformed portable URI strings return
156
+ * `false` unless they are exactly equal.
157
+ *
158
+ * @since 2.4.0
159
+ */
160
+ function arePortableUrisEqual(left, right) {
161
+ if (typeof left !== "string" || typeof right !== "string") return false;
162
+ if (left === right) return true;
163
+ if (!PORTABLE_IRI_PATTERN.test(left) || !PORTABLE_IRI_PATTERN.test(right)) return false;
164
+ try {
165
+ return canonicalizePortableUri(left) === canonicalizePortableUri(right);
166
+ } catch (error) {
167
+ if (error instanceof TypeError) return false;
168
+ throw error;
169
+ }
170
+ }
171
+ /**
172
+ * Computes an IRI's FEP-fe34 origin.
173
+ *
174
+ * HTTP(S) IRIs use their web origin. FEP-ef61 portable ActivityPub IRIs and
175
+ * DID URLs use their DID as a cryptographic origin.
176
+ *
177
+ * @throws {TypeError} If the IRI does not have a supported FEP-fe34 origin.
178
+ * @since 2.4.0
179
+ */
180
+ function getFe34Origin(input) {
181
+ if (input instanceof URL) {
182
+ const portable = normalizePortableUrl(input);
183
+ if (portable != null) return getPortableCryptographicOrigin(portable);
184
+ if (input.protocol === "did:") return getDidUrlOrigin(input.href);
185
+ if (input.protocol === "http:" || input.protocol === "https:") return input.origin;
186
+ throw new TypeError("Unsupported FEP-fe34 origin IRI.");
187
+ }
188
+ const portable = parsePortableIri(input);
189
+ if (portable != null) return getPortableCryptographicOrigin(portable);
190
+ if (DID_SCHEME_PATTERN.test(input)) return getDidUrlOrigin(input);
191
+ const parsed = new URL(input);
192
+ if (parsed.protocol === "http:" || parsed.protocol === "https:") return parsed.origin;
193
+ throw new TypeError("Unsupported FEP-fe34 origin IRI.");
194
+ }
195
+ /**
196
+ * Checks whether two IRIs have the same FEP-fe34 origin.
197
+ *
198
+ * Malformed or unsupported IRIs are treated as non-matching.
199
+ *
200
+ * @since 2.4.0
201
+ */
202
+ function haveSameFe34Origin(left, right) {
203
+ try {
204
+ return getFe34Origin(left) === getFe34Origin(right);
205
+ } catch (error) {
206
+ if (error instanceof TypeError) return false;
207
+ throw error;
208
+ }
209
+ }
210
+ /**
211
+ * Checks whether two IRIs have the same origin. Unlike comparing
212
+ * `URL.origin`, which is `"null"` for URLs with non-special schemes, this
213
+ * compares FEP-ef61 portable ActivityPub IRIs by their schemes and DIDs, so
214
+ * that `ap:` and `ap+ef61:` IRIs of the same DID with decoded or
215
+ * percent-encoded authorities have the same origin. Other IRIs with
216
+ * a non-special scheme and a host are compared by their schemes and hosts.
217
+ *
218
+ * This is not an FEP-fe34 origin check: an `ap+ef61:` IRI and the `did:key`
219
+ * verification method of the same DID have different origins here. Use
220
+ * {@link haveSameFe34Origin} for that.
221
+ * @param left The first IRI.
222
+ * @param right The second IRI.
223
+ * @returns `true` if the IRIs have the same origin.
224
+ * @since 2.4.0
225
+ */
226
+ function haveSameIriOrigin(left, right) {
227
+ return getComparableIriOrigin(left) === getComparableIriOrigin(right);
228
+ }
229
+ function getComparableIriOrigin(iri) {
230
+ iri = normalizePortableUrl(iri) ?? iri;
231
+ if (iri.origin !== "null") return iri.origin;
232
+ if (iri.host !== "") {
233
+ const host = iri.protocol === "ap+ef61:" ? encodeURIComponent(getDidUrlOrigin(decodePortableAuthority(iri.host))) : iri.host;
234
+ return `${iri.protocol}//${host}`;
235
+ }
236
+ return iri.href;
237
+ }
238
+ function getPortableCryptographicOrigin(iri) {
239
+ return getDidUrlOrigin(decodePortableAuthority(iri.host));
240
+ }
241
+ function getDidUrlOrigin(iri) {
242
+ const did = iri.split(/[/?#]/, 1)[0].replace(DID_SCHEME_PATTERN, "did:");
243
+ if (!DID_PATTERN.test(did)) throw new TypeError("Invalid DID URL.");
244
+ const parts = did.split(":");
245
+ parts[1] = parts[1].toLowerCase();
246
+ return normalizePortableAuthority(parts.join(":"));
247
+ }
248
+ function parsePortableIri(iri) {
249
+ const match = iri.match(PORTABLE_IRI_PATTERN);
250
+ if (match == null) return null;
251
+ const authority = getDidUrlOrigin(decodePortableAuthority(match[2]));
252
+ if (!DID_PATTERN.test(authority)) throw new TypeError("Invalid portable ActivityPub IRI authority.");
253
+ if (match[3] === "") throw new TypeError("Invalid portable ActivityPub IRI path.");
254
+ return new URL(`ap+ef61://${encodeURIComponent(authority)}${match[3]}${match[4] ?? ""}${match[5] ?? ""}`);
255
+ }
256
+ function normalizePortableUrl(iri) {
257
+ if (iri.protocol !== "ap:" && iri.protocol !== "ap+ef61:") return null;
258
+ const raw = `ap+ef61://${iri.host}${iri.pathname}${iri.search}${iri.hash}`;
259
+ assertPortablePathCanBeParsed(raw);
260
+ return parsePortableIri(raw);
261
+ }
262
+ function normalizeBaseIri(base) {
263
+ if (base == null) return void 0;
264
+ if (base instanceof URL) return normalizePortableUrl(base) ?? base;
265
+ assertPortablePathCanBeParsed(base);
266
+ if (URL.canParse(base)) assertCompatiblePathCanBeParsed(base, new URL(base));
267
+ return parsePortableIri(base) ?? (base.startsWith("at://") && !URL.canParse(".", base) ? parseAtUri(base) : base);
268
+ }
269
+ function decodePortableAuthority(authority) {
270
+ if (INVALID_PERCENT_ENCODING_PATTERN.test(authority)) throw new TypeError("Invalid portable ActivityPub IRI authority.");
271
+ if (DID_SCHEME_PATTERN.test(authority)) {
272
+ const decoded = authority.replace(/%25/gi, "%");
273
+ if (INVALID_PERCENT_ENCODING_PATTERN.test(decoded)) throw new TypeError("Invalid portable ActivityPub IRI authority.");
274
+ return decoded;
275
+ }
276
+ const decoded = authority.replace(/%(25|3A)/gi, (match) => match.toLowerCase() === "%3a" ? ":" : "%");
277
+ if (INVALID_PERCENT_ENCODING_PATTERN.test(decoded)) throw new TypeError("Invalid portable ActivityPub IRI authority.");
278
+ return decoded;
279
+ }
280
+ function normalizePercentEncoding(value) {
281
+ return value.replace(PERCENT_ENCODING_PATTERN, (match) => match.toUpperCase());
282
+ }
283
+ function normalizePortableAuthority(authority) {
284
+ return normalizePercentEncoding(authority).replace(PERCENT_ENCODING_PATTERN, (match) => {
285
+ const decoded = String.fromCharCode(Number.parseInt(match.slice(1), 16));
286
+ return /[A-Za-z0-9._~-]/.test(decoded) ? decoded : match;
287
+ });
288
+ }
289
+ function normalizePortableComponent(value) {
290
+ if (INVALID_PERCENT_ENCODING_PATTERN.test(value)) throw new TypeError("Invalid portable ActivityPub IRI component.");
291
+ return value.replace(/%[0-9A-Fa-f]{2}|[^%]+/g, (match) => {
292
+ if (match.startsWith("%")) {
293
+ const upper = match.toUpperCase();
294
+ const decoded = String.fromCharCode(Number.parseInt(upper.slice(1), 16));
295
+ return /[A-Za-z0-9._~-]/.test(decoded) ? decoded : upper;
296
+ }
297
+ try {
298
+ return encodeURI(match);
299
+ } catch (error) {
300
+ if (error instanceof URIError) throw new TypeError("Invalid portable ActivityPub IRI component.");
301
+ throw error;
302
+ }
303
+ });
304
+ }
305
+ function parseAtUri(uri) {
306
+ const index = uri.indexOf("/", 5);
307
+ const authority = index >= 0 ? uri.slice(5, index) : uri.slice(5);
308
+ const path = index >= 0 ? uri.slice(index) : "";
309
+ return new URL("at://" + encodeURIComponent(authority) + path);
310
+ }
311
+ /**
312
+ * Checks whether the URL is an FEP-ef61 gateway base URI, i.e., an HTTP(S)
313
+ * URI with no credentials, path, query, or fragment, such as
314
+ * `https://example.com/`. FEP-ef61 requires every item of a portable actor's
315
+ * `gateways` to be such a URI. A URI with an empty query or fragment
316
+ * delimiter, such as `https://example.com/?`, is not a gateway base URI.
317
+ *
318
+ * Note that the `URL` class normalizes `https://example.com` to
319
+ * `https://example.com/`, so both are gateway base URIs.
320
+ * @param url The URL to check.
321
+ * @returns `true` if the URL is an FEP-ef61 gateway base URI.
322
+ * @since 2.4.0
323
+ */
324
+ function isGatewayUrl(url) {
325
+ return (url.protocol === "http:" || url.protocol === "https:") && url.href === `${url.origin}/`;
326
+ }
327
+ /**
328
+ * Parses and validates an FEP-ef61 gateway base URI, i.e., an HTTP(S) URI with
329
+ * no credentials, path, query, or fragment, such as `https://example.com`.
330
+ * See {@link isGatewayUrl} for the rules.
331
+ * @param url The gateway base URI to parse.
332
+ * @returns The parsed gateway base URI, whose path is `/`.
333
+ * @throws {TypeError} If the URI is malformed, or is not an HTTP(S) base URI
334
+ * with no credentials, path, query, or fragment. In the
335
+ * latter case, the message starts with
336
+ * `Invalid FEP-ef61 gateway:`.
337
+ * @since 2.4.0
338
+ */
339
+ function parseGatewayUrl(url) {
340
+ const parsed = parseIri(url);
341
+ if (!isGatewayUrl(parsed)) throw new TypeError(`Invalid FEP-ef61 gateway: ${url}. FEP-ef61 gateways must be HTTP(S) base URIs with no credentials, path, query, or fragment.`);
342
+ return parsed;
343
+ }
344
+ const COMPATIBLE_ID_PATH_PREFIX = "/.well-known/apgateway/";
345
+ const COMPATIBLE_ID_DID_PATTERN = /^did(?::|%3A)/i;
346
+ const RAW_COMPATIBLE_ID_PREFIX_PATTERN = /^(?:[hH][tT][tT][pP][sS]?):\/\/[^/?#]*\/\.well-known\/apgateway\/(?=[dD][iI][dD](?::|%3[aA]))/;
347
+ const LOCATION_HINT_PARAMETERS = /* @__PURE__ */ new Set(["@gateway", "gateways"]);
348
+ /**
349
+ * Converts an [FEP-ef61] compatible identifier into a portable ActivityPub
350
+ * URI.
351
+ *
352
+ * A compatible identifier is an HTTP(S) URL under a gateway's fixed
353
+ * `/.well-known/apgateway/` path, such as
354
+ * `https://server.example/.well-known/apgateway/did:key:z6Mk.../objects/1`.
355
+ * This function removes the gateway part and returns the corresponding
356
+ * portable URI, e.g., `ap+ef61://did:key:z6Mk.../objects/1`, in the same
357
+ * internal `URL` form that {@link parseIri} produces. The path, query, and
358
+ * fragment are preserved, so the result is a portable URI, not a comparison
359
+ * form; pass its `href` to {@link canonicalizePortableUri} or
360
+ * {@link arePortableUrisEqual} to compare it with other portable URIs.
361
+ *
362
+ * The conversion only reveals the *claimed* portable identifier. Anyone can
363
+ * publish a compatible identifier for any DID on their own server, so the
364
+ * gateway that served it is neither the object's origin nor authorized to act
365
+ * for the DID. Callers must still verify the retrieved document's Object
366
+ * Integrity Proof against the DID, as FEP-ef61 requires, and should keep the
367
+ * original URL if they need the gateway as a retrieval hint.
368
+ *
369
+ * Arbitrary gateway paths are not supported.
370
+ *
371
+ * [FEP-ef61]: https://w3id.org/fep/ef61
372
+ *
373
+ * @param input The URL to convert.
374
+ * @returns The portable ActivityPub URI, or `null` if the input is not an
375
+ * HTTP(S) URL whose path starts with `/.well-known/apgateway/did:`.
376
+ * Other gateway routes, such as the gateway discovery endpoint and
377
+ * hashlink media URLs, also yield `null`.
378
+ * @throws {TypeError} If the input looks like a compatible identifier but is
379
+ * malformed, e.g., it has an invalid DID, no object path,
380
+ * invalid percent-encoding, credentials, or location
381
+ * hints (`@gateway` query parameters, or the legacy
382
+ * `gateways` parameter), or its raw string path would
383
+ * change during URL parsing. Already-parsed `URL`
384
+ * arguments cannot reveal segments lost by their parser.
385
+ * @since 2.4.0
386
+ */
387
+ function fromCompatibleEf61Id(input) {
388
+ return convertCompatibleEf61Id(input)?.url ?? null;
389
+ }
390
+ function convertCompatibleEf61Id(input) {
391
+ let url;
392
+ const rawPrefix = typeof input === "string" ? input.match(RAW_COMPATIBLE_ID_PREFIX_PATTERN) : null;
393
+ if (input instanceof URL) url = input;
394
+ else if (typeof input === "string" && URL.canParse(input)) url = new URL(input);
395
+ else return null;
396
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
397
+ if (typeof input === "string" && rawPrefix == null) {
398
+ if (url.pathname.startsWith(COMPATIBLE_ID_PATH_PREFIX) && COMPATIBLE_ID_DID_PATTERN.test(url.pathname.slice(23))) throw new TypeError("Invalid FEP-ef61 compatible identifier.");
399
+ }
400
+ if (!url.pathname.startsWith(COMPATIBLE_ID_PATH_PREFIX)) {
401
+ if (rawPrefix != null) throw new TypeError("Invalid FEP-ef61 compatible identifier.");
402
+ return null;
403
+ }
404
+ const tail = url.pathname.slice(23);
405
+ if (!COMPATIBLE_ID_DID_PATTERN.test(tail)) {
406
+ if (rawPrefix != null) throw new TypeError("Invalid FEP-ef61 compatible identifier.");
407
+ return null;
408
+ }
409
+ if (url.username !== "" || url.password !== "") throw new TypeError("Invalid FEP-ef61 compatible identifier: credentials are not allowed.");
410
+ const iri = "ap+ef61://" + url.href.slice(url.origin.length + 23);
411
+ try {
412
+ const parsed = parsePortableIri(iri);
413
+ if (parsed == null) throw new TypeError("Not a portable IRI.");
414
+ if (typeof input === "string" && rawPrefix != null && canonicalizePortableUri("ap://" + input.slice(rawPrefix[0].length)) !== canonicalizePortableUri(iri)) throw new TypeError("URL parsing changed the portable identifier.");
415
+ canonicalizePortableUri(iri);
416
+ if ((url.search === "" ? [] : normalizePortableComponent(url.search.slice(1)).split("&")).some(isLocationHint)) throw new TypeError("Location hints are not allowed.");
417
+ return {
418
+ url: parsed,
419
+ iri
420
+ };
421
+ } catch (error) {
422
+ if (error instanceof TypeError) throw new TypeError("Invalid FEP-ef61 compatible identifier.", { cause: error });
423
+ throw error;
424
+ }
425
+ }
426
+ /**
427
+ * Converts a portable ActivityPub URI into an [FEP-ef61] compatible
428
+ * identifier, which is an HTTP(S) URL under the gateway's fixed
429
+ * `/.well-known/apgateway/` path.
430
+ *
431
+ * For example, `ap+ef61://did:key:z6Mk.../objects/1` and
432
+ * `https://server.example` yield
433
+ * `https://server.example/.well-known/apgateway/did:key:z6Mk.../objects/1`.
434
+ * Both `ap:` and `ap+ef61:` URIs with decoded or percent-encoded DID
435
+ * authorities are accepted. Publishers should use the first gateway in the
436
+ * actor's `gateways` list, as FEP-ef61 requires.
437
+ *
438
+ * The path and fragment are preserved, with characters that are not allowed
439
+ * in HTTP(S) URLs percent-encoded the same way as
440
+ * {@link canonicalizePortableUri} does. FEP-ef61 location hints (`@gateway`
441
+ * query parameters, and the legacy `gateways` parameter) are removed, since
442
+ * compatible identifiers must not have them; other query parameters are kept
443
+ * in order.
444
+ *
445
+ * Arbitrary gateway paths are not supported.
446
+ *
447
+ * [FEP-ef61]: https://w3id.org/fep/ef61
448
+ *
449
+ * @param portableId The `ap:` or `ap+ef61:` URI to convert.
450
+ * @param gateway The gateway's HTTP(S) origin, e.g., `https://server.example`.
451
+ * @returns The compatible identifier.
452
+ * @throws {TypeError} If the portable ID is not a valid `ap:` or `ap+ef61:`
453
+ * URI, if its path has `.` or `..` segments (which
454
+ * HTTP(S) URLs cannot represent without changing the
455
+ * identified object), or if the gateway is
456
+ * not an HTTP(S) origin with no credentials, path, query,
457
+ * or fragment.
458
+ * @since 2.4.0
459
+ */
460
+ function toCompatibleEf61Id(portableId, gateway) {
461
+ const gatewayUrl = parseCompatibleEf61Gateway(gateway);
462
+ const raw = getRawPortableIri(portableId);
463
+ const match = raw.match(PORTABLE_IRI_PATTERN);
464
+ const parsed = parsePortableIri(raw);
465
+ if (match == null || parsed == null) throw new TypeError("Invalid portable ActivityPub IRI.");
466
+ let did = decodePortableAuthority(parsed.host);
467
+ if (/%25/i.test(did)) did = did.replace(/%/g, "%25");
468
+ const path = normalizePortableComponent(match[3]);
469
+ if (path.split("/").some((segment) => segment === "." || segment === "..")) throw new TypeError("FEP-ef61 compatible identifiers cannot represent portable IRI paths with dot segments.");
470
+ const query = match[4] == null ? "" : stripLocationHints(normalizePortableComponent(match[4].slice(1)));
471
+ const fragment = match[5] == null ? "" : normalizePortableComponent(match[5]);
472
+ const result = new URL(gatewayUrl.origin + COMPATIBLE_ID_PATH_PREFIX + did + path + query + fragment);
473
+ const converted = convertCompatibleEf61Id(result);
474
+ if (converted == null || canonicalizePortableUri(converted.iri) !== canonicalizePortableUri(raw)) throw new TypeError("The portable ActivityPub IRI cannot be represented as an FEP-ef61 compatible identifier.");
475
+ return result;
476
+ }
477
+ function parseCompatibleEf61Gateway(gateway) {
478
+ const url = gateway instanceof URL ? gateway : typeof gateway === "string" && URL.canParse(gateway) ? new URL(gateway) : null;
479
+ if (url == null || !isGatewayUrl(url)) throw new TypeError("FEP-ef61 gateways for compatible identifiers must be HTTP(S) origins with no credentials, path, query, or fragment.");
480
+ return url;
481
+ }
482
+ function getRawPortableIri(portableId) {
483
+ if (portableId instanceof URL) {
484
+ if (portableId.protocol !== "ap:" && portableId.protocol !== "ap+ef61:") throw new TypeError("Invalid portable ActivityPub IRI.");
485
+ if (portableId.username !== "" || portableId.password !== "" || portableId.port !== "") throw new TypeError("Invalid portable ActivityPub IRI authority.");
486
+ return portableId.href;
487
+ }
488
+ if (typeof portableId !== "string") throw new TypeError("Invalid portable ActivityPub IRI.");
489
+ return portableId;
490
+ }
491
+ function stripLocationHints(query) {
492
+ const pairs = query.split("&").filter((pair) => !isLocationHint(pair));
493
+ return pairs.length < 1 ? "" : `?${pairs.join("&")}`;
494
+ }
495
+ function isLocationHint(pair) {
496
+ const name = pair.split("=", 1)[0].replace(/\+/g, " ");
497
+ try {
498
+ return LOCATION_HINT_PARAMETERS.has(decodeURIComponent(name));
499
+ } catch (error) {
500
+ if (error instanceof URIError) return false;
501
+ throw error;
502
+ }
503
+ }
504
+ /**
505
+ * The name of the FEP-ef61 location hint query parameter.
506
+ * @internal
507
+ */
508
+ const GATEWAY_HINT_PARAMETER = "@gateway";
509
+ /**
510
+ * Parses an FEP-ef61 gateway, which has to be an HTTP(S) origin with no
511
+ * credentials, path, query, or fragment.
512
+ * @returns The gateway, or `null` if it is not a valid gateway.
513
+ * @internal
514
+ */
515
+ function parseGatewayOrigin(gateway) {
516
+ let url;
517
+ if (gateway instanceof URL) url = new URL(gateway.href);
518
+ else if (typeof gateway === "string" && URL.canParse(gateway)) url = new URL(gateway);
519
+ else return null;
520
+ return isGatewayUrl(url) ? url : null;
521
+ }
522
+ /**
523
+ * Returns a copy of an [FEP-ef61] portable ActivityPub URI with `@gateway`
524
+ * location hints for the given gateways, which tell consumers where they can
525
+ * retrieve the object. Put hints on *references* to portable actors, e.g.,
526
+ * in `actor`, `attributedTo`, `to`, or `cc`, when constructing an object, as
527
+ * FEP-ef61 recommends:
528
+ *
529
+ * ~~~~ typescript
530
+ * withGatewayHints("ap://did:key:z6Mk.../actor", [
531
+ * "https://server1.example",
532
+ * "https://server2.example",
533
+ * ]);
534
+ * // ap+ef61://did:key:z6Mk.../actor?@gateway=https%3A%2F%2Fserver1.example&@gateway=https%3A%2F%2Fserver2.example
535
+ * ~~~~
536
+ *
537
+ * Do not put hints on an object's own `id`. Hints do not change the
538
+ * identity of a portable URI, since FEP-ef61 drops the query when comparing
539
+ * portable URIs, but implementations that do not canonicalize portable URIs
540
+ * would take a hinted ID for another object. Add hints before signing the
541
+ * object, since its Object Integrity Proof covers its references too.
542
+ *
543
+ * The hints that the URI already has, including the legacy `gateways`
544
+ * parameter, are replaced. Each gateway becomes a `@gateway` query
545
+ * parameter whose value is its URI-encoded origin, e.g.,
546
+ * `@gateway=https%3A%2F%2Fserver1.example`, in the given order after the
547
+ * other query parameters. Duplicate gateways are dropped, and an empty list
548
+ * removes the hints as {@link withoutGatewayHints} does. The other query
549
+ * parameters, their order, and the fragment are kept, but percent-encoding
550
+ * is normalized the same way as {@link canonicalizePortableUri} does it.
551
+ *
552
+ * Fedify follows at most five hints when dereferencing a portable URI
553
+ * (three for the key ID of an HTTP Signature), so list the preferred
554
+ * gateways first; there is no limit on the number of hints added here.
555
+ *
556
+ * [FEP-ef61]: https://w3id.org/fep/ef61
557
+ *
558
+ * @param portableId The `ap:` or `ap+ef61:` URI. Pass the raw string rather
559
+ * than a `URL` if its path may have `.` or `..` segments,
560
+ * because the `URL` class resolves them.
561
+ * @param gateways The gateways, e.g., the `gateways` of the actor that the
562
+ * URI refers to. Each has to be an HTTP(S) origin with no
563
+ * credentials, path, query, or fragment.
564
+ * @returns The portable URI with the hints, in the same internal `URL` form
565
+ * as {@link parseIri} returns. Use {@link formatIri} to get its
566
+ * canonical string.
567
+ * @throws {TypeError} If the portable ID is not a valid `ap:` or `ap+ef61:`
568
+ * URI, e.g., it is a compatible identifier, which must
569
+ * not have location hints; if its path has `.` or `..`
570
+ * segments, which the `URL` class cannot represent; or
571
+ * if a gateway is invalid.
572
+ * @since 2.4.0
573
+ */
574
+ function withGatewayHints(portableId, gateways) {
575
+ const parts = splitPortableIri(portableId);
576
+ if (typeof gateways === "string") throw new TypeError("The gateways must be an iterable of gateways, not a string.");
577
+ const hints = [];
578
+ const seen = /* @__PURE__ */ new Set();
579
+ for (const gateway of gateways) {
580
+ const url = parseGatewayOrigin(gateway);
581
+ if (url == null) throw new TypeError("FEP-ef61 gateways must be HTTP(S) origins with no credentials, path, query, or fragment: " + String(gateway));
582
+ if (seen.has(url.href)) continue;
583
+ seen.add(url.href);
584
+ hints.push(url);
585
+ }
586
+ return replaceGatewayHints(parts, hints);
587
+ }
588
+ /**
589
+ * Returns a copy of an [FEP-ef61] portable ActivityPub URI without its
590
+ * location hints, i.e., `@gateway` query parameters and the legacy
591
+ * `gateways` parameter. The other query parameters, their order, and the
592
+ * fragment are kept, but percent-encoding is normalized the same way as
593
+ * {@link canonicalizePortableUri} does it.
594
+ *
595
+ * [FEP-ef61]: https://w3id.org/fep/ef61
596
+ *
597
+ * @param portableId The `ap:` or `ap+ef61:` URI. Pass the raw string rather
598
+ * than a `URL` if its path may have `.` or `..` segments,
599
+ * because the `URL` class resolves them.
600
+ * @returns The portable URI without the hints, in the same internal `URL`
601
+ * form as {@link parseIri} returns.
602
+ * @throws {TypeError} If the portable ID is not a valid `ap:` or `ap+ef61:`
603
+ * URI, or if its path has `.` or `..` segments, which
604
+ * the `URL` class cannot represent.
605
+ * @since 2.4.0
606
+ */
607
+ function withoutGatewayHints(portableId) {
608
+ return replaceGatewayHints(splitPortableIri(portableId), []);
609
+ }
610
+ /**
611
+ * Gets the gateways in the `@gateway` location hints of an [FEP-ef61]
612
+ * portable ActivityPub URI, in order. Hints that are not valid gateways,
613
+ * i.e., HTTP(S) origins with no credentials, path, query, or fragment, are
614
+ * skipped, and so are duplicates. The legacy `gateways` parameter is not
615
+ * read.
616
+ *
617
+ * Unlike Fedify's dereferencing, which follows at most five hints, this
618
+ * returns all of them.
619
+ *
620
+ * [FEP-ef61]: https://w3id.org/fep/ef61
621
+ *
622
+ * @param portableId The `ap:` or `ap+ef61:` URI.
623
+ * @returns The gateways, e.g., `https://server1.example/`.
624
+ * @throws {TypeError} If the portable ID is not a valid `ap:` or `ap+ef61:`
625
+ * URI.
626
+ * @since 2.4.0
627
+ */
628
+ function getGatewayHints(portableId) {
629
+ const { query } = splitPortableIri(portableId);
630
+ return query == null ? [] : parseGatewayHints(query);
631
+ }
632
+ function splitPortableIri(portableId) {
633
+ const raw = getRawPortableIri(portableId);
634
+ const match = raw.match(PORTABLE_IRI_PATTERN);
635
+ const parsed = parsePortableIri(raw);
636
+ if (match == null || parsed == null) throw new TypeError("Invalid portable ActivityPub IRI.");
637
+ return {
638
+ raw,
639
+ parsed,
640
+ path: normalizePortableComponent(match[3]),
641
+ query: match[4] == null ? null : normalizePortableComponent(match[4].slice(1)),
642
+ fragment: match[5] == null ? "" : normalizePortableComponent(match[5])
643
+ };
644
+ }
645
+ function parseGatewayHints(query) {
646
+ const hints = [];
647
+ const seen = /* @__PURE__ */ new Set();
648
+ for (const hint of new URLSearchParams(`?${query}`).getAll(GATEWAY_HINT_PARAMETER)) {
649
+ const url = parseGatewayOrigin(hint);
650
+ if (url == null || seen.has(url.href)) continue;
651
+ seen.add(url.href);
652
+ hints.push(url);
653
+ }
654
+ return hints;
655
+ }
656
+ function replaceGatewayHints(parts, hints) {
657
+ const pairs = parts.query == null ? [] : parts.query.split("&").filter((pair) => pair !== "" && !isLocationHint(pair));
658
+ for (const hint of hints) pairs.push(`${GATEWAY_HINT_PARAMETER}=${encodeURIComponent(hint.origin)}`);
659
+ const query = pairs.length < 1 ? "" : `?${pairs.join("&")}`;
660
+ const result = parsePortableIri(`ap+ef61://${parts.parsed.host}${parts.path}${query}${parts.fragment}`);
661
+ if (result == null || canonicalizePortableUri(result.href) !== canonicalizePortableUri(parts.raw) || parseGatewayHints(result.search.slice(1)).map((url) => url.href).join(" ") !== hints.map((url) => url.href).join(" ")) throw new TypeError("The portable ActivityPub IRI cannot be represented as a URL without changing the object it refers to.");
662
+ return result;
663
+ }
664
+ /**
665
+ * Validates a URL to prevent SSRF attacks.
666
+ */
667
+ async function validatePublicUrl(url) {
668
+ const parsed = new URL(url);
669
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new UrlError(`Unsupported protocol: ${parsed.protocol}`);
670
+ let hostname = parsed.hostname;
671
+ if (hostname.startsWith("[") && hostname.endsWith("]")) hostname = hostname.slice(1, -1);
672
+ if (hostname === "localhost") throw new UrlError("Localhost is not allowed");
673
+ const hostnameFamily = isIP(hostname);
674
+ if (hostnameFamily !== 0) {
675
+ validatePublicIpAddress(hostname, hostnameFamily);
676
+ return;
677
+ }
678
+ if ("Deno" in globalThis && !isIP(hostname)) {
679
+ if ((await Deno.permissions.query({ name: "net" })).state !== "granted") return;
680
+ }
681
+ if ("Bun" in globalThis) {
682
+ if (hostname === "example.com" || hostname.endsWith(".example.com")) return;
683
+ else if (hostname === "fedify-test.internal") throw new UrlError("Invalid or private address: fedify-test.internal");
684
+ }
685
+ let addresses;
686
+ try {
687
+ addresses = await dns.lookup(hostname, { all: true });
688
+ } catch (error) {
689
+ throw new UrlError("DNS lookup failed", {
690
+ cause: error,
691
+ reason: "dns"
692
+ });
693
+ }
694
+ validateLookupAddresses(addresses);
695
+ }
696
+ /**
697
+ * Validates the IP addresses returned by `node:dns.lookup()`.
698
+ *
699
+ * Cloudflare Workers' `node:dns` implementation currently maps every record
700
+ * in a DNS-over-HTTPS `Answer` array—including CNAME records—to a
701
+ * `LookupAddress`, even though Node.js specifies that the `address` field must
702
+ * contain an IPv4 or IPv6 literal. See:
703
+ * https://github.com/cloudflare/workerd/issues/6886
704
+ *
705
+ * Work around that bug by ignoring non-IP entries only when the lookup also
706
+ * returns at least one actual IP address. This remains fail-closed: a result
707
+ * containing no IP addresses is rejected, and every returned IP address is
708
+ * still validated and must be public. This workaround can be revisited once
709
+ * the Workerd issue is fixed in supported Cloudflare Workers runtimes.
710
+ *
711
+ * @internal
712
+ */
713
+ function validateLookupAddresses(addresses) {
714
+ let ipAddressCount = 0;
715
+ for (const { address } of addresses) {
716
+ const family = isIP(address);
717
+ if (family === 0) continue;
718
+ ipAddressCount++;
719
+ validatePublicIpAddress(address, family);
720
+ }
721
+ if (ipAddressCount === 0) throw new UrlError("DNS lookup did not return any IP address", { reason: "dns" });
722
+ }
723
+ function validatePublicIpAddress(address, family) {
724
+ if (family === 4 && isValidPublicIPv4Address(address) || family === 6 && isValidPublicIPv6Address(address)) return;
725
+ throw new UrlError(`Invalid or private address: ${address}`);
726
+ }
727
+ function isValidPublicIPv4Address(address) {
728
+ const parts = parseIPv4Address(address);
729
+ if (parts == null) return false;
730
+ const value = ipv4PartsToNumber(parts);
731
+ return !nonPublicIPv4Prefixes.some(({ base, prefix }) => matchesIPv4Prefix(value, base, prefix));
732
+ }
733
+ function isValidPublicIPv6Address(address) {
734
+ const words = parseIPv6Address(address);
735
+ if (words == null) return false;
736
+ if (nonPublicIPv6Prefixes.some(({ words: prefixWords, prefix }) => matchesIPv6Prefix(words, prefixWords, prefix))) return false;
737
+ for (const { extractIPv4, prefix, words: prefixWords } of ipv6WithIPv4Prefixes) {
738
+ if (!matchesIPv6Prefix(words, prefixWords, prefix)) continue;
739
+ const ipv4Address = extractIPv4(words);
740
+ if (ipv4Address != null && !isValidPublicIPv4Address(ipv4Address)) return false;
741
+ }
742
+ return true;
743
+ }
744
+ function expandIPv6Address(address) {
745
+ address = address.toLowerCase();
746
+ const ipv4Delimiter = address.lastIndexOf(":");
747
+ if (address.includes(".") && ipv4Delimiter >= 0) {
748
+ const ipv4Parts = parseIPv4Address(address.substring(ipv4Delimiter + 1));
749
+ if (ipv4Parts == null) return address;
750
+ const high = (ipv4Parts[0] << 8) + ipv4Parts[1];
751
+ const low = (ipv4Parts[2] << 8) + ipv4Parts[3];
752
+ address = address.substring(0, ipv4Delimiter + 1) + high.toString(16) + ":" + low.toString(16);
753
+ }
754
+ if (address === "::") return "0000:0000:0000:0000:0000:0000:0000:0000";
755
+ if (address.startsWith("::")) address = "0000" + address;
756
+ if (address.endsWith("::")) address = address + "0000";
757
+ address = address.replace("::", ":0000".repeat(8 - (address.match(/:/g) || []).length) + ":");
758
+ return address.split(":").map((part) => part.padStart(4, "0")).join(":");
759
+ }
760
+ const nonPublicIPv4Prefixes = [
761
+ ipv4Prefix("0.0.0.0/8", "RFC 6890"),
762
+ ipv4Prefix("10.0.0.0/8", "RFC 1918"),
763
+ ipv4Prefix("100.64.0.0/10", "RFC 6598"),
764
+ ipv4Prefix("127.0.0.0/8", "RFC 1122"),
765
+ ipv4Prefix("169.254.0.0/16", "RFC 3927"),
766
+ ipv4Prefix("172.16.0.0/12", "RFC 1918"),
767
+ ipv4Prefix("192.0.0.0/24", "RFC 6890"),
768
+ ipv4Prefix("192.0.2.0/24", "RFC 5737"),
769
+ ipv4Prefix("192.88.99.0/24", "RFC 7526"),
770
+ ipv4Prefix("192.168.0.0/16", "RFC 1918"),
771
+ ipv4Prefix("198.18.0.0/15", "RFC 2544"),
772
+ ipv4Prefix("198.51.100.0/24", "RFC 5737"),
773
+ ipv4Prefix("203.0.113.0/24", "RFC 5737"),
774
+ ipv4Prefix("224.0.0.0/4", "RFC 5771"),
775
+ ipv4Prefix("240.0.0.0/4", "RFC 1112")
776
+ ];
777
+ const nonPublicIPv6Prefixes = [
778
+ ipv6Prefix("::/16", "RFC 4291"),
779
+ ipv6Prefix("2001::/32", "RFC 4380"),
780
+ ipv6Prefix("2002::/16", "RFC 3056"),
781
+ ipv6Prefix("64:ff9b:1::/48", "RFC 8215"),
782
+ ipv6Prefix("fc00::/7", "RFC 4193"),
783
+ ipv6Prefix("fe80::/10", "RFC 4291"),
784
+ ipv6Prefix("ff00::/8", "RFC 4291")
785
+ ];
786
+ const ipv6WithIPv4Prefixes = [{
787
+ ...ipv6Prefix("64:ff9b::/96", "RFC 6052"),
788
+ extractIPv4: (words) => ipv4FromWords(words[6], words[7])
789
+ }];
790
+ function ipv4Prefix(cidr, rfc) {
791
+ const [address, prefixText] = cidr.split("/");
792
+ const prefix = parseInt(prefixText, 10);
793
+ const parts = parseIPv4Address(address);
794
+ if (parts == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 32) throw new Error(`Invalid IPv4 prefix: ${cidr}`);
795
+ return {
796
+ cidr,
797
+ base: ipv4PartsToNumber(parts),
798
+ prefix,
799
+ rfc
800
+ };
801
+ }
802
+ function ipv6Prefix(cidr, rfc) {
803
+ const [address, prefixText] = cidr.split("/");
804
+ const prefix = parseInt(prefixText, 10);
805
+ const words = parseIPv6Address(address);
806
+ if (words == null || !Number.isInteger(prefix) || prefix < 0 || prefix > 128) throw new Error(`Invalid IPv6 prefix: ${cidr}`);
807
+ return {
808
+ cidr,
809
+ words,
810
+ prefix,
811
+ rfc
812
+ };
813
+ }
814
+ function parseIPv4Address(address) {
815
+ const parts = address.split(".").map((part) => {
816
+ if (!/^\d+$/.test(part)) return NaN;
817
+ return parseInt(part, 10);
818
+ });
819
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
820
+ return parts;
821
+ }
822
+ function parseIPv6Address(address) {
823
+ const parts = expandIPv6Address(address).split(":");
824
+ if (parts.length !== 8) return null;
825
+ const words = parts.map((part) => {
826
+ if (!/^[0-9a-f]{1,4}$/i.test(part)) return NaN;
827
+ return parseInt(part, 16);
828
+ });
829
+ if (words.some((word) => !Number.isInteger(word) || word < 0 || word > 65535)) return null;
830
+ return words;
831
+ }
832
+ function ipv4PartsToNumber(parts) {
833
+ return parts[0] * 2 ** 24 + parts[1] * 2 ** 16 + parts[2] * 2 ** 8 + parts[3];
834
+ }
835
+ function ipv4FromWords(highWord, lowWord) {
836
+ return [
837
+ highWord >> 8,
838
+ highWord & 255,
839
+ lowWord >> 8,
840
+ lowWord & 255
841
+ ].join(".");
842
+ }
843
+ function matchesIPv4Prefix(address, prefixBase, prefixLength) {
844
+ const blockSize = 2 ** (32 - prefixLength);
845
+ return Math.floor(address / blockSize) === Math.floor(prefixBase / blockSize);
846
+ }
847
+ function matchesIPv6Prefix(address, prefixWords, prefixLength) {
848
+ let remaining = prefixLength;
849
+ for (let i = 0; i < 8 && remaining > 0; i++) if (remaining >= 16) {
850
+ if (address[i] !== prefixWords[i]) return false;
851
+ remaining -= 16;
852
+ } else {
853
+ const mask = 65535 << 16 - remaining & 65535;
854
+ if ((address[i] & mask) !== (prefixWords[i] & mask)) return false;
855
+ remaining = 0;
856
+ }
857
+ return true;
858
+ }
859
+ //#endregion
860
+ export { withoutGatewayHints as S, parseIri as _, expandIPv6Address as a, validatePublicUrl as b, getFe34Origin as c, haveSameIriOrigin as d, isGatewayUrl as f, parseGatewayUrl as g, parseGatewayOrigin as h, canonicalizePortableUri as i, getGatewayHints as l, isValidPublicIPv6Address as m, UrlError as n, formatIri as o, isValidPublicIPv4Address as p, arePortableUrisEqual as r, fromCompatibleEf61Id as s, GATEWAY_HINT_PARAMETER as t, haveSameFe34Origin as u, parseJsonLdId as v, withGatewayHints as x, toCompatibleEf61Id as y };