emdash 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (681) hide show
  1. package/dist/{adapters-C0ONzkUP.d.mts → adapters-BMyNSSZi.d.mts} +9 -1
  2. package/dist/adapters-BMyNSSZi.d.mts.map +1 -0
  3. package/dist/after-CBU2vkoO.mjs +96 -0
  4. package/dist/after-CBU2vkoO.mjs.map +1 -0
  5. package/dist/{allowed-origins-CCEi9bPI.mjs → allowed-origins-CG1pACtS.mjs} +2 -2
  6. package/dist/{allowed-origins-CCEi9bPI.mjs.map → allowed-origins-CG1pACtS.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -4
  8. package/dist/api/route-utils.d.mts.map +1 -1
  9. package/dist/api/route-utils.mjs +22 -22
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +5 -5
  12. package/dist/{api-DgPbMlng.mjs → api-D2hunekQ.mjs} +247 -45
  13. package/dist/api-D2hunekQ.mjs.map +1 -0
  14. package/dist/{api-tokens-p-iMzvXR.mjs → api-tokens-CSND0i1z.mjs} +2 -2
  15. package/dist/{api-tokens-p-iMzvXR.mjs.map → api-tokens-CSND0i1z.mjs.map} +1 -1
  16. package/dist/{apply-1_6ra7NP.mjs → apply-kwNEJW2l.mjs} +35 -22
  17. package/dist/apply-kwNEJW2l.mjs.map +1 -0
  18. package/dist/astro/index.d.mts +12 -12
  19. package/dist/astro/index.mjs +13 -3
  20. package/dist/astro/index.mjs.map +1 -1
  21. package/dist/astro/middleware/auth.d.mts +10 -10
  22. package/dist/astro/middleware/auth.mjs +8 -8
  23. package/dist/astro/middleware/redirect.d.mts.map +1 -1
  24. package/dist/astro/middleware/redirect.mjs +8 -8
  25. package/dist/astro/middleware/redirect.mjs.map +1 -1
  26. package/dist/astro/middleware/request-context.mjs +4 -4
  27. package/dist/astro/middleware/setup.mjs +1 -1
  28. package/dist/astro/middleware.d.mts +10 -10
  29. package/dist/astro/middleware.d.mts.map +1 -1
  30. package/dist/astro/middleware.mjs +344 -173
  31. package/dist/astro/middleware.mjs.map +1 -1
  32. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +7 -7
  33. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +7 -7
  34. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +4 -4
  35. package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
  36. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +5 -5
  37. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +10 -10
  38. package/dist/astro/routes/api/admin/byline-fields/index.mjs +10 -10
  39. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +10 -10
  40. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +18 -18
  41. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +18 -18
  42. package/dist/astro/routes/api/admin/bylines/index.mjs +18 -18
  43. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +16 -16
  44. package/dist/astro/routes/api/admin/comments/_id_/status.mjs.map +1 -1
  45. package/dist/astro/routes/api/admin/comments/_id_.mjs +7 -7
  46. package/dist/astro/routes/api/admin/comments/bulk.mjs +12 -12
  47. package/dist/astro/routes/api/admin/comments/counts.mjs +7 -7
  48. package/dist/astro/routes/api/admin/comments/index.mjs +12 -12
  49. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +5 -5
  50. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +4 -4
  51. package/dist/astro/routes/api/admin/media-usage/repair.mjs +12 -12
  52. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +4 -4
  53. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
  54. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +46 -45
  55. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  56. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +46 -45
  57. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  58. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +45 -44
  59. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  60. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +5 -5
  61. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +45 -44
  62. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  63. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +45 -44
  64. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  65. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +45 -44
  66. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  67. package/dist/astro/routes/api/admin/plugins/index.mjs +45 -44
  68. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  69. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
  70. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +45 -44
  71. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  72. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +45 -44
  73. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  74. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +45 -44
  75. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  76. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +45 -44
  77. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  78. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +46 -45
  79. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  80. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +45 -44
  81. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +46 -45
  83. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/updates.mjs +45 -44
  85. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +45 -44
  87. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
  89. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +45 -44
  90. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  91. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +3 -3
  92. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
  93. package/dist/astro/routes/api/admin/users/_id_/index.mjs +8 -8
  94. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +5 -5
  95. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs.map +1 -1
  96. package/dist/astro/routes/api/admin/users/index.mjs +7 -7
  97. package/dist/astro/routes/api/auth/dev-bypass.mjs +6 -6
  98. package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
  99. package/dist/astro/routes/api/auth/invite/complete.mjs +12 -12
  100. package/dist/astro/routes/api/auth/invite/index.mjs +10 -10
  101. package/dist/astro/routes/api/auth/invite/index.mjs.map +1 -1
  102. package/dist/astro/routes/api/auth/invite/register-options.mjs +11 -11
  103. package/dist/astro/routes/api/auth/logout.mjs +3 -3
  104. package/dist/astro/routes/api/auth/magic-link/send.mjs +12 -12
  105. package/dist/astro/routes/api/auth/magic-link/send.mjs.map +1 -1
  106. package/dist/astro/routes/api/auth/magic-link/verify.mjs +3 -3
  107. package/dist/astro/routes/api/auth/me.mjs +8 -8
  108. package/dist/astro/routes/api/auth/mode.mjs +3 -3
  109. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  110. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  111. package/dist/astro/routes/api/auth/passkey/_id_.mjs +7 -7
  112. package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
  113. package/dist/astro/routes/api/auth/passkey/options.mjs +13 -13
  114. package/dist/astro/routes/api/auth/passkey/register/options.mjs +11 -11
  115. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +12 -12
  116. package/dist/astro/routes/api/auth/passkey/verify.mjs +12 -12
  117. package/dist/astro/routes/api/auth/signup/complete.mjs +12 -12
  118. package/dist/astro/routes/api/auth/signup/request.mjs +12 -12
  119. package/dist/astro/routes/api/auth/signup/request.mjs.map +1 -1
  120. package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
  121. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +18 -18
  122. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs.map +1 -1
  123. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +15 -15
  124. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
  125. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +4 -4
  126. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +4 -4
  127. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +3 -3
  128. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +13 -13
  129. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +9 -9
  130. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +18 -18
  131. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +18 -18
  132. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +4 -4
  133. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
  134. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +9 -9
  135. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +16 -16
  136. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
  137. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +4 -4
  138. package/dist/astro/routes/api/content/_collection_/_id_.mjs +9 -9
  139. package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
  140. package/dist/astro/routes/api/content/_collection_/index.mjs +9 -9
  141. package/dist/astro/routes/api/content/_collection_/trash.mjs +8 -8
  142. package/dist/astro/routes/api/dashboard.mjs +9 -9
  143. package/dist/astro/routes/api/dev/emails.mjs +3 -3
  144. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  145. package/dist/astro/routes/api/import/probe.mjs +19 -19
  146. package/dist/astro/routes/api/import/wordpress/analyze.mjs +4 -4
  147. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  148. package/dist/astro/routes/api/import/wordpress/execute.mjs +15 -15
  149. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  150. package/dist/astro/routes/api/import/wordpress/media.mjs +10 -10
  151. package/dist/astro/routes/api/import/wordpress/prepare.mjs +11 -11
  152. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  153. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +12 -12
  154. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  155. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +19 -19
  156. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  157. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +27 -27
  158. package/dist/astro/routes/api/manifest.mjs +5 -5
  159. package/dist/astro/routes/api/mcp.mjs +42 -42
  160. package/dist/astro/routes/api/media/_id_/confirm.mjs +10 -10
  161. package/dist/astro/routes/api/media/_id_/upload.mjs +6 -6
  162. package/dist/astro/routes/api/media/_id_/usage.mjs +14 -14
  163. package/dist/astro/routes/api/media/_id_.mjs +13 -13
  164. package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
  165. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
  166. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
  167. package/dist/astro/routes/api/media/providers/index.mjs +3 -3
  168. package/dist/astro/routes/api/media/upload-url.mjs +9 -9
  169. package/dist/astro/routes/api/media.mjs +13 -13
  170. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +11 -11
  171. package/dist/astro/routes/api/menus/_name_/items.mjs +11 -11
  172. package/dist/astro/routes/api/menus/_name_/reorder.mjs +11 -11
  173. package/dist/astro/routes/api/menus/_name_/translations.mjs +11 -11
  174. package/dist/astro/routes/api/menus/_name_.mjs +11 -11
  175. package/dist/astro/routes/api/menus/index.mjs +11 -11
  176. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  177. package/dist/astro/routes/api/oauth/device/authorize.mjs +6 -6
  178. package/dist/astro/routes/api/oauth/device/code.mjs +9 -9
  179. package/dist/astro/routes/api/oauth/device/token.mjs +8 -8
  180. package/dist/astro/routes/api/oauth/register.mjs +3 -3
  181. package/dist/astro/routes/api/oauth/token/refresh.mjs +6 -6
  182. package/dist/astro/routes/api/oauth/token/revoke.mjs +6 -6
  183. package/dist/astro/routes/api/oauth/token.mjs +6 -6
  184. package/dist/astro/routes/api/openapi.json.mjs +36 -5
  185. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  186. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +5 -5
  187. package/dist/astro/routes/api/redirects/404s/index.mjs +12 -12
  188. package/dist/astro/routes/api/redirects/404s/summary.mjs +12 -12
  189. package/dist/astro/routes/api/redirects/_id_.mjs +14 -13
  190. package/dist/astro/routes/api/redirects/_id_.mjs.map +1 -1
  191. package/dist/astro/routes/api/redirects/index.mjs +14 -13
  192. package/dist/astro/routes/api/redirects/index.mjs.map +1 -1
  193. package/dist/astro/routes/api/relations/_id_/index.mjs +18 -18
  194. package/dist/astro/routes/api/relations/_id_/translations.mjs +13 -13
  195. package/dist/astro/routes/api/relations/index.mjs +18 -18
  196. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
  197. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +4 -4
  198. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +45 -44
  199. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  200. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +45 -44
  201. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  202. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +45 -44
  203. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  204. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +45 -44
  205. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  206. package/dist/astro/routes/api/schema/collections/index.mjs +45 -44
  207. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  208. package/dist/astro/routes/api/schema/collections/reorder.d.mts +8 -0
  209. package/dist/astro/routes/api/schema/collections/reorder.d.mts.map +1 -0
  210. package/dist/astro/routes/api/schema/collections/reorder.mjs +66 -0
  211. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -0
  212. package/dist/astro/routes/api/schema/index.mjs +11 -9
  213. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  214. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +45 -44
  215. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  216. package/dist/astro/routes/api/schema/orphans/index.mjs +45 -44
  217. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  218. package/dist/astro/routes/api/search/enable.d.mts +1 -0
  219. package/dist/astro/routes/api/search/enable.d.mts.map +1 -1
  220. package/dist/astro/routes/api/search/enable.mjs +17 -13
  221. package/dist/astro/routes/api/search/enable.mjs.map +1 -1
  222. package/dist/astro/routes/api/search/index.mjs +11 -11
  223. package/dist/astro/routes/api/search/rebuild.mjs +13 -13
  224. package/dist/astro/routes/api/search/rebuild.mjs.map +1 -1
  225. package/dist/astro/routes/api/search/stats.mjs +7 -7
  226. package/dist/astro/routes/api/search/suggest.mjs +11 -11
  227. package/dist/astro/routes/api/sections/_slug_.mjs +11 -11
  228. package/dist/astro/routes/api/sections/index.mjs +11 -11
  229. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +7 -7
  230. package/dist/astro/routes/api/settings/backups/archives/index.mjs +6 -6
  231. package/dist/astro/routes/api/settings/backups/export.mjs +7 -7
  232. package/dist/astro/routes/api/settings/backups/index.mjs +8 -8
  233. package/dist/astro/routes/api/settings/email.mjs +5 -5
  234. package/dist/astro/routes/api/settings.mjs +16 -16
  235. package/dist/astro/routes/api/setup/admin-verify.mjs +13 -13
  236. package/dist/astro/routes/api/setup/admin.mjs +12 -12
  237. package/dist/astro/routes/api/setup/dev-bypass.mjs +30 -30
  238. package/dist/astro/routes/api/setup/dev-reset.mjs +3 -3
  239. package/dist/astro/routes/api/setup/index.mjs +32 -32
  240. package/dist/astro/routes/api/setup/status.mjs +4 -4
  241. package/dist/astro/routes/api/snapshot.mjs +9 -9
  242. package/dist/astro/routes/api/taxonomies/_name_/reorder.d.mts +8 -0
  243. package/dist/astro/routes/api/taxonomies/_name_/reorder.d.mts.map +1 -0
  244. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +43 -0
  245. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -0
  246. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +16 -16
  247. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +16 -16
  248. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +16 -16
  249. package/dist/astro/routes/api/taxonomies/index.mjs +16 -16
  250. package/dist/astro/routes/api/themes/preview.mjs +7 -7
  251. package/dist/astro/routes/api/typegen.mjs +5 -5
  252. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  253. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  254. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  255. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +8 -8
  256. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +11 -11
  257. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +11 -11
  258. package/dist/astro/routes/api/widget-areas/_name_.mjs +6 -6
  259. package/dist/astro/routes/api/widget-areas/index.mjs +11 -11
  260. package/dist/astro/routes/api/widget-components.mjs +3 -3
  261. package/dist/astro/routes/robots.txt.mjs +9 -9
  262. package/dist/astro/routes/sitemap-_collection_.xml.mjs +12 -12
  263. package/dist/astro/routes/sitemap.xml.mjs +10 -10
  264. package/dist/astro/types.d.mts +19 -13
  265. package/dist/astro/types.d.mts.map +1 -1
  266. package/dist/auth/providers/github.d.mts +1 -1
  267. package/dist/auth/providers/google.d.mts +1 -1
  268. package/dist/{authorize-R5iYYrpa.mjs → authorize-qRhWQnel.mjs} +2 -2
  269. package/dist/{authorize-R5iYYrpa.mjs.map → authorize-qRhWQnel.mjs.map} +1 -1
  270. package/dist/{backup-LpQ1V_sR.mjs → backup-CtA6LDNw.mjs} +5 -5
  271. package/dist/{backup-LpQ1V_sR.mjs.map → backup-CtA6LDNw.mjs.map} +1 -1
  272. package/dist/{byline-C5TAqs8N.mjs → byline-Cp6csL84.mjs} +9 -9
  273. package/dist/{byline-C5TAqs8N.mjs.map → byline-Cp6csL84.mjs.map} +1 -1
  274. package/dist/{byline-fields-T9ZLZMxJ.mjs → byline-fields-CNc0Yq5i.mjs} +2 -2
  275. package/dist/{byline-fields-T9ZLZMxJ.mjs.map → byline-fields-CNc0Yq5i.mjs.map} +1 -1
  276. package/dist/{byline-registry-BCuOp4UF.mjs → byline-registry-ZkPKqEwC.mjs} +4 -4
  277. package/dist/{byline-registry-BCuOp4UF.mjs.map → byline-registry-ZkPKqEwC.mjs.map} +1 -1
  278. package/dist/{bylines-B8-WGdja.mjs → bylines-CEj5CdT4.mjs} +7 -7
  279. package/dist/{bylines-B8-WGdja.mjs.map → bylines-CEj5CdT4.mjs.map} +1 -1
  280. package/dist/{bylines-DGuqBLjV.mjs → bylines-cf-C9lmF.mjs} +4 -4
  281. package/dist/{bylines-DGuqBLjV.mjs.map → bylines-cf-C9lmF.mjs.map} +1 -1
  282. package/dist/cache-C9FptTFR.mjs +108 -0
  283. package/dist/cache-C9FptTFR.mjs.map +1 -0
  284. package/dist/{challenge-store-BFzgFRog.mjs → challenge-store-D9VNKELo.mjs} +1 -1
  285. package/dist/{challenge-store-BFzgFRog.mjs.map → challenge-store-D9VNKELo.mjs.map} +1 -1
  286. package/dist/{chunks-D5dlPeRb.mjs → chunks-DbYzib_k.mjs} +2 -2
  287. package/dist/{chunks-D5dlPeRb.mjs.map → chunks-DbYzib_k.mjs.map} +1 -1
  288. package/dist/cli/index.mjs +40 -32
  289. package/dist/cli/index.mjs.map +1 -1
  290. package/dist/client/cf-access.d.mts +1 -1
  291. package/dist/client/index.d.mts +1 -1
  292. package/dist/client/index.mjs +2 -2
  293. package/dist/{comment-DnTxxVHv.mjs → comment-BIkJ6Fil.mjs} +3 -3
  294. package/dist/{comment-DnTxxVHv.mjs.map → comment-BIkJ6Fil.mjs.map} +1 -1
  295. package/dist/{comment-reaction-BUlUz2bh.mjs → comment-reaction-D-laEceb.mjs} +2 -2
  296. package/dist/{comment-reaction-BUlUz2bh.mjs.map → comment-reaction-D-laEceb.mjs.map} +1 -1
  297. package/dist/{comments-QPKgK3nk.mjs → comments-0_w6KChA.mjs} +3 -3
  298. package/dist/{comments-QPKgK3nk.mjs.map → comments-0_w6KChA.mjs.map} +1 -1
  299. package/dist/{components-DZkL4Fx0.mjs → components-BPxrRjpE.mjs} +1 -1
  300. package/dist/{components-DZkL4Fx0.mjs.map → components-BPxrRjpE.mjs.map} +1 -1
  301. package/dist/{content-CpfKV9QE.mjs → content-CJ94NEx5.mjs} +165 -112
  302. package/dist/content-CJ94NEx5.mjs.map +1 -0
  303. package/dist/{content-refresh-DgqUBeTv.mjs → content-refresh-Xw7aKmou.mjs} +6 -6
  304. package/dist/{content-refresh-DgqUBeTv.mjs.map → content-refresh-Xw7aKmou.mjs.map} +1 -1
  305. package/dist/{context-kO4YZB03.mjs → context-C_1nrqnW.mjs} +14 -14
  306. package/dist/{context-kO4YZB03.mjs.map → context-C_1nrqnW.mjs.map} +1 -1
  307. package/dist/{cron-BlKIMD_e.mjs → cron-DRV-UC4K.mjs} +1 -1
  308. package/dist/{cron-BlKIMD_e.mjs.map → cron-DRV-UC4K.mjs.map} +1 -1
  309. package/dist/{dashboard-DoBwPnON.mjs → dashboard-DINnNVVU.mjs} +5 -5
  310. package/dist/{dashboard-DoBwPnON.mjs.map → dashboard-DINnNVVU.mjs.map} +1 -1
  311. package/dist/db/index.d.mts +3 -3
  312. package/dist/db/index.mjs +2 -2
  313. package/dist/db/index.mjs.map +1 -1
  314. package/dist/db/libsql.d.mts +1 -1
  315. package/dist/db/postgres.d.mts +1 -1
  316. package/dist/db/sqlite.d.mts +1 -1
  317. package/dist/{default-C4v9KP56.mjs → default-BD2FG0xV.mjs} +1 -1
  318. package/dist/{default-C4v9KP56.mjs.map → default-BD2FG0xV.mjs.map} +1 -1
  319. package/dist/deferred-tasks-C-WRCcKo.d.mts +9 -0
  320. package/dist/deferred-tasks-C-WRCcKo.d.mts.map +1 -0
  321. package/dist/{device-flow-DhUsyJU6.mjs → device-flow-CTqd8mud.mjs} +5 -5
  322. package/dist/{device-flow-DhUsyJU6.mjs.map → device-flow-CTqd8mud.mjs.map} +1 -1
  323. package/dist/{dialect-helpers-DFwyWjTM.mjs → dialect-helpers-BSbfaO3F.mjs} +24 -16
  324. package/dist/dialect-helpers-BSbfaO3F.mjs.map +1 -0
  325. package/dist/{email-console-C-9Ng8DM.mjs → email-console-C6WdcWbL.mjs} +1 -1
  326. package/dist/{email-console-C-9Ng8DM.mjs.map → email-console-C6WdcWbL.mjs.map} +1 -1
  327. package/dist/{error-DmmN74gW.mjs → error-oh_9i6bR.mjs} +3 -3
  328. package/dist/{error-DmmN74gW.mjs.map → error-oh_9i6bR.mjs.map} +1 -1
  329. package/dist/{errors-DtEXIQQV.mjs → errors-BucQ8VYz.mjs} +2 -1
  330. package/dist/errors-BucQ8VYz.mjs.map +1 -0
  331. package/dist/{escape-CdW31WsG.mjs → escape-CXps5F_v.mjs} +1 -1
  332. package/dist/{escape-CdW31WsG.mjs.map → escape-CXps5F_v.mjs.map} +1 -1
  333. package/dist/{field-defs-cache-QMVnzTH6.mjs → field-defs-cache-WD82dMQq.mjs} +4 -4
  334. package/dist/{field-defs-cache-QMVnzTH6.mjs.map → field-defs-cache-WD82dMQq.mjs.map} +1 -1
  335. package/dist/{fts-manager-vncsZIJm.mjs → fts-manager-BITakW_R.mjs} +37 -13
  336. package/dist/fts-manager-BITakW_R.mjs.map +1 -0
  337. package/dist/{hash-Cb7U1b5M.mjs → hash-Cg0TXJPV.mjs} +1 -1
  338. package/dist/{hash-Cb7U1b5M.mjs.map → hash-Cg0TXJPV.mjs.map} +1 -1
  339. package/dist/{hreflang-CZbSx6Bg.d.mts → hreflang-BaLCNcDx.d.mts} +2 -2
  340. package/dist/{hreflang-CZbSx6Bg.d.mts.map → hreflang-BaLCNcDx.d.mts.map} +1 -1
  341. package/dist/{hreflang-Bg-zMpkr.mjs → hreflang-BdZuVBhL.mjs} +6 -6
  342. package/dist/{hreflang-Bg-zMpkr.mjs.map → hreflang-BdZuVBhL.mjs.map} +1 -1
  343. package/dist/{import-PKhLeXvn.mjs → import-C-9uqyT3.mjs} +6 -6
  344. package/dist/{import-PKhLeXvn.mjs.map → import-C-9uqyT3.mjs.map} +1 -1
  345. package/dist/{index-j9rTh3cp.d.mts → index-M37iz29I.d.mts} +75 -35
  346. package/dist/index-M37iz29I.d.mts.map +1 -0
  347. package/dist/{index-BeNto_Vs.d.mts → index-MGw47uWq.d.mts} +3 -3
  348. package/dist/{index-BeNto_Vs.d.mts.map → index-MGw47uWq.d.mts.map} +1 -1
  349. package/dist/index.d.mts +19 -19
  350. package/dist/index.mjs +68 -66
  351. package/dist/{load-BwTdWE8B.mjs → load-DV1DZuUJ.mjs} +2 -2
  352. package/dist/{load-BwTdWE8B.mjs.map → load-DV1DZuUJ.mjs.map} +1 -1
  353. package/dist/{loader-C1XOLV5b.mjs → loader-CGugY7Zl.mjs} +29 -15
  354. package/dist/loader-CGugY7Zl.mjs.map +1 -0
  355. package/dist/{manifest-schema-bCq54i7F.mjs → manifest-schema-Da7kj23y.mjs} +1 -1
  356. package/dist/{manifest-schema-bCq54i7F.mjs.map → manifest-schema-Da7kj23y.mjs.map} +1 -1
  357. package/dist/media/index.d.mts +1 -1
  358. package/dist/media/local-runtime.d.mts +12 -12
  359. package/dist/media/local-runtime.mjs +8 -8
  360. package/dist/{media-tQDZEdu7.mjs → media-BP7S-nHT.mjs} +2 -2
  361. package/dist/{media-tQDZEdu7.mjs.map → media-BP7S-nHT.mjs.map} +1 -1
  362. package/dist/{media-DWIzoVFL.mjs → media-OhYL-7Io.mjs} +1 -1
  363. package/dist/{media-DWIzoVFL.mjs.map → media-OhYL-7Io.mjs.map} +1 -1
  364. package/dist/{media-allowlist-B7TPD6aq.mjs → media-allowlist-D-peH1H5.mjs} +1 -1
  365. package/dist/{media-allowlist-B7TPD6aq.mjs.map → media-allowlist-D-peH1H5.mjs.map} +1 -1
  366. package/dist/{media-upload-Bc9Nc5Zf.mjs → media-upload-DtrwU2B0.mjs} +7 -7
  367. package/dist/{media-upload-Bc9Nc5Zf.mjs.map → media-upload-DtrwU2B0.mjs.map} +1 -1
  368. package/dist/{media-url-BCm5vBn6.mjs → media-url-DYs_YLOx.mjs} +1 -1
  369. package/dist/{media-url-BCm5vBn6.mjs.map → media-url-DYs_YLOx.mjs.map} +1 -1
  370. package/dist/{media-usage-DPJcNaAq.mjs → media-usage-BlxfTkN0.mjs} +8 -8
  371. package/dist/{media-usage-DPJcNaAq.mjs.map → media-usage-BlxfTkN0.mjs.map} +1 -1
  372. package/dist/{menus-BxPLFfIc.mjs → menus-BcQWxeXu.mjs} +4 -4
  373. package/dist/{menus-BxPLFfIc.mjs.map → menus-BcQWxeXu.mjs.map} +1 -1
  374. package/dist/{menus-C6qhqP4X.mjs → menus-Y54RDPIN.mjs} +215 -38
  375. package/dist/menus-Y54RDPIN.mjs.map +1 -0
  376. package/dist/{mode-fiXRMfeA.mjs → mode-BWyTBe3I.mjs} +1 -1
  377. package/dist/{mode-fiXRMfeA.mjs.map → mode-BWyTBe3I.mjs.map} +1 -1
  378. package/dist/{oauth-authorization-C9tFinly.mjs → oauth-authorization-ClvktmrL.mjs} +5 -5
  379. package/dist/{oauth-authorization-C9tFinly.mjs.map → oauth-authorization-ClvktmrL.mjs.map} +1 -1
  380. package/dist/{oauth-clients-BwTxE1aE.mjs → oauth-clients-8ao-U66l.mjs} +1 -1
  381. package/dist/{oauth-clients-BwTxE1aE.mjs.map → oauth-clients-8ao-U66l.mjs.map} +1 -1
  382. package/dist/{oauth-state-store-DaRUwPWO.mjs → oauth-state-store-B1ofdTiQ.mjs} +1 -1
  383. package/dist/{oauth-state-store-DaRUwPWO.mjs.map → oauth-state-store-B1ofdTiQ.mjs.map} +1 -1
  384. package/dist/{oauth-user-lookup-CzuzOSlF.mjs → oauth-user-lookup-CscEuIiR.mjs} +1 -1
  385. package/dist/{oauth-user-lookup-CzuzOSlF.mjs.map → oauth-user-lookup-CscEuIiR.mjs.map} +1 -1
  386. package/dist/object-cache/memory.d.mts +1 -1
  387. package/dist/{object-cache-Bok5j2ae.mjs → object-cache-71tPfV4A.mjs} +106 -5
  388. package/dist/object-cache-71tPfV4A.mjs.map +1 -0
  389. package/dist/{options-aeIs8WFu.d.mts → options-CA4eVX6P.d.mts} +3 -3
  390. package/dist/{options-aeIs8WFu.d.mts.map → options-CA4eVX6P.d.mts.map} +1 -1
  391. package/dist/{options-BlmBHTvX.mjs → options-CBXIHUoT.mjs} +1 -1
  392. package/dist/{options-BlmBHTvX.mjs.map → options-CBXIHUoT.mjs.map} +1 -1
  393. package/dist/page/index.d.mts +2 -2
  394. package/dist/{parse-BL49yb9D.mjs → parse-CJKNuewM.mjs} +2 -2
  395. package/dist/{parse-BL49yb9D.mjs.map → parse-CJKNuewM.mjs.map} +1 -1
  396. package/dist/{passkey-config-KMhgFjdQ.mjs → passkey-config-D-zrzMJI.mjs} +1 -1
  397. package/dist/{passkey-config-KMhgFjdQ.mjs.map → passkey-config-D-zrzMJI.mjs.map} +1 -1
  398. package/dist/{placeholder-Dxo5Zt58.d.mts → placeholder-DaeNS-VG.d.mts} +1 -1
  399. package/dist/{placeholder-Dxo5Zt58.d.mts.map → placeholder-DaeNS-VG.d.mts.map} +1 -1
  400. package/dist/plugin-types.d.mts +1 -1
  401. package/dist/plugin-utils.d.mts +10 -10
  402. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  403. package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
  404. package/dist/{portable-text-CNahFfj6.mjs → portable-text-B_kqBmXB.mjs} +1 -1
  405. package/dist/{portable-text-CNahFfj6.mjs.map → portable-text-B_kqBmXB.mjs.map} +1 -1
  406. package/dist/{preview-D4Jnbfx7.mjs → preview-BU6PaLpM.mjs} +2 -2
  407. package/dist/{preview-D4Jnbfx7.mjs.map → preview-BU6PaLpM.mjs.map} +1 -1
  408. package/dist/{public-url-DSGTnJFw.mjs → public-url-Ox9oOlgp.mjs} +14 -3
  409. package/dist/public-url-Ox9oOlgp.mjs.map +1 -0
  410. package/dist/{query-DCiXI7OZ.mjs → query-C5w7PsRQ.mjs} +20 -41
  411. package/dist/query-C5w7PsRQ.mjs.map +1 -0
  412. package/dist/{query-1xOcEy18.mjs → query-rC9HKv1N.mjs} +4 -4
  413. package/dist/{query-1xOcEy18.mjs.map → query-rC9HKv1N.mjs.map} +1 -1
  414. package/dist/{rate-limit-Vkp9gQ1Y.mjs → rate-limit-kug6q99V.mjs} +2 -2
  415. package/dist/{rate-limit-Vkp9gQ1Y.mjs.map → rate-limit-kug6q99V.mjs.map} +1 -1
  416. package/dist/{redirect-BJ6d1yHh.mjs → redirect-DIJxXKOG.mjs} +3 -3
  417. package/dist/{redirect-BJ6d1yHh.mjs.map → redirect-DIJxXKOG.mjs.map} +1 -1
  418. package/dist/{redirect-CDgfv9vh.mjs → redirect-Egf2R9yP.mjs} +1 -1
  419. package/dist/{redirect-CDgfv9vh.mjs.map → redirect-Egf2R9yP.mjs.map} +1 -1
  420. package/dist/{redirects-Cwkq2H-G.mjs → redirects-Bzm812bY.mjs} +5 -5
  421. package/dist/{redirects-Cwkq2H-G.mjs.map → redirects-Bzm812bY.mjs.map} +1 -1
  422. package/dist/{redirects-BOn2DIUs.mjs → redirects-G8wAhWAf.mjs} +20 -6
  423. package/dist/redirects-G8wAhWAf.mjs.map +1 -0
  424. package/dist/{registry-BP1JK2xh.mjs → registry-Dbodb4Uo.mjs} +59 -14
  425. package/dist/registry-Dbodb4Uo.mjs.map +1 -0
  426. package/dist/{relation-DJ5DZh7B.mjs → relation-Cbe3Sd3m.mjs} +3 -3
  427. package/dist/{relation-DJ5DZh7B.mjs.map → relation-Cbe3Sd3m.mjs.map} +1 -1
  428. package/dist/{relations-C4duJnwI.mjs → relations-Bw_E1TXo.mjs} +3 -3
  429. package/dist/{relations-C4duJnwI.mjs.map → relations-Bw_E1TXo.mjs.map} +1 -1
  430. package/dist/{relations-DHFQGX0h.d.mts → relations-G2ta7GIl.d.mts} +36 -9
  431. package/dist/relations-G2ta7GIl.d.mts.map +1 -0
  432. package/dist/{relations-DpTjftCl.mjs → relations-qHwpUe66.mjs} +5 -5
  433. package/dist/{relations-DpTjftCl.mjs.map → relations-qHwpUe66.mjs.map} +1 -1
  434. package/dist/request-context.d.mts +3 -0
  435. package/dist/request-context.d.mts.map +1 -1
  436. package/dist/request-context.mjs.map +1 -1
  437. package/dist/{request-meta-DzXYYI-n.mjs → request-meta-Df-jFbAd.mjs} +2 -2
  438. package/dist/{request-meta-DzXYYI-n.mjs.map → request-meta-Df-jFbAd.mjs.map} +1 -1
  439. package/dist/{resolve-BUvFE0Lr.mjs → resolve-DZzG4HqM.mjs} +1 -1
  440. package/dist/{resolve-BUvFE0Lr.mjs.map → resolve-DZzG4HqM.mjs.map} +1 -1
  441. package/dist/{runner-BsI18UgP.mjs → runner-BFTrkYhu.mjs} +482 -216
  442. package/dist/runner-BFTrkYhu.mjs.map +1 -0
  443. package/dist/{runner-CHdkERbt.d.mts → runner-BaADli8l.d.mts} +2 -2
  444. package/dist/{runner-CHdkERbt.d.mts.map → runner-BaADli8l.d.mts.map} +1 -1
  445. package/dist/runtime.d.mts +11 -11
  446. package/dist/runtime.mjs +3 -3
  447. package/dist/{schema-eqZhkR0S.mjs → schema-CiQXr6_F.mjs} +3 -3
  448. package/dist/{schema-eqZhkR0S.mjs.map → schema-CiQXr6_F.mjs.map} +1 -1
  449. package/dist/{scopes-Be2d8bSb.mjs → scopes-CNJVT5i5.mjs} +3 -3
  450. package/dist/{scopes-Be2d8bSb.mjs.map → scopes-CNJVT5i5.mjs.map} +1 -1
  451. package/dist/{search-CeO678cp.mjs → search-FZhx5dDU.mjs} +6 -6
  452. package/dist/{search-CeO678cp.mjs.map → search-FZhx5dDU.mjs.map} +1 -1
  453. package/dist/{secrets-870d-7yA.mjs → secrets-DLd8RXee.mjs} +4 -4
  454. package/dist/{secrets-870d-7yA.mjs.map → secrets-DLd8RXee.mjs.map} +1 -1
  455. package/dist/{sections-DSuEfirn.mjs → sections-BrIrMUCn.mjs} +3 -3
  456. package/dist/{sections-DSuEfirn.mjs.map → sections-BrIrMUCn.mjs.map} +1 -1
  457. package/dist/seed/index.d.mts +2 -2
  458. package/dist/seed/index.mjs +24 -24
  459. package/dist/seo/index.d.mts +3 -3
  460. package/dist/seo/index.mjs +17 -17
  461. package/dist/{seo-C3GDfT0V.mjs → seo-CobNfOvb.mjs} +2 -2
  462. package/dist/{seo-C3GDfT0V.mjs.map → seo-CobNfOvb.mjs.map} +1 -1
  463. package/dist/{seo-BAPKiED8.mjs → seo-DTHRntNC.mjs} +3 -3
  464. package/dist/{seo-BAPKiED8.mjs.map → seo-DTHRntNC.mjs.map} +1 -1
  465. package/dist/{service-DyFT-k-R.mjs → service-B-pYGPgR.mjs} +4 -4
  466. package/dist/{service-DyFT-k-R.mjs.map → service-B-pYGPgR.mjs.map} +1 -1
  467. package/dist/{session-user-BrK2zz7S.mjs → session-user-BvM9-zNl.mjs} +2 -2
  468. package/dist/{session-user-BrK2zz7S.mjs.map → session-user-BvM9-zNl.mjs.map} +1 -1
  469. package/dist/{settings-CREKyj8I.mjs → settings-DPHau-WH.mjs} +3 -3
  470. package/dist/{settings-CREKyj8I.mjs.map → settings-DPHau-WH.mjs.map} +1 -1
  471. package/dist/{settings-DgKouY2S.mjs → settings-kJhGiQ4z.mjs} +7 -7
  472. package/dist/{settings-DgKouY2S.mjs.map → settings-kJhGiQ4z.mjs.map} +1 -1
  473. package/dist/{setup-complete-L7bMK2VI.mjs → setup-complete-u50Qm8rY.mjs} +2 -2
  474. package/dist/{setup-complete-L7bMK2VI.mjs.map → setup-complete-u50Qm8rY.mjs.map} +1 -1
  475. package/dist/{setup-nonce-Ct5tjWcq.mjs → setup-nonce-DCjiiOD2.mjs} +1 -1
  476. package/dist/{setup-nonce-Ct5tjWcq.mjs.map → setup-nonce-DCjiiOD2.mjs.map} +1 -1
  477. package/dist/{single-flight-cache-C2exrGAi.mjs → single-flight-cache-DW3w11Pu.mjs} +1 -1
  478. package/dist/{single-flight-cache-C2exrGAi.mjs.map → single-flight-cache-DW3w11Pu.mjs.map} +1 -1
  479. package/dist/site-url-I-lJ5kma.mjs +16 -0
  480. package/dist/site-url-I-lJ5kma.mjs.map +1 -0
  481. package/dist/{snapshot-BdpUJKD-.mjs → snapshot-I_fjLDaD.mjs} +2 -2
  482. package/dist/{snapshot-BdpUJKD-.mjs.map → snapshot-I_fjLDaD.mjs.map} +1 -1
  483. package/dist/{ssrf-CviKqWmq.mjs → ssrf-CTa6v21i.mjs} +1 -1
  484. package/dist/{ssrf-CviKqWmq.mjs.map → ssrf-CTa6v21i.mjs.map} +1 -1
  485. package/dist/{state-xxv6ZTMv.mjs → state-CQvoefYP.mjs} +1 -1
  486. package/dist/{state-xxv6ZTMv.mjs.map → state-CQvoefYP.mjs.map} +1 -1
  487. package/dist/{status-COfycGIU.mjs → status-CIsmlC1E.mjs} +1 -1
  488. package/dist/{status-COfycGIU.mjs.map → status-CIsmlC1E.mjs.map} +1 -1
  489. package/dist/storage/local.d.mts +1 -1
  490. package/dist/storage/local.mjs +1 -1
  491. package/dist/storage/s3.d.mts +1 -1
  492. package/dist/storage/s3.mjs +1 -1
  493. package/dist/{taxonomies-Dbdki3Un.mjs → taxonomies-CKuaZER5.mjs} +85 -5
  494. package/dist/taxonomies-CKuaZER5.mjs.map +1 -0
  495. package/dist/{taxonomies-B61CRSha.mjs → taxonomies-CLN1N92E.mjs} +16 -17
  496. package/dist/taxonomies-CLN1N92E.mjs.map +1 -0
  497. package/dist/{taxonomy-DvwWAPvA.mjs → taxonomy-pOrB2kZe.mjs} +142 -15
  498. package/dist/taxonomy-pOrB2kZe.mjs.map +1 -0
  499. package/dist/{tokens-DVltpO2D.mjs → tokens-DagaJGK8.mjs} +1 -1
  500. package/dist/{tokens-DVltpO2D.mjs.map → tokens-DagaJGK8.mjs.map} +1 -1
  501. package/dist/{transaction-D0FOsb3X.mjs → transaction-NQj4VJ7Z.mjs} +1 -1
  502. package/dist/{transaction-D0FOsb3X.mjs.map → transaction-NQj4VJ7Z.mjs.map} +1 -1
  503. package/dist/{transport-DokJOScS.d.mts → transport-CAwTaTp_.d.mts} +1 -1
  504. package/dist/{transport-DokJOScS.d.mts.map → transport-CAwTaTp_.d.mts.map} +1 -1
  505. package/dist/{transport-BWQo0Foy.mjs → transport-DVsa5YYo.mjs} +1 -1
  506. package/dist/{transport-BWQo0Foy.mjs.map → transport-DVsa5YYo.mjs.map} +1 -1
  507. package/dist/{trusted-proxy-CwjQj0YG.mjs → trusted-proxy-D20_7fyX.mjs} +1 -1
  508. package/dist/{trusted-proxy-CwjQj0YG.mjs.map → trusted-proxy-D20_7fyX.mjs.map} +1 -1
  509. package/dist/{types-DqZVPILm.d.mts → types-BGWPMiBO.d.mts} +2 -2
  510. package/dist/{types-DqZVPILm.d.mts.map → types-BGWPMiBO.d.mts.map} +1 -1
  511. package/dist/{types-DsAMyD_o.d.mts → types-BK6U01Ro.d.mts} +1 -1
  512. package/dist/{types-DsAMyD_o.d.mts.map → types-BK6U01Ro.d.mts.map} +1 -1
  513. package/dist/{types-BD40g7zz.mjs → types-BjxTKxrZ.mjs} +1 -1
  514. package/dist/{types-BD40g7zz.mjs.map → types-BjxTKxrZ.mjs.map} +1 -1
  515. package/dist/{types-jISEalTX.d.mts → types-BnFP1M3J.d.mts} +22 -1
  516. package/dist/types-BnFP1M3J.d.mts.map +1 -0
  517. package/dist/{types-Dr2GLlwu.d.mts → types-C8oz_ayJ.d.mts} +1 -1
  518. package/dist/{types-Dr2GLlwu.d.mts.map → types-C8oz_ayJ.d.mts.map} +1 -1
  519. package/dist/{types-C9P3ysxq.d.mts → types-CbUcuxxc.d.mts} +1 -1
  520. package/dist/{types-C9P3ysxq.d.mts.map → types-CbUcuxxc.d.mts.map} +1 -1
  521. package/dist/{types-XrQQ-Aex.mjs → types-Cd8iuS1J.mjs} +10 -3
  522. package/dist/{types-XrQQ-Aex.mjs.map → types-Cd8iuS1J.mjs.map} +1 -1
  523. package/dist/types-CtzytVXn.mjs +18 -0
  524. package/dist/types-CtzytVXn.mjs.map +1 -0
  525. package/dist/{types-BQY7VYw6.d.mts → types-Cz8hNch2.d.mts} +5 -5
  526. package/dist/{types-BQY7VYw6.d.mts.map → types-Cz8hNch2.d.mts.map} +1 -1
  527. package/dist/{types-CcSZCcF1.d.mts → types-DLG4IFEQ.d.mts} +1 -1
  528. package/dist/{types-CcSZCcF1.d.mts.map → types-DLG4IFEQ.d.mts.map} +1 -1
  529. package/dist/{types-84Bque3-.d.mts → types-Dc4ntQjQ.d.mts} +10 -1
  530. package/dist/types-Dc4ntQjQ.d.mts.map +1 -0
  531. package/dist/{types-DQLZ58GV.d.mts → types-LoagAGzH.d.mts} +1 -1
  532. package/dist/{types-DQLZ58GV.d.mts.map → types-LoagAGzH.d.mts.map} +1 -1
  533. package/dist/{types-o7xo7VgH.mjs → types-NBI3rF-_.mjs} +3 -2
  534. package/dist/types-NBI3rF-_.mjs.map +1 -0
  535. package/dist/{upload-attempts-C5yd6Gae.mjs → upload-attempts-D8QAFLUJ.mjs} +1 -1
  536. package/dist/{upload-attempts-C5yd6Gae.mjs.map → upload-attempts-D8QAFLUJ.mjs.map} +1 -1
  537. package/dist/{user-BAumEmpA.mjs → user-DBrq4UVq.mjs} +3 -3
  538. package/dist/{user-BAumEmpA.mjs.map → user-DBrq4UVq.mjs.map} +1 -1
  539. package/dist/{utils-BbUgmeZG.mjs → utils-hLzi_2Fn.mjs} +2 -2
  540. package/dist/{utils-BbUgmeZG.mjs.map → utils-hLzi_2Fn.mjs.map} +1 -1
  541. package/dist/{validate-VPnKoIzW.mjs → validate-BpwoDOgt.mjs} +25 -2
  542. package/dist/validate-BpwoDOgt.mjs.map +1 -0
  543. package/dist/{validate-CdYcY-Ln.d.mts → validate-C3oSmA7F.d.mts} +15 -5
  544. package/dist/validate-C3oSmA7F.d.mts.map +1 -0
  545. package/dist/{validate-Bs_wT2ul.mjs → validate-mKo3RxBM.mjs} +3 -3
  546. package/dist/{validate-Bs_wT2ul.mjs.map → validate-mKo3RxBM.mjs.map} +1 -1
  547. package/dist/{validation-BngR0nit.mjs → validation-BgpucsvF.mjs} +10 -10
  548. package/dist/{validation-BngR0nit.mjs.map → validation-BgpucsvF.mjs.map} +1 -1
  549. package/dist/version-C4PnpmoV.mjs +7 -0
  550. package/dist/{version-Bdfb34kk.mjs.map → version-C4PnpmoV.mjs.map} +1 -1
  551. package/dist/{widgets-L-VndTKD.mjs → widgets-CJJtkiKh.mjs} +3 -3
  552. package/dist/{widgets-L-VndTKD.mjs.map → widgets-CJJtkiKh.mjs.map} +1 -1
  553. package/dist/{wxr-taxonomies-BexjtNid.mjs → wxr-taxonomies-9PPSy8X6.mjs} +4 -4
  554. package/dist/{wxr-taxonomies-BexjtNid.mjs.map → wxr-taxonomies-9PPSy8X6.mjs.map} +1 -1
  555. package/dist/{wxr-taxonomies-DueaLFd9.d.mts → wxr-taxonomies-Bkpp_2tK.d.mts} +1 -1
  556. package/dist/{wxr-taxonomies-DueaLFd9.d.mts.map → wxr-taxonomies-Bkpp_2tK.d.mts.map} +1 -1
  557. package/dist/{zod-generator-DMzfga3g.mjs → zod-generator-CG64Hnbh.mjs} +3 -3
  558. package/dist/{zod-generator-DMzfga3g.mjs.map → zod-generator-CG64Hnbh.mjs.map} +1 -1
  559. package/package.json +11 -8
  560. package/src/after.ts +6 -1
  561. package/src/api/errors.ts +1 -0
  562. package/src/api/handlers/content.ts +45 -4
  563. package/src/api/handlers/marketplace.ts +14 -0
  564. package/src/api/handlers/registry.ts +14 -0
  565. package/src/api/handlers/revision.ts +19 -5
  566. package/src/api/handlers/schema.ts +37 -0
  567. package/src/api/handlers/snapshot.ts +1 -1
  568. package/src/api/handlers/taxonomies.ts +101 -1
  569. package/src/api/openapi/document.ts +48 -0
  570. package/src/api/public-url.ts +14 -2
  571. package/src/api/schemas/schema.ts +13 -0
  572. package/src/api/schemas/search.ts +2 -0
  573. package/src/api/schemas/taxonomies.ts +18 -0
  574. package/src/api/site-url.ts +16 -6
  575. package/src/astro/integration/routes.ts +14 -0
  576. package/src/astro/integration/runtime.ts +13 -0
  577. package/src/astro/integration/virtual-modules.ts +2 -0
  578. package/src/astro/middleware/redirect.ts +2 -10
  579. package/src/astro/middleware/scoped-db.ts +35 -4
  580. package/src/astro/middleware.ts +56 -22
  581. package/src/astro/routes/api/admin/comments/[id]/status.ts +1 -1
  582. package/src/astro/routes/api/admin/users/[id]/send-recovery.ts +2 -2
  583. package/src/astro/routes/api/auth/invite/index.ts +2 -2
  584. package/src/astro/routes/api/auth/magic-link/send.ts +2 -2
  585. package/src/astro/routes/api/auth/signup/request.ts +2 -2
  586. package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +1 -1
  587. package/src/astro/routes/api/schema/collections/reorder.ts +31 -0
  588. package/src/astro/routes/api/schema/index.ts +2 -0
  589. package/src/astro/routes/api/search/enable.ts +5 -1
  590. package/src/astro/routes/api/search/rebuild.ts +6 -1
  591. package/src/astro/routes/api/taxonomies/[name]/reorder.ts +41 -0
  592. package/src/astro/types.ts +6 -0
  593. package/src/cleanup.ts +31 -26
  594. package/src/cli/commands/dev.ts +13 -3
  595. package/src/cli/commands/export-seed.ts +2 -0
  596. package/src/cli/index.ts +1 -1
  597. package/src/components/CommentForm.astro +1 -1
  598. package/src/components/Comments.astro +1 -1
  599. package/src/components/InlinePortableTextEditor.tsx +171 -31
  600. package/src/components/OrderedList.astro +14 -0
  601. package/src/components/PortableText.astro +26 -4
  602. package/src/components/index.ts +12 -1
  603. package/src/components/ordered-list.ts +549 -0
  604. package/src/content/converters/numbered-list.ts +148 -0
  605. package/src/content/converters/portable-text-to-prosemirror.ts +59 -9
  606. package/src/content/converters/prosemirror-to-portable-text.ts +23 -12
  607. package/src/content/converters/types.ts +2 -0
  608. package/src/content/portable-text-lists.ts +205 -0
  609. package/src/database/dialect-helpers.ts +3 -22
  610. package/src/database/migrations/055_content_translation_group_locale_index.ts +67 -0
  611. package/src/database/migrations/056_taxonomy_term_sort_order.ts +189 -0
  612. package/src/database/migrations/057_collection_hidden.ts +24 -0
  613. package/src/database/migrations/058_collection_sort_order.ts +20 -0
  614. package/src/database/migrations/059_revision_prune_queue.ts +36 -0
  615. package/src/database/migrations/runner.ts +10 -0
  616. package/src/database/repositories/content.ts +191 -178
  617. package/src/database/repositories/revision.ts +82 -17
  618. package/src/database/repositories/taxonomy.ts +202 -7
  619. package/src/database/repositories/types.ts +7 -0
  620. package/src/database/types.ts +13 -1
  621. package/src/database/validate.ts +39 -0
  622. package/src/db/adapters.ts +8 -0
  623. package/src/deferred-tasks.ts +71 -0
  624. package/src/emdash-runtime.ts +268 -92
  625. package/src/index.ts +2 -0
  626. package/src/loader.ts +46 -24
  627. package/src/media/usage/gc.ts +50 -0
  628. package/src/object-cache/index.ts +160 -3
  629. package/src/plugins/routes.ts +34 -0
  630. package/src/plugins/storage-indexes.ts +50 -11
  631. package/src/query.ts +21 -42
  632. package/src/redirects/cache.ts +79 -19
  633. package/src/request-context.ts +3 -0
  634. package/src/scheduled-publish.ts +6 -1
  635. package/src/schema/registry.ts +95 -3
  636. package/src/schema/types.ts +24 -0
  637. package/src/search/fts-manager.ts +50 -10
  638. package/src/search/index.ts +2 -0
  639. package/src/search/types.ts +6 -0
  640. package/src/seed/apply.ts +22 -2
  641. package/src/seed/types.ts +10 -0
  642. package/src/taxonomies/index.ts +11 -7
  643. package/src/taxonomies/term-counts.ts +2 -4
  644. package/src/ui-comments.ts +19 -0
  645. package/src/ui.ts +11 -3
  646. package/src/virtual-modules.d.ts +8 -0
  647. package/dist/adapters-C0ONzkUP.d.mts.map +0 -1
  648. package/dist/after-B1IIdH3Y.mjs +0 -29
  649. package/dist/after-B1IIdH3Y.mjs.map +0 -1
  650. package/dist/api-DgPbMlng.mjs.map +0 -1
  651. package/dist/apply-1_6ra7NP.mjs.map +0 -1
  652. package/dist/cache-B26cufFd.mjs +0 -65
  653. package/dist/cache-B26cufFd.mjs.map +0 -1
  654. package/dist/content-CpfKV9QE.mjs.map +0 -1
  655. package/dist/dialect-helpers-DFwyWjTM.mjs.map +0 -1
  656. package/dist/errors-DtEXIQQV.mjs.map +0 -1
  657. package/dist/fts-manager-vncsZIJm.mjs.map +0 -1
  658. package/dist/index-j9rTh3cp.d.mts.map +0 -1
  659. package/dist/loader-C1XOLV5b.mjs.map +0 -1
  660. package/dist/menus-C6qhqP4X.mjs.map +0 -1
  661. package/dist/object-cache-Bok5j2ae.mjs.map +0 -1
  662. package/dist/public-url-DSGTnJFw.mjs.map +0 -1
  663. package/dist/query-DCiXI7OZ.mjs.map +0 -1
  664. package/dist/redirects-BOn2DIUs.mjs.map +0 -1
  665. package/dist/registry-BP1JK2xh.mjs.map +0 -1
  666. package/dist/relations-DHFQGX0h.d.mts.map +0 -1
  667. package/dist/runner-BsI18UgP.mjs.map +0 -1
  668. package/dist/site-url-8N3kSyVZ.mjs +0 -13
  669. package/dist/site-url-8N3kSyVZ.mjs.map +0 -1
  670. package/dist/taxonomies-B61CRSha.mjs.map +0 -1
  671. package/dist/taxonomies-Dbdki3Un.mjs.map +0 -1
  672. package/dist/taxonomy-DvwWAPvA.mjs.map +0 -1
  673. package/dist/types-84Bque3-.d.mts.map +0 -1
  674. package/dist/types-jISEalTX.d.mts.map +0 -1
  675. package/dist/types-o7xo7VgH.mjs.map +0 -1
  676. package/dist/validate-CdYcY-Ln.d.mts.map +0 -1
  677. package/dist/validate-VPnKoIzW.mjs.map +0 -1
  678. package/dist/version-Bdfb34kk.mjs +0 -7
  679. /package/dist/{api-tokens-CEsW_jCg.mjs → api-tokens-Dai9dND0.mjs} +0 -0
  680. /package/dist/{ssrf-BB__xfNM.mjs → ssrf-Cj568Dgs.mjs} +0 -0
  681. /package/dist/{types-CK0LxPUQ.mjs → types-DKuWPYV5.mjs} +0 -0
@@ -0,0 +1,16 @@
1
+ import { t as OptionsRepository } from "./options-CBXIHUoT.mjs";
2
+ import { t as getConfiguredOrigin } from "./public-url-Ox9oOlgp.mjs";
3
+
4
+ //#region src/api/site-url.ts
5
+ async function getSiteBaseUrl(db, request, config) {
6
+ const configured = getConfiguredOrigin(config);
7
+ if (configured) return `${configured}/_emdash`;
8
+ const storedUrl = await new OptionsRepository(db).get("emdash:site_url");
9
+ if (storedUrl) return `${storedUrl}/_emdash`;
10
+ const url = new URL(request.url);
11
+ return `${url.protocol}//${url.host}/_emdash`;
12
+ }
13
+
14
+ //#endregion
15
+ export { getSiteBaseUrl as t };
16
+ //# sourceMappingURL=site-url-I-lJ5kma.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-url-I-lJ5kma.mjs","names":[],"sources":["../src/api/site-url.ts"],"sourcesContent":["/**\n * Resolve the canonical site base URL for use in outbound links (emails, etc.).\n *\n * Precedence mirrors `getPublicOrigin`: the operator-configured origin\n * (`config.siteUrl`, then the `EMDASH_SITE_URL`/`SITE_URL` env vars) wins,\n * then the stored `emdash:site_url` option (written once during setup on the\n * real domain), and only before setup completes does the request URL fill in.\n * A configured or stored value always beats the request, so Host header\n * spoofing cannot redirect users to attacker-controlled domains.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getConfiguredOrigin, type SiteUrlConfig } from \"./public-url.js\";\n\nexport async function getSiteBaseUrl(\n\tdb: Kysely<Database>,\n\trequest: Request,\n\tconfig?: SiteUrlConfig,\n): Promise<string> {\n\tconst configured = getConfiguredOrigin(config);\n\tif (configured) {\n\t\treturn `${configured}/_emdash`;\n\t}\n\tconst options = new OptionsRepository(db);\n\tconst storedUrl = await options.get<string>(\"emdash:site_url\");\n\tif (storedUrl) {\n\t\treturn `${storedUrl}/_emdash`;\n\t}\n\t// Fallback: derive from request (only reached before setup completes)\n\tconst url = new URL(request.url);\n\treturn `${url.protocol}//${url.host}/_emdash`;\n}\n"],"mappings":";;;;AAiBA,eAAsB,eACrB,IACA,SACA,QACkB;CAClB,MAAM,aAAa,oBAAoB,OAAO;AAC9C,KAAI,WACH,QAAO,GAAG,WAAW;CAGtB,MAAM,YAAY,MADF,IAAI,kBAAkB,GAAG,CACT,IAAY,kBAAkB;AAC9D,KAAI,UACH,QAAO,GAAG,UAAU;CAGrB,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;AAChC,QAAO,GAAG,IAAI,SAAS,IAAI,IAAI,KAAK"}
@@ -180,7 +180,7 @@ async function generateSnapshot(db, options) {
180
180
  else rows = (await sql`
181
181
  SELECT * FROM ${sql.raw(`"${tableName}"`)}
182
182
  WHERE deleted_at IS NULL
183
- AND (status = 'published' OR (status = 'scheduled' AND scheduled_at <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))
183
+ AND status = 'published'
184
184
  `.execute(db)).rows;
185
185
  else if (tableName === "options") rows = (await sql`
186
186
  SELECT * FROM ${sql.raw(`"${tableName}"`)}
@@ -213,4 +213,4 @@ async function generateSnapshot(db, options) {
213
213
 
214
214
  //#endregion
215
215
  export { parsePreviewSignatureHeader as n, verifyPreviewSignature as r, generateSnapshot as t };
216
- //# sourceMappingURL=snapshot-BdpUJKD-.mjs.map
216
+ //# sourceMappingURL=snapshot-I_fjLDaD.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"snapshot-BdpUJKD-.mjs","names":[],"sources":["../src/api/handlers/snapshot.ts"],"sourcesContent":["/**\n * Snapshot handler — generates a portable database snapshot.\n *\n * Returns all content tables, schema definitions, and supporting data\n * needed to render content in an isolated preview database.\n *\n * Used by:\n * - DO preview database (EmDashPreviewDB.populateFromSnapshot)\n * - Future: CLI export, backup, site migration\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\n\n// ─�� Preview signature verification ──────────────────────────────\n\n/**\n * Verify HMAC-SHA256 preview signature using crypto.subtle.\n * Returns true if the signature is valid and not expired.\n */\nexport async function verifyPreviewSignature(\n\tsource: string,\n\texp: number,\n\tsig: string,\n\tsecret: string,\n): Promise<boolean> {\n\tif (exp < Date.now() / 1000) return false;\n\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\n\tconst sigBytes = new Uint8Array(sig.length / 2);\n\tfor (let i = 0; i < sig.length; i += 2) {\n\t\tsigBytes[i / 2] = parseInt(sig.substring(i, i + 2), 16);\n\t}\n\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, encoder.encode(`${source}:${exp}`));\n}\n\n/**\n * Parse an X-Preview-Signature header value into its components.\n *\n * Format: \"source:exp:sig\" where source is a URL (contains colons),\n * exp is a unix timestamp, and sig is 64 hex chars.\n *\n * Parses from the right since source URLs contain colons.\n *\n * @returns Parsed components, or null if the format is invalid\n */\nexport function parsePreviewSignatureHeader(\n\theader: string,\n): { source: string; exp: number; sig: string } | null {\n\tconst lastColon = header.lastIndexOf(\":\");\n\tif (lastColon <= 0) return null;\n\n\tconst sig = header.substring(lastColon + 1);\n\tif (sig.length !== 64) return null;\n\n\tconst rest = header.substring(0, lastColon);\n\tconst secondLastColon = rest.lastIndexOf(\":\");\n\tif (secondLastColon <= 0) return null;\n\n\tconst source = rest.substring(0, secondLastColon);\n\tconst exp = parseInt(rest.substring(secondLastColon + 1), 10);\n\n\tif (isNaN(exp) || source.length === 0) return null;\n\n\treturn { source, exp, sig };\n}\n\n// ── Media URL rewriting ─────────────────────────────────────────\n\nconst MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\n\n/**\n * Parse a JSON string value and inject `src` for local media objects.\n * Returns the original string if it's not a local media value.\n */\nfunction injectMediaSrc(jsonStr: string, origin: string): string {\n\ttry {\n\t\tconst obj = JSON.parse(jsonStr);\n\t\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return jsonStr;\n\t\tif (injectMediaSrcInto(obj, origin)) {\n\t\t\treturn JSON.stringify(obj);\n\t\t}\n\t\treturn jsonStr;\n\t} catch {\n\t\treturn jsonStr;\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively walk an object and inject `src` into local media values.\n * Returns true if any modifications were made.\n */\nfunction injectMediaSrcInto(obj: Record<string, unknown>, origin: string): boolean {\n\tlet modified = false;\n\n\t// Check if this object itself is a local media value\n\tif ((obj.provider === \"local\" || (!obj.provider && obj.id && obj.meta)) && !obj.src) {\n\t\tconst meta = isRecord(obj.meta) ? obj.meta : undefined;\n\t\tconst storageKey = meta?.storageKey ?? obj.id;\n\t\tif (typeof storageKey === \"string\" && storageKey) {\n\t\t\tobj.src = `${origin}${MEDIA_FILE_PREFIX}${storageKey}`;\n\t\t\tmodified = true;\n\t\t}\n\t}\n\n\t// Recurse into nested objects/arrays (e.g. Portable Text with image blocks)\n\tfor (const value of Object.values(obj)) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) {\n\t\t\t\tif (isRecord(item)) {\n\t\t\t\t\tif (injectMediaSrcInto(item, origin)) {\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (isRecord(value)) {\n\t\t\tif (injectMediaSrcInto(value, origin)) {\n\t\t\t\tmodified = true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn modified;\n}\n\n// ── Snapshot generation ─────────────────────────────────────────\n\n/**\n * Safe identifier pattern for snapshot table names.\n * More permissive than validateIdentifier() — allows leading underscores\n * (needed for system tables like _emdash_collections).\n */\nconst SAFE_TABLE_NAME = /^[a-z_][a-z0-9_]*$/;\n\n/** Snapshot shape consumed by the DO preview database */\nexport interface Snapshot {\n\ttables: Record<string, Record<string, unknown>[]>;\n\tschema: Record<\n\t\tstring,\n\t\t{\n\t\t\tcolumns: string[];\n\t\t\ttypes?: Record<string, string>;\n\t\t}\n\t>;\n\tgeneratedAt: string;\n}\n\n/**\n * System tables included in snapshots.\n * Content tables (ec_*) are discovered dynamically.\n */\nconst SYSTEM_TABLES = [\n\t\"_emdash_collections\",\n\t\"_emdash_fields\",\n\t\"_emdash_taxonomy_defs\",\n\t\"_emdash_menus\",\n\t\"_emdash_menu_items\",\n\t\"_emdash_sections\",\n\t\"_emdash_widget_areas\",\n\t\"_emdash_widgets\",\n\t\"_emdash_seo\",\n\t\"_emdash_migrations\",\n\t\"taxonomies\",\n\t\"content_taxonomies\",\n\t\"media\",\n\t\"options\",\n\t\"revisions\",\n];\n\n/**\n * Table name prefixes excluded from snapshots (auth/security data).\n */\nconst EXCLUDED_PREFIXES = [\n\t\"_emdash_api_tokens\",\n\t\"_emdash_oauth_tokens\",\n\t\"_emdash_authorization_codes\",\n\t\"_emdash_device_codes\",\n\t\"_emdash_migrations_lock\",\n\t\"_plugin_\",\n\t\"users\",\n\t\"sessions\",\n\t\"credentials\",\n\t\"challenges\",\n];\n\n/**\n * Options key prefixes safe for inclusion in snapshots.\n *\n * The options table contains plugin secrets (plugin:*), passkey challenges\n * (emdash:passkey_pending:*), and setup state that must not leak to\n * preview databases. Only site-level rendering settings are needed.\n */\nconst SAFE_OPTIONS_PREFIXES = [\"site:\"];\n\nfunction isExcluded(tableName: string): boolean {\n\treturn EXCLUDED_PREFIXES.some((prefix) => tableName.startsWith(prefix));\n}\n\n/** Column info from PRAGMA table_info */\ninterface ColumnInfo {\n\tname: string;\n\ttype: string;\n}\n\nexport interface GenerateSnapshotOptions {\n\t/** Include draft and scheduled content (default: false) */\n\tincludeDrafts?: boolean;\n\t/** Include trashed content (deleted_at set). Used by backups (default: false) */\n\tincludeTrashed?: boolean;\n\t/** Origin URL for absolutizing local media URLs (e.g. \"https://mysite.com\") */\n\torigin?: string;\n\t/**\n\t * Allowlist of options-table key prefixes to include (default:\n\t * `SAFE_OPTIONS_PREFIXES`). Callers widening this must never include a\n\t * prefix that matches secrets (`emdash:preview_secret`, `plugin:`,\n\t * `emdash:passkey_pending:`) — the output may be user-downloadable.\n\t */\n\toptionPrefixes?: string[];\n}\n\n/**\n * Generate a portable database snapshot.\n *\n * Discovers ec_* content tables dynamically, exports system tables\n * needed for rendering, and includes schema info for table recreation.\n */\nexport async function generateSnapshot(\n\tdb: Kysely<Database>,\n\toptions?: GenerateSnapshotOptions,\n): Promise<Snapshot> {\n\tconst includeDrafts = options?.includeDrafts ?? false;\n\tconst includeTrashed = options?.includeTrashed ?? false;\n\tconst optionPrefixes = options?.optionPrefixes ?? SAFE_OPTIONS_PREFIXES;\n\n\t// Discover all ec_* content tables\n\tconst tableResult = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table'\n\t\tAND name LIKE 'ec_%'\n\t\tORDER BY name\n\t`.execute(db);\n\n\tconst contentTables = tableResult.rows.map((r) => r.name);\n\n\t// Build list of all tables to export\n\tconst allTables = [...contentTables, ...SYSTEM_TABLES];\n\n\tconst tables: Record<string, Record<string, unknown>[]> = {};\n\tconst schema: Record<string, { columns: string[]; types?: Record<string, string> }> = {};\n\n\tfor (const tableName of allTables) {\n\t\tif (isExcluded(tableName)) continue;\n\n\t\t// Validate identifier before interpolating into sql.raw().\n\t\t// SYSTEM_TABLES are hardcoded and safe, but ec_* names come from\n\t\t// sqlite_master and must be validated.\n\t\tif (!SAFE_TABLE_NAME.test(tableName)) continue;\n\n\t\ttry {\n\t\t\t// Get column info via PRAGMA\n\t\t\tconst pragmaResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.raw(`\"${tableName}\"`)})\n\t\t\t`.execute(db);\n\n\t\t\tif (pragmaResult.rows.length === 0) continue;\n\n\t\t\tconst columns = pragmaResult.rows.map((r) => r.name);\n\t\t\tconst types: Record<string, string> = {};\n\t\t\tfor (const row of pragmaResult.rows) {\n\t\t\t\ttypes[row.name] = row.type || \"TEXT\";\n\t\t\t}\n\n\t\t\tschema[tableName] = { columns, types };\n\n\t\t\t// Fetch rows\n\t\t\tlet rows: Record<string, unknown>[];\n\n\t\t\tif (tableName.startsWith(\"ec_\")) {\n\t\t\t\tif (includeTrashed) {\n\t\t\t\t\t// Everything, including trash — full-fidelity backup export\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else if (includeDrafts) {\n\t\t\t\t\t// Include all non-deleted content (published, draft, scheduled)\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else {\n\t\t\t\t\t// Only export published content\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND (status = 'published' OR (status = 'scheduled' AND scheduled_at <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t}\n\t\t\t} else if (tableName === \"options\") {\n\t\t\t\t// Filter options to safe rendering-only prefixes.\n\t\t\t\t// Excludes plugin secrets, passkey challenges, and setup state.\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows.filter((row) => {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\treturn optionPrefixes.some((prefix) => name.startsWith(prefix));\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows;\n\t\t\t}\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\ttables[tableName] = rows;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Table might not exist yet (e.g. pre-migration) — skip silently\n\t\t}\n\t}\n\n\t// Absolutize local media URLs in content tables so snapshots are portable.\n\t// Local image fields are stored as JSON with provider:\"local\" and\n\t// meta.storageKey but no src — the URL is derived at render time.\n\t// For snapshots consumed by external preview services, inject src now.\n\tif (options?.origin) {\n\t\tconst origin = options.origin;\n\t\tfor (const [tableName, rows] of Object.entries(tables)) {\n\t\t\tif (!tableName.startsWith(\"ec_\")) continue;\n\t\t\tfor (const row of rows) {\n\t\t\t\tfor (const [col, value] of Object.entries(row)) {\n\t\t\t\t\tif (typeof value !== \"string\" || !value.startsWith(\"{\")) continue;\n\t\t\t\t\trow[col] = injectMediaSrc(value, origin);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttables,\n\t\tschema,\n\t\tgeneratedAt: new Date().toISOString(),\n\t};\n}\n"],"mappings":";;;;;;;AAsBA,eAAsB,uBACrB,QACA,KACA,KACA,QACmB;AACnB,KAAI,MAAM,KAAK,KAAK,GAAG,IAAM,QAAO;CAEpC,MAAM,UAAU,IAAI,aAAa;CACjC,MAAM,MAAM,MAAM,OAAO,OAAO,UAC/B,OACA,QAAQ,OAAO,OAAO,EACtB;EAAE,MAAM;EAAQ,MAAM;EAAW,EACjC,OACA,CAAC,SAAS,CACV;CAED,MAAM,WAAW,IAAI,WAAW,IAAI,SAAS,EAAE;AAC/C,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,EACpC,UAAS,IAAI,KAAK,SAAS,IAAI,UAAU,GAAG,IAAI,EAAE,EAAE,GAAG;AAGxD,QAAO,OAAO,OAAO,OAAO,QAAQ,KAAK,UAAU,QAAQ,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;;;;;;;;;;;;AAavF,SAAgB,4BACf,QACsD;CACtD,MAAM,YAAY,OAAO,YAAY,IAAI;AACzC,KAAI,aAAa,EAAG,QAAO;CAE3B,MAAM,MAAM,OAAO,UAAU,YAAY,EAAE;AAC3C,KAAI,IAAI,WAAW,GAAI,QAAO;CAE9B,MAAM,OAAO,OAAO,UAAU,GAAG,UAAU;CAC3C,MAAM,kBAAkB,KAAK,YAAY,IAAI;AAC7C,KAAI,mBAAmB,EAAG,QAAO;CAE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QAAQ,GAAG,EACX;OAGF,SACC,MAAM,GAA4B;sBAClB,IAAI,IAAI,IAAI,UAAU,GAAG,CAAC;;;OAGzC,QAAQ,GAAG,EACX;YAEO,cAAc,UAGxB,SACC,MAAM,GAA4B;qBAClB,IAAI,IAAI,IAAI,UAAU,GAAG,CAAC;MACzC,QAAQ,GAAG,EACX,KAAK,QAAQ,QAAQ;IACtB,MAAM,OAAO,OAAO,IAAI,SAAS,WAAW,IAAI,OAAO;AACvD,WAAO,eAAe,MAAM,WAAW,KAAK,WAAW,OAAO,CAAC;KAC9D;OAEF,SACC,MAAM,GAA4B;qBAClB,IAAI,IAAI,IAAI,UAAU,GAAG,CAAC;MACzC,QAAQ,GAAG,EACX;AAGH,OAAI,KAAK,SAAS,EACjB,QAAO,aAAa;UAEd;;AAST,KAAI,SAAS,QAAQ;EACpB,MAAM,SAAS,QAAQ;AACvB,OAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,OAAO,EAAE;AACvD,OAAI,CAAC,UAAU,WAAW,MAAM,CAAE;AAClC,QAAK,MAAM,OAAO,KACjB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,EAAE;AAC/C,QAAI,OAAO,UAAU,YAAY,CAAC,MAAM,WAAW,IAAI,CAAE;AACzD,QAAI,OAAO,eAAe,OAAO,OAAO;;;;AAM5C,QAAO;EACN;EACA;EACA,8BAAa,IAAI,MAAM,EAAC,aAAa;EACrC"}
1
+ {"version":3,"file":"snapshot-I_fjLDaD.mjs","names":[],"sources":["../src/api/handlers/snapshot.ts"],"sourcesContent":["/**\n * Snapshot handler — generates a portable database snapshot.\n *\n * Returns all content tables, schema definitions, and supporting data\n * needed to render content in an isolated preview database.\n *\n * Used by:\n * - DO preview database (EmDashPreviewDB.populateFromSnapshot)\n * - Future: CLI export, backup, site migration\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport type { Database } from \"../../database/types.js\";\n\n// ─�� Preview signature verification ──────────────────────────────\n\n/**\n * Verify HMAC-SHA256 preview signature using crypto.subtle.\n * Returns true if the signature is valid and not expired.\n */\nexport async function verifyPreviewSignature(\n\tsource: string,\n\texp: number,\n\tsig: string,\n\tsecret: string,\n): Promise<boolean> {\n\tif (exp < Date.now() / 1000) return false;\n\n\tconst encoder = new TextEncoder();\n\tconst key = await crypto.subtle.importKey(\n\t\t\"raw\",\n\t\tencoder.encode(secret),\n\t\t{ name: \"HMAC\", hash: \"SHA-256\" },\n\t\tfalse,\n\t\t[\"verify\"],\n\t);\n\n\tconst sigBytes = new Uint8Array(sig.length / 2);\n\tfor (let i = 0; i < sig.length; i += 2) {\n\t\tsigBytes[i / 2] = parseInt(sig.substring(i, i + 2), 16);\n\t}\n\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, encoder.encode(`${source}:${exp}`));\n}\n\n/**\n * Parse an X-Preview-Signature header value into its components.\n *\n * Format: \"source:exp:sig\" where source is a URL (contains colons),\n * exp is a unix timestamp, and sig is 64 hex chars.\n *\n * Parses from the right since source URLs contain colons.\n *\n * @returns Parsed components, or null if the format is invalid\n */\nexport function parsePreviewSignatureHeader(\n\theader: string,\n): { source: string; exp: number; sig: string } | null {\n\tconst lastColon = header.lastIndexOf(\":\");\n\tif (lastColon <= 0) return null;\n\n\tconst sig = header.substring(lastColon + 1);\n\tif (sig.length !== 64) return null;\n\n\tconst rest = header.substring(0, lastColon);\n\tconst secondLastColon = rest.lastIndexOf(\":\");\n\tif (secondLastColon <= 0) return null;\n\n\tconst source = rest.substring(0, secondLastColon);\n\tconst exp = parseInt(rest.substring(secondLastColon + 1), 10);\n\n\tif (isNaN(exp) || source.length === 0) return null;\n\n\treturn { source, exp, sig };\n}\n\n// ── Media URL rewriting ─────────────────────────────────────────\n\nconst MEDIA_FILE_PREFIX = \"/_emdash/api/media/file/\";\n\n/**\n * Parse a JSON string value and inject `src` for local media objects.\n * Returns the original string if it's not a local media value.\n */\nfunction injectMediaSrc(jsonStr: string, origin: string): string {\n\ttry {\n\t\tconst obj = JSON.parse(jsonStr);\n\t\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return jsonStr;\n\t\tif (injectMediaSrcInto(obj, origin)) {\n\t\t\treturn JSON.stringify(obj);\n\t\t}\n\t\treturn jsonStr;\n\t} catch {\n\t\treturn jsonStr;\n\t}\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively walk an object and inject `src` into local media values.\n * Returns true if any modifications were made.\n */\nfunction injectMediaSrcInto(obj: Record<string, unknown>, origin: string): boolean {\n\tlet modified = false;\n\n\t// Check if this object itself is a local media value\n\tif ((obj.provider === \"local\" || (!obj.provider && obj.id && obj.meta)) && !obj.src) {\n\t\tconst meta = isRecord(obj.meta) ? obj.meta : undefined;\n\t\tconst storageKey = meta?.storageKey ?? obj.id;\n\t\tif (typeof storageKey === \"string\" && storageKey) {\n\t\t\tobj.src = `${origin}${MEDIA_FILE_PREFIX}${storageKey}`;\n\t\t\tmodified = true;\n\t\t}\n\t}\n\n\t// Recurse into nested objects/arrays (e.g. Portable Text with image blocks)\n\tfor (const value of Object.values(obj)) {\n\t\tif (Array.isArray(value)) {\n\t\t\tfor (const item of value) {\n\t\t\t\tif (isRecord(item)) {\n\t\t\t\t\tif (injectMediaSrcInto(item, origin)) {\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (isRecord(value)) {\n\t\t\tif (injectMediaSrcInto(value, origin)) {\n\t\t\t\tmodified = true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn modified;\n}\n\n// ── Snapshot generation ─────────────────────────────────────────\n\n/**\n * Safe identifier pattern for snapshot table names.\n * More permissive than validateIdentifier() — allows leading underscores\n * (needed for system tables like _emdash_collections).\n */\nconst SAFE_TABLE_NAME = /^[a-z_][a-z0-9_]*$/;\n\n/** Snapshot shape consumed by the DO preview database */\nexport interface Snapshot {\n\ttables: Record<string, Record<string, unknown>[]>;\n\tschema: Record<\n\t\tstring,\n\t\t{\n\t\t\tcolumns: string[];\n\t\t\ttypes?: Record<string, string>;\n\t\t}\n\t>;\n\tgeneratedAt: string;\n}\n\n/**\n * System tables included in snapshots.\n * Content tables (ec_*) are discovered dynamically.\n */\nconst SYSTEM_TABLES = [\n\t\"_emdash_collections\",\n\t\"_emdash_fields\",\n\t\"_emdash_taxonomy_defs\",\n\t\"_emdash_menus\",\n\t\"_emdash_menu_items\",\n\t\"_emdash_sections\",\n\t\"_emdash_widget_areas\",\n\t\"_emdash_widgets\",\n\t\"_emdash_seo\",\n\t\"_emdash_migrations\",\n\t\"taxonomies\",\n\t\"content_taxonomies\",\n\t\"media\",\n\t\"options\",\n\t\"revisions\",\n];\n\n/**\n * Table name prefixes excluded from snapshots (auth/security data).\n */\nconst EXCLUDED_PREFIXES = [\n\t\"_emdash_api_tokens\",\n\t\"_emdash_oauth_tokens\",\n\t\"_emdash_authorization_codes\",\n\t\"_emdash_device_codes\",\n\t\"_emdash_migrations_lock\",\n\t\"_plugin_\",\n\t\"users\",\n\t\"sessions\",\n\t\"credentials\",\n\t\"challenges\",\n];\n\n/**\n * Options key prefixes safe for inclusion in snapshots.\n *\n * The options table contains plugin secrets (plugin:*), passkey challenges\n * (emdash:passkey_pending:*), and setup state that must not leak to\n * preview databases. Only site-level rendering settings are needed.\n */\nconst SAFE_OPTIONS_PREFIXES = [\"site:\"];\n\nfunction isExcluded(tableName: string): boolean {\n\treturn EXCLUDED_PREFIXES.some((prefix) => tableName.startsWith(prefix));\n}\n\n/** Column info from PRAGMA table_info */\ninterface ColumnInfo {\n\tname: string;\n\ttype: string;\n}\n\nexport interface GenerateSnapshotOptions {\n\t/** Include draft and scheduled content (default: false) */\n\tincludeDrafts?: boolean;\n\t/** Include trashed content (deleted_at set). Used by backups (default: false) */\n\tincludeTrashed?: boolean;\n\t/** Origin URL for absolutizing local media URLs (e.g. \"https://mysite.com\") */\n\torigin?: string;\n\t/**\n\t * Allowlist of options-table key prefixes to include (default:\n\t * `SAFE_OPTIONS_PREFIXES`). Callers widening this must never include a\n\t * prefix that matches secrets (`emdash:preview_secret`, `plugin:`,\n\t * `emdash:passkey_pending:`) — the output may be user-downloadable.\n\t */\n\toptionPrefixes?: string[];\n}\n\n/**\n * Generate a portable database snapshot.\n *\n * Discovers ec_* content tables dynamically, exports system tables\n * needed for rendering, and includes schema info for table recreation.\n */\nexport async function generateSnapshot(\n\tdb: Kysely<Database>,\n\toptions?: GenerateSnapshotOptions,\n): Promise<Snapshot> {\n\tconst includeDrafts = options?.includeDrafts ?? false;\n\tconst includeTrashed = options?.includeTrashed ?? false;\n\tconst optionPrefixes = options?.optionPrefixes ?? SAFE_OPTIONS_PREFIXES;\n\n\t// Discover all ec_* content tables\n\tconst tableResult = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table'\n\t\tAND name LIKE 'ec_%'\n\t\tORDER BY name\n\t`.execute(db);\n\n\tconst contentTables = tableResult.rows.map((r) => r.name);\n\n\t// Build list of all tables to export\n\tconst allTables = [...contentTables, ...SYSTEM_TABLES];\n\n\tconst tables: Record<string, Record<string, unknown>[]> = {};\n\tconst schema: Record<string, { columns: string[]; types?: Record<string, string> }> = {};\n\n\tfor (const tableName of allTables) {\n\t\tif (isExcluded(tableName)) continue;\n\n\t\t// Validate identifier before interpolating into sql.raw().\n\t\t// SYSTEM_TABLES are hardcoded and safe, but ec_* names come from\n\t\t// sqlite_master and must be validated.\n\t\tif (!SAFE_TABLE_NAME.test(tableName)) continue;\n\n\t\ttry {\n\t\t\t// Get column info via PRAGMA\n\t\t\tconst pragmaResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.raw(`\"${tableName}\"`)})\n\t\t\t`.execute(db);\n\n\t\t\tif (pragmaResult.rows.length === 0) continue;\n\n\t\t\tconst columns = pragmaResult.rows.map((r) => r.name);\n\t\t\tconst types: Record<string, string> = {};\n\t\t\tfor (const row of pragmaResult.rows) {\n\t\t\t\ttypes[row.name] = row.type || \"TEXT\";\n\t\t\t}\n\n\t\t\tschema[tableName] = { columns, types };\n\n\t\t\t// Fetch rows\n\t\t\tlet rows: Record<string, unknown>[];\n\n\t\t\tif (tableName.startsWith(\"ec_\")) {\n\t\t\t\tif (includeTrashed) {\n\t\t\t\t\t// Everything, including trash — full-fidelity backup export\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else if (includeDrafts) {\n\t\t\t\t\t// Include all non-deleted content (published, draft, scheduled)\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t} else {\n\t\t\t\t\t// Only export published content\n\t\t\t\t\trows = (\n\t\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\t\t\tAND status = 'published'\n\t\t\t\t\t`.execute(db)\n\t\t\t\t\t).rows;\n\t\t\t\t}\n\t\t\t} else if (tableName === \"options\") {\n\t\t\t\t// Filter options to safe rendering-only prefixes.\n\t\t\t\t// Excludes plugin secrets, passkey challenges, and setup state.\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows.filter((row) => {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\treturn optionPrefixes.some((prefix) => name.startsWith(prefix));\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\trows = (\n\t\t\t\t\tawait sql<Record<string, unknown>>`\n\t\t\t\t\tSELECT * FROM ${sql.raw(`\"${tableName}\"`)}\n\t\t\t\t`.execute(db)\n\t\t\t\t).rows;\n\t\t\t}\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\ttables[tableName] = rows;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Table might not exist yet (e.g. pre-migration) — skip silently\n\t\t}\n\t}\n\n\t// Absolutize local media URLs in content tables so snapshots are portable.\n\t// Local image fields are stored as JSON with provider:\"local\" and\n\t// meta.storageKey but no src — the URL is derived at render time.\n\t// For snapshots consumed by external preview services, inject src now.\n\tif (options?.origin) {\n\t\tconst origin = options.origin;\n\t\tfor (const [tableName, rows] of Object.entries(tables)) {\n\t\t\tif (!tableName.startsWith(\"ec_\")) continue;\n\t\t\tfor (const row of rows) {\n\t\t\t\tfor (const [col, value] of Object.entries(row)) {\n\t\t\t\t\tif (typeof value !== \"string\" || !value.startsWith(\"{\")) continue;\n\t\t\t\t\trow[col] = injectMediaSrc(value, origin);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttables,\n\t\tschema,\n\t\tgeneratedAt: new Date().toISOString(),\n\t};\n}\n"],"mappings":";;;;;;;AAsBA,eAAsB,uBACrB,QACA,KACA,KACA,QACmB;AACnB,KAAI,MAAM,KAAK,KAAK,GAAG,IAAM,QAAO;CAEpC,MAAM,UAAU,IAAI,aAAa;CACjC,MAAM,MAAM,MAAM,OAAO,OAAO,UAC/B,OACA,QAAQ,OAAO,OAAO,EACtB;EAAE,MAAM;EAAQ,MAAM;EAAW,EACjC,OACA,CAAC,SAAS,CACV;CAED,MAAM,WAAW,IAAI,WAAW,IAAI,SAAS,EAAE;AAC/C,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,EACpC,UAAS,IAAI,KAAK,SAAS,IAAI,UAAU,GAAG,I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O,eAAe,OAAO,OAAO;;;;AAM5C,QAAO;EACN;EACA;EACA,8BAAa,IAAI,MAAM,EAAC,aAAa;EACrC"}
@@ -329,4 +329,4 @@ function stripCredentialHeaders(init) {
329
329
 
330
330
  //#endregion
331
331
  export { validateExternalUrl as a, stripCredentialHeaders as i, resolveAndValidateExternalUrl as n, ssrfSafeFetch as r, SsrfError as t };
332
- //# sourceMappingURL=ssrf-CviKqWmq.mjs.map
332
+ //# sourceMappingURL=ssrf-CTa6v21i.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssrf-CviKqWmq.mjs","names":[],"sources":["../src/security/ssrf.ts"],"sourcesContent":["/**\n * SSRF protection for import URLs.\n *\n * Validates that URLs don't target internal/private network addresses.\n * Applied before any fetch() call in the import pipeline.\n */\n\nconst IPV4_MAPPED_IPV6_DOTTED_PATTERN = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i;\nconst IPV4_MAPPED_IPV6_HEX_PATTERN = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\nconst IPV4_TRANSLATED_HEX_PATTERN = /^::ffff:0:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\nconst IPV6_EXPANDED_MAPPED_PATTERN =\n\t/^0{0,4}:0{0,4}:0{0,4}:0{0,4}:0{0,4}:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\n/**\n * IPv4-compatible (deprecated) addresses: ::XXXX:XXXX\n *\n * The WHATWG URL parser normalizes [::127.0.0.1] to [::7f00:1] (no ffff prefix).\n * These are deprecated but still parsed, and bypass the ffff-based checks.\n */\nconst IPV4_COMPATIBLE_HEX_PATTERN = /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\n/**\n * NAT64 prefix (RFC 6052): 64:ff9b::XXXX:XXXX\n *\n * Used by NAT64 gateways to embed IPv4 addresses in IPv6.\n * [64:ff9b::127.0.0.1] normalizes to [64:ff9b::7f00:1].\n */\nconst NAT64_HEX_PATTERN = /^64:ff9b::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\nconst IPV6_BRACKET_PATTERN = /^\\[|\\]$/g;\n\n/** Match fc00::/7 ULA — first byte 0xfc or 0xfd followed by any byte. */\nconst IPV6_ULA_FC_PATTERN = /^fc[0-9a-f]{2}:/;\nconst IPV6_ULA_FD_PATTERN = /^fd[0-9a-f]{2}:/;\n\n/** Strip trailing dots from an FQDN-form hostname (\"localhost.\" -> \"localhost\"). */\nconst TRAILING_DOT_PATTERN = /\\.+$/;\n\n/**\n * Private and reserved IP ranges that should never be fetched.\n *\n * Includes:\n * - Loopback (127.0.0.0/8)\n * - Private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)\n * - Link-local (169.254.0.0/16)\n * - Cloud metadata (169.254.169.254 — AWS/GCP/Azure)\n * - IPv6 loopback and link-local\n */\nconst BLOCKED_PATTERNS: Array<{ start: number; end: number }> = [\n\t// 127.0.0.0/8 — loopback\n\t{ start: ip4ToNum(127, 0, 0, 0), end: ip4ToNum(127, 255, 255, 255) },\n\t// 10.0.0.0/8 — private\n\t{ start: ip4ToNum(10, 0, 0, 0), end: ip4ToNum(10, 255, 255, 255) },\n\t// 172.16.0.0/12 — private\n\t{ start: ip4ToNum(172, 16, 0, 0), end: ip4ToNum(172, 31, 255, 255) },\n\t// 192.168.0.0/16 — private\n\t{ start: ip4ToNum(192, 168, 0, 0), end: ip4ToNum(192, 168, 255, 255) },\n\t// 169.254.0.0/16 — link-local (includes cloud metadata endpoint)\n\t{ start: ip4ToNum(169, 254, 0, 0), end: ip4ToNum(169, 254, 255, 255) },\n\t// 0.0.0.0/8 — current network\n\t{ start: ip4ToNum(0, 0, 0, 0), end: ip4ToNum(0, 255, 255, 255) },\n];\n\n// Bracket-stripped form is used for lookups (validateExternalUrl strips\n// brackets from parsed.hostname before checking), so \"::1\" appears here\n// without brackets. The \"::1\" case is already covered by isPrivateIp, but\n// keeping it here makes the intent explicit and gives a clearer error\n// message for the common `http://[::1]/` form.\nconst BLOCKED_HOSTNAMES = new Set([\n\t\"localhost\",\n\t\"metadata.google.internal\",\n\t\"metadata.google\",\n\t\"::1\",\n]);\n\n/**\n * Wildcard DNS services that publicly resolve arbitrary IPs embedded in the\n * hostname. Commonly used in local dev and by SSRF exploit tooling to bypass\n * hostname-only blocklists (e.g. 127.0.0.1.nip.io -> 127.0.0.1).\n *\n * Matched case-insensitively as a suffix, so both the apex and any subdomain\n * are blocked.\n */\nconst BLOCKED_HOSTNAME_SUFFIXES = [\n\t\"nip.io\",\n\t\"sslip.io\",\n\t\"xip.io\",\n\t\"traefik.me\",\n\t\"lvh.me\",\n\t\"localtest.me\",\n];\n\n/** Blocked URL schemes */\nconst ALLOWED_SCHEMES = new Set([\"http:\", \"https:\"]);\n\nfunction ip4ToNum(a: number, b: number, c: number, d: number): number {\n\treturn ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;\n}\n\nfunction parseIpv4(ip: string): number | null {\n\tconst parts = ip.split(\".\");\n\tif (parts.length !== 4) return null;\n\n\tconst nums = parts.map(Number);\n\tif (nums.some((n) => isNaN(n) || n < 0 || n > 255)) return null;\n\n\treturn ip4ToNum(nums[0], nums[1], nums[2], nums[3]);\n}\n\n/**\n * Convert IPv4-mapped/translated IPv6 addresses from hex form back to IPv4.\n *\n * The WHATWG URL parser normalizes dotted-decimal to hex:\n * [::ffff:127.0.0.1] -> [::ffff:7f00:1]\n * [::ffff:169.254.169.254] -> [::ffff:a9fe:a9fe]\n *\n * Without this conversion, the hex forms bypass isPrivateIp() regex checks.\n */\nexport function normalizeIPv6MappedToIPv4(ip: string): string | null {\n\t// Match hex-form IPv4-mapped IPv6: ::ffff:XXXX:XXXX\n\tlet match = ip.match(IPV4_MAPPED_IPV6_HEX_PATTERN);\n\tif (!match) {\n\t\t// Match IPv4-translated (RFC 6052): ::ffff:0:XXXX:XXXX\n\t\tmatch = ip.match(IPV4_TRANSLATED_HEX_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match fully expanded form: 0000:0000:0000:0000:0000:ffff:XXXX:XXXX\n\t\tmatch = ip.match(IPV6_EXPANDED_MAPPED_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match IPv4-compatible (deprecated) form: ::XXXX:XXXX (no ffff prefix)\n\t\tmatch = ip.match(IPV4_COMPATIBLE_HEX_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match NAT64 prefix (RFC 6052): 64:ff9b::XXXX:XXXX\n\t\tmatch = ip.match(NAT64_HEX_PATTERN);\n\t}\n\tif (match) {\n\t\tconst high = parseInt(match[1] ?? \"\", 16);\n\t\tconst low = parseInt(match[2] ?? \"\", 16);\n\t\treturn `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;\n\t}\n\treturn null;\n}\n\nfunction isPrivateIp(ip: string): boolean {\n\t// Normalize IPv6 strings to lowercase. `new URL().hostname` already\n\t// lowercases, but resolver output (from DoH or an injected resolver) may\n\t// not. Without this, \"FE80::1\" bypasses the link-local check.\n\tconst normalized = ip.toLowerCase();\n\n\t// Handle IPv6 loopback\n\tif (normalized === \"::1\" || normalized === \"::ffff:127.0.0.1\") return true;\n\n\t// Handle IPv4-mapped IPv6 in hex form (WHATWG URL parser normalizes to this)\n\t// e.g. ::ffff:7f00:1 -> 127.0.0.1, ::ffff:a9fe:a9fe -> 169.254.169.254\n\tconst hexIpv4 = normalizeIPv6MappedToIPv4(normalized);\n\tif (hexIpv4) return isPrivateIp(hexIpv4);\n\n\t// Handle IPv4-mapped IPv6 in dotted-decimal form\n\tconst v4Match = normalized.match(IPV4_MAPPED_IPV6_DOTTED_PATTERN);\n\tconst ipv4 = v4Match ? v4Match[1] : normalized;\n\n\tconst num = parseIpv4(ipv4);\n\tif (num === null) {\n\t\t// If we can't parse it, block IPv6 addresses that look internal.\n\t\t// fc00::/7 is Unique Local (first byte 0xfc or 0xfd), fe80::/10 is\n\t\t// link-local. Only match when followed by hex digit + colon to avoid\n\t\t// collisions with hypothetical non-address strings.\n\t\treturn (\n\t\t\tnormalized.startsWith(\"fe80:\") ||\n\t\t\tIPV6_ULA_FC_PATTERN.test(normalized) ||\n\t\t\tIPV6_ULA_FD_PATTERN.test(normalized)\n\t\t);\n\t}\n\n\treturn BLOCKED_PATTERNS.some((range) => num >= range.start && num <= range.end);\n}\n\n/**\n * Error thrown when SSRF protection blocks a URL.\n */\nexport class SsrfError extends Error {\n\tcode = \"SSRF_BLOCKED\" as const;\n\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SsrfError\";\n\t}\n}\n\n/**\n * Validate that a URL is safe to fetch (not targeting internal networks).\n *\n * Checks:\n * 1. URL is well-formed with http/https scheme\n * 2. Hostname is not a known internal name (localhost, metadata endpoints)\n * 3. If hostname is an IP literal, it's not in a private range\n *\n * Note: DNS rebinding attacks are not fully mitigated (hostname could resolve\n * to a private IP). Full protection requires resolving DNS and checking the IP\n * before connecting, which needs a custom fetch implementation. This covers\n * the most common SSRF vectors.\n *\n * @throws SsrfError if the URL targets an internal address\n */\n/** Maximum number of redirects to follow in ssrfSafeFetch */\nconst MAX_REDIRECTS = 5;\n\nexport function validateExternalUrl(url: string): URL {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\tthrow new SsrfError(\"Invalid URL\");\n\t}\n\n\t// Only allow http/https\n\tif (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n\t\tthrow new SsrfError(`Scheme '${parsed.protocol}' is not allowed`);\n\t}\n\n\t// Strip brackets from IPv6 hostname\n\tconst hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, \"\");\n\n\t// Normalize the hostname for blocklist matching: lowercase + strip any\n\t// trailing dots. WHATWG preserves trailing dots on .hostname, so without\n\t// this normalization \"localhost.\" and \"nip.io.\" bypass the checks.\n\tconst normalizedHost = hostname.toLowerCase().replace(TRAILING_DOT_PATTERN, \"\");\n\n\t// Check against known internal hostnames\n\tif (BLOCKED_HOSTNAMES.has(normalizedHost)) {\n\t\tthrow new SsrfError(\"URLs targeting internal hosts are not allowed\");\n\t}\n\n\t// Check against wildcard DNS services used by SSRF tooling to bypass\n\t// hostname-only checks. Match the apex and any subdomain.\n\tfor (const suffix of BLOCKED_HOSTNAME_SUFFIXES) {\n\t\tif (normalizedHost === suffix || normalizedHost.endsWith(`.${suffix}`)) {\n\t\t\tthrow new SsrfError(\"URLs targeting wildcard DNS services are not allowed\");\n\t\t}\n\t}\n\n\t// Check if hostname is an IP address in a private range. Use the\n\t// normalized form so \"127.0.0.1..\" and friends don't bypass parseIpv4\n\t// (which rejects extra trailing dots).\n\tif (isPrivateIp(normalizedHost)) {\n\t\tthrow new SsrfError(\"URLs targeting private IP addresses are not allowed\");\n\t}\n\n\treturn parsed;\n}\n\n// ---------------------------------------------------------------------------\n// DNS-aware validation\n// ---------------------------------------------------------------------------\n\n/**\n * A resolver that maps a hostname to a list of IPv4/IPv6 addresses.\n * Injectable so callers can swap in OS-level DNS on Node, stub it in tests,\n * or point to a different DoH endpoint.\n */\nexport type DnsResolver = (hostname: string) => Promise<string[]>;\n\n/**\n * Module-level default resolver. Tests can swap this with a stub so fetch\n * mocks don't see unexpected DoH round-trips. Production code should leave\n * it alone.\n */\nlet defaultResolver: DnsResolver | null = null;\n\n/** Override the default DNS resolver. Returns the previous value. */\nexport function setDefaultDnsResolver(resolver: DnsResolver | null): DnsResolver | null {\n\tconst previous = defaultResolver;\n\tdefaultResolver = resolver;\n\treturn previous;\n}\n\n/** Timeout for a single DoH request, in milliseconds. */\nconst DOH_TIMEOUT_MS = 3000;\n\n/** Default DoH endpoint — Cloudflare's public resolver. */\nconst DEFAULT_DOH_URL = \"https://cloudflare-dns.com/dns-query\";\n\ninterface DohAnswer {\n\tdata: string;\n}\n\ninterface DohResponse {\n\tStatus: number;\n\tAnswer: DohAnswer[];\n}\n\nfunction hasProperty<K extends string>(obj: unknown, key: K): obj is Record<K, unknown> {\n\treturn typeof obj === \"object\" && obj !== null && key in obj;\n}\n\n/**\n * Narrow an unknown JSON body to a DohResponse shape we can read safely.\n * Throws if the body doesn't look like a DoH response — a malformed body is\n * indistinguishable from a failure and must not be silently treated as empty.\n */\nfunction parseDohResponse(raw: unknown): DohResponse {\n\tif (!hasProperty(raw, \"Status\") || typeof raw.Status !== \"number\") {\n\t\tthrow new Error(\"DoH response missing Status field\");\n\t}\n\tconst answers: DohAnswer[] = [];\n\tif (hasProperty(raw, \"Answer\") && Array.isArray(raw.Answer)) {\n\t\tfor (const entry of raw.Answer) {\n\t\t\tif (hasProperty(entry, \"data\") && typeof entry.data === \"string\") {\n\t\t\t\tanswers.push({ data: entry.data });\n\t\t\t}\n\t\t}\n\t}\n\treturn { Status: raw.Status, Answer: answers };\n}\n\n/**\n * Resolve a hostname via DNS over HTTPS (Cloudflare). Returns all A and AAAA\n * records. Works in both Workers and Node without requiring node:dns.\n *\n * Fails closed: any network error, non-2xx response, or DNS rcode != 0\n * causes a rejected promise so the calling validator treats it as a block.\n */\nexport const cloudflareDohResolver: DnsResolver = async (hostname) => {\n\tasync function query(type: \"A\" | \"AAAA\"): Promise<string[]> {\n\t\tconst params = new URLSearchParams({ name: hostname, type });\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), DOH_TIMEOUT_MS);\n\t\ttry {\n\t\t\tconst response = await globalThis.fetch(`${DEFAULT_DOH_URL}?${params.toString()}`, {\n\t\t\t\theaders: { Accept: \"application/dns-json\" },\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`DoH lookup failed: ${response.status}`);\n\t\t\t}\n\t\t\tconst raw = await response.json();\n\t\t\tconst body = parseDohResponse(raw);\n\t\t\t// NXDOMAIN (3) is a legitimate \"does not exist\" — treat as empty.\n\t\t\t// Any other non-zero status (SERVFAIL=2, REFUSED=5, etc.) is\n\t\t\t// ambiguous and could be a split-view attacker hiding records\n\t\t\t// from our resolver. Fail closed.\n\t\t\tif (body.Status === 3) return [];\n\t\t\tif (body.Status !== 0) {\n\t\t\t\tthrow new Error(`DoH ${type} lookup failed: rcode=${body.Status}`);\n\t\t\t}\n\t\t\t// DoH Answer arrays often include CNAME records alongside A/AAAA\n\t\t\t// records. Their `data` is a hostname, not an IP. Filter to just\n\t\t\t// IP literals so isPrivateIp sees real addresses.\n\t\t\treturn body.Answer.map((a) => a.data).filter(isIpLiteral);\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t}\n\n\tconst [a, aaaa] = await Promise.all([query(\"A\"), query(\"AAAA\")]);\n\treturn [...a, ...aaaa];\n};\n\n/**\n * Validate a URL and resolve its hostname to check the actual IPs against\n * the private-range blocklist. This catches DNS rebinding attacks using\n * attacker-controlled domains that publicly resolve to private addresses,\n * and wildcard DNS services like nip.io used by exploit tooling.\n *\n * Runs `validateExternalUrl` first for cheap pre-flight checks (scheme,\n * literal IP, known-bad hostnames). Then resolves the hostname and rejects\n * if ANY returned address is private.\n *\n * Fails closed: if resolution fails or returns no records, throws SsrfError.\n *\n * **Caveats.** This does NOT fully close the TOCTOU between check and\n * connect. Attacks that still work against this layer include:\n *\n * - TTL=0 rebind: authoritative server returns public IP to the check, then\n * private IP to the subsequent fetch() a few milliseconds later.\n * - Split-view via EDNS Client Subnet or source-IP inspection: the\n * authoritative server returns public IP to Cloudflare's DoH resolver and\n * private IP to the victim's own resolver (used by fetch()).\n * - Host-file overrides or split-horizon corporate DNS on self-hosted Node.\n * - Attacker-controlled rebinding services the caller has allowlisted.\n *\n * The only complete defense is a network-layer egress firewall. On\n * Cloudflare Workers, the platform fetch pipeline provides most of that.\n * On self-hosted Node, operators must restrict egress themselves.\n */\nexport async function resolveAndValidateExternalUrl(\n\turl: string,\n\toptions?: { resolver?: DnsResolver },\n): Promise<URL> {\n\tconst parsed = validateExternalUrl(url);\n\n\t// Strip brackets from IPv6 hostnames\n\tconst hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, \"\");\n\n\t// If the hostname is already an IP literal, validateExternalUrl has\n\t// already checked it against the private-range list. Skip DNS.\n\tif (isIpLiteral(hostname)) {\n\t\treturn parsed;\n\t}\n\n\tconst resolver = options?.resolver ?? defaultResolver ?? cloudflareDohResolver;\n\n\tlet addresses: string[];\n\ttry {\n\t\taddresses = await resolver(hostname);\n\t} catch (error) {\n\t\tthrow new SsrfError(\n\t\t\t`Could not resolve hostname: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\tif (addresses.length === 0) {\n\t\tthrow new SsrfError(\"Hostname resolved to no addresses\");\n\t}\n\n\tfor (const ip of addresses) {\n\t\tif (isPrivateIp(ip)) {\n\t\t\tthrow new SsrfError(\"Hostname resolves to a private IP address\");\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/** True when a string looks like an IPv4 or IPv6 literal. */\nfunction isIpLiteral(host: string): boolean {\n\tif (parseIpv4(host) !== null) return true;\n\t// Very loose IPv6 heuristic — matches anything with a colon, which is\n\t// never valid in DNS hostnames, so this is safe.\n\treturn host.includes(\":\");\n}\n\n/**\n * Fetch a URL with SSRF protection on redirects.\n *\n * Uses `redirect: \"manual\"` to intercept redirects and re-validate each\n * redirect target against SSRF rules before following it. This prevents\n * an attacker from setting up an allowed external URL that redirects to\n * an internal IP (e.g. 169.254.169.254 for cloud metadata).\n *\n * @throws SsrfError if the initial URL or any redirect target is internal\n */\n/** Headers that must be stripped when a redirect crosses origins */\nconst CREDENTIAL_HEADERS = [\"authorization\", \"cookie\", \"proxy-authorization\"];\n\nexport async function ssrfSafeFetch(\n\turl: string,\n\tinit?: RequestInit,\n\toptions?: { resolver?: DnsResolver },\n): Promise<Response> {\n\tlet currentUrl = url;\n\tlet currentInit = init;\n\n\tfor (let i = 0; i <= MAX_REDIRECTS; i++) {\n\t\tawait resolveAndValidateExternalUrl(currentUrl, options);\n\n\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t...currentInit,\n\t\t\tredirect: \"manual\",\n\t\t});\n\n\t\t// Not a redirect -- return directly\n\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Extract redirect target\n\t\tconst location = response.headers.get(\"Location\");\n\t\tif (!location) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Resolve relative redirects against the current URL\n\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t// Strip credential headers on cross-origin redirects\n\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t}\n\t}\n\n\tthrow new SsrfError(`Too many redirects (max ${MAX_REDIRECTS})`);\n}\n\n/**\n * Return a copy of init with credential headers removed.\n */\nexport function stripCredentialHeaders(init: RequestInit): RequestInit {\n\tif (!init.headers) return init;\n\n\tconst headers = new Headers(init.headers);\n\tfor (const name of CREDENTIAL_HEADERS) {\n\t\theaders.delete(name);\n\t}\n\n\treturn { ...init, headers };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,kCAAkC;AACxC,MAAM,+BAA+B;AACrC,MAAM,8BAA8B;AACpC,MAAM,+BACL;;;;;;;AAQD,MAAM,8BAA8B;;;;;;;AAQpC,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB;;AAG7B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;;AAG5B,MAAM,uBAAuB;;;;;;;;;;;AAY7B,MAAM,mBAA0D;CAE/D;EAAE,OAAO,SAAS,KAAK,GAAG,GAAG,EAAE;EAAE,KAAK,SAAS,KAAK,KAAK,KAAK,IAAI;EAAE;CAEpE;EAAE,OAAO,SAAS,IAAI,GAAG,GAAG,EAAE;EAAE,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;EAAE;CAElE;EAAE,OAAO,SAAS,KAAK,IAAI,GAAG,EAAE;EAAE,KAAK,SAAS,KAAK,IAAI,KAAK,IAAI;EAAE;CAEpE;EAAE,OAAO,SAAS,KAAK,KAAK,GAAG,EA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AC,SACJ,QAAO;EAIR,MAAM,iBAAiB,IAAI,IAAI,WAAW,CAAC;AAC3C,eAAa,IAAI,IAAI,UAAU,WAAW,CAAC;AAI3C,MAAI,mBAHe,IAAI,IAAI,WAAW,CAAC,UAGF,YACpC,eAAc,uBAAuB,YAAY;;AAInD,OAAM,IAAI,UAAU,2BAA2B,cAAc,GAAG;;;;;AAMjE,SAAgB,uBAAuB,MAAgC;AACtE,KAAI,CAAC,KAAK,QAAS,QAAO;CAE1B,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,MAAK,MAAM,QAAQ,mBAClB,SAAQ,OAAO,KAAK;AAGrB,QAAO;EAAE,GAAG;EAAM;EAAS"}
1
+ {"version":3,"file":"ssrf-CTa6v21i.mjs","names":[],"sources":["../src/security/ssrf.ts"],"sourcesContent":["/**\n * SSRF protection for import URLs.\n *\n * Validates that URLs don't target internal/private network addresses.\n * Applied before any fetch() call in the import pipeline.\n */\n\nconst IPV4_MAPPED_IPV6_DOTTED_PATTERN = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i;\nconst IPV4_MAPPED_IPV6_HEX_PATTERN = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\nconst IPV4_TRANSLATED_HEX_PATTERN = /^::ffff:0:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\nconst IPV6_EXPANDED_MAPPED_PATTERN =\n\t/^0{0,4}:0{0,4}:0{0,4}:0{0,4}:0{0,4}:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\n/**\n * IPv4-compatible (deprecated) addresses: ::XXXX:XXXX\n *\n * The WHATWG URL parser normalizes [::127.0.0.1] to [::7f00:1] (no ffff prefix).\n * These are deprecated but still parsed, and bypass the ffff-based checks.\n */\nconst IPV4_COMPATIBLE_HEX_PATTERN = /^::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\n/**\n * NAT64 prefix (RFC 6052): 64:ff9b::XXXX:XXXX\n *\n * Used by NAT64 gateways to embed IPv4 addresses in IPv6.\n * [64:ff9b::127.0.0.1] normalizes to [64:ff9b::7f00:1].\n */\nconst NAT64_HEX_PATTERN = /^64:ff9b::([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;\n\nconst IPV6_BRACKET_PATTERN = /^\\[|\\]$/g;\n\n/** Match fc00::/7 ULA — first byte 0xfc or 0xfd followed by any byte. */\nconst IPV6_ULA_FC_PATTERN = /^fc[0-9a-f]{2}:/;\nconst IPV6_ULA_FD_PATTERN = /^fd[0-9a-f]{2}:/;\n\n/** Strip trailing dots from an FQDN-form hostname (\"localhost.\" -> \"localhost\"). */\nconst TRAILING_DOT_PATTERN = /\\.+$/;\n\n/**\n * Private and reserved IP ranges that should never be fetched.\n *\n * Includes:\n * - Loopback (127.0.0.0/8)\n * - Private (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)\n * - Link-local (169.254.0.0/16)\n * - Cloud metadata (169.254.169.254 — AWS/GCP/Azure)\n * - IPv6 loopback and link-local\n */\nconst BLOCKED_PATTERNS: Array<{ start: number; end: number }> = [\n\t// 127.0.0.0/8 — loopback\n\t{ start: ip4ToNum(127, 0, 0, 0), end: ip4ToNum(127, 255, 255, 255) },\n\t// 10.0.0.0/8 — private\n\t{ start: ip4ToNum(10, 0, 0, 0), end: ip4ToNum(10, 255, 255, 255) },\n\t// 172.16.0.0/12 — private\n\t{ start: ip4ToNum(172, 16, 0, 0), end: ip4ToNum(172, 31, 255, 255) },\n\t// 192.168.0.0/16 — private\n\t{ start: ip4ToNum(192, 168, 0, 0), end: ip4ToNum(192, 168, 255, 255) },\n\t// 169.254.0.0/16 — link-local (includes cloud metadata endpoint)\n\t{ start: ip4ToNum(169, 254, 0, 0), end: ip4ToNum(169, 254, 255, 255) },\n\t// 0.0.0.0/8 — current network\n\t{ start: ip4ToNum(0, 0, 0, 0), end: ip4ToNum(0, 255, 255, 255) },\n];\n\n// Bracket-stripped form is used for lookups (validateExternalUrl strips\n// brackets from parsed.hostname before checking), so \"::1\" appears here\n// without brackets. The \"::1\" case is already covered by isPrivateIp, but\n// keeping it here makes the intent explicit and gives a clearer error\n// message for the common `http://[::1]/` form.\nconst BLOCKED_HOSTNAMES = new Set([\n\t\"localhost\",\n\t\"metadata.google.internal\",\n\t\"metadata.google\",\n\t\"::1\",\n]);\n\n/**\n * Wildcard DNS services that publicly resolve arbitrary IPs embedded in the\n * hostname. Commonly used in local dev and by SSRF exploit tooling to bypass\n * hostname-only blocklists (e.g. 127.0.0.1.nip.io -> 127.0.0.1).\n *\n * Matched case-insensitively as a suffix, so both the apex and any subdomain\n * are blocked.\n */\nconst BLOCKED_HOSTNAME_SUFFIXES = [\n\t\"nip.io\",\n\t\"sslip.io\",\n\t\"xip.io\",\n\t\"traefik.me\",\n\t\"lvh.me\",\n\t\"localtest.me\",\n];\n\n/** Blocked URL schemes */\nconst ALLOWED_SCHEMES = new Set([\"http:\", \"https:\"]);\n\nfunction ip4ToNum(a: number, b: number, c: number, d: number): number {\n\treturn ((a << 24) | (b << 16) | (c << 8) | d) >>> 0;\n}\n\nfunction parseIpv4(ip: string): number | null {\n\tconst parts = ip.split(\".\");\n\tif (parts.length !== 4) return null;\n\n\tconst nums = parts.map(Number);\n\tif (nums.some((n) => isNaN(n) || n < 0 || n > 255)) return null;\n\n\treturn ip4ToNum(nums[0], nums[1], nums[2], nums[3]);\n}\n\n/**\n * Convert IPv4-mapped/translated IPv6 addresses from hex form back to IPv4.\n *\n * The WHATWG URL parser normalizes dotted-decimal to hex:\n * [::ffff:127.0.0.1] -> [::ffff:7f00:1]\n * [::ffff:169.254.169.254] -> [::ffff:a9fe:a9fe]\n *\n * Without this conversion, the hex forms bypass isPrivateIp() regex checks.\n */\nexport function normalizeIPv6MappedToIPv4(ip: string): string | null {\n\t// Match hex-form IPv4-mapped IPv6: ::ffff:XXXX:XXXX\n\tlet match = ip.match(IPV4_MAPPED_IPV6_HEX_PATTERN);\n\tif (!match) {\n\t\t// Match IPv4-translated (RFC 6052): ::ffff:0:XXXX:XXXX\n\t\tmatch = ip.match(IPV4_TRANSLATED_HEX_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match fully expanded form: 0000:0000:0000:0000:0000:ffff:XXXX:XXXX\n\t\tmatch = ip.match(IPV6_EXPANDED_MAPPED_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match IPv4-compatible (deprecated) form: ::XXXX:XXXX (no ffff prefix)\n\t\tmatch = ip.match(IPV4_COMPATIBLE_HEX_PATTERN);\n\t}\n\tif (!match) {\n\t\t// Match NAT64 prefix (RFC 6052): 64:ff9b::XXXX:XXXX\n\t\tmatch = ip.match(NAT64_HEX_PATTERN);\n\t}\n\tif (match) {\n\t\tconst high = parseInt(match[1] ?? \"\", 16);\n\t\tconst low = parseInt(match[2] ?? \"\", 16);\n\t\treturn `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;\n\t}\n\treturn null;\n}\n\nfunction isPrivateIp(ip: string): boolean {\n\t// Normalize IPv6 strings to lowercase. `new URL().hostname` already\n\t// lowercases, but resolver output (from DoH or an injected resolver) may\n\t// not. Without this, \"FE80::1\" bypasses the link-local check.\n\tconst normalized = ip.toLowerCase();\n\n\t// Handle IPv6 loopback\n\tif (normalized === \"::1\" || normalized === \"::ffff:127.0.0.1\") return true;\n\n\t// Handle IPv4-mapped IPv6 in hex form (WHATWG URL parser normalizes to this)\n\t// e.g. ::ffff:7f00:1 -> 127.0.0.1, ::ffff:a9fe:a9fe -> 169.254.169.254\n\tconst hexIpv4 = normalizeIPv6MappedToIPv4(normalized);\n\tif (hexIpv4) return isPrivateIp(hexIpv4);\n\n\t// Handle IPv4-mapped IPv6 in dotted-decimal form\n\tconst v4Match = normalized.match(IPV4_MAPPED_IPV6_DOTTED_PATTERN);\n\tconst ipv4 = v4Match ? v4Match[1] : normalized;\n\n\tconst num = parseIpv4(ipv4);\n\tif (num === null) {\n\t\t// If we can't parse it, block IPv6 addresses that look internal.\n\t\t// fc00::/7 is Unique Local (first byte 0xfc or 0xfd), fe80::/10 is\n\t\t// link-local. Only match when followed by hex digit + colon to avoid\n\t\t// collisions with hypothetical non-address strings.\n\t\treturn (\n\t\t\tnormalized.startsWith(\"fe80:\") ||\n\t\t\tIPV6_ULA_FC_PATTERN.test(normalized) ||\n\t\t\tIPV6_ULA_FD_PATTERN.test(normalized)\n\t\t);\n\t}\n\n\treturn BLOCKED_PATTERNS.some((range) => num >= range.start && num <= range.end);\n}\n\n/**\n * Error thrown when SSRF protection blocks a URL.\n */\nexport class SsrfError extends Error {\n\tcode = \"SSRF_BLOCKED\" as const;\n\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"SsrfError\";\n\t}\n}\n\n/**\n * Validate that a URL is safe to fetch (not targeting internal networks).\n *\n * Checks:\n * 1. URL is well-formed with http/https scheme\n * 2. Hostname is not a known internal name (localhost, metadata endpoints)\n * 3. If hostname is an IP literal, it's not in a private range\n *\n * Note: DNS rebinding attacks are not fully mitigated (hostname could resolve\n * to a private IP). Full protection requires resolving DNS and checking the IP\n * before connecting, which needs a custom fetch implementation. This covers\n * the most common SSRF vectors.\n *\n * @throws SsrfError if the URL targets an internal address\n */\n/** Maximum number of redirects to follow in ssrfSafeFetch */\nconst MAX_REDIRECTS = 5;\n\nexport function validateExternalUrl(url: string): URL {\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\tthrow new SsrfError(\"Invalid URL\");\n\t}\n\n\t// Only allow http/https\n\tif (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n\t\tthrow new SsrfError(`Scheme '${parsed.protocol}' is not allowed`);\n\t}\n\n\t// Strip brackets from IPv6 hostname\n\tconst hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, \"\");\n\n\t// Normalize the hostname for blocklist matching: lowercase + strip any\n\t// trailing dots. WHATWG preserves trailing dots on .hostname, so without\n\t// this normalization \"localhost.\" and \"nip.io.\" bypass the checks.\n\tconst normalizedHost = hostname.toLowerCase().replace(TRAILING_DOT_PATTERN, \"\");\n\n\t// Check against known internal hostnames\n\tif (BLOCKED_HOSTNAMES.has(normalizedHost)) {\n\t\tthrow new SsrfError(\"URLs targeting internal hosts are not allowed\");\n\t}\n\n\t// Check against wildcard DNS services used by SSRF tooling to bypass\n\t// hostname-only checks. Match the apex and any subdomain.\n\tfor (const suffix of BLOCKED_HOSTNAME_SUFFIXES) {\n\t\tif (normalizedHost === suffix || normalizedHost.endsWith(`.${suffix}`)) {\n\t\t\tthrow new SsrfError(\"URLs targeting wildcard DNS services are not allowed\");\n\t\t}\n\t}\n\n\t// Check if hostname is an IP address in a private range. Use the\n\t// normalized form so \"127.0.0.1..\" and friends don't bypass parseIpv4\n\t// (which rejects extra trailing dots).\n\tif (isPrivateIp(normalizedHost)) {\n\t\tthrow new SsrfError(\"URLs targeting private IP addresses are not allowed\");\n\t}\n\n\treturn parsed;\n}\n\n// ---------------------------------------------------------------------------\n// DNS-aware validation\n// ---------------------------------------------------------------------------\n\n/**\n * A resolver that maps a hostname to a list of IPv4/IPv6 addresses.\n * Injectable so callers can swap in OS-level DNS on Node, stub it in tests,\n * or point to a different DoH endpoint.\n */\nexport type DnsResolver = (hostname: string) => Promise<string[]>;\n\n/**\n * Module-level default resolver. Tests can swap this with a stub so fetch\n * mocks don't see unexpected DoH round-trips. Production code should leave\n * it alone.\n */\nlet defaultResolver: DnsResolver | null = null;\n\n/** Override the default DNS resolver. Returns the previous value. */\nexport function setDefaultDnsResolver(resolver: DnsResolver | null): DnsResolver | null {\n\tconst previous = defaultResolver;\n\tdefaultResolver = resolver;\n\treturn previous;\n}\n\n/** Timeout for a single DoH request, in milliseconds. */\nconst DOH_TIMEOUT_MS = 3000;\n\n/** Default DoH endpoint — Cloudflare's public resolver. */\nconst DEFAULT_DOH_URL = \"https://cloudflare-dns.com/dns-query\";\n\ninterface DohAnswer {\n\tdata: string;\n}\n\ninterface DohResponse {\n\tStatus: number;\n\tAnswer: DohAnswer[];\n}\n\nfunction hasProperty<K extends string>(obj: unknown, key: K): obj is Record<K, unknown> {\n\treturn typeof obj === \"object\" && obj !== null && key in obj;\n}\n\n/**\n * Narrow an unknown JSON body to a DohResponse shape we can read safely.\n * Throws if the body doesn't look like a DoH response — a malformed body is\n * indistinguishable from a failure and must not be silently treated as empty.\n */\nfunction parseDohResponse(raw: unknown): DohResponse {\n\tif (!hasProperty(raw, \"Status\") || typeof raw.Status !== \"number\") {\n\t\tthrow new Error(\"DoH response missing Status field\");\n\t}\n\tconst answers: DohAnswer[] = [];\n\tif (hasProperty(raw, \"Answer\") && Array.isArray(raw.Answer)) {\n\t\tfor (const entry of raw.Answer) {\n\t\t\tif (hasProperty(entry, \"data\") && typeof entry.data === \"string\") {\n\t\t\t\tanswers.push({ data: entry.data });\n\t\t\t}\n\t\t}\n\t}\n\treturn { Status: raw.Status, Answer: answers };\n}\n\n/**\n * Resolve a hostname via DNS over HTTPS (Cloudflare). Returns all A and AAAA\n * records. Works in both Workers and Node without requiring node:dns.\n *\n * Fails closed: any network error, non-2xx response, or DNS rcode != 0\n * causes a rejected promise so the calling validator treats it as a block.\n */\nexport const cloudflareDohResolver: DnsResolver = async (hostname) => {\n\tasync function query(type: \"A\" | \"AAAA\"): Promise<string[]> {\n\t\tconst params = new URLSearchParams({ name: hostname, type });\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), DOH_TIMEOUT_MS);\n\t\ttry {\n\t\t\tconst response = await globalThis.fetch(`${DEFAULT_DOH_URL}?${params.toString()}`, {\n\t\t\t\theaders: { Accept: \"application/dns-json\" },\n\t\t\t\tsignal: controller.signal,\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(`DoH lookup failed: ${response.status}`);\n\t\t\t}\n\t\t\tconst raw = await response.json();\n\t\t\tconst body = parseDohResponse(raw);\n\t\t\t// NXDOMAIN (3) is a legitimate \"does not exist\" — treat as empty.\n\t\t\t// Any other non-zero status (SERVFAIL=2, REFUSED=5, etc.) is\n\t\t\t// ambiguous and could be a split-view attacker hiding records\n\t\t\t// from our resolver. Fail closed.\n\t\t\tif (body.Status === 3) return [];\n\t\t\tif (body.Status !== 0) {\n\t\t\t\tthrow new Error(`DoH ${type} lookup failed: rcode=${body.Status}`);\n\t\t\t}\n\t\t\t// DoH Answer arrays often include CNAME records alongside A/AAAA\n\t\t\t// records. Their `data` is a hostname, not an IP. Filter to just\n\t\t\t// IP literals so isPrivateIp sees real addresses.\n\t\t\treturn body.Answer.map((a) => a.data).filter(isIpLiteral);\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t}\n\n\tconst [a, aaaa] = await Promise.all([query(\"A\"), query(\"AAAA\")]);\n\treturn [...a, ...aaaa];\n};\n\n/**\n * Validate a URL and resolve its hostname to check the actual IPs against\n * the private-range blocklist. This catches DNS rebinding attacks using\n * attacker-controlled domains that publicly resolve to private addresses,\n * and wildcard DNS services like nip.io used by exploit tooling.\n *\n * Runs `validateExternalUrl` first for cheap pre-flight checks (scheme,\n * literal IP, known-bad hostnames). Then resolves the hostname and rejects\n * if ANY returned address is private.\n *\n * Fails closed: if resolution fails or returns no records, throws SsrfError.\n *\n * **Caveats.** This does NOT fully close the TOCTOU between check and\n * connect. Attacks that still work against this layer include:\n *\n * - TTL=0 rebind: authoritative server returns public IP to the check, then\n * private IP to the subsequent fetch() a few milliseconds later.\n * - Split-view via EDNS Client Subnet or source-IP inspection: the\n * authoritative server returns public IP to Cloudflare's DoH resolver and\n * private IP to the victim's own resolver (used by fetch()).\n * - Host-file overrides or split-horizon corporate DNS on self-hosted Node.\n * - Attacker-controlled rebinding services the caller has allowlisted.\n *\n * The only complete defense is a network-layer egress firewall. On\n * Cloudflare Workers, the platform fetch pipeline provides most of that.\n * On self-hosted Node, operators must restrict egress themselves.\n */\nexport async function resolveAndValidateExternalUrl(\n\turl: string,\n\toptions?: { resolver?: DnsResolver },\n): Promise<URL> {\n\tconst parsed = validateExternalUrl(url);\n\n\t// Strip brackets from IPv6 hostnames\n\tconst hostname = parsed.hostname.replace(IPV6_BRACKET_PATTERN, \"\");\n\n\t// If the hostname is already an IP literal, validateExternalUrl has\n\t// already checked it against the private-range list. Skip DNS.\n\tif (isIpLiteral(hostname)) {\n\t\treturn parsed;\n\t}\n\n\tconst resolver = options?.resolver ?? defaultResolver ?? cloudflareDohResolver;\n\n\tlet addresses: string[];\n\ttry {\n\t\taddresses = await resolver(hostname);\n\t} catch (error) {\n\t\tthrow new SsrfError(\n\t\t\t`Could not resolve hostname: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\n\tif (addresses.length === 0) {\n\t\tthrow new SsrfError(\"Hostname resolved to no addresses\");\n\t}\n\n\tfor (const ip of addresses) {\n\t\tif (isPrivateIp(ip)) {\n\t\t\tthrow new SsrfError(\"Hostname resolves to a private IP address\");\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/** True when a string looks like an IPv4 or IPv6 literal. */\nfunction isIpLiteral(host: string): boolean {\n\tif (parseIpv4(host) !== null) return true;\n\t// Very loose IPv6 heuristic — matches anything with a colon, which is\n\t// never valid in DNS hostnames, so this is safe.\n\treturn host.includes(\":\");\n}\n\n/**\n * Fetch a URL with SSRF protection on redirects.\n *\n * Uses `redirect: \"manual\"` to intercept redirects and re-validate each\n * redirect target against SSRF rules before following it. This prevents\n * an attacker from setting up an allowed external URL that redirects to\n * an internal IP (e.g. 169.254.169.254 for cloud metadata).\n *\n * @throws SsrfError if the initial URL or any redirect target is internal\n */\n/** Headers that must be stripped when a redirect crosses origins */\nconst CREDENTIAL_HEADERS = [\"authorization\", \"cookie\", \"proxy-authorization\"];\n\nexport async function ssrfSafeFetch(\n\turl: string,\n\tinit?: RequestInit,\n\toptions?: { resolver?: DnsResolver },\n): Promise<Response> {\n\tlet currentUrl = url;\n\tlet currentInit = init;\n\n\tfor (let i = 0; i <= MAX_REDIRECTS; i++) {\n\t\tawait resolveAndValidateExternalUrl(currentUrl, options);\n\n\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t...currentInit,\n\t\t\tredirect: \"manual\",\n\t\t});\n\n\t\t// Not a redirect -- return directly\n\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Extract redirect target\n\t\tconst location = response.headers.get(\"Location\");\n\t\tif (!location) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Resolve relative redirects against the current URL\n\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t// Strip credential headers on cross-origin redirects\n\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t}\n\t}\n\n\tthrow new SsrfError(`Too many redirects (max ${MAX_REDIRECTS})`);\n}\n\n/**\n * Return a copy of init with credential headers removed.\n */\nexport function stripCredentialHeaders(init: RequestInit): RequestInit {\n\tif (!init.headers) return init;\n\n\tconst headers = new Headers(init.headers);\n\tfor (const name of CREDENTIAL_HEADERS) {\n\t\theaders.delete(name);\n\t}\n\n\treturn { ...init, headers };\n}\n"],"mappings":";;;;;;;AAOA,MAAM,kCAAkC;AACxC,MAAM,+BAA+B;AACrC,MAAM,8BAA8B;AACpC,MAAM,+BACL;;;;;;;AAQD,MAAM,8BAA8B;;;;;;;AAQpC,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB;;AAG7B,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB;;AAG5B,MAAM,uBAAuB;;;;;;;;;;;AAY7B,MAAM,mBAA0D;CAE/D;EAAE,OAAO,SAAS,KAAK,GAAG,GAAG,EAAE;EAAE,KAAK,SAAS,KAAK,KAAK,KAAK,IAAI;EAAE;CAEpE;EAAE,OAAO,SAAS,IAAI,GAAG,GAAG,EAAE;EAAE,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;EAAE;CAElE;EAAE,OAAO,SAAS,KAAK,IAAI,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AAI,SAAS,SAAS,OAAO,SAAS,UAAU,IAC/C,QAAO;EAIR,MAAM,WAAW,SAAS,QAAQ,IAAI,WAAW;AACjD,MAAI,CAAC,SACJ,QAAO;EAIR,MAAM,iBAAiB,IAAI,IAAI,WAAW,CAAC;AAC3C,eAAa,IAAI,IAAI,UAAU,WAAW,CAAC;AAI3C,MAAI,mBAHe,IAAI,IAAI,WAAW,CAAC,UAGF,YACpC,eAAc,uBAAuB,YAAY;;AAInD,OAAM,IAAI,UAAU,2BAA2B,cAAc,GAAG;;;;;AAMjE,SAAgB,uBAAuB,MAAgC;AACtE,KAAI,CAAC,KAAK,QAAS,QAAO;CAE1B,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,MAAK,MAAM,QAAQ,mBAClB,SAAQ,OAAO,KAAK;AAGrB,QAAO;EAAE,GAAG;EAAM;EAAS"}
@@ -125,4 +125,4 @@ function rowToPluginState(row) {
125
125
 
126
126
  //#endregion
127
127
  export { PluginStateRepository as t };
128
- //# sourceMappingURL=state-xxv6ZTMv.mjs.map
128
+ //# sourceMappingURL=state-CQvoefYP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"state-xxv6ZTMv.mjs","names":[],"sources":["../src/plugins/state.ts"],"sourcesContent":["/**\n * Plugin State Repository\n *\n * Database-backed storage for plugin activation state.\n * Used by the admin API to persist plugin enable/disable across restarts.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\n\nexport type PluginStatus = \"active\" | \"inactive\";\nexport type PluginSource = \"config\" | \"marketplace\" | \"registry\";\n\nfunction toPluginStatus(value: string): PluginStatus {\n\tif (value === \"active\") return \"active\";\n\treturn \"inactive\";\n}\n\nfunction toPluginSource(value: string | undefined | null): PluginSource {\n\tif (value === \"marketplace\") return \"marketplace\";\n\tif (value === \"registry\") return \"registry\";\n\treturn \"config\";\n}\n\nexport interface PluginState {\n\tpluginId: string;\n\tstatus: PluginStatus;\n\tversion: string;\n\tinstalledAt: Date;\n\tactivatedAt: Date | null;\n\tdeactivatedAt: Date | null;\n\tsource: PluginSource;\n\tmarketplaceVersion: string | null;\n\tdisplayName: string | null;\n\tdescription: string | null;\n\t/**\n\t * Publisher DID this plugin was published under. Populated only when\n\t * `source === \"registry\"`; null otherwise.\n\t */\n\tregistryPublisherDid: string | null;\n\t/**\n\t * Slug under which the plugin was published in the publisher's repo\n\t * (the rkey of the `pm.fair.package.profile` record). Populated only\n\t * when `source === \"registry\"`; null otherwise.\n\t *\n\t * The opaque `pluginId` for registry installs is derived from\n\t * `(registryPublisherDid, registrySlug)` -- see\n\t * `packages/core/src/registry/plugin-id.ts`.\n\t */\n\tregistrySlug: string | null;\n\tmcpToolsEnabled: boolean;\n\tmcpToolsConsent: string | null;\n}\n\n/**\n * Repository for plugin state in the database\n */\nexport class PluginStateRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Get state for a specific plugin\n\t */\n\tasync get(pluginId: string): Promise<PluginState | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\n\t\treturn rowToPluginState(row);\n\t}\n\n\t/**\n\t * Get all plugin states\n\t */\n\tasync getAll(): Promise<PluginState[]> {\n\t\tconst rows = await this.db.selectFrom(\"_plugin_state\").selectAll().execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Get all marketplace-installed plugin states\n\t */\n\tasync getMarketplacePlugins(): Promise<PluginState[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", \"marketplace\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Get all registry-installed plugin states.\n\t *\n\t * The runtime's registry sync path uses this to discover which\n\t * registry plugins should be loaded into the sandbox on this worker.\n\t */\n\tasync getRegistryPlugins(): Promise<PluginState[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", \"registry\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Create or update plugin state\n\t */\n\tasync upsert(\n\t\tpluginId: string,\n\t\tversion: string,\n\t\tstatus: PluginStatus,\n\t\topts?: {\n\t\t\tsource?: PluginSource;\n\t\t\tmarketplaceVersion?: string;\n\t\t\tdisplayName?: string;\n\t\t\tdescription?: string;\n\t\t\tregistryPublisherDid?: string;\n\t\t\tregistrySlug?: string;\n\t\t\tmcpToolsEnabled?: boolean;\n\t\t\tmcpToolsConsent?: string | null;\n\t\t},\n\t): Promise<PluginState> {\n\t\tconst now = new Date().toISOString();\n\t\tconst existing = await this.get(pluginId);\n\n\t\tif (existing) {\n\t\t\t// Update existing state\n\t\t\tconst updates: Record<string, string | number | null> = {\n\t\t\t\tstatus,\n\t\t\t\tversion,\n\t\t\t};\n\n\t\t\tif (status === \"active\" && existing.status !== \"active\") {\n\t\t\t\tupdates.activated_at = now;\n\t\t\t} else if (status === \"inactive\" && existing.status !== \"inactive\") {\n\t\t\t\tupdates.deactivated_at = now;\n\t\t\t}\n\n\t\t\tif (opts?.source) updates.source = opts.source;\n\t\t\tif (opts?.marketplaceVersion !== undefined) {\n\t\t\t\tupdates.marketplace_version = opts.marketplaceVersion;\n\t\t\t}\n\t\t\tif (opts?.displayName !== undefined) {\n\t\t\t\tupdates.display_name = opts.displayName;\n\t\t\t}\n\t\t\tif (opts?.description !== undefined) {\n\t\t\t\tupdates.description = opts.description;\n\t\t\t}\n\t\t\tif (opts?.registryPublisherDid !== undefined) {\n\t\t\t\tupdates.registry_publisher_did = opts.registryPublisherDid;\n\t\t\t}\n\t\t\tif (opts?.registrySlug !== undefined) {\n\t\t\t\tupdates.registry_slug = opts.registrySlug;\n\t\t\t}\n\t\t\tif (opts?.mcpToolsEnabled !== undefined) {\n\t\t\t\tupdates.mcp_tools_enabled = opts.mcpToolsEnabled ? 1 : 0;\n\t\t\t}\n\t\t\tif (opts?.mcpToolsConsent !== undefined) {\n\t\t\t\tupdates.mcp_tools_consent = opts.mcpToolsConsent;\n\t\t\t}\n\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_plugin_state\")\n\t\t\t\t.set(updates)\n\t\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t\t.execute();\n\t\t} else {\n\t\t\t// Create new state\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"_plugin_state\")\n\t\t\t\t.values({\n\t\t\t\t\tplugin_id: pluginId,\n\t\t\t\t\tstatus,\n\t\t\t\t\tversion,\n\t\t\t\t\tinstalled_at: now,\n\t\t\t\t\tactivated_at: status === \"active\" ? now : null,\n\t\t\t\t\tdeactivated_at: null,\n\t\t\t\t\tdata: null,\n\t\t\t\t\tsource: opts?.source ?? \"config\",\n\t\t\t\t\tmarketplace_version: opts?.marketplaceVersion ?? null,\n\t\t\t\t\tdisplay_name: opts?.displayName ?? null,\n\t\t\t\t\tdescription: opts?.description ?? null,\n\t\t\t\t\tregistry_publisher_did: opts?.registryPublisherDid ?? null,\n\t\t\t\t\tregistry_slug: opts?.registrySlug ?? null,\n\t\t\t\t\tmcp_tools_enabled: opts?.mcpToolsEnabled ? 1 : 0,\n\t\t\t\t\tmcp_tools_consent: opts?.mcpToolsConsent ?? null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\t\t}\n\n\t\treturn (await this.get(pluginId))!;\n\t}\n\n\t/**\n\t * Enable a plugin\n\t */\n\tasync enable(pluginId: string, version: string): Promise<PluginState> {\n\t\treturn this.upsert(pluginId, version, \"active\");\n\t}\n\n\t/**\n\t * Disable a plugin\n\t */\n\tasync disable(pluginId: string, version: string): Promise<PluginState> {\n\t\treturn this.upsert(pluginId, version, \"inactive\");\n\t}\n\n\t/**\n\t * Delete plugin state\n\t */\n\tasync delete(pluginId: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_state\")\n\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n}\n\n/**\n * Internal: map a `_plugin_state` row to the public `PluginState` shape.\n *\n * Kept at module scope so the three select paths (`get`, `getAll`,\n * `getMarketplacePlugins`, `getRegistryPlugins`) stay byte-identical in\n * their handling of nullable columns -- adding a new column to the table\n * means changing this function and nothing else.\n */\ninterface PluginStateRow {\n\tplugin_id: string;\n\tstatus: string;\n\tversion: string;\n\tinstalled_at: string;\n\tactivated_at: string | null;\n\tdeactivated_at: string | null;\n\tsource: string;\n\tmarketplace_version: string | null;\n\tdisplay_name: string | null;\n\tdescription: string | null;\n\tregistry_publisher_did: string | null;\n\tregistry_slug: string | null;\n\tmcp_tools_enabled: number;\n\tmcp_tools_consent: string | null;\n}\n\nfunction rowToPluginState(row: PluginStateRow): PluginState {\n\treturn {\n\t\tpluginId: row.plugin_id,\n\t\tstatus: toPluginStatus(row.status),\n\t\tversion: row.version,\n\t\tinstalledAt: new Date(row.installed_at),\n\t\tactivatedAt: row.activated_at ? new Date(row.activated_at) : null,\n\t\tdeactivatedAt: row.deactivated_at ? new Date(row.deactivated_at) : null,\n\t\tsource: toPluginSource(row.source),\n\t\tmarketplaceVersion: row.marketplace_version ?? null,\n\t\tdisplayName: row.display_name ?? null,\n\t\tdescription: row.description ?? null,\n\t\tregistryPublisherDid: row.registry_publisher_did ?? null,\n\t\tregistrySlug: row.registry_slug ?? null,\n\t\tmcpToolsEnabled: row.mcp_tools_enabled === 1,\n\t\tmcpToolsConsent: row.mcp_tools_consent ?? null,\n\t};\n}\n"],"mappings":";AAcA,SAAS,eAAe,OAA6B;AACpD,KAAI,UAAU,SAAU,QAAO;AAC/B,QAAO;;AAGR,SAAS,eAAe,OAAgD;AACvE,KAAI,UAAU,cAAe,QAAO;AACpC,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G;EAC7D,eAAe,IAAI,iBAAiB,IAAI,KAAK,IAAI,eAAe,GAAG;EACnE,QAAQ,eAAe,IAAI,OAAO;EAClC,oBAAoB,IAAI,uBAAuB;EAC/C,aAAa,IAAI,gBAAgB;EACjC,aAAa,IAAI,eAAe;EAChC,sBAAsB,IAAI,0BAA0B;EACpD,cAAc,IAAI,iBAAiB;EACnC,iBAAiB,IAAI,sBAAsB;EAC3C,iBAAiB,IAAI,qBAAqB;EAC1C"}
1
+ {"version":3,"file":"state-CQvoefYP.mjs","names":[],"sources":["../src/plugins/state.ts"],"sourcesContent":["/**\n * Plugin State Repository\n *\n * Database-backed storage for plugin activation state.\n * Used by the admin API to persist plugin enable/disable across restarts.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport type { Database } from \"../database/types.js\";\n\nexport type PluginStatus = \"active\" | \"inactive\";\nexport type PluginSource = \"config\" | \"marketplace\" | \"registry\";\n\nfunction toPluginStatus(value: string): PluginStatus {\n\tif (value === \"active\") return \"active\";\n\treturn \"inactive\";\n}\n\nfunction toPluginSource(value: string | undefined | null): PluginSource {\n\tif (value === \"marketplace\") return \"marketplace\";\n\tif (value === \"registry\") return \"registry\";\n\treturn \"config\";\n}\n\nexport interface PluginState {\n\tpluginId: string;\n\tstatus: PluginStatus;\n\tversion: string;\n\tinstalledAt: Date;\n\tactivatedAt: Date | null;\n\tdeactivatedAt: Date | null;\n\tsource: PluginSource;\n\tmarketplaceVersion: string | null;\n\tdisplayName: string | null;\n\tdescription: string | null;\n\t/**\n\t * Publisher DID this plugin was published under. Populated only when\n\t * `source === \"registry\"`; null otherwise.\n\t */\n\tregistryPublisherDid: string | null;\n\t/**\n\t * Slug under which the plugin was published in the publisher's repo\n\t * (the rkey of the `pm.fair.package.profile` record). Populated only\n\t * when `source === \"registry\"`; null otherwise.\n\t *\n\t * The opaque `pluginId` for registry installs is derived from\n\t * `(registryPublisherDid, registrySlug)` -- see\n\t * `packages/core/src/registry/plugin-id.ts`.\n\t */\n\tregistrySlug: string | null;\n\tmcpToolsEnabled: boolean;\n\tmcpToolsConsent: string | null;\n}\n\n/**\n * Repository for plugin state in the database\n */\nexport class PluginStateRepository {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Get state for a specific plugin\n\t */\n\tasync get(pluginId: string): Promise<PluginState | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\n\t\treturn rowToPluginState(row);\n\t}\n\n\t/**\n\t * Get all plugin states\n\t */\n\tasync getAll(): Promise<PluginState[]> {\n\t\tconst rows = await this.db.selectFrom(\"_plugin_state\").selectAll().execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Get all marketplace-installed plugin states\n\t */\n\tasync getMarketplacePlugins(): Promise<PluginState[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", \"marketplace\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Get all registry-installed plugin states.\n\t *\n\t * The runtime's registry sync path uses this to discover which\n\t * registry plugins should be loaded into the sandbox on this worker.\n\t */\n\tasync getRegistryPlugins(): Promise<PluginState[]> {\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_state\")\n\t\t\t.selectAll()\n\t\t\t.where(\"source\", \"=\", \"registry\")\n\t\t\t.execute();\n\t\treturn rows.map(rowToPluginState);\n\t}\n\n\t/**\n\t * Create or update plugin state\n\t */\n\tasync upsert(\n\t\tpluginId: string,\n\t\tversion: string,\n\t\tstatus: PluginStatus,\n\t\topts?: {\n\t\t\tsource?: PluginSource;\n\t\t\tmarketplaceVersion?: string;\n\t\t\tdisplayName?: string;\n\t\t\tdescription?: string;\n\t\t\tregistryPublisherDid?: string;\n\t\t\tregistrySlug?: string;\n\t\t\tmcpToolsEnabled?: boolean;\n\t\t\tmcpToolsConsent?: string | null;\n\t\t},\n\t): Promise<PluginState> {\n\t\tconst now = new Date().toISOString();\n\t\tconst existing = await this.get(pluginId);\n\n\t\tif (existing) {\n\t\t\t// Update existing state\n\t\t\tconst updates: Record<string, string | number | null> = {\n\t\t\t\tstatus,\n\t\t\t\tversion,\n\t\t\t};\n\n\t\t\tif (status === \"active\" && existing.status !== \"active\") {\n\t\t\t\tupdates.activated_at = now;\n\t\t\t} else if (status === \"inactive\" && existing.status !== \"inactive\") {\n\t\t\t\tupdates.deactivated_at = now;\n\t\t\t}\n\n\t\t\tif (opts?.source) updates.source = opts.source;\n\t\t\tif (opts?.marketplaceVersion !== undefined) {\n\t\t\t\tupdates.marketplace_version = opts.marketplaceVersion;\n\t\t\t}\n\t\t\tif (opts?.displayName !== undefined) {\n\t\t\t\tupdates.display_name = opts.displayName;\n\t\t\t}\n\t\t\tif (opts?.description !== undefined) {\n\t\t\t\tupdates.description = opts.description;\n\t\t\t}\n\t\t\tif (opts?.registryPublisherDid !== undefined) {\n\t\t\t\tupdates.registry_publisher_did = opts.registryPublisherDid;\n\t\t\t}\n\t\t\tif (opts?.registrySlug !== undefined) {\n\t\t\t\tupdates.registry_slug = opts.registrySlug;\n\t\t\t}\n\t\t\tif (opts?.mcpToolsEnabled !== undefined) {\n\t\t\t\tupdates.mcp_tools_enabled = opts.mcpToolsEnabled ? 1 : 0;\n\t\t\t}\n\t\t\tif (opts?.mcpToolsConsent !== undefined) {\n\t\t\t\tupdates.mcp_tools_consent = opts.mcpToolsConsent;\n\t\t\t}\n\n\t\t\tawait this.db\n\t\t\t\t.updateTable(\"_plugin_state\")\n\t\t\t\t.set(updates)\n\t\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t\t.execute();\n\t\t} else {\n\t\t\t// Create new state\n\t\t\tawait this.db\n\t\t\t\t.insertInto(\"_plugin_state\")\n\t\t\t\t.values({\n\t\t\t\t\tplugin_id: pluginId,\n\t\t\t\t\tstatus,\n\t\t\t\t\tversion,\n\t\t\t\t\tinstalled_at: now,\n\t\t\t\t\tactivated_at: status === \"active\" ? now : null,\n\t\t\t\t\tdeactivated_at: null,\n\t\t\t\t\tdata: null,\n\t\t\t\t\tsource: opts?.source ?? \"config\",\n\t\t\t\t\tmarketplace_version: opts?.marketplaceVersion ?? null,\n\t\t\t\t\tdisplay_name: opts?.displayName ?? null,\n\t\t\t\t\tdescription: opts?.description ?? null,\n\t\t\t\t\tregistry_publisher_did: opts?.registryPublisherDid ?? null,\n\t\t\t\t\tregistry_slug: opts?.registrySlug ?? null,\n\t\t\t\t\tmcp_tools_enabled: opts?.mcpToolsEnabled ? 1 : 0,\n\t\t\t\t\tmcp_tools_consent: opts?.mcpToolsConsent ?? null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\t\t}\n\n\t\treturn (await this.get(pluginId))!;\n\t}\n\n\t/**\n\t * Enable a plugin\n\t */\n\tasync enable(pluginId: string, version: string): Promise<PluginState> {\n\t\treturn this.upsert(pluginId, version, \"active\");\n\t}\n\n\t/**\n\t * Disable a plugin\n\t */\n\tasync disable(pluginId: string, version: string): Promise<PluginState> {\n\t\treturn this.upsert(pluginId, version, \"inactive\");\n\t}\n\n\t/**\n\t * Delete plugin state\n\t */\n\tasync delete(pluginId: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_state\")\n\t\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n}\n\n/**\n * Internal: map a `_plugin_state` row to the public `PluginState` shape.\n *\n * Kept at module scope so the three select paths (`get`, `getAll`,\n * `getMarketplacePlugins`, `getRegistryPlugins`) stay byte-identical in\n * their handling of nullable columns -- adding a new column to the table\n * means changing this function and nothing else.\n */\ninterface PluginStateRow {\n\tplugin_id: string;\n\tstatus: string;\n\tversion: string;\n\tinstalled_at: string;\n\tactivated_at: string | null;\n\tdeactivated_at: string | null;\n\tsource: string;\n\tmarketplace_version: string | null;\n\tdisplay_name: string | null;\n\tdescription: string | null;\n\tregistry_publisher_did: string | null;\n\tregistry_slug: string | null;\n\tmcp_tools_enabled: number;\n\tmcp_tools_consent: string | null;\n}\n\nfunction rowToPluginState(row: PluginStateRow): PluginState {\n\treturn {\n\t\tpluginId: row.plugin_id,\n\t\tstatus: toPluginStatus(row.status),\n\t\tversion: row.version,\n\t\tinstalledAt: new Date(row.installed_at),\n\t\tactivatedAt: row.activated_at ? new Date(row.activated_at) : null,\n\t\tdeactivatedAt: row.deactivated_at ? new Date(row.deactivated_at) : null,\n\t\tsource: toPluginSource(row.source),\n\t\tmarketplaceVersion: row.marketplace_version ?? null,\n\t\tdisplayName: row.display_name ?? null,\n\t\tdescription: row.description ?? null,\n\t\tregistryPublisherDid: row.registry_publisher_did ?? null,\n\t\tregistrySlug: row.registry_slug ?? null,\n\t\tmcpToolsEnabled: row.mcp_tools_enabled === 1,\n\t\tmcpToolsConsent: row.mcp_tools_consent ?? null,\n\t};\n}\n"],"mappings":";AAcA,SAAS,eAAe,OAA6B;AACpD,KAAI,UAAU,SAAU,QAAO;AAC/B,QAAO;;AAGR,SAAS,eAAe,OAAgD;AACvE,KAAI,UAAU,cAAe,QAAO;AACpC,KAAI,UAAU,WAAY,QAAO;AACjC,QAAO;;;;;AAoCR,IAAa,wBAAb,MAAmC;CAClC,YAAY,AAAQ,IAAsB;EAAtB;;;;;CAKpB,MAAM,IAAI,UAA+C;EACxD,MAAM,MAAM,MAAM,KAAK,GACrB,WAAW,gBAAgB,CAC3B,WAAW,CACX,MAAM,aAAa,KAAK,SAAS,CACjC,kBAAkB;AAEpB,MAAI,CAAC,IAAK,QAAO;AAEjB,SAAO,iBAAiB,IAAI;;;;;CAM7B,MAAM,SAAiC;AAEtC,UADa,MAAM,KAAK,GAAG,WAAW,gBAAgB,CAAC,WAAW,CAAC,SAAS,EAChE,IAAI,iBAAiB;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=status-COfycGIU.mjs.map
30
+ //# sourceMappingURL=status-CIsmlC1E.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"status-COfycGIU.mjs","names":[],"sources":["../src/redirects/status.ts"],"sourcesContent":["/**\n * Redirect rule status codes.\n *\n * A redirect rule's `type` is either a *redirect* status (issues a `Location`\n * header) or a *terminal* status (serves the status with no target). Terminal\n * statuses let editors mark a URL as intentionally gone:\n * - `410 Gone` — permanently and intentionally deleted (Google deindexes it\n * faster than a 404).\n * - `451 Unavailable For Legal Reasons`.\n */\n\n/** Statuses that issue an HTTP redirect (require a destination). */\nexport const REDIRECT_STATUSES = [301, 302, 307, 308] as const;\n\n/** Terminal statuses that serve a status with no `Location` / no destination. */\nexport const TERMINAL_STATUSES = [410, 451] as const;\n\n/** All values accepted as a redirect rule `type`. */\nexport const REDIRECT_RULE_STATUSES: readonly number[] = [\n\t...REDIRECT_STATUSES,\n\t...TERMINAL_STATUSES,\n];\n\n/** True for terminal statuses (410/451) — served directly, with no target. */\nexport function isTerminalStatus(type: number): boolean {\n\treturn (TERMINAL_STATUSES as readonly number[]).includes(type);\n}\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,oBAAoB;CAAC;CAAK;CAAK;CAAK;CAAI;;AAGrD,MAAa,oBAAoB,CAAC,KAAK,IAAI;;AAG3C,MAAa,yBAA4C,CACxD,GAAG,mBACH,GAAG,kBACH;;AAGD,SAAgB,iBAAiB,MAAuB;AACvD,QAAQ,kBAAwC,SAAS,KAAK"}
1
+ {"version":3,"file":"status-CIsmlC1E.mjs","names":[],"sources":["../src/redirects/status.ts"],"sourcesContent":["/**\n * Redirect rule status codes.\n *\n * A redirect rule's `type` is either a *redirect* status (issues a `Location`\n * header) or a *terminal* status (serves the status with no target). Terminal\n * statuses let editors mark a URL as intentionally gone:\n * - `410 Gone` — permanently and intentionally deleted (Google deindexes it\n * faster than a 404).\n * - `451 Unavailable For Legal Reasons`.\n */\n\n/** Statuses that issue an HTTP redirect (require a destination). */\nexport const REDIRECT_STATUSES = [301, 302, 307, 308] as const;\n\n/** Terminal statuses that serve a status with no `Location` / no destination. */\nexport const TERMINAL_STATUSES = [410, 451] as const;\n\n/** All values accepted as a redirect rule `type`. */\nexport const REDIRECT_RULE_STATUSES: readonly number[] = [\n\t...REDIRECT_STATUSES,\n\t...TERMINAL_STATUSES,\n];\n\n/** True for terminal statuses (410/451) — served directly, with no target. */\nexport function isTerminalStatus(type: number): boolean {\n\treturn (TERMINAL_STATUSES as readonly number[]).includes(type);\n}\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,oBAAoB;CAAC;CAAK;CAAK;CAAK;CAAI;;AAGrD,MAAa,oBAAoB,CAAC,KAAK,IAAI;;AAG3C,MAAa,yBAA4C,CACxD,GAAG,mBACH,GAAG,kBACH;;AAGD,SAAgB,iBAAiB,MAAuB;AACvD,QAAQ,kBAAwC,SAAS,KAAK"}
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-CcSZCcF1.mjs";
1
+ import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-DLG4IFEQ.mjs";
2
2
 
3
3
  //#region src/storage/local.d.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as EmDashStorageError } from "../types-BD40g7zz.mjs";
1
+ import { t as EmDashStorageError } from "../types-BjxTKxrZ.mjs";
2
2
  import mime from "mime/lite";
3
3
  import { createReadStream, existsSync } from "node:fs";
4
4
  import * as path from "node:path";
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-CcSZCcF1.mjs";
1
+ import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-DLG4IFEQ.mjs";
2
2
 
3
3
  //#region src/storage/s3.d.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as EmDashStorageError } from "../types-BD40g7zz.mjs";
1
+ import { t as EmDashStorageError } from "../types-BjxTKxrZ.mjs";
2
2
  import { z } from "zod";
3
3
  import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
4
4
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
@@ -1,7 +1,7 @@
1
- import { o as __exportAll } from "./runner-BsI18UgP.mjs";
1
+ import { o as __exportAll } from "./runner-BFTrkYhu.mjs";
2
2
  import { i as resolveConfiguredLocale } from "./config-DyF3OKg_.mjs";
3
- import { t as TaxonomyRepository } from "./taxonomy-DvwWAPvA.mjs";
4
- import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-B61CRSha.mjs";
3
+ import { t as TaxonomyRepository } from "./taxonomy-pOrB2kZe.mjs";
4
+ import { f as fetchVisibleTermCounts, l as invalidateTaxonomyDefsCache, u as invalidateTermCache } from "./taxonomies-CLN1N92E.mjs";
5
5
  import { ulid } from "ulidx";
6
6
 
7
7
  //#region src/api/handlers/taxonomies.ts
@@ -12,6 +12,7 @@ var taxonomies_exports = /* @__PURE__ */ __exportAll({
12
12
  handleTermDelete: () => handleTermDelete,
13
13
  handleTermGet: () => handleTermGet,
14
14
  handleTermList: () => handleTermList,
15
+ handleTermReorder: () => handleTermReorder,
15
16
  handleTermTranslations: () => handleTermTranslations,
16
17
  handleTermUpdate: () => handleTermUpdate
17
18
  });
@@ -216,6 +217,85 @@ async function handleTermList(db, taxonomyName, options = {}) {
216
217
  }
217
218
  }
218
219
  /**
220
+ * Set the manual order of one sibling group.
221
+ *
222
+ * `ids` names the terms to move, in the desired order; each is a row id or a
223
+ * translation_group and resolves to the latter, because a position belongs to a
224
+ * term rather than to one of its locales. Reordering never reparents — moving a
225
+ * term under a different parent is a term update.
226
+ *
227
+ * The group is `(taxonomy, parentId)` and has no locale: `parentId` is the
228
+ * parent's translation_group (a row id is accepted and resolved), and `null`
229
+ * selects the top level — which for a flat taxonomy is every term.
230
+ *
231
+ * `ids` may be a *subset* of the group, and the listed terms are permuted
232
+ * within the positions they already occupy. A locale only renders the terms
233
+ * translated into it, so a caller often cannot name every member; a member left
234
+ * out keeps its place, which is also what makes a stale list harmless.
235
+ */
236
+ async function handleTermReorder(db, taxonomyName, input) {
237
+ try {
238
+ const lookup = await requireTaxonomyDef(db, taxonomyName);
239
+ if (!lookup.success) return lookup;
240
+ const repo = new TaxonomyRepository(db);
241
+ let parentId = input.parentId ?? null;
242
+ if (parentId !== null) {
243
+ const parent = await repo.findById(parentId);
244
+ if (parent) parentId = parent.translationGroup ?? parent.id;
245
+ }
246
+ const members = await repo.findByName(taxonomyName, { parentId });
247
+ const siblings = [];
248
+ const seen = /* @__PURE__ */ new Set();
249
+ const resolve = /* @__PURE__ */ new Map();
250
+ for (const term of members) {
251
+ const group = term.translationGroup ?? term.id;
252
+ if (!seen.has(group)) {
253
+ seen.add(group);
254
+ siblings.push({
255
+ group,
256
+ position: term.sortOrder
257
+ });
258
+ }
259
+ resolve.set(group, group);
260
+ resolve.set(term.id, group);
261
+ }
262
+ const groups = [];
263
+ for (const id of input.ids) {
264
+ const group = resolve.get(id);
265
+ if (!group) return {
266
+ success: false,
267
+ error: {
268
+ code: "REORDER_MISMATCH",
269
+ message: `Term "${id}" is not in the sibling group being reordered`
270
+ }
271
+ };
272
+ if (groups.includes(group)) return {
273
+ success: false,
274
+ error: {
275
+ code: "REORDER_MISMATCH",
276
+ message: `Term "${id}" is listed more than once`
277
+ }
278
+ };
279
+ groups.push(group);
280
+ }
281
+ await repo.reorder(groups, siblings);
282
+ invalidateTermCache();
283
+ return {
284
+ success: true,
285
+ data: { reordered: true }
286
+ };
287
+ } catch (error) {
288
+ console.error("[taxonomies] term reorder failed:", error);
289
+ return {
290
+ success: false,
291
+ error: {
292
+ code: "TERM_REORDER_ERROR",
293
+ message: "Failed to reorder terms"
294
+ }
295
+ };
296
+ }
297
+ }
298
+ /**
219
299
  * Validate a parent term reference for create/update.
220
300
  *
221
301
  * Returns `null` on success or a structured error message that callers
@@ -526,5 +606,5 @@ async function handleTermDelete(db, taxonomyName, termSlug, options = {}) {
526
606
  }
527
607
 
528
608
  //#endregion
529
- export { handleTermGet as a, handleTermUpdate as c, handleTermDelete as i, taxonomies_exports as l, handleTaxonomyList as n, handleTermList as o, handleTermCreate as r, handleTermTranslations as s, handleTaxonomyCreate as t };
530
- //# sourceMappingURL=taxonomies-Dbdki3Un.mjs.map
609
+ export { handleTermGet as a, handleTermTranslations as c, handleTermDelete as i, handleTermUpdate as l, handleTaxonomyList as n, handleTermList as o, handleTermCreate as r, handleTermReorder as s, handleTaxonomyCreate as t, taxonomies_exports as u };
610
+ //# sourceMappingURL=taxonomies-CKuaZER5.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taxonomies-CKuaZER5.mjs","names":[],"sources":["../src/api/handlers/taxonomies.ts"],"sourcesContent":["/**\n * Taxonomy and term CRUD handlers.\n *\n * i18n: terms and defs are per-locale. `(name, slug, locale)` is unique for\n * terms; `(name, locale)` for defs. Translations of the same term/def share a\n * `translation_group`. The content_taxonomies pivot stores translation_groups\n * so assignments span every locale of a post.\n */\n\nimport type { Kysely, Selectable } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { TaxonomyRepository, type SiblingPosition } from \"../../database/repositories/taxonomy.js\";\nimport type { Database, TaxonomyDefTable } from \"../../database/types.js\";\nimport { resolveConfiguredLocale } from \"../../i18n/config.js\";\nimport { invalidateTaxonomyDefsCache, invalidateTermCache } from \"../../taxonomies/index.js\";\nimport { fetchVisibleTermCounts } from \"../../taxonomies/term-counts.js\";\nimport type { ApiResult } from \"../types.js\";\n\nconst NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\n// ---------------------------------------------------------------------------\n// Response types\n// ---------------------------------------------------------------------------\n\nexport interface TaxonomyDef {\n\tid: string;\n\tname: string;\n\tlabel: string;\n\tlabelSingular?: string;\n\thierarchical: boolean;\n\tcollections: string[];\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TaxonomyListResponse {\n\ttaxonomies: TaxonomyDef[];\n}\n\nexport interface TermData {\n\tid: string;\n\tname: string;\n\tslug: string;\n\tlabel: string;\n\tparentId: string | null;\n\tdescription?: string;\n\tlocale: string;\n\ttranslationGroup: string | null;\n}\n\nexport interface TermWithCount extends TermData {\n\t/** Absent when the caller opted out of counts (`includeCounts: false`). */\n\tcount?: number;\n\tchildren: TermWithCount[];\n}\n\nexport interface TermListResponse {\n\tterms: TermWithCount[];\n}\n\nexport interface TermReorderResponse {\n\treordered: true;\n}\n\nexport interface TermResponse {\n\tterm: TermData;\n}\n\nexport interface TermGetResponse {\n\tterm: TermData & {\n\t\tcount: number;\n\t\tchildren: Array<{ id: string; slug: string; label: string }>;\n\t};\n}\n\nexport interface TermTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tslug: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\nexport interface TaxonomyDefTranslationsResponse {\n\ttranslationGroup: string | null;\n\ttranslations: Array<{\n\t\tid: string;\n\t\tname: string;\n\t\tlabel: string;\n\t\tlocale: string;\n\t}>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build tree structure from flat terms\n */\nfunction buildTree(flatTerms: TermWithCount[]): TermWithCount[] {\n\t// `parentId` holds the parent's translation_group, so resolve links by group.\n\t// Key by (locale, group): a child's parent lives in the same locale, and an\n\t// unfiltered list mixes locales whose translated siblings share a group —\n\t// keying by group alone would collide and misattach children across locales.\n\tconst byLocaleGroup = new Map<string, TermWithCount>();\n\tconst roots: TermWithCount[] = [];\n\tfor (const term of flatTerms) {\n\t\tbyLocaleGroup.set(`${term.locale}::${term.translationGroup ?? term.id}`, term);\n\t}\n\tfor (const term of flatTerms) {\n\t\tconst parent = term.parentId\n\t\t\t? byLocaleGroup.get(`${term.locale}::${term.parentId}`)\n\t\t\t: undefined;\n\t\tif (parent) {\n\t\t\tparent.children.push(term);\n\t\t} else {\n\t\t\troots.push(term);\n\t\t}\n\t}\n\treturn roots;\n}\n\n/**\n * Look up a taxonomy definition by name (optionally scoped to a locale).\n * Returns the lowest-locale match when no locale is provided.\n */\nasync function requireTaxonomyDef(\n\tdb: Kysely<Database>,\n\tname: string,\n\tlocale?: string,\n): Promise<\n\t| { success: true; def: Selectable<TaxonomyDefTable> }\n\t| { success: false; error: { code: string; message: string } }\n> {\n\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll().where(\"name\", \"=\", name);\n\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\tconst def = await query.orderBy(\"locale\", \"asc\").executeTakeFirst();\n\tif (!def) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"NOT_FOUND\", message: `Taxonomy '${name}' not found` },\n\t\t};\n\t}\n\treturn { success: true, def };\n}\n\n/** Declared collections of a taxonomy def row (deduped, parsed from JSON). */\nfunction defCollections(def: Selectable<TaxonomyDefTable>): string[] {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- column stores a JSON string[] written by handleTaxonomyCreate\n\tconst parsed = def.collections ? (JSON.parse(def.collections) as string[]) : [];\n\treturn [...new Set(parsed)];\n}\n\nfunction rowToDef(row: Selectable<TaxonomyDefTable>): TaxonomyDef {\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tlabel: row.label,\n\t\tlabelSingular: row.label_singular ?? undefined,\n\t\thierarchical: row.hierarchical === 1,\n\t\tcollections: row.collections ? JSON.parse(row.collections) : [],\n\t\tlocale: row.locale,\n\t\ttranslationGroup: row.translation_group,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Taxonomy definition handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all taxonomy definitions\n */\nexport async function handleTaxonomyList(\n\tdb: Kysely<Database>,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TaxonomyListResponse>> {\n\ttry {\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tlet query = db.selectFrom(\"_emdash_taxonomy_defs\").selectAll();\n\t\tif (locale !== undefined) query = query.where(\"locale\", \"=\", locale);\n\t\tconst [rows, collectionRows] = await Promise.all([\n\t\t\tquery.execute(),\n\t\t\tdb.selectFrom(\"_emdash_collections\").select(\"slug\").execute(),\n\t\t]);\n\n\t\t// Filter orphan collection references on read so the response stays\n\t\t// consistent with `schema_list_collections`. Storage is untouched —\n\t\t// re-creating the collection re-links automatically.\n\t\tconst realCollections = new Set(collectionRows.map((r) => r.slug));\n\n\t\tconst taxonomies: TaxonomyDef[] = rows.map((row) => {\n\t\t\tconst def = rowToDef(row);\n\t\t\treturn { ...def, collections: def.collections.filter((slug) => realCollections.has(slug)) };\n\t\t});\n\n\t\treturn { success: true, data: { taxonomies } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_LIST_ERROR\", message: \"Failed to list taxonomies\" },\n\t\t};\n\t}\n}\n\n/**\n * Create a new taxonomy definition\n */\nexport async function handleTaxonomyCreate(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tname: string;\n\t\tlabel: string;\n\t\tlabelSingular?: string;\n\t\thierarchical?: boolean;\n\t\tcollections?: string[];\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<{ taxonomy: TaxonomyDef }>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\tif (!NAME_PATTERN.test(input.name)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"Taxonomy name must start with a letter and contain only lowercase letters, numbers, and underscores\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst collections = [...new Set(input.collections ?? [])];\n\t\tif (collections.length > 0) {\n\t\t\tconst existingCollections = await db\n\t\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t\t.select(\"slug\")\n\t\t\t\t.where(\"slug\", \"in\", collections)\n\t\t\t\t.execute();\n\t\t\tconst existingSlugs = new Set(existingCollections.map((c) => c.slug));\n\t\t\tconst invalid = collections.filter((c) => !existingSlugs.has(c));\n\t\t\tif (invalid.length > 0) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\t\tmessage: `Unknown collection(s): ${invalid.join(\", \")}`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet translationGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.selectAll()\n\t\t\t\t.where(\"id\", \"=\", input.translationOf)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (!source) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Source taxonomy for translation not found\" },\n\t\t\t\t};\n\t\t\t}\n\t\t\ttranslationGroup = source.translation_group ?? source.id;\n\t\t}\n\n\t\t// Duplicate guard scoped to locale (so the same name can exist in ES\n\t\t// and EN).\n\t\tif (locale !== undefined) {\n\t\t\tconst existing = await db\n\t\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t\t.select(\"id\")\n\t\t\t\t.where(\"name\", \"=\", input.name)\n\t\t\t\t.where(\"locale\", \"=\", locale)\n\t\t\t\t.executeTakeFirst();\n\t\t\tif (existing) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Taxonomy '${input.name}' already exists in locale '${locale}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tconst id = ulid();\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_taxonomy_defs\")\n\t\t\t.values({\n\t\t\t\tid,\n\t\t\t\tname: input.name,\n\t\t\t\tlabel: input.label,\n\t\t\t\tlabel_singular: input.labelSingular ?? null,\n\t\t\t\thierarchical: input.hierarchical ? 1 : 0,\n\t\t\t\tcollections: JSON.stringify(collections),\n\t\t\t\t...(locale !== undefined ? { locale } : {}),\n\t\t\t\ttranslation_group: translationGroup ?? id,\n\t\t\t})\n\t\t\t.execute();\n\n\t\t// A new def changes which taxonomies exist — drop the isolate-wide\n\t\t// defs/names caches so this isolate reflects it immediately.\n\t\tinvalidateTaxonomyDefsCache();\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirstOrThrow();\n\t\treturn { success: true, data: { taxonomy: rowToDef(row) } };\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message.includes(\"UNIQUE constraint failed\")) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"CONFLICT\", message: `Taxonomy '${input.name}' already exists` },\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TAXONOMY_CREATE_ERROR\", message: \"Failed to create taxonomy\" },\n\t\t};\n\t}\n}\n\n/**\n * List every locale translation of a taxonomy def (by id or translation_group).\n */\nexport async function handleTaxonomyDefTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TaxonomyDefTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Taxonomy not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"_emdash_taxonomy_defs\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tname: r.name,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TAXONOMY_TRANSLATIONS_ERROR\",\n\t\t\t\tmessage: \"Failed to list taxonomy translations\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Term handlers\n// ---------------------------------------------------------------------------\n\n/**\n * List all terms for a taxonomy (returns tree for hierarchical taxonomies)\n */\nexport async function handleTermList(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\toptions: { locale?: string; includeCounts?: boolean } = {},\n): Promise<ApiResult<TermListResponse>> {\n\ttry {\n\t\t// Definitions are per-locale but terms aren't bound to the def's locale —\n\t\t// just ensure the taxonomy exists somewhere.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst terms = await repo.findByName(taxonomyName, { locale });\n\n\t\t// Counts match what visitors see on the public site: published (or\n\t\t// scheduled-and-due) entries that aren't soft-deleted, scoped to the\n\t\t// taxonomy's declared collections — one query for the whole list.\n\t\t// content_taxonomies.taxonomy_id stores the translation_group, so we\n\t\t// look up by group and map back to each term's id.\n\t\tconst includeCounts = options.includeCounts ?? true;\n\t\tconst countsByGroup = includeCounts\n\t\t\t? await fetchVisibleTermCounts(db, taxonomyName, defCollections(lookup.def))\n\t\t\t: undefined;\n\n\t\tconst termData: TermWithCount[] = terms.map((term) => ({\n\t\t\tid: term.id,\n\t\t\tname: term.name,\n\t\t\tslug: term.slug,\n\t\t\tlabel: term.label,\n\t\t\tparentId: term.parentId,\n\t\t\tdescription: typeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\tchildren: [],\n\t\t\t...(countsByGroup && { count: countsByGroup.get(term.translationGroup ?? term.id) ?? 0 }),\n\t\t\tlocale: term.locale,\n\t\t\ttranslationGroup: term.translationGroup,\n\t\t}));\n\n\t\tconst isHierarchical = lookup.def.hierarchical === 1;\n\t\tconst result = isHierarchical ? buildTree(termData) : termData;\n\t\treturn { success: true, data: { terms: result } };\n\t} catch (error) {\n\t\tconsole.error(\"[taxonomies] term list failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_LIST_ERROR\", message: \"Failed to list terms\" },\n\t\t};\n\t}\n}\n\n/**\n * Set the manual order of one sibling group.\n *\n * `ids` names the terms to move, in the desired order; each is a row id or a\n * translation_group and resolves to the latter, because a position belongs to a\n * term rather than to one of its locales. Reordering never reparents — moving a\n * term under a different parent is a term update.\n *\n * The group is `(taxonomy, parentId)` and has no locale: `parentId` is the\n * parent's translation_group (a row id is accepted and resolved), and `null`\n * selects the top level — which for a flat taxonomy is every term.\n *\n * `ids` may be a *subset* of the group, and the listed terms are permuted\n * within the positions they already occupy. A locale only renders the terms\n * translated into it, so a caller often cannot name every member; a member left\n * out keeps its place, which is also what makes a stale list harmless.\n */\nexport async function handleTermReorder(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tinput: { parentId?: string | null; ids: string[] },\n): Promise<ApiResult<TermReorderResponse>> {\n\ttry {\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\n\t\tlet parentId = input.parentId ?? null;\n\t\tif (parentId !== null) {\n\t\t\t// Children store the parent's translation_group, so a caller passing a\n\t\t\t// row id still addresses the right group. A parent whose anchor row is\n\t\t\t// gone keeps the value as given (see TaxonomyRepository.resolveParentRef).\n\t\t\tconst parent = await repo.findById(parentId);\n\t\t\tif (parent) parentId = parent.translationGroup ?? parent.id;\n\t\t}\n\n\t\t// Every locale's rows: membership is locale-agnostic, and a term the\n\t\t// caller can't see still holds its slot.\n\t\t// The order carries into how ties are resolved, so it must be stable\n\t\t// across calls; with locales interleaved a tie falls to whichever\n\t\t// locale's label sorts first, not to the order the caller rendered.\n\t\tconst members = await repo.findByName(taxonomyName, { parentId });\n\t\tconst siblings: SiblingPosition[] = [];\n\t\tconst seen = new Set<string>();\n\t\tconst resolve = new Map<string, string>();\n\t\tfor (const term of members) {\n\t\t\tconst group = term.translationGroup ?? term.id;\n\t\t\tif (!seen.has(group)) {\n\t\t\t\tseen.add(group);\n\t\t\t\tsiblings.push({ group, position: term.sortOrder });\n\t\t\t}\n\t\t\t// Both spellings resolve to the group: a row id, and the group itself for\n\t\t\t// a caller that already holds one — including when its anchor row is gone\n\t\t\t// and no member's id matches it.\n\t\t\tresolve.set(group, group);\n\t\t\tresolve.set(term.id, group);\n\t\t}\n\n\t\tconst groups: string[] = [];\n\t\tfor (const id of input.ids) {\n\t\t\tconst group = resolve.get(id);\n\t\t\tif (!group) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"REORDER_MISMATCH\",\n\t\t\t\t\t\tmessage: `Term \"${id}\" is not in the sibling group being reordered`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (groups.includes(group)) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"REORDER_MISMATCH\",\n\t\t\t\t\t\tmessage: `Term \"${id}\" is listed more than once`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tgroups.push(group);\n\t\t}\n\n\t\tawait repo.reorder(groups, siblings);\n\t\tinvalidateTermCache();\n\n\t\treturn { success: true, data: { reordered: true } };\n\t} catch (error) {\n\t\tconsole.error(\"[taxonomies] term reorder failed:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_REORDER_ERROR\", message: \"Failed to reorder terms\" },\n\t\t};\n\t}\n}\n\n/**\n * Validate a parent term reference for create/update.\n *\n * Returns `null` on success or a structured error message that callers\n * wrap in their own ApiResult.\n *\n * - `parentId === undefined` -> no-op (no parent change requested).\n * - `parentId === null` -> caller intends to detach; no-op here.\n * - parent must exist (FK exists -> term row not soft-deleted).\n * - parent must live in the same taxonomy.\n * - reject a parent in the term's own translation_group (self-parent),\n * including the create path: a translation inherits its source's group, so\n * `selfGroup` carries that prospective group when `termId` is absent.\n * - on update, walk up the parent chain to detect cycles.\n */\nasync function validateParentTerm(\n\trepo: TaxonomyRepository,\n\ttaxonomyName: string,\n\ttermId: string | undefined,\n\tparentId: string | null | undefined,\n\tselfGroup?: string | null,\n): Promise<{ code: \"VALIDATION_ERROR\"; message: string } | null> {\n\tif (parentId === undefined || parentId === null) return null;\n\n\tconst parent = await repo.findById(parentId);\n\tif (!parent) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' not found`,\n\t\t};\n\t}\n\tif (parent.name !== taxonomyName) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: `Parent term '${parentId}' belongs to taxonomy '${parent.name}', not '${taxonomyName}'`,\n\t\t};\n\t}\n\n\t// Parentage keys off translation_group (what `parent_id` persists), so the\n\t// self-parent and cycle checks compare groups, not row ids — picking a\n\t// sibling translation of the term as its parent is still self-parenting.\n\tconst parentGroup = parent.translationGroup ?? parent.id;\n\tlet termGroup: string | null = selfGroup ?? null;\n\tif (termId !== undefined) {\n\t\tconst term = await repo.findById(termId);\n\t\ttermGroup = term ? (term.translationGroup ?? term.id) : termId;\n\t}\n\tif (termGroup !== null && parentGroup === termGroup) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"A term cannot be its own parent\",\n\t\t};\n\t}\n\n\t// Walk up the parent chain. Two checks fold into one walk:\n\t// - Cycle detection (only on update — a non-existent term-being-\n\t// created can't be its own ancestor): if the walk revisits termId\n\t// the proposed parent makes the term a descendant of itself.\n\t// - Depth bound: refuse to extend a chain past MAX_DEPTH ancestors.\n\t// Runs on both create and update so a malicious or buggy caller\n\t// can't grow the tree without limit.\n\t//\n\t// The depth-exceeded error fires only when we hit the limit AND there\n\t// was still chain to walk — a legitimate chain of exactly MAX_DEPTH\n\t// ancestors exits with `cursor === null` and is accepted.\n\t// `parent_id` stores a translation_group, which always equals the anchor\n\t// row's id, so findById(cursor) still resolves each ancestor.\n\tconst MAX_DEPTH = 100;\n\tlet cursor: string | null = parent.parentId;\n\tlet steps = 0;\n\twhile (cursor !== null && steps < MAX_DEPTH) {\n\t\tif (termGroup !== null && cursor === termGroup) {\n\t\t\treturn {\n\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\tmessage: \"Cycle detected: cannot make a descendant the parent\",\n\t\t\t};\n\t\t}\n\t\tconst next = await repo.findById(cursor);\n\t\tif (!next) break;\n\t\tcursor = next.parentId;\n\t\tsteps++;\n\t}\n\tif (cursor !== null && steps >= MAX_DEPTH) {\n\t\treturn {\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tmessage: \"Parent chain exceeds maximum depth\",\n\t\t};\n\t}\n\n\treturn null;\n}\n\n/**\n * Create a new term in a taxonomy\n */\nexport async function handleTermCreate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\tinput: {\n\t\tslug: string;\n\t\tlabel: string;\n\t\tparentId?: string | null;\n\t\tdescription?: string;\n\t\tlocale?: string;\n\t\ttranslationOf?: string;\n\t},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst locale = input.locale ? resolveConfiguredLocale(input.locale) : undefined;\n\t\t// Taxonomy definitions are per-locale, but terms can exist in any locale\n\t\t// regardless of whether the def has been translated there. Look up the\n\t\t// def across all locales — we only care that it *exists*.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tif (!lookup.success) return lookup;\n\n\t\tconst repo = new TaxonomyRepository(db);\n\n\t\t// Coerce empty-string parentId to undefined (treat as \"no parent\").\n\t\tconst parentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Conflict check is scoped to locale (per-locale slugs are unique).\n\t\tconst existing = await repo.findBySlug(taxonomyName, input.slug, locale);\n\t\tif (existing) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\tmessage: locale\n\t\t\t\t\t\t? `Term '${input.slug}' already exists in '${taxonomyName}' (${locale})`\n\t\t\t\t\t\t: `Term with slug '${input.slug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// No locale re-pointing needed: `repo.create` persists the parent's\n\t\t// translation_group in `parent_id`, so a child stays nested under the\n\t\t// parent in every locale automatically — including parents translated\n\t\t// after the child was created.\n\n\t\t// A translation inherits its source's translation_group; pass that\n\t\t// prospective group so validateParentTerm can reject a parent in the same\n\t\t// group (cross-locale self-parent) even though the term doesn't exist yet.\n\t\tlet selfGroup: string | null = null;\n\t\tif (input.translationOf) {\n\t\t\tconst source = await repo.findById(input.translationOf);\n\t\t\tselfGroup = source ? (source.translationGroup ?? source.id) : null;\n\t\t}\n\n\t\t// Validate parentId: must exist AND belong to the same taxonomy.\n\t\t// (Cycle check is N/A on create — the term doesn't exist yet.)\n\t\tconst parentError = await validateParentTerm(\n\t\t\trepo,\n\t\t\ttaxonomyName,\n\t\t\tundefined,\n\t\t\tparentId,\n\t\t\tselfGroup,\n\t\t);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst term = await repo.create({\n\t\t\tname: taxonomyName,\n\t\t\tslug: input.slug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: parentId ?? undefined,\n\t\t\tdata: input.description ? { description: input.description } : undefined,\n\t\t\tlocale,\n\t\t\ttranslationOf: input.translationOf,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_CREATE_ERROR\", message: \"Failed to create term\" },\n\t\t};\n\t}\n}\n\n/**\n * Get a single term by slug\n */\nexport async function handleTermGet(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermGetResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Count matches public visibility (published or scheduled-and-due, not\n\t\t// soft-deleted) scoped to the def's declared collections. The def lookup\n\t\t// is lenient: a term whose def is missing still resolves, with count 0.\n\t\tconst lookup = await requireTaxonomyDef(db, taxonomyName);\n\t\tconst counts = await fetchVisibleTermCounts(\n\t\t\tdb,\n\t\t\ttaxonomyName,\n\t\t\tlookup.success ? defCollections(lookup.def) : [],\n\t\t);\n\t\tconst count = counts.get(term.translationGroup ?? term.id) ?? 0;\n\t\t// Children share this term's translation_group as their parent_id; scope\n\t\t// to the term's own locale so the response stays within one locale's tree.\n\t\tconst children = await repo.findChildren(term.id, term.locale);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: term.id,\n\t\t\t\t\tname: term.name,\n\t\t\t\t\tslug: term.slug,\n\t\t\t\t\tlabel: term.label,\n\t\t\t\t\tparentId: term.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof term.data?.description === \"string\" ? term.data.description : undefined,\n\t\t\t\t\tcount,\n\t\t\t\t\tchildren: children.map((c) => ({ id: c.id, slug: c.slug, label: c.label })),\n\t\t\t\t\tlocale: term.locale,\n\t\t\t\t\ttranslationGroup: term.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_GET_ERROR\", message: \"Failed to get term\" },\n\t\t};\n\t}\n}\n\n/** List every translation of a term (by id or translation_group). */\nexport async function handleTermTranslations(\n\tdb: Kysely<Database>,\n\tidOrGroup: string,\n): Promise<ApiResult<TermTranslationsResponse>> {\n\ttry {\n\t\tconst anchor = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where((eb) => eb.or([eb(\"id\", \"=\", idOrGroup), eb(\"translation_group\", \"=\", idOrGroup)]))\n\t\t\t.executeTakeFirst();\n\t\tif (!anchor) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"NOT_FOUND\", message: \"Term not found\" },\n\t\t\t};\n\t\t}\n\t\tconst group = anchor.translation_group ?? anchor.id;\n\t\tconst rows = await db\n\t\t\t.selectFrom(\"taxonomies\")\n\t\t\t.selectAll()\n\t\t\t.where(\"translation_group\", \"=\", group)\n\t\t\t.orderBy(\"locale\", \"asc\")\n\t\t\t.execute();\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\ttranslationGroup: group,\n\t\t\t\ttranslations: rows.map((r) => ({\n\t\t\t\t\tid: r.id,\n\t\t\t\t\tslug: r.slug,\n\t\t\t\t\tlabel: r.label,\n\t\t\t\t\tlocale: r.locale,\n\t\t\t\t})),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_TRANSLATIONS_ERROR\", message: \"Failed to list term translations\" },\n\t\t};\n\t}\n}\n\n/**\n * Update a term\n */\nexport async function handleTermUpdate(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\tinput: { slug?: string; label?: string; parentId?: string | null; description?: string },\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<TermResponse>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Coerce empty-string slug/parentId to undefined (treat as \"no change\").\n\t\t// `null` parentId is a valid request meaning \"detach from parent\".\n\t\tconst newSlug = input.slug === \"\" || input.slug === undefined ? undefined : input.slug;\n\t\tconst newParentId =\n\t\t\tinput.parentId === \"\" || input.parentId === undefined ? undefined : input.parentId;\n\n\t\t// Check if new slug conflicts (per-locale uniqueness).\n\t\tif (newSlug !== undefined && newSlug !== termSlug) {\n\t\t\tconst existing = await repo.findBySlug(taxonomyName, newSlug, locale);\n\t\t\tif (existing && existing.id !== term.id) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"CONFLICT\",\n\t\t\t\t\t\tmessage: `Term with slug '${newSlug}' already exists in taxonomy '${taxonomyName}'`,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Validate parentId: existence, same-taxonomy, no self-parent, no cycle.\n\t\tconst parentError = await validateParentTerm(repo, taxonomyName, term.id, newParentId);\n\t\tif (parentError) {\n\t\t\treturn { success: false, error: parentError };\n\t\t}\n\n\t\tconst updated = await repo.update(term.id, {\n\t\t\tslug: newSlug,\n\t\t\tlabel: input.label,\n\t\t\tparentId: newParentId,\n\t\t\tdata: input.description !== undefined ? { description: input.description } : undefined,\n\t\t});\n\n\t\tinvalidateTermCache();\n\n\t\tif (!updated) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tterm: {\n\t\t\t\t\tid: updated.id,\n\t\t\t\t\tname: updated.name,\n\t\t\t\t\tslug: updated.slug,\n\t\t\t\t\tlabel: updated.label,\n\t\t\t\t\tparentId: updated.parentId,\n\t\t\t\t\tdescription:\n\t\t\t\t\t\ttypeof updated.data?.description === \"string\" ? updated.data.description : undefined,\n\t\t\t\t\tlocale: updated.locale,\n\t\t\t\t\ttranslationGroup: updated.translationGroup,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: { code: \"TERM_UPDATE_ERROR\", message: \"Failed to update term\" },\n\t\t};\n\t}\n}\n\n/**\n * Delete a term\n */\nexport async function handleTermDelete(\n\tdb: Kysely<Database>,\n\ttaxonomyName: string,\n\ttermSlug: string,\n\toptions: { locale?: string } = {},\n): Promise<ApiResult<{ deleted: true }>> {\n\ttry {\n\t\tconst repo = new TaxonomyRepository(db);\n\t\tconst locale = options.locale ? resolveConfiguredLocale(options.locale) : undefined;\n\t\tconst term = await repo.findBySlug(taxonomyName, termSlug, locale);\n\n\t\tif (!term) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"NOT_FOUND\",\n\t\t\t\t\tmessage: `Term '${termSlug}' not found in taxonomy '${taxonomyName}'`,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Block deletion if the term's group still parents any child in any\n\t\t// locale — children store this group in parent_id, so removing the term\n\t\t// would orphan them (or null their parent_id via the self-FK).\n\t\tconst children = await repo.findChildren(term.id);\n\t\tif (children.length > 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\t\t\tmessage: \"Cannot delete term with children. Delete children first.\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst deleted = await repo.delete(term.id);\n\t\tif (!deleted) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"TERM_DELETE_ERROR\", message: \"Failed to delete term\" },\n\t\t\t};\n\t\t}\n\n\t\tinvalidateTermCache();\n\t\treturn { success: true, data: { deleted: true } };\n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