@fedify/fedify 2.0.0-dev.1641 → 2.0.0-dev.167

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 (316) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +66 -30
  3. package/dist/{assert_rejects-7UF4R_Qs.js → assert_rejects-Ce45JcFg.js} +1 -1
  4. package/dist/{assert_is_error-B035L3om.js → assert_throws-BNXdRGWP.js} +31 -1
  5. package/dist/{builder-E2Icrl_a.js → builder-CRQGVq_N.js} +15 -8
  6. package/dist/{client-bgSdkFa2.d.ts → client-CUTUGgvJ.d.ts} +19 -19
  7. package/dist/{client-BW4V0OJx.js → client-Dg7OfUDA.js} +28 -23
  8. package/dist/{client-CegPX0Rn.d.cts → client-by-PEGAJ.d.cts} +19 -19
  9. package/dist/compat/mod.cjs +1 -1
  10. package/dist/compat/mod.d.cts +6 -12
  11. package/dist/compat/mod.d.ts +6 -12
  12. package/dist/compat/mod.js +1 -1
  13. package/dist/compat/transformers.test.js +21 -19
  14. package/dist/context-Bns6uTJq.js +109 -0
  15. package/dist/{context-CDSZdQHD.d.ts → context-C7vzWilY.d.ts} +374 -182
  16. package/dist/{context-Dq8aCtMH.d.cts → context-CrB9RFy5.d.cts} +374 -182
  17. package/dist/deno-Bvf4AA-X.js +117 -0
  18. package/dist/{testing-ByQmUvf-.js → dist-B5f6a8Tt.js} +90 -111
  19. package/dist/{authdocloader-BkIZCKQv.js → docloader-2gNKaklf.js} +17 -8
  20. package/dist/{esm-mtx3XJAD.js → esm-DGl7uK1r.js} +32 -17
  21. package/dist/federation/builder.test.js +9 -9
  22. package/dist/federation/collection.test.js +3 -6
  23. package/dist/federation/handler.test.js +113 -145
  24. package/dist/federation/idempotency.test.js +202 -0
  25. package/dist/federation/inbox.test.js +5 -6
  26. package/dist/federation/keycache.test.js +4 -5
  27. package/dist/federation/kv.test.js +58 -7
  28. package/dist/federation/middleware.test.js +306 -111
  29. package/dist/federation/mod.cjs +8 -12
  30. package/dist/federation/mod.d.cts +7 -13
  31. package/dist/federation/mod.d.ts +7 -13
  32. package/dist/federation/mod.js +8 -13
  33. package/dist/federation/mq.test.js +7 -8
  34. package/dist/federation/negotiation.test.js +25 -0
  35. package/dist/federation/retry.test.js +2 -4
  36. package/dist/federation/router.test.js +4 -6
  37. package/dist/federation/send.test.js +53 -13
  38. package/dist/{webfinger/handler.test.js → federation/webfinger.test.js} +25 -23
  39. package/dist/{federation-H2_En3j5.cjs → federation-B431K2gm.cjs} +22 -0
  40. package/dist/{federation-D1U8YY9t.js → federation-BbZwNNWj.js} +28 -6
  41. package/dist/{http-C7uYFcBo.js → http-0lpbWrFT.js} +371 -11
  42. package/dist/{http-BS6766zs.d.cts → http-ClB3pLcL.d.cts} +2 -2
  43. package/dist/{http-DqSNLFNY.d.ts → http-DLBDPal9.d.ts} +2 -2
  44. package/dist/{http-Cox5GsED.js → http-DP374h--.js} +3 -2
  45. package/dist/{http-ZhcoaYEa.cjs → http-d_vxukl7.cjs} +410 -14
  46. package/dist/{inbox-BDdRbWNI.js → inbox-Dv3k4z7l.js} +25 -7
  47. package/dist/{key-CfiBDu3o.js → key-t0uDOx8t.js} +3 -2
  48. package/dist/{keycache-CVBjz3xi.js → keycache-DRxpZ5r9.js} +1 -1
  49. package/dist/{keys-CBKbYaJA.js → keys-ZbcByPg9.js} +2 -1
  50. package/dist/{kv-63Cil1MD.d.cts → kv-B4vFhIYL.d.cts} +30 -1
  51. package/dist/{kv-C7sopW2E.d.ts → kv-CYySNrsn.d.ts} +30 -1
  52. package/dist/{kv-CRZrzyXm.js → kv-QzKcOQgP.js} +22 -0
  53. package/dist/kv-cache-BEeqyGER.js +107 -0
  54. package/dist/kv-cache-KFREoRaI.cjs +134 -0
  55. package/dist/kv-cache-aVS_ypNU.js +122 -0
  56. package/dist/{ld-CxgmnSO3.js → ld-CpXPfqRW.js} +4 -2
  57. package/dist/middleware-6Nb3n763.js +12 -0
  58. package/dist/{middleware-LyCG_YVM.cjs → middleware-Clcecst5.cjs} +309 -303
  59. package/dist/{middleware-DXidHY4N.js → middleware-DEy7WEOy.js} +254 -254
  60. package/dist/{middleware-ByPnvMMS.js → middleware-DLaPtWGX.js} +215 -313
  61. package/dist/middleware-DRg9fmN1.js +26 -0
  62. package/dist/middleware-lkdHuEk5.cjs +12 -0
  63. package/dist/mod-0p9zUdzg.d.cts +107 -0
  64. package/dist/mod-0qnPv4EC.d.cts +62 -0
  65. package/dist/{mod-BClfg3ej.d.cts → mod-BrS8tiad.d.cts} +3 -3
  66. package/dist/mod-C3SOvTD1.d.ts +64 -0
  67. package/dist/{mod-BhMnAkFX.d.cts → mod-D6pS5_xJ.d.cts} +4 -4
  68. package/dist/{mod-Drmz72EK.d.ts → mod-jOa7W503.d.ts} +3 -3
  69. package/dist/{mod-RI3-KvUI.d.ts → mod-waqu-BL_.d.ts} +4 -4
  70. package/dist/mod-xc20HhMD.d.ts +109 -0
  71. package/dist/mod.cjs +17 -112
  72. package/dist/mod.d.cts +11 -17
  73. package/dist/mod.d.ts +11 -17
  74. package/dist/mod.js +11 -17
  75. package/dist/negotiation-5NPJL6zp.js +71 -0
  76. package/dist/nodeinfo/client.test.js +5 -8
  77. package/dist/nodeinfo/handler.test.js +23 -22
  78. package/dist/nodeinfo/mod.cjs +2 -3
  79. package/dist/nodeinfo/mod.d.cts +2 -4
  80. package/dist/nodeinfo/mod.d.ts +2 -4
  81. package/dist/nodeinfo/mod.js +2 -3
  82. package/dist/nodeinfo/types.test.js +4 -7
  83. package/dist/otel/exporter.test.js +893 -0
  84. package/dist/otel/mod.cjs +256 -0
  85. package/dist/otel/mod.d.cts +230 -0
  86. package/dist/otel/mod.d.ts +232 -0
  87. package/dist/otel/mod.js +255 -0
  88. package/dist/{owner-Cxob5_PK.js → owner-BaG2jUgZ.js} +45 -8
  89. package/dist/{owner-CQPnQVtf.d.ts → owner-BgI8C-VY.d.ts} +2 -3
  90. package/dist/{owner-B-7Ptt_m.d.cts → owner-C-zfmVAD.d.cts} +2 -3
  91. package/dist/{proof-DkxwMaWE.js → proof-ClXweyp2.js} +47 -11
  92. package/dist/{proof-2Gcor0_N.cjs → proof-Cy-QcHCv.cjs} +69 -33
  93. package/dist/{proof-BiSQNUmQ.js → proof-D8bfMlig.js} +3 -2
  94. package/dist/router-D9eI0s4b.js +118 -0
  95. package/dist/{send-DSEhWIYD.js → send-BLogwy3G.js} +9 -4
  96. package/dist/sig/http.test.js +9 -11
  97. package/dist/sig/key.test.js +7 -9
  98. package/dist/sig/ld.test.js +8 -10
  99. package/dist/sig/mod.cjs +7 -11
  100. package/dist/sig/mod.d.cts +3 -7
  101. package/dist/sig/mod.d.ts +3 -7
  102. package/dist/sig/mod.js +3 -7
  103. package/dist/sig/owner.test.js +31 -10
  104. package/dist/sig/proof.test.js +11 -12
  105. package/dist/testing/mod.d.ts +243 -6982
  106. package/dist/testing/mod.js +4 -4
  107. package/dist/{transformers-CoBS-oFG.cjs → transformers-BjBg6Lag.cjs} +2 -2
  108. package/dist/{transformers-BFT6d7J5.js → transformers-N_ip_y4P.js} +2 -2
  109. package/dist/{types-l2uh_ZhP.js → types-8l28uC8o.js} +31 -26
  110. package/dist/{types-Bqt2EgP0.cjs → types-B6z6CqIz.cjs} +33 -28
  111. package/dist/{types-BSuWJsOm.js → types-CPz01LGH.js} +3 -3
  112. package/dist/{runtime/authdocloader.test.js → utils/docloader.test.js} +11 -13
  113. package/dist/utils/kv-cache.test.js +211 -0
  114. package/dist/utils/mod.cjs +10 -0
  115. package/dist/utils/mod.d.cts +4 -0
  116. package/dist/utils/mod.d.ts +6 -0
  117. package/dist/utils/mod.js +9 -0
  118. package/package.json +34 -75
  119. package/dist/actor-C22bXuuC.d.ts +0 -130
  120. package/dist/actor-CP03csrm.cjs +0 -37786
  121. package/dist/actor-DMgu-ZjT.d.cts +0 -128
  122. package/dist/actor-DU511yTk.js +0 -37312
  123. package/dist/actor-DVpsNXhn.js +0 -146
  124. package/dist/assert_throws-53_pKeP3.js +0 -39
  125. package/dist/authdocloader-BnsFSERg.cjs +0 -58
  126. package/dist/authdocloader-DCgMyo82.js +0 -52
  127. package/dist/denokv-jZ0Z2h0M.js +0 -57
  128. package/dist/docloader-BtqIh1OE.js +0 -4795
  129. package/dist/docloader-CxWcuWqQ.d.ts +0 -221
  130. package/dist/docloader-D-MrRyHl.d.cts +0 -219
  131. package/dist/docloader-kae6M-GI.cjs +0 -4861
  132. package/dist/fixtures/activitypub.academy/users/brauca_darradiul.json +0 -83
  133. package/dist/fixtures/example.com/announce.json +0 -6
  134. package/dist/fixtures/example.com/collection.json +0 -19
  135. package/dist/fixtures/example.com/create.json +0 -6
  136. package/dist/fixtures/example.com/cross-origin-actor.json +0 -6
  137. package/dist/fixtures/example.com/hong-gildong.json +0 -11
  138. package/dist/fixtures/example.com/invite.json +0 -7
  139. package/dist/fixtures/example.com/key.json +0 -7
  140. package/dist/fixtures/example.com/key2.json +0 -6
  141. package/dist/fixtures/example.com/object.json +0 -6
  142. package/dist/fixtures/example.com/orderedcollectionpage.json +0 -24
  143. package/dist/fixtures/example.com/paged/a.json +0 -13
  144. package/dist/fixtures/example.com/paged/b.json +0 -16
  145. package/dist/fixtures/example.com/paged-collection.json +0 -6
  146. package/dist/fixtures/example.com/person.json +0 -22
  147. package/dist/fixtures/example.com/person2.json +0 -40
  148. package/dist/fixtures/example.com/test.json +0 -5
  149. package/dist/fixtures/example.com/users/handle.json +0 -16
  150. package/dist/fixtures/example.com/wrong-type.json +0 -3
  151. package/dist/fixtures/oeee.cafe/ap/users/3609fd4e-d51d-4db8-9f04-4189815864dd.json +0 -24
  152. package/dist/fixtures/remote.domain/users/bob.json +0 -20
  153. package/dist/fixtures/server.example/users/alice.json +0 -20
  154. package/dist/fixtures/w3id.org/identity/v1.json +0 -152
  155. package/dist/fixtures/w3id.org/security/data-integrity/v1.json +0 -74
  156. package/dist/fixtures/w3id.org/security/multikey/v1.json +0 -35
  157. package/dist/fixtures/w3id.org/security/v1.json +0 -50
  158. package/dist/fixtures/wizard.casa/users/hongminhee.json +0 -69
  159. package/dist/fixtures/www.w3.org/ns/activitystreams.json +0 -379
  160. package/dist/fixtures/www.w3.org/ns/did/v1.json +0 -58
  161. package/dist/key-B9Z5ZuX9.js +0 -10
  162. package/dist/key-Cc0JlcKe.js +0 -260
  163. package/dist/key-CgwCzDC4.js +0 -10
  164. package/dist/key-D-7DPHNl.cjs +0 -10
  165. package/dist/key-HqzOCwDc.cjs +0 -290
  166. package/dist/lookup-CiU3QxQz.js +0 -322
  167. package/dist/lookup-NuT9cCSl.js +0 -131
  168. package/dist/lookup-QHjmy4Og.cjs +0 -137
  169. package/dist/middleware-BHboQ4BE.js +0 -25
  170. package/dist/middleware-Bp3I9z8r.js +0 -17
  171. package/dist/middleware-oYqSU5ky.cjs +0 -17
  172. package/dist/mod-Cxt4Kpf6.d.ts +0 -291
  173. package/dist/mod-DBzN0aCM.d.ts +0 -115
  174. package/dist/mod-Dc_-mf8s.d.cts +0 -102
  175. package/dist/mod-FZd39qVq.d.cts +0 -1
  176. package/dist/mod-TFoH2Ql8.d.ts +0 -104
  177. package/dist/mod-evzlRVZq.d.cts +0 -289
  178. package/dist/mod-g0xFzAP9.d.ts +0 -2
  179. package/dist/mod-jQ4OODsl.d.cts +0 -113
  180. package/dist/mq-B7R1Q-M5.d.cts +0 -140
  181. package/dist/mq-CRGm1e_F.d.ts +0 -143
  182. package/dist/runtime/docloader.test.js +0 -522
  183. package/dist/runtime/key.test.js +0 -103
  184. package/dist/runtime/langstr.test.js +0 -39
  185. package/dist/runtime/link.test.js +0 -61
  186. package/dist/runtime/mod.cjs +0 -25
  187. package/dist/runtime/mod.d.cts +0 -6
  188. package/dist/runtime/mod.d.ts +0 -8
  189. package/dist/runtime/mod.js +0 -13
  190. package/dist/runtime/multibase/multibase.test.d.ts +0 -3
  191. package/dist/runtime/multibase/multibase.test.js +0 -358
  192. package/dist/runtime/url.test.d.ts +0 -3
  193. package/dist/runtime/url.test.js +0 -45
  194. package/dist/src/vocab/accept.yaml +0 -15
  195. package/dist/src/vocab/activity.yaml +0 -98
  196. package/dist/src/vocab/add.yaml +0 -16
  197. package/dist/src/vocab/announce.yaml +0 -30
  198. package/dist/src/vocab/application.yaml +0 -324
  199. package/dist/src/vocab/arrive.yaml +0 -15
  200. package/dist/src/vocab/article.yaml +0 -46
  201. package/dist/src/vocab/audio.yaml +0 -11
  202. package/dist/src/vocab/block.yaml +0 -16
  203. package/dist/src/vocab/chatmessage.yaml +0 -50
  204. package/dist/src/vocab/collection.yaml +0 -154
  205. package/dist/src/vocab/collectionpage.yaml +0 -55
  206. package/dist/src/vocab/create.yaml +0 -28
  207. package/dist/src/vocab/dataintegrityproof.yaml +0 -56
  208. package/dist/src/vocab/delete.yaml +0 -27
  209. package/dist/src/vocab/didservice.yaml +0 -22
  210. package/dist/src/vocab/dislike.yaml +0 -14
  211. package/dist/src/vocab/document.yaml +0 -31
  212. package/dist/src/vocab/emoji.yaml +0 -12
  213. package/dist/src/vocab/emojireact.yaml +0 -17
  214. package/dist/src/vocab/endpoints.yaml +0 -85
  215. package/dist/src/vocab/event.yaml +0 -11
  216. package/dist/src/vocab/export.yaml +0 -9
  217. package/dist/src/vocab/flag.yaml +0 -15
  218. package/dist/src/vocab/follow.yaml +0 -19
  219. package/dist/src/vocab/group.yaml +0 -324
  220. package/dist/src/vocab/hashtag.yaml +0 -14
  221. package/dist/src/vocab/ignore.yaml +0 -14
  222. package/dist/src/vocab/image.yaml +0 -9
  223. package/dist/src/vocab/intransitiveactivity.yaml +0 -15
  224. package/dist/src/vocab/invite.yaml +0 -14
  225. package/dist/src/vocab/join.yaml +0 -14
  226. package/dist/src/vocab/key.yaml +0 -28
  227. package/dist/src/vocab/leave.yaml +0 -14
  228. package/dist/src/vocab/like.yaml +0 -16
  229. package/dist/src/vocab/link.yaml +0 -101
  230. package/dist/src/vocab/listen.yaml +0 -12
  231. package/dist/src/vocab/mention.yaml +0 -9
  232. package/dist/src/vocab/move.yaml +0 -15
  233. package/dist/src/vocab/multikey.yaml +0 -36
  234. package/dist/src/vocab/note.yaml +0 -48
  235. package/dist/src/vocab/object.yaml +0 -404
  236. package/dist/src/vocab/offer.yaml +0 -15
  237. package/dist/src/vocab/orderedcollection.yaml +0 -39
  238. package/dist/src/vocab/orderedcollectionpage.yaml +0 -50
  239. package/dist/src/vocab/organization.yaml +0 -324
  240. package/dist/src/vocab/page.yaml +0 -11
  241. package/dist/src/vocab/person.yaml +0 -324
  242. package/dist/src/vocab/place.yaml +0 -75
  243. package/dist/src/vocab/profile.yaml +0 -26
  244. package/dist/src/vocab/propertyvalue.yaml +0 -32
  245. package/dist/src/vocab/question.yaml +0 -103
  246. package/dist/src/vocab/read.yaml +0 -13
  247. package/dist/src/vocab/reject.yaml +0 -14
  248. package/dist/src/vocab/relationship.yaml +0 -52
  249. package/dist/src/vocab/remove.yaml +0 -14
  250. package/dist/src/vocab/service.yaml +0 -324
  251. package/dist/src/vocab/source.yaml +0 -26
  252. package/dist/src/vocab/tentativeaccept.yaml +0 -14
  253. package/dist/src/vocab/tentativereject.yaml +0 -14
  254. package/dist/src/vocab/tombstone.yaml +0 -24
  255. package/dist/src/vocab/travel.yaml +0 -16
  256. package/dist/src/vocab/undo.yaml +0 -26
  257. package/dist/src/vocab/update.yaml +0 -58
  258. package/dist/src/vocab/video.yaml +0 -11
  259. package/dist/src/vocab/view.yaml +0 -13
  260. package/dist/testing/docloader.test.js +0 -24
  261. package/dist/type-B4NJkfVg.js +0 -42187
  262. package/dist/vocab/actor.test.d.ts +0 -3
  263. package/dist/vocab/actor.test.js +0 -5965
  264. package/dist/vocab/lookup.test.d.ts +0 -3
  265. package/dist/vocab/lookup.test.js +0 -206
  266. package/dist/vocab/mod.cjs +0 -87
  267. package/dist/vocab/mod.d.cts +0 -6
  268. package/dist/vocab/mod.d.ts +0 -8
  269. package/dist/vocab/mod.js +0 -10
  270. package/dist/vocab/schema.yaml +0 -247
  271. package/dist/vocab/type.test.d.ts +0 -3
  272. package/dist/vocab/type.test.js +0 -25
  273. package/dist/vocab/vocab.test.d.ts +0 -3
  274. package/dist/vocab/vocab.test.js +0 -3398
  275. package/dist/vocab-B0-5a8pw.cjs +0 -282
  276. package/dist/vocab-DJTYMqyU.d.cts +0 -14632
  277. package/dist/vocab-SOE1ifCr.d.ts +0 -14634
  278. package/dist/vocab-lBFcVxVF.js +0 -246
  279. package/dist/webfinger/handler.test.d.ts +0 -3
  280. package/dist/webfinger/lookup.test.d.ts +0 -3
  281. package/dist/webfinger/lookup.test.js +0 -195
  282. package/dist/webfinger/mod.cjs +0 -9
  283. package/dist/webfinger/mod.d.cts +0 -4
  284. package/dist/webfinger/mod.d.ts +0 -6
  285. package/dist/webfinger/mod.js +0 -9
  286. package/dist/webfinger-BjOEdFPs.cjs +0 -4
  287. package/dist/webfinger-De_bU0iE.js +0 -4
  288. package/dist/x/cfworkers.cjs +0 -100
  289. package/dist/x/cfworkers.d.cts +0 -59
  290. package/dist/x/cfworkers.d.ts +0 -61
  291. package/dist/x/cfworkers.js +0 -98
  292. package/dist/x/cfworkers.test.d.ts +0 -3
  293. package/dist/x/cfworkers.test.js +0 -179
  294. package/dist/x/hono.cjs +0 -61
  295. package/dist/x/hono.d.cts +0 -54
  296. package/dist/x/hono.d.ts +0 -56
  297. package/dist/x/hono.js +0 -60
  298. package/dist/x/sveltekit.cjs +0 -69
  299. package/dist/x/sveltekit.d.cts +0 -46
  300. package/dist/x/sveltekit.d.ts +0 -48
  301. package/dist/x/sveltekit.js +0 -68
  302. /package/dist/{runtime/authdocloader.test.d.ts → federation/idempotency.test.d.ts} +0 -0
  303. /package/dist/{runtime/docloader.test.d.ts → federation/negotiation.test.d.ts} +0 -0
  304. /package/dist/{runtime/key.test.d.ts → federation/webfinger.test.d.ts} +0 -0
  305. /package/dist/{mod-1pDWKvUL.d.ts → mod-1E3W847c.d.ts} +0 -0
  306. /package/dist/{mod-C2tOeRkN.d.cts → mod-C81L6_lQ.d.cts} +0 -0
  307. /package/dist/{nodeinfo-DfycQ8Wf.js → nodeinfo-BlLsRSiT.js} +0 -0
  308. /package/dist/{nodeinfo-Co9lJrWl.cjs → nodeinfo-DuMYTpbZ.cjs} +0 -0
  309. /package/dist/{runtime/langstr.test.d.ts → otel/exporter.test.d.ts} +0 -0
  310. /package/dist/{retry-CfF8Gn4d.js → retry-D4GJ670a.js} +0 -0
  311. /package/dist/{runtime-DPYEDf-o.js → sig-CwuONEzF.js} +0 -0
  312. /package/dist/{runtime-C58AJWSv.cjs → sig-DeXX2xnj.cjs} +0 -0
  313. /package/dist/{testing → utils}/docloader.test.d.ts +0 -0
  314. /package/dist/{runtime/link.test.d.ts → utils/kv-cache.test.d.ts} +0 -0
  315. /package/dist/{sig-ByHXzqUi.cjs → utils-Db0ZmjcD.cjs} +0 -0
  316. /package/dist/{sig-Cj3tk-ig.js → utils-Wranxuoe.js} +0 -0
@@ -1,3398 +0,0 @@
1
-
2
- import { Temporal } from "@js-temporal/polyfill";
3
- import { URLPattern } from "urlpattern-polyfill";
4
- globalThis.addEventListener = () => {};
5
-
6
- import { Activity, Announce, Collection, Create, CryptographicKey, Follow, Hashtag, LanguageString, Link, Note, Object as Object$1, OrderedCollectionPage, Person, Place, Question, Source, decode, vocab_exports } from "../type-B4NJkfVg.js";
7
- import { assertEquals } from "../assert_equals-DSbWqCm3.js";
8
- import { assert } from "../assert-MZs1qjMx.js";
9
- import { assertInstanceOf } from "../assert_instance_of-DHz7EHNU.js";
10
- import "../lookup-CiU3QxQz.js";
11
- import { mockDocumentLoader, test } from "../testing-ByQmUvf-.js";
12
- import "../std__assert-DWivtrGR.js";
13
- import { assertFalse, assertRejects } from "../assert_rejects-7UF4R_Qs.js";
14
- import "../assert_is_error-B035L3om.js";
15
- import { assertNotEquals } from "../assert_not_equals-C80BG-_5.js";
16
- import { assertThrows } from "../assert_throws-53_pKeP3.js";
17
- import { ed25519PublicKey, rsaPublicKey1 } from "../keys-CBKbYaJA.js";
18
- import { pascalCase } from "es-toolkit";
19
- import { Validator } from "@cfworker/json-schema";
20
- import { readFile, readdir } from "node:fs/promises";
21
- import { join } from "node:path";
22
-
23
- //#region ../../node_modules/.pnpm/@jsr+std__internal@1.0.10/node_modules/@jsr/std__internal/_os.js
24
- function checkWindows() {
25
- const global = globalThis;
26
- const os = global.Deno?.build?.os;
27
- return typeof os === "string" ? os === "windows" : global.navigator?.platform?.startsWith("Win") ?? global.process?.platform?.startsWith("win") ?? false;
28
- }
29
-
30
- //#endregion
31
- //#region ../../node_modules/.pnpm/@jsr+std__internal@1.0.10/node_modules/@jsr/std__internal/os.js
32
- /** Whether the current platform is Windows */ const isWindows = checkWindows();
33
-
34
- //#endregion
35
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.2/node_modules/@jsr/std__path/_common/from_file_url.js
36
- function assertArg$3(url) {
37
- url = url instanceof URL ? url : new URL(url);
38
- if (url.protocol !== "file:") throw new TypeError(`URL must be a file URL: received "${url.protocol}"`);
39
- return url;
40
- }
41
-
42
- //#endregion
43
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.2/node_modules/@jsr/std__path/posix/from_file_url.js
44
- /**
45
- * Converts a file URL to a path string.
46
- *
47
- * @example Usage
48
- * ```ts
49
- * import { fromFileUrl } from "@std/path/posix/from-file-url";
50
- * import { assertEquals } from "@std/assert";
51
- *
52
- * assertEquals(fromFileUrl(new URL("file:///home/foo")), "/home/foo");
53
- * ```
54
- *
55
- * @param url The file URL to convert.
56
- * @returns The path string.
57
- */ function fromFileUrl$2(url) {
58
- url = assertArg$3(url);
59
- return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"));
60
- }
61
-
62
- //#endregion
63
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.2/node_modules/@jsr/std__path/windows/from_file_url.js
64
- /**
65
- * Converts a file URL to a path string.
66
- *
67
- * @example Usage
68
- * ```ts
69
- * import { fromFileUrl } from "@std/path/windows/from-file-url";
70
- * import { assertEquals } from "@std/assert";
71
- *
72
- * assertEquals(fromFileUrl("file:///home/foo"), "\\home\\foo");
73
- * assertEquals(fromFileUrl("file:///C:/Users/foo"), "C:\\Users\\foo");
74
- * assertEquals(fromFileUrl("file://localhost/home/foo"), "\\home\\foo");
75
- * ```
76
- *
77
- * @param url The file URL to convert.
78
- * @returns The path string.
79
- */ function fromFileUrl$3(url) {
80
- url = assertArg$3(url);
81
- let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
82
- if (url.hostname !== "") path = `\\\\${url.hostname}${path}`;
83
- return path;
84
- }
85
-
86
- //#endregion
87
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.2/node_modules/@jsr/std__path/from_file_url.js
88
- /**
89
- * Converts a file URL to a path string.
90
- *
91
- * @example Usage
92
- * ```ts
93
- * import { fromFileUrl } from "@std/path/from-file-url";
94
- * import { assertEquals } from "@std/assert";
95
- *
96
- * if (Deno.build.os === "windows") {
97
- * assertEquals(fromFileUrl("file:///home/foo"), "\\home\\foo");
98
- * assertEquals(fromFileUrl("file:///C:/Users/foo"), "C:\\Users\\foo");
99
- * assertEquals(fromFileUrl("file://localhost/home/foo"), "\\home\\foo");
100
- * } else {
101
- * assertEquals(fromFileUrl("file:///home/foo"), "/home/foo");
102
- * }
103
- * ```
104
- *
105
- * @param url The file URL to convert to a path.
106
- * @returns The path string.
107
- */ function fromFileUrl(url) {
108
- return isWindows ? fromFileUrl$3(url) : fromFileUrl$2(url);
109
- }
110
-
111
- //#endregion
112
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/assert_path.js
113
- function assertPath(path) {
114
- if (typeof path !== "string") throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`);
115
- }
116
-
117
- //#endregion
118
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/from_file_url.js
119
- function assertArg$2(url) {
120
- url = url instanceof URL ? url : new URL(url);
121
- if (url.protocol !== "file:") throw new TypeError(`URL must be a file URL: received "${url.protocol}"`);
122
- return url;
123
- }
124
-
125
- //#endregion
126
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/posix/from_file_url.js
127
- /**
128
- * Converts a file URL to a path string.
129
- *
130
- * @example Usage
131
- * ```ts
132
- * import { fromFileUrl } from "@std/path/posix/from-file-url";
133
- * import { assertEquals } from "@std/assert";
134
- *
135
- * assertEquals(fromFileUrl(new URL("file:///home/foo")), "/home/foo");
136
- * ```
137
- *
138
- * @param url The file URL to convert.
139
- * @returns The path string.
140
- */ function fromFileUrl$1(url) {
141
- url = assertArg$2(url);
142
- return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"));
143
- }
144
-
145
- //#endregion
146
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/strip_trailing_separators.js
147
- function stripTrailingSeparators(segment, isSep) {
148
- if (segment.length <= 1) return segment;
149
- let end = segment.length;
150
- for (let i = segment.length - 1; i > 0; i--) if (isSep(segment.charCodeAt(i))) end = i;
151
- else break;
152
- return segment.slice(0, end);
153
- }
154
-
155
- //#endregion
156
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/constants.js
157
- const CHAR_DOT = 46;
158
- const CHAR_FORWARD_SLASH = 47;
159
-
160
- //#endregion
161
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/posix/_util.js
162
- function isPosixPathSeparator(code) {
163
- return code === CHAR_FORWARD_SLASH;
164
- }
165
-
166
- //#endregion
167
- //#region ../../node_modules/.pnpm/@jsr+std__url@1.0.0-rc.3/node_modules/@jsr/std__url/_strip.js
168
- /**
169
- * Strips any hash (eg. `#header`) or search parameters (eg. `?foo=bar`) from the provided URL.
170
- *
171
- * (Mutates the original url provided)
172
- * @param url to be stripped.
173
- */ function strip(url) {
174
- url.hash = "";
175
- url.search = "";
176
- }
177
-
178
- //#endregion
179
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/dirname.js
180
- function assertArg$1(path) {
181
- assertPath(path);
182
- if (path.length === 0) return ".";
183
- }
184
-
185
- //#endregion
186
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/posix/dirname.js
187
- /**
188
- * Return the directory path of a `path`.
189
- *
190
- * @example Usage
191
- * ```ts
192
- * import { dirname } from "@std/path/posix/dirname";
193
- * import { assertEquals } from "@std/assert";
194
- *
195
- * assertEquals(dirname("/home/user/Documents/"), "/home/user");
196
- * assertEquals(dirname("/home/user/Documents/image.png"), "/home/user/Documents");
197
- * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path");
198
- * assertEquals(dirname(new URL("file:///home/user/Documents/image.png")), "/home/user/Documents");
199
- * ```
200
- *
201
- * @example Working with URLs
202
- *
203
- * ```ts
204
- * import { dirname } from "@std/path/posix/dirname";
205
- * import { assertEquals } from "@std/assert";
206
- *
207
- * assertEquals(dirname("https://deno.land/std/path/mod.ts"), "https://deno.land/std/path");
208
- * assertEquals(dirname("https://deno.land/std/path/mod.ts?a=b"), "https://deno.land/std/path");
209
- * assertEquals(dirname("https://deno.land/std/path/mod.ts#header"), "https://deno.land/std/path");
210
- * ```
211
- *
212
- * @param path The path to get the directory from.
213
- * @returns The directory path.
214
- */ function dirname(path) {
215
- if (path instanceof URL) path = fromFileUrl$1(path);
216
- assertArg$1(path);
217
- let end = -1;
218
- let matchedNonSeparator = false;
219
- for (let i = path.length - 1; i >= 1; --i) if (isPosixPathSeparator(path.charCodeAt(i))) {
220
- if (matchedNonSeparator) {
221
- end = i;
222
- break;
223
- }
224
- } else matchedNonSeparator = true;
225
- if (end === -1) return isPosixPathSeparator(path.charCodeAt(0)) ? "/" : ".";
226
- return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator);
227
- }
228
-
229
- //#endregion
230
- //#region ../../node_modules/.pnpm/@jsr+std__url@1.0.0-rc.3/node_modules/@jsr/std__url/dirname.js
231
- /**
232
- * Returns the directory path URL of a URL or URL string.
233
- *
234
- * The directory path is the portion of a URL up to but excluding the final path
235
- * segment. URL queries and hashes are ignored.
236
- *
237
- * @param url URL to extract the directory from.
238
- * @returns The directory path URL of the URL.
239
- *
240
- * @example Usage
241
- * ```ts
242
- * import { dirname } from "@std/url/dirname";
243
- * import { assertEquals } from "@std/assert";
244
- *
245
- * assertEquals(dirname("https://deno.land/std/path/mod.ts"), new URL("https://deno.land/std/path"));
246
- * assertEquals(dirname(new URL("https://deno.land/std/path/mod.ts")), new URL("https://deno.land/std/path"));
247
- * ```
248
- *
249
- * @deprecated Use
250
- * {@linkcode https://jsr.io/@std/path/doc/posix/~/dirname | @std/path/posix/dirname}
251
- * instead (examples included). `@std/url` will be removed in the future.
252
- */ function dirname$1(url) {
253
- url = new URL(url);
254
- strip(url);
255
- url.pathname = dirname(url.pathname);
256
- return url;
257
- }
258
-
259
- //#endregion
260
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/normalize.js
261
- function assertArg(path) {
262
- assertPath(path);
263
- if (path.length === 0) return ".";
264
- }
265
-
266
- //#endregion
267
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/_common/normalize_string.js
268
- function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
269
- let res = "";
270
- let lastSegmentLength = 0;
271
- let lastSlash = -1;
272
- let dots = 0;
273
- let code;
274
- for (let i = 0; i <= path.length; ++i) {
275
- if (i < path.length) code = path.charCodeAt(i);
276
- else if (isPathSeparator(code)) break;
277
- else code = CHAR_FORWARD_SLASH;
278
- if (isPathSeparator(code)) {
279
- if (lastSlash === i - 1 || dots === 1) {} else if (lastSlash !== i - 1 && dots === 2) {
280
- if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
281
- if (res.length > 2) {
282
- const lastSlashIndex = res.lastIndexOf(separator);
283
- if (lastSlashIndex === -1) {
284
- res = "";
285
- lastSegmentLength = 0;
286
- } else {
287
- res = res.slice(0, lastSlashIndex);
288
- lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
289
- }
290
- lastSlash = i;
291
- dots = 0;
292
- continue;
293
- } else if (res.length === 2 || res.length === 1) {
294
- res = "";
295
- lastSegmentLength = 0;
296
- lastSlash = i;
297
- dots = 0;
298
- continue;
299
- }
300
- }
301
- if (allowAboveRoot) {
302
- if (res.length > 0) res += `${separator}..`;
303
- else res = "..";
304
- lastSegmentLength = 2;
305
- }
306
- } else {
307
- if (res.length > 0) res += separator + path.slice(lastSlash + 1, i);
308
- else res = path.slice(lastSlash + 1, i);
309
- lastSegmentLength = i - lastSlash - 1;
310
- }
311
- lastSlash = i;
312
- dots = 0;
313
- } else if (code === CHAR_DOT && dots !== -1) ++dots;
314
- else dots = -1;
315
- }
316
- return res;
317
- }
318
-
319
- //#endregion
320
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/posix/normalize.js
321
- /**
322
- * Normalize the `path`, resolving `'..'` and `'.'` segments.
323
- * Note that resolving these segments does not necessarily mean that all will be eliminated.
324
- * A `'..'` at the top-level will be preserved, and an empty path is canonically `'.'`.
325
- *
326
- * @example Usage
327
- * ```ts
328
- * import { normalize } from "@std/path/posix/normalize";
329
- * import { assertEquals } from "@std/assert";
330
- *
331
- * assertEquals(normalize("/foo/bar//baz/asdf/quux/.."), "/foo/bar/baz/asdf");
332
- * assertEquals(normalize(new URL("file:///foo/bar//baz/asdf/quux/..")), "/foo/bar/baz/asdf/");
333
- * ```
334
- *
335
- * @example Working with URLs
336
- *
337
- * Note: This function will remove the double slashes from a URL's scheme.
338
- * Hence, do not pass a full URL to this function. Instead, pass the pathname of
339
- * the URL.
340
- *
341
- * ```ts
342
- * import { normalize } from "@std/path/posix/normalize";
343
- * import { assertEquals } from "@std/assert";
344
- *
345
- * const url = new URL("https://deno.land");
346
- * url.pathname = normalize("//std//assert//.//mod.ts");
347
- * assertEquals(url.href, "https://deno.land/std/assert/mod.ts");
348
- *
349
- * url.pathname = normalize("std/assert/../async/retry.ts");
350
- * assertEquals(url.href, "https://deno.land/std/async/retry.ts");
351
- * ```
352
- *
353
- * @param path The path to normalize.
354
- * @returns The normalized path.
355
- */ function normalize(path) {
356
- if (path instanceof URL) path = fromFileUrl$1(path);
357
- assertArg(path);
358
- const isAbsolute = isPosixPathSeparator(path.charCodeAt(0));
359
- const trailingSeparator = isPosixPathSeparator(path.charCodeAt(path.length - 1));
360
- path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
361
- if (path.length === 0 && !isAbsolute) path = ".";
362
- if (path.length > 0 && trailingSeparator) path += "/";
363
- if (isAbsolute) return `/${path}`;
364
- return path;
365
- }
366
-
367
- //#endregion
368
- //#region ../../node_modules/.pnpm/@jsr+std__path@1.1.0/node_modules/@jsr/std__path/posix/join.js
369
- /**
370
- * Join all given a sequence of `paths`,then normalizes the resulting path.
371
- *
372
- * @example Usage
373
- * ```ts
374
- * import { join } from "@std/path/posix/join";
375
- * import { assertEquals } from "@std/assert";
376
- *
377
- * assertEquals(join("/foo", "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf");
378
- * assertEquals(join(new URL("file:///foo"), "bar", "baz/asdf", "quux", ".."), "/foo/bar/baz/asdf");
379
- * ```
380
- *
381
- * @example Working with URLs
382
- * ```ts
383
- * import { join } from "@std/path/posix/join";
384
- * import { assertEquals } from "@std/assert";
385
- *
386
- * const url = new URL("https://deno.land");
387
- * url.pathname = join("std", "path", "mod.ts");
388
- * assertEquals(url.href, "https://deno.land/std/path/mod.ts");
389
- *
390
- * url.pathname = join("//std", "path/", "/mod.ts");
391
- * assertEquals(url.href, "https://deno.land/std/path/mod.ts");
392
- * ```
393
- *
394
- * @param path The path to join. This can be string or file URL.
395
- * @param paths The paths to join.
396
- * @returns The joined path.
397
- */ function join$1(path, ...paths) {
398
- if (path === void 0) return ".";
399
- if (path instanceof URL) path = fromFileUrl$1(path);
400
- paths = path ? [path, ...paths] : paths;
401
- paths.forEach((path$1) => assertPath(path$1));
402
- const joined = paths.filter((path$1) => path$1.length > 0).join("/");
403
- return joined === "" ? "." : normalize(joined);
404
- }
405
-
406
- //#endregion
407
- //#region ../../node_modules/.pnpm/@jsr+std__url@1.0.0-rc.3/node_modules/@jsr/std__url/join.js
408
- /**
409
- * Joins a base URL or URL string, and a sequence of path segments together,
410
- * then normalizes the resulting URL.
411
- *
412
- * @param url Base URL to be joined with the paths and normalized.
413
- * @param paths Array of path segments to be joined to the base URL.
414
- * @returns A complete URL containing the base URL joined with the paths.
415
- *
416
- * @example Usage
417
- *
418
- * ```ts
419
- * import { join } from "@std/url/join";
420
- * import { assertEquals } from "@std/assert";
421
- *
422
- * assertEquals(join("https://deno.land/", "std", "path", "mod.ts").href, "https://deno.land/std/path/mod.ts");
423
- * assertEquals(join("https://deno.land", "//std", "path/", "/mod.ts").href, "https://deno.land/std/path/mod.ts");
424
- * ```
425
- *
426
- * @deprecated Use
427
- * {@linkcode https://jsr.io/@std/path/doc/posix/~/join | @std/path/posix/join}
428
- * instead (examples included). `@std/url` will be removed in the future.
429
- */ function join$2(url, ...paths) {
430
- url = new URL(url);
431
- url.pathname = join$1(url.pathname, ...paths);
432
- return url;
433
- }
434
-
435
- //#endregion
436
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_chars.js
437
- const TAB = 9;
438
- const LINE_FEED = 10;
439
- const CARRIAGE_RETURN = 13;
440
- const SPACE = 32;
441
- const EXCLAMATION = 33;
442
- const DOUBLE_QUOTE = 34;
443
- const SHARP = 35;
444
- const PERCENT = 37;
445
- const AMPERSAND = 38;
446
- const SINGLE_QUOTE = 39;
447
- const ASTERISK = 42;
448
- const PLUS = 43;
449
- const COMMA = 44;
450
- const MINUS = 45;
451
- const DOT = 46;
452
- const COLON = 58;
453
- const SMALLER_THAN = 60;
454
- const GREATER_THAN = 62;
455
- const QUESTION = 63;
456
- const COMMERCIAL_AT = 64;
457
- const LEFT_SQUARE_BRACKET = 91;
458
- const BACKSLASH = 92;
459
- const RIGHT_SQUARE_BRACKET = 93;
460
- const GRAVE_ACCENT = 96;
461
- const LEFT_CURLY_BRACKET = 123;
462
- const VERTICAL_LINE = 124;
463
- const RIGHT_CURLY_BRACKET = 125;
464
- function isEOL(c) {
465
- return c === LINE_FEED || c === CARRIAGE_RETURN;
466
- }
467
- function isWhiteSpace(c) {
468
- return c === TAB || c === SPACE;
469
- }
470
- function isWhiteSpaceOrEOL(c) {
471
- return isWhiteSpace(c) || isEOL(c);
472
- }
473
- function isFlowIndicator(c) {
474
- return c === COMMA || c === LEFT_SQUARE_BRACKET || c === RIGHT_SQUARE_BRACKET || c === LEFT_CURLY_BRACKET || c === RIGHT_CURLY_BRACKET;
475
- }
476
-
477
- //#endregion
478
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/binary.js
479
- const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
480
- function resolveYamlBinary(data) {
481
- if (data === null) return false;
482
- let code;
483
- let bitlen = 0;
484
- const max = data.length;
485
- const map$1 = BASE64_MAP;
486
- for (let idx = 0; idx < max; idx++) {
487
- code = map$1.indexOf(data.charAt(idx));
488
- if (code > 64) continue;
489
- if (code < 0) return false;
490
- bitlen += 6;
491
- }
492
- return bitlen % 8 === 0;
493
- }
494
- function constructYamlBinary(data) {
495
- const input = data.replace(/[\r\n=]/g, "");
496
- const max = input.length;
497
- const map$1 = BASE64_MAP;
498
- const result = [];
499
- let bits = 0;
500
- for (let idx = 0; idx < max; idx++) {
501
- if (idx % 4 === 0 && idx) {
502
- result.push(bits >> 16 & 255);
503
- result.push(bits >> 8 & 255);
504
- result.push(bits & 255);
505
- }
506
- bits = bits << 6 | map$1.indexOf(input.charAt(idx));
507
- }
508
- const tailbits = max % 4 * 6;
509
- if (tailbits === 0) {
510
- result.push(bits >> 16 & 255);
511
- result.push(bits >> 8 & 255);
512
- result.push(bits & 255);
513
- } else if (tailbits === 18) {
514
- result.push(bits >> 10 & 255);
515
- result.push(bits >> 2 & 255);
516
- } else if (tailbits === 12) result.push(bits >> 4 & 255);
517
- return new Uint8Array(result);
518
- }
519
- function representYamlBinary(object) {
520
- const max = object.length;
521
- const map$1 = BASE64_MAP;
522
- let result = "";
523
- let bits = 0;
524
- for (let idx = 0; idx < max; idx++) {
525
- if (idx % 3 === 0 && idx) {
526
- result += map$1[bits >> 18 & 63];
527
- result += map$1[bits >> 12 & 63];
528
- result += map$1[bits >> 6 & 63];
529
- result += map$1[bits & 63];
530
- }
531
- bits = (bits << 8) + object[idx];
532
- }
533
- const tail = max % 3;
534
- if (tail === 0) {
535
- result += map$1[bits >> 18 & 63];
536
- result += map$1[bits >> 12 & 63];
537
- result += map$1[bits >> 6 & 63];
538
- result += map$1[bits & 63];
539
- } else if (tail === 2) {
540
- result += map$1[bits >> 10 & 63];
541
- result += map$1[bits >> 4 & 63];
542
- result += map$1[bits << 2 & 63];
543
- result += map$1[64];
544
- } else if (tail === 1) {
545
- result += map$1[bits >> 2 & 63];
546
- result += map$1[bits << 4 & 63];
547
- result += map$1[64];
548
- result += map$1[64];
549
- }
550
- return result;
551
- }
552
- function isBinary(obj) {
553
- return obj instanceof Uint8Array;
554
- }
555
- const binary = {
556
- tag: "tag:yaml.org,2002:binary",
557
- construct: constructYamlBinary,
558
- kind: "scalar",
559
- predicate: isBinary,
560
- represent: representYamlBinary,
561
- resolve: resolveYamlBinary
562
- };
563
-
564
- //#endregion
565
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/bool.js
566
- const YAML_TRUE_BOOLEANS = [
567
- "true",
568
- "True",
569
- "TRUE"
570
- ];
571
- const YAML_FALSE_BOOLEANS = [
572
- "false",
573
- "False",
574
- "FALSE"
575
- ];
576
- const YAML_BOOLEANS = [...YAML_TRUE_BOOLEANS, ...YAML_FALSE_BOOLEANS];
577
- const bool = {
578
- tag: "tag:yaml.org,2002:bool",
579
- kind: "scalar",
580
- defaultStyle: "lowercase",
581
- predicate: (value) => typeof value === "boolean" || value instanceof Boolean,
582
- construct: (data) => YAML_TRUE_BOOLEANS.includes(data),
583
- resolve: (data) => YAML_BOOLEANS.includes(data),
584
- represent: {
585
- lowercase: (object) => {
586
- const value = object instanceof Boolean ? object.valueOf() : object;
587
- return value ? "true" : "false";
588
- },
589
- uppercase: (object) => {
590
- const value = object instanceof Boolean ? object.valueOf() : object;
591
- return value ? "TRUE" : "FALSE";
592
- },
593
- camelcase: (object) => {
594
- const value = object instanceof Boolean ? object.valueOf() : object;
595
- return value ? "True" : "False";
596
- }
597
- }
598
- };
599
-
600
- //#endregion
601
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_utils.js
602
- function isObject(value) {
603
- return value !== null && typeof value === "object";
604
- }
605
- function isNegativeZero(i) {
606
- return i === 0 && Number.NEGATIVE_INFINITY === 1 / i;
607
- }
608
- function isPlainObject(object) {
609
- return Object.prototype.toString.call(object) === "[object Object]";
610
- }
611
-
612
- //#endregion
613
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/float.js
614
- const YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
615
- function resolveYamlFloat(data) {
616
- if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") return false;
617
- return true;
618
- }
619
- function constructYamlFloat(data) {
620
- let value = data.replace(/_/g, "").toLowerCase();
621
- const sign = value[0] === "-" ? -1 : 1;
622
- if (value[0] && "+-".includes(value[0])) value = value.slice(1);
623
- if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
624
- if (value === ".nan") return NaN;
625
- return sign * parseFloat(value);
626
- }
627
- const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
628
- function representYamlFloat(object, style) {
629
- const value = object instanceof Number ? object.valueOf() : object;
630
- if (isNaN(value)) switch (style) {
631
- case "lowercase": return ".nan";
632
- case "uppercase": return ".NAN";
633
- case "camelcase": return ".NaN";
634
- }
635
- else if (Number.POSITIVE_INFINITY === value) switch (style) {
636
- case "lowercase": return ".inf";
637
- case "uppercase": return ".INF";
638
- case "camelcase": return ".Inf";
639
- }
640
- else if (Number.NEGATIVE_INFINITY === value) switch (style) {
641
- case "lowercase": return "-.inf";
642
- case "uppercase": return "-.INF";
643
- case "camelcase": return "-.Inf";
644
- }
645
- else if (isNegativeZero(value)) return "-0.0";
646
- const res = value.toString(10);
647
- return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
648
- }
649
- function isFloat(object) {
650
- if (object instanceof Number) object = object.valueOf();
651
- return typeof object === "number" && (object % 1 !== 0 || isNegativeZero(object));
652
- }
653
- const float = {
654
- tag: "tag:yaml.org,2002:float",
655
- construct: constructYamlFloat,
656
- defaultStyle: "lowercase",
657
- kind: "scalar",
658
- predicate: isFloat,
659
- represent: representYamlFloat,
660
- resolve: resolveYamlFloat
661
- };
662
-
663
- //#endregion
664
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/int.js
665
- function isCharCodeInRange(c, lower, upper) {
666
- return lower <= c && c <= upper;
667
- }
668
- function isHexCode(c) {
669
- return isCharCodeInRange(c, 48, 57) || isCharCodeInRange(c, 65, 70) || isCharCodeInRange(c, 97, 102);
670
- }
671
- function isOctCode(c) {
672
- return isCharCodeInRange(c, 48, 55);
673
- }
674
- function isDecCode(c) {
675
- return isCharCodeInRange(c, 48, 57);
676
- }
677
- function resolveYamlInteger(data) {
678
- const max = data.length;
679
- let index = 0;
680
- let hasDigits = false;
681
- if (!max) return false;
682
- let ch = data[index];
683
- if (ch === "-" || ch === "+") ch = data[++index];
684
- if (ch === "0") {
685
- if (index + 1 === max) return true;
686
- ch = data[++index];
687
- if (ch === "b") {
688
- index++;
689
- for (; index < max; index++) {
690
- ch = data[index];
691
- if (ch === "_") continue;
692
- if (ch !== "0" && ch !== "1") return false;
693
- hasDigits = true;
694
- }
695
- return hasDigits && ch !== "_";
696
- }
697
- if (ch === "x") {
698
- index++;
699
- for (; index < max; index++) {
700
- ch = data[index];
701
- if (ch === "_") continue;
702
- if (!isHexCode(data.charCodeAt(index))) return false;
703
- hasDigits = true;
704
- }
705
- return hasDigits && ch !== "_";
706
- }
707
- for (; index < max; index++) {
708
- ch = data[index];
709
- if (ch === "_") continue;
710
- if (!isOctCode(data.charCodeAt(index))) return false;
711
- hasDigits = true;
712
- }
713
- return hasDigits && ch !== "_";
714
- }
715
- if (ch === "_") return false;
716
- for (; index < max; index++) {
717
- ch = data[index];
718
- if (ch === "_") continue;
719
- if (!isDecCode(data.charCodeAt(index))) return false;
720
- hasDigits = true;
721
- }
722
- if (!hasDigits || ch === "_") return false;
723
- return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
724
- }
725
- function constructYamlInteger(data) {
726
- let value = data;
727
- if (value.includes("_")) value = value.replace(/_/g, "");
728
- let sign = 1;
729
- let ch = value[0];
730
- if (ch === "-" || ch === "+") {
731
- if (ch === "-") sign = -1;
732
- value = value.slice(1);
733
- ch = value[0];
734
- }
735
- if (value === "0") return 0;
736
- if (ch === "0") {
737
- if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
738
- if (value[1] === "x") return sign * parseInt(value, 16);
739
- return sign * parseInt(value, 8);
740
- }
741
- return sign * parseInt(value, 10);
742
- }
743
- function isInteger(object) {
744
- if (object instanceof Number) object = object.valueOf();
745
- return typeof object === "number" && object % 1 === 0 && !isNegativeZero(object);
746
- }
747
- const int = {
748
- tag: "tag:yaml.org,2002:int",
749
- construct: constructYamlInteger,
750
- defaultStyle: "decimal",
751
- kind: "scalar",
752
- predicate: isInteger,
753
- represent: {
754
- binary(object) {
755
- const value = object instanceof Number ? object.valueOf() : object;
756
- return value >= 0 ? `0b${value.toString(2)}` : `-0b${value.toString(2).slice(1)}`;
757
- },
758
- octal(object) {
759
- const value = object instanceof Number ? object.valueOf() : object;
760
- return value >= 0 ? `0${value.toString(8)}` : `-0${value.toString(8).slice(1)}`;
761
- },
762
- decimal(object) {
763
- const value = object instanceof Number ? object.valueOf() : object;
764
- return value.toString(10);
765
- },
766
- hexadecimal(object) {
767
- const value = object instanceof Number ? object.valueOf() : object;
768
- return value >= 0 ? `0x${value.toString(16).toUpperCase()}` : `-0x${value.toString(16).toUpperCase().slice(1)}`;
769
- }
770
- },
771
- resolve: resolveYamlInteger
772
- };
773
-
774
- //#endregion
775
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/map.js
776
- const map = {
777
- tag: "tag:yaml.org,2002:map",
778
- resolve() {
779
- return true;
780
- },
781
- construct(data) {
782
- return data !== null ? data : {};
783
- },
784
- kind: "mapping"
785
- };
786
-
787
- //#endregion
788
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/merge.js
789
- const merge = {
790
- tag: "tag:yaml.org,2002:merge",
791
- kind: "scalar",
792
- resolve: (data) => data === "<<" || data === null,
793
- construct: (data) => data
794
- };
795
-
796
- //#endregion
797
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/nil.js
798
- const nil = {
799
- tag: "tag:yaml.org,2002:null",
800
- kind: "scalar",
801
- defaultStyle: "lowercase",
802
- predicate: (object) => object === null,
803
- construct: () => null,
804
- resolve: (data) => {
805
- return data === "~" || data === "null" || data === "Null" || data === "NULL";
806
- },
807
- represent: {
808
- lowercase: () => "null",
809
- uppercase: () => "NULL",
810
- camelcase: () => "Null"
811
- }
812
- };
813
-
814
- //#endregion
815
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/omap.js
816
- function resolveYamlOmap(data) {
817
- const objectKeys = /* @__PURE__ */ new Set();
818
- for (const object of data) {
819
- if (!isPlainObject(object)) return false;
820
- const keys = Object.keys(object);
821
- if (keys.length !== 1) return false;
822
- for (const key of keys) {
823
- if (objectKeys.has(key)) return false;
824
- objectKeys.add(key);
825
- }
826
- }
827
- return true;
828
- }
829
- const omap = {
830
- tag: "tag:yaml.org,2002:omap",
831
- kind: "sequence",
832
- resolve: resolveYamlOmap,
833
- construct(data) {
834
- return data;
835
- }
836
- };
837
-
838
- //#endregion
839
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/pairs.js
840
- function resolveYamlPairs(data) {
841
- if (data === null) return true;
842
- return data.every((it) => isPlainObject(it) && Object.keys(it).length === 1);
843
- }
844
- const pairs = {
845
- tag: "tag:yaml.org,2002:pairs",
846
- construct(data) {
847
- return data?.flatMap(Object.entries) ?? [];
848
- },
849
- kind: "sequence",
850
- resolve: resolveYamlPairs
851
- };
852
-
853
- //#endregion
854
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/regexp.js
855
- const REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;
856
- const regexp = {
857
- tag: "tag:yaml.org,2002:js/regexp",
858
- kind: "scalar",
859
- resolve(data) {
860
- if (data === null || !data.length) return false;
861
- if (data.charAt(0) === "/") {
862
- const groups = data.match(REGEXP)?.groups;
863
- if (!groups) return false;
864
- const modifiers = groups.modifiers ?? "";
865
- if (new Set(modifiers).size < modifiers.length) return false;
866
- }
867
- return true;
868
- },
869
- construct(data) {
870
- const { regexp: regexp$1 = data, modifiers = "" } = data.match(REGEXP)?.groups ?? {};
871
- return new RegExp(regexp$1, modifiers);
872
- },
873
- predicate: (object) => object instanceof RegExp,
874
- represent: (object) => object.toString()
875
- };
876
-
877
- //#endregion
878
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/seq.js
879
- const seq = {
880
- tag: "tag:yaml.org,2002:seq",
881
- kind: "sequence",
882
- resolve: () => true,
883
- construct: (data) => data !== null ? data : []
884
- };
885
-
886
- //#endregion
887
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/set.js
888
- const set = {
889
- tag: "tag:yaml.org,2002:set",
890
- kind: "mapping",
891
- construct: (data) => data !== null ? data : {},
892
- resolve: (data) => {
893
- if (data === null) return true;
894
- return Object.values(data).every((it) => it === null);
895
- }
896
- };
897
-
898
- //#endregion
899
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/str.js
900
- const str = {
901
- tag: "tag:yaml.org,2002:str",
902
- kind: "scalar",
903
- resolve: () => true,
904
- construct: (data) => data !== null ? data : ""
905
- };
906
-
907
- //#endregion
908
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/timestamp.js
909
- const YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
910
- const YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
911
- function resolveYamlTimestamp(data) {
912
- if (data === null) return false;
913
- if (YAML_DATE_REGEXP.exec(data) !== null) return true;
914
- if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
915
- return false;
916
- }
917
- function constructYamlTimestamp(data) {
918
- let match = YAML_DATE_REGEXP.exec(data);
919
- if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
920
- if (match === null) throw new Error("Cannot construct YAML timestamp: date resolve error");
921
- const year = +match[1];
922
- const month = +match[2] - 1;
923
- const day = +match[3];
924
- if (!match[4]) return new Date(Date.UTC(year, month, day));
925
- const hour = +match[4];
926
- const minute = +match[5];
927
- const second = +match[6];
928
- let fraction = 0;
929
- if (match[7]) {
930
- let partFraction = match[7].slice(0, 3);
931
- while (partFraction.length < 3) partFraction += "0";
932
- fraction = +partFraction;
933
- }
934
- let delta = null;
935
- if (match[9] && match[10]) {
936
- const tzHour = +match[10];
937
- const tzMinute = +(match[11] || 0);
938
- delta = (tzHour * 60 + tzMinute) * 6e4;
939
- if (match[9] === "-") delta = -delta;
940
- }
941
- const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
942
- if (delta) date.setTime(date.getTime() - delta);
943
- return date;
944
- }
945
- function representYamlTimestamp(date) {
946
- return date.toISOString();
947
- }
948
- const timestamp = {
949
- tag: "tag:yaml.org,2002:timestamp",
950
- construct: constructYamlTimestamp,
951
- predicate(object) {
952
- return object instanceof Date;
953
- },
954
- kind: "scalar",
955
- represent: representYamlTimestamp,
956
- resolve: resolveYamlTimestamp
957
- };
958
-
959
- //#endregion
960
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_type/undefined.js
961
- const undefinedType = {
962
- tag: "tag:yaml.org,2002:js/undefined",
963
- kind: "scalar",
964
- resolve() {
965
- return true;
966
- },
967
- construct() {
968
- return void 0;
969
- },
970
- predicate(object) {
971
- return typeof object === "undefined";
972
- },
973
- represent() {
974
- return "";
975
- }
976
- };
977
-
978
- //#endregion
979
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_schema.js
980
- function createTypeMap(implicitTypes, explicitTypes) {
981
- const result = {
982
- fallback: /* @__PURE__ */ new Map(),
983
- mapping: /* @__PURE__ */ new Map(),
984
- scalar: /* @__PURE__ */ new Map(),
985
- sequence: /* @__PURE__ */ new Map()
986
- };
987
- const fallbackMap = result.fallback;
988
- for (const type of [...implicitTypes, ...explicitTypes]) {
989
- const map$1 = result[type.kind];
990
- map$1.set(type.tag, type);
991
- fallbackMap.set(type.tag, type);
992
- }
993
- return result;
994
- }
995
- function createSchema({ explicitTypes = [], implicitTypes = [], include }) {
996
- if (include) {
997
- implicitTypes.push(...include.implicitTypes);
998
- explicitTypes.push(...include.explicitTypes);
999
- }
1000
- const typeMap = createTypeMap(implicitTypes, explicitTypes);
1001
- return {
1002
- implicitTypes,
1003
- explicitTypes,
1004
- typeMap
1005
- };
1006
- }
1007
- /**
1008
- * Standard YAML's failsafe schema.
1009
- *
1010
- * @see {@link http://www.yaml.org/spec/1.2/spec.html#id2802346}
1011
- */ const FAILSAFE_SCHEMA = createSchema({ explicitTypes: [
1012
- str,
1013
- seq,
1014
- map
1015
- ] });
1016
- /**
1017
- * Standard YAML's JSON schema.
1018
- *
1019
- * @see {@link http://www.yaml.org/spec/1.2/spec.html#id2803231}
1020
- */ const JSON_SCHEMA = createSchema({
1021
- implicitTypes: [
1022
- nil,
1023
- bool,
1024
- int,
1025
- float
1026
- ],
1027
- include: FAILSAFE_SCHEMA
1028
- });
1029
- /**
1030
- * Standard YAML's core schema.
1031
- *
1032
- * @see {@link http://www.yaml.org/spec/1.2/spec.html#id2804923}
1033
- */ const CORE_SCHEMA = createSchema({ include: JSON_SCHEMA });
1034
- /**
1035
- * Default YAML schema. It is not described in the YAML specification.
1036
- */ const DEFAULT_SCHEMA = createSchema({
1037
- explicitTypes: [
1038
- binary,
1039
- omap,
1040
- pairs,
1041
- set
1042
- ],
1043
- implicitTypes: [timestamp, merge],
1044
- include: CORE_SCHEMA
1045
- });
1046
- /***
1047
- * Extends JS-YAML default schema with additional JavaScript types
1048
- * It is not described in the YAML specification.
1049
- * Functions are no longer supported for security reasons.
1050
- *
1051
- * @example
1052
- * ```ts
1053
- * import { parse } from "@std/yaml";
1054
- *
1055
- * const data = parse(
1056
- * `
1057
- * regexp:
1058
- * simple: !!js/regexp foobar
1059
- * modifiers: !!js/regexp /foobar/mi
1060
- * undefined: !!js/undefined ~
1061
- * `,
1062
- * { schema: "extended" },
1063
- * );
1064
- * ```
1065
- */ const EXTENDED_SCHEMA = createSchema({
1066
- explicitTypes: [regexp, undefinedType],
1067
- include: DEFAULT_SCHEMA
1068
- });
1069
- const SCHEMA_MAP = new Map([
1070
- ["core", CORE_SCHEMA],
1071
- ["default", DEFAULT_SCHEMA],
1072
- ["failsafe", FAILSAFE_SCHEMA],
1073
- ["json", JSON_SCHEMA],
1074
- ["extended", EXTENDED_SCHEMA]
1075
- ]);
1076
-
1077
- //#endregion
1078
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/_loader_state.js
1079
- const CONTEXT_FLOW_IN = 1;
1080
- const CONTEXT_FLOW_OUT = 2;
1081
- const CONTEXT_BLOCK_IN = 3;
1082
- const CONTEXT_BLOCK_OUT = 4;
1083
- const CHOMPING_CLIP = 1;
1084
- const CHOMPING_STRIP = 2;
1085
- const CHOMPING_KEEP = 3;
1086
- const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1087
- const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1088
- const PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
1089
- const PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
1090
- const PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
1091
- const ESCAPED_HEX_LENGTHS = new Map([
1092
- [120, 2],
1093
- [117, 4],
1094
- [85, 8]
1095
- ]);
1096
- const SIMPLE_ESCAPE_SEQUENCES = new Map([
1097
- [48, "\0"],
1098
- [97, "\x07"],
1099
- [98, "\b"],
1100
- [116, " "],
1101
- [9, " "],
1102
- [110, "\n"],
1103
- [118, "\v"],
1104
- [102, "\f"],
1105
- [114, "\r"],
1106
- [101, "\x1B"],
1107
- [32, " "],
1108
- [34, "\""],
1109
- [47, "/"],
1110
- [92, "\\"],
1111
- [78, "…"],
1112
- [95, "\xA0"],
1113
- [76, "\u2028"],
1114
- [80, "\u2029"]
1115
- ]);
1116
- /**
1117
- * Converts a hexadecimal character code to its decimal value.
1118
- */ function hexCharCodeToNumber(charCode) {
1119
- if (48 <= charCode && charCode <= 57) return charCode - 48;
1120
- const lc = charCode | 32;
1121
- if (97 <= lc && lc <= 102) return lc - 97 + 10;
1122
- return -1;
1123
- }
1124
- /**
1125
- * Converts a decimal character code to its decimal value.
1126
- */ function decimalCharCodeToNumber(charCode) {
1127
- if (48 <= charCode && charCode <= 57) return charCode - 48;
1128
- return -1;
1129
- }
1130
- /**
1131
- * Converts a Unicode code point to a string.
1132
- */ function codepointToChar(codepoint) {
1133
- if (codepoint <= 65535) return String.fromCharCode(codepoint);
1134
- return String.fromCharCode((codepoint - 65536 >> 10) + 55296, (codepoint - 65536 & 1023) + 56320);
1135
- }
1136
- const INDENT = 4;
1137
- const MAX_LENGTH = 75;
1138
- const DELIMITERS = "\0\r\n…\u2028\u2029";
1139
- function getSnippet(buffer, position) {
1140
- if (!buffer) return null;
1141
- let start = position;
1142
- let end = position;
1143
- let head = "";
1144
- let tail = "";
1145
- while (start > 0 && !DELIMITERS.includes(buffer.charAt(start - 1))) {
1146
- start--;
1147
- if (position - start > MAX_LENGTH / 2 - 1) {
1148
- head = " ... ";
1149
- start += 5;
1150
- break;
1151
- }
1152
- }
1153
- while (end < buffer.length && !DELIMITERS.includes(buffer.charAt(end))) {
1154
- end++;
1155
- if (end - position > MAX_LENGTH / 2 - 1) {
1156
- tail = " ... ";
1157
- end -= 5;
1158
- break;
1159
- }
1160
- }
1161
- const snippet = buffer.slice(start, end);
1162
- const indent = " ".repeat(INDENT);
1163
- const caretIndent = " ".repeat(INDENT + position - start + head.length);
1164
- return `${indent + head + snippet + tail}\n${caretIndent}^`;
1165
- }
1166
- function markToString(buffer, position, line, column) {
1167
- let where = `at line ${line + 1}, column ${column + 1}`;
1168
- const snippet = getSnippet(buffer, position);
1169
- if (snippet) where += `:\n${snippet}`;
1170
- return where;
1171
- }
1172
- var LoaderState = class {
1173
- input;
1174
- length;
1175
- lineIndent = 0;
1176
- lineStart = 0;
1177
- position = 0;
1178
- line = 0;
1179
- onWarning;
1180
- allowDuplicateKeys;
1181
- implicitTypes;
1182
- typeMap;
1183
- version;
1184
- checkLineBreaks = false;
1185
- tagMap = /* @__PURE__ */ new Map();
1186
- anchorMap = /* @__PURE__ */ new Map();
1187
- tag;
1188
- anchor;
1189
- kind;
1190
- result = "";
1191
- constructor(input, { schema = DEFAULT_SCHEMA, onWarning, allowDuplicateKeys = false }) {
1192
- this.input = input;
1193
- this.onWarning = onWarning;
1194
- this.allowDuplicateKeys = allowDuplicateKeys;
1195
- this.implicitTypes = schema.implicitTypes;
1196
- this.typeMap = schema.typeMap;
1197
- this.length = input.length;
1198
- this.version = null;
1199
- this.readIndent();
1200
- }
1201
- skipWhitespaces() {
1202
- let ch = this.peek();
1203
- while (isWhiteSpace(ch)) ch = this.next();
1204
- }
1205
- skipComment() {
1206
- let ch = this.peek();
1207
- if (ch !== SHARP) return;
1208
- ch = this.next();
1209
- while (ch !== 0 && !isEOL(ch)) ch = this.next();
1210
- }
1211
- readIndent() {
1212
- let char = this.peek();
1213
- while (char === SPACE) {
1214
- this.lineIndent += 1;
1215
- char = this.next();
1216
- }
1217
- }
1218
- peek(offset = 0) {
1219
- return this.input.charCodeAt(this.position + offset);
1220
- }
1221
- next() {
1222
- this.position += 1;
1223
- return this.peek();
1224
- }
1225
- #createError(message) {
1226
- const mark = markToString(this.input, this.position, this.line, this.position - this.lineStart);
1227
- return /* @__PURE__ */ new SyntaxError(`${message} ${mark}`);
1228
- }
1229
- dispatchWarning(message) {
1230
- const error = this.#createError(message);
1231
- this.onWarning?.(error);
1232
- }
1233
- yamlDirectiveHandler(...args) {
1234
- if (this.version !== null) throw this.#createError("Cannot handle YAML directive: duplication of %YAML directive");
1235
- if (args.length !== 1) throw this.#createError("Cannot handle YAML directive: YAML directive accepts exactly one argument");
1236
- const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1237
- if (match === null) throw this.#createError("Cannot handle YAML directive: ill-formed argument");
1238
- const major = parseInt(match[1], 10);
1239
- const minor = parseInt(match[2], 10);
1240
- if (major !== 1) throw this.#createError("Cannot handle YAML directive: unacceptable YAML version");
1241
- this.version = args[0] ?? null;
1242
- this.checkLineBreaks = minor < 2;
1243
- if (minor !== 1 && minor !== 2) return this.dispatchWarning("Cannot handle YAML directive: unsupported YAML version");
1244
- }
1245
- tagDirectiveHandler(...args) {
1246
- if (args.length !== 2) throw this.#createError(`Cannot handle tag directive: directive accepts exactly two arguments, received ${args.length}`);
1247
- const handle = args[0];
1248
- const prefix = args[1];
1249
- if (!PATTERN_TAG_HANDLE.test(handle)) throw this.#createError(`Cannot handle tag directive: ill-formed handle (first argument) in "${handle}"`);
1250
- if (this.tagMap.has(handle)) throw this.#createError(`Cannot handle tag directive: previously declared suffix for "${handle}" tag handle`);
1251
- if (!PATTERN_TAG_URI.test(prefix)) throw this.#createError("Cannot handle tag directive: ill-formed tag prefix (second argument) of the TAG directive");
1252
- this.tagMap.set(handle, prefix);
1253
- }
1254
- captureSegment(start, end, checkJson) {
1255
- if (start < end) {
1256
- const result = this.input.slice(start, end);
1257
- if (checkJson) for (let position = 0; position < result.length; position++) {
1258
- const character = result.charCodeAt(position);
1259
- if (!(character === 9 || 32 <= character && character <= 1114111)) throw this.#createError(`Expected valid JSON character: received "${character}"`);
1260
- }
1261
- else if (PATTERN_NON_PRINTABLE.test(result)) throw this.#createError("Stream contains non-printable characters");
1262
- this.result += result;
1263
- }
1264
- }
1265
- readBlockSequence(nodeIndent) {
1266
- let detected = false;
1267
- const tag = this.tag;
1268
- const anchor = this.anchor;
1269
- const result = [];
1270
- if (this.anchor !== null && typeof this.anchor !== "undefined") this.anchorMap.set(this.anchor, result);
1271
- let ch = this.peek();
1272
- while (ch !== 0) {
1273
- if (ch !== MINUS) break;
1274
- const following = this.peek(1);
1275
- if (!isWhiteSpaceOrEOL(following)) break;
1276
- detected = true;
1277
- this.position++;
1278
- if (this.skipSeparationSpace(true, -1)) {
1279
- if (this.lineIndent <= nodeIndent) {
1280
- result.push(null);
1281
- ch = this.peek();
1282
- continue;
1283
- }
1284
- }
1285
- const line = this.line;
1286
- this.composeNode({
1287
- parentIndent: nodeIndent,
1288
- nodeContext: CONTEXT_BLOCK_IN,
1289
- allowToSeek: false,
1290
- allowCompact: true
1291
- });
1292
- result.push(this.result);
1293
- this.skipSeparationSpace(true, -1);
1294
- ch = this.peek();
1295
- if ((this.line === line || this.lineIndent > nodeIndent) && ch !== 0) throw this.#createError("Cannot read block sequence: bad indentation of a sequence entry");
1296
- else if (this.lineIndent < nodeIndent) break;
1297
- }
1298
- if (detected) {
1299
- this.tag = tag;
1300
- this.anchor = anchor;
1301
- this.kind = "sequence";
1302
- this.result = result;
1303
- return true;
1304
- }
1305
- return false;
1306
- }
1307
- mergeMappings(destination, source, overridableKeys) {
1308
- if (!isObject(source)) throw this.#createError("Cannot merge mappings: the provided source object is unacceptable");
1309
- for (const [key, value] of Object.entries(source)) {
1310
- if (Object.hasOwn(destination, key)) continue;
1311
- Object.defineProperty(destination, key, {
1312
- value,
1313
- writable: true,
1314
- enumerable: true,
1315
- configurable: true
1316
- });
1317
- overridableKeys.add(key);
1318
- }
1319
- }
1320
- storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
1321
- if (Array.isArray(keyNode)) {
1322
- keyNode = Array.prototype.slice.call(keyNode);
1323
- for (let index = 0; index < keyNode.length; index++) {
1324
- if (Array.isArray(keyNode[index])) throw this.#createError("Cannot store mapping pair: nested arrays are not supported inside keys");
1325
- if (typeof keyNode === "object" && isPlainObject(keyNode[index])) keyNode[index] = "[object Object]";
1326
- }
1327
- }
1328
- if (typeof keyNode === "object" && isPlainObject(keyNode)) keyNode = "[object Object]";
1329
- keyNode = String(keyNode);
1330
- if (keyTag === "tag:yaml.org,2002:merge") if (Array.isArray(valueNode)) for (let index = 0; index < valueNode.length; index++) this.mergeMappings(result, valueNode[index], overridableKeys);
1331
- else this.mergeMappings(result, valueNode, overridableKeys);
1332
- else {
1333
- if (!this.allowDuplicateKeys && !overridableKeys.has(keyNode) && Object.hasOwn(result, keyNode)) {
1334
- this.line = startLine || this.line;
1335
- this.position = startPos || this.position;
1336
- throw this.#createError("Cannot store mapping pair: duplicated key");
1337
- }
1338
- Object.defineProperty(result, keyNode, {
1339
- value: valueNode,
1340
- writable: true,
1341
- enumerable: true,
1342
- configurable: true
1343
- });
1344
- overridableKeys.delete(keyNode);
1345
- }
1346
- return result;
1347
- }
1348
- readLineBreak() {
1349
- const ch = this.peek();
1350
- if (ch === LINE_FEED) this.position++;
1351
- else if (ch === CARRIAGE_RETURN) {
1352
- this.position++;
1353
- if (this.peek() === LINE_FEED) this.position++;
1354
- } else throw this.#createError("Cannot read line: line break not found");
1355
- this.line += 1;
1356
- this.lineStart = this.position;
1357
- }
1358
- skipSeparationSpace(allowComments, checkIndent) {
1359
- let lineBreaks = 0;
1360
- let ch = this.peek();
1361
- while (ch !== 0) {
1362
- this.skipWhitespaces();
1363
- ch = this.peek();
1364
- if (allowComments) {
1365
- this.skipComment();
1366
- ch = this.peek();
1367
- }
1368
- if (isEOL(ch)) {
1369
- this.readLineBreak();
1370
- ch = this.peek();
1371
- lineBreaks++;
1372
- this.lineIndent = 0;
1373
- this.readIndent();
1374
- ch = this.peek();
1375
- } else break;
1376
- }
1377
- if (checkIndent !== -1 && lineBreaks !== 0 && this.lineIndent < checkIndent) this.dispatchWarning("deficient indentation");
1378
- return lineBreaks;
1379
- }
1380
- testDocumentSeparator() {
1381
- let ch = this.peek();
1382
- if ((ch === MINUS || ch === DOT) && ch === this.peek(1) && ch === this.peek(2)) {
1383
- ch = this.peek(3);
1384
- if (ch === 0 || isWhiteSpaceOrEOL(ch)) return true;
1385
- }
1386
- return false;
1387
- }
1388
- writeFoldedLines(count) {
1389
- if (count === 1) this.result += " ";
1390
- else if (count > 1) this.result += "\n".repeat(count - 1);
1391
- }
1392
- readPlainScalar(nodeIndent, withinFlowCollection) {
1393
- const kind = this.kind;
1394
- const result = this.result;
1395
- let ch = this.peek();
1396
- if (isWhiteSpaceOrEOL(ch) || isFlowIndicator(ch) || ch === SHARP || ch === AMPERSAND || ch === ASTERISK || ch === EXCLAMATION || ch === VERTICAL_LINE || ch === GREATER_THAN || ch === SINGLE_QUOTE || ch === DOUBLE_QUOTE || ch === PERCENT || ch === COMMERCIAL_AT || ch === GRAVE_ACCENT) return false;
1397
- let following;
1398
- if (ch === QUESTION || ch === MINUS) {
1399
- following = this.peek(1);
1400
- if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) return false;
1401
- }
1402
- this.kind = "scalar";
1403
- this.result = "";
1404
- let captureEnd = this.position;
1405
- let captureStart = this.position;
1406
- let hasPendingContent = false;
1407
- let line = 0;
1408
- while (ch !== 0) {
1409
- if (ch === COLON) {
1410
- following = this.peek(1);
1411
- if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) break;
1412
- } else if (ch === SHARP) {
1413
- const preceding = this.peek(-1);
1414
- if (isWhiteSpaceOrEOL(preceding)) break;
1415
- } else if (this.position === this.lineStart && this.testDocumentSeparator() || withinFlowCollection && isFlowIndicator(ch)) break;
1416
- else if (isEOL(ch)) {
1417
- line = this.line;
1418
- const lineStart = this.lineStart;
1419
- const lineIndent = this.lineIndent;
1420
- this.skipSeparationSpace(false, -1);
1421
- if (this.lineIndent >= nodeIndent) {
1422
- hasPendingContent = true;
1423
- ch = this.peek();
1424
- continue;
1425
- } else {
1426
- this.position = captureEnd;
1427
- this.line = line;
1428
- this.lineStart = lineStart;
1429
- this.lineIndent = lineIndent;
1430
- break;
1431
- }
1432
- }
1433
- if (hasPendingContent) {
1434
- this.captureSegment(captureStart, captureEnd, false);
1435
- this.writeFoldedLines(this.line - line);
1436
- captureStart = captureEnd = this.position;
1437
- hasPendingContent = false;
1438
- }
1439
- if (!isWhiteSpace(ch)) captureEnd = this.position + 1;
1440
- ch = this.next();
1441
- }
1442
- this.captureSegment(captureStart, captureEnd, false);
1443
- if (this.result) return true;
1444
- this.kind = kind;
1445
- this.result = result;
1446
- return false;
1447
- }
1448
- readSingleQuotedScalar(nodeIndent) {
1449
- let ch = this.peek();
1450
- if (ch !== SINGLE_QUOTE) return false;
1451
- this.kind = "scalar";
1452
- this.result = "";
1453
- this.position++;
1454
- let captureStart = this.position;
1455
- let captureEnd = this.position;
1456
- ch = this.peek();
1457
- while (ch !== 0) {
1458
- if (ch === SINGLE_QUOTE) {
1459
- this.captureSegment(captureStart, this.position, true);
1460
- ch = this.next();
1461
- if (ch === SINGLE_QUOTE) {
1462
- captureStart = this.position;
1463
- this.position++;
1464
- captureEnd = this.position;
1465
- } else return true;
1466
- } else if (isEOL(ch)) {
1467
- this.captureSegment(captureStart, captureEnd, true);
1468
- this.writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
1469
- captureStart = captureEnd = this.position;
1470
- } else if (this.position === this.lineStart && this.testDocumentSeparator()) throw this.#createError("Unexpected end of the document within a single quoted scalar");
1471
- else {
1472
- this.position++;
1473
- captureEnd = this.position;
1474
- }
1475
- ch = this.peek();
1476
- }
1477
- throw this.#createError("Unexpected end of the stream within a single quoted scalar");
1478
- }
1479
- readDoubleQuotedScalar(nodeIndent) {
1480
- let ch = this.peek();
1481
- if (ch !== DOUBLE_QUOTE) return false;
1482
- this.kind = "scalar";
1483
- this.result = "";
1484
- this.position++;
1485
- let captureEnd = this.position;
1486
- let captureStart = this.position;
1487
- let tmp;
1488
- ch = this.peek();
1489
- while (ch !== 0) {
1490
- if (ch === DOUBLE_QUOTE) {
1491
- this.captureSegment(captureStart, this.position, true);
1492
- this.position++;
1493
- return true;
1494
- }
1495
- if (ch === BACKSLASH) {
1496
- this.captureSegment(captureStart, this.position, true);
1497
- ch = this.next();
1498
- if (isEOL(ch)) this.skipSeparationSpace(false, nodeIndent);
1499
- else if (ch < 256 && SIMPLE_ESCAPE_SEQUENCES.has(ch)) {
1500
- this.result += SIMPLE_ESCAPE_SEQUENCES.get(ch);
1501
- this.position++;
1502
- } else if ((tmp = ESCAPED_HEX_LENGTHS.get(ch) ?? 0) > 0) {
1503
- let hexLength = tmp;
1504
- let hexResult = 0;
1505
- for (; hexLength > 0; hexLength--) {
1506
- ch = this.next();
1507
- if ((tmp = hexCharCodeToNumber(ch)) >= 0) hexResult = (hexResult << 4) + tmp;
1508
- else throw this.#createError("Cannot read double quoted scalar: expected hexadecimal character");
1509
- }
1510
- this.result += codepointToChar(hexResult);
1511
- this.position++;
1512
- } else throw this.#createError("Cannot read double quoted scalar: unknown escape sequence");
1513
- captureStart = captureEnd = this.position;
1514
- } else if (isEOL(ch)) {
1515
- this.captureSegment(captureStart, captureEnd, true);
1516
- this.writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
1517
- captureStart = captureEnd = this.position;
1518
- } else if (this.position === this.lineStart && this.testDocumentSeparator()) throw this.#createError("Unexpected end of the document within a double quoted scalar");
1519
- else {
1520
- this.position++;
1521
- captureEnd = this.position;
1522
- }
1523
- ch = this.peek();
1524
- }
1525
- throw this.#createError("Unexpected end of the stream within a double quoted scalar");
1526
- }
1527
- readFlowCollection(nodeIndent) {
1528
- let ch = this.peek();
1529
- let terminator;
1530
- let isMapping = true;
1531
- let result = {};
1532
- if (ch === LEFT_SQUARE_BRACKET) {
1533
- terminator = RIGHT_SQUARE_BRACKET;
1534
- isMapping = false;
1535
- result = [];
1536
- } else if (ch === LEFT_CURLY_BRACKET) terminator = RIGHT_CURLY_BRACKET;
1537
- else return false;
1538
- if (this.anchor !== null && typeof this.anchor !== "undefined") this.anchorMap.set(this.anchor, result);
1539
- ch = this.next();
1540
- const tag = this.tag;
1541
- const anchor = this.anchor;
1542
- let readNext = true;
1543
- let valueNode = null;
1544
- let keyNode = null;
1545
- let keyTag = null;
1546
- let isExplicitPair = false;
1547
- let isPair = false;
1548
- let following = 0;
1549
- let line = 0;
1550
- const overridableKeys = /* @__PURE__ */ new Set();
1551
- while (ch !== 0) {
1552
- this.skipSeparationSpace(true, nodeIndent);
1553
- ch = this.peek();
1554
- if (ch === terminator) {
1555
- this.position++;
1556
- this.tag = tag;
1557
- this.anchor = anchor;
1558
- this.kind = isMapping ? "mapping" : "sequence";
1559
- this.result = result;
1560
- return true;
1561
- }
1562
- if (!readNext) throw this.#createError("Cannot read flow collection: missing comma between flow collection entries");
1563
- keyTag = keyNode = valueNode = null;
1564
- isPair = isExplicitPair = false;
1565
- if (ch === QUESTION) {
1566
- following = this.peek(1);
1567
- if (isWhiteSpaceOrEOL(following)) {
1568
- isPair = isExplicitPair = true;
1569
- this.position++;
1570
- this.skipSeparationSpace(true, nodeIndent);
1571
- }
1572
- }
1573
- line = this.line;
1574
- this.composeNode({
1575
- parentIndent: nodeIndent,
1576
- nodeContext: CONTEXT_FLOW_IN,
1577
- allowToSeek: false,
1578
- allowCompact: true
1579
- });
1580
- keyTag = this.tag || null;
1581
- keyNode = this.result;
1582
- this.skipSeparationSpace(true, nodeIndent);
1583
- ch = this.peek();
1584
- if ((isExplicitPair || this.line === line) && ch === COLON) {
1585
- isPair = true;
1586
- ch = this.next();
1587
- this.skipSeparationSpace(true, nodeIndent);
1588
- this.composeNode({
1589
- parentIndent: nodeIndent,
1590
- nodeContext: CONTEXT_FLOW_IN,
1591
- allowToSeek: false,
1592
- allowCompact: true
1593
- });
1594
- valueNode = this.result;
1595
- }
1596
- if (isMapping) this.storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode);
1597
- else if (isPair) result.push(this.storeMappingPair({}, overridableKeys, keyTag, keyNode, valueNode));
1598
- else result.push(keyNode);
1599
- this.skipSeparationSpace(true, nodeIndent);
1600
- ch = this.peek();
1601
- if (ch === COMMA) {
1602
- readNext = true;
1603
- ch = this.next();
1604
- } else readNext = false;
1605
- }
1606
- throw this.#createError("Cannot read flow collection: unexpected end of the stream within a flow collection");
1607
- }
1608
- readBlockScalar(nodeIndent) {
1609
- let chomping = CHOMPING_CLIP;
1610
- let didReadContent = false;
1611
- let detectedIndent = false;
1612
- let textIndent = nodeIndent;
1613
- let emptyLines = 0;
1614
- let atMoreIndented = false;
1615
- let ch = this.peek();
1616
- let folding = false;
1617
- if (ch === VERTICAL_LINE) folding = false;
1618
- else if (ch === GREATER_THAN) folding = true;
1619
- else return false;
1620
- this.kind = "scalar";
1621
- this.result = "";
1622
- let tmp = 0;
1623
- while (ch !== 0) {
1624
- ch = this.next();
1625
- if (ch === PLUS || ch === MINUS) if (CHOMPING_CLIP === chomping) chomping = ch === PLUS ? CHOMPING_KEEP : CHOMPING_STRIP;
1626
- else throw this.#createError("Cannot read block: chomping mode identifier repeated");
1627
- else if ((tmp = decimalCharCodeToNumber(ch)) >= 0) if (tmp === 0) throw this.#createError("Cannot read block: indentation width must be greater than 0");
1628
- else if (!detectedIndent) {
1629
- textIndent = nodeIndent + tmp - 1;
1630
- detectedIndent = true;
1631
- } else throw this.#createError("Cannot read block: indentation width identifier repeated");
1632
- else break;
1633
- }
1634
- if (isWhiteSpace(ch)) {
1635
- this.skipWhitespaces();
1636
- this.skipComment();
1637
- ch = this.peek();
1638
- }
1639
- while (ch !== 0) {
1640
- this.readLineBreak();
1641
- this.lineIndent = 0;
1642
- ch = this.peek();
1643
- while ((!detectedIndent || this.lineIndent < textIndent) && ch === SPACE) {
1644
- this.lineIndent++;
1645
- ch = this.next();
1646
- }
1647
- if (!detectedIndent && this.lineIndent > textIndent) textIndent = this.lineIndent;
1648
- if (isEOL(ch)) {
1649
- emptyLines++;
1650
- continue;
1651
- }
1652
- if (this.lineIndent < textIndent) {
1653
- if (chomping === CHOMPING_KEEP) this.result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1654
- else if (chomping === CHOMPING_CLIP) {
1655
- if (didReadContent) this.result += "\n";
1656
- }
1657
- break;
1658
- }
1659
- if (folding) if (isWhiteSpace(ch)) {
1660
- atMoreIndented = true;
1661
- this.result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1662
- } else if (atMoreIndented) {
1663
- atMoreIndented = false;
1664
- this.result += "\n".repeat(emptyLines + 1);
1665
- } else if (emptyLines === 0) {
1666
- if (didReadContent) this.result += " ";
1667
- } else this.result += "\n".repeat(emptyLines);
1668
- else this.result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1669
- didReadContent = true;
1670
- detectedIndent = true;
1671
- emptyLines = 0;
1672
- const captureStart = this.position;
1673
- while (!isEOL(ch) && ch !== 0) ch = this.next();
1674
- this.captureSegment(captureStart, this.position, false);
1675
- }
1676
- return true;
1677
- }
1678
- readBlockMapping(nodeIndent, flowIndent) {
1679
- const tag = this.tag;
1680
- const anchor = this.anchor;
1681
- const result = {};
1682
- const overridableKeys = /* @__PURE__ */ new Set();
1683
- let allowCompact = false;
1684
- let line;
1685
- let pos;
1686
- let keyTag = null;
1687
- let keyNode = null;
1688
- let valueNode = null;
1689
- let atExplicitKey = false;
1690
- let detected = false;
1691
- if (this.anchor !== null && typeof this.anchor !== "undefined") this.anchorMap.set(this.anchor, result);
1692
- let ch = this.peek();
1693
- while (ch !== 0) {
1694
- const following = this.peek(1);
1695
- line = this.line;
1696
- pos = this.position;
1697
- if ((ch === QUESTION || ch === COLON) && isWhiteSpaceOrEOL(following)) {
1698
- if (ch === QUESTION) {
1699
- if (atExplicitKey) {
1700
- this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
1701
- keyTag = null;
1702
- keyNode = null;
1703
- valueNode = null;
1704
- }
1705
- detected = true;
1706
- atExplicitKey = true;
1707
- allowCompact = true;
1708
- } else if (atExplicitKey) {
1709
- atExplicitKey = false;
1710
- allowCompact = true;
1711
- } else throw this.#createError("Cannot read block as explicit mapping pair is incomplete: a key node is missed or followed by a non-tabulated empty line");
1712
- this.position += 1;
1713
- ch = following;
1714
- } else if (this.composeNode({
1715
- parentIndent: flowIndent,
1716
- nodeContext: CONTEXT_FLOW_OUT,
1717
- allowToSeek: false,
1718
- allowCompact: true
1719
- })) if (this.line === line) {
1720
- ch = this.peek();
1721
- this.skipWhitespaces();
1722
- ch = this.peek();
1723
- if (ch === COLON) {
1724
- ch = this.next();
1725
- if (!isWhiteSpaceOrEOL(ch)) throw this.#createError("Cannot read block: a whitespace character is expected after the key-value separator within a block mapping");
1726
- if (atExplicitKey) {
1727
- this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
1728
- keyTag = null;
1729
- keyNode = null;
1730
- valueNode = null;
1731
- }
1732
- detected = true;
1733
- atExplicitKey = false;
1734
- allowCompact = false;
1735
- keyTag = this.tag;
1736
- keyNode = this.result;
1737
- } else if (detected) throw this.#createError("Cannot read an implicit mapping pair: missing colon");
1738
- else {
1739
- this.tag = tag;
1740
- this.anchor = anchor;
1741
- return true;
1742
- }
1743
- } else if (detected) throw this.#createError("Cannot read a block mapping entry: a multiline key may not be an implicit key");
1744
- else {
1745
- this.tag = tag;
1746
- this.anchor = anchor;
1747
- return true;
1748
- }
1749
- else break;
1750
- if (this.line === line || this.lineIndent > nodeIndent) {
1751
- if (this.composeNode({
1752
- parentIndent: nodeIndent,
1753
- nodeContext: CONTEXT_BLOCK_OUT,
1754
- allowToSeek: true,
1755
- allowCompact
1756
- })) if (atExplicitKey) keyNode = this.result;
1757
- else valueNode = this.result;
1758
- if (!atExplicitKey) {
1759
- this.storeMappingPair(result, overridableKeys, keyTag, keyNode, valueNode, line, pos);
1760
- keyTag = keyNode = valueNode = null;
1761
- }
1762
- this.skipSeparationSpace(true, -1);
1763
- ch = this.peek();
1764
- }
1765
- if (this.lineIndent > nodeIndent && ch !== 0) throw this.#createError("Cannot read block: bad indentation of a mapping entry");
1766
- else if (this.lineIndent < nodeIndent) break;
1767
- }
1768
- if (atExplicitKey) this.storeMappingPair(result, overridableKeys, keyTag, keyNode, null);
1769
- if (detected) {
1770
- this.tag = tag;
1771
- this.anchor = anchor;
1772
- this.kind = "mapping";
1773
- this.result = result;
1774
- }
1775
- return detected;
1776
- }
1777
- readTagProperty() {
1778
- let isVerbatim = false;
1779
- let isNamed = false;
1780
- let tagHandle = "";
1781
- let tagName;
1782
- let ch = this.peek();
1783
- if (ch !== EXCLAMATION) return false;
1784
- if (this.tag !== null) throw this.#createError("Cannot read tag property: duplication of a tag property");
1785
- ch = this.next();
1786
- if (ch === SMALLER_THAN) {
1787
- isVerbatim = true;
1788
- ch = this.next();
1789
- } else if (ch === EXCLAMATION) {
1790
- isNamed = true;
1791
- tagHandle = "!!";
1792
- ch = this.next();
1793
- } else tagHandle = "!";
1794
- let position = this.position;
1795
- if (isVerbatim) {
1796
- do
1797
- ch = this.next();
1798
- while (ch !== 0 && ch !== GREATER_THAN);
1799
- if (this.position < this.length) {
1800
- tagName = this.input.slice(position, this.position);
1801
- ch = this.next();
1802
- } else throw this.#createError("Cannot read tag property: unexpected end of stream");
1803
- } else {
1804
- while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
1805
- if (ch === EXCLAMATION) if (!isNamed) {
1806
- tagHandle = this.input.slice(position - 1, this.position + 1);
1807
- if (!PATTERN_TAG_HANDLE.test(tagHandle)) throw this.#createError("Cannot read tag property: named tag handle contains invalid characters");
1808
- isNamed = true;
1809
- position = this.position + 1;
1810
- } else throw this.#createError("Cannot read tag property: tag suffix cannot contain an exclamation mark");
1811
- ch = this.next();
1812
- }
1813
- tagName = this.input.slice(position, this.position);
1814
- if (PATTERN_FLOW_INDICATORS.test(tagName)) throw this.#createError("Cannot read tag property: tag suffix cannot contain flow indicator characters");
1815
- }
1816
- if (tagName && !PATTERN_TAG_URI.test(tagName)) throw this.#createError(`Cannot read tag property: invalid characters in tag name "${tagName}"`);
1817
- if (isVerbatim) this.tag = tagName;
1818
- else if (this.tagMap.has(tagHandle)) this.tag = this.tagMap.get(tagHandle) + tagName;
1819
- else if (tagHandle === "!") this.tag = `!${tagName}`;
1820
- else if (tagHandle === "!!") this.tag = `tag:yaml.org,2002:${tagName}`;
1821
- else throw this.#createError(`Cannot read tag property: undeclared tag handle "${tagHandle}"`);
1822
- return true;
1823
- }
1824
- readAnchorProperty() {
1825
- let ch = this.peek();
1826
- if (ch !== AMPERSAND) return false;
1827
- if (this.anchor !== null) throw this.#createError("Cannot read anchor property: duplicate anchor property");
1828
- ch = this.next();
1829
- const position = this.position;
1830
- while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) ch = this.next();
1831
- if (this.position === position) throw this.#createError("Cannot read anchor property: name of an anchor node must contain at least one character");
1832
- this.anchor = this.input.slice(position, this.position);
1833
- return true;
1834
- }
1835
- readAlias() {
1836
- if (this.peek() !== ASTERISK) return false;
1837
- let ch = this.next();
1838
- const position = this.position;
1839
- while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) ch = this.next();
1840
- if (this.position === position) throw this.#createError("Cannot read alias: alias name must contain at least one character");
1841
- const alias = this.input.slice(position, this.position);
1842
- if (!this.anchorMap.has(alias)) throw this.#createError(`Cannot read alias: unidentified alias "${alias}"`);
1843
- this.result = this.anchorMap.get(alias);
1844
- this.skipSeparationSpace(true, -1);
1845
- return true;
1846
- }
1847
- composeNode({ parentIndent, nodeContext, allowToSeek, allowCompact }) {
1848
- let indentStatus = 1;
1849
- let atNewLine = false;
1850
- let hasContent = false;
1851
- let type;
1852
- this.tag = null;
1853
- this.anchor = null;
1854
- this.kind = null;
1855
- this.result = null;
1856
- const allowBlockScalars = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
1857
- let allowBlockCollections = allowBlockScalars;
1858
- const allowBlockStyles = allowBlockScalars;
1859
- if (allowToSeek) {
1860
- if (this.skipSeparationSpace(true, -1)) {
1861
- atNewLine = true;
1862
- if (this.lineIndent > parentIndent) indentStatus = 1;
1863
- else if (this.lineIndent === parentIndent) indentStatus = 0;
1864
- else if (this.lineIndent < parentIndent) indentStatus = -1;
1865
- }
1866
- }
1867
- if (indentStatus === 1) while (this.readTagProperty() || this.readAnchorProperty()) if (this.skipSeparationSpace(true, -1)) {
1868
- atNewLine = true;
1869
- allowBlockCollections = allowBlockStyles;
1870
- if (this.lineIndent > parentIndent) indentStatus = 1;
1871
- else if (this.lineIndent === parentIndent) indentStatus = 0;
1872
- else if (this.lineIndent < parentIndent) indentStatus = -1;
1873
- } else allowBlockCollections = false;
1874
- if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact;
1875
- if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
1876
- const cond = CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext;
1877
- const flowIndent = cond ? parentIndent : parentIndent + 1;
1878
- const blockIndent = this.position - this.lineStart;
1879
- if (indentStatus === 1) if (allowBlockCollections && (this.readBlockSequence(blockIndent) || this.readBlockMapping(blockIndent, flowIndent)) || this.readFlowCollection(flowIndent)) hasContent = true;
1880
- else {
1881
- if (allowBlockScalars && this.readBlockScalar(flowIndent) || this.readSingleQuotedScalar(flowIndent) || this.readDoubleQuotedScalar(flowIndent)) hasContent = true;
1882
- else if (this.readAlias()) {
1883
- hasContent = true;
1884
- if (this.tag !== null || this.anchor !== null) throw this.#createError("Cannot compose node: alias node should not have any properties");
1885
- } else if (this.readPlainScalar(flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
1886
- hasContent = true;
1887
- if (this.tag === null) this.tag = "?";
1888
- }
1889
- if (this.anchor !== null) this.anchorMap.set(this.anchor, this.result);
1890
- }
1891
- else if (indentStatus === 0) hasContent = allowBlockCollections && this.readBlockSequence(blockIndent);
1892
- }
1893
- if (this.tag !== null && this.tag !== "!") if (this.tag === "?") for (let typeIndex = 0; typeIndex < this.implicitTypes.length; typeIndex++) {
1894
- type = this.implicitTypes[typeIndex];
1895
- if (type.resolve(this.result)) {
1896
- this.result = type.construct(this.result);
1897
- this.tag = type.tag;
1898
- if (this.anchor !== null) this.anchorMap.set(this.anchor, this.result);
1899
- break;
1900
- }
1901
- }
1902
- else if (this.typeMap[this.kind ?? "fallback"].has(this.tag)) {
1903
- const map$1 = this.typeMap[this.kind ?? "fallback"];
1904
- type = map$1.get(this.tag);
1905
- if (this.result !== null && type.kind !== this.kind) throw this.#createError(`Unacceptable node kind for !<${this.tag}> tag: it should be "${type.kind}", not "${this.kind}"`);
1906
- if (!type.resolve(this.result)) throw this.#createError(`Cannot resolve a node with !<${this.tag}> explicit tag`);
1907
- else {
1908
- this.result = type.construct(this.result);
1909
- if (this.anchor !== null) this.anchorMap.set(this.anchor, this.result);
1910
- }
1911
- } else throw this.#createError(`Cannot resolve unknown tag !<${this.tag}>`);
1912
- return this.tag !== null || this.anchor !== null || hasContent;
1913
- }
1914
- readDocument() {
1915
- const documentStart = this.position;
1916
- let hasDirectives = false;
1917
- this.version = null;
1918
- this.checkLineBreaks = false;
1919
- this.tagMap = /* @__PURE__ */ new Map();
1920
- this.anchorMap = /* @__PURE__ */ new Map();
1921
- let ch = this.peek();
1922
- while (ch !== 0) {
1923
- this.skipSeparationSpace(true, -1);
1924
- ch = this.peek();
1925
- if (this.lineIndent > 0 || ch !== PERCENT) break;
1926
- hasDirectives = true;
1927
- ch = this.next();
1928
- let position = this.position;
1929
- while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) ch = this.next();
1930
- const directiveName = this.input.slice(position, this.position);
1931
- const directiveArgs = [];
1932
- if (directiveName.length < 1) throw this.#createError("Cannot read document: directive name length must be greater than zero");
1933
- while (ch !== 0) {
1934
- this.skipWhitespaces();
1935
- this.skipComment();
1936
- ch = this.peek();
1937
- if (isEOL(ch)) break;
1938
- position = this.position;
1939
- while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) ch = this.next();
1940
- directiveArgs.push(this.input.slice(position, this.position));
1941
- }
1942
- if (ch !== 0) this.readLineBreak();
1943
- switch (directiveName) {
1944
- case "YAML":
1945
- this.yamlDirectiveHandler(...directiveArgs);
1946
- break;
1947
- case "TAG":
1948
- this.tagDirectiveHandler(...directiveArgs);
1949
- break;
1950
- default:
1951
- this.dispatchWarning(`unknown document directive "${directiveName}"`);
1952
- break;
1953
- }
1954
- ch = this.peek();
1955
- }
1956
- this.skipSeparationSpace(true, -1);
1957
- if (this.lineIndent === 0 && this.peek() === MINUS && this.peek(1) === MINUS && this.peek(2) === MINUS) {
1958
- this.position += 3;
1959
- this.skipSeparationSpace(true, -1);
1960
- } else if (hasDirectives) throw this.#createError("Cannot read document: directives end mark is expected");
1961
- this.composeNode({
1962
- parentIndent: this.lineIndent - 1,
1963
- nodeContext: CONTEXT_BLOCK_OUT,
1964
- allowToSeek: false,
1965
- allowCompact: true
1966
- });
1967
- this.skipSeparationSpace(true, -1);
1968
- if (this.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(this.input.slice(documentStart, this.position))) this.dispatchWarning("non-ASCII line breaks are interpreted as content");
1969
- if (this.position === this.lineStart && this.testDocumentSeparator()) {
1970
- if (this.peek() === DOT) {
1971
- this.position += 3;
1972
- this.skipSeparationSpace(true, -1);
1973
- }
1974
- } else if (this.position < this.length - 1) throw this.#createError("Cannot read document: end of the stream or a document separator is expected");
1975
- return this.result;
1976
- }
1977
- *readDocuments() {
1978
- while (this.position < this.length - 1) yield this.readDocument();
1979
- }
1980
- };
1981
-
1982
- //#endregion
1983
- //#region ../../node_modules/.pnpm/@jsr+std__yaml@1.0.8/node_modules/@jsr/std__yaml/parse.js
1984
- function sanitizeInput(input) {
1985
- input = String(input);
1986
- if (input.length > 0) {
1987
- if (!isEOL(input.charCodeAt(input.length - 1))) input += "\n";
1988
- if (input.charCodeAt(0) === 65279) input = input.slice(1);
1989
- }
1990
- input += "\0";
1991
- return input;
1992
- }
1993
- /**
1994
- * Parse and return a YAML string as a parsed YAML document object.
1995
- *
1996
- * Note: This does not support functions. Untrusted data is safe to parse.
1997
- *
1998
- * @example Usage
1999
- * ```ts
2000
- * import { parse } from "@std/yaml/parse";
2001
- * import { assertEquals } from "@std/assert";
2002
- *
2003
- * const data = parse(`
2004
- * id: 1
2005
- * name: Alice
2006
- * `);
2007
- *
2008
- * assertEquals(data, { id: 1, name: "Alice" });
2009
- * ```
2010
- *
2011
- * @throws {SyntaxError} Throws error on invalid YAML.
2012
- * @param content YAML string to parse.
2013
- * @param options Parsing options.
2014
- * @returns Parsed document.
2015
- */ function parse(content, options = {}) {
2016
- content = sanitizeInput(content);
2017
- const state = new LoaderState(content, {
2018
- ...options,
2019
- schema: SCHEMA_MAP.get(options.schema)
2020
- });
2021
- const documentGenerator = state.readDocuments();
2022
- const document = documentGenerator.next().value;
2023
- if (!documentGenerator.next().done) throw new SyntaxError("Found more than 1 document in the stream: expected a single document");
2024
- return document ?? null;
2025
- }
2026
-
2027
- //#endregion
2028
- //#region src/codegen/fs.ts
2029
- /**
2030
- * Recursively read a directory, yielding the paths of all files. File paths
2031
- * are relative to the directory, and directories are not yielded.
2032
- * @param dir The directory to read.
2033
- * @returns An async iterable of file paths.
2034
- */
2035
- async function* readDirRecursive(dir) {
2036
- for (const entry of await readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) {
2037
- const path = join(dir, entry.name);
2038
- for await (const subentry of readDirRecursive(path)) yield join(entry.name, subentry);
2039
- } else yield entry.name;
2040
- }
2041
-
2042
- //#endregion
2043
- //#region src/codegen/schema.ts
2044
- /**
2045
- * An error that occurred while loading a schema file.
2046
- */
2047
- var SchemaError = class extends Error {
2048
- /**
2049
- * The path of the schema file.
2050
- */
2051
- path;
2052
- /**
2053
- * Constructs a new `SchemaError`.
2054
- * @param path The path of the schema file.
2055
- * @param message The error message.
2056
- */
2057
- constructor(path, message) {
2058
- super(message);
2059
- this.path = path;
2060
- }
2061
- };
2062
- async function loadSchemaValidator() {
2063
- const thisFile = new URL(import.meta.url);
2064
- const schemaFile = join$2(dirname$1(thisFile), "schema.yaml");
2065
- let content;
2066
- if (schemaFile.protocol !== "file:") {
2067
- const response = await fetch(schemaFile);
2068
- content = await response.text();
2069
- } else content = await readFile(fromFileUrl(schemaFile), { encoding: "utf-8" });
2070
- const schemaObject = parse(content);
2071
- return new Validator(schemaObject);
2072
- }
2073
- let schemaValidator = void 0;
2074
- async function loadSchema(path) {
2075
- const content = await readFile(path, { encoding: "utf-8" });
2076
- const schema = parse(content);
2077
- if (schemaValidator == null) schemaValidator = await loadSchemaValidator();
2078
- const result = schemaValidator.validate(schema);
2079
- const errors = [];
2080
- if (result.valid) return schema;
2081
- for (const e of result.errors) errors.push(new SchemaError(path, `${path}:${e.instanceLocation}: ${e.error}`));
2082
- throw new AggregateError(errors);
2083
- }
2084
- /**
2085
- * Loads all schema files in the directory.
2086
- * @param dir The path of the directory to load schema files from.
2087
- * @returns A map from the qualified URI of a type to its {@link SchemaFile}.
2088
- * @throws {@link AggregateError} if any schema file is invalid. It contains
2089
- * all {@link SchemaError}s of the invalid schema files.
2090
- */
2091
- async function loadSchemaFiles(dir) {
2092
- if (typeof dir !== "string") throw new TypeError("Expected a directory path in string");
2093
- const result = {};
2094
- const errors = [];
2095
- for await (const relPath of readDirRecursive(dir)) {
2096
- if (!relPath.match(/\.ya?ml$/i)) continue;
2097
- if (relPath.match(/(^|[/\\])schema.yaml$/i)) continue;
2098
- const path = join(dir, relPath);
2099
- let schema;
2100
- try {
2101
- schema = await loadSchema(path);
2102
- } catch (e) {
2103
- if (e instanceof AggregateError && e.errors.length > 0 && e.errors[0] instanceof SchemaError) {
2104
- errors.push(...e.errors);
2105
- continue;
2106
- }
2107
- throw e;
2108
- }
2109
- result[schema.uri] = schema;
2110
- }
2111
- if (errors.length > 0) throw new AggregateError(errors);
2112
- const entries = Object.entries(result);
2113
- entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2114
- return Object.fromEntries(entries);
2115
- }
2116
-
2117
- //#endregion
2118
- //#region src/codegen/type.ts
2119
- const scalarTypes = {
2120
- "http://www.w3.org/2001/XMLSchema#boolean": {
2121
- name: "boolean",
2122
- typeGuard(v) {
2123
- return `typeof ${v} === "boolean"`;
2124
- },
2125
- encoder(v) {
2126
- return `{ "@value": ${v} }`;
2127
- },
2128
- compactEncoder(v) {
2129
- return v;
2130
- },
2131
- dataCheck(v) {
2132
- return `typeof ${v} === "object" && "@value" in ${v}
2133
- && typeof ${v}["@value"] === "boolean"`;
2134
- },
2135
- decoder(v) {
2136
- return `${v}["@value"]`;
2137
- }
2138
- },
2139
- "http://www.w3.org/2001/XMLSchema#integer": {
2140
- name: "number",
2141
- typeGuard(v) {
2142
- return `typeof ${v} === "number" && Number.isInteger(${v})`;
2143
- },
2144
- encoder(v) {
2145
- return `{
2146
- "@type": "http://www.w3.org/2001/XMLSchema#integer",
2147
- "@value": ${v},
2148
- }`;
2149
- },
2150
- compactEncoder(v) {
2151
- return v;
2152
- },
2153
- dataCheck(v) {
2154
- return `typeof ${v} === "object" && "@type" in ${v}
2155
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#integer"
2156
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
2157
- },
2158
- decoder(v) {
2159
- return `${v}["@value"] as number`;
2160
- }
2161
- },
2162
- "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": {
2163
- name: "number",
2164
- typeGuard(v) {
2165
- return `typeof ${v} === "number" && Number.isInteger(${v}) && ${v} >= 0`;
2166
- },
2167
- encoder(v) {
2168
- return `{
2169
- "@type": "http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
2170
- "@value": ${v},
2171
- }`;
2172
- },
2173
- compactEncoder(v) {
2174
- return v;
2175
- },
2176
- dataCheck(v) {
2177
- return `typeof ${v} === "object" && "@type" in ${v}
2178
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#nonNegativeInteger"
2179
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
2180
- },
2181
- decoder(v) {
2182
- return `${v}["@value"]`;
2183
- }
2184
- },
2185
- "http://www.w3.org/2001/XMLSchema#float": {
2186
- name: "number",
2187
- typeGuard(v) {
2188
- return `typeof ${v} === "number" && !Number.isNaN(${v})`;
2189
- },
2190
- encoder(v) {
2191
- return `{
2192
- "@type": "http://www.w3.org/2001/XMLSchema#float",
2193
- "@value": ${v},
2194
- }`;
2195
- },
2196
- compactEncoder(v) {
2197
- return v;
2198
- },
2199
- dataCheck(v) {
2200
- return `typeof ${v} === "object" && "@type" in ${v}
2201
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#float"
2202
- && "@value" in ${v} && typeof ${v}["@value"] === "number"`;
2203
- },
2204
- decoder(v) {
2205
- return `${v}["@value"]`;
2206
- }
2207
- },
2208
- "http://www.w3.org/2001/XMLSchema#string": {
2209
- name: "string",
2210
- typeGuard(v) {
2211
- return `typeof ${v} === "string"`;
2212
- },
2213
- encoder(v) {
2214
- return `{ "@value": ${v} }`;
2215
- },
2216
- compactEncoder(v) {
2217
- return v;
2218
- },
2219
- dataCheck(v) {
2220
- return `typeof ${v} === "object" && "@value" in ${v}
2221
- && typeof ${v}["@value"] === "string" && !("@language" in ${v})`;
2222
- },
2223
- decoder(v) {
2224
- return `${v}["@value"]`;
2225
- }
2226
- },
2227
- "http://www.w3.org/2001/XMLSchema#anyURI": {
2228
- name: "URL",
2229
- typeGuard(v) {
2230
- return `${v} instanceof URL`;
2231
- },
2232
- encoder(v) {
2233
- return `{ "@id": ${v}.href }`;
2234
- },
2235
- compactEncoder(v) {
2236
- return `${v}.href`;
2237
- },
2238
- dataCheck(v) {
2239
- return `typeof ${v} === "object" && "@id" in ${v}
2240
- && typeof ${v}["@id"] === "string"
2241
- && ${v}["@id"] !== "" && ${v}["@id"] !== "/"`;
2242
- },
2243
- decoder(v) {
2244
- return `${v}["@id"].startsWith("at://")
2245
- ? new URL("at://" +
2246
- encodeURIComponent(
2247
- ${v}["@id"].includes("/", 5)
2248
- ? ${v}["@id"].slice(5, ${v}["@id"].indexOf("/", 5))
2249
- : ${v}["@id"].slice(5)
2250
- ) +
2251
- (
2252
- ${v}["@id"].includes("/", 5)
2253
- ? ${v}["@id"].slice(${v}["@id"].indexOf("/", 5))
2254
- : ""
2255
- )
2256
- )
2257
- : new URL(${v}["@id"])`;
2258
- }
2259
- },
2260
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString": {
2261
- name: "LanguageString",
2262
- typeGuard(v) {
2263
- return `${v} instanceof LanguageString`;
2264
- },
2265
- encoder(v) {
2266
- return `{
2267
- "@value": ${v}.toString(),
2268
- "@language": ${v}.locale.baseName,
2269
- }`;
2270
- },
2271
- dataCheck(v) {
2272
- return `typeof ${v} === "object" && "@language" in ${v} && "@value" in ${v}
2273
- && typeof ${v}["@language"] === "string"
2274
- && typeof ${v}["@value"] === "string"`;
2275
- },
2276
- decoder(v) {
2277
- return `new LanguageString(${v}["@value"], ${v}["@language"])`;
2278
- }
2279
- },
2280
- "http://www.w3.org/2001/XMLSchema#dateTime": {
2281
- name: "Temporal.Instant",
2282
- typeGuard(v) {
2283
- return `${v} instanceof Temporal.Instant`;
2284
- },
2285
- encoder(v) {
2286
- return `{
2287
- "@type": "http://www.w3.org/2001/XMLSchema#dateTime",
2288
- "@value": ${v}.toString(),
2289
- }`;
2290
- },
2291
- compactEncoder(v) {
2292
- return `${v}.toString()`;
2293
- },
2294
- dataCheck(v) {
2295
- return `typeof ${v} === "object" && "@type" in ${v}
2296
- && "@value" in ${v} && typeof ${v}["@value"] === "string"
2297
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#dateTime"
2298
- // Check if the value is a valid RFC 3339 date-time string
2299
- && new Date(${v}["@value"]).toString() !== "Invalid Date"
2300
- `;
2301
- },
2302
- decoder(v) {
2303
- return `Temporal.Instant.from(
2304
- ${v}["@value"].substring(19).match(/[Z+-]/)
2305
- ? ${v}["@value"]
2306
- : ${v}["@value"] + "Z"
2307
- )`;
2308
- }
2309
- },
2310
- "http://www.w3.org/2001/XMLSchema#duration": {
2311
- name: "Temporal.Duration",
2312
- typeGuard(v) {
2313
- return `${v} instanceof Temporal.Duration`;
2314
- },
2315
- encoder(v) {
2316
- return `{
2317
- "@type": "http://www.w3.org/2001/XMLSchema#duration",
2318
- "@value": ${v}.toString(),
2319
- }`;
2320
- },
2321
- compactEncoder(v) {
2322
- return `${v}.toString()`;
2323
- },
2324
- dataCheck(v) {
2325
- return `typeof ${v} === "object" && "@type" in ${v}
2326
- && "@value" in ${v} && typeof ${v}["@value"] === "string"
2327
- && ${v}["@type"] === "http://www.w3.org/2001/XMLSchema#duration"`;
2328
- },
2329
- decoder(v) {
2330
- return `Temporal.Duration.from(${v}["@value"])`;
2331
- }
2332
- },
2333
- "https://w3id.org/security#cryptosuiteString": {
2334
- name: "\"eddsa-jcs-2022\"",
2335
- typeGuard(v) {
2336
- return `${v} == "eddsa-jcs-2022"`;
2337
- },
2338
- encoder(v) {
2339
- return `{ "@value": ${v} }`;
2340
- },
2341
- compactEncoder(v) {
2342
- return v;
2343
- },
2344
- dataCheck(v) {
2345
- return `typeof ${v} === "object" && "@value" in ${v}
2346
- && !("@language" in ${v}) && ${v}["@value"] === "eddsa-jcs-2022"`;
2347
- },
2348
- decoder(v) {
2349
- return `${v}["@value"]`;
2350
- }
2351
- },
2352
- "https://w3id.org/security#multibase": {
2353
- name: "Uint8Array",
2354
- typeGuard(v) {
2355
- return `${v} instanceof Uint8Array`;
2356
- },
2357
- encoder(v) {
2358
- return `{
2359
- "@type": "https://w3id.org/security#multibase",
2360
- "@value": new TextDecoder().decode(encodeMultibase("base58btc", ${v})),
2361
- }`;
2362
- },
2363
- compactEncoder(v) {
2364
- return `new TextDecoder().decode(encodeMultibase("base58btc", ${v}))`;
2365
- },
2366
- dataCheck(v) {
2367
- return `typeof ${v} === "object" && "@value" in ${v}
2368
- && typeof ${v}["@value"] === "string"`;
2369
- },
2370
- decoder(v) {
2371
- return `decodeMultibase(${v}["@value"])`;
2372
- }
2373
- },
2374
- "fedify:langTag": {
2375
- name: "Intl.Locale",
2376
- typeGuard(v) {
2377
- return `${v} instanceof Intl.Locale`;
2378
- },
2379
- encoder(v) {
2380
- return `{ "@value": ${v}.baseName }`;
2381
- },
2382
- compactEncoder(v) {
2383
- return `${v}.baseName`;
2384
- },
2385
- dataCheck(v) {
2386
- return `typeof ${v} === "object" && "@value" in ${v}
2387
- && typeof ${v}["@value"] === "string" && !("@language" in ${v})`;
2388
- },
2389
- decoder(v) {
2390
- return `new Intl.Locale(${v}["@value"])`;
2391
- }
2392
- },
2393
- "fedify:url": {
2394
- name: "URL",
2395
- typeGuard(v) {
2396
- return `${v} instanceof URL`;
2397
- },
2398
- encoder(v) {
2399
- return `{ "@value": ${v}.href }`;
2400
- },
2401
- compactEncoder(v) {
2402
- return `${v}.href`;
2403
- },
2404
- dataCheck(v) {
2405
- return `typeof ${v} === "object" && "@value" in ${v}
2406
- && typeof ${v}["@value"] === "string"
2407
- && ${v}["@value"] !== "" && ${v}["@value"] !== "/"`;
2408
- },
2409
- decoder(v) {
2410
- return `new URL(${v}["@value"])`;
2411
- }
2412
- },
2413
- "fedify:publicKey": {
2414
- name: "CryptoKey",
2415
- typeGuard(v) {
2416
- return `
2417
- // @ts-ignore: CryptoKey exists in the global scope.
2418
- ${v} instanceof CryptoKey
2419
- `;
2420
- },
2421
- encoder(v) {
2422
- return `{ "@value": await exportSpki(${v}) }`;
2423
- },
2424
- compactEncoder(v) {
2425
- return `await exportSpki(${v})`;
2426
- },
2427
- dataCheck(v) {
2428
- return `typeof ${v} === "object" && "@value" in ${v}
2429
- && typeof ${v}["@value"] === "string"`;
2430
- },
2431
- decoder(v) {
2432
- return `await importPem(${v}["@value"])`;
2433
- }
2434
- },
2435
- "fedify:multibaseKey": {
2436
- name: "CryptoKey",
2437
- typeGuard(v) {
2438
- return `
2439
- // @ts-ignore: CryptoKey exists in the global scope.
2440
- ${v} instanceof CryptoKey
2441
- `;
2442
- },
2443
- encoder(v) {
2444
- return `{
2445
- "@type": "https://w3id.org/security#multibase",
2446
- "@value": await exportMultibaseKey(${v}),
2447
- }`;
2448
- },
2449
- compactEncoder(v) {
2450
- return `await exportMultibaseKey(${v})`;
2451
- },
2452
- dataCheck(v) {
2453
- return `typeof ${v} === "object" && "@value" in ${v}
2454
- && typeof ${v}["@value"] === "string"`;
2455
- },
2456
- decoder(v) {
2457
- return `await importMultibaseKey(${v}["@value"])`;
2458
- }
2459
- },
2460
- "fedify:proofPurpose": {
2461
- name: "\"assertionMethod\" | \"authentication\" | \"capabilityInvocation\" | \"capabilityDelegation\" | \"keyAgreement\"",
2462
- typeGuard(v) {
2463
- return `${v} === "assertionMethod" || ${v} === "authentication" ||
2464
- ${v} === "capabilityInvocation" || ${v} === "capabilityDelegation" ||
2465
- ${v} === "keyAgreement"`;
2466
- },
2467
- encoder(v) {
2468
- return `{
2469
- "@id": "https://w3id.org/security#" + ${v},
2470
- }`;
2471
- },
2472
- compactEncoder(v) {
2473
- return v;
2474
- },
2475
- dataCheck(v) {
2476
- return `typeof ${v} === "object" && "@id" in ${v}
2477
- && typeof ${v}["@id"] === "string"
2478
- && ${v}["@id"].startsWith("https://w3id.org/security#")
2479
- && [
2480
- "assertionMethod", "authentication", "capabilityInvocation",
2481
- "capabilityDelegation", "keyAgreement",
2482
- ].includes(${v}["@id"].substring(26))`;
2483
- },
2484
- decoder(v) {
2485
- return `${v}["@id"].substring(26)`;
2486
- }
2487
- },
2488
- "fedify:units": {
2489
- name: "\"cm\" | \"feet\" | \"inches\" | \"km\" | \"m\" | \"miles\"",
2490
- typeGuard(v) {
2491
- return `${v} == "cm" || ${v} == "feet" || ${v} == "inches" || ${v} == "km" || ${v} == "m" || ${v} == "miles"`;
2492
- },
2493
- encoder(v) {
2494
- return `{ "@value": ${v} }`;
2495
- },
2496
- compactEncoder(v) {
2497
- return v;
2498
- },
2499
- dataCheck(v) {
2500
- return `typeof ${v} === "object" && "@value" in ${v}
2501
- && (${v}["@value"] == "cm" || ${v}["@value"] == "feet" || ${v}["@value"] == "inches" || ${v}["@value"] == "km" || ${v}["@value"] == "m" || ${v}["@value"] == "miles")`;
2502
- },
2503
- decoder(v) {
2504
- return `${v}["@value"]`;
2505
- }
2506
- }
2507
- };
2508
- function isScalarType(typeUri, types$1) {
2509
- if (typeUri in scalarTypes) return true;
2510
- else if (typeUri in types$1) return !types$1[typeUri].entity;
2511
- throw new Error(`Unknown type: ${typeUri}`);
2512
- }
2513
- function areAllScalarTypes(typeUris, types$1) {
2514
- return typeUris.every((typeUri) => isScalarType(typeUri, types$1));
2515
- }
2516
-
2517
- //#endregion
2518
- //#region src/vocab/vocab.test.ts
2519
- test("new Object()", () => {
2520
- const obj = new Object$1({
2521
- name: "Test",
2522
- contents: [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]
2523
- });
2524
- assertEquals(obj.name, "Test");
2525
- assertEquals(obj.contents[0], new LanguageString("Hello", "en"));
2526
- assertEquals(obj.contents[1], new LanguageString("你好", "zh"));
2527
- assertThrows(() => new Object$1({ id: 123 }), TypeError, "The id must be a URL.");
2528
- assertThrows(() => new Object$1({
2529
- name: "singular",
2530
- names: ["plural"]
2531
- }), TypeError, "Cannot initialize both name and names at the same time.");
2532
- assertThrows(() => new Object$1({ name: 123 }), TypeError, "The name must be of type string | LanguageString.");
2533
- assertThrows(() => new Object$1({ names: "foo" }), TypeError, "The names must be an array of type string | LanguageString.");
2534
- assertThrows(() => new Object$1({ names: ["foo", 123] }), TypeError, "The names must be an array of type string | LanguageString.");
2535
- });
2536
- test("Object.clone()", () => {
2537
- const obj = new Object$1({
2538
- id: new URL("https://example.com/"),
2539
- name: "Test",
2540
- contents: [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]
2541
- });
2542
- const clone = obj.clone({ content: "Modified" });
2543
- assertInstanceOf(clone, Object$1);
2544
- assertEquals(clone.id, new URL("https://example.com/"));
2545
- assertEquals(clone.name, "Test");
2546
- assertEquals(clone.content, "Modified");
2547
- const cloned2 = obj.clone({ id: new URL("https://example.com/modified") });
2548
- assertInstanceOf(cloned2, Object$1);
2549
- assertEquals(cloned2.id, new URL("https://example.com/modified"));
2550
- assertEquals(cloned2.name, "Test");
2551
- assertEquals(cloned2.contents, [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]);
2552
- assertThrows(() => obj.clone({ id: 123 }), TypeError, "The id must be a URL.");
2553
- assertThrows(() => obj.clone({
2554
- name: "singular",
2555
- names: ["plural"]
2556
- }), TypeError, "Cannot update both name and names at the same time.");
2557
- assertThrows(() => obj.clone({ name: 123 }), TypeError, "The name must be of type string | LanguageString.");
2558
- assertThrows(() => obj.clone({ names: "foo" }), TypeError, "The names must be an array of type string | LanguageString.");
2559
- assertThrows(() => obj.clone({ names: ["foo", 123] }), TypeError, "The names must be an array of type string | LanguageString.");
2560
- });
2561
- test("Object.fromJsonLd()", async () => {
2562
- const obj = await Object$1.fromJsonLd({
2563
- "@context": "https://www.w3.org/ns/activitystreams",
2564
- "type": "Object",
2565
- "name": "Test",
2566
- "contentMap": {
2567
- "en": "Hello",
2568
- "zh": "你好"
2569
- },
2570
- "source": {
2571
- "content": "Hello",
2572
- "mediaType": "text/plain"
2573
- },
2574
- "published": "2025-01-01 12:34:56"
2575
- }, {
2576
- documentLoader: mockDocumentLoader,
2577
- contextLoader: mockDocumentLoader
2578
- });
2579
- assertInstanceOf(obj, Object$1);
2580
- assertEquals(obj.name, "Test");
2581
- assertEquals(obj.contents, [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]);
2582
- assertInstanceOf(obj.source, Source);
2583
- assertEquals(obj.source.content, "Hello");
2584
- assertEquals(obj.source.mediaType, "text/plain");
2585
- assertEquals(obj.published, Temporal.Instant.from("2025-01-01T12:34:56Z"));
2586
- const createJsonLd = {
2587
- "@context": "https://www.w3.org/ns/activitystreams",
2588
- "type": "Create",
2589
- "name": "Test",
2590
- "contentMap": {
2591
- "en": "Hello",
2592
- "zh": "你好"
2593
- },
2594
- "object": {
2595
- "type": "Note",
2596
- "content": "Content"
2597
- }
2598
- };
2599
- const create = await Object$1.fromJsonLd(createJsonLd, {
2600
- documentLoader: mockDocumentLoader,
2601
- contextLoader: mockDocumentLoader
2602
- });
2603
- assertInstanceOf(create, Create);
2604
- assertEquals(create.name, "Test");
2605
- assertEquals(create.contents, [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]);
2606
- assertEquals(await create.toJsonLd(), createJsonLd);
2607
- const note = await create.getObject();
2608
- assertInstanceOf(note, Note);
2609
- assertEquals(note.content, "Content");
2610
- const empty = await Object$1.fromJsonLd({});
2611
- assertInstanceOf(empty, Object$1);
2612
- await assertRejects(() => Object$1.fromJsonLd(null), TypeError, "Invalid JSON-LD: null.");
2613
- await assertRejects(() => Object$1.fromJsonLd(void 0), TypeError, "Invalid JSON-LD: undefined.");
2614
- });
2615
- test("Object.toJsonLd()", async () => {
2616
- const obj = new Object$1({
2617
- name: "Test",
2618
- contents: [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]
2619
- });
2620
- assertEquals(await obj.toJsonLd({
2621
- format: "expand",
2622
- contextLoader: mockDocumentLoader
2623
- }), [{
2624
- "@type": ["https://www.w3.org/ns/activitystreams#Object"],
2625
- "https://www.w3.org/ns/activitystreams#name": [{ "@value": "Test" }],
2626
- "https://www.w3.org/ns/activitystreams#content": [{
2627
- "@value": "Hello",
2628
- "@language": "en"
2629
- }, {
2630
- "@value": "你好",
2631
- "@language": "zh"
2632
- }]
2633
- }]);
2634
- assertEquals(await obj.toJsonLd({ contextLoader: mockDocumentLoader }), {
2635
- "@context": [
2636
- "https://www.w3.org/ns/activitystreams",
2637
- "https://w3id.org/security/data-integrity/v1",
2638
- {
2639
- fedibird: "http://fedibird.com/ns#",
2640
- sensitive: "as:sensitive",
2641
- emojiReactions: {
2642
- "@id": "fedibird:emojiReactions",
2643
- "@type": "@id"
2644
- }
2645
- }
2646
- ],
2647
- type: "Object",
2648
- name: "Test",
2649
- contentMap: {
2650
- en: "Hello",
2651
- zh: "你好"
2652
- }
2653
- });
2654
- });
2655
- test("Note.toJsonLd()", async () => {
2656
- const note = new Note({ tags: [new Hashtag({
2657
- name: "#Fedify",
2658
- href: new URL("https://fedify.dev/")
2659
- })] });
2660
- assertEquals(await note.toJsonLd({ contextLoader: mockDocumentLoader }), {
2661
- "@context": [
2662
- "https://www.w3.org/ns/activitystreams",
2663
- "https://w3id.org/security/data-integrity/v1",
2664
- {
2665
- Emoji: "toot:Emoji",
2666
- Hashtag: "as:Hashtag",
2667
- _misskey_quote: "misskey:_misskey_quote",
2668
- fedibird: "http://fedibird.com/ns#",
2669
- misskey: "https://misskey-hub.net/ns#",
2670
- quoteUri: "fedibird:quoteUri",
2671
- quoteUrl: "as:quoteUrl",
2672
- sensitive: "as:sensitive",
2673
- toot: "http://joinmastodon.org/ns#",
2674
- emojiReactions: {
2675
- "@id": "fedibird:emojiReactions",
2676
- "@type": "@id"
2677
- }
2678
- }
2679
- ],
2680
- tag: {
2681
- "@context": ["https://www.w3.org/ns/activitystreams", { Hashtag: "as:Hashtag" }],
2682
- href: "https://fedify.dev/",
2683
- name: "#Fedify",
2684
- type: "Hashtag"
2685
- },
2686
- type: "Note"
2687
- });
2688
- const noteWithName = note.clone({ name: "Test" });
2689
- assertEquals(await noteWithName.toJsonLd({ contextLoader: mockDocumentLoader }), await noteWithName.toJsonLd({
2690
- contextLoader: mockDocumentLoader,
2691
- format: "compact"
2692
- }));
2693
- });
2694
- test("Activity.fromJsonLd()", async () => {
2695
- const follow = await Activity.fromJsonLd({
2696
- "@context": "https://www.w3.org/ns/activitystreams",
2697
- id: "https://activitypub.academy/80c50305-7405-4e38-809f-697647a1f679",
2698
- type: "Follow",
2699
- actor: "https://activitypub.academy/users/egulia_anbeiss",
2700
- object: "https://example.com/users/hongminhee"
2701
- }, {
2702
- documentLoader: mockDocumentLoader,
2703
- contextLoader: mockDocumentLoader
2704
- });
2705
- assertInstanceOf(follow, Follow);
2706
- assertEquals(follow.id, new URL("https://activitypub.academy/80c50305-7405-4e38-809f-697647a1f679"));
2707
- assertEquals(follow.actorId, new URL("https://activitypub.academy/users/egulia_anbeiss"));
2708
- assertEquals(follow.objectId, new URL("https://example.com/users/hongminhee"));
2709
- const create = await Activity.fromJsonLd({
2710
- "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"],
2711
- type: "Create",
2712
- actor: "https://server.example/users/alice",
2713
- object: {
2714
- type: "Note",
2715
- content: "Hello world"
2716
- },
2717
- proof: {
2718
- type: "DataIntegrityProof",
2719
- cryptosuite: "eddsa-jcs-2022",
2720
- verificationMethod: "https://server.example/users/alice#ed25519-key",
2721
- proofPurpose: "assertionMethod",
2722
- proofValue: "z3sXaxjKs4M3BRicwWA9peyNPJvJqxtGsDmpt1jjoHCjgeUf71TRFz56osPSfDErszyLp5Ks1EhYSgpDaNM977Rg2",
2723
- created: "2023-02-24T23:36:38Z"
2724
- }
2725
- }, {
2726
- documentLoader: mockDocumentLoader,
2727
- contextLoader: mockDocumentLoader
2728
- });
2729
- const proofs = [];
2730
- for await (const proof of create.getProofs()) proofs.push(proof);
2731
- assertEquals(proofs.length, 1);
2732
- assertEquals(proofs[0].cryptosuite, "eddsa-jcs-2022");
2733
- assertEquals(proofs[0].verificationMethodId, new URL("https://server.example/users/alice#ed25519-key"));
2734
- assertEquals(proofs[0].proofPurpose, "assertionMethod");
2735
- assertEquals(proofs[0].proofValue, decode("z3sXaxjKs4M3BRicwWA9peyNPJvJqxtGsDmpt1jjoHCjgeUf71TRFz56osPSfDErszyLp5Ks1EhYSgpDaNM977Rg2"));
2736
- assertEquals(proofs[0].created, Temporal.Instant.from("2023-02-24T23:36:38Z"));
2737
- });
2738
- test({
2739
- name: "Activity.getObject()",
2740
- permissions: {
2741
- env: true,
2742
- read: true
2743
- },
2744
- async fn() {
2745
- const activity = new Activity({ object: new URL("https://example.com/announce") });
2746
- const announce = await activity.getObject({
2747
- documentLoader: mockDocumentLoader,
2748
- contextLoader: mockDocumentLoader
2749
- });
2750
- assertInstanceOf(announce, Announce);
2751
- assertEquals(announce.id, new URL("https://example.com/announce"));
2752
- const object = await announce.getObject();
2753
- assertInstanceOf(object, Object$1);
2754
- assertEquals(object.id, new URL("https://example.com/object"));
2755
- assertEquals(object.name, "Fetched object");
2756
- const jsonLd = await activity.toJsonLd();
2757
- assertEquals(jsonLd, {
2758
- "@context": [
2759
- "https://w3id.org/identity/v1",
2760
- "https://www.w3.org/ns/activitystreams",
2761
- "https://w3id.org/security/v1",
2762
- "https://w3id.org/security/data-integrity/v1"
2763
- ],
2764
- type: "Activity",
2765
- object: {
2766
- id: "https://example.com/announce",
2767
- type: "Announce",
2768
- object: {
2769
- type: "Object",
2770
- id: "https://example.com/object",
2771
- name: "Fetched object"
2772
- }
2773
- }
2774
- });
2775
- const activity2 = new Activity({ object: new URL("https://example.com/not-found") });
2776
- assertEquals(await activity2.getObject({ suppressError: true }), null);
2777
- const activity3 = await Activity.fromJsonLd({
2778
- "@context": "https://www.w3.org/ns/activitystreams",
2779
- type: "Create",
2780
- object: {
2781
- "@context": "https://www.w3.org/ns/activitystreams",
2782
- type: "Note",
2783
- content: "Hello world"
2784
- }
2785
- });
2786
- const object3 = await activity3.getObject();
2787
- assertInstanceOf(object3, Note);
2788
- assertEquals(await object3.toJsonLd(), {
2789
- "@context": "https://www.w3.org/ns/activitystreams",
2790
- type: "Note",
2791
- content: "Hello world"
2792
- });
2793
- }
2794
- });
2795
- test({
2796
- name: "Activity.getObjects()",
2797
- permissions: {
2798
- env: true,
2799
- read: true
2800
- },
2801
- async fn() {
2802
- const activity = new Activity({ objects: [new URL("https://example.com/object"), new Object$1({ name: "Second object" })] });
2803
- const objects = await Array.fromAsync(activity.getObjects({
2804
- documentLoader: mockDocumentLoader,
2805
- contextLoader: mockDocumentLoader
2806
- }));
2807
- assertEquals(objects.length, 2);
2808
- assertInstanceOf(objects[0], Object$1);
2809
- assertEquals(objects[0].id, new URL("https://example.com/object"));
2810
- assertEquals(objects[0].name, "Fetched object");
2811
- assertInstanceOf(objects[1], Object$1);
2812
- assertEquals(objects[1].name, "Second object");
2813
- const activity2 = new Activity({ objects: [new URL("https://example.com/not-found"), new Object$1({ name: "Second object" })] });
2814
- const objects2 = await Array.fromAsync(activity2.getObjects({ suppressError: true }));
2815
- assertEquals(objects2.length, 1);
2816
- assertInstanceOf(objects2[0], Object$1);
2817
- assertEquals(objects2[0].name, "Second object");
2818
- }
2819
- });
2820
- test("Activity.clone()", async () => {
2821
- const activity = new Activity({
2822
- actor: new Person({ name: "John Doe" }),
2823
- object: new Object$1({ name: "Test" }),
2824
- name: "Test",
2825
- summary: "Test"
2826
- });
2827
- const clone = activity.clone({
2828
- object: new Object$1({ name: "Modified" }),
2829
- summary: "Modified"
2830
- });
2831
- assertEquals((await activity.getActor())?.name, "John Doe");
2832
- assertEquals((await clone.getActor())?.name, "John Doe");
2833
- assertEquals((await activity.getObject())?.name, "Test");
2834
- assertEquals((await clone.getObject())?.name, "Modified");
2835
- assertEquals(activity.name, "Test");
2836
- assertEquals(clone.name, "Test");
2837
- assertEquals(activity.summary, "Test");
2838
- assertEquals(clone.summary, "Modified");
2839
- assertThrows(() => activity.clone({
2840
- summary: "singular",
2841
- summaries: ["plural"]
2842
- }), TypeError, "Cannot update both summary and summaries at the same time.");
2843
- });
2844
- test("Question.voters", async () => {
2845
- const question = new Question({ voters: 123 });
2846
- const json = await question.toJsonLd({ format: "compact" });
2847
- assert(typeof json === "object" && json != null);
2848
- assert("votersCount" in json);
2849
- assertEquals(json["votersCount"], 123);
2850
- });
2851
- test({
2852
- name: "Deno.inspect(Object)",
2853
- ignore: !("Deno" in globalThis),
2854
- fn() {
2855
- const obj = new Object$1({
2856
- id: new URL("https://example.com/"),
2857
- attribution: new URL("https://example.com/foo"),
2858
- name: "Test",
2859
- contents: [new LanguageString("Hello", "en"), new LanguageString("你好", "zh")]
2860
- });
2861
- assertEquals(Deno.inspect(obj, {
2862
- colors: false,
2863
- sorted: true,
2864
- compact: false
2865
- }), "Deno" in globalThis ? "Object {\n attribution: URL \"https://example.com/foo\",\n contents: [\n <en> \"Hello\",\n <zh> \"你好\"\n ],\n id: URL \"https://example.com/\",\n name: \"Test\"\n}" : "Object {\n attribution: URL 'https://example.com/foo',\n contents: [\n <en> 'Hello',\n <zh> '你好'\n ],\n id: URL 'https://example.com/',\n name: 'Test'\n}");
2866
- }
2867
- });
2868
- test("Person.fromJsonLd()", async () => {
2869
- const person = await Person.fromJsonLd({
2870
- "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
2871
- "publicKey": {
2872
- "id": "https://todon.eu/users/hongminhee#main-key",
2873
- "owner": "https://todon.eu/users/hongminhee",
2874
- "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsRuvCkgJtflBTl4OVsm\nnt/J1mQfZasfJtN33dcZ3d1lJroxmgmMu69zjGEAwkNbMQaWNLqC4eogkJaeJ4RR\n5MHYXkL9nNilVoTkjX5BVit3puzs7XJ7WQnKQgQMI+ezn24GHsZ/v1JIo77lerX5\nk4HNwTNVt+yaZVQWaOMR3+6FwziQR6kd0VuG9/a9dgAnz2cEoORRC1i4W7IZaB1s\nZnh1WbHbevlGd72HSXll5rocPIHn8gq6xpBgpHwRphlRsgn4KHaJ6brXDIJjrnQh\nIe/YUBOGj/ImSEXhRwlFerKsoAVnZ0Hwbfa46qk44TAt8CyoPMWmpK6pt0ng4pQ2\nuwIDAQAB\n-----END PUBLIC KEY-----\n"
2875
- }
2876
- }, {
2877
- documentLoader: mockDocumentLoader,
2878
- contextLoader: mockDocumentLoader
2879
- });
2880
- assertEquals(person.publicKeyId, new URL("https://todon.eu/users/hongminhee#main-key"));
2881
- const publicKey = await person.getPublicKey({ documentLoader: mockDocumentLoader });
2882
- assertInstanceOf(publicKey, CryptographicKey);
2883
- assertEquals(publicKey?.ownerId, new URL("https://todon.eu/users/hongminhee"));
2884
- const person2 = await Person.fromJsonLd({
2885
- "@context": ["https://www.w3.org/ns/activitystreams", { alsoKnownAs: {
2886
- "@id": "as:alsoKnownAs",
2887
- "@type": "@id"
2888
- } }],
2889
- "type": "Person",
2890
- "alsoKnownAs": "at://did:plc:x7xdowahlhm5xulzqw4ehv6q"
2891
- });
2892
- assertEquals(person2.aliasId, new URL("at://did%3Aplc%3Ax7xdowahlhm5xulzqw4ehv6q"));
2893
- });
2894
- test("Person.toJsonLd()", async () => {
2895
- const person = new Person({ aliases: [new URL("https://example.com/alias")] });
2896
- assertEquals(await person.toJsonLd(), {
2897
- "@context": [
2898
- "https://www.w3.org/ns/activitystreams",
2899
- "https://w3id.org/security/v1",
2900
- "https://w3id.org/security/data-integrity/v1",
2901
- "https://www.w3.org/ns/did/v1",
2902
- "https://w3id.org/security/multikey/v1",
2903
- {
2904
- PropertyValue: "schema:PropertyValue",
2905
- alsoKnownAs: {
2906
- "@id": "as:alsoKnownAs",
2907
- "@type": "@id"
2908
- },
2909
- movedTo: {
2910
- "@id": "as:movedTo",
2911
- "@type": "@id"
2912
- },
2913
- discoverable: "toot:discoverable",
2914
- featured: {
2915
- "@id": "toot:featured",
2916
- "@type": "@id"
2917
- },
2918
- featuredTags: {
2919
- "@id": "toot:featuredTags",
2920
- "@type": "@id"
2921
- },
2922
- indexable: "toot:indexable",
2923
- _misskey_followedMessage: "misskey:_misskey_followedMessage",
2924
- isCat: "misskey:isCat",
2925
- manuallyApprovesFollowers: "as:manuallyApprovesFollowers",
2926
- memorial: "toot:memorial",
2927
- misskey: "https://misskey-hub.net/ns#",
2928
- schema: "http://schema.org#",
2929
- suspended: "toot:suspended",
2930
- toot: "http://joinmastodon.org/ns#",
2931
- value: "schema:value",
2932
- Emoji: "toot:Emoji"
2933
- }
2934
- ],
2935
- alsoKnownAs: "https://example.com/alias",
2936
- type: "Person"
2937
- });
2938
- });
2939
- test("Collection.fromJsonLd()", async () => {
2940
- const collection = await Collection.fromJsonLd({
2941
- "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/fep/5711"],
2942
- "type": "Collection",
2943
- "id": "https://example.com/collection/jzc50wc28l",
2944
- "inboxOf": "https://example.com/person/bup9a8eqm"
2945
- });
2946
- assertEquals(collection.id, new URL("https://example.com/collection/jzc50wc28l"));
2947
- assertEquals(collection.inboxOfId, new URL("https://example.com/person/bup9a8eqm"));
2948
- });
2949
- test("Note.quoteUrl", async () => {
2950
- const note = new Note({ quoteUrl: new URL("https://example.com/object") });
2951
- const expected = {
2952
- "@context": [
2953
- "https://www.w3.org/ns/activitystreams",
2954
- "https://w3id.org/security/data-integrity/v1",
2955
- {
2956
- Emoji: "toot:Emoji",
2957
- Hashtag: "as:Hashtag",
2958
- _misskey_quote: "misskey:_misskey_quote",
2959
- fedibird: "http://fedibird.com/ns#",
2960
- misskey: "https://misskey-hub.net/ns#",
2961
- quoteUri: "fedibird:quoteUri",
2962
- quoteUrl: "as:quoteUrl",
2963
- sensitive: "as:sensitive",
2964
- toot: "http://joinmastodon.org/ns#",
2965
- emojiReactions: {
2966
- "@id": "fedibird:emojiReactions",
2967
- "@type": "@id"
2968
- }
2969
- }
2970
- ],
2971
- _misskey_quote: "https://example.com/object",
2972
- quoteUri: "https://example.com/object",
2973
- quoteUrl: "https://example.com/object",
2974
- type: "Note"
2975
- };
2976
- assertEquals(await note.toJsonLd(), expected);
2977
- assertEquals(await note.toJsonLd({ format: "compact" }), expected);
2978
- const jsonLd = {
2979
- "@context": ["https://www.w3.org/ns/activitystreams", {
2980
- _misskey_quote: "misskey:_misskey_quote",
2981
- fedibird: "http://fedibird.com/ns#",
2982
- misskey: "https://misskey-hub.net/ns#",
2983
- quoteUri: "fedibird:quoteUri",
2984
- quoteUrl: "as:quoteUrl"
2985
- }],
2986
- type: "Note",
2987
- quoteUrl: "https://example.com/object",
2988
- _misskey_quote: "https://example.com/object2",
2989
- quoteUri: "https://example.com/object3"
2990
- };
2991
- const loaded = await Note.fromJsonLd(jsonLd);
2992
- assertEquals(loaded.quoteUrl, new URL("https://example.com/object"));
2993
- delete jsonLd.quoteUrl;
2994
- const loaded2 = await Note.fromJsonLd(jsonLd);
2995
- assertEquals(loaded2.quoteUrl, new URL("https://example.com/object2"));
2996
- delete jsonLd._misskey_quote;
2997
- const loaded3 = await Note.fromJsonLd(jsonLd);
2998
- assertEquals(loaded3.quoteUrl, new URL("https://example.com/object3"));
2999
- });
3000
- test("Key.publicKey", async () => {
3001
- const jwk = {
3002
- kty: "RSA",
3003
- alg: "RS256",
3004
- n: "xsRuvCkgJtflBTl4OVsmnt_J1mQfZasfJtN33dcZ3d1lJroxmgmMu69zjGEAwkNbMQaWNLqC4eogkJaeJ4RR5MHYXkL9nNilVoTkjX5BVit3puzs7XJ7WQnKQgQMI-ezn24GHsZ_v1JIo77lerX5k4HNwTNVt-yaZVQWaOMR3-6FwziQR6kd0VuG9_a9dgAnz2cEoORRC1i4W7IZaB1sZnh1WbHbevlGd72HSXll5rocPIHn8gq6xpBgpHwRphlRsgn4KHaJ6brXDIJjrnQhIe_YUBOGj_ImSEXhRwlFerKsoAVnZ0Hwbfa46qk44TAt8CyoPMWmpK6pt0ng4pQ2uw",
3005
- e: "AQAB",
3006
- key_ops: ["verify"],
3007
- ext: true
3008
- };
3009
- const key = new CryptographicKey({ publicKey: await crypto.subtle.importKey("jwk", jwk, {
3010
- name: "RSASSA-PKCS1-v1_5",
3011
- hash: "SHA-256"
3012
- }, true, ["verify"]) });
3013
- const jsonLd = await key.toJsonLd({ contextLoader: mockDocumentLoader });
3014
- assertEquals(jsonLd, {
3015
- "@context": "https://w3id.org/security/v1",
3016
- publicKeyPem: "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxsRuvCkgJtflBTl4OVsm\nnt/J1mQfZasfJtN33dcZ3d1lJroxmgmMu69zjGEAwkNbMQaWNLqC4eogkJaeJ4RR\n5MHYXkL9nNilVoTkjX5BVit3puzs7XJ7WQnKQgQMI+ezn24GHsZ/v1JIo77lerX5\nk4HNwTNVt+yaZVQWaOMR3+6FwziQR6kd0VuG9/a9dgAnz2cEoORRC1i4W7IZaB1s\nZnh1WbHbevlGd72HSXll5rocPIHn8gq6xpBgpHwRphlRsgn4KHaJ6brXDIJjrnQh\nIe/YUBOGj/ImSEXhRwlFerKsoAVnZ0Hwbfa46qk44TAt8CyoPMWmpK6pt0ng4pQ2\nuwIDAQAB\n-----END PUBLIC KEY-----\n",
3017
- type: "CryptographicKey"
3018
- });
3019
- const loadedKey = await CryptographicKey.fromJsonLd(jsonLd, {
3020
- documentLoader: mockDocumentLoader,
3021
- contextLoader: mockDocumentLoader
3022
- });
3023
- assertNotEquals(loadedKey.publicKey, null);
3024
- assertEquals(await crypto.subtle.exportKey("jwk", loadedKey.publicKey), jwk);
3025
- });
3026
- test("Place.fromJsonLd()", async () => {
3027
- const place = await Place.fromJsonLd({
3028
- "@context": "https://www.w3.org/ns/activitystreams",
3029
- type: "Place",
3030
- name: "Fresno Area",
3031
- latitude: 36.75,
3032
- longitude: 119.7667,
3033
- radius: 15,
3034
- units: "miles"
3035
- }, {
3036
- documentLoader: mockDocumentLoader,
3037
- contextLoader: mockDocumentLoader
3038
- });
3039
- assertInstanceOf(place, Place);
3040
- assertEquals(place.name, "Fresno Area");
3041
- assertEquals(place.latitude, 36.75);
3042
- assertEquals(place.longitude, 119.7667);
3043
- assertEquals(place.radius, 15);
3044
- assertEquals(place.units, "miles");
3045
- let jsonLd = await place.toJsonLd({ contextLoader: mockDocumentLoader });
3046
- assertEquals(jsonLd, {
3047
- "@context": "https://www.w3.org/ns/activitystreams",
3048
- type: "Place",
3049
- name: "Fresno Area",
3050
- latitude: 36.75,
3051
- longitude: 119.7667,
3052
- radius: 15,
3053
- units: "miles"
3054
- });
3055
- jsonLd = await place.toJsonLd({
3056
- format: "compact",
3057
- contextLoader: mockDocumentLoader
3058
- });
3059
- assertEquals(jsonLd, {
3060
- "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"],
3061
- type: "Place",
3062
- name: "Fresno Area",
3063
- latitude: 36.75,
3064
- longitude: 119.7667,
3065
- radius: 15,
3066
- units: "miles"
3067
- });
3068
- });
3069
- test("Actor.getOutbox()", async () => {
3070
- const person = new Person({ outbox: new URL("https://example.com/orderedcollectionpage") });
3071
- const outbox = await person.getOutbox({ documentLoader: mockDocumentLoader });
3072
- assertInstanceOf(outbox, OrderedCollectionPage);
3073
- assertEquals(outbox.totalItems, 1);
3074
- });
3075
- test("Link.fromJsonLd()", async () => {
3076
- const link = await Link.fromJsonLd({
3077
- "@context": "https://www.w3.org/ns/activitystreams",
3078
- "type": "Link",
3079
- "rel": "canonical",
3080
- "href": "at://did:plc:ia76kvnndjutgedggx2ibrem/app.bsky.feed.post/3lyxjjs27jkqg"
3081
- });
3082
- assertEquals(link.rel, "canonical");
3083
- assertEquals(link.href, new URL("at://did%3Aplc%3Aia76kvnndjutgedggx2ibrem/app.bsky.feed.post/3lyxjjs27jkqg"));
3084
- const link2 = await Link.fromJsonLd({
3085
- "@context": "https://www.w3.org/ns/activitystreams",
3086
- "type": "Link",
3087
- "href": "at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26"
3088
- });
3089
- assertEquals(link2.href, new URL("at://bnewbold.bsky.team/app.bsky.feed.post/3jwdwj2ctlk26"));
3090
- const link3 = await Link.fromJsonLd({
3091
- "@context": "https://www.w3.org/ns/activitystreams",
3092
- "type": "Link",
3093
- "href": "at://did:plc:ia76kvnndjutgedggx2ibrem"
3094
- });
3095
- assertEquals(link3.href, new URL("at://did%3Aplc%3Aia76kvnndjutgedggx2ibrem"));
3096
- });
3097
- function getAllProperties(type, types$1) {
3098
- const props = type.properties;
3099
- if (type.extends != null) props.push(...getAllProperties(types$1[type.extends], types$1));
3100
- return props;
3101
- }
3102
- const sampleValues = {
3103
- "http://www.w3.org/2001/XMLSchema#boolean": true,
3104
- "http://www.w3.org/2001/XMLSchema#integer": -123,
3105
- "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": 123,
3106
- "http://www.w3.org/2001/XMLSchema#float": 12.34,
3107
- "http://www.w3.org/2001/XMLSchema#string": "hello",
3108
- "http://www.w3.org/2001/XMLSchema#anyURI": new URL("https://example.com/"),
3109
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString": new LanguageString("hello", "en"),
3110
- "http://www.w3.org/2001/XMLSchema#dateTime": Temporal.Instant.from("2024-03-03T08:30:06.796196096Z"),
3111
- "http://www.w3.org/2001/XMLSchema#duration": Temporal.Duration.from({ hours: 1 }),
3112
- "https://w3id.org/security#cryptosuiteString": "eddsa-jcs-2022",
3113
- "https://w3id.org/security#multibase": new Uint8Array([
3114
- 143,
3115
- 155,
3116
- 90,
3117
- 201,
3118
- 20,
3119
- 23,
3120
- 208,
3121
- 209,
3122
- 136,
3123
- 190,
3124
- 250,
3125
- 133,
3126
- 143,
3127
- 116,
3128
- 68,
3129
- 152,
3130
- 29,
3131
- 200,
3132
- 121,
3133
- 218,
3134
- 186,
3135
- 80,
3136
- 152,
3137
- 60,
3138
- 67,
3139
- 235,
3140
- 207,
3141
- 114,
3142
- 95,
3143
- 56,
3144
- 88,
3145
- 17,
3146
- 159,
3147
- 35,
3148
- 197,
3149
- 191,
3150
- 132,
3151
- 35,
3152
- 118,
3153
- 162,
3154
- 29,
3155
- 83,
3156
- 192,
3157
- 190,
3158
- 26,
3159
- 170,
3160
- 150,
3161
- 110,
3162
- 48,
3163
- 101,
3164
- 89,
3165
- 118,
3166
- 240,
3167
- 176,
3168
- 219,
3169
- 120,
3170
- 13,
3171
- 245,
3172
- 193,
3173
- 173,
3174
- 63,
3175
- 189,
3176
- 243,
3177
- 7
3178
- ]),
3179
- "fedify:langTag": new Intl.Locale("en-Latn-US"),
3180
- "fedify:url": new URL("https://fedify.dev/"),
3181
- "fedify:publicKey": rsaPublicKey1.publicKey,
3182
- "fedify:multibaseKey": ed25519PublicKey.publicKey,
3183
- "fedify:proofPurpose": "assertionMethod",
3184
- "fedify:units": "m"
3185
- };
3186
- const types = navigator?.userAgent === "Cloudflare-Workers" ? {} : await loadSchemaFiles(import.meta.dirname);
3187
- for (const typeUri in types) {
3188
- const type = types[typeUri];
3189
- const cls = vocab_exports[type.name];
3190
- sampleValues[typeUri] = new cls({
3191
- "@id": "https://example.com/",
3192
- "@type": typeUri
3193
- });
3194
- }
3195
- for (const typeUri in types) {
3196
- const type = types[typeUri];
3197
- const cls = vocab_exports[type.name];
3198
- const allProperties = getAllProperties(type, types);
3199
- const initValues = globalThis.Object.fromEntries(allProperties.map((property) => !property.functional ? [property.pluralName, property.range.map((t) => sampleValues[t])] : [property.singularName, sampleValues[property.range[0]]]));
3200
- test(`new ${type.name}() [auto]`, async () => {
3201
- const instance = new cls(initValues);
3202
- for (const property of allProperties) {
3203
- if (areAllScalarTypes(property.range, types)) {
3204
- if (property.functional || property.singularAccessor) assertEquals(instance[property.singularName], sampleValues[property.range[0]]);
3205
- if (!property.functional) assertEquals(instance[property.pluralName], property.range.map((t) => sampleValues[t]));
3206
- } else {
3207
- if (property.functional || property.singularAccessor) {
3208
- assertEquals(await instance[`get${pascalCase(property.singularName)}`].call(instance, { documentLoader: mockDocumentLoader }), sampleValues[property.range[0]]);
3209
- assertEquals(instance[`${property.singularName}Id`], sampleValues[property.range[0]].id);
3210
- }
3211
- if (!property.functional) {
3212
- assertEquals(await Array.fromAsync(instance[`get${pascalCase(property.pluralName)}`].call(instance, { documentLoader: mockDocumentLoader })), property.range.map((t) => sampleValues[t]));
3213
- assertEquals(instance[`${property.singularName}Ids`], property.range.map((t) => sampleValues[t].id).filter((i) => i != null));
3214
- }
3215
- }
3216
- const empty = new cls({});
3217
- for (const property$1 of allProperties) if (areAllScalarTypes(property$1.range, types)) {
3218
- if (property$1.functional || property$1.singularAccessor) assertEquals(empty[property$1.singularName], null);
3219
- if (!property$1.functional) assertEquals(empty[property$1.pluralName], []);
3220
- } else {
3221
- if (property$1.functional || property$1.singularAccessor) {
3222
- assertEquals(await empty[`get${pascalCase(property$1.singularName)}`].call(empty, { documentLoader: mockDocumentLoader }), null);
3223
- assertEquals(empty[`${property$1.singularName}Id`], null);
3224
- }
3225
- if (!property$1.functional) {
3226
- assertEquals(await Array.fromAsync(empty[`get${pascalCase(property$1.pluralName)}`].call(empty, { documentLoader: mockDocumentLoader })), []);
3227
- assertEquals(empty[`${property$1.singularName}Ids`], []);
3228
- }
3229
- }
3230
- }
3231
- for (const property of allProperties) if (!property.functional && property.singularAccessor) assertThrows(() => new cls({
3232
- [property.singularName]: sampleValues[property.range[0]],
3233
- [property.pluralName]: property.range.map((t) => sampleValues[t])
3234
- }), TypeError);
3235
- const instance2 = new cls({
3236
- id: new URL("https://example.com/"),
3237
- ...globalThis.Object.fromEntries(allProperties.filter((p) => !areAllScalarTypes(p.range, types)).map((p) => p.functional ? [p.singularName, new URL("https://example.com/test")] : [p.pluralName, [new URL("https://example.com/test")]]))
3238
- });
3239
- for (const property of allProperties) {
3240
- if (areAllScalarTypes(property.range, types)) continue;
3241
- if (property.functional || property.singularAccessor) assertEquals(instance2[`${property.singularName}Id`], new URL("https://example.com/test"));
3242
- if (!property.functional) assertEquals(instance2[`${property.singularName}Ids`], [new URL("https://example.com/test")]);
3243
- }
3244
- assertThrows(() => new cls({ id: 123 }), TypeError, "The id must be a URL.");
3245
- for (const property of allProperties) {
3246
- const wrongValues = globalThis.Object.fromEntries(globalThis.Object.entries(initValues));
3247
- if (property.functional) wrongValues[property.singularName] = {};
3248
- else wrongValues[property.pluralName] = [{}];
3249
- assertThrows(() => new cls(wrongValues), TypeError);
3250
- }
3251
- });
3252
- test(`${type.name}.clone() [auto]`, () => {
3253
- const instance = new cls({});
3254
- for (const property of allProperties) if (!property.functional && property.singularAccessor) assertThrows(() => instance.clone({
3255
- [property.singularName]: sampleValues[property.range[0]],
3256
- [property.pluralName]: property.range.map((t) => sampleValues[t])
3257
- }), TypeError);
3258
- assertThrows(() => instance.clone({ id: 123 }), TypeError, "The id must be a URL.");
3259
- for (const property of allProperties) {
3260
- const wrongValues = globalThis.Object.fromEntries(globalThis.Object.entries(initValues));
3261
- if (property.functional) wrongValues[property.singularName] = {};
3262
- else wrongValues[property.pluralName] = [{}];
3263
- assertThrows(() => instance.clone(wrongValues), TypeError);
3264
- }
3265
- });
3266
- for (const property of allProperties) {
3267
- if (areAllScalarTypes(property.range, types)) continue;
3268
- const docLoader = async (url) => {
3269
- if (url !== `https://example.com/test`) throw new Error("Not Found");
3270
- return {
3271
- documentUrl: url,
3272
- contextUrl: null,
3273
- document: await sampleValues[property.range[0]].toJsonLd({ contextLoader: mockDocumentLoader })
3274
- };
3275
- };
3276
- if (property.functional || property.singularAccessor) test(`${type.name}.get${pascalCase(property.singularName)}() [auto]`, async () => {
3277
- const instance = new cls({ [property.singularName]: new URL("https://example.com/test") });
3278
- const value = await instance[`get${pascalCase(property.singularName)}`].call(instance, { documentLoader: docLoader });
3279
- assertEquals(value, sampleValues[property.range[0]]);
3280
- if (property.untyped) return;
3281
- const wrongRef = new cls({ [property.singularName]: new URL("https://example.com/wrong-type") });
3282
- await assertRejects(() => wrongRef[`get${pascalCase(property.singularName)}`].call(wrongRef, { documentLoader: mockDocumentLoader }), TypeError);
3283
- });
3284
- if (!property.functional) test(`${type.name}.get${pascalCase(property.pluralName)}() [auto]`, async () => {
3285
- const instance = new cls({ [property.pluralName]: [new URL("https://example.com/test")] });
3286
- const value = instance[`get${pascalCase(property.pluralName)}`].call(instance, { documentLoader: docLoader });
3287
- assertEquals(await Array.fromAsync(value), [sampleValues[property.range[0]]]);
3288
- if (property.untyped) return;
3289
- const wrongRef = new cls({ [property.pluralName]: [new URL("https://example.com/wrong-type")] });
3290
- await assertRejects(() => Array.fromAsync(wrongRef[`get${pascalCase(property.pluralName)}`].call(wrongRef, { documentLoader: mockDocumentLoader })), TypeError);
3291
- });
3292
- }
3293
- test(`${type.name}.fromJsonLd() [auto]`, async () => {
3294
- const instance = await cls.fromJsonLd({
3295
- "@id": "https://example.com/",
3296
- "@type": typeUri
3297
- }, {
3298
- documentLoader: mockDocumentLoader,
3299
- contextLoader: mockDocumentLoader
3300
- });
3301
- assertInstanceOf(instance, cls);
3302
- assertEquals(instance.id, new URL("https://example.com/"));
3303
- assertEquals(await instance.toJsonLd(), {
3304
- "@id": "https://example.com/",
3305
- "@type": typeUri
3306
- });
3307
- assertEquals(await instance.toJsonLd({
3308
- format: "compact",
3309
- contextLoader: mockDocumentLoader
3310
- }), {
3311
- "@context": type.defaultContext,
3312
- "id": "https://example.com/",
3313
- "type": type.compactName ?? (type.name === "DataIntegrityProof" ? type.name : type.uri)
3314
- });
3315
- if (type.extends != null) await assertRejects(() => cls.fromJsonLd({
3316
- "@id": "https://example.com/",
3317
- "@type": "https://example.com/"
3318
- }), TypeError);
3319
- await assertRejects(() => cls.fromJsonLd(null), TypeError);
3320
- await assertRejects(() => cls.fromJsonLd(void 0), TypeError);
3321
- });
3322
- test(`${type.name}.toJsonLd() [auto]`, async () => {
3323
- const instance = new cls({
3324
- id: new URL("https://example.com/"),
3325
- ...initValues
3326
- });
3327
- const jsonLd = await instance.toJsonLd({ contextLoader: mockDocumentLoader });
3328
- assertEquals(jsonLd["@context"], type.defaultContext);
3329
- assertEquals(jsonLd.id, "https://example.com/");
3330
- const restored = await cls.fromJsonLd(jsonLd, {
3331
- documentLoader: mockDocumentLoader,
3332
- contextLoader: mockDocumentLoader
3333
- });
3334
- assertEquals(restored, instance);
3335
- assertEquals(await restored.toJsonLd({ contextLoader: mockDocumentLoader }), jsonLd);
3336
- const jsonLd2 = await instance.toJsonLd({
3337
- contextLoader: mockDocumentLoader,
3338
- format: "compact",
3339
- context: "https://www.w3.org/ns/activitystreams"
3340
- });
3341
- assertEquals(jsonLd2["@context"], "https://www.w3.org/ns/activitystreams");
3342
- assertEquals(jsonLd2.id, "https://example.com/");
3343
- const restored2 = await cls.fromJsonLd(jsonLd2, {
3344
- documentLoader: mockDocumentLoader,
3345
- contextLoader: mockDocumentLoader
3346
- });
3347
- assertEquals(restored2, instance);
3348
- const expanded = await instance.toJsonLd({
3349
- contextLoader: mockDocumentLoader,
3350
- format: "expand"
3351
- });
3352
- const restored3 = await cls.fromJsonLd(expanded, {
3353
- documentLoader: mockDocumentLoader,
3354
- contextLoader: mockDocumentLoader
3355
- });
3356
- assertEquals(restored3, instance);
3357
- const instance2 = new cls({
3358
- id: new URL("https://example.com/"),
3359
- ...initValues,
3360
- ...globalThis.Object.fromEntries(allProperties.filter((p) => !areAllScalarTypes(p.range, types)).map((p) => p.functional ? [p.singularName, new URL("https://example.com/test")] : [p.pluralName, [new URL("https://example.com/test")]]))
3361
- });
3362
- const jsonLd3 = await instance2.toJsonLd({ contextLoader: mockDocumentLoader });
3363
- const restored4 = await cls.fromJsonLd(jsonLd3, {
3364
- documentLoader: mockDocumentLoader,
3365
- contextLoader: mockDocumentLoader
3366
- });
3367
- assertEquals(restored4, instance2);
3368
- assertRejects(() => instance.toJsonLd({ context: "https://www.w3.org/ns/activitystreams" }), TypeError);
3369
- assertRejects(() => instance.toJsonLd({
3370
- format: "expand",
3371
- context: "https://www.w3.org/ns/activitystreams"
3372
- }), TypeError);
3373
- });
3374
- if ("Deno" in globalThis) {
3375
- const { assertSnapshot } = await import("@std/testing/snapshot").catch(() => ({ assertSnapshot: () => Promise.resolve() }));
3376
- test(`Deno.inspect(${type.name}) [auto]`, async (t) => {
3377
- const empty = new cls({});
3378
- assertEquals(Deno.inspect(empty), `${type.name} {}`);
3379
- const instance = new cls({
3380
- id: new URL("https://example.com/"),
3381
- ...initValues
3382
- });
3383
- await assertSnapshot(t, Deno.inspect(instance));
3384
- const instance2 = instance.clone(globalThis.Object.fromEntries(type.properties.filter((p) => !areAllScalarTypes(p.range, types)).map((p) => p.functional ? [p.singularName, new URL("https://example.com/")] : [p.pluralName, [new URL("https://example.com/")]])));
3385
- await assertSnapshot(t, Deno.inspect(instance2));
3386
- const instance3 = instance.clone(globalThis.Object.fromEntries(type.properties.filter((p) => !p.functional).map((p) => {
3387
- assertFalse(p.functional);
3388
- return [p.pluralName, [sampleValues[p.range[0]], sampleValues[p.range[0]]]];
3389
- })));
3390
- await assertSnapshot(t, Deno.inspect(instance3));
3391
- });
3392
- }
3393
- test(`${type.name}.typeId`, () => {
3394
- assertEquals(cls.typeId, new URL(type.uri));
3395
- });
3396
- }
3397
-
3398
- //#endregion