emdash 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1267) hide show
  1. package/dist/action-token-AgOs1UWD.mjs +26 -0
  2. package/dist/action-token-AgOs1UWD.mjs.map +1 -0
  3. package/dist/activation-xomsCMJg.mjs +387 -0
  4. package/dist/activation-xomsCMJg.mjs.map +1 -0
  5. package/dist/adapters-DM1oyHIN.d.mts +173 -0
  6. package/dist/adapters-DM1oyHIN.d.mts.map +1 -0
  7. package/dist/allowed-origins-CFtudhyw.mjs +116 -0
  8. package/dist/allowed-origins-CFtudhyw.mjs.map +1 -0
  9. package/dist/api/route-utils.d.mts +4 -4
  10. package/dist/api/route-utils.mjs +48 -47
  11. package/dist/api/route-utils.mjs.map +1 -1
  12. package/dist/api/schemas/index.d.mts +2 -2
  13. package/dist/api/schemas/index.mjs +10 -10
  14. package/dist/api-CltsXhiX.mjs +4980 -0
  15. package/dist/api-CltsXhiX.mjs.map +1 -0
  16. package/dist/api-tokens-P3mAaQgr.mjs +166 -0
  17. package/dist/api-tokens-P3mAaQgr.mjs.map +1 -0
  18. package/dist/apply-Q7uvzBWW.mjs +1680 -0
  19. package/dist/apply-Q7uvzBWW.mjs.map +1 -0
  20. package/dist/approvals-DycwI6lZ.mjs +460 -0
  21. package/dist/approvals-DycwI6lZ.mjs.map +1 -0
  22. package/dist/artifact-fetch-CWxyELVI.mjs +659 -0
  23. package/dist/artifact-fetch-CWxyELVI.mjs.map +1 -0
  24. package/dist/artifacts-UzWbysb8.mjs +307 -0
  25. package/dist/artifacts-UzWbysb8.mjs.map +1 -0
  26. package/dist/astro/index.d.mts +14 -14
  27. package/dist/astro/index.d.mts.map +1 -1
  28. package/dist/astro/index.mjs +38 -12
  29. package/dist/astro/index.mjs.map +1 -1
  30. package/dist/astro/middleware/auth.d.mts +12 -12
  31. package/dist/astro/middleware/auth.mjs +12 -11
  32. package/dist/astro/middleware/auth.mjs.map +1 -1
  33. package/dist/astro/middleware/media-usage-write-fence.mjs +6 -6
  34. package/dist/astro/middleware/redirect.d.mts.map +1 -1
  35. package/dist/astro/middleware/redirect.mjs +9 -22
  36. package/dist/astro/middleware/redirect.mjs.map +1 -1
  37. package/dist/astro/middleware/request-context.d.mts.map +1 -1
  38. package/dist/astro/middleware/request-context.mjs +33 -21
  39. package/dist/astro/middleware/request-context.mjs.map +1 -1
  40. package/dist/astro/middleware/setup.mjs +1 -1
  41. package/dist/astro/middleware.d.mts +12 -12
  42. package/dist/astro/middleware.d.mts.map +1 -1
  43. package/dist/astro/middleware.mjs +203 -120
  44. package/dist/astro/middleware.mjs.map +1 -1
  45. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +15 -15
  46. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +15 -15
  47. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +7 -7
  48. package/dist/astro/routes/api/admin/api-tokens/index.mjs +8 -8
  49. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +7 -7
  50. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +17 -17
  51. package/dist/astro/routes/api/admin/byline-fields/index.mjs +17 -17
  52. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +17 -17
  53. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +22 -22
  54. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +22 -23
  55. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs.map +1 -1
  56. package/dist/astro/routes/api/admin/bylines/index.mjs +23 -23
  57. package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
  58. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +19 -19
  59. package/dist/astro/routes/api/admin/comments/_id_.mjs +8 -8
  60. package/dist/astro/routes/api/admin/comments/bulk.mjs +18 -18
  61. package/dist/astro/routes/api/admin/comments/counts.mjs +8 -8
  62. package/dist/astro/routes/api/admin/comments/index.mjs +18 -18
  63. package/dist/astro/routes/api/admin/core-update.mjs +8 -8
  64. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +7 -7
  65. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +6 -6
  66. package/dist/astro/routes/api/admin/media-usage/activation.mjs +21 -21
  67. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +22 -22
  68. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +22 -22
  69. package/dist/astro/routes/api/admin/media-usage/progress.mjs +23 -23
  70. package/dist/astro/routes/api/admin/media-usage/repair.mjs +29 -29
  71. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +22 -22
  72. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +22 -22
  73. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +7 -7
  74. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +7 -7
  75. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +9 -9
  76. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +9 -9
  77. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +72 -71
  78. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  79. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +8 -8
  80. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +70 -69
  81. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +71 -70
  83. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +81 -80
  85. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/plugins/index.mjs +71 -70
  87. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +8 -8
  89. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +70 -69
  90. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  91. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +80 -79
  92. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  93. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +70 -69
  94. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  95. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +71 -70
  96. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  97. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +82 -81
  98. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  99. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +10 -10
  100. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +73 -72
  101. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  102. package/dist/astro/routes/api/admin/plugins/registry/publisher-handle.mjs +8 -8
  103. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +71 -70
  104. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -1
  105. package/dist/astro/routes/api/admin/plugins/updates.mjs +70 -69
  106. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  107. package/dist/astro/routes/api/admin/scheduled-policy-rejections/_collection_/_id_.mjs +6 -6
  108. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +70 -69
  109. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  110. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +8 -8
  111. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +70 -69
  112. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  113. package/dist/astro/routes/api/admin/transfer/_...path_.mjs +5 -5
  114. package/dist/astro/routes/api/admin/transfer/approvals/_id_/approve.mjs +39 -39
  115. package/dist/astro/routes/api/admin/transfer/approvals/_id_/deny.mjs +39 -39
  116. package/dist/astro/routes/api/admin/transfer/approvals/index.mjs +41 -41
  117. package/dist/astro/routes/api/admin/transfer/capabilities.mjs +41 -41
  118. package/dist/astro/routes/api/admin/transfer/exports/_id_/advance.mjs +41 -41
  119. package/dist/astro/routes/api/admin/transfer/exports/_id_/archive.mjs +42 -42
  120. package/dist/astro/routes/api/admin/transfer/exports/_id_/files/_...path_.mjs +42 -42
  121. package/dist/astro/routes/api/admin/transfer/exports/_id_/index.mjs +41 -41
  122. package/dist/astro/routes/api/admin/transfer/exports/_id_/manifest.mjs +42 -42
  123. package/dist/astro/routes/api/admin/transfer/exports/index.mjs +43 -43
  124. package/dist/astro/routes/api/admin/transfer/imports/_id_/abandon.mjs +41 -41
  125. package/dist/astro/routes/api/admin/transfer/imports/_id_/advance.mjs +41 -41
  126. package/dist/astro/routes/api/admin/transfer/imports/_id_/analyze.mjs +43 -43
  127. package/dist/astro/routes/api/admin/transfer/imports/_id_/cancel.mjs +41 -41
  128. package/dist/astro/routes/api/admin/transfer/imports/_id_/execute.mjs +43 -43
  129. package/dist/astro/routes/api/admin/transfer/imports/_id_/files/_...path_.mjs +41 -41
  130. package/dist/astro/routes/api/admin/transfer/imports/_id_/index.mjs +41 -41
  131. package/dist/astro/routes/api/admin/transfer/imports/_id_/missing.mjs +43 -43
  132. package/dist/astro/routes/api/admin/transfer/imports/_id_/plan.mjs +41 -41
  133. package/dist/astro/routes/api/admin/transfer/imports/_id_/receipt.mjs +41 -41
  134. package/dist/astro/routes/api/admin/transfer/imports/index.mjs +43 -43
  135. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +5 -5
  136. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +5 -5
  137. package/dist/astro/routes/api/admin/users/_id_/index.mjs +15 -15
  138. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +7 -7
  139. package/dist/astro/routes/api/admin/users/index.mjs +15 -15
  140. package/dist/astro/routes/api/auth/dev-bypass.mjs +7 -7
  141. package/dist/astro/routes/api/auth/invite/accept.mjs +5 -5
  142. package/dist/astro/routes/api/auth/invite/complete.mjs +20 -20
  143. package/dist/astro/routes/api/auth/invite/index.mjs +17 -17
  144. package/dist/astro/routes/api/auth/invite/register-options.mjs +18 -18
  145. package/dist/astro/routes/api/auth/logout.mjs +6 -6
  146. package/dist/astro/routes/api/auth/magic-link/send.mjs +19 -19
  147. package/dist/astro/routes/api/auth/magic-link/verify.mjs +16 -16
  148. package/dist/astro/routes/api/auth/me.mjs +16 -16
  149. package/dist/astro/routes/api/auth/mode.mjs +6 -6
  150. package/dist/astro/routes/api/auth/oauth/_provider_/callback.d.mts.map +1 -1
  151. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +36 -13
  152. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs.map +1 -1
  153. package/dist/astro/routes/api/auth/oauth/_provider_.d.mts.map +1 -1
  154. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +20 -5
  155. package/dist/astro/routes/api/auth/oauth/_provider_.mjs.map +1 -1
  156. package/dist/astro/routes/api/auth/passkey/_id_.mjs +15 -15
  157. package/dist/astro/routes/api/auth/passkey/index.mjs +5 -5
  158. package/dist/astro/routes/api/auth/passkey/options.mjs +20 -20
  159. package/dist/astro/routes/api/auth/passkey/register/options.mjs +18 -18
  160. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +19 -19
  161. package/dist/astro/routes/api/auth/passkey/verify.mjs +20 -20
  162. package/dist/astro/routes/api/auth/signup/complete.mjs +20 -20
  163. package/dist/astro/routes/api/auth/signup/request.mjs +18 -18
  164. package/dist/astro/routes/api/auth/signup/verify.mjs +5 -5
  165. package/dist/astro/routes/api/calendar.d.mts +8 -0
  166. package/dist/astro/routes/api/calendar.d.mts.map +1 -0
  167. package/dist/astro/routes/api/calendar.mjs +204 -0
  168. package/dist/astro/routes/api/calendar.mjs.map +1 -0
  169. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +14 -14
  170. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +20 -20
  171. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +6 -6
  172. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +17 -17
  173. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +6 -6
  174. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs +17 -17
  175. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +6 -6
  176. package/dist/astro/routes/api/content/_collection_/_id_/plugin-extensions/_pluginId_/_kind_/_extensionId_.mjs +12 -12
  177. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +31 -31
  178. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +17 -17
  179. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +34 -34
  180. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +34 -34
  181. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +6 -6
  182. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +6 -6
  183. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +17 -17
  184. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +24 -24
  185. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +6 -6
  186. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +17 -17
  187. package/dist/astro/routes/api/content/_collection_/_id_.mjs +17 -17
  188. package/dist/astro/routes/api/content/_collection_/authors.mjs +6 -6
  189. package/dist/astro/routes/api/content/_collection_/index.mjs +16 -16
  190. package/dist/astro/routes/api/content/_collection_/trash.mjs +16 -16
  191. package/dist/astro/routes/api/dashboard.mjs +11 -11
  192. package/dist/astro/routes/api/dev/emails.mjs +6 -6
  193. package/dist/astro/routes/api/health.mjs +7 -7
  194. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  195. package/dist/astro/routes/api/import/probe.mjs +24 -24
  196. package/dist/astro/routes/api/import/wordpress/analyze.mjs +6 -6
  197. package/dist/astro/routes/api/import/wordpress/execute.d.mts +13 -13
  198. package/dist/astro/routes/api/import/wordpress/execute.mjs +23 -23
  199. package/dist/astro/routes/api/import/wordpress/media.d.mts +12 -12
  200. package/dist/astro/routes/api/import/wordpress/media.mjs +20 -20
  201. package/dist/astro/routes/api/import/wordpress/prepare.mjs +18 -18
  202. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +13 -13
  203. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +27 -27
  204. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  205. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +24 -24
  206. package/dist/astro/routes/api/import/wordpress-plugin/callback.mjs +1 -1
  207. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +13 -13
  208. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +32 -32
  209. package/dist/astro/routes/api/manifest.mjs +7 -7
  210. package/dist/astro/routes/api/mcp.mjs +94 -94
  211. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  212. package/dist/astro/routes/api/media/_id_/confirm.mjs +19 -19
  213. package/dist/astro/routes/api/media/_id_/replace.mjs +17 -17
  214. package/dist/astro/routes/api/media/_id_/upload.mjs +10 -10
  215. package/dist/astro/routes/api/media/_id_/usage.mjs +31 -31
  216. package/dist/astro/routes/api/media/_id_.mjs +29 -29
  217. package/dist/astro/routes/api/media/asset/_id_/_filename_.mjs +7 -7
  218. package/dist/astro/routes/api/media/file/_...key_.mjs +10 -10
  219. package/dist/astro/routes/api/media/folders/_id_.mjs +17 -17
  220. package/dist/astro/routes/api/media/folders/index.mjs +17 -17
  221. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +6 -6
  222. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +6 -6
  223. package/dist/astro/routes/api/media/providers/index.mjs +6 -6
  224. package/dist/astro/routes/api/media/upload-url.mjs +23 -23
  225. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  226. package/dist/astro/routes/api/media.mjs +37 -36
  227. package/dist/astro/routes/api/media.mjs.map +1 -1
  228. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +18 -18
  229. package/dist/astro/routes/api/menus/_name_/items.mjs +18 -18
  230. package/dist/astro/routes/api/menus/_name_/reorder.mjs +18 -18
  231. package/dist/astro/routes/api/menus/_name_/translations.mjs +18 -18
  232. package/dist/astro/routes/api/menus/_name_.mjs +18 -18
  233. package/dist/astro/routes/api/menus/index.mjs +18 -18
  234. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  235. package/dist/astro/routes/api/oauth/device/authorize.mjs +9 -9
  236. package/dist/astro/routes/api/oauth/device/code.mjs +12 -12
  237. package/dist/astro/routes/api/oauth/device/token.mjs +11 -11
  238. package/dist/astro/routes/api/oauth/register.mjs +8 -8
  239. package/dist/astro/routes/api/oauth/token/refresh.mjs +9 -9
  240. package/dist/astro/routes/api/oauth/token/revoke.mjs +9 -9
  241. package/dist/astro/routes/api/oauth/token.mjs +9 -9
  242. package/dist/astro/routes/api/openapi.json.mjs +21 -21
  243. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +12 -12
  244. package/dist/astro/routes/api/redirects/404s/index.mjs +20 -19
  245. package/dist/astro/routes/api/redirects/404s/index.mjs.map +1 -1
  246. package/dist/astro/routes/api/redirects/404s/summary.mjs +20 -19
  247. package/dist/astro/routes/api/redirects/404s/summary.mjs.map +1 -1
  248. package/dist/astro/routes/api/redirects/_id_.mjs +20 -19
  249. package/dist/astro/routes/api/redirects/_id_.mjs.map +1 -1
  250. package/dist/astro/routes/api/redirects/index.mjs +20 -19
  251. package/dist/astro/routes/api/redirects/index.mjs.map +1 -1
  252. package/dist/astro/routes/api/relations/_id_/index.mjs +34 -34
  253. package/dist/astro/routes/api/relations/index.mjs +34 -34
  254. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +6 -6
  255. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +17 -17
  256. package/dist/astro/routes/api/schema/block-types/_slug_/index.mjs +70 -69
  257. package/dist/astro/routes/api/schema/block-types/_slug_/index.mjs.map +1 -1
  258. package/dist/astro/routes/api/schema/block-types/_slug_/versions/_version_/activate.mjs +70 -69
  259. package/dist/astro/routes/api/schema/block-types/_slug_/versions/_version_/activate.mjs.map +1 -1
  260. package/dist/astro/routes/api/schema/block-types/index.mjs +70 -69
  261. package/dist/astro/routes/api/schema/block-types/index.mjs.map +1 -1
  262. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +70 -69
  263. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  264. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +70 -69
  265. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  266. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +70 -69
  267. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  268. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +70 -69
  269. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  270. package/dist/astro/routes/api/schema/collections/index.mjs +70 -69
  271. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  272. package/dist/astro/routes/api/schema/collections/reorder.mjs +70 -69
  273. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  274. package/dist/astro/routes/api/schema/index.mjs +16 -16
  275. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +70 -69
  276. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  277. package/dist/astro/routes/api/schema/orphans/index.mjs +70 -69
  278. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  279. package/dist/astro/routes/api/search/enable.mjs +19 -19
  280. package/dist/astro/routes/api/search/index.mjs +18 -18
  281. package/dist/astro/routes/api/search/rebuild.mjs +19 -19
  282. package/dist/astro/routes/api/search/stats.mjs +9 -9
  283. package/dist/astro/routes/api/search/suggest.mjs +18 -18
  284. package/dist/astro/routes/api/sections/_slug_.mjs +18 -18
  285. package/dist/astro/routes/api/sections/index.mjs +18 -18
  286. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +8 -8
  287. package/dist/astro/routes/api/settings/backups/archives/index.mjs +8 -8
  288. package/dist/astro/routes/api/settings/backups/export.mjs +8 -8
  289. package/dist/astro/routes/api/settings/backups/index.mjs +9 -9
  290. package/dist/astro/routes/api/settings/email.mjs +7 -7
  291. package/dist/astro/routes/api/settings.mjs +22 -22
  292. package/dist/astro/routes/api/setup/admin-verify.mjs +21 -21
  293. package/dist/astro/routes/api/setup/admin.mjs +19 -19
  294. package/dist/astro/routes/api/setup/dev-bypass.mjs +42 -42
  295. package/dist/astro/routes/api/setup/dev-reset.mjs +5 -5
  296. package/dist/astro/routes/api/setup/index.mjs +54 -49
  297. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  298. package/dist/astro/routes/api/setup/status.mjs +7 -7
  299. package/dist/astro/routes/api/snapshot.mjs +10 -10
  300. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +22 -22
  301. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +22 -22
  302. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +22 -22
  303. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +22 -22
  304. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +21 -21
  305. package/dist/astro/routes/api/taxonomies/_name_.mjs +22 -22
  306. package/dist/astro/routes/api/taxonomies/bulk-tag.mjs +35 -35
  307. package/dist/astro/routes/api/taxonomies/index.mjs +22 -22
  308. package/dist/astro/routes/api/themes/preview.mjs +8 -8
  309. package/dist/astro/routes/api/typegen.mjs +7 -7
  310. package/dist/astro/routes/api/visual-editing/action-token.mjs +8 -8
  311. package/dist/astro/routes/api/visual-editing/content/_collection_/_id_/publish.mjs +20 -20
  312. package/dist/astro/routes/api/visual-editing/toolbar-labels.mjs +5 -5
  313. package/dist/astro/routes/api/well-known/auth.mjs +1 -1
  314. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  315. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  316. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +17 -17
  317. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +19 -19
  318. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +19 -19
  319. package/dist/astro/routes/api/widget-areas/_name_.mjs +9 -9
  320. package/dist/astro/routes/api/widget-areas/index.mjs +19 -19
  321. package/dist/astro/routes/api/widget-components.mjs +6 -6
  322. package/dist/astro/routes/robots.txt.mjs +7 -7
  323. package/dist/astro/routes/sitemap-_collection_.xml.mjs +9 -9
  324. package/dist/astro/routes/sitemap.xml.mjs +8 -8
  325. package/dist/astro/types.d.mts +17 -17
  326. package/dist/audit-CCH3MA4Y.mjs +127 -0
  327. package/dist/audit-CCH3MA4Y.mjs.map +1 -0
  328. package/dist/auth/providers/github.d.mts +1 -1
  329. package/dist/auth/providers/google.d.mts +1 -1
  330. package/dist/auth/providers/microsoft.d.mts +27 -0
  331. package/dist/auth/providers/microsoft.d.mts.map +1 -0
  332. package/dist/auth/providers/microsoft.mjs +20 -0
  333. package/dist/auth/providers/microsoft.mjs.map +1 -0
  334. package/dist/authoritative-records-dSvXCfzb.mjs +5172 -0
  335. package/dist/authoritative-records-dSvXCfzb.mjs.map +1 -0
  336. package/dist/authorize-DeWfk--K.mjs +49 -0
  337. package/dist/authorize-DeWfk--K.mjs.map +1 -0
  338. package/dist/backup-CFnbdTSJ.mjs +246 -0
  339. package/dist/backup-CFnbdTSJ.mjs.map +1 -0
  340. package/dist/base64-BQBZwXCx.mjs +63 -0
  341. package/dist/base64-BQBZwXCx.mjs.map +1 -0
  342. package/dist/block-types-C0YFSfR7.mjs +132 -0
  343. package/dist/block-types-C0YFSfR7.mjs.map +1 -0
  344. package/dist/block-values-H4E0XwE8.mjs +175 -0
  345. package/dist/block-values-H4E0XwE8.mjs.map +1 -0
  346. package/dist/byline-BhVslYLz.mjs +909 -0
  347. package/dist/byline-BhVslYLz.mjs.map +1 -0
  348. package/dist/byline-fields-DHJs0Mja.mjs +280 -0
  349. package/dist/byline-fields-DHJs0Mja.mjs.map +1 -0
  350. package/dist/byline-fields-xdxE9kxZ.mjs +123 -0
  351. package/dist/byline-fields-xdxE9kxZ.mjs.map +1 -0
  352. package/dist/bylines-B_nN9liM.mjs +234 -0
  353. package/dist/bylines-B_nN9liM.mjs.map +1 -0
  354. package/dist/bylines-C71YACkL.mjs +150 -0
  355. package/dist/bylines-C71YACkL.mjs.map +1 -0
  356. package/dist/cache-aTYCL9nK.mjs +133 -0
  357. package/dist/cache-aTYCL9nK.mjs.map +1 -0
  358. package/dist/canonical-Y1dpjCnp.mjs +174 -0
  359. package/dist/canonical-Y1dpjCnp.mjs.map +1 -0
  360. package/dist/capture-triggers-C9JKoIdT.mjs +362 -0
  361. package/dist/capture-triggers-C9JKoIdT.mjs.map +1 -0
  362. package/dist/challenge-store-CxZxPqaw.mjs +51 -0
  363. package/dist/challenge-store-CxZxPqaw.mjs.map +1 -0
  364. package/dist/checksum-DtH6m5uk.mjs +162 -0
  365. package/dist/checksum-DtH6m5uk.mjs.map +1 -0
  366. package/dist/chrome-tags-BIKBMZYO.mjs +24 -0
  367. package/dist/chrome-tags-BIKBMZYO.mjs.map +1 -0
  368. package/dist/chunks-zlGB5IQP.mjs +25 -0
  369. package/dist/chunks-zlGB5IQP.mjs.map +1 -0
  370. package/dist/cli/index.mjs +47 -47
  371. package/dist/client/cf-access.d.mts +1 -1
  372. package/dist/client/index.d.mts +121 -121
  373. package/dist/client/index.mjs +2 -2
  374. package/dist/collection-slugs-cache-B2Gs9Jwx.mjs +85 -0
  375. package/dist/collection-slugs-cache-B2Gs9Jwx.mjs.map +1 -0
  376. package/dist/comment-Bu08Wvr3.mjs +313 -0
  377. package/dist/comment-Bu08Wvr3.mjs.map +1 -0
  378. package/dist/comment-reaction-B8SfT-yM.mjs +85 -0
  379. package/dist/comment-reaction-B8SfT-yM.mjs.map +1 -0
  380. package/dist/comments-BRtp992B.mjs +99 -0
  381. package/dist/comments-BRtp992B.mjs.map +1 -0
  382. package/dist/comments-DVUYqdyC.mjs +195 -0
  383. package/dist/comments-DVUYqdyC.mjs.map +1 -0
  384. package/dist/components-CQY-Sgm-.mjs +108 -0
  385. package/dist/components-CQY-Sgm-.mjs.map +1 -0
  386. package/dist/config-B-uePMLj.d.mts +39 -0
  387. package/dist/config-B-uePMLj.d.mts.map +1 -0
  388. package/dist/config-B6BDSsz2.d.mts +6712 -0
  389. package/dist/config-B6BDSsz2.d.mts.map +1 -0
  390. package/dist/config-BsJHiQxC.mjs +228 -0
  391. package/dist/config-BsJHiQxC.mjs.map +1 -0
  392. package/dist/connection-B9pIasFd.mjs +36 -0
  393. package/dist/connection-B9pIasFd.mjs.map +1 -0
  394. package/dist/content-Dji9vEiW.mjs +2063 -0
  395. package/dist/content-Dji9vEiW.mjs.map +1 -0
  396. package/dist/content-list-query-DiNwyKtd.d.mts +26 -0
  397. package/dist/content-list-query-DiNwyKtd.d.mts.map +1 -0
  398. package/dist/content-repair-B7wnbzhN.mjs +442 -0
  399. package/dist/content-repair-B7wnbzhN.mjs.map +1 -0
  400. package/dist/context-Ctcxc8Ia.mjs +2026 -0
  401. package/dist/context-Ctcxc8Ia.mjs.map +1 -0
  402. package/dist/credits-Bu7dlobo.mjs +110 -0
  403. package/dist/credits-Bu7dlobo.mjs.map +1 -0
  404. package/dist/cron-xe5XKqA-.mjs +306 -0
  405. package/dist/cron-xe5XKqA-.mjs.map +1 -0
  406. package/dist/dashboard-B5hVHOtf.mjs +151 -0
  407. package/dist/dashboard-B5hVHOtf.mjs.map +1 -0
  408. package/dist/db/index.d.mts +3 -3
  409. package/dist/db/index.mjs +1 -1
  410. package/dist/db/index.mjs.map +1 -1
  411. package/dist/db/libsql-migrations.d.mts +1 -1
  412. package/dist/db/libsql-migrations.mjs +5 -5
  413. package/dist/db/libsql.d.mts +1 -1
  414. package/dist/db/postgres-migrations.d.mts +1 -1
  415. package/dist/db/postgres-migrations.mjs +4 -4
  416. package/dist/db/postgres.d.mts +1 -1
  417. package/dist/db/sqlite-migrations.d.mts +1 -1
  418. package/dist/db/sqlite-migrations.mjs +4 -4
  419. package/dist/db/sqlite.d.mts +1 -1
  420. package/dist/db/sqlite.mjs +1 -1
  421. package/dist/default-DaoYyFRS.mjs +81 -0
  422. package/dist/default-DaoYyFRS.mjs.map +1 -0
  423. package/dist/deferred-tasks-BYcDx2o_.d.mts +9 -0
  424. package/dist/deferred-tasks-BYcDx2o_.d.mts.map +1 -0
  425. package/dist/dev-typegen-Dtl8AfS6.mjs +29 -0
  426. package/dist/dev-typegen-Dtl8AfS6.mjs.map +1 -0
  427. package/dist/device-flow-Ma5P5d2e.mjs +521 -0
  428. package/dist/device-flow-Ma5P5d2e.mjs.map +1 -0
  429. package/dist/digest-xIpR3o64.mjs +194 -0
  430. package/dist/digest-xIpR3o64.mjs.map +1 -0
  431. package/dist/direct-executor-DMWwCey3.mjs +104 -0
  432. package/dist/direct-executor-DMWwCey3.mjs.map +1 -0
  433. package/dist/email-console-DmqVF5J_.mjs +50 -0
  434. package/dist/email-console-DmqVF5J_.mjs.map +1 -0
  435. package/dist/email-locale-Cc5YSXfJ.mjs +25 -0
  436. package/dist/email-locale-Cc5YSXfJ.mjs.map +1 -0
  437. package/dist/emdash-runtime-BlybX9Ui.mjs +4249 -0
  438. package/dist/emdash-runtime-BlybX9Ui.mjs.map +1 -0
  439. package/dist/enrich-Duu4sV3a.mjs +194 -0
  440. package/dist/enrich-Duu4sV3a.mjs.map +1 -0
  441. package/dist/entry-lock-De1L8qUQ.mjs +163 -0
  442. package/dist/entry-lock-De1L8qUQ.mjs.map +1 -0
  443. package/dist/entry-lock-esmMbgI9.d.mts +4551 -0
  444. package/dist/entry-lock-esmMbgI9.d.mts.map +1 -0
  445. package/dist/entry-lock-sxz2PGAT.mjs +1197 -0
  446. package/dist/entry-lock-sxz2PGAT.mjs.map +1 -0
  447. package/dist/env-types-BkjCtN13.mjs +38 -0
  448. package/dist/env-types-BkjCtN13.mjs.map +1 -0
  449. package/dist/error-B0rgPgsQ.mjs +90 -0
  450. package/dist/error-B0rgPgsQ.mjs.map +1 -0
  451. package/dist/errors-CuHQRiBW.mjs +120 -0
  452. package/dist/errors-CuHQRiBW.mjs.map +1 -0
  453. package/dist/errors-DTE6C3K_.mjs +470 -0
  454. package/dist/errors-DTE6C3K_.mjs.map +1 -0
  455. package/dist/escape-nJW7dR0s.mjs +9 -0
  456. package/dist/escape-nJW7dR0s.mjs.map +1 -0
  457. package/dist/fence-CGw57S4v.mjs +162 -0
  458. package/dist/fence-CGw57S4v.mjs.map +1 -0
  459. package/dist/field-defs-cache-Bw8w499w.mjs +77 -0
  460. package/dist/field-defs-cache-Bw8w499w.mjs.map +1 -0
  461. package/dist/field-map-hn-D-SyH.mjs +83 -0
  462. package/dist/field-map-hn-D-SyH.mjs.map +1 -0
  463. package/dist/fts-manager-DacCYIe4.mjs +443 -0
  464. package/dist/fts-manager-DacCYIe4.mjs.map +1 -0
  465. package/dist/gc-BBplHrv6.mjs +75 -0
  466. package/dist/gc-BBplHrv6.mjs.map +1 -0
  467. package/dist/hash-C4DFoJ7Z.mjs +37 -0
  468. package/dist/hash-C4DFoJ7Z.mjs.map +1 -0
  469. package/dist/hook-result-DSRRxu_-.d.mts +31 -0
  470. package/dist/hook-result-DSRRxu_-.d.mts.map +1 -0
  471. package/dist/hreflang-CKPunvU0.mjs +105 -0
  472. package/dist/hreflang-CKPunvU0.mjs.map +1 -0
  473. package/dist/hreflang-egumj6WF.d.mts +50 -0
  474. package/dist/hreflang-egumj6WF.d.mts.map +1 -0
  475. package/dist/http-route-dispatch-DjNFZcJ2.mjs +339 -0
  476. package/dist/http-route-dispatch-DjNFZcJ2.mjs.map +1 -0
  477. package/dist/identity-Dfrx2_Bc.mjs +35 -0
  478. package/dist/identity-Dfrx2_Bc.mjs.map +1 -0
  479. package/dist/import-ROBvhbNc.mjs +2021 -0
  480. package/dist/import-ROBvhbNc.mjs.map +1 -0
  481. package/dist/index-B4sIdCAT.d.mts +623 -0
  482. package/dist/index-B4sIdCAT.d.mts.map +1 -0
  483. package/dist/index.d.mts +24 -24
  484. package/dist/index.mjs +98 -97
  485. package/dist/init-lock-BGmew3r1.mjs +56 -0
  486. package/dist/init-lock-BGmew3r1.mjs.map +1 -0
  487. package/dist/install-finalization-CPM7Gged.mjs +58 -0
  488. package/dist/install-finalization-CPM7Gged.mjs.map +1 -0
  489. package/dist/keys-DxqxcAD4.mjs +61 -0
  490. package/dist/keys-DxqxcAD4.mjs.map +1 -0
  491. package/dist/kinds-BQl5gN6e.mjs +974 -0
  492. package/dist/kinds-BQl5gN6e.mjs.map +1 -0
  493. package/dist/lifecycle-DGQI7itS.mjs +25 -0
  494. package/dist/lifecycle-DGQI7itS.mjs.map +1 -0
  495. package/dist/load-DMxRl4VK.mjs +28 -0
  496. package/dist/load-DMxRl4VK.mjs.map +1 -0
  497. package/dist/loader-1DMiOq5s.mjs +1303 -0
  498. package/dist/loader-1DMiOq5s.mjs.map +1 -0
  499. package/dist/loops-Dn1i16FP.mjs +205 -0
  500. package/dist/loops-Dn1i16FP.mjs.map +1 -0
  501. package/dist/manifest-builder-CTw4FmZk.mjs +189 -0
  502. package/dist/manifest-builder-CTw4FmZk.mjs.map +1 -0
  503. package/dist/manifest-schema-gy37bD_D.mjs +496 -0
  504. package/dist/manifest-schema-gy37bD_D.mjs.map +1 -0
  505. package/dist/marketplace-tHWSsCUo.mjs +257 -0
  506. package/dist/marketplace-tHWSsCUo.mjs.map +1 -0
  507. package/dist/media/index.d.mts +1 -1
  508. package/dist/media/index.mjs +1 -1
  509. package/dist/media/local-runtime.d.mts +14 -14
  510. package/dist/media/local-runtime.mjs +7 -7
  511. package/dist/media-Bw-Q65ve.mjs +294 -0
  512. package/dist/media-Bw-Q65ve.mjs.map +1 -0
  513. package/dist/media-BzUDu7nl.mjs +373 -0
  514. package/dist/media-BzUDu7nl.mjs.map +1 -0
  515. package/dist/media-aahnKHze.mjs +408 -0
  516. package/dist/media-aahnKHze.mjs.map +1 -0
  517. package/dist/media-allowlist-RMrjo8TU.mjs +45 -0
  518. package/dist/media-allowlist-RMrjo8TU.mjs.map +1 -0
  519. package/dist/media-folders-kabR1oJf.mjs +210 -0
  520. package/dist/media-folders-kabR1oJf.mjs.map +1 -0
  521. package/dist/media-url-DloW2xrP.mjs +43 -0
  522. package/dist/media-url-DloW2xrP.mjs.map +1 -0
  523. package/dist/media-usage-CHHpV7ee.mjs +282 -0
  524. package/dist/media-usage-CHHpV7ee.mjs.map +1 -0
  525. package/dist/media-usage-activation-BinYqC_r.mjs +78 -0
  526. package/dist/media-usage-activation-BinYqC_r.mjs.map +1 -0
  527. package/dist/media-usage-work-C734aq6s.mjs +1015 -0
  528. package/dist/media-usage-work-C734aq6s.mjs.map +1 -0
  529. package/dist/media-usage-work-lxvV0-UO.mjs +151 -0
  530. package/dist/media-usage-work-lxvV0-UO.mjs.map +1 -0
  531. package/dist/menus-6RHNq4ZK.mjs +753 -0
  532. package/dist/menus-6RHNq4ZK.mjs.map +1 -0
  533. package/dist/menus-AuCTaO9W.mjs +3704 -0
  534. package/dist/menus-AuCTaO9W.mjs.map +1 -0
  535. package/dist/menus-BQKqf0Up.mjs +92 -0
  536. package/dist/menus-BQKqf0Up.mjs.map +1 -0
  537. package/dist/migrations/index.d.mts +1 -1
  538. package/dist/migrations/index.mjs +3 -3
  539. package/dist/mime-B5M9R53H.mjs +81 -0
  540. package/dist/mime-B5M9R53H.mjs.map +1 -0
  541. package/dist/mode-nh0ppSX5.mjs +23 -0
  542. package/dist/mode-nh0ppSX5.mjs.map +1 -0
  543. package/dist/node-sqlite-compat-CDOEcc97.mjs +63 -0
  544. package/dist/node-sqlite-compat-CDOEcc97.mjs.map +1 -0
  545. package/dist/oauth-authorization-BtYQ80uU.mjs +274 -0
  546. package/dist/oauth-authorization-BtYQ80uU.mjs.map +1 -0
  547. package/dist/oauth-clients-C1S4NQHh.mjs +266 -0
  548. package/dist/oauth-clients-C1S4NQHh.mjs.map +1 -0
  549. package/dist/oauth-state-store-CpGi2FZH.mjs +50 -0
  550. package/dist/oauth-state-store-CpGi2FZH.mjs.map +1 -0
  551. package/dist/oauth-user-lookup-BNp1aFAr.mjs +26 -0
  552. package/dist/oauth-user-lookup-BNp1aFAr.mjs.map +1 -0
  553. package/dist/object-cache/memory.d.mts +1 -1
  554. package/dist/options-B41aLm1I.d.mts +81 -0
  555. package/dist/options-B41aLm1I.d.mts.map +1 -0
  556. package/dist/ownership-DoeAIuTg.mjs +12 -0
  557. package/dist/ownership-DoeAIuTg.mjs.map +1 -0
  558. package/dist/page/index.d.mts +2 -2
  559. package/dist/page/index.mjs +6 -6
  560. package/dist/parse-CmFDTGzp.mjs +81 -0
  561. package/dist/parse-CmFDTGzp.mjs.map +1 -0
  562. package/dist/parse-QVS0t5oR.d.mts +172 -0
  563. package/dist/parse-QVS0t5oR.d.mts.map +1 -0
  564. package/dist/passkey-config-C-MxsV22.mjs +46 -0
  565. package/dist/passkey-config-C-MxsV22.mjs.map +1 -0
  566. package/dist/paths-kr8hAMMI.mjs +77 -0
  567. package/dist/paths-kr8hAMMI.mjs.map +1 -0
  568. package/dist/placeholder-Dn7MMdWr.d.mts +306 -0
  569. package/dist/placeholder-Dn7MMdWr.d.mts.map +1 -0
  570. package/dist/plan-CuQOeU9g.mjs +135 -0
  571. package/dist/plan-CuQOeU9g.mjs.map +1 -0
  572. package/dist/plugin-test-runtime.d.mts +14 -14
  573. package/dist/plugin-test-runtime.mjs +110 -109
  574. package/dist/plugin-types.d.mts +2 -2
  575. package/dist/plugin-utils.d.mts +12 -12
  576. package/dist/plugins/adapt-sandbox-entry.d.mts +12 -12
  577. package/dist/plugins/adapt-sandbox-entry.mjs +3 -3
  578. package/dist/plugins/host.d.mts +5 -5
  579. package/dist/plugins/host.mjs +44 -43
  580. package/dist/plugins-CGb-G98c.mjs +261 -0
  581. package/dist/plugins-CGb-G98c.mjs.map +1 -0
  582. package/dist/policy-C5wrDXYV.mjs +45 -0
  583. package/dist/policy-C5wrDXYV.mjs.map +1 -0
  584. package/dist/portable-text-BnRuiR1-.mjs +307 -0
  585. package/dist/portable-text-BnRuiR1-.mjs.map +1 -0
  586. package/dist/preview-xWNSR1Li.mjs +107 -0
  587. package/dist/preview-xWNSR1Li.mjs.map +1 -0
  588. package/dist/protocol-ClxN-m1e.d.mts +61 -0
  589. package/dist/protocol-ClxN-m1e.d.mts.map +1 -0
  590. package/dist/public-submission-CkmT2SKv.mjs +250 -0
  591. package/dist/public-submission-CkmT2SKv.mjs.map +1 -0
  592. package/dist/public-url-B5a0QAh6.mjs +101 -0
  593. package/dist/public-url-B5a0QAh6.mjs.map +1 -0
  594. package/dist/query-DHqFiqqH.mjs +41 -0
  595. package/dist/query-DHqFiqqH.mjs.map +1 -0
  596. package/dist/query-DT85BehD.mjs +1125 -0
  597. package/dist/query-DT85BehD.mjs.map +1 -0
  598. package/dist/rate-limit-iMvcu3eu.mjs +120 -0
  599. package/dist/rate-limit-iMvcu3eu.mjs.map +1 -0
  600. package/dist/receipt-Dpp1uaX9.mjs +43 -0
  601. package/dist/receipt-Dpp1uaX9.mjs.map +1 -0
  602. package/dist/redirect-BRoLiWQE.mjs +19 -0
  603. package/dist/redirect-BRoLiWQE.mjs.map +1 -0
  604. package/dist/redirect-xZNpBoGp.mjs +417 -0
  605. package/dist/redirect-xZNpBoGp.mjs.map +1 -0
  606. package/dist/redirects-D4EWeXAo.mjs +148 -0
  607. package/dist/redirects-D4EWeXAo.mjs.map +1 -0
  608. package/dist/redirects-DCKqwiWp.mjs +446 -0
  609. package/dist/redirects-DCKqwiWp.mjs.map +1 -0
  610. package/dist/registry/testing.mjs +3 -3
  611. package/dist/registry-DaXmUsD4.mjs +8369 -0
  612. package/dist/registry-DaXmUsD4.mjs.map +1 -0
  613. package/dist/relations-JvBP8nGP.mjs +776 -0
  614. package/dist/relations-JvBP8nGP.mjs.map +1 -0
  615. package/dist/request-context.d.mts +2 -2
  616. package/dist/request-context.mjs.map +1 -1
  617. package/dist/request-meta-B6blULFY.mjs +141 -0
  618. package/dist/request-meta-B6blULFY.mjs.map +1 -0
  619. package/dist/resolve-DAhHi5tn.mjs +100 -0
  620. package/dist/resolve-DAhHi5tn.mjs.map +1 -0
  621. package/dist/revision-BWEH2qQB.mjs +368 -0
  622. package/dist/revision-BWEH2qQB.mjs.map +1 -0
  623. package/dist/route-wire-DK600v4u.mjs +197 -0
  624. package/dist/route-wire-DK600v4u.mjs.map +1 -0
  625. package/dist/routes-BeZyaCzv.mjs +272 -0
  626. package/dist/routes-BeZyaCzv.mjs.map +1 -0
  627. package/dist/runner-CskI4Hmq.mjs +6372 -0
  628. package/dist/runner-CskI4Hmq.mjs.map +1 -0
  629. package/dist/runner-J3Cj6DGk.d.mts +68 -0
  630. package/dist/runner-J3Cj6DGk.d.mts.map +1 -0
  631. package/dist/runtime.d.mts +13 -13
  632. package/dist/runtime.mjs +3 -3
  633. package/dist/schema/project-env-types.mjs +37 -37
  634. package/dist/schema-CK0ihqMR.mjs +815 -0
  635. package/dist/schema-CK0ihqMR.mjs.map +1 -0
  636. package/dist/schema-VtaZSrC-.mjs +13 -0
  637. package/dist/schema-VtaZSrC-.mjs.map +1 -0
  638. package/dist/scopes-BRnGlL9t.mjs +34 -0
  639. package/dist/scopes-BRnGlL9t.mjs.map +1 -0
  640. package/dist/search-D6-XK1Sn.mjs +448 -0
  641. package/dist/search-D6-XK1Sn.mjs.map +1 -0
  642. package/dist/secrets-Cc_O3Kp-.mjs +369 -0
  643. package/dist/secrets-Cc_O3Kp-.mjs.map +1 -0
  644. package/dist/sections-CBDCf7qR.mjs +346 -0
  645. package/dist/sections-CBDCf7qR.mjs.map +1 -0
  646. package/dist/seed/index.d.mts +2 -2
  647. package/dist/seed/index.mjs +35 -35
  648. package/dist/seo/index.d.mts +3 -3
  649. package/dist/seo/index.mjs +22 -22
  650. package/dist/seo-BdeEPDNW.mjs +133 -0
  651. package/dist/seo-BdeEPDNW.mjs.map +1 -0
  652. package/dist/seo-C61bnPuV.mjs +114 -0
  653. package/dist/seo-C61bnPuV.mjs.map +1 -0
  654. package/dist/service-BuRKLMxa.mjs +150 -0
  655. package/dist/service-BuRKLMxa.mjs.map +1 -0
  656. package/dist/session-user-CqkPtrPL.mjs +61 -0
  657. package/dist/session-user-CqkPtrPL.mjs.map +1 -0
  658. package/dist/settings-0u0lTthS.mjs +51 -0
  659. package/dist/settings-0u0lTthS.mjs.map +1 -0
  660. package/dist/settings-WHr45II1.mjs +61 -0
  661. package/dist/settings-WHr45II1.mjs.map +1 -0
  662. package/dist/settings-m5tIYnF0.mjs +443 -0
  663. package/dist/settings-m5tIYnF0.mjs.map +1 -0
  664. package/dist/setup-complete-B2_dhZZz.mjs +65 -0
  665. package/dist/setup-complete-B2_dhZZz.mjs.map +1 -0
  666. package/dist/setup-nonce-CJV9ftSK.mjs +25 -0
  667. package/dist/setup-nonce-CJV9ftSK.mjs.map +1 -0
  668. package/dist/single-flight-cache-D0EaGbN1.mjs +104 -0
  669. package/dist/single-flight-cache-D0EaGbN1.mjs.map +1 -0
  670. package/dist/site-settings-KJOqJW6W.mjs +50 -0
  671. package/dist/site-settings-KJOqJW6W.mjs.map +1 -0
  672. package/dist/site-url-Ceq_AUK0.mjs +16 -0
  673. package/dist/site-url-Ceq_AUK0.mjs.map +1 -0
  674. package/dist/snapshot-Dzsn3NZa.mjs +414 -0
  675. package/dist/snapshot-Dzsn3NZa.mjs.map +1 -0
  676. package/dist/ssrf-DsmvZB80.mjs +406 -0
  677. package/dist/ssrf-DsmvZB80.mjs.map +1 -0
  678. package/dist/stage-Csnh_yEd.mjs +662 -0
  679. package/dist/stage-Csnh_yEd.mjs.map +1 -0
  680. package/dist/staged-Q7pnEVvI.mjs +686 -0
  681. package/dist/staged-Q7pnEVvI.mjs.map +1 -0
  682. package/dist/state-kGdOMQRY.mjs +153 -0
  683. package/dist/state-kGdOMQRY.mjs.map +1 -0
  684. package/dist/status-D39Fpy8R.mjs +30 -0
  685. package/dist/status-D39Fpy8R.mjs.map +1 -0
  686. package/dist/storage/local.d.mts +1 -1
  687. package/dist/storage/local.mjs +2 -2
  688. package/dist/storage/s3.d.mts +1 -1
  689. package/dist/storage/s3.mjs +1 -1
  690. package/dist/storage-query-C7iy6eUb.d.mts +1615 -0
  691. package/dist/storage-query-C7iy6eUb.d.mts.map +1 -0
  692. package/dist/tar-BWiraSUY.mjs +449 -0
  693. package/dist/tar-BWiraSUY.mjs.map +1 -0
  694. package/dist/target-DOFs5oUC.mjs +27 -0
  695. package/dist/target-DOFs5oUC.mjs.map +1 -0
  696. package/dist/taxonomies-BS40Wxvi.mjs +939 -0
  697. package/dist/taxonomies-BS40Wxvi.mjs.map +1 -0
  698. package/dist/taxonomies-DAZU9VDd.mjs +697 -0
  699. package/dist/taxonomies-DAZU9VDd.mjs.map +1 -0
  700. package/dist/taxonomy-XzLE95Vx.mjs +525 -0
  701. package/dist/taxonomy-XzLE95Vx.mjs.map +1 -0
  702. package/dist/tokens-DSQan4p7.mjs +171 -0
  703. package/dist/tokens-DSQan4p7.mjs.map +1 -0
  704. package/dist/transfer-BcCVxDgf.mjs +166 -0
  705. package/dist/transfer-BcCVxDgf.mjs.map +1 -0
  706. package/dist/transfer-OMrancOt.mjs +8873 -0
  707. package/dist/transfer-OMrancOt.mjs.map +1 -0
  708. package/dist/transfer-download-Dc-ltjZY.mjs +33 -0
  709. package/dist/transfer-download-Dc-ltjZY.mjs.map +1 -0
  710. package/dist/transformations-Ddx7UtrY.mjs +196 -0
  711. package/dist/transformations-Ddx7UtrY.mjs.map +1 -0
  712. package/dist/transport-flR-Zmds.d.mts +42 -0
  713. package/dist/transport-flR-Zmds.d.mts.map +1 -0
  714. package/dist/transport-umzEbgYO.mjs +136 -0
  715. package/dist/transport-umzEbgYO.mjs.map +1 -0
  716. package/dist/trusted-proxy-BqfQFs6a.mjs +51 -0
  717. package/dist/trusted-proxy-BqfQFs6a.mjs.map +1 -0
  718. package/dist/turnstile-Do60baId.mjs +58 -0
  719. package/dist/turnstile-Do60baId.mjs.map +1 -0
  720. package/dist/types-BT1p3uyb.d.mts +1735 -0
  721. package/dist/types-BT1p3uyb.d.mts.map +1 -0
  722. package/dist/types-BYaPWs_F.d.mts +198 -0
  723. package/dist/types-BYaPWs_F.d.mts.map +1 -0
  724. package/dist/types-C-Xp0CcN.mjs +103 -0
  725. package/dist/types-C-Xp0CcN.mjs.map +1 -0
  726. package/dist/types-CLTQ9b_r.d.mts +374 -0
  727. package/dist/types-CLTQ9b_r.d.mts.map +1 -0
  728. package/dist/types-CPkQw2T2.d.mts +85 -0
  729. package/dist/types-CPkQw2T2.d.mts.map +1 -0
  730. package/dist/types-CQLvuXoZ.d.mts +198 -0
  731. package/dist/types-CQLvuXoZ.d.mts.map +1 -0
  732. package/dist/types-CV5xszpF.d.mts +363 -0
  733. package/dist/types-CV5xszpF.d.mts.map +1 -0
  734. package/dist/types-CdEMurNh.mjs +77 -0
  735. package/dist/types-CdEMurNh.mjs.map +1 -0
  736. package/dist/types-Cj0_yZkn.mjs +18 -0
  737. package/dist/types-Cj0_yZkn.mjs.map +1 -0
  738. package/dist/types-CxwtnuSS.mjs +37 -0
  739. package/dist/types-CxwtnuSS.mjs.map +1 -0
  740. package/dist/types-DGw8KMX_.mjs +16 -0
  741. package/dist/types-DGw8KMX_.mjs.map +1 -0
  742. package/dist/types-DOfVMPoo.d.mts +125 -0
  743. package/dist/types-DOfVMPoo.d.mts.map +1 -0
  744. package/dist/types-LtS0SM4F.d.mts +287 -0
  745. package/dist/types-LtS0SM4F.d.mts.map +1 -0
  746. package/dist/types-ifgOkcBa.d.mts +916 -0
  747. package/dist/types-ifgOkcBa.d.mts.map +1 -0
  748. package/dist/update-check-DOc2aBIU.mjs +161 -0
  749. package/dist/update-check-DOc2aBIU.mjs.map +1 -0
  750. package/dist/upload-attempts-nzdc3cay.mjs +32 -0
  751. package/dist/upload-attempts-nzdc3cay.mjs.map +1 -0
  752. package/dist/url-pattern-hVbqpXs6.mjs +41 -0
  753. package/dist/url-pattern-hVbqpXs6.mjs.map +1 -0
  754. package/dist/user-Dnp53zTq.mjs +171 -0
  755. package/dist/user-Dnp53zTq.mjs.map +1 -0
  756. package/dist/utils-CoV-PYhg.mjs +439 -0
  757. package/dist/utils-CoV-PYhg.mjs.map +1 -0
  758. package/dist/validate-CfQ9_YlD.d.mts +468 -0
  759. package/dist/validate-CfQ9_YlD.d.mts.map +1 -0
  760. package/dist/validate-DBX3DKtL.mjs +516 -0
  761. package/dist/validate-DBX3DKtL.mjs.map +1 -0
  762. package/dist/validation-BJMiDhB1.mjs +219 -0
  763. package/dist/validation-BJMiDhB1.mjs.map +1 -0
  764. package/dist/version-BaT8yKIT.mjs +7 -0
  765. package/dist/version-BaT8yKIT.mjs.map +1 -0
  766. package/dist/version-BwEGkqkx.mjs +9 -0
  767. package/dist/version-BwEGkqkx.mjs.map +1 -0
  768. package/dist/virtual-modules-B6vJW15k.mjs +516 -0
  769. package/dist/virtual-modules-B6vJW15k.mjs.map +1 -0
  770. package/dist/widgets-BkxBAgZ_.mjs +126 -0
  771. package/dist/widgets-BkxBAgZ_.mjs.map +1 -0
  772. package/dist/wxr-taxonomies-D7gAJyOF.mjs +453 -0
  773. package/dist/wxr-taxonomies-D7gAJyOF.mjs.map +1 -0
  774. package/dist/wxr-taxonomies-DM5J9AsT.d.mts +34 -0
  775. package/dist/wxr-taxonomies-DM5J9AsT.d.mts.map +1 -0
  776. package/dist/zod-generator-BQilAboC.mjs +424 -0
  777. package/dist/zod-generator-BQilAboC.mjs.map +1 -0
  778. package/package.json +11 -5
  779. package/src/api/errors.ts +3 -0
  780. package/src/api/handlers/bylines.ts +24 -3
  781. package/src/api/handlers/calendar.ts +246 -0
  782. package/src/api/handlers/content.ts +12 -5
  783. package/src/api/handlers/media-allowlist.ts +1 -0
  784. package/src/api/handlers/media-upload.ts +13 -10
  785. package/src/api/handlers/plugins.ts +21 -29
  786. package/src/api/handlers/redirects.ts +6 -6
  787. package/src/api/schemas/bylines.ts +3 -1
  788. package/src/api/schemas/content.ts +16 -0
  789. package/src/astro/integration/index.ts +18 -1
  790. package/src/astro/integration/routes.ts +5 -0
  791. package/src/astro/integration/vite-config.ts +11 -0
  792. package/src/astro/middleware/csp.ts +1 -0
  793. package/src/astro/middleware/redirect.ts +20 -9
  794. package/src/astro/middleware/request-context.ts +54 -27
  795. package/src/astro/middleware.ts +97 -12
  796. package/src/astro/prefetch.ts +10 -3
  797. package/src/astro/routes/api/admin/bylines/[id]/translations.ts +0 -5
  798. package/src/astro/routes/api/admin/bylines/index.ts +1 -1
  799. package/src/astro/routes/api/admin/plugins/[id]/index.ts +1 -0
  800. package/src/astro/routes/api/auth/oauth/[provider]/callback.ts +56 -4
  801. package/src/astro/routes/api/auth/oauth/[provider].ts +37 -4
  802. package/src/astro/routes/api/calendar.ts +35 -0
  803. package/src/astro/routes/api/media/upload-url.ts +8 -4
  804. package/src/astro/routes/api/media.ts +9 -5
  805. package/src/astro/routes/api/setup/index.ts +14 -2
  806. package/src/auth/providers/microsoft-admin.tsx +31 -0
  807. package/src/auth/providers/microsoft.ts +47 -0
  808. package/src/comments/turnstile.ts +6 -1
  809. package/src/components/HtmlBlock.astro +17 -6
  810. package/src/components/HtmlBlockFrame.astro +63 -0
  811. package/src/components/Iframe.astro +141 -0
  812. package/src/components/InlinePortableTextEditor.tsx +8 -7
  813. package/src/components/WebMcpSearch.astro +80 -0
  814. package/src/components/index.ts +5 -2
  815. package/src/components/webmcp-search.ts +142 -0
  816. package/src/config/secrets.ts +27 -15
  817. package/src/content/converters/portable-text-identity.ts +1 -0
  818. package/src/content/converters/portable-text-to-prosemirror.ts +36 -2
  819. package/src/content/converters/prosemirror-to-portable-text.ts +28 -2
  820. package/src/content/converters/types.ts +24 -0
  821. package/src/database/content-datetime.ts +11 -4
  822. package/src/database/migrations/090_redirect_enable_loop_guard.ts +70 -0
  823. package/src/database/migrations/091_redirect_artifacts.ts +141 -0
  824. package/src/database/migrations/runner.ts +4 -0
  825. package/src/database/repositories/content.ts +81 -26
  826. package/src/database/repositories/redirect.ts +6 -1
  827. package/src/database/request-scoped.ts +34 -0
  828. package/src/database/types.ts +23 -0
  829. package/src/db/adapters.ts +2 -0
  830. package/src/emdash-runtime.ts +28 -3
  831. package/src/import/menus.ts +3 -0
  832. package/src/index.ts +1 -0
  833. package/src/loader.ts +226 -55
  834. package/src/mcp/server.ts +12 -4
  835. package/src/media/mime.ts +21 -0
  836. package/src/menus/index.ts +30 -26
  837. package/src/plugins/hooks.ts +10 -0
  838. package/src/plugins/manager.ts +12 -2
  839. package/src/plugins/types.ts +16 -0
  840. package/src/query.ts +12 -29
  841. package/src/redirects/artifacts.ts +460 -0
  842. package/src/redirects/cache.ts +76 -41
  843. package/src/request-context.ts +1 -1
  844. package/src/seed/apply.ts +65 -57
  845. package/src/settings/index.ts +17 -12
  846. package/src/transfer/format/columns.ts +3 -0
  847. package/src/transfer/import/rebuild.ts +17 -2
  848. package/src/transfer/import/scaffold.ts +16 -9
  849. package/src/ui.ts +1 -0
  850. package/src/utils/sanitize.ts +14 -9
  851. package/src/virtual-modules.d.ts +3 -0
  852. package/dist/action-token-D2KE1Rqf.mjs +0 -26
  853. package/dist/action-token-D2KE1Rqf.mjs.map +0 -1
  854. package/dist/activation-DDuqAat2.mjs +0 -387
  855. package/dist/activation-DDuqAat2.mjs.map +0 -1
  856. package/dist/adapters-Ds-1Pmkm.d.mts +0 -171
  857. package/dist/adapters-Ds-1Pmkm.d.mts.map +0 -1
  858. package/dist/allowed-origins-D78QvbTO.mjs +0 -116
  859. package/dist/allowed-origins-D78QvbTO.mjs.map +0 -1
  860. package/dist/api-BBZlif0y.mjs +0 -4974
  861. package/dist/api-BBZlif0y.mjs.map +0 -1
  862. package/dist/api-tokens-BGbfWZVO.mjs +0 -166
  863. package/dist/api-tokens-BGbfWZVO.mjs.map +0 -1
  864. package/dist/apply-CDNV4JJ-.mjs +0 -1672
  865. package/dist/apply-CDNV4JJ-.mjs.map +0 -1
  866. package/dist/approvals-CVvJSEBF.mjs +0 -460
  867. package/dist/approvals-CVvJSEBF.mjs.map +0 -1
  868. package/dist/artifact-fetch-CGK0DQLj.mjs +0 -659
  869. package/dist/artifact-fetch-CGK0DQLj.mjs.map +0 -1
  870. package/dist/audit-BszbE_BP.mjs +0 -127
  871. package/dist/audit-BszbE_BP.mjs.map +0 -1
  872. package/dist/authoritative-records-ChM8dTeV.mjs +0 -5172
  873. package/dist/authoritative-records-ChM8dTeV.mjs.map +0 -1
  874. package/dist/authorize-CTGywswM.mjs +0 -49
  875. package/dist/authorize-CTGywswM.mjs.map +0 -1
  876. package/dist/backup-CDrPP8fI.mjs +0 -246
  877. package/dist/backup-CDrPP8fI.mjs.map +0 -1
  878. package/dist/base64-DvnNgP7e.mjs +0 -63
  879. package/dist/base64-DvnNgP7e.mjs.map +0 -1
  880. package/dist/block-types-nNEaPkvx.mjs +0 -132
  881. package/dist/block-types-nNEaPkvx.mjs.map +0 -1
  882. package/dist/block-values-Bho1nsZF.mjs +0 -175
  883. package/dist/block-values-Bho1nsZF.mjs.map +0 -1
  884. package/dist/byline-02tu_Uc-.mjs +0 -909
  885. package/dist/byline-02tu_Uc-.mjs.map +0 -1
  886. package/dist/byline-fields-BYbTptTU.mjs +0 -280
  887. package/dist/byline-fields-BYbTptTU.mjs.map +0 -1
  888. package/dist/byline-fields-BjQH-1z9.mjs +0 -123
  889. package/dist/byline-fields-BjQH-1z9.mjs.map +0 -1
  890. package/dist/bylines-VytjeHBI.mjs +0 -214
  891. package/dist/bylines-VytjeHBI.mjs.map +0 -1
  892. package/dist/bylines-gyWBWUUc.mjs +0 -150
  893. package/dist/bylines-gyWBWUUc.mjs.map +0 -1
  894. package/dist/cache-CPanL9IO.mjs +0 -114
  895. package/dist/cache-CPanL9IO.mjs.map +0 -1
  896. package/dist/canonical-CAecl1UQ.mjs +0 -174
  897. package/dist/canonical-CAecl1UQ.mjs.map +0 -1
  898. package/dist/capture-triggers-CdZfvHtF.mjs +0 -362
  899. package/dist/capture-triggers-CdZfvHtF.mjs.map +0 -1
  900. package/dist/challenge-store-VePApay4.mjs +0 -51
  901. package/dist/challenge-store-VePApay4.mjs.map +0 -1
  902. package/dist/checksum-BSIhEAYW.mjs +0 -162
  903. package/dist/checksum-BSIhEAYW.mjs.map +0 -1
  904. package/dist/chrome-tags-CKELm-bo.mjs +0 -24
  905. package/dist/chrome-tags-CKELm-bo.mjs.map +0 -1
  906. package/dist/chunks-DBmkKmBH.mjs +0 -25
  907. package/dist/chunks-DBmkKmBH.mjs.map +0 -1
  908. package/dist/collection-slugs-cache-BNRAPNiu.mjs +0 -85
  909. package/dist/collection-slugs-cache-BNRAPNiu.mjs.map +0 -1
  910. package/dist/comment-Cq1UYN8_.mjs +0 -313
  911. package/dist/comment-Cq1UYN8_.mjs.map +0 -1
  912. package/dist/comment-reaction-B5sZzSoA.mjs +0 -85
  913. package/dist/comment-reaction-B5sZzSoA.mjs.map +0 -1
  914. package/dist/comments-B3F-ETyh.mjs +0 -195
  915. package/dist/comments-B3F-ETyh.mjs.map +0 -1
  916. package/dist/comments-zrTgWBSg.mjs +0 -99
  917. package/dist/comments-zrTgWBSg.mjs.map +0 -1
  918. package/dist/components-Dbf4Eq16.mjs +0 -108
  919. package/dist/components-Dbf4Eq16.mjs.map +0 -1
  920. package/dist/config-BCM5sQP7.d.mts +0 -6688
  921. package/dist/config-BCM5sQP7.d.mts.map +0 -1
  922. package/dist/config-CXPcy2iY.mjs +0 -228
  923. package/dist/config-CXPcy2iY.mjs.map +0 -1
  924. package/dist/config-CZkZBuBK.d.mts +0 -39
  925. package/dist/config-CZkZBuBK.d.mts.map +0 -1
  926. package/dist/connection-C5GIciX9.mjs +0 -36
  927. package/dist/connection-C5GIciX9.mjs.map +0 -1
  928. package/dist/content-RzEXY3QX.mjs +0 -2020
  929. package/dist/content-RzEXY3QX.mjs.map +0 -1
  930. package/dist/content-list-query-B6P37Ug_.d.mts +0 -26
  931. package/dist/content-list-query-B6P37Ug_.d.mts.map +0 -1
  932. package/dist/content-repair-BDVsYXWK.mjs +0 -442
  933. package/dist/content-repair-BDVsYXWK.mjs.map +0 -1
  934. package/dist/context-BpTIzY5h.mjs +0 -2026
  935. package/dist/context-BpTIzY5h.mjs.map +0 -1
  936. package/dist/credits-JOE92Gr7.mjs +0 -110
  937. package/dist/credits-JOE92Gr7.mjs.map +0 -1
  938. package/dist/cron-ktyapbdB.mjs +0 -306
  939. package/dist/cron-ktyapbdB.mjs.map +0 -1
  940. package/dist/dashboard-BoV4pwPP.mjs +0 -151
  941. package/dist/dashboard-BoV4pwPP.mjs.map +0 -1
  942. package/dist/default-B7KnYwtQ.mjs +0 -81
  943. package/dist/default-B7KnYwtQ.mjs.map +0 -1
  944. package/dist/deferred-tasks-eaUIqXj8.d.mts +0 -9
  945. package/dist/deferred-tasks-eaUIqXj8.d.mts.map +0 -1
  946. package/dist/dev-typegen-8JlYYFno.mjs +0 -29
  947. package/dist/dev-typegen-8JlYYFno.mjs.map +0 -1
  948. package/dist/device-flow-BlV_z24g.mjs +0 -521
  949. package/dist/device-flow-BlV_z24g.mjs.map +0 -1
  950. package/dist/digest-DiYAoZpf.mjs +0 -194
  951. package/dist/digest-DiYAoZpf.mjs.map +0 -1
  952. package/dist/direct-executor-Db8xA3zg.mjs +0 -104
  953. package/dist/direct-executor-Db8xA3zg.mjs.map +0 -1
  954. package/dist/email-console-Dm78wSmg.mjs +0 -50
  955. package/dist/email-console-Dm78wSmg.mjs.map +0 -1
  956. package/dist/email-locale-B4X9LXe9.mjs +0 -25
  957. package/dist/email-locale-B4X9LXe9.mjs.map +0 -1
  958. package/dist/emdash-runtime-BakQ6io7.mjs +0 -4239
  959. package/dist/emdash-runtime-BakQ6io7.mjs.map +0 -1
  960. package/dist/enrich-BDdVNeDK.mjs +0 -194
  961. package/dist/enrich-BDdVNeDK.mjs.map +0 -1
  962. package/dist/entry-lock-DY8B-xcr.d.mts +0 -4544
  963. package/dist/entry-lock-DY8B-xcr.d.mts.map +0 -1
  964. package/dist/entry-lock-DrUAdTzf.mjs +0 -163
  965. package/dist/entry-lock-DrUAdTzf.mjs.map +0 -1
  966. package/dist/entry-lock-yIkBduqJ.mjs +0 -1180
  967. package/dist/entry-lock-yIkBduqJ.mjs.map +0 -1
  968. package/dist/env-types-DkHYR2pl.mjs +0 -38
  969. package/dist/env-types-DkHYR2pl.mjs.map +0 -1
  970. package/dist/error-DIYXAVk4.mjs +0 -90
  971. package/dist/error-DIYXAVk4.mjs.map +0 -1
  972. package/dist/errors-CNvATh_7.mjs +0 -469
  973. package/dist/errors-CNvATh_7.mjs.map +0 -1
  974. package/dist/errors-CjXd1LgH.mjs +0 -120
  975. package/dist/errors-CjXd1LgH.mjs.map +0 -1
  976. package/dist/escape-B1GM0yJU.mjs +0 -9
  977. package/dist/escape-B1GM0yJU.mjs.map +0 -1
  978. package/dist/fence-8MaKKWhp.mjs +0 -162
  979. package/dist/fence-8MaKKWhp.mjs.map +0 -1
  980. package/dist/field-defs-cache-DEkFYCDE.mjs +0 -77
  981. package/dist/field-defs-cache-DEkFYCDE.mjs.map +0 -1
  982. package/dist/field-map-D7ioN0r0.mjs +0 -83
  983. package/dist/field-map-D7ioN0r0.mjs.map +0 -1
  984. package/dist/fts-manager-DU03MxWu.mjs +0 -443
  985. package/dist/fts-manager-DU03MxWu.mjs.map +0 -1
  986. package/dist/gc-DMiE7ezk.mjs +0 -75
  987. package/dist/gc-DMiE7ezk.mjs.map +0 -1
  988. package/dist/hash-CY4QdeMJ.mjs +0 -37
  989. package/dist/hash-CY4QdeMJ.mjs.map +0 -1
  990. package/dist/hook-result-Cb67D3P3.d.mts +0 -31
  991. package/dist/hook-result-Cb67D3P3.d.mts.map +0 -1
  992. package/dist/hreflang-Bterc3b7.mjs +0 -105
  993. package/dist/hreflang-Bterc3b7.mjs.map +0 -1
  994. package/dist/hreflang-uIBOE5yg.d.mts +0 -50
  995. package/dist/hreflang-uIBOE5yg.d.mts.map +0 -1
  996. package/dist/http-route-dispatch-DubjTibD.mjs +0 -339
  997. package/dist/http-route-dispatch-DubjTibD.mjs.map +0 -1
  998. package/dist/identity-DJ-5AcdG.mjs +0 -35
  999. package/dist/identity-DJ-5AcdG.mjs.map +0 -1
  1000. package/dist/import-DEfuIgRz.mjs +0 -2020
  1001. package/dist/import-DEfuIgRz.mjs.map +0 -1
  1002. package/dist/index-xCy3j0f6.d.mts +0 -623
  1003. package/dist/index-xCy3j0f6.d.mts.map +0 -1
  1004. package/dist/init-lock-4eRRB4Le.mjs +0 -56
  1005. package/dist/init-lock-4eRRB4Le.mjs.map +0 -1
  1006. package/dist/install-finalization-DeGRbaVa.mjs +0 -58
  1007. package/dist/install-finalization-DeGRbaVa.mjs.map +0 -1
  1008. package/dist/keys-DWwMxdZh.mjs +0 -61
  1009. package/dist/keys-DWwMxdZh.mjs.map +0 -1
  1010. package/dist/kinds-D1A-00-F.mjs +0 -974
  1011. package/dist/kinds-D1A-00-F.mjs.map +0 -1
  1012. package/dist/lifecycle-BWtBGNEn.mjs +0 -25
  1013. package/dist/lifecycle-BWtBGNEn.mjs.map +0 -1
  1014. package/dist/load-BR1NEa_3.mjs +0 -28
  1015. package/dist/load-BR1NEa_3.mjs.map +0 -1
  1016. package/dist/loader-D4edocWH.mjs +0 -1197
  1017. package/dist/loader-D4edocWH.mjs.map +0 -1
  1018. package/dist/loops-DLaHFrvI.mjs +0 -205
  1019. package/dist/loops-DLaHFrvI.mjs.map +0 -1
  1020. package/dist/manifest-builder-8jsSLR7s.mjs +0 -189
  1021. package/dist/manifest-builder-8jsSLR7s.mjs.map +0 -1
  1022. package/dist/manifest-schema-DcZjRNEv.mjs +0 -496
  1023. package/dist/manifest-schema-DcZjRNEv.mjs.map +0 -1
  1024. package/dist/marketplace-CNxjq10S.mjs +0 -257
  1025. package/dist/marketplace-CNxjq10S.mjs.map +0 -1
  1026. package/dist/media-3v7mqAVX.mjs +0 -294
  1027. package/dist/media-3v7mqAVX.mjs.map +0 -1
  1028. package/dist/media-Bs6qmlVl.mjs +0 -408
  1029. package/dist/media-Bs6qmlVl.mjs.map +0 -1
  1030. package/dist/media-CputjGE1.mjs +0 -373
  1031. package/dist/media-CputjGE1.mjs.map +0 -1
  1032. package/dist/media-allowlist-isqF1gAh.mjs +0 -44
  1033. package/dist/media-allowlist-isqF1gAh.mjs.map +0 -1
  1034. package/dist/media-folders-D2VdVBf6.mjs +0 -210
  1035. package/dist/media-folders-D2VdVBf6.mjs.map +0 -1
  1036. package/dist/media-url-DbkMY3y6.mjs +0 -43
  1037. package/dist/media-url-DbkMY3y6.mjs.map +0 -1
  1038. package/dist/media-usage-activation-BaT4AlNI.mjs +0 -78
  1039. package/dist/media-usage-activation-BaT4AlNI.mjs.map +0 -1
  1040. package/dist/media-usage-v43L0kR_.mjs +0 -282
  1041. package/dist/media-usage-v43L0kR_.mjs.map +0 -1
  1042. package/dist/media-usage-work-CY8gIeU-.mjs +0 -151
  1043. package/dist/media-usage-work-CY8gIeU-.mjs.map +0 -1
  1044. package/dist/media-usage-work-VO108Q9E.mjs +0 -1015
  1045. package/dist/media-usage-work-VO108Q9E.mjs.map +0 -1
  1046. package/dist/menus-BYyeRemR.mjs +0 -3647
  1047. package/dist/menus-BYyeRemR.mjs.map +0 -1
  1048. package/dist/menus-mC_XTxD7.mjs +0 -92
  1049. package/dist/menus-mC_XTxD7.mjs.map +0 -1
  1050. package/dist/menus-trvc6_fW.mjs +0 -753
  1051. package/dist/menus-trvc6_fW.mjs.map +0 -1
  1052. package/dist/mime-IZf-LHIS.mjs +0 -36
  1053. package/dist/mime-IZf-LHIS.mjs.map +0 -1
  1054. package/dist/mode-B9-gMXL9.mjs +0 -23
  1055. package/dist/mode-B9-gMXL9.mjs.map +0 -1
  1056. package/dist/node-sqlite-compat-DztcWs4y.mjs +0 -63
  1057. package/dist/node-sqlite-compat-DztcWs4y.mjs.map +0 -1
  1058. package/dist/oauth-authorization-BIHy9SGU.mjs +0 -274
  1059. package/dist/oauth-authorization-BIHy9SGU.mjs.map +0 -1
  1060. package/dist/oauth-clients-BZWZvKXa.mjs +0 -266
  1061. package/dist/oauth-clients-BZWZvKXa.mjs.map +0 -1
  1062. package/dist/oauth-state-store-CxXTjXdI.mjs +0 -50
  1063. package/dist/oauth-state-store-CxXTjXdI.mjs.map +0 -1
  1064. package/dist/oauth-user-lookup-GWojfxRl.mjs +0 -26
  1065. package/dist/oauth-user-lookup-GWojfxRl.mjs.map +0 -1
  1066. package/dist/options-DRF6dlXY.d.mts +0 -81
  1067. package/dist/options-DRF6dlXY.d.mts.map +0 -1
  1068. package/dist/ownership-Bd77AmJz.mjs +0 -12
  1069. package/dist/ownership-Bd77AmJz.mjs.map +0 -1
  1070. package/dist/parse-5Y0W39xR.mjs +0 -81
  1071. package/dist/parse-5Y0W39xR.mjs.map +0 -1
  1072. package/dist/parse-BPblgoa-.d.mts +0 -172
  1073. package/dist/parse-BPblgoa-.d.mts.map +0 -1
  1074. package/dist/passkey-config-PiQ5cBnt.mjs +0 -46
  1075. package/dist/passkey-config-PiQ5cBnt.mjs.map +0 -1
  1076. package/dist/paths-DkS74lBM.mjs +0 -77
  1077. package/dist/paths-DkS74lBM.mjs.map +0 -1
  1078. package/dist/placeholder-Bez2282x.d.mts +0 -306
  1079. package/dist/placeholder-Bez2282x.d.mts.map +0 -1
  1080. package/dist/plan-Lw7iGnGD.mjs +0 -135
  1081. package/dist/plan-Lw7iGnGD.mjs.map +0 -1
  1082. package/dist/plugins-D7xSh1Lu.mjs +0 -277
  1083. package/dist/plugins-D7xSh1Lu.mjs.map +0 -1
  1084. package/dist/policy-DMRiMdLn.mjs +0 -45
  1085. package/dist/policy-DMRiMdLn.mjs.map +0 -1
  1086. package/dist/portable-text-kcyN3F-a.mjs +0 -307
  1087. package/dist/portable-text-kcyN3F-a.mjs.map +0 -1
  1088. package/dist/preview--2VDLaND.mjs +0 -107
  1089. package/dist/preview--2VDLaND.mjs.map +0 -1
  1090. package/dist/protocol-FvwLA8P-.d.mts +0 -61
  1091. package/dist/protocol-FvwLA8P-.d.mts.map +0 -1
  1092. package/dist/public-submission-BRyK76U8.mjs +0 -250
  1093. package/dist/public-submission-BRyK76U8.mjs.map +0 -1
  1094. package/dist/public-url-7j0cpCFc.mjs +0 -101
  1095. package/dist/public-url-7j0cpCFc.mjs.map +0 -1
  1096. package/dist/query-BRNTde3V.mjs +0 -41
  1097. package/dist/query-BRNTde3V.mjs.map +0 -1
  1098. package/dist/query-DyYYWOKk.mjs +0 -1161
  1099. package/dist/query-DyYYWOKk.mjs.map +0 -1
  1100. package/dist/rate-limit-D0BcE76H.mjs +0 -120
  1101. package/dist/rate-limit-D0BcE76H.mjs.map +0 -1
  1102. package/dist/receipt-C4icyHlC.mjs +0 -43
  1103. package/dist/receipt-C4icyHlC.mjs.map +0 -1
  1104. package/dist/redirect-9DbtxSNG.mjs +0 -19
  1105. package/dist/redirect-9DbtxSNG.mjs.map +0 -1
  1106. package/dist/redirect-BvFKh8Sz.mjs +0 -416
  1107. package/dist/redirect-BvFKh8Sz.mjs.map +0 -1
  1108. package/dist/redirects-1nhdEaTq.mjs +0 -148
  1109. package/dist/redirects-1nhdEaTq.mjs.map +0 -1
  1110. package/dist/redirects-D1yMnSR9.mjs +0 -446
  1111. package/dist/redirects-D1yMnSR9.mjs.map +0 -1
  1112. package/dist/registry-CzPJNu3H.mjs +0 -8366
  1113. package/dist/registry-CzPJNu3H.mjs.map +0 -1
  1114. package/dist/relations-C8JpSkU6.mjs +0 -776
  1115. package/dist/relations-C8JpSkU6.mjs.map +0 -1
  1116. package/dist/request-meta-Bs60XW1m.mjs +0 -141
  1117. package/dist/request-meta-Bs60XW1m.mjs.map +0 -1
  1118. package/dist/resolve-BHWgMU_X.mjs +0 -100
  1119. package/dist/resolve-BHWgMU_X.mjs.map +0 -1
  1120. package/dist/revision-CGkQA0e5.mjs +0 -366
  1121. package/dist/revision-CGkQA0e5.mjs.map +0 -1
  1122. package/dist/route-wire-ClUVQduA.mjs +0 -197
  1123. package/dist/route-wire-ClUVQduA.mjs.map +0 -1
  1124. package/dist/routes-D2GFl3B7.mjs +0 -272
  1125. package/dist/routes-D2GFl3B7.mjs.map +0 -1
  1126. package/dist/runner-CLpxmhl8.mjs +0 -6197
  1127. package/dist/runner-CLpxmhl8.mjs.map +0 -1
  1128. package/dist/runner-CWl76CH3.d.mts +0 -68
  1129. package/dist/runner-CWl76CH3.d.mts.map +0 -1
  1130. package/dist/schema-27XefSYG.mjs +0 -13
  1131. package/dist/schema-27XefSYG.mjs.map +0 -1
  1132. package/dist/schema-Btvj3BMh.mjs +0 -815
  1133. package/dist/schema-Btvj3BMh.mjs.map +0 -1
  1134. package/dist/scopes-DGCj6K4p.mjs +0 -34
  1135. package/dist/scopes-DGCj6K4p.mjs.map +0 -1
  1136. package/dist/search-pZRRmWjh.mjs +0 -448
  1137. package/dist/search-pZRRmWjh.mjs.map +0 -1
  1138. package/dist/secrets-CIi0nFiR.mjs +0 -341
  1139. package/dist/secrets-CIi0nFiR.mjs.map +0 -1
  1140. package/dist/sections-CIhqs3Ao.mjs +0 -346
  1141. package/dist/sections-CIhqs3Ao.mjs.map +0 -1
  1142. package/dist/seo-DifeiGdl.mjs +0 -114
  1143. package/dist/seo-DifeiGdl.mjs.map +0 -1
  1144. package/dist/seo-DpYxmGaL.mjs +0 -133
  1145. package/dist/seo-DpYxmGaL.mjs.map +0 -1
  1146. package/dist/service-COVdVpSK.mjs +0 -150
  1147. package/dist/service-COVdVpSK.mjs.map +0 -1
  1148. package/dist/session-user-C6IEjuty.mjs +0 -61
  1149. package/dist/session-user-C6IEjuty.mjs.map +0 -1
  1150. package/dist/settings-CwcrX-Ay.mjs +0 -61
  1151. package/dist/settings-CwcrX-Ay.mjs.map +0 -1
  1152. package/dist/settings-D_cJtT48.mjs +0 -439
  1153. package/dist/settings-D_cJtT48.mjs.map +0 -1
  1154. package/dist/settings-tnPQN3Z2.mjs +0 -51
  1155. package/dist/settings-tnPQN3Z2.mjs.map +0 -1
  1156. package/dist/setup-complete-BOrI10UY.mjs +0 -65
  1157. package/dist/setup-complete-BOrI10UY.mjs.map +0 -1
  1158. package/dist/setup-nonce-0XTBLTsX.mjs +0 -25
  1159. package/dist/setup-nonce-0XTBLTsX.mjs.map +0 -1
  1160. package/dist/single-flight-cache-B5O2qhO1.mjs +0 -104
  1161. package/dist/single-flight-cache-B5O2qhO1.mjs.map +0 -1
  1162. package/dist/site-settings-B7vGFRDT.mjs +0 -50
  1163. package/dist/site-settings-B7vGFRDT.mjs.map +0 -1
  1164. package/dist/site-url-wEYRMHBv.mjs +0 -16
  1165. package/dist/site-url-wEYRMHBv.mjs.map +0 -1
  1166. package/dist/snapshot-W36KbLmc.mjs +0 -414
  1167. package/dist/snapshot-W36KbLmc.mjs.map +0 -1
  1168. package/dist/ssrf-CRJ-xom5.mjs +0 -406
  1169. package/dist/ssrf-CRJ-xom5.mjs.map +0 -1
  1170. package/dist/stage-DA0NrTRZ.mjs +0 -662
  1171. package/dist/stage-DA0NrTRZ.mjs.map +0 -1
  1172. package/dist/staged-Bw5eHbKS.mjs +0 -686
  1173. package/dist/staged-Bw5eHbKS.mjs.map +0 -1
  1174. package/dist/state-BTlprvUF.mjs +0 -153
  1175. package/dist/state-BTlprvUF.mjs.map +0 -1
  1176. package/dist/status-C6IrSLMT.mjs +0 -30
  1177. package/dist/status-C6IrSLMT.mjs.map +0 -1
  1178. package/dist/storage-query-CdVF2bng.d.mts +0 -1614
  1179. package/dist/storage-query-CdVF2bng.d.mts.map +0 -1
  1180. package/dist/tar-BGOZARjy.mjs +0 -449
  1181. package/dist/tar-BGOZARjy.mjs.map +0 -1
  1182. package/dist/target-YhYH_0uc.mjs +0 -27
  1183. package/dist/target-YhYH_0uc.mjs.map +0 -1
  1184. package/dist/taxonomies-DK_XBrmT.mjs +0 -697
  1185. package/dist/taxonomies-DK_XBrmT.mjs.map +0 -1
  1186. package/dist/taxonomies-S1M3rUC0.mjs +0 -939
  1187. package/dist/taxonomies-S1M3rUC0.mjs.map +0 -1
  1188. package/dist/taxonomy-BesdHIwi.mjs +0 -525
  1189. package/dist/taxonomy-BesdHIwi.mjs.map +0 -1
  1190. package/dist/tokens-B_ffPF1q.mjs +0 -171
  1191. package/dist/tokens-B_ffPF1q.mjs.map +0 -1
  1192. package/dist/transfer-9fVSxyrV.mjs +0 -166
  1193. package/dist/transfer-9fVSxyrV.mjs.map +0 -1
  1194. package/dist/transfer-B7LUTaYD.mjs +0 -8855
  1195. package/dist/transfer-B7LUTaYD.mjs.map +0 -1
  1196. package/dist/transfer-download-BdNq4VWN.mjs +0 -33
  1197. package/dist/transfer-download-BdNq4VWN.mjs.map +0 -1
  1198. package/dist/transformations-BtQdvyly.mjs +0 -196
  1199. package/dist/transformations-BtQdvyly.mjs.map +0 -1
  1200. package/dist/transport-CriYXY1c.mjs +0 -136
  1201. package/dist/transport-CriYXY1c.mjs.map +0 -1
  1202. package/dist/transport-SnhS6xku.d.mts +0 -42
  1203. package/dist/transport-SnhS6xku.d.mts.map +0 -1
  1204. package/dist/trusted-proxy-C0eHXPd-.mjs +0 -51
  1205. package/dist/trusted-proxy-C0eHXPd-.mjs.map +0 -1
  1206. package/dist/turnstile-BNPrWd1e.mjs +0 -53
  1207. package/dist/turnstile-BNPrWd1e.mjs.map +0 -1
  1208. package/dist/types-B8sF_kE5.d.mts +0 -287
  1209. package/dist/types-B8sF_kE5.d.mts.map +0 -1
  1210. package/dist/types-BYVIYOlD.d.mts +0 -1720
  1211. package/dist/types-BYVIYOlD.d.mts.map +0 -1
  1212. package/dist/types-Bs4bi95j.d.mts +0 -374
  1213. package/dist/types-Bs4bi95j.d.mts.map +0 -1
  1214. package/dist/types-CGuODCZi.d.mts +0 -198
  1215. package/dist/types-CGuODCZi.d.mts.map +0 -1
  1216. package/dist/types-CVsmpTcU.mjs +0 -18
  1217. package/dist/types-CVsmpTcU.mjs.map +0 -1
  1218. package/dist/types-ClFEExxn.mjs +0 -37
  1219. package/dist/types-ClFEExxn.mjs.map +0 -1
  1220. package/dist/types-D994zUWB.d.mts +0 -85
  1221. package/dist/types-D994zUWB.d.mts.map +0 -1
  1222. package/dist/types-DAj1ByJQ.d.mts +0 -125
  1223. package/dist/types-DAj1ByJQ.d.mts.map +0 -1
  1224. package/dist/types-Dlv6esp4.mjs +0 -77
  1225. package/dist/types-Dlv6esp4.mjs.map +0 -1
  1226. package/dist/types-Dr1LVwL7.d.mts +0 -363
  1227. package/dist/types-Dr1LVwL7.d.mts.map +0 -1
  1228. package/dist/types-MN9bOQ1g.d.mts +0 -198
  1229. package/dist/types-MN9bOQ1g.d.mts.map +0 -1
  1230. package/dist/types-d2Szb1oz.mjs +0 -16
  1231. package/dist/types-d2Szb1oz.mjs.map +0 -1
  1232. package/dist/types-ibtP7GEA.d.mts +0 -896
  1233. package/dist/types-ibtP7GEA.d.mts.map +0 -1
  1234. package/dist/types-j6MBDjlZ.mjs +0 -103
  1235. package/dist/types-j6MBDjlZ.mjs.map +0 -1
  1236. package/dist/update-check-D8No-E5s.mjs +0 -161
  1237. package/dist/update-check-D8No-E5s.mjs.map +0 -1
  1238. package/dist/upload-attempts-BodUoFBu.mjs +0 -32
  1239. package/dist/upload-attempts-BodUoFBu.mjs.map +0 -1
  1240. package/dist/url-pattern-DGAG6ZP2.mjs +0 -41
  1241. package/dist/url-pattern-DGAG6ZP2.mjs.map +0 -1
  1242. package/dist/user-BOvuF1sQ.mjs +0 -171
  1243. package/dist/user-BOvuF1sQ.mjs.map +0 -1
  1244. package/dist/utils-Dr01wRKt.mjs +0 -439
  1245. package/dist/utils-Dr01wRKt.mjs.map +0 -1
  1246. package/dist/validate-BttYU7NK.mjs +0 -516
  1247. package/dist/validate-BttYU7NK.mjs.map +0 -1
  1248. package/dist/validate-Df09inbC.d.mts +0 -468
  1249. package/dist/validate-Df09inbC.d.mts.map +0 -1
  1250. package/dist/validation-DH2WRwWO.mjs +0 -219
  1251. package/dist/validation-DH2WRwWO.mjs.map +0 -1
  1252. package/dist/version-BbygH8CT.mjs +0 -7
  1253. package/dist/version-BbygH8CT.mjs.map +0 -1
  1254. package/dist/version-CseoDDOd.mjs +0 -9
  1255. package/dist/version-CseoDDOd.mjs.map +0 -1
  1256. package/dist/virtual-modules-82GlnQyG.mjs +0 -516
  1257. package/dist/virtual-modules-82GlnQyG.mjs.map +0 -1
  1258. package/dist/widgets-DMAgGcQt.mjs +0 -126
  1259. package/dist/widgets-DMAgGcQt.mjs.map +0 -1
  1260. package/dist/wxr-taxonomies-Bi5kFSxQ.mjs +0 -453
  1261. package/dist/wxr-taxonomies-Bi5kFSxQ.mjs.map +0 -1
  1262. package/dist/wxr-taxonomies-y_FpYlDn.d.mts +0 -34
  1263. package/dist/wxr-taxonomies-y_FpYlDn.d.mts.map +0 -1
  1264. package/dist/zod-generator-DnfG5sGQ.mjs +0 -424
  1265. package/dist/zod-generator-DnfG5sGQ.mjs.map +0 -1
  1266. /package/dist/{api-tokens-B4COohsb.mjs → api-tokens-BLz2MtQs.mjs} +0 -0
  1267. /package/dist/{ssrf-sC4_5rxm.mjs → ssrf-tA45vIPX.mjs} +0 -0
@@ -0,0 +1,4980 @@
1
+ import { n as isMissingTableError, t as isMissingColumnError } from "./db-errors-CBD5yMro.mjs";
2
+ import { i as validateStorageCollectionName, n as validateJsonFieldName, r as validatePluginIdentifier, t as validateIdentifier } from "./validate-DANX1-Qi.mjs";
3
+ import { d as isSqlite, f as jsonExtractExpr, u as isPostgres } from "./dialect-helpers-7_IqPdh9.mjs";
4
+ import { i as isI18nEnabled, o as resolveConfiguredLocale, r as getI18nConfig } from "./config-CvmjJcVw.mjs";
5
+ import { t as after } from "./after-PcEvMY_6.mjs";
6
+ import { t as OptionsRepository } from "./options-DhrI7eMv.mjs";
7
+ import { t as EmDashSecretsError } from "./secrets-Cc_O3Kp-.mjs";
8
+ import { i as encodeBase64, t as decodeBase64 } from "./base64-BQBZwXCx.mjs";
9
+ import { r as isSystemOrderField, t as ContentRepository } from "./content-Dji9vEiW.mjs";
10
+ import { m as isStoragelessFieldRow, p as isStoragelessField, s as MAX_COLLECTION_LIST_COLUMNS } from "./types-BGmQ0uXs.mjs";
11
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-zlGB5IQP.mjs";
12
+ import { r as requestCached } from "./request-cache-C4CIo5ad.mjs";
13
+ import { i as InvalidCursorError, n as ContentMutationConflictError, o as ScheduledNotDueError, r as EmDashValidationError, t as ContentCollectionNotFoundError } from "./types-C-Xp0CcN.mjs";
14
+ import { t as RevisionRepository } from "./revision-BWEH2qQB.mjs";
15
+ import { t as withTransaction } from "./transaction-BVYIo_yu.mjs";
16
+ import { t as UserRepository } from "./user-Dnp53zTq.mjs";
17
+ import { t as TaxonomyRepository } from "./taxonomy-XzLE95Vx.mjs";
18
+ import { t as CommentRepository } from "./comment-Bu08Wvr3.mjs";
19
+ import { t as RedirectRepository } from "./redirect-xZNpBoGp.mjs";
20
+ import { t as BylineRepository } from "./byline-BhVslYLz.mjs";
21
+ import { c as readStagedReferenceBaselines, d as RelationRepository, i as STAGED_REFERENCES_KEY, l as readStagedReferences, r as STAGED_REFERENCES_BASELINE_KEY, s as pageStagedGroups } from "./staged-Q7pnEVvI.mjs";
22
+ import { r as parseAllowedMimeTypes, t as matchesMimeAllowlist } from "./mime-B5M9R53H.mjs";
23
+ import { t as EntryLockRepository } from "./entry-locks-DJAqVweV.mjs";
24
+ import { t as SeoRepository } from "./seo-BdeEPDNW.mjs";
25
+ import { i as scheduledPolicyRejectionKey } from "./content-policy-Dm32n9C6.mjs";
26
+ import { n as invalidateRedirectCache } from "./cache-aTYCL9nK.mjs";
27
+ import { r as publishRedirectChanges } from "./artifacts-UzWbysb8.mjs";
28
+ import { t as FTSManager } from "./fts-manager-DacCYIe4.mjs";
29
+ import { d as invalidateTermCache } from "./taxonomies-DAZU9VDd.mjs";
30
+ import { L as BlockTypeRegistry, n as SchemaRegistry } from "./registry-DaXmUsD4.mjs";
31
+ import { r as hashString } from "./hash-C4DFoJ7Z.mjs";
32
+ import { n as expandCollectionBlockFields } from "./block-values-H4E0XwE8.mjs";
33
+ import { _ as referenceFieldConstraints, d as resolveEntryGroups, f as resolveReferenceSelection, g as writeReferenceSelection, h as validateOppositeSideLimit, n as getReferenceTitleField, p as resolveReferenceSelectionTargets, u as resolveEntries, v as validateReferenceSelection, y as validateRequiredReferencesPresent } from "./relations-JvBP8nGP.mjs";
34
+ import { a as parseDurationSeconds, l as validateAggregatorUrl, n as coerceRegistryConfig, o as releaseExemptFromMinimumAge, t as canonicalCapabilitiesForDriftCheck } from "./config-BsJHiQxC.mjs";
35
+ import { t as ErrorCode } from "./errors-DTE6C3K_.mjs";
36
+ import { t as PluginStateRepository } from "./state-kGdOMQRY.mjs";
37
+ import { f as encodePluginSettingValue, l as PluginSettingEncryptionError } from "./settings-m5tIYnF0.mjs";
38
+ import { a as pluginManifestSchema$1, i as normalizeManifestRoute$1, o as reconcileManifestAccess$1 } from "./manifest-schema-gy37bD_D.mjs";
39
+ import { n as MarketplaceUnavailableError, r as createMarketplaceClient, t as MarketplaceError } from "./marketplace-tHWSsCUo.mjs";
40
+ import { o as withUnavailableReason } from "./types-CdEMurNh.mjs";
41
+ import { o as warnDeprecatedPluginCapabilities, r as normalizeCapabilities } from "./types-CxwtnuSS.mjs";
42
+ import { t as EmDashStorageError } from "./types-DGw8KMX_.mjs";
43
+ import { i as verificationError, r as verifyMultihash, t as computeArtifactDigestCandidates } from "./checksum-DtH6m5uk.mjs";
44
+ import { n as fetchReleaseArtifact, t as fetchRegistryArtifactUrl } from "./artifact-fetch-CWxyELVI.mjs";
45
+ import { i as resolveAndValidateExternalUrlTarget } from "./ssrf-DsmvZB80.mjs";
46
+ import { r as verifyAuthoritativePackageRelease, t as readAuthoritativePackageRelease } from "./authoritative-records-dSvXCfzb.mjs";
47
+ import { sql } from "kysely";
48
+ import { canonicalizeDeclaredAccess, pluginManifestSchema, reconcileManifestAccess } from "@emdash-cms/plugin-types";
49
+ import { createGzipDecoder } from "modern-tar";
50
+ import { ClientResponseError, ClientValidationError } from "@atcute/client";
51
+ import { checkEnvCompatibility, compareVersions, findSkippedEnvConstraints } from "@emdash-cms/registry-client/env";
52
+ import { isProvenFirstRelease } from "@emdash-cms/registry-client/listing-policy";
53
+ import { evaluateRegistryReleaseWithdrawal } from "@emdash-cms/registry-client/withdrawal";
54
+ import { NSID } from "@emdash-cms/registry-lexicons";
55
+
56
+ //#region src/api/rev.ts
57
+ /**
58
+ * Generate a _rev token from a content item's version and updatedAt.
59
+ */
60
+ function encodeRev(item) {
61
+ return encodeBase64(`${item.version}:${item.updatedAt}`);
62
+ }
63
+ /**
64
+ * Decode a _rev token into its components.
65
+ * Returns null if the token is malformed.
66
+ */
67
+ function decodeRev(rev) {
68
+ try {
69
+ const decoded = decodeBase64(rev);
70
+ const colonIdx = decoded.indexOf(":");
71
+ if (colonIdx === -1) return null;
72
+ const version = parseInt(decoded.slice(0, colonIdx), 10);
73
+ const updatedAt = decoded.slice(colonIdx + 1);
74
+ if (isNaN(version) || !updatedAt) return null;
75
+ return {
76
+ version,
77
+ updatedAt
78
+ };
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ /**
84
+ * Validate a _rev token against a content item.
85
+ * Returns null if valid (or if no _rev provided), or an error message if invalid.
86
+ */
87
+ function validateRev(rev, item) {
88
+ if (!rev) return { valid: true };
89
+ const decoded = decodeRev(rev);
90
+ if (!decoded) return {
91
+ valid: false,
92
+ message: "Malformed _rev token"
93
+ };
94
+ if (decoded.version !== item.version || decoded.updatedAt !== item.updatedAt) return {
95
+ valid: false,
96
+ message: "Content has been modified since last read (version conflict)"
97
+ };
98
+ return { valid: true };
99
+ }
100
+
101
+ //#endregion
102
+ //#region src/api/handlers/staged-references.ts
103
+ /** One bound field's live selection as translation groups. */
104
+ async function liveFieldSelection(repo, field, entryGroup) {
105
+ return (field.relationSide === "child" ? await repo.getParents(field.relation, entryGroup) : await repo.getChildren(field.relation, entryGroup)).map((link) => field.relationSide === "child" ? link.parentGroup : link.childGroup);
106
+ }
107
+ /**
108
+ * Re-check what publication is about to make live against the relation's current
109
+ * cardinality.
110
+ *
111
+ * A draft can sit unpublished across a schema edit that makes its field required
112
+ * or narrows the relation's limits, and across another entry claiming what it
113
+ * selected. It is publication — not the save that staged it — that has to hold
114
+ * the line on both ends. So this walks the collection's bound fields rather than
115
+ * the staged keys: a field added as required after the entry was written appears
116
+ * in no existing draft, and iterating `staged` would never reach it. A field the
117
+ * draft does stage needs no link read.
118
+ */
119
+ async function validateStagedReferences(db, collection, staged, entryGroup, baselines) {
120
+ const repo = new RelationRepository(db);
121
+ for (const field of (await referenceFieldConstraints(db, collection)).values()) {
122
+ const isStaged = Object.hasOwn(staged, field.slug);
123
+ let groups = isStaged ? staged[field.slug] ?? [] : void 0;
124
+ const baseline = baselines?.[field.slug];
125
+ if (groups && baseline) {
126
+ const live = await liveFieldSelection(repo, field, entryGroup);
127
+ groups = applyReferenceDiff(baseline, groups, live);
128
+ }
129
+ groups ??= await liveFieldSelection(repo, field, entryGroup);
130
+ const valid = validateReferenceSelection(field, groups);
131
+ if (!valid.success) return valid;
132
+ if (!isStaged || field.relationId === null) continue;
133
+ const far = await validateOppositeSideLimit(db, {
134
+ relationId: field.relationId,
135
+ farLimit: field.maxOpposite,
136
+ side: field.relationSide,
137
+ entryGroup,
138
+ groups
139
+ });
140
+ if (!far.success) return far;
141
+ }
142
+ return {
143
+ success: true,
144
+ data: true
145
+ };
146
+ }
147
+ /**
148
+ * The live selection, in the same shape a draft stages: every bound reference
149
+ * field on the collection, by field slug, as translation groups.
150
+ *
151
+ * One link read per bound field. Used where both selections have to be
152
+ * comparable — the live and draft sides of a compare — never on a render path.
153
+ */
154
+ async function liveReferenceSelection(db, collection, entryGroup) {
155
+ const repo = new RelationRepository(db);
156
+ const selection = {};
157
+ for (const field of (await referenceFieldConstraints(db, collection)).values()) selection[field.slug] = await liveFieldSelection(repo, field, entryGroup);
158
+ return selection;
159
+ }
160
+ /**
161
+ * Compute the selection that results from applying the staged-versus-baseline
162
+ * diff on top of the current live selection.
163
+ *
164
+ * Additions and removals made in the draft win. Items the draft left unchanged
165
+ * follow the current live selection, preserving additions and removals made
166
+ * from the relation's opposite end.
167
+ */
168
+ function applyReferenceDiff(baseline, staged, live) {
169
+ const baselineSet = new Set(baseline);
170
+ const stagedSet = new Set(staged);
171
+ const liveSet = new Set(live);
172
+ const additionSet = new Set(staged.filter((group) => !baselineSet.has(group)));
173
+ const removalSet = new Set(baseline.filter((group) => !stagedSet.has(group)));
174
+ const result = [];
175
+ const seen = /* @__PURE__ */ new Set();
176
+ for (const group of staged) {
177
+ if (!additionSet.has(group) && !liveSet.has(group) || seen.has(group)) continue;
178
+ result.push(group);
179
+ seen.add(group);
180
+ }
181
+ for (const group of live) {
182
+ if (removalSet.has(group) || seen.has(group)) continue;
183
+ result.push(group);
184
+ seen.add(group);
185
+ }
186
+ return result;
187
+ }
188
+ /**
189
+ * Record the complete live selection in the revision publication just made live.
190
+ *
191
+ * A draft stages only the fields its saves named, and a revision written from
192
+ * the columns stages none. Restoring either would otherwise leave whatever was
193
+ * published after it linked in the fields it does not carry.
194
+ */
195
+ async function recordPublishedReferences(db, collection, revisionId, entryGroup) {
196
+ const selection = await liveReferenceSelection(db, collection, entryGroup);
197
+ if (Object.keys(selection).length === 0) return;
198
+ await new RevisionRepository(db).mergeData(revisionId, { [STAGED_REFERENCES_KEY]: selection });
199
+ }
200
+ /**
201
+ * Promote a staged selection to live links.
202
+ *
203
+ * A field slug the collection no longer carries as a bound reference field is
204
+ * skipped: the revision outlived the field, and there is no relation left to
205
+ * write into.
206
+ *
207
+ * When `baselines` are provided, each staged field is promoted as a diff
208
+ * against its baseline rather than as a wholesale replacement. That prevents a
209
+ * draft saved before a concurrent opposite-end publish from undoing the links
210
+ * that publish added or removed.
211
+ */
212
+ async function applyStagedReferences(db, collection, entryGroup, staged, baselines) {
213
+ const constraints = await referenceFieldConstraints(db, collection);
214
+ const repo = new RelationRepository(db);
215
+ for (const [fieldSlug, groups] of Object.entries(staged)) {
216
+ const field = constraints.get(fieldSlug);
217
+ if (!field) continue;
218
+ const baseline = baselines?.[fieldSlug];
219
+ let selection;
220
+ if (baseline) selection = applyReferenceDiff(baseline, groups, await liveFieldSelection(repo, field, entryGroup));
221
+ else selection = groups;
222
+ await writeReferenceSelection(db, {
223
+ relation: field.relation,
224
+ side: field.relationSide,
225
+ entryGroup,
226
+ groups: selection
227
+ });
228
+ }
229
+ }
230
+
231
+ //#endregion
232
+ //#region src/api/handlers/validate-media-fields.ts
233
+ function asMediaRef(value) {
234
+ if (value === null || value === void 0) return null;
235
+ if (typeof value !== "object" || Array.isArray(value)) return null;
236
+ return value;
237
+ }
238
+ function fail(message) {
239
+ return {
240
+ success: false,
241
+ error: {
242
+ code: "INVALID_MIME_FOR_FIELD",
243
+ message
244
+ }
245
+ };
246
+ }
247
+ function addTarget(targets, path, value, allowedMimeTypes, includeDarkVariant) {
248
+ if (!allowedMimeTypes?.length || value == null) return;
249
+ targets.push({
250
+ path,
251
+ value,
252
+ allowedMimeTypes: [...allowedMimeTypes]
253
+ });
254
+ const ref = includeDarkVariant ? asMediaRef(value) : null;
255
+ if (ref && "darkVariant" in ref && ref.darkVariant != null) targets.push({
256
+ path: `${path}.darkVariant`,
257
+ value: ref.darkVariant,
258
+ allowedMimeTypes: [...allowedMimeTypes]
259
+ });
260
+ }
261
+ function collectBlockTargets(targets, field, value) {
262
+ if (!Array.isArray(value)) return {
263
+ success: true,
264
+ data: true
265
+ };
266
+ const types = new Map((field.blockTypes ?? []).map((type) => [type.slug, type]));
267
+ for (const [index, block] of value.entries()) {
268
+ if (!block || typeof block !== "object" || Array.isArray(block)) continue;
269
+ const typeSlug = "_type" in block && typeof block._type === "string" ? block._type : void 0;
270
+ const versionNumber = "_version" in block && typeof block._version === "number" ? block._version : void 0;
271
+ const key = "_key" in block && typeof block._key === "string" ? block._key : String(index);
272
+ const type = typeSlug ? types.get(typeSlug) : void 0;
273
+ const version = type?.versions.find((candidate) => candidate.version === versionNumber);
274
+ if (!type || !version || version.unsupportedTypes?.length) return {
275
+ success: false,
276
+ error: {
277
+ code: "UNSUPPORTED_FIELD_TYPE",
278
+ message: `Field '${field.slug}' block '${key}' has no retained definition`
279
+ }
280
+ };
281
+ for (const nestedField of version.fields) {
282
+ const nestedValue = nestedField.slug in block ? block[nestedField.slug] : void 0;
283
+ const nestedPath = `${field.slug}.${key}.${nestedField.slug}`;
284
+ if (nestedField.type !== "image" && nestedField.type !== "file") continue;
285
+ addTarget(targets, nestedPath, nestedValue, nestedField.validation?.allowedMimeTypes, nestedField.type === "image");
286
+ }
287
+ }
288
+ return {
289
+ success: true,
290
+ data: true
291
+ };
292
+ }
293
+ async function loadMediaFieldsForCollection(db, collectionSlug) {
294
+ const rows = await db.selectFrom("_emdash_fields").innerJoin("_emdash_collections", "_emdash_collections.id", "_emdash_fields.collection_id").select([
295
+ "_emdash_fields.slug",
296
+ "_emdash_fields.type",
297
+ "_emdash_fields.validation"
298
+ ]).where("_emdash_collections.slug", "=", collectionSlug).where("_emdash_fields.type", "in", [
299
+ "file",
300
+ "image",
301
+ "blocks"
302
+ ]).execute();
303
+ const out = [];
304
+ const allBlockTypes = rows.some((row) => row.type === "blocks") ? await new BlockTypeRegistry(db).listBlockTypes() : [];
305
+ const blockTypeBySlug = new Map(allBlockTypes.map((type) => [type.slug, type]));
306
+ for (const row of rows) {
307
+ if (row.type === "blocks") {
308
+ let validation;
309
+ try {
310
+ validation = row.validation ? JSON.parse(row.validation) : {};
311
+ } catch {
312
+ validation = {};
313
+ }
314
+ let configured = [];
315
+ if (validation && typeof validation === "object" && !Array.isArray(validation)) {
316
+ const allowed = "allowedTypes" in validation && Array.isArray(validation.allowedTypes) ? validation.allowedTypes : [];
317
+ const retired = "retiredTypes" in validation && Array.isArray(validation.retiredTypes) ? validation.retiredTypes : [];
318
+ configured = [...allowed, ...retired];
319
+ }
320
+ out.push({
321
+ slug: row.slug,
322
+ type: row.type,
323
+ allowedMimeTypes: [],
324
+ blockTypes: configured.flatMap((slug) => {
325
+ const type = typeof slug === "string" ? blockTypeBySlug.get(slug) : void 0;
326
+ return type ? [type] : [];
327
+ })
328
+ });
329
+ continue;
330
+ }
331
+ const list = parseAllowedMimeTypes(row.validation);
332
+ if (!list) continue;
333
+ out.push({
334
+ slug: row.slug,
335
+ type: row.type,
336
+ allowedMimeTypes: list
337
+ });
338
+ }
339
+ return out;
340
+ }
341
+ async function validateMediaFields(db, collectionSlug, data) {
342
+ const fields = await requestCached(`mediaFields:${collectionSlug}`, () => loadMediaFieldsForCollection(db, collectionSlug));
343
+ if (fields.length === 0) return {
344
+ success: true,
345
+ data: true
346
+ };
347
+ const targets = [];
348
+ for (const field of fields) {
349
+ const value = data[field.slug];
350
+ if (field.type === "blocks") {
351
+ const collected = collectBlockTargets(targets, field, value);
352
+ if (!collected.success) return collected;
353
+ } else addTarget(targets, field.slug, value, field.allowedMimeTypes, field.type === "image");
354
+ }
355
+ if (targets.length === 0) return {
356
+ success: true,
357
+ data: true
358
+ };
359
+ const localIds = /* @__PURE__ */ new Set();
360
+ for (const target of targets) {
361
+ const ref = asMediaRef(target.value);
362
+ if (!ref) continue;
363
+ if ((typeof ref.provider === "string" ? ref.provider : "local") === "local" && typeof ref.id === "string") localIds.add(ref.id);
364
+ }
365
+ const idList = [...localIds];
366
+ const mimeById = /* @__PURE__ */ new Map();
367
+ if (idList.length > 0) for (const batch of chunks(idList, SQL_BATCH_SIZE)) {
368
+ const rows = await db.selectFrom("media").select(["id", "mime_type"]).where("id", "in", batch).execute();
369
+ for (const r of rows) mimeById.set(r.id, r.mime_type);
370
+ }
371
+ for (const target of targets) {
372
+ const ref = asMediaRef(target.value);
373
+ if (!ref) continue;
374
+ const provider = typeof ref.provider === "string" ? ref.provider : "local";
375
+ let mime;
376
+ if (provider === "local") {
377
+ if (typeof ref.id !== "string") return fail(`Field '${target.path}' references media with an invalid id`);
378
+ mime = mimeById.get(ref.id);
379
+ if (!mime) return fail(`Field '${target.path}' references media with unknown MIME type`);
380
+ } else {
381
+ if (typeof ref.mimeType !== "string") return fail(`Field '${target.path}' requires a mimeType declaration for non-local media`);
382
+ mime = ref.mimeType;
383
+ }
384
+ if (!matchesMimeAllowlist(mime, target.allowedMimeTypes)) return fail(`Field '${target.path}' does not accept ${mime}`);
385
+ }
386
+ return {
387
+ success: true,
388
+ data: true
389
+ };
390
+ }
391
+
392
+ //#endregion
393
+ //#region src/api/handlers/content.ts
394
+ /**
395
+ * Narrow a caught error to one carrying a structured `apiError` discriminant.
396
+ * Used by transaction callbacks that want to surface a specific error code
397
+ * through the standard Error throwing path.
398
+ */
399
+ function hasApiError(error) {
400
+ if (!(error instanceof Error) || !("apiError" in error)) return false;
401
+ const { apiError } = error;
402
+ return typeof apiError === "object" && apiError !== null && "code" in apiError && typeof apiError.code === "string";
403
+ }
404
+ /**
405
+ * Abort the surrounding transaction when a relation's limit refused an edge.
406
+ *
407
+ * `farSide` names the end that filled up, which is the opposite of the end the
408
+ * refused group sits on: a child that cannot take another parent refuses with
409
+ * `"parent"`.
410
+ */
411
+ function throwIfReferenceLimitRefused(rejected, farSide) {
412
+ if (rejected.length === 0) return;
413
+ throw Object.assign(/* @__PURE__ */ new Error(`Entry '${rejected[0]}' already has the maximum number of ${farSide} entries on this relation.`), { apiError: { code: "VALIDATION_ERROR" } });
414
+ }
415
+ /** The slug a draft revision stages, when it stages one. */
416
+ function readStagedSlug(data) {
417
+ return typeof data?._slug === "string" ? data._slug : null;
418
+ }
419
+ /**
420
+ * Make every refusal `publish()` decides before it writes, ahead of it.
421
+ *
422
+ * `publish()` decides all of them again and stays authoritative; this does not
423
+ * replace it. It exists for the one caller that has irreversible work to do
424
+ * first — promoting a draft's staged reference selection, which nothing takes
425
+ * back where `withTransaction` degrades to plain statements. A refusal that
426
+ * landed after that promotion would leave a draft's links live on an entry that
427
+ * never published.
428
+ *
429
+ * The optimistic fence `publish()` ends on is not checked here, because it is
430
+ * the write itself: a publish lost to a concurrent edit still promotes.
431
+ */
432
+ async function assertPublishWillNotBeRefused(db, collection, id, existing, options) {
433
+ const { expectedRevision } = options;
434
+ if (expectedRevision && (existing.version !== expectedRevision.version || existing.updatedAt !== expectedRevision.updatedAt)) throw new ContentMutationConflictError();
435
+ if (options.requireDue && options.expectedScheduledAt !== void 0 && existing.scheduledAt !== options.expectedScheduledAt) throw new ScheduledNotDueError();
436
+ const intendedSlug = options.stagedSlug ?? existing.slug;
437
+ if (options.requireSlug && !intendedSlug?.trim()) throw new EmDashValidationError("Cannot publish routable content without a slug");
438
+ if (options.stagedSlug !== null && options.stagedSlug !== existing.slug && existing.locale !== null) {
439
+ const conflict = await new ContentRepository(db).findBySlugIncludingTrashed(collection, options.stagedSlug, existing.locale);
440
+ if (conflict && conflict.id !== id) throw new EmDashValidationError(`Cannot publish: slug '${options.stagedSlug}' is already used by another entry in this collection (id: ${conflict.id}). Choose a different slug.`, { code: "SLUG_CONFLICT" });
441
+ }
442
+ }
443
+ function isTranslationLocaleConflict(error, collection) {
444
+ if (!(error instanceof Error)) return false;
445
+ const message = error.message.toLowerCase();
446
+ const storedIndexName = `uidx_ec_${collection}_active_tg_locale`.slice(0, 63).toLowerCase();
447
+ return message.includes(storedIndexName) || message.includes("unique constraint failed") && message.includes("translation_group") && message.includes("locale");
448
+ }
449
+ function decodeRevisionPrecondition(rev) {
450
+ if (rev === void 0) return void 0;
451
+ const decoded = decodeRev(rev);
452
+ if (!decoded) throw new ContentMutationConflictError("Revision precondition did not match");
453
+ return decoded;
454
+ }
455
+ /**
456
+ * Extract a slug source (title or name) from content data.
457
+ * Returns null if no suitable string field is found.
458
+ */
459
+ function getSlugSource(data) {
460
+ if (typeof data.title === "string" && data.title.length > 0) return data.title;
461
+ if (typeof data.name === "string" && data.name.length > 0) return data.name;
462
+ return null;
463
+ }
464
+ /** Default SEO values for content without an explicit SEO row */
465
+ const SEO_DEFAULTS = {
466
+ title: null,
467
+ description: null,
468
+ image: null,
469
+ canonical: null,
470
+ noIndex: false
471
+ };
472
+ /**
473
+ * Check if a collection has SEO enabled.
474
+ *
475
+ * Cached per request so bulk imports do not re-query `_emdash_collections`
476
+ * for every item they create.
477
+ */
478
+ async function collectionHasSeo(db, collection) {
479
+ return requestCached(`collectionHasSeo:${collection}`, async () => {
480
+ return (await db.selectFrom("_emdash_collections").select("has_seo").where("slug", "=", collection).executeTakeFirst())?.has_seo === 1;
481
+ });
482
+ }
483
+ /**
484
+ * Collection publication metadata, cached per request for bulk imports.
485
+ */
486
+ async function getCollectionPublishConfig(db, collection) {
487
+ return requestCached(`collectionPublishConfig:${collection}`, async () => {
488
+ const row = await db.selectFrom("_emdash_collections").select(["supports", "routable"]).where("slug", "=", collection).executeTakeFirst();
489
+ const supports = row?.supports ? JSON.parse(row.supports) : [];
490
+ return {
491
+ supportsRevisions: Array.isArray(supports) && supports.includes("revisions"),
492
+ routable: row?.routable !== 0
493
+ };
494
+ });
495
+ }
496
+ function requireRoutablePublishSlug(routable, slug) {
497
+ if (routable && !slug?.trim()) throw new EmDashValidationError("Cannot publish routable content without a slug");
498
+ }
499
+ /**
500
+ * Hydrate SEO data on a single content item if the collection has SEO enabled.
501
+ */
502
+ async function hydrateSeo(db, collection, item, hasSeo) {
503
+ if (!hasSeo) return;
504
+ item.seo = await new SeoRepository(db).get(collection, item.id);
505
+ }
506
+ /**
507
+ * Hydrate SEO data on multiple content items using a single batch query.
508
+ */
509
+ async function hydrateSeoMany(db, collection, items, hasSeo) {
510
+ if (!hasSeo || items.length === 0) return;
511
+ const seoMap = await new SeoRepository(db).getMany(collection, items.map((i) => i.id));
512
+ for (const item of items) item.seo = seoMap.get(item.id) ?? { ...SEO_DEFAULTS };
513
+ }
514
+ async function hydrateBylines(db, collection, item) {
515
+ const bylineRepo = new BylineRepository(db);
516
+ const localeOpt = item.locale ? { locale: item.locale } : void 0;
517
+ const bylines = await bylineRepo.getContentBylines(collection, item.id, localeOpt);
518
+ if (bylines.length > 0) {
519
+ item.bylines = bylines.map((c) => ({
520
+ ...c,
521
+ source: "explicit"
522
+ }));
523
+ item.byline = bylines[0]?.byline ?? null;
524
+ return;
525
+ }
526
+ if (item.primaryBylineId) {
527
+ item.bylines = [];
528
+ item.byline = null;
529
+ return;
530
+ }
531
+ if (item.authorId) {
532
+ const fallback = await bylineRepo.findByUserId(item.authorId, localeOpt);
533
+ if (fallback) {
534
+ item.bylines = [{
535
+ byline: fallback,
536
+ sortOrder: 0,
537
+ roleLabel: null,
538
+ source: "inferred"
539
+ }];
540
+ item.byline = fallback;
541
+ return;
542
+ }
543
+ }
544
+ item.bylines = [];
545
+ item.byline = null;
546
+ }
547
+ function isRecord(value) {
548
+ return typeof value === "object" && value !== null;
549
+ }
550
+ /**
551
+ * Hydrate the first page of each reference field's selection onto a single
552
+ * content item, keyed by field slug — the same key the create and update bodies
553
+ * take a selection under.
554
+ *
555
+ * Callers must have already decided `includeDrafts` — draft visibility is
556
+ * enforced by the caller, not this helper — because a resolved entry can carry
557
+ * a draft or scheduled entry's id and slug. The admin's REST GET route is the
558
+ * only caller, and it asks for every entry it serves, so a collection with no
559
+ * reference field still pays the two lookups below.
560
+ *
561
+ * For a caller that opted into drafts, a field whose selection is staged in the
562
+ * entry's draft revision is answered from that revision; every other field, and
563
+ * every field for a caller that did not opt in, is answered from the links,
564
+ * which hold the published selection. That is what keeps a picker change on a
565
+ * published entry invisible until it is published.
566
+ *
567
+ * Either selection arrives one page at a time, with the cursor to walk the rest
568
+ * through the edge routes — a draft's pending selection can be as long as a
569
+ * published one, and a caller that reads an entry should not have to take a
570
+ * field of a thousand entries to find out.
571
+ */
572
+ async function hydrateReferences(db, collection, item, includeDrafts) {
573
+ if (!item.translationGroup) return;
574
+ const collectionRow = await db.selectFrom("_emdash_collections").select("id").where("slug", "=", collection).executeTakeFirst();
575
+ if (!collectionRow) return;
576
+ const fields = await db.selectFrom("_emdash_fields").select(["slug", "validation"]).where("collection_id", "=", collectionRow.id).where("type", "=", "reference").execute();
577
+ const references = {};
578
+ if (fields.length === 0) {
579
+ item.references = references;
580
+ return;
581
+ }
582
+ const repo = new RelationRepository(db);
583
+ const content = new ContentRepository(db);
584
+ const staged = includeDrafts && item.draftRevisionId ? readStagedReferences((await new RevisionRepository(db).findById(item.draftRevisionId))?.data) : void 0;
585
+ for (const field of fields) {
586
+ let validation = {};
587
+ if (field.validation) {
588
+ let parsed;
589
+ try {
590
+ parsed = JSON.parse(field.validation);
591
+ } catch {
592
+ continue;
593
+ }
594
+ if (isRecord(parsed)) validation = parsed;
595
+ }
596
+ const relation = typeof validation.relation === "string" ? validation.relation : void 0;
597
+ const targetCollection = typeof validation.targetCollection === "string" ? validation.targetCollection : void 0;
598
+ if (!relation || !targetCollection) continue;
599
+ const stagedGroups = staged?.[field.slug];
600
+ if (stagedGroups) {
601
+ const page = pageStagedGroups(stagedGroups);
602
+ references[field.slug] = {
603
+ children: await resolveEntryGroups(content, targetCollection, page.groups, item.locale, includeDrafts, await getReferenceTitleField(db, targetCollection)),
604
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
605
+ };
606
+ continue;
607
+ }
608
+ const onChildSide = validation.relationSide === "child";
609
+ const edges = onChildSide ? await repo.getParentsPage(relation, item.translationGroup) : await repo.getChildrenPage(relation, item.translationGroup);
610
+ const children = await resolveEntries(content, targetCollection, edges.items, (e) => onChildSide ? e.parentGroup : e.childGroup, item.locale, includeDrafts, await getReferenceTitleField(db, targetCollection));
611
+ references[field.slug] = {
612
+ children,
613
+ ...edges.nextCursor ? { nextCursor: edges.nextCursor } : {}
614
+ };
615
+ }
616
+ item.references = references;
617
+ }
618
+ /**
619
+ * Batch-hydrate bylines for multiple items using two bulk queries instead of N+1.
620
+ *
621
+ * Items may live at different locales (e.g. a list endpoint returning the
622
+ * translations of an entry). Group by `item.locale` and call the strict
623
+ * per-locale repo method once per group so each item resolves against its
624
+ * own locale's byline rows.
625
+ */
626
+ async function hydrateBylinesMany(db, collection, items) {
627
+ if (items.length === 0) return;
628
+ const bylineRepo = new BylineRepository(db);
629
+ const localeBuckets = /* @__PURE__ */ new Map();
630
+ for (const item of items) {
631
+ const key = item.locale ?? null;
632
+ const bucket = localeBuckets.get(key);
633
+ if (bucket) bucket.push(item);
634
+ else localeBuckets.set(key, [item]);
635
+ }
636
+ const bylinesByItem = /* @__PURE__ */ new Map();
637
+ const itemsNeedingAuthorCheck = [];
638
+ for (const [locale, bucket] of localeBuckets) {
639
+ const localeOpt = locale ? { locale } : void 0;
640
+ const ids = bucket.map((i) => i.id);
641
+ const credits = await bylineRepo.getContentBylinesMany(collection, ids, localeOpt);
642
+ for (const [id, list] of credits) bylinesByItem.set(id, list);
643
+ for (const item of bucket) {
644
+ if (credits.has(item.id) && credits.get(item.id).length > 0) continue;
645
+ if (item.authorId) itemsNeedingAuthorCheck.push(item);
646
+ }
647
+ }
648
+ const fallbackByItem = /* @__PURE__ */ new Map();
649
+ if (itemsNeedingAuthorCheck.length > 0) {
650
+ const authorBuckets = /* @__PURE__ */ new Map();
651
+ for (const item of itemsNeedingAuthorCheck) {
652
+ if (item.primaryBylineId) continue;
653
+ const key = item.locale ?? null;
654
+ const bucket = authorBuckets.get(key);
655
+ if (bucket) bucket.push(item);
656
+ else authorBuckets.set(key, [item]);
657
+ }
658
+ for (const [locale, bucket] of authorBuckets) {
659
+ const localeOpt = locale ? { locale } : void 0;
660
+ const authorIds = bucket.map((i) => i.authorId).filter((id) => id !== null);
661
+ const uniqueAuthorIds = [...new Set(authorIds)];
662
+ if (uniqueAuthorIds.length === 0) continue;
663
+ const authorMap = await bylineRepo.findByUserIds(uniqueAuthorIds, localeOpt);
664
+ for (const item of bucket) {
665
+ if (!item.authorId) continue;
666
+ const f = authorMap.get(item.authorId);
667
+ if (f) fallbackByItem.set(item.id, f);
668
+ }
669
+ }
670
+ }
671
+ for (const item of items) {
672
+ const explicit = bylinesByItem.get(item.id);
673
+ if (explicit && explicit.length > 0) {
674
+ item.bylines = explicit.map((c) => ({
675
+ ...c,
676
+ source: "explicit"
677
+ }));
678
+ item.byline = explicit[0]?.byline ?? null;
679
+ continue;
680
+ }
681
+ const fallback = fallbackByItem.get(item.id);
682
+ if (fallback) {
683
+ item.bylines = [{
684
+ byline: fallback,
685
+ sortOrder: 0,
686
+ roleLabel: null,
687
+ source: "inferred"
688
+ }];
689
+ item.byline = fallback;
690
+ continue;
691
+ }
692
+ item.bylines = [];
693
+ item.byline = null;
694
+ }
695
+ }
696
+ /**
697
+ * Resolve an identifier (ID or slug) to a real content ID.
698
+ * Returns the ID if found, null if not found.
699
+ * When locale is provided, slug lookups are scoped to that locale.
700
+ */
701
+ async function resolveId(repo, collection, identifier, locale) {
702
+ return (await repo.findByIdOrSlug(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
703
+ }
704
+ /**
705
+ * Resolve an identifier (ID or slug) to a real content ID,
706
+ * including trashed (soft-deleted) items.
707
+ */
708
+ async function resolveIdIncludingTrashed(repo, collection, identifier, locale) {
709
+ return (await repo.findByIdOrSlugIncludingTrashed(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
710
+ }
711
+ /**
712
+ * Resolve the columns a content-list search should match against. Always
713
+ * includes `slug` (a standard column), adds the configured `titleField` plus
714
+ * the `title`/`name` display fields when the collection actually defines them,
715
+ * mirroring the admin's item-title resolution (titleField -> title -> name ->
716
+ * slug), and includes every field explicitly marked searchable. Returning only
717
+ * schema-backed columns avoids "no such column" errors.
718
+ */
719
+ async function resolveSearchColumns(db, collection) {
720
+ const row = await db.selectFrom("_emdash_collections").select(["id", "title_field"]).where("slug", "=", collection).executeTakeFirst();
721
+ if (!row) return ["slug"];
722
+ const fields = await db.selectFrom("_emdash_fields").select(["slug", "searchable"]).where("collection_id", "=", row.id).orderBy("sort_order", "asc").execute();
723
+ const columns = new Set(["slug"]);
724
+ const fieldSlugs = new Set(fields.map((f) => f.slug));
725
+ if (row.title_field && fieldSlugs.has(row.title_field)) columns.add(row.title_field);
726
+ for (const candidate of ["title", "name"]) if (fieldSlugs.has(candidate)) columns.add(candidate);
727
+ for (const field of fields) if (field.searchable === 1) columns.add(field.slug);
728
+ return [...columns];
729
+ }
730
+ /**
731
+ * The keys of `data` that name a storage-less field — a reference field bound
732
+ * to a relation, whose selection lives in the edge table and reaches the API
733
+ * under the separate `references` key.
734
+ *
735
+ * A reference field with no relation still owns its column, so its value in
736
+ * `data` is exactly where it belongs and is not returned here.
737
+ */
738
+ async function storagelessDataKeys(db, collection, data) {
739
+ const collectionRow = await db.selectFrom("_emdash_collections").select("id").where("slug", "=", collection).executeTakeFirst();
740
+ if (!collectionRow) return [];
741
+ const fields = await db.selectFrom("_emdash_fields").select([
742
+ "slug",
743
+ "type",
744
+ "validation"
745
+ ]).where("collection_id", "=", collectionRow.id).execute();
746
+ const storageless = new Set(fields.filter(isStoragelessFieldRow).map((f) => f.slug));
747
+ if (storageless.size === 0) return [];
748
+ return Object.keys(data).filter((key) => storageless.has(key));
749
+ }
750
+ /**
751
+ * Refuse a `data` payload that tries to set a storage-less field.
752
+ *
753
+ * Such a key would otherwise reach the column writer and throw "no such
754
+ * column". Dropping it instead is worse than refusing it: a client that can
755
+ * only write `data` would be told its write succeeded while nothing was linked.
756
+ * On a collection that keeps drafts the key never reaches the column writer at
757
+ * all — it is merged into the draft revision's JSON — so the runtime applies
758
+ * this before staging rather than leaving it to the write below.
759
+ */
760
+ function storagelessDataKeyError(keys) {
761
+ return {
762
+ success: false,
763
+ error: {
764
+ code: "VALIDATION_ERROR",
765
+ message: `Reference fields bound to a relation are set through 'references', not 'data': ${keys.join(", ")}`
766
+ }
767
+ };
768
+ }
769
+ /**
770
+ * The storage-less keys in `data` that an update is actually trying to change.
771
+ *
772
+ * A field bound to a relation after its column existed keeps that column, and
773
+ * every read hands the value frozen in it back under the field's own slug. A
774
+ * read-then-write client — the admin editor among them — therefore echoes a key
775
+ * it never touched, and refusing that would make such an entry unsaveable. An
776
+ * echo asks for nothing; a different value is an attempt to set a selection
777
+ * through the one channel that cannot carry it.
778
+ *
779
+ * A key the entry does not store counts as changed, which is every key of a
780
+ * field that never had a column: there is nothing for such a payload to be
781
+ * echoing, and letting it through would reach the column writer.
782
+ */
783
+ function changedStoragelessDataKeys(storageless, data, stored) {
784
+ return Object.keys(data).filter((key) => storageless.has(key) && (!Object.hasOwn(stored, key) || JSON.stringify(data[key]) !== JSON.stringify(stored[key])));
785
+ }
786
+ /**
787
+ * Decide whether the content-list `q` filter can be served from the
788
+ * collection's FTS5 index instead of a full-scan substring LIKE (#1517).
789
+ *
790
+ * Requires SQLite (FTS5 is SQLite-only), search enabled on the collection,
791
+ * every non-slug display column present in the searchable-field set (or the
792
+ * index would miss matches the LIKE finds), and the index table actually
793
+ * existing.
794
+ */
795
+ async function canUseFtsForListFilter(db, collection, searchColumns) {
796
+ if (!isSqlite(db)) return false;
797
+ const ftsManager = new FTSManager(db);
798
+ if (!(await ftsManager.getSearchConfig(collection))?.enabled) return false;
799
+ const searchable = new Set(await ftsManager.getSearchableFields(collection));
800
+ if (!searchColumns.every((col) => col === "slug" || searchable.has(col))) return false;
801
+ return ftsManager.ftsTableExists(collection);
802
+ }
803
+ /**
804
+ * Create a 301 auto-redirect from an entry's old URL to its new one after a
805
+ * slug change, using the collection's URL pattern. Shared by
806
+ * handleContentUpdate (direct slug edits) and handleContentPublish (slug edits
807
+ * staged as `_slug` in a draft revision, which only land on publish).
808
+ */
809
+ async function createSlugChangeRedirect(db, collection, oldSlug, newSlug, contentId, oldPublishedAt, newPublishedAt) {
810
+ if (await slugStillTaken(db, collection, oldSlug, contentId)) return false;
811
+ const collectionRow = await db.selectFrom("_emdash_collections").select("url_pattern").where("slug", "=", collection).executeTakeFirst();
812
+ const redirect = await new RedirectRepository(db).createAutoRedirect(collection, oldSlug, newSlug, contentId, collectionRow?.url_pattern ?? null, oldPublishedAt, newPublishedAt);
813
+ invalidateRedirectCache();
814
+ return redirect !== null;
815
+ }
816
+ /** Whether a row other than `contentId` still holds `slug` in this collection. */
817
+ async function slugStillTaken(db, collection, slug, contentId) {
818
+ validateIdentifier(collection, "collection slug");
819
+ return (await sql`
820
+ SELECT id FROM ${sql.ref(`ec_${collection}`)}
821
+ WHERE slug = ${slug}
822
+ AND id != ${contentId}
823
+ AND deleted_at IS NULL
824
+ LIMIT 1
825
+ `.execute(db)).rows.length > 0;
826
+ }
827
+ /** Matches a date-only `YYYY-MM-DD` bound (no time component). */
828
+ const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
829
+ /**
830
+ * Normalize a date-range bound to an ISO datetime for lexicographic comparison
831
+ * against stored ISO 8601 timestamps. A bare `YYYY-MM-DD` is widened to the
832
+ * appropriate UTC day boundary so the range stays inclusive: a `start` bound
833
+ * becomes the start of the day and an `end` bound the end of the day.
834
+ * Otherwise a date-only upper bound would exclude every same-day row (since
835
+ * `2024-06-01T12:00:00Z` sorts after `2024-06-01`). Full datetimes pass
836
+ * through unchanged.
837
+ */
838
+ function normalizeDateBound(value, edge) {
839
+ if (!value) return void 0;
840
+ if (!DATE_ONLY_RE.test(value)) return new Date(value).toISOString();
841
+ return edge === "start" ? `${value}T00:00:00.000Z` : `${value}T23:59:59.999Z`;
842
+ }
843
+ /**
844
+ * Build the repository's byline filter from the wire params.
845
+ *
846
+ * `locale` is the locale the list is scoped to, which is the locale an
847
+ * inferred credit has to resolve at — the admin list is always scoped to the
848
+ * locale picked in its switcher.
849
+ */
850
+ function resolveBylineFilter(params, locale) {
851
+ const includeInferred = params.includeInferredBylines === true;
852
+ if (params.bylinesNone) return {
853
+ mode: "none",
854
+ includeInferred,
855
+ locale
856
+ };
857
+ const bylineIds = params.bylines ?? [];
858
+ if (bylineIds.length === 0) return void 0;
859
+ return {
860
+ mode: "any",
861
+ bylineIds,
862
+ includeInferred,
863
+ locale
864
+ };
865
+ }
866
+ /**
867
+ * Create content list handler
868
+ */
869
+ async function handleContentList(db, collection, params) {
870
+ try {
871
+ const repo = new ContentRepository(db);
872
+ const where = {};
873
+ if (params.status) where.status = params.status;
874
+ const locale = params.locale ? resolveConfiguredLocale(params.locale) : void 0;
875
+ if (locale) where.locale = locale;
876
+ if (params.authorId) where.authorId = params.authorId;
877
+ if (params.fieldFilters && Object.keys(params.fieldFilters).length > 0) where.fieldFilters = params.fieldFilters;
878
+ const bylineFilter = resolveBylineFilter(params, locale);
879
+ if (bylineFilter) where.bylineFilter = bylineFilter;
880
+ if (params.dateField && (params.dateFrom || params.dateTo)) where.dateFilter = {
881
+ field: params.dateField,
882
+ from: normalizeDateBound(params.dateFrom, "start"),
883
+ to: normalizeDateBound(params.dateTo, "end")
884
+ };
885
+ const q = params.q?.trim();
886
+ if (q) {
887
+ where.q = q;
888
+ where.searchColumns = await resolveSearchColumns(db, collection);
889
+ where.useFts = await canUseFtsForListFilter(db, collection, where.searchColumns);
890
+ }
891
+ let sortableExtras;
892
+ if (params.orderBy && !isSystemOrderField(params.orderBy)) {
893
+ const coll = await db.selectFrom("_emdash_collections").select(["title_field", "date_field"]).where("slug", "=", collection).executeTakeFirst();
894
+ sortableExtras = [coll?.title_field, coll?.date_field].filter((slug) => !!slug);
895
+ }
896
+ const result = await repo.findMany(collection, {
897
+ cursor: params.cursor,
898
+ limit: params.limit || 50,
899
+ where: Object.keys(where).length > 0 ? where : void 0,
900
+ orderBy: params.orderBy ? {
901
+ field: params.orderBy,
902
+ direction: params.order || "desc"
903
+ } : void 0,
904
+ sortableExtras
905
+ });
906
+ const hasSeo = await collectionHasSeo(db, collection);
907
+ await hydrateSeoMany(db, collection, result.items, hasSeo);
908
+ await hydrateBylinesMany(db, collection, result.items);
909
+ return {
910
+ success: true,
911
+ data: {
912
+ items: result.items,
913
+ nextCursor: result.nextCursor,
914
+ total: result.total
915
+ }
916
+ };
917
+ } catch (error) {
918
+ if (error instanceof InvalidCursorError) return {
919
+ success: false,
920
+ error: {
921
+ code: "INVALID_CURSOR",
922
+ message: error.message
923
+ }
924
+ };
925
+ if (error instanceof ContentCollectionNotFoundError || isMissingTableError(error)) return {
926
+ success: false,
927
+ error: {
928
+ code: "COLLECTION_NOT_FOUND",
929
+ message: `Collection '${collection}' not found`
930
+ }
931
+ };
932
+ if (isMissingColumnError(error, "deleted_at")) return {
933
+ success: false,
934
+ error: {
935
+ code: "COLLECTION_SCHEMA_MISMATCH",
936
+ message: `Collection '${collection}' backing table is missing the 'deleted_at' column`
937
+ }
938
+ };
939
+ if (error instanceof EmDashValidationError) return {
940
+ success: false,
941
+ error: {
942
+ code: "VALIDATION_ERROR",
943
+ message: error.message
944
+ }
945
+ };
946
+ console.error("Content list error:", error);
947
+ return {
948
+ success: false,
949
+ error: {
950
+ code: "CONTENT_LIST_ERROR",
951
+ message: "Failed to list content"
952
+ }
953
+ };
954
+ }
955
+ }
956
+ /**
957
+ * List the distinct authors of a collection's live content.
958
+ *
959
+ * Backs the admin content-list author filter. Unlike `/admin/users` (ADMIN
960
+ * only), this is gated on `content:read`, so any editor can filter by author.
961
+ * Returns only users who have authored at least one non-trashed entry, sorted
962
+ * by display name then email for a stable dropdown order.
963
+ */
964
+ async function handleContentAuthors(db, collection) {
965
+ try {
966
+ const authorIds = await new ContentRepository(db).findDistinctAuthorIds(collection);
967
+ if (authorIds.length === 0) return {
968
+ success: true,
969
+ data: { items: [] }
970
+ };
971
+ return {
972
+ success: true,
973
+ data: { items: (await new UserRepository(db).findByIds(authorIds)).map((u) => ({
974
+ id: u.id,
975
+ name: u.name,
976
+ email: u.email,
977
+ avatarUrl: u.avatarUrl
978
+ })).toSorted((a, b) => (a.name ?? a.email).localeCompare(b.name ?? b.email)) }
979
+ };
980
+ } catch (error) {
981
+ if (isMissingTableError(error)) return {
982
+ success: false,
983
+ error: {
984
+ code: "COLLECTION_NOT_FOUND",
985
+ message: `Collection '${collection}' not found`
986
+ }
987
+ };
988
+ console.error("Content authors error:", error);
989
+ return {
990
+ success: false,
991
+ error: {
992
+ code: "CONTENT_AUTHORS_ERROR",
993
+ message: "Failed to list content authors"
994
+ }
995
+ };
996
+ }
997
+ }
998
+ /**
999
+ * Get single content item
1000
+ */
1001
+ async function handleContentGet(db, collection, id, locale, referenceOptions) {
1002
+ try {
1003
+ const item = await new ContentRepository(db).findByIdOrSlug(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
1004
+ if (!item) return {
1005
+ success: false,
1006
+ error: {
1007
+ code: "NOT_FOUND",
1008
+ message: `Content item not found: ${id}`
1009
+ }
1010
+ };
1011
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1012
+ await hydrateBylines(db, collection, item);
1013
+ if (referenceOptions) await hydrateReferences(db, collection, item, referenceOptions.includeDrafts);
1014
+ return {
1015
+ success: true,
1016
+ data: {
1017
+ item,
1018
+ _rev: encodeRev(item)
1019
+ }
1020
+ };
1021
+ } catch (error) {
1022
+ console.error("Content get error:", error);
1023
+ return {
1024
+ success: false,
1025
+ error: {
1026
+ code: "CONTENT_GET_ERROR",
1027
+ message: "Failed to get content"
1028
+ }
1029
+ };
1030
+ }
1031
+ }
1032
+ /**
1033
+ * Get a content item by id, including trashed items.
1034
+ * Used by restore endpoint for ownership checks on soft-deleted items.
1035
+ */
1036
+ async function handleContentGetIncludingTrashed(db, collection, id, locale) {
1037
+ try {
1038
+ const item = await new ContentRepository(db).findByIdOrSlugIncludingTrashed(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
1039
+ if (!item) return {
1040
+ success: false,
1041
+ error: {
1042
+ code: "NOT_FOUND",
1043
+ message: `Content item not found: ${id}`
1044
+ }
1045
+ };
1046
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1047
+ await hydrateBylines(db, collection, item);
1048
+ return {
1049
+ success: true,
1050
+ data: {
1051
+ item,
1052
+ _rev: encodeRev(item)
1053
+ }
1054
+ };
1055
+ } catch (error) {
1056
+ console.error("Content get error:", error);
1057
+ return {
1058
+ success: false,
1059
+ error: {
1060
+ code: "CONTENT_GET_ERROR",
1061
+ message: "Failed to get content"
1062
+ }
1063
+ };
1064
+ }
1065
+ }
1066
+ /**
1067
+ * Create content item.
1068
+ *
1069
+ * Content + SEO writes are wrapped in a transaction so either both succeed
1070
+ * or neither does. If `body.seo` is provided for a non-SEO collection, the
1071
+ * API returns a validation error rather than silently dropping it.
1072
+ */
1073
+ async function handleContentCreate(db, collection, body) {
1074
+ try {
1075
+ const hasSeo = await collectionHasSeo(db, collection);
1076
+ if (body.seo && !hasSeo) return {
1077
+ success: false,
1078
+ error: {
1079
+ code: "VALIDATION_ERROR",
1080
+ message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
1081
+ }
1082
+ };
1083
+ const storagelessKeys = await storagelessDataKeys(db, collection, body.data);
1084
+ if (storagelessKeys.length > 0) return storagelessDataKeyError(storagelessKeys);
1085
+ const mimeCheck = await validateMediaFields(db, collection, body.data);
1086
+ if (!mimeCheck.success) return mimeCheck;
1087
+ const requiredReferences = await validateRequiredReferencesPresent(db, collection, body.references, body.translationOf);
1088
+ if (!requiredReferences.success) return requiredReferences;
1089
+ const item = await withTransaction(db, async (trx) => {
1090
+ const repo = new ContentRepository(trx);
1091
+ const bylineRepo = new BylineRepository(trx);
1092
+ const inheritedFields = body.translationOf ? (await trx.selectFrom("_emdash_fields as field").innerJoin("_emdash_collections as collection", "collection.id", "field.collection_id").select("field.slug").where("collection.slug", "=", collection).where("field.translatable", "=", 0).execute()).map((field) => field.slug) : [];
1093
+ const referenceWrites = [];
1094
+ if (body.references) {
1095
+ const entryGroup = body.translationOf ? (await repo.findById(collection, body.translationOf))?.translationGroup ?? null : null;
1096
+ for (const [fieldSlug, selectedIds] of Object.entries(body.references)) {
1097
+ const resolved = await resolveReferenceSelectionTargets(trx, collection, fieldSlug, selectedIds, entryGroup);
1098
+ if (!resolved.success) throw Object.assign(new Error(resolved.error.message), { apiError: { code: resolved.error.code } });
1099
+ referenceWrites.push(resolved.data);
1100
+ }
1101
+ }
1102
+ const effectiveLocale = body.locale ? resolveConfiguredLocale(body.locale) : getI18nConfig()?.defaultLocale;
1103
+ let slug = body.slug;
1104
+ if (!slug) {
1105
+ const slugSource = getSlugSource(body.data);
1106
+ if (slugSource) slug = await repo.generateUniqueSlug(collection, slugSource, effectiveLocale);
1107
+ }
1108
+ if (body.status === "published") requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, slug);
1109
+ const created = await repo.create({
1110
+ type: collection,
1111
+ slug,
1112
+ data: body.data,
1113
+ status: body.status || "draft",
1114
+ authorId: body.authorId,
1115
+ locale: effectiveLocale,
1116
+ translationOf: body.translationOf,
1117
+ inheritFields: inheritedFields,
1118
+ createdAt: body.createdAt,
1119
+ publishedAt: body.publishedAt
1120
+ });
1121
+ if (body.bylines !== void 0) created.primaryBylineId = (await bylineRepo.setContentBylines(collection, created.id, body.bylines))[0]?.byline.translationGroup ?? null;
1122
+ if (body.translationOf) {
1123
+ if (body.bylines === void 0) {
1124
+ await bylineRepo.copyContentBylines(collection, body.translationOf, created.id);
1125
+ const source = await repo.findById(collection, body.translationOf);
1126
+ if (source) created.primaryBylineId = source.primaryBylineId;
1127
+ }
1128
+ }
1129
+ await hydrateBylines(trx, collection, created);
1130
+ if (body.seo && hasSeo) created.seo = await new SeoRepository(trx).upsert(collection, created.id, body.seo);
1131
+ else if (hasSeo) created.seo = { ...SEO_DEFAULTS };
1132
+ if (body.taxonomies) await assignTaxonomies(trx, collection, created.id, effectiveLocale, body.taxonomies);
1133
+ if (created.translationGroup) for (const write of referenceWrites) await writeReferenceSelection(trx, {
1134
+ ...write,
1135
+ entryGroup: created.translationGroup
1136
+ });
1137
+ return created;
1138
+ });
1139
+ return {
1140
+ success: true,
1141
+ data: {
1142
+ item,
1143
+ _rev: encodeRev(item)
1144
+ }
1145
+ };
1146
+ } catch (error) {
1147
+ if (hasApiError(error)) return {
1148
+ success: false,
1149
+ error: {
1150
+ code: error.apiError.code,
1151
+ message: error.message
1152
+ }
1153
+ };
1154
+ if (isMissingTableError(error)) return {
1155
+ success: false,
1156
+ error: {
1157
+ code: "COLLECTION_NOT_FOUND",
1158
+ message: `Collection '${collection}' not found`
1159
+ }
1160
+ };
1161
+ if (error instanceof EmDashValidationError) {
1162
+ if (error.message === "Translation source content not found") return {
1163
+ success: false,
1164
+ error: {
1165
+ code: "NOT_FOUND",
1166
+ message: error.message
1167
+ }
1168
+ };
1169
+ return {
1170
+ success: false,
1171
+ error: {
1172
+ code: "VALIDATION_ERROR",
1173
+ message: error.message
1174
+ }
1175
+ };
1176
+ }
1177
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
1178
+ if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
1179
+ if (message.includes("active_tg_locale") || message.includes("translation_group") && message.includes("locale")) return {
1180
+ success: false,
1181
+ error: {
1182
+ code: "CONFLICT",
1183
+ message: `Translation already exists in locale "${body.locale ?? getI18nConfig()?.defaultLocale ?? "en"}" for this content item`
1184
+ }
1185
+ };
1186
+ if (message.includes("slug")) return {
1187
+ success: false,
1188
+ error: {
1189
+ code: "SLUG_CONFLICT",
1190
+ message: `Slug '${body.slug ?? "(auto-generated)"}' already exists in collection '${collection}'`
1191
+ }
1192
+ };
1193
+ return {
1194
+ success: false,
1195
+ error: {
1196
+ code: "CONFLICT",
1197
+ message: "Unique constraint violation"
1198
+ }
1199
+ };
1200
+ }
1201
+ console.error("Content create error:", error);
1202
+ return {
1203
+ success: false,
1204
+ error: {
1205
+ code: "CONTENT_CREATE_ERROR",
1206
+ message: "Failed to create content"
1207
+ }
1208
+ };
1209
+ }
1210
+ }
1211
+ /**
1212
+ * Update content item.
1213
+ * If `_rev` is provided, validates it against the current version before writing.
1214
+ * No `_rev` = blind write (backwards-compatible for admin UI).
1215
+ *
1216
+ * Content + SEO writes are wrapped in a transaction for atomicity.
1217
+ */
1218
+ async function handleContentUpdate(db, collection, id, body) {
1219
+ try {
1220
+ const hasSeo = await collectionHasSeo(db, collection);
1221
+ if (body.seo && !hasSeo) return {
1222
+ success: false,
1223
+ error: {
1224
+ code: "VALIDATION_ERROR",
1225
+ message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
1226
+ }
1227
+ };
1228
+ if (body.data) {
1229
+ const mimeCheck = await validateMediaFields(db, collection, body.data);
1230
+ if (!mimeCheck.success) return mimeCheck;
1231
+ }
1232
+ const repo = new ContentRepository(db);
1233
+ const resolvedId = await resolveId(repo, collection, id, body.locale) ?? id;
1234
+ if (body.data) {
1235
+ const storagelessKeys = await storagelessDataKeys(db, collection, body.data);
1236
+ if (storagelessKeys.length > 0) {
1237
+ const stored = await repo.findById(collection, resolvedId);
1238
+ const changed = changedStoragelessDataKeys(new Set(storagelessKeys), body.data, stored?.data ?? {});
1239
+ if (changed.length > 0) return storagelessDataKeyError(changed);
1240
+ }
1241
+ }
1242
+ let redirectCreated = false;
1243
+ const item = await withTransaction(db, async (trx) => {
1244
+ const trxRepo = new ContentRepository(trx);
1245
+ const bylineRepo = new BylineRepository(trx);
1246
+ const existing = body._rev || body.slug !== void 0 || body.status === "published" ? await trxRepo.findById(collection, resolvedId) : null;
1247
+ if (body._rev) {
1248
+ if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
1249
+ const revCheck = validateRev(body._rev, existing);
1250
+ if (!revCheck.valid) throw Object.assign(new Error(revCheck.message), { apiError: { code: "CONFLICT" } });
1251
+ }
1252
+ let oldSlug;
1253
+ if (body.slug && existing?.slug && existing.slug !== body.slug) oldSlug = existing.slug;
1254
+ if ((body.status ?? existing?.status) === "published") {
1255
+ if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
1256
+ const publishConfig = await getCollectionPublishConfig(trx, collection);
1257
+ const intendedSlug = body.slug !== void 0 ? body.slug : existing.slug;
1258
+ requireRoutablePublishSlug(publishConfig.routable, intendedSlug);
1259
+ }
1260
+ const referenceWrites = [];
1261
+ if (body.references) for (const [fieldSlug, selectedIds] of Object.entries(body.references)) {
1262
+ const resolved = await resolveReferenceSelection(trx, collection, resolvedId, fieldSlug, selectedIds);
1263
+ if (!resolved.success) throw Object.assign(new Error(resolved.error.message), { apiError: { code: resolved.error.code } });
1264
+ referenceWrites.push(resolved.data);
1265
+ }
1266
+ const updated = await trxRepo.update(collection, resolvedId, {
1267
+ data: body.data,
1268
+ slug: body.slug,
1269
+ status: body.status,
1270
+ authorId: body.authorId,
1271
+ publishedAt: body.publishedAt
1272
+ });
1273
+ if (body.bylines !== void 0) updated.primaryBylineId = (await bylineRepo.setContentBylines(collection, resolvedId, body.bylines))[0]?.byline.translationGroup ?? null;
1274
+ if (oldSlug && body.slug) redirectCreated = await createSlugChangeRedirect(trx, collection, oldSlug, body.slug, resolvedId, existing?.publishedAt ?? null, updated.publishedAt ?? null);
1275
+ if (isI18nEnabled() && body.data && updated.translationGroup) await trxRepo.syncNonTranslatableFields(collection, updated.id, updated.translationGroup, body.data);
1276
+ if (body.seo && hasSeo) updated.seo = await new SeoRepository(trx).upsert(collection, resolvedId, body.seo);
1277
+ else if (hasSeo) updated.seo = await new SeoRepository(trx).get(collection, resolvedId);
1278
+ await hydrateBylines(trx, collection, updated);
1279
+ if (body.taxonomies) await assignTaxonomies(trx, collection, resolvedId, updated.locale ?? body.locale, body.taxonomies);
1280
+ for (const write of referenceWrites) await writeReferenceSelection(trx, write);
1281
+ return updated;
1282
+ });
1283
+ if (redirectCreated) after(() => publishRedirectChanges(db));
1284
+ return {
1285
+ success: true,
1286
+ data: {
1287
+ item,
1288
+ _rev: encodeRev(item)
1289
+ }
1290
+ };
1291
+ } catch (error) {
1292
+ if (hasApiError(error)) return {
1293
+ success: false,
1294
+ error: {
1295
+ code: error.apiError.code,
1296
+ message: error.message
1297
+ }
1298
+ };
1299
+ if (isMissingTableError(error)) return {
1300
+ success: false,
1301
+ error: {
1302
+ code: "COLLECTION_NOT_FOUND",
1303
+ message: `Collection '${collection}' not found`
1304
+ }
1305
+ };
1306
+ if (error instanceof EmDashValidationError) return {
1307
+ success: false,
1308
+ error: {
1309
+ code: "VALIDATION_ERROR",
1310
+ message: error.message
1311
+ }
1312
+ };
1313
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
1314
+ if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
1315
+ if (message.includes("slug")) return {
1316
+ success: false,
1317
+ error: {
1318
+ code: "SLUG_CONFLICT",
1319
+ message: `Slug '${body.slug ?? id}' already exists in collection '${collection}'`
1320
+ }
1321
+ };
1322
+ return {
1323
+ success: false,
1324
+ error: {
1325
+ code: "CONFLICT",
1326
+ message: "Unique constraint violation"
1327
+ }
1328
+ };
1329
+ }
1330
+ console.error("Content update error:", error);
1331
+ return {
1332
+ success: false,
1333
+ error: {
1334
+ code: "CONTENT_UPDATE_ERROR",
1335
+ message: "Failed to update content"
1336
+ }
1337
+ };
1338
+ }
1339
+ }
1340
+ /**
1341
+ * Duplicate content item.
1342
+ *
1343
+ * Only copies SEO data if the collection has SEO enabled.
1344
+ * Always returns consistent `seo` shape for SEO-enabled collections.
1345
+ */
1346
+ async function handleContentDuplicate(db, collection, id, authorId) {
1347
+ try {
1348
+ const hasSeo = await collectionHasSeo(db, collection);
1349
+ return {
1350
+ success: true,
1351
+ data: { item: await withTransaction(db, async (trx) => {
1352
+ const repo = new ContentRepository(trx);
1353
+ const bylineRepo = new BylineRepository(trx);
1354
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1355
+ const original = await repo.findById(collection, resolvedId);
1356
+ const dup = await repo.duplicate(collection, resolvedId, authorId);
1357
+ if (original?.translationGroup && dup.translationGroup) {
1358
+ const relations = new RelationRepository(trx);
1359
+ throwIfReferenceLimitRefused(await relations.copyParentEdges(original.translationGroup, dup.translationGroup), "parent");
1360
+ for (const field of (await referenceFieldConstraints(trx, collection)).values()) {
1361
+ if (field.relationSide !== "child") continue;
1362
+ const parents = await relations.getParents(field.relation, original.translationGroup);
1363
+ if (parents.length === 0) continue;
1364
+ throwIfReferenceLimitRefused(await relations.setParents(field.relation, dup.translationGroup, parents.map((parent) => parent.parentGroup)), "child");
1365
+ }
1366
+ }
1367
+ const existingBylines = await bylineRepo.getContentBylines(collection, resolvedId);
1368
+ if (existingBylines.length > 0) await bylineRepo.setContentBylines(collection, dup.id, existingBylines.map((entry) => ({
1369
+ bylineId: entry.byline.id,
1370
+ roleLabel: entry.roleLabel
1371
+ })));
1372
+ if (hasSeo) {
1373
+ const seoRepo = new SeoRepository(trx);
1374
+ await seoRepo.copyForDuplicate(collection, resolvedId, dup.id);
1375
+ dup.seo = await seoRepo.get(collection, dup.id);
1376
+ }
1377
+ await hydrateBylines(trx, collection, dup);
1378
+ return dup;
1379
+ }) }
1380
+ };
1381
+ } catch (err) {
1382
+ if (err instanceof EmDashValidationError) return {
1383
+ success: false,
1384
+ error: {
1385
+ code: "NOT_FOUND",
1386
+ message: err.message
1387
+ }
1388
+ };
1389
+ if (hasApiError(err)) return {
1390
+ success: false,
1391
+ error: {
1392
+ code: err.apiError.code,
1393
+ message: err.message
1394
+ }
1395
+ };
1396
+ console.error("Content duplicate error:", err);
1397
+ return {
1398
+ success: false,
1399
+ error: {
1400
+ code: "CONTENT_DUPLICATE_ERROR",
1401
+ message: "Failed to duplicate content"
1402
+ }
1403
+ };
1404
+ }
1405
+ }
1406
+ /**
1407
+ * Delete content item (soft delete - moves to trash)
1408
+ */
1409
+ async function handleContentDelete(db, collection, id) {
1410
+ try {
1411
+ const result = await withTransaction(db, async (trx) => {
1412
+ const repo = new ContentRepository(trx);
1413
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1414
+ const deleted = await repo.delete(collection, resolvedId);
1415
+ if (deleted) await new EntryLockRepository(trx).releaseEntry(collection, resolvedId);
1416
+ return {
1417
+ id: resolvedId,
1418
+ deleted
1419
+ };
1420
+ });
1421
+ if (!result.deleted) return {
1422
+ success: false,
1423
+ error: {
1424
+ code: "NOT_FOUND",
1425
+ message: `Content item not found: ${id}`
1426
+ }
1427
+ };
1428
+ return {
1429
+ success: true,
1430
+ data: {
1431
+ deleted: true,
1432
+ id: result.id
1433
+ }
1434
+ };
1435
+ } catch (error) {
1436
+ console.error("Content delete error:", error);
1437
+ return {
1438
+ success: false,
1439
+ error: {
1440
+ code: "CONTENT_DELETE_ERROR",
1441
+ message: "Failed to delete content"
1442
+ }
1443
+ };
1444
+ }
1445
+ }
1446
+ /**
1447
+ * Restore content item from trash
1448
+ */
1449
+ async function handleContentRestore(db, collection, id, options = {}) {
1450
+ try {
1451
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1452
+ const item = await withTransaction(db, async (trx) => {
1453
+ const repo = new ContentRepository(trx);
1454
+ const resolvedId = await resolveIdIncludingTrashed(repo, collection, id) ?? id;
1455
+ return repo.restore(collection, resolvedId, expectedRevision);
1456
+ });
1457
+ if (!item) return {
1458
+ success: false,
1459
+ error: {
1460
+ code: "NOT_FOUND",
1461
+ message: `Trashed content item not found: ${id}`
1462
+ }
1463
+ };
1464
+ return {
1465
+ success: true,
1466
+ data: {
1467
+ restored: true,
1468
+ item,
1469
+ _rev: encodeRev(item)
1470
+ }
1471
+ };
1472
+ } catch (error) {
1473
+ if (error instanceof ContentMutationConflictError) return {
1474
+ success: false,
1475
+ error: {
1476
+ code: "CONFLICT",
1477
+ message: error.message
1478
+ }
1479
+ };
1480
+ if (isTranslationLocaleConflict(error, collection)) return {
1481
+ success: false,
1482
+ error: {
1483
+ code: "CONFLICT",
1484
+ message: "An active translation already exists in this locale"
1485
+ }
1486
+ };
1487
+ console.error("Content restore error:", error);
1488
+ return {
1489
+ success: false,
1490
+ error: {
1491
+ code: "CONTENT_RESTORE_ERROR",
1492
+ message: "Failed to restore content"
1493
+ }
1494
+ };
1495
+ }
1496
+ }
1497
+ /**
1498
+ * Permanently delete content item (cannot be undone).
1499
+ * Also cleans up associated SEO data.
1500
+ */
1501
+ async function handleContentPermanentDelete(db, collection, id) {
1502
+ try {
1503
+ const resolvedId = await resolveIdIncludingTrashed(new ContentRepository(db), collection, id) ?? id;
1504
+ if (!await withTransaction(db, async (trx) => {
1505
+ const trxRepo = new ContentRepository(trx);
1506
+ const item = await trxRepo.findByIdIncludingTrashed(collection, resolvedId);
1507
+ if (!item || item.deletedAt === null) return false;
1508
+ const lastOfGroup = item.translationGroup !== null ? !await trxRepo.hasTranslationsIncludingTrashed(collection, item.translationGroup, { excludeId: resolvedId }) : false;
1509
+ if (lastOfGroup && item.translationGroup) await new RelationRepository(trx).clearReferencesForGroup(item.translationGroup);
1510
+ const wasDeleted = await trxRepo.permanentDelete(collection, resolvedId);
1511
+ if (wasDeleted) {
1512
+ await new SeoRepository(trx).delete(collection, resolvedId);
1513
+ await new CommentRepository(trx).deleteByContent(collection, resolvedId);
1514
+ await new RevisionRepository(trx).deleteByEntry(collection, resolvedId);
1515
+ await new EntryLockRepository(trx).releaseEntry(collection, resolvedId);
1516
+ await new BylineRepository(trx).deleteContentBylines(collection, resolvedId);
1517
+ if (lastOfGroup && item.translationGroup) await new TaxonomyRepository(trx).clearEntryGroupTerms(collection, item.translationGroup);
1518
+ }
1519
+ return wasDeleted;
1520
+ })) return {
1521
+ success: false,
1522
+ error: {
1523
+ code: "NOT_FOUND",
1524
+ message: `Content item not found: ${id}`
1525
+ }
1526
+ };
1527
+ return {
1528
+ success: true,
1529
+ data: {
1530
+ deleted: true,
1531
+ id: resolvedId
1532
+ }
1533
+ };
1534
+ } catch (error) {
1535
+ console.error("Content permanent delete error:", error);
1536
+ return {
1537
+ success: false,
1538
+ error: {
1539
+ code: "CONTENT_DELETE_ERROR",
1540
+ message: "Failed to permanently delete content"
1541
+ }
1542
+ };
1543
+ }
1544
+ }
1545
+ /**
1546
+ * List trashed content items
1547
+ */
1548
+ async function handleContentListTrashed(db, collection, options = {}) {
1549
+ try {
1550
+ const result = await new ContentRepository(db).findTrashed(collection, {
1551
+ limit: options.limit,
1552
+ cursor: options.cursor,
1553
+ where: { locale: options.locale }
1554
+ });
1555
+ return {
1556
+ success: true,
1557
+ data: {
1558
+ items: result.items.map((item) => ({
1559
+ id: item.id,
1560
+ type: item.type,
1561
+ slug: item.slug,
1562
+ status: item.status,
1563
+ locale: item.locale,
1564
+ translationGroup: item.translationGroup,
1565
+ data: item.data,
1566
+ authorId: item.authorId,
1567
+ createdAt: item.createdAt,
1568
+ updatedAt: item.updatedAt,
1569
+ publishedAt: item.publishedAt,
1570
+ deletedAt: item.deletedAt
1571
+ })),
1572
+ nextCursor: result.nextCursor
1573
+ }
1574
+ };
1575
+ } catch (error) {
1576
+ if (error instanceof InvalidCursorError) return {
1577
+ success: false,
1578
+ error: {
1579
+ code: "INVALID_CURSOR",
1580
+ message: error.message
1581
+ }
1582
+ };
1583
+ console.error("Content list trashed error:", error);
1584
+ return {
1585
+ success: false,
1586
+ error: {
1587
+ code: "CONTENT_LIST_ERROR",
1588
+ message: "Failed to list trashed content"
1589
+ }
1590
+ };
1591
+ }
1592
+ }
1593
+ /**
1594
+ * Count trashed content items
1595
+ */
1596
+ async function handleContentCountTrashed(db, collection, options = {}) {
1597
+ try {
1598
+ return {
1599
+ success: true,
1600
+ data: { count: await new ContentRepository(db).countTrashed(collection, { locale: options.locale }) }
1601
+ };
1602
+ } catch (error) {
1603
+ console.error("Content count trashed error:", error);
1604
+ return {
1605
+ success: false,
1606
+ error: {
1607
+ code: "CONTENT_COUNT_ERROR",
1608
+ message: "Failed to count trashed content"
1609
+ }
1610
+ };
1611
+ }
1612
+ }
1613
+ /**
1614
+ * Schedule content for future publishing
1615
+ */
1616
+ async function handleContentSchedule(db, collection, id, scheduledAt, currentTime = /* @__PURE__ */ new Date(), _rev) {
1617
+ try {
1618
+ const expectedRevision = decodeRevisionPrecondition(_rev);
1619
+ const item = await withTransaction(db, async (trx) => {
1620
+ const repo = new ContentRepository(trx);
1621
+ const existing = await repo.findByIdOrSlug(collection, id);
1622
+ const resolvedId = existing?.id ?? id;
1623
+ if (existing) requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, existing.slug);
1624
+ return repo.schedule(collection, resolvedId, scheduledAt, currentTime, expectedRevision);
1625
+ });
1626
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1627
+ return {
1628
+ success: true,
1629
+ data: {
1630
+ item,
1631
+ _rev: encodeRev(item)
1632
+ }
1633
+ };
1634
+ } catch (error) {
1635
+ if (error instanceof ContentMutationConflictError) return {
1636
+ success: false,
1637
+ error: {
1638
+ code: "CONFLICT",
1639
+ message: error.message
1640
+ }
1641
+ };
1642
+ if (error instanceof EmDashValidationError) return {
1643
+ success: false,
1644
+ error: {
1645
+ code: "VALIDATION_ERROR",
1646
+ message: error.message
1647
+ }
1648
+ };
1649
+ console.error("Content schedule error:", error);
1650
+ return {
1651
+ success: false,
1652
+ error: {
1653
+ code: "CONTENT_SCHEDULE_ERROR",
1654
+ message: "Failed to schedule content"
1655
+ }
1656
+ };
1657
+ }
1658
+ }
1659
+ /**
1660
+ * Unschedule content (revert to draft)
1661
+ */
1662
+ async function handleContentUnschedule(db, collection, id, options = {}) {
1663
+ try {
1664
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1665
+ const item = await withTransaction(db, async (trx) => {
1666
+ const repo = new ContentRepository(trx);
1667
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1668
+ return repo.unschedule(collection, resolvedId, expectedRevision);
1669
+ });
1670
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1671
+ return {
1672
+ success: true,
1673
+ data: {
1674
+ item,
1675
+ _rev: encodeRev(item)
1676
+ }
1677
+ };
1678
+ } catch (error) {
1679
+ if (error instanceof ContentMutationConflictError) return {
1680
+ success: false,
1681
+ error: {
1682
+ code: "CONFLICT",
1683
+ message: error.message
1684
+ }
1685
+ };
1686
+ if (error instanceof EmDashValidationError) return {
1687
+ success: false,
1688
+ error: {
1689
+ code: "VALIDATION_ERROR",
1690
+ message: error.message
1691
+ }
1692
+ };
1693
+ console.error("Content unschedule error:", error);
1694
+ return {
1695
+ success: false,
1696
+ error: {
1697
+ code: "CONTENT_UNSCHEDULE_ERROR",
1698
+ message: "Failed to unschedule content"
1699
+ }
1700
+ };
1701
+ }
1702
+ }
1703
+ /**
1704
+ * Persist a permanent policy rejection and unschedule the publication.
1705
+ * Databases with transactions commit both writes together. D1 persists the
1706
+ * reason first so a failed option write cannot silently remove the entry from
1707
+ * future sweeps; if unscheduling then fails, the due entry and its dashboard
1708
+ * notice remain available for retry and operator action.
1709
+ */
1710
+ async function handleScheduledPolicyRejection(db, collection, id, options) {
1711
+ try {
1712
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1713
+ const item = await withTransaction(db, async (trx) => {
1714
+ const repo = new ContentRepository(trx);
1715
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1716
+ const optionsRepo = new OptionsRepository(trx);
1717
+ const rejectionKey = scheduledPolicyRejectionKey(collection, resolvedId);
1718
+ const rejectionRevision = await optionsRepo.setVersioned(rejectionKey, {
1719
+ ...options.rejection,
1720
+ id: resolvedId
1721
+ });
1722
+ try {
1723
+ return await repo.unschedule(collection, resolvedId, expectedRevision);
1724
+ } catch (error) {
1725
+ if (error instanceof ContentMutationConflictError) try {
1726
+ await optionsRepo.compareAndDelete(rejectionKey, rejectionRevision);
1727
+ } catch (cleanupError) {
1728
+ console.error("Failed to clear stale scheduled policy rejection:", cleanupError);
1729
+ }
1730
+ throw error;
1731
+ }
1732
+ });
1733
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1734
+ return {
1735
+ success: true,
1736
+ data: {
1737
+ item,
1738
+ _rev: encodeRev(item)
1739
+ }
1740
+ };
1741
+ } catch (error) {
1742
+ if (error instanceof ContentMutationConflictError) return {
1743
+ success: false,
1744
+ error: {
1745
+ code: "CONFLICT",
1746
+ message: error.message
1747
+ }
1748
+ };
1749
+ if (error instanceof EmDashValidationError) return {
1750
+ success: false,
1751
+ error: {
1752
+ code: "VALIDATION_ERROR",
1753
+ message: error.message
1754
+ }
1755
+ };
1756
+ console.error("Scheduled policy rejection error:", error);
1757
+ return {
1758
+ success: false,
1759
+ error: {
1760
+ code: "CONTENT_UNSCHEDULE_ERROR",
1761
+ message: "Failed to record scheduled publication rejection"
1762
+ }
1763
+ };
1764
+ }
1765
+ }
1766
+ /**
1767
+ * Publish content immediately.
1768
+ *
1769
+ * Publication is one atomic content-row statement. On databases that support
1770
+ * transactions, the slug redirect and the locale sync stay grouped with it.
1771
+ */
1772
+ async function handleContentPublish(db, collection, id, options = {}) {
1773
+ try {
1774
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1775
+ let redirectCreated = false;
1776
+ const item = await withTransaction(db, async (trx) => {
1777
+ const repo = new ContentRepository(trx);
1778
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1779
+ const publishConfig = await getCollectionPublishConfig(trx, collection);
1780
+ const existing = await repo.findById(collection, resolvedId);
1781
+ const draftRevision = publishConfig.supportsRevisions && existing?.draftRevisionId ? await new RevisionRepository(trx).findById(existing.draftRevisionId) : void 0;
1782
+ const stagedReferences = draftRevision ? readStagedReferences(draftRevision.data) : void 0;
1783
+ const stagedReferenceBaselines = draftRevision ? readStagedReferenceBaselines(draftRevision.data) : void 0;
1784
+ if (existing?.translationGroup) {
1785
+ const valid = await validateStagedReferences(trx, collection, stagedReferences ?? {}, existing.translationGroup, stagedReferenceBaselines);
1786
+ if (!valid.success) throw Object.assign(new Error(valid.error.message), { apiError: { code: valid.error.code } });
1787
+ if (stagedReferences) {
1788
+ await assertPublishWillNotBeRefused(trx, collection, resolvedId, existing, {
1789
+ stagedSlug: readStagedSlug(draftRevision?.data),
1790
+ requireSlug: publishConfig.routable,
1791
+ requireDue: options.requireScheduledDue,
1792
+ expectedScheduledAt: options.expectedScheduledAt,
1793
+ expectedRevision
1794
+ });
1795
+ await applyStagedReferences(trx, collection, existing.translationGroup, stagedReferences, stagedReferenceBaselines);
1796
+ }
1797
+ }
1798
+ const published = await repo.publish(collection, resolvedId, options.publishedAt, options.requireScheduledDue, options.expectedScheduledAt, publishConfig.supportsRevisions, publishConfig.routable, expectedRevision, options.currentTime);
1799
+ if (publishConfig.supportsRevisions && published.liveRevisionId && published.translationGroup) await recordPublishedReferences(trx, collection, published.liveRevisionId, published.translationGroup);
1800
+ if (existing && isI18nEnabled() && publishConfig.supportsRevisions && published.translationGroup) await repo.syncNonTranslatableFields(collection, published.id, published.translationGroup, published.data, { previous: existing.data });
1801
+ if (existing?.status === "published" && existing.slug && published.slug && existing.slug !== published.slug) redirectCreated = await createSlugChangeRedirect(trx, collection, existing.slug, published.slug, resolvedId, existing.publishedAt ?? null, published.publishedAt ?? null);
1802
+ return published;
1803
+ });
1804
+ if (redirectCreated) after(() => publishRedirectChanges(db));
1805
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1806
+ return {
1807
+ success: true,
1808
+ data: {
1809
+ item,
1810
+ _rev: encodeRev(item)
1811
+ }
1812
+ };
1813
+ } catch (error) {
1814
+ if (hasApiError(error)) return {
1815
+ success: false,
1816
+ error: {
1817
+ code: error.apiError.code,
1818
+ message: error.message
1819
+ }
1820
+ };
1821
+ if (error instanceof ContentMutationConflictError) return {
1822
+ success: false,
1823
+ error: {
1824
+ code: "CONFLICT",
1825
+ message: error.message
1826
+ }
1827
+ };
1828
+ if (error instanceof ScheduledNotDueError) return {
1829
+ success: false,
1830
+ error: {
1831
+ code: "NOT_DUE",
1832
+ message: error.message
1833
+ }
1834
+ };
1835
+ if (error instanceof EmDashValidationError) {
1836
+ const details = error.details;
1837
+ return {
1838
+ success: false,
1839
+ error: {
1840
+ code: typeof details === "object" && details !== null && "code" in details && details.code === "SLUG_CONFLICT" ? "SLUG_CONFLICT" : "VALIDATION_ERROR",
1841
+ message: error.message
1842
+ }
1843
+ };
1844
+ }
1845
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
1846
+ if ((message.includes("unique constraint failed") || message.includes("duplicate key")) && message.includes("slug")) return {
1847
+ success: false,
1848
+ error: {
1849
+ code: "SLUG_CONFLICT",
1850
+ message: `The staged slug is already used by another entry in collection '${collection}'`
1851
+ }
1852
+ };
1853
+ console.error("Content publish error:", error);
1854
+ return {
1855
+ success: false,
1856
+ error: {
1857
+ code: "CONTENT_PUBLISH_ERROR",
1858
+ message: "Failed to publish content"
1859
+ }
1860
+ };
1861
+ }
1862
+ }
1863
+ /**
1864
+ * Unpublish content (revert to draft).
1865
+ *
1866
+ * Wrapped in a transaction — unpublish may create a draft revision
1867
+ * from the live version then update the status, which is multi-step.
1868
+ */
1869
+ async function handleContentUnpublish(db, collection, id, options = {}) {
1870
+ try {
1871
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1872
+ const item = await withTransaction(db, async (trx) => {
1873
+ const repo = new ContentRepository(trx);
1874
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1875
+ return repo.unpublish(collection, resolvedId, expectedRevision);
1876
+ });
1877
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1878
+ return {
1879
+ success: true,
1880
+ data: {
1881
+ item,
1882
+ _rev: encodeRev(item)
1883
+ }
1884
+ };
1885
+ } catch (error) {
1886
+ if (error instanceof ContentMutationConflictError) return {
1887
+ success: false,
1888
+ error: {
1889
+ code: "CONFLICT",
1890
+ message: error.message
1891
+ }
1892
+ };
1893
+ if (error instanceof EmDashValidationError) return {
1894
+ success: false,
1895
+ error: {
1896
+ code: "VALIDATION_ERROR",
1897
+ message: error.message
1898
+ }
1899
+ };
1900
+ console.error("Content unpublish error:", error);
1901
+ return {
1902
+ success: false,
1903
+ error: {
1904
+ code: "CONTENT_UNPUBLISH_ERROR",
1905
+ message: "Failed to unpublish content"
1906
+ }
1907
+ };
1908
+ }
1909
+ }
1910
+ /**
1911
+ * Count scheduled content items
1912
+ */
1913
+ async function handleContentCountScheduled(db, collection) {
1914
+ try {
1915
+ return {
1916
+ success: true,
1917
+ data: { count: await new ContentRepository(db).countScheduled(collection) }
1918
+ };
1919
+ } catch (error) {
1920
+ console.error("Content count scheduled error:", error);
1921
+ return {
1922
+ success: false,
1923
+ error: {
1924
+ code: "CONTENT_COUNT_ERROR",
1925
+ message: "Failed to count scheduled content"
1926
+ }
1927
+ };
1928
+ }
1929
+ }
1930
+ /**
1931
+ * Discard draft changes (revert to live version)
1932
+ */
1933
+ async function handleContentDiscardDraft(db, collection, id, options = {}) {
1934
+ try {
1935
+ const expectedRevision = decodeRevisionPrecondition(options._rev);
1936
+ const item = await withTransaction(db, async (trx) => {
1937
+ const repo = new ContentRepository(trx);
1938
+ const resolvedId = await resolveId(repo, collection, id) ?? id;
1939
+ return repo.discardDraft(collection, resolvedId, expectedRevision);
1940
+ });
1941
+ await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1942
+ return {
1943
+ success: true,
1944
+ data: {
1945
+ item,
1946
+ _rev: encodeRev(item)
1947
+ }
1948
+ };
1949
+ } catch (error) {
1950
+ if (error instanceof ContentMutationConflictError) return {
1951
+ success: false,
1952
+ error: {
1953
+ code: "CONFLICT",
1954
+ message: error.message
1955
+ }
1956
+ };
1957
+ if (error instanceof EmDashValidationError) return {
1958
+ success: false,
1959
+ error: {
1960
+ code: "NOT_FOUND",
1961
+ message: error.message
1962
+ }
1963
+ };
1964
+ console.error("Content discard draft error:", error);
1965
+ return {
1966
+ success: false,
1967
+ error: {
1968
+ code: "CONTENT_DISCARD_DRAFT_ERROR",
1969
+ message: "Failed to discard draft"
1970
+ }
1971
+ };
1972
+ }
1973
+ }
1974
+ /**
1975
+ * Compare live and draft revisions
1976
+ */
1977
+ async function handleContentCompare(db, collection, id) {
1978
+ try {
1979
+ const entry = await new ContentRepository(db).findByIdOrSlug(collection, id);
1980
+ if (!entry) return {
1981
+ success: false,
1982
+ error: {
1983
+ code: "NOT_FOUND",
1984
+ message: `Content item not found: ${id}`
1985
+ }
1986
+ };
1987
+ const revisionRepo = new RevisionRepository(db);
1988
+ const live = entry.liveRevisionId ? await revisionRepo.findById(entry.liveRevisionId) : null;
1989
+ const draft = entry.draftRevisionId ? await revisionRepo.findById(entry.draftRevisionId) : null;
1990
+ const liveReferences = entry.translationGroup ? await liveReferenceSelection(db, collection, entry.translationGroup) : {};
1991
+ const withReferences = (revisionData, staged) => {
1992
+ if (!revisionData) return void 0;
1993
+ const selection = {
1994
+ ...liveReferences,
1995
+ ...staged
1996
+ };
1997
+ if (Object.keys(selection).length === 0) return revisionData;
1998
+ return {
1999
+ ...revisionData,
2000
+ [STAGED_REFERENCES_KEY]: selection
2001
+ };
2002
+ };
2003
+ return {
2004
+ success: true,
2005
+ data: {
2006
+ hasChanges: entry.draftRevisionId !== null && entry.draftRevisionId !== entry.liveRevisionId,
2007
+ live: withReferences(live?.data, {}) ?? null,
2008
+ draft: withReferences(draft?.data, readStagedReferences(draft?.data) ?? {}) ?? null
2009
+ }
2010
+ };
2011
+ } catch (error) {
2012
+ console.error("Content compare error:", error);
2013
+ return {
2014
+ success: false,
2015
+ error: {
2016
+ code: "CONTENT_COMPARE_ERROR",
2017
+ message: "Failed to compare revisions"
2018
+ }
2019
+ };
2020
+ }
2021
+ }
2022
+ /**
2023
+ * Get all translations for a content item.
2024
+ * Returns the item's translation group members with locale and status info.
2025
+ */
2026
+ async function handleContentTranslations(db, collection, id) {
2027
+ try {
2028
+ const repo = new ContentRepository(db);
2029
+ const item = await repo.findByIdOrSlug(collection, id);
2030
+ if (!item) return {
2031
+ success: false,
2032
+ error: {
2033
+ code: "NOT_FOUND",
2034
+ message: `Content item not found: ${id}`
2035
+ }
2036
+ };
2037
+ if (!item.translationGroup) return {
2038
+ success: true,
2039
+ data: {
2040
+ translationGroup: item.id,
2041
+ translations: [{
2042
+ id: item.id,
2043
+ locale: item.locale,
2044
+ slug: item.slug,
2045
+ status: item.status,
2046
+ updatedAt: item.updatedAt
2047
+ }]
2048
+ }
2049
+ };
2050
+ const translations = await repo.findTranslations(collection, item.translationGroup);
2051
+ return {
2052
+ success: true,
2053
+ data: {
2054
+ translationGroup: item.translationGroup,
2055
+ translations: translations.map((t) => ({
2056
+ id: t.id,
2057
+ locale: t.locale,
2058
+ slug: t.slug,
2059
+ status: t.status,
2060
+ updatedAt: t.updatedAt
2061
+ }))
2062
+ }
2063
+ };
2064
+ } catch (error) {
2065
+ if (error instanceof Error) console.error("Content translations error:", error);
2066
+ return {
2067
+ success: false,
2068
+ error: {
2069
+ code: "CONTENT_TRANSLATIONS_ERROR",
2070
+ message: "Failed to get translations"
2071
+ }
2072
+ };
2073
+ }
2074
+ }
2075
+ /**
2076
+ * Resolve a `{ taxonomyName: [slug, ...] }` map to term IDs and replace the
2077
+ * entry's assignments for each named taxonomy.
2078
+ *
2079
+ * Shared by handleContentCreate and handleContentUpdate so both MCP entry
2080
+ * points behave identically. Slug resolution is scoped to `locale`; passing
2081
+ * `undefined` lets `findBySlug` fall back to its default (lowest locale code)
2082
+ * so callers on single-locale sites don't need to know the site's default.
2083
+ *
2084
+ * Throws EmDashValidationError on unknown slug or wrong shape; the calling
2085
+ * handler translates that into a VALIDATION_ERROR response.
2086
+ */
2087
+ async function assignTaxonomies(trx, collection, entryId, locale, taxonomies) {
2088
+ const taxRepo = new TaxonomyRepository(trx);
2089
+ let anyChange = false;
2090
+ for (const [taxonomyName, slugs] of Object.entries(taxonomies)) {
2091
+ if (!Array.isArray(slugs)) throw new EmDashValidationError(`taxonomies.${taxonomyName} must be an array of term slugs`);
2092
+ const termIds = [];
2093
+ for (const slug of slugs) {
2094
+ if (typeof slug !== "string" || slug.length === 0) throw new EmDashValidationError(`taxonomies.${taxonomyName} contains a non-string or empty slug`);
2095
+ const term = await taxRepo.findBySlug(taxonomyName, slug, locale);
2096
+ if (!term) throw new EmDashValidationError(`Unknown taxonomy term: ${taxonomyName}='${slug}'${locale ? ` (locale '${locale}')` : ""}`);
2097
+ termIds.push(term.id);
2098
+ }
2099
+ await taxRepo.setTermsForEntry(collection, entryId, taxonomyName, termIds);
2100
+ anyChange = true;
2101
+ }
2102
+ if (anyChange) invalidateTermCache();
2103
+ }
2104
+
2105
+ //#endregion
2106
+ //#region src/api/handlers/manifest.ts
2107
+ /** Pattern to add spaces before capital letters */
2108
+ const CAMEL_CASE_PATTERN = /([A-Z])/g;
2109
+ const FIRST_CHAR_PATTERN = /^./;
2110
+ /**
2111
+ * Map schema field types to editor field kinds.
2112
+ */
2113
+ /** Field types that can be surfaced as list columns in the admin. */
2114
+ const LIST_COLUMN_FIELD_TYPES = new Set([
2115
+ "string",
2116
+ "number",
2117
+ "integer",
2118
+ "boolean",
2119
+ "datetime",
2120
+ "select",
2121
+ "multiSelect"
2122
+ ]);
2123
+ const FIELD_TYPE_TO_KIND = {
2124
+ string: "string",
2125
+ slug: "string",
2126
+ url: "url",
2127
+ text: "richText",
2128
+ number: "number",
2129
+ integer: "number",
2130
+ boolean: "boolean",
2131
+ datetime: "datetime",
2132
+ select: "select",
2133
+ multiSelect: "multiSelect",
2134
+ portableText: "portableText",
2135
+ image: "image",
2136
+ file: "file",
2137
+ reference: "reference",
2138
+ json: "json",
2139
+ repeater: "repeater",
2140
+ blocks: "blocks"
2141
+ };
2142
+ /**
2143
+ * Generate admin manifest from collections
2144
+ */
2145
+ async function generateManifest(collections, plugins = {}, options = {}) {
2146
+ const manifestCollections = await buildManifestCollections(collections, options.db);
2147
+ return {
2148
+ version: "0.1.0",
2149
+ hash: await hashString(JSON.stringify(manifestCollections)),
2150
+ collections: manifestCollections,
2151
+ plugins
2152
+ };
2153
+ }
2154
+ /**
2155
+ * Build collection descriptors from build-time config plus live database rows.
2156
+ *
2157
+ * Config collections are added first and win on slug conflicts. Runtime/manual
2158
+ * collections have no Zod schema to inspect, so their field descriptors are
2159
+ * synthesized from `_emdash_fields`.
2160
+ */
2161
+ async function buildManifestCollections(collections, db) {
2162
+ const manifestCollections = {};
2163
+ for (const [name, definition] of Object.entries(collections)) {
2164
+ const fields = extractFieldDescriptors(definition.schema);
2165
+ manifestCollections[name] = {
2166
+ label: definition.admin.label,
2167
+ labelSingular: definition.admin.labelSingular || definition.admin.label,
2168
+ supports: definition.admin.supports || [],
2169
+ hasSeo: (definition.admin.supports || []).includes("seo"),
2170
+ routable: definition.admin.routable ?? true,
2171
+ fields
2172
+ };
2173
+ }
2174
+ if (!db) return manifestCollections;
2175
+ try {
2176
+ const storedCollections = await new SchemaRegistry(db).listCollectionsWithFields();
2177
+ const dbCollections = await Promise.all(storedCollections.map((collection) => expandCollectionBlockFields(db, collection)));
2178
+ const cardinality = await relationCardinality(db, dbCollections);
2179
+ for (const collection of dbCollections) {
2180
+ if (manifestCollections[collection.slug]) continue;
2181
+ const fields = {};
2182
+ for (const field of collection.fields) fields[field.slug] = dbFieldDescriptor(field, cardinality);
2183
+ const configuredListColumns = collection.admin?.listColumns ?? [];
2184
+ const fieldTypes = new Map(collection.fields.map((field) => [field.slug, field.type]));
2185
+ const listColumns = [];
2186
+ for (const slug of configuredListColumns) {
2187
+ if (listColumns.includes(slug)) continue;
2188
+ const fieldType = fieldTypes.get(slug);
2189
+ if (!fieldType || !LIST_COLUMN_FIELD_TYPES.has(fieldType)) {
2190
+ console.warn(`EmDash: Ignoring unsupported or unknown list column "${slug}" in collection "${collection.slug}".`);
2191
+ continue;
2192
+ }
2193
+ if (listColumns.length >= MAX_COLLECTION_LIST_COLUMNS) {
2194
+ console.warn(`EmDash: Collection "${collection.slug}" declares more than ${MAX_COLLECTION_LIST_COLUMNS} list columns; extra columns are ignored.`);
2195
+ break;
2196
+ }
2197
+ listColumns.push(slug);
2198
+ }
2199
+ manifestCollections[collection.slug] = {
2200
+ label: collection.label,
2201
+ labelSingular: collection.labelSingular || collection.label,
2202
+ supports: collection.supports || [],
2203
+ hasSeo: collection.hasSeo,
2204
+ urlPattern: collection.urlPattern,
2205
+ routable: collection.routable !== false,
2206
+ titleField: collection.titleField,
2207
+ dateField: collection.dateField,
2208
+ ...collection.hidden ? { hidden: true } : {},
2209
+ ...collection.icon ? { icon: collection.icon } : {},
2210
+ ...collection.group ? { group: collection.group } : {},
2211
+ ...collection.admin?.quickCreate === false ? { quickCreate: false } : {},
2212
+ listColumns: listColumns.length > 0 ? listColumns : void 0,
2213
+ fields
2214
+ };
2215
+ }
2216
+ } catch (error) {
2217
+ console.debug("EmDash: Could not load database collections for manifest:", error);
2218
+ }
2219
+ return manifestCollections;
2220
+ }
2221
+ /**
2222
+ * Extract field descriptors from Zod schema
2223
+ * Note: This is a simplified implementation that handles common types
2224
+ */
2225
+ function extractFieldDescriptors(schema) {
2226
+ const fields = {};
2227
+ const shape = typeof schema._def?.shape === "function" ? schema._def.shape() : schema.shape || {};
2228
+ for (const [name, fieldSchema] of Object.entries(shape)) fields[name] = extractFieldType(name, fieldSchema);
2229
+ return fields;
2230
+ }
2231
+ /**
2232
+ * Extract field type from Zod schema
2233
+ */
2234
+ /** Type guard: check if a value is a non-null object */
2235
+ function isObject(value) {
2236
+ return typeof value === "object" && value !== null;
2237
+ }
2238
+ function extractFieldType(name, schema) {
2239
+ if (!isObject(schema)) return {
2240
+ kind: "string",
2241
+ label: formatLabel(name)
2242
+ };
2243
+ if (schema.isPortableText) return {
2244
+ kind: "portableText",
2245
+ label: formatLabel(name)
2246
+ };
2247
+ if (schema.isImage) return {
2248
+ kind: "image",
2249
+ label: formatLabel(name)
2250
+ };
2251
+ if (schema.isReference) return {
2252
+ kind: "reference",
2253
+ label: formatLabel(name)
2254
+ };
2255
+ const def = isObject(schema._def) ? schema._def : void 0;
2256
+ switch (typeof def?.typeName === "string" ? def.typeName : void 0) {
2257
+ case "ZodString": return {
2258
+ kind: "string",
2259
+ label: formatLabel(name)
2260
+ };
2261
+ case "ZodNumber": return {
2262
+ kind: "number",
2263
+ label: formatLabel(name)
2264
+ };
2265
+ case "ZodBoolean": return {
2266
+ kind: "boolean",
2267
+ label: formatLabel(name)
2268
+ };
2269
+ case "ZodDate": return {
2270
+ kind: "datetime",
2271
+ label: formatLabel(name)
2272
+ };
2273
+ case "ZodEnum": {
2274
+ const values = Array.isArray(def?.values) ? def.values : [];
2275
+ return {
2276
+ kind: "select",
2277
+ label: formatLabel(name),
2278
+ options: values.filter((v) => typeof v === "string").map((v) => ({
2279
+ value: v,
2280
+ label: v.charAt(0).toUpperCase() + v.slice(1)
2281
+ }))
2282
+ };
2283
+ }
2284
+ case "ZodArray": return {
2285
+ kind: "array",
2286
+ label: formatLabel(name)
2287
+ };
2288
+ case "ZodObject": return {
2289
+ kind: "object",
2290
+ label: formatLabel(name)
2291
+ };
2292
+ case "ZodOptional":
2293
+ case "ZodDefault":
2294
+ if (def?.innerType) return extractFieldType(name, def.innerType);
2295
+ return {
2296
+ kind: "string",
2297
+ label: formatLabel(name)
2298
+ };
2299
+ default: return {
2300
+ kind: "string",
2301
+ label: formatLabel(name)
2302
+ };
2303
+ }
2304
+ }
2305
+ /**
2306
+ * The limits of every relation a bound reference field names, by relation slug.
2307
+ *
2308
+ * Empty when nothing is bound, so a site with no reference fields never issues
2309
+ * the query, and empty before migration 086 has created the table.
2310
+ */
2311
+ async function relationCardinality(db, collections) {
2312
+ if (!collections.some((collection) => collection.fields.some(isStoragelessField))) return /* @__PURE__ */ new Map();
2313
+ try {
2314
+ const rows = await db.selectFrom("_emdash_relations").select([
2315
+ "slug",
2316
+ "max_children_per_parent",
2317
+ "max_parents_per_child"
2318
+ ]).execute();
2319
+ return new Map(rows.map((row) => [row.slug, {
2320
+ maxChildrenPerParent: row.max_children_per_parent,
2321
+ maxParentsPerChild: row.max_parents_per_child
2322
+ }]));
2323
+ } catch (error) {
2324
+ if (isMissingTableError(error)) return /* @__PURE__ */ new Map();
2325
+ throw error;
2326
+ }
2327
+ }
2328
+ /**
2329
+ * Whether the editor may select more than one entry for a bound reference
2330
+ * field: the question the relation answers, from the end the field views.
2331
+ *
2332
+ * `validation.multiple` on the field row is a create-time input — it is what
2333
+ * set the relation's limit — and the relation is what the write path enforces.
2334
+ * Reading the field back would let the two disagree, which is what happens when
2335
+ * a later edit rewrites the row's validation without it.
2336
+ */
2337
+ function boundReferenceIsMultiple(validation, cardinality) {
2338
+ return (validation.relationSide === "child" ? cardinality.maxParentsPerChild : cardinality.maxChildrenPerParent) !== 1;
2339
+ }
2340
+ function dbFieldDescriptor(field, cardinality) {
2341
+ const entry = {
2342
+ kind: field.unsupportedType ? "unsupported" : FIELD_TYPE_TO_KIND[field.type],
2343
+ label: field.label,
2344
+ required: field.required,
2345
+ translatable: field.translatable,
2346
+ id: field.id
2347
+ };
2348
+ if (field.unsupportedType) entry.unsupportedType = field.unsupportedType;
2349
+ if (field.blockTypes) entry.blockTypes = field.blockTypes;
2350
+ if (field.blockTypeFingerprint) entry.blockTypeFingerprint = field.blockTypeFingerprint;
2351
+ if (field.widget) entry.widget = field.widget;
2352
+ if (field.options) entry.options = field.options;
2353
+ if (field.validation?.options) entry.options = field.validation.options.map((value) => ({
2354
+ value,
2355
+ label: value.charAt(0).toUpperCase() + value.slice(1)
2356
+ }));
2357
+ if (field.validation) {
2358
+ const validation = { ...field.validation };
2359
+ if (isStoragelessField(field) && field.validation.relation) {
2360
+ const limits = cardinality.get(field.validation.relation);
2361
+ if (limits) validation.multiple = boundReferenceIsMultiple(field.validation, limits);
2362
+ }
2363
+ entry.validation = validation;
2364
+ }
2365
+ return entry;
2366
+ }
2367
+ /**
2368
+ * Format field name as label
2369
+ */
2370
+ function formatLabel(name) {
2371
+ return name.replace(CAMEL_CASE_PATTERN, " $1").replace(FIRST_CHAR_PATTERN, (str) => str.toUpperCase()).trim();
2372
+ }
2373
+
2374
+ //#endregion
2375
+ //#region src/api/handlers/revision.ts
2376
+ /**
2377
+ * List revisions for a content entry
2378
+ */
2379
+ async function handleRevisionList(db, collection, entryId, params = {}) {
2380
+ try {
2381
+ const repo = new RevisionRepository(db);
2382
+ const [items, total] = await Promise.all([repo.findByEntry(collection, entryId, { limit: Math.max(1, Math.min(params.limit || 50, 100)) }), repo.countByEntry(collection, entryId)]);
2383
+ return {
2384
+ success: true,
2385
+ data: {
2386
+ items,
2387
+ total
2388
+ }
2389
+ };
2390
+ } catch {
2391
+ return {
2392
+ success: false,
2393
+ error: {
2394
+ code: "REVISION_LIST_ERROR",
2395
+ message: "Failed to list revisions"
2396
+ }
2397
+ };
2398
+ }
2399
+ }
2400
+ /**
2401
+ * Get a specific revision
2402
+ */
2403
+ async function handleRevisionGet(db, revisionId) {
2404
+ try {
2405
+ const item = await new RevisionRepository(db).findById(revisionId);
2406
+ if (!item) return {
2407
+ success: false,
2408
+ error: {
2409
+ code: "NOT_FOUND",
2410
+ message: `Revision not found: ${revisionId}`
2411
+ }
2412
+ };
2413
+ return {
2414
+ success: true,
2415
+ data: { item }
2416
+ };
2417
+ } catch {
2418
+ return {
2419
+ success: false,
2420
+ error: {
2421
+ code: "REVISION_GET_ERROR",
2422
+ message: "Failed to get revision"
2423
+ }
2424
+ };
2425
+ }
2426
+ }
2427
+ /**
2428
+ * Restore a revision (updates content to this revision's data and creates new revision)
2429
+ */
2430
+ async function handleRevisionRestore(db, revisionId, callerUserId) {
2431
+ try {
2432
+ const revision = await new RevisionRepository(db).findById(revisionId);
2433
+ if (!revision) return {
2434
+ success: false,
2435
+ error: {
2436
+ code: "NOT_FOUND",
2437
+ message: `Revision not found: ${revisionId}`
2438
+ }
2439
+ };
2440
+ const stagedReferences = readStagedReferences(revision.data);
2441
+ if (stagedReferences) {
2442
+ const entry = await new ContentRepository(db).findById(revision.collection, revision.entryId);
2443
+ if (entry?.translationGroup) {
2444
+ const valid = await validateStagedReferences(db, revision.collection, stagedReferences, entry.translationGroup);
2445
+ if (!valid.success) return valid;
2446
+ }
2447
+ }
2448
+ const restoredData = { ...revision.data };
2449
+ delete restoredData[STAGED_REFERENCES_BASELINE_KEY];
2450
+ const { item, revisionId: queuedRevisionId } = await new ContentRepository(db).restoreRevision(revision.collection, revision.entryId, restoredData, callerUserId);
2451
+ if (stagedReferences && item.translationGroup) await applyStagedReferences(db, revision.collection, item.translationGroup, stagedReferences);
2452
+ const pruneRepo = new RevisionRepository(db);
2453
+ after(async () => {
2454
+ try {
2455
+ await pruneRepo.pruneQueuedEntry(revision.collection, revision.entryId, queuedRevisionId, 50);
2456
+ } catch (error) {
2457
+ console.error(`[revisions] Failed to prune revisions for ${revision.collection}/${revision.entryId}:`, error);
2458
+ }
2459
+ });
2460
+ return {
2461
+ success: true,
2462
+ data: {
2463
+ item,
2464
+ _rev: encodeRev(item)
2465
+ }
2466
+ };
2467
+ } catch (error) {
2468
+ if (error instanceof ContentMutationConflictError) return {
2469
+ success: false,
2470
+ error: {
2471
+ code: "CONFLICT",
2472
+ message: error.message
2473
+ }
2474
+ };
2475
+ return {
2476
+ success: false,
2477
+ error: {
2478
+ code: "REVISION_RESTORE_ERROR",
2479
+ message: "Failed to restore revision"
2480
+ }
2481
+ };
2482
+ }
2483
+ }
2484
+
2485
+ //#endregion
2486
+ //#region src/api/handlers/plugin-settings.ts
2487
+ function settingsKey(pluginId, key) {
2488
+ return `plugin:${pluginId}:settings:${key}`;
2489
+ }
2490
+ /**
2491
+ * Resolve a plugin's settings schema from either the configured
2492
+ * (in-process) plugin list or the statically-sandboxed entries.
2493
+ * Returns null when the plugin doesn't exist, undefined-equivalent
2494
+ * empty object when it declares no schema.
2495
+ */
2496
+ function getPluginSettingsSchema(configuredPlugins, sandboxedPluginEntries, pluginId) {
2497
+ const plugin = configuredPlugins.find((p) => p.id === pluginId);
2498
+ if (plugin) return plugin.admin.settingsSchema ?? {};
2499
+ const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
2500
+ if (sandboxed) return sandboxed.settingsSchema ?? {};
2501
+ return null;
2502
+ }
2503
+ /**
2504
+ * Validate a single value against its schema field.
2505
+ * Returns an error message, or null when valid.
2506
+ */
2507
+ function validateValue(key, field, value) {
2508
+ switch (field.type) {
2509
+ case "string":
2510
+ case "secret":
2511
+ case "url":
2512
+ case "email":
2513
+ if (typeof value !== "string") return `Setting "${key}" must be a string`;
2514
+ if (field.type === "url" && value !== "" && !URL.canParse(value)) return `Setting "${key}" must be a valid URL`;
2515
+ if (field.type === "email" && value !== "" && !value.includes("@")) return `Setting "${key}" must be a valid email address`;
2516
+ return null;
2517
+ case "number":
2518
+ if (typeof value !== "number" || Number.isNaN(value)) return `Setting "${key}" must be a number`;
2519
+ if (field.min !== void 0 && value < field.min) return `Setting "${key}" must be at least ${field.min}`;
2520
+ if (field.max !== void 0 && value > field.max) return `Setting "${key}" must be at most ${field.max}`;
2521
+ return null;
2522
+ case "boolean": return typeof value === "boolean" ? null : `Setting "${key}" must be a boolean`;
2523
+ case "select":
2524
+ if (typeof value !== "string" || !field.options.some((o) => o.value === value)) return `Setting "${key}" must be one of the defined options`;
2525
+ return null;
2526
+ default: return `Setting "${key}" has an unknown field type`;
2527
+ }
2528
+ }
2529
+ async function buildSettingsResponse(optionsRepo, pluginId, schema) {
2530
+ const keys = Object.keys(schema);
2531
+ const stored = await optionsRepo.getMany(keys.map((key) => settingsKey(pluginId, key)));
2532
+ const values = {};
2533
+ const secretsSet = {};
2534
+ for (const key of keys) {
2535
+ const field = schema[key];
2536
+ if (!field) continue;
2537
+ const storedValue = stored.get(settingsKey(pluginId, key));
2538
+ if (field.type === "secret") {
2539
+ secretsSet[key] = storedValue !== void 0 && storedValue !== null && storedValue !== "";
2540
+ continue;
2541
+ }
2542
+ if (storedValue !== void 0 && storedValue !== null) values[key] = storedValue;
2543
+ else if ("default" in field && field.default !== void 0) values[key] = field.default;
2544
+ else values[key] = null;
2545
+ }
2546
+ return {
2547
+ schema,
2548
+ values,
2549
+ secretsSet
2550
+ };
2551
+ }
2552
+ /**
2553
+ * Get a plugin's settings (schema + current values, secrets masked)
2554
+ */
2555
+ async function handlePluginSettingsGet(db, pluginId, schema) {
2556
+ try {
2557
+ return {
2558
+ success: true,
2559
+ data: await buildSettingsResponse(new OptionsRepository(db), pluginId, schema)
2560
+ };
2561
+ } catch {
2562
+ return {
2563
+ success: false,
2564
+ error: {
2565
+ code: ErrorCode.PLUGIN_SETTINGS_READ_ERROR,
2566
+ message: "Failed to read plugin settings"
2567
+ }
2568
+ };
2569
+ }
2570
+ }
2571
+ /**
2572
+ * Update a plugin's settings.
2573
+ *
2574
+ * Only keys present in `updates` are written. A `null` value deletes the
2575
+ * stored value (reverting to the schema default). Secret fields are
2576
+ * write-only: they accept a new string value or `null` to clear, and the
2577
+ * response never echoes them back.
2578
+ */
2579
+ async function handlePluginSettingsUpdate(db, pluginId, schema, updates) {
2580
+ try {
2581
+ for (const [key, value] of Object.entries(updates)) {
2582
+ const field = schema[key];
2583
+ if (!field) return {
2584
+ success: false,
2585
+ error: {
2586
+ code: ErrorCode.VALIDATION_ERROR,
2587
+ message: `Unknown setting "${key}" for plugin "${pluginId}"`
2588
+ }
2589
+ };
2590
+ if (value === null) continue;
2591
+ const error = validateValue(key, field, value);
2592
+ if (error) return {
2593
+ success: false,
2594
+ error: {
2595
+ code: ErrorCode.VALIDATION_ERROR,
2596
+ message: error
2597
+ }
2598
+ };
2599
+ }
2600
+ const encodedUpdates = /* @__PURE__ */ new Map();
2601
+ for (const [key, value] of Object.entries(updates)) encodedUpdates.set(key, value === null ? null : await encodePluginSettingValue(pluginId, key, value, schema));
2602
+ return {
2603
+ success: true,
2604
+ data: await withTransaction(db, async (trx) => {
2605
+ const txRepo = new OptionsRepository(trx);
2606
+ for (const [key, value] of encodedUpdates) {
2607
+ if (value === null) await txRepo.delete(settingsKey(pluginId, key));
2608
+ else await txRepo.set(settingsKey(pluginId, key), value);
2609
+ await trx.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).where("collection", "=", "__kv").where("id", "=", `settings:${key}`).execute();
2610
+ }
2611
+ return buildSettingsResponse(txRepo, pluginId, schema);
2612
+ })
2613
+ };
2614
+ } catch (error) {
2615
+ if (error instanceof PluginSettingEncryptionError) return {
2616
+ success: false,
2617
+ error: {
2618
+ code: error.code,
2619
+ message: error.message
2620
+ }
2621
+ };
2622
+ if (error instanceof EmDashSecretsError) return {
2623
+ success: false,
2624
+ error: {
2625
+ code: ErrorCode.PLUGIN_SETTING_ENCRYPTION_KEY_INVALID,
2626
+ message: "EMDASH_ENCRYPTION_KEY is malformed. Restore or correct the configured key from its secret backup. Generate a new key only if no stored plugin setting depends on the lost key."
2627
+ }
2628
+ };
2629
+ return {
2630
+ success: false,
2631
+ error: {
2632
+ code: ErrorCode.PLUGIN_SETTINGS_UPDATE_ERROR,
2633
+ message: "Failed to update plugin settings"
2634
+ }
2635
+ };
2636
+ }
2637
+ }
2638
+
2639
+ //#endregion
2640
+ //#region src/plugins/storage-indexes.ts
2641
+ /**
2642
+ * Generate a deterministic index name.
2643
+ * Unique indexes use a `uidx_` prefix to avoid collisions with regular indexes on the same fields.
2644
+ */
2645
+ function generateIndexName(pluginId, collection, fields, options) {
2646
+ return `${options?.unique ? "uidx" : "idx"}_plugin_${pluginId}_${collection}_${fields.join("_")}`.substring(0, 128);
2647
+ }
2648
+ /**
2649
+ * Generate a Kysely sql expression for creating an expression index.
2650
+ *
2651
+ * Validates all inputs before interpolation. The collection uses the
2652
+ * permissive manifest-key rules rather than SQL-identifier rules — it is
2653
+ * stored as opaque text and only reaches SQL inside the generated index
2654
+ * name — so kebab-case collections index like any other.
2655
+ */
2656
+ function generateCreateIndexSql(db, pluginId, collection, fields, options) {
2657
+ validatePluginIdentifier(pluginId, "plugin ID");
2658
+ validateStorageCollectionName(collection, "collection name");
2659
+ for (const field of fields) validateJsonFieldName(field, "index field name");
2660
+ const indexName = generateIndexName(pluginId, collection, fields, options);
2661
+ const expressions = fields.map((field) => {
2662
+ if (isPostgres(db)) return `(${jsonExtractExpr(db, "data", field)})`;
2663
+ return jsonExtractExpr(db, "data", field);
2664
+ }).join(", ");
2665
+ const createKeyword = options?.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
2666
+ return sql`${sql.raw(createKeyword)} IF NOT EXISTS ${sql.ref(indexName)}
2667
+ ON _plugin_storage(plugin_id, collection, ${sql.raw(expressions)})
2668
+ `;
2669
+ }
2670
+ /**
2671
+ * Generate a Kysely sql expression for dropping an index.
2672
+ *
2673
+ * Uses sql.ref() for safe identifier quoting.
2674
+ */
2675
+ function generateDropIndexSql(indexName) {
2676
+ return sql`DROP INDEX IF EXISTS ${sql.ref(indexName)}`;
2677
+ }
2678
+ /**
2679
+ * Normalize index declarations to arrays of field arrays
2680
+ */
2681
+ function normalizeIndexes(indexes) {
2682
+ return indexes.map((index) => Array.isArray(index) ? index : [index]);
2683
+ }
2684
+ /**
2685
+ * Create all declared indexes for a plugin collection
2686
+ */
2687
+ async function createStorageIndexes(db, pluginId, collection, indexes, options) {
2688
+ const normalized = normalizeIndexes(indexes);
2689
+ const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2690
+ const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2691
+ const allEntries = [...normalized.filter((f) => !uniqueSet.has(f.join(","))).map((fields) => ({
2692
+ fields,
2693
+ unique: false
2694
+ })), ...uniqueNormalized.map((fields) => ({
2695
+ fields,
2696
+ unique: true
2697
+ }))];
2698
+ const created = [];
2699
+ const errors = [];
2700
+ for (const entry of allEntries) {
2701
+ const { fields } = entry;
2702
+ const indexName = generateIndexName(pluginId, collection, fields, { unique: entry.unique });
2703
+ try {
2704
+ await generateCreateIndexSql(db, pluginId, collection, fields, { unique: entry.unique }).execute(db);
2705
+ await db.insertInto("_plugin_indexes").values({
2706
+ plugin_id: pluginId,
2707
+ collection,
2708
+ index_name: indexName,
2709
+ fields: JSON.stringify(fields)
2710
+ }).onConflict((oc) => oc.columns([
2711
+ "plugin_id",
2712
+ "collection",
2713
+ "index_name"
2714
+ ]).doUpdateSet({ fields: JSON.stringify(fields) })).execute();
2715
+ created.push(indexName);
2716
+ } catch (error) {
2717
+ errors.push({
2718
+ index: indexName,
2719
+ error: error instanceof Error ? error.message : String(error)
2720
+ });
2721
+ }
2722
+ }
2723
+ return {
2724
+ created,
2725
+ errors
2726
+ };
2727
+ }
2728
+ /**
2729
+ * Remove indexes that are no longer declared
2730
+ */
2731
+ async function removeOrphanedIndexes(db, pluginId, collection, currentIndexes, options) {
2732
+ const normalized = normalizeIndexes(currentIndexes);
2733
+ const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2734
+ const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2735
+ const currentIndexNames = /* @__PURE__ */ new Set();
2736
+ for (const fields of normalized) if (!uniqueSet.has(fields.join(","))) currentIndexNames.add(generateIndexName(pluginId, collection, fields));
2737
+ for (const fields of uniqueNormalized) currentIndexNames.add(generateIndexName(pluginId, collection, fields, { unique: true }));
2738
+ const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name"]).where("plugin_id", "=", pluginId).where("collection", "=", collection).execute();
2739
+ const removed = [];
2740
+ const errors = [];
2741
+ for (const { index_name } of existingIndexes) if (!currentIndexNames.has(index_name)) try {
2742
+ await generateDropIndexSql(index_name).execute(db);
2743
+ await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).where("collection", "=", collection).where("index_name", "=", index_name).execute();
2744
+ removed.push(index_name);
2745
+ } catch (error) {
2746
+ errors.push({
2747
+ index: index_name,
2748
+ error: error instanceof Error ? error.message : String(error)
2749
+ });
2750
+ }
2751
+ return {
2752
+ removed,
2753
+ errors
2754
+ };
2755
+ }
2756
+ /**
2757
+ * Sync indexes for a plugin collection (create new, remove old)
2758
+ */
2759
+ async function syncStorageIndexes(db, pluginId, collection, indexes, options) {
2760
+ const [createResult, removeResult] = await Promise.all([createStorageIndexes(db, pluginId, collection, indexes, options), removeOrphanedIndexes(db, pluginId, collection, indexes, options)]);
2761
+ return {
2762
+ created: createResult.created,
2763
+ removed: removeResult.removed,
2764
+ errors: [...createResult.errors, ...removeResult.errors]
2765
+ };
2766
+ }
2767
+ /**
2768
+ * Materialize the storage indexes a set of plugins declare in their
2769
+ * manifests. Failures are logged per collection and never thrown — a missing
2770
+ * index affects query performance, not correctness, so it must not fail an
2771
+ * install or a scheduler tick.
2772
+ */
2773
+ async function syncDeclaredStorageIndexes(db, plugins) {
2774
+ for (const plugin of plugins) for (const [collection, config] of Object.entries(plugin.storage ?? {})) try {
2775
+ const result = await syncStorageIndexes(db, plugin.id, collection, config.indexes, { uniqueIndexes: config.uniqueIndexes });
2776
+ for (const failure of result.errors) console.error(`[plugins] Failed to sync storage index ${failure.index} for ${plugin.id}/${collection}: ${failure.error}`);
2777
+ } catch (error) {
2778
+ console.error(`[plugins] Failed to sync storage indexes for ${plugin.id}/${collection}:`, error);
2779
+ }
2780
+ }
2781
+ /**
2782
+ * Remove all indexes for a plugin
2783
+ */
2784
+ async function removeAllPluginIndexes(db, pluginId) {
2785
+ const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name", "collection"]).where("plugin_id", "=", pluginId).execute();
2786
+ const removed = [];
2787
+ const errors = [];
2788
+ for (const { index_name } of existingIndexes) try {
2789
+ await generateDropIndexSql(index_name).execute(db);
2790
+ removed.push(index_name);
2791
+ } catch (error) {
2792
+ errors.push({
2793
+ index: index_name,
2794
+ error: error instanceof Error ? error.message : String(error)
2795
+ });
2796
+ }
2797
+ await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).execute();
2798
+ return {
2799
+ removed,
2800
+ errors
2801
+ };
2802
+ }
2803
+
2804
+ //#endregion
2805
+ //#region src/api/handlers/marketplace.ts
2806
+ /** Semver-like pattern: digits, dots, hyphens, plus signs (e.g. 1.0.0, 1.0.0-beta.1) */
2807
+ const VERSION_PATTERN = /^[a-z0-9][a-z0-9._+-]*$/i;
2808
+ function validateVersion(version) {
2809
+ if (version.includes("..")) throw new Error("Invalid version format");
2810
+ if (!VERSION_PATTERN.test(version)) throw new Error("Invalid version format");
2811
+ }
2812
+ function getClient(marketplaceUrl, siteOrigin) {
2813
+ if (!marketplaceUrl) return null;
2814
+ return createMarketplaceClient(marketplaceUrl, siteOrigin);
2815
+ }
2816
+ function diffCapabilities(oldCaps, newCaps) {
2817
+ const oldNorm = normalizeCapabilities(oldCaps);
2818
+ const newNorm = normalizeCapabilities(newCaps);
2819
+ const oldSet = new Set(oldNorm);
2820
+ const newSet = new Set(newNorm);
2821
+ return {
2822
+ added: newNorm.filter((c) => !oldSet.has(c)),
2823
+ removed: oldNorm.filter((c) => !newSet.has(c))
2824
+ };
2825
+ }
2826
+ /**
2827
+ * Diff route visibility between two manifests.
2828
+ * Returns routes that changed from private to public (newly exposed).
2829
+ */
2830
+ function diffRouteVisibility(oldManifest, newManifest) {
2831
+ const oldPublicRoutes = /* @__PURE__ */ new Set();
2832
+ if (oldManifest) for (const entry of oldManifest.routes) {
2833
+ const normalized = normalizeManifestRoute$1(entry);
2834
+ if (normalized.public === true) oldPublicRoutes.add(normalized.name);
2835
+ }
2836
+ const newlyPublic = [];
2837
+ for (const entry of newManifest.routes) {
2838
+ const normalized = normalizeManifestRoute$1(entry);
2839
+ if (normalized.public === true && !oldPublicRoutes.has(normalized.name)) newlyPublic.push(normalized.name);
2840
+ }
2841
+ return { newlyPublic };
2842
+ }
2843
+ async function resolveVersionMetadata(client, pluginId, pluginDetail, version) {
2844
+ if (pluginDetail.latestVersion?.version === version) return {
2845
+ version: pluginDetail.latestVersion.version,
2846
+ minEmDashVersion: pluginDetail.latestVersion.minEmDashVersion,
2847
+ bundleSize: pluginDetail.latestVersion.bundleSize,
2848
+ checksum: pluginDetail.latestVersion.checksum,
2849
+ changelog: pluginDetail.latestVersion.changelog,
2850
+ capabilities: pluginDetail.latestVersion.capabilities,
2851
+ status: pluginDetail.latestVersion.status,
2852
+ auditVerdict: pluginDetail.latestVersion.audit?.verdict ?? null,
2853
+ imageAuditVerdict: pluginDetail.latestVersion.imageAudit?.verdict ?? null,
2854
+ publishedAt: pluginDetail.latestVersion.publishedAt
2855
+ };
2856
+ return (await client.getVersions(pluginId)).find((v) => v.version === version) ?? null;
2857
+ }
2858
+ /** A null verdict means no audit ran, which is allowed; "fail" and "warn" are not. */
2859
+ function checkAuditVerdict(versionMetadata) {
2860
+ if (versionMetadata.auditVerdict !== "fail" && versionMetadata.auditVerdict !== "warn") return null;
2861
+ return {
2862
+ success: false,
2863
+ error: {
2864
+ code: "AUDIT_FAILED",
2865
+ message: versionMetadata.auditVerdict === "fail" ? "Plugin failed security audit and cannot be installed or updated" : "Plugin audit was inconclusive and cannot be installed or updated until reviewed"
2866
+ }
2867
+ };
2868
+ }
2869
+ function validateBundleIdentity(bundle, pluginId, version) {
2870
+ if (bundle.manifest.id !== pluginId) return {
2871
+ success: false,
2872
+ error: {
2873
+ code: "MANIFEST_MISMATCH",
2874
+ message: `Bundle manifest ID (${bundle.manifest.id}) does not match requested plugin (${pluginId})`
2875
+ }
2876
+ };
2877
+ if (bundle.manifest.version !== version) return {
2878
+ success: false,
2879
+ error: {
2880
+ code: "MANIFEST_VERSION_MISMATCH",
2881
+ message: `Bundle manifest version (${bundle.manifest.version}) does not match requested version (${version})`
2882
+ }
2883
+ };
2884
+ return null;
2885
+ }
2886
+ function bundlePrefix(source, pluginId, version) {
2887
+ return `${source}/${pluginId}/${version}`;
2888
+ }
2889
+ async function storeBundleInR2(storage, pluginId, version, bundle, source = "marketplace") {
2890
+ validatePluginIdentifier(pluginId, "plugin ID");
2891
+ validateVersion(version);
2892
+ const prefix = bundlePrefix(source, pluginId, version);
2893
+ await storage.upload({
2894
+ key: `${prefix}/manifest.json`,
2895
+ body: new TextEncoder().encode(JSON.stringify(bundle.manifest)),
2896
+ contentType: "application/json"
2897
+ });
2898
+ await storage.upload({
2899
+ key: `${prefix}/backend.js`,
2900
+ body: new TextEncoder().encode(bundle.backendCode),
2901
+ contentType: "application/javascript"
2902
+ });
2903
+ if (bundle.adminCode) await storage.upload({
2904
+ key: `${prefix}/admin.js`,
2905
+ body: new TextEncoder().encode(bundle.adminCode),
2906
+ contentType: "application/javascript"
2907
+ });
2908
+ }
2909
+ /** Read a ReadableStream to string */
2910
+ async function streamToText(stream) {
2911
+ return new Response(stream).text();
2912
+ }
2913
+ /**
2914
+ * Load a plugin bundle from site-local R2 storage.
2915
+ *
2916
+ * `source` selects the R2 key prefix: marketplace plugins are stored
2917
+ * under `marketplace/<id>/<version>/`, registry plugins under
2918
+ * `registry/<id>/<version>/`. Defaults to `"marketplace"` for
2919
+ * backwards compatibility with pre-registry call sites.
2920
+ */
2921
+ async function loadBundleFromR2(storage, pluginId, version, source = "marketplace") {
2922
+ validatePluginIdentifier(pluginId, "plugin ID");
2923
+ validateVersion(version);
2924
+ const prefix = bundlePrefix(source, pluginId, version);
2925
+ try {
2926
+ const manifestResult = await storage.download(`${prefix}/manifest.json`);
2927
+ const backendResult = await storage.download(`${prefix}/backend.js`);
2928
+ const manifestText = await streamToText(manifestResult.body);
2929
+ const backendCode = await streamToText(backendResult.body);
2930
+ const parsed = JSON.parse(manifestText);
2931
+ const result = pluginManifestSchema$1.safeParse(parsed);
2932
+ if (!result.success) return null;
2933
+ const manifest = reconcileManifestAccess$1(result.data);
2934
+ warnDeprecatedPluginCapabilities(manifest.id, manifest.capabilities);
2935
+ let adminCode;
2936
+ try {
2937
+ adminCode = await streamToText((await storage.download(`${prefix}/admin.js`)).body);
2938
+ } catch {}
2939
+ return {
2940
+ manifest,
2941
+ backendCode,
2942
+ adminCode
2943
+ };
2944
+ } catch {
2945
+ return null;
2946
+ }
2947
+ }
2948
+ /** Delete a plugin bundle from site-local R2 storage */
2949
+ async function deleteBundleFromR2(storage, pluginId, version, source = "marketplace") {
2950
+ validatePluginIdentifier(pluginId, "plugin ID");
2951
+ validateVersion(version);
2952
+ const prefix = bundlePrefix(source, pluginId, version);
2953
+ for (const file of [
2954
+ "manifest.json",
2955
+ "backend.js",
2956
+ "admin.js"
2957
+ ]) try {
2958
+ await storage.delete(`${prefix}/${file}`);
2959
+ } catch {}
2960
+ }
2961
+ async function rollbackPluginUpdate(db, storage, previousState, failedVersion, source) {
2962
+ if (!storage) return {
2963
+ success: false,
2964
+ error: {
2965
+ code: "STORAGE_NOT_CONFIGURED",
2966
+ message: "Storage is required"
2967
+ }
2968
+ };
2969
+ if (previousState.source !== source) return {
2970
+ success: false,
2971
+ error: {
2972
+ code: "UPDATE_ROLLBACK_CONFLICT",
2973
+ message: "Plugin source changed during update"
2974
+ }
2975
+ };
2976
+ try {
2977
+ if (!await new PluginStateRepository(db).restoreIfVersion(failedVersion, previousState)) return {
2978
+ success: false,
2979
+ error: {
2980
+ code: "UPDATE_ROLLBACK_CONFLICT",
2981
+ message: "Plugin state changed before the failed update could be rolled back"
2982
+ }
2983
+ };
2984
+ await deleteBundleFromR2(storage, previousState.pluginId, failedVersion, source);
2985
+ return {
2986
+ success: true,
2987
+ data: {
2988
+ pluginId: previousState.pluginId,
2989
+ version: previousState.version
2990
+ }
2991
+ };
2992
+ } catch (error) {
2993
+ console.error("Failed to roll back plugin update:", error);
2994
+ return {
2995
+ success: false,
2996
+ error: {
2997
+ code: "UPDATE_ROLLBACK_FAILED",
2998
+ message: "Failed to roll back plugin update"
2999
+ }
3000
+ };
3001
+ }
3002
+ }
3003
+ async function handleMarketplaceInstall(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
3004
+ const client = getClient(marketplaceUrl, opts?.siteOrigin);
3005
+ if (!client) return {
3006
+ success: false,
3007
+ error: {
3008
+ code: "MARKETPLACE_NOT_CONFIGURED",
3009
+ message: "Marketplace is not configured"
3010
+ }
3011
+ };
3012
+ if (!storage) return {
3013
+ success: false,
3014
+ error: {
3015
+ code: "STORAGE_NOT_CONFIGURED",
3016
+ message: "Storage is required for marketplace plugin installation"
3017
+ }
3018
+ };
3019
+ if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
3020
+ success: false,
3021
+ error: {
3022
+ code: "SANDBOX_NOT_AVAILABLE",
3023
+ message: withUnavailableReason("Sandbox runner is required for marketplace plugins", sandboxRunner)
3024
+ }
3025
+ };
3026
+ try {
3027
+ const stateRepo = new PluginStateRepository(db);
3028
+ const existing = await stateRepo.get(pluginId);
3029
+ if (existing && existing.source === "marketplace") return {
3030
+ success: false,
3031
+ error: {
3032
+ code: "ALREADY_INSTALLED",
3033
+ message: `Plugin ${pluginId} is already installed`
3034
+ }
3035
+ };
3036
+ if (opts?.configuredPluginIds?.has(pluginId)) return {
3037
+ success: false,
3038
+ error: {
3039
+ code: "PLUGIN_ID_CONFLICT",
3040
+ message: `Cannot install marketplace plugin "${pluginId}" — a configured plugin with the same ID already exists`
3041
+ }
3042
+ };
3043
+ const pluginDetail = await client.getPlugin(pluginId);
3044
+ const version = opts?.version ?? pluginDetail.latestVersion?.version;
3045
+ if (!version) return {
3046
+ success: false,
3047
+ error: {
3048
+ code: "NO_VERSION",
3049
+ message: `No published versions found for plugin ${pluginId}`
3050
+ }
3051
+ };
3052
+ const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, version);
3053
+ if (!versionMetadata) return {
3054
+ success: false,
3055
+ error: {
3056
+ code: "NO_VERSION",
3057
+ message: `Version ${version} was not found for plugin ${pluginId}`
3058
+ }
3059
+ };
3060
+ const auditError = checkAuditVerdict(versionMetadata);
3061
+ if (auditError) return auditError;
3062
+ const bundle = await client.downloadBundle(pluginId, version);
3063
+ if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
3064
+ success: false,
3065
+ error: {
3066
+ code: "CHECKSUM_MISMATCH",
3067
+ message: "Bundle checksum does not match marketplace record. Download may be corrupted."
3068
+ }
3069
+ };
3070
+ const bundleIdentityError = validateBundleIdentity(bundle, pluginId, version);
3071
+ if (bundleIdentityError) return bundleIdentityError;
3072
+ const routeVisibilityChanges = diffRouteVisibility(void 0, bundle.manifest);
3073
+ const hasPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
3074
+ const publicRoutes = routeVisibilityChanges.newlyPublic.toSorted();
3075
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).toSorted();
3076
+ const mcpTools = bundle.manifest.mcp?.tools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
3077
+ const consentDetails = {
3078
+ routeVisibilityChanges: hasPublicRoutes ? { newlyPublic: publicRoutes } : void 0,
3079
+ mcpTools
3080
+ };
3081
+ if (hasPublicRoutes && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(publicRoutes)) return {
3082
+ success: false,
3083
+ error: {
3084
+ code: "ROUTE_VISIBILITY_ESCALATION",
3085
+ message: "Plugin install exposes public (unauthenticated) routes",
3086
+ details: consentDetails
3087
+ }
3088
+ };
3089
+ if ((mcpTools?.length ?? 0) > 0 && !opts?.confirmMcpTools) return {
3090
+ success: false,
3091
+ error: {
3092
+ code: "MCP_TOOL_CONSENT_REQUIRED",
3093
+ message: "Plugin MCP tools require explicit consent",
3094
+ details: consentDetails
3095
+ }
3096
+ };
3097
+ await storeBundleInR2(storage, pluginId, version, bundle);
3098
+ await stateRepo.upsert(pluginId, version, "active", {
3099
+ source: "marketplace",
3100
+ marketplaceVersion: version,
3101
+ displayName: pluginDetail.name,
3102
+ description: pluginDetail.description ?? void 0
3103
+ });
3104
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
3105
+ client.reportInstall(pluginId, version).catch(() => {});
3106
+ return {
3107
+ success: true,
3108
+ data: {
3109
+ pluginId,
3110
+ version,
3111
+ capabilities: bundle.manifest.capabilities
3112
+ }
3113
+ };
3114
+ } catch (err) {
3115
+ if (err instanceof MarketplaceUnavailableError) return {
3116
+ success: false,
3117
+ error: {
3118
+ code: "MARKETPLACE_UNAVAILABLE",
3119
+ message: "Plugin marketplace is currently unavailable"
3120
+ }
3121
+ };
3122
+ if (err instanceof MarketplaceError) return {
3123
+ success: false,
3124
+ error: {
3125
+ code: err.code ?? "MARKETPLACE_ERROR",
3126
+ message: err.message
3127
+ }
3128
+ };
3129
+ if (err instanceof EmDashStorageError) return {
3130
+ success: false,
3131
+ error: {
3132
+ code: err.code ?? "STORAGE_ERROR",
3133
+ message: "Storage error while installing plugin"
3134
+ }
3135
+ };
3136
+ if (err && typeof err === "object" && "code" in err) {
3137
+ const code = err.code;
3138
+ if (typeof code === "string" && code.trim()) return {
3139
+ success: false,
3140
+ error: {
3141
+ code,
3142
+ message: "Failed to install plugin from marketplace"
3143
+ }
3144
+ };
3145
+ }
3146
+ console.error("Failed to install marketplace plugin:", err);
3147
+ return {
3148
+ success: false,
3149
+ error: {
3150
+ code: "INSTALL_FAILED",
3151
+ message: "Failed to install plugin from marketplace"
3152
+ }
3153
+ };
3154
+ }
3155
+ }
3156
+ async function handleMarketplaceUpdate(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
3157
+ const client = getClient(marketplaceUrl);
3158
+ if (!client) return {
3159
+ success: false,
3160
+ error: {
3161
+ code: "MARKETPLACE_NOT_CONFIGURED",
3162
+ message: "Marketplace is not configured"
3163
+ }
3164
+ };
3165
+ if (!storage) return {
3166
+ success: false,
3167
+ error: {
3168
+ code: "STORAGE_NOT_CONFIGURED",
3169
+ message: "Storage is required"
3170
+ }
3171
+ };
3172
+ if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
3173
+ success: false,
3174
+ error: {
3175
+ code: "SANDBOX_NOT_AVAILABLE",
3176
+ message: withUnavailableReason("Sandbox runner is required", sandboxRunner)
3177
+ }
3178
+ };
3179
+ try {
3180
+ const stateRepo = new PluginStateRepository(db);
3181
+ const existing = await stateRepo.get(pluginId);
3182
+ if (!existing || existing.source !== "marketplace") return {
3183
+ success: false,
3184
+ error: {
3185
+ code: "NOT_FOUND",
3186
+ message: `No marketplace plugin found: ${pluginId}`
3187
+ }
3188
+ };
3189
+ const oldVersion = existing.marketplaceVersion ?? existing.version;
3190
+ const pluginDetail = await client.getPlugin(pluginId);
3191
+ const newVersion = opts?.version ?? pluginDetail.latestVersion?.version;
3192
+ if (!newVersion) return {
3193
+ success: false,
3194
+ error: {
3195
+ code: "NO_VERSION",
3196
+ message: "No newer version available"
3197
+ }
3198
+ };
3199
+ if (newVersion === oldVersion) return {
3200
+ success: false,
3201
+ error: {
3202
+ code: "ALREADY_UP_TO_DATE",
3203
+ message: "Plugin is already up to date"
3204
+ }
3205
+ };
3206
+ const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, newVersion);
3207
+ if (!versionMetadata) return {
3208
+ success: false,
3209
+ error: {
3210
+ code: "NO_VERSION",
3211
+ message: `Version ${newVersion} was not found for plugin ${pluginId}`
3212
+ }
3213
+ };
3214
+ const auditError = checkAuditVerdict(versionMetadata);
3215
+ if (auditError) return auditError;
3216
+ const bundle = await client.downloadBundle(pluginId, newVersion);
3217
+ if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
3218
+ success: false,
3219
+ error: {
3220
+ code: "CHECKSUM_MISMATCH",
3221
+ message: "Bundle checksum does not match marketplace record. Download may be corrupted."
3222
+ }
3223
+ };
3224
+ const bundleIdentityError = validateBundleIdentity(bundle, pluginId, newVersion);
3225
+ if (bundleIdentityError) return bundleIdentityError;
3226
+ const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion);
3227
+ const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
3228
+ const hasEscalation = capabilityChanges.added.length > 0;
3229
+ const routeVisibilityChanges = diffRouteVisibility(oldBundle?.manifest, bundle.manifest);
3230
+ const hasNewPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
3231
+ const newlyPublicRoutes = routeVisibilityChanges.newlyPublic.toSorted();
3232
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).toSorted();
3233
+ const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3234
+ const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3235
+ const hasMcpChanges = JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools);
3236
+ const mcpTools = newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
3237
+ const consentDetails = {
3238
+ capabilityChanges,
3239
+ routeVisibilityChanges: hasNewPublicRoutes ? { newlyPublic: newlyPublicRoutes } : void 0,
3240
+ mcpTools: hasMcpChanges ? mcpTools : void 0
3241
+ };
3242
+ if (hasEscalation && !opts?.confirmCapabilityChanges) return {
3243
+ success: false,
3244
+ error: {
3245
+ code: "CAPABILITY_ESCALATION",
3246
+ message: "Plugin update requires new capabilities",
3247
+ details: consentDetails
3248
+ }
3249
+ };
3250
+ if (hasNewPublicRoutes && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(newlyPublicRoutes)) return {
3251
+ success: false,
3252
+ error: {
3253
+ code: "ROUTE_VISIBILITY_ESCALATION",
3254
+ message: "Plugin update exposes new public (unauthenticated) routes",
3255
+ details: consentDetails
3256
+ }
3257
+ };
3258
+ if (hasMcpChanges && !opts?.confirmMcpTools) return {
3259
+ success: false,
3260
+ error: {
3261
+ code: "MCP_TOOL_CONSENT_REQUIRED",
3262
+ message: "Plugin update changes its MCP tools",
3263
+ details: consentDetails
3264
+ }
3265
+ };
3266
+ await storeBundleInR2(storage, pluginId, newVersion, bundle);
3267
+ await stateRepo.upsert(pluginId, newVersion, "active", {
3268
+ source: "marketplace",
3269
+ marketplaceVersion: newVersion,
3270
+ displayName: pluginDetail.name,
3271
+ description: pluginDetail.description ?? void 0,
3272
+ mcpToolsEnabled: false,
3273
+ mcpToolsConsent: null
3274
+ });
3275
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
3276
+ return {
3277
+ success: true,
3278
+ data: {
3279
+ pluginId,
3280
+ oldVersion,
3281
+ newVersion,
3282
+ capabilityChanges,
3283
+ routeVisibilityChanges: hasNewPublicRoutes ? routeVisibilityChanges : void 0
3284
+ }
3285
+ };
3286
+ } catch (err) {
3287
+ if (err instanceof MarketplaceUnavailableError) return {
3288
+ success: false,
3289
+ error: {
3290
+ code: "MARKETPLACE_UNAVAILABLE",
3291
+ message: "Marketplace is unavailable"
3292
+ }
3293
+ };
3294
+ if (err instanceof MarketplaceError) return {
3295
+ success: false,
3296
+ error: {
3297
+ code: err.code ?? "MARKETPLACE_ERROR",
3298
+ message: err.message
3299
+ }
3300
+ };
3301
+ console.error("Failed to update marketplace plugin:", err);
3302
+ return {
3303
+ success: false,
3304
+ error: {
3305
+ code: "UPDATE_FAILED",
3306
+ message: "Failed to update plugin"
3307
+ }
3308
+ };
3309
+ }
3310
+ }
3311
+ async function handleMarketplaceUninstall(db, storage, pluginId, opts) {
3312
+ try {
3313
+ const stateRepo = new PluginStateRepository(db);
3314
+ const existing = await stateRepo.get(pluginId);
3315
+ if (!existing || existing.source !== "marketplace") return {
3316
+ success: false,
3317
+ error: {
3318
+ code: "NOT_FOUND",
3319
+ message: `No marketplace plugin found: ${pluginId}`
3320
+ }
3321
+ };
3322
+ const version = existing.marketplaceVersion ?? existing.version;
3323
+ await opts?.beforeDelete?.();
3324
+ let dataDeleted = false;
3325
+ if (opts?.deleteData) try {
3326
+ await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
3327
+ dataDeleted = true;
3328
+ } catch {}
3329
+ try {
3330
+ await removeAllPluginIndexes(db, pluginId);
3331
+ } catch {}
3332
+ await stateRepo.delete(pluginId);
3333
+ if (storage) await deleteBundleFromR2(storage, pluginId, version);
3334
+ return {
3335
+ success: true,
3336
+ data: {
3337
+ pluginId,
3338
+ dataDeleted
3339
+ }
3340
+ };
3341
+ } catch (err) {
3342
+ console.error("Failed to uninstall marketplace plugin:", err);
3343
+ return {
3344
+ success: false,
3345
+ error: {
3346
+ code: "UNINSTALL_FAILED",
3347
+ message: "Failed to uninstall plugin"
3348
+ }
3349
+ };
3350
+ }
3351
+ }
3352
+ async function handleMarketplaceUpdateCheck(db, marketplaceUrl) {
3353
+ const client = getClient(marketplaceUrl);
3354
+ if (!client) return {
3355
+ success: false,
3356
+ error: {
3357
+ code: "MARKETPLACE_NOT_CONFIGURED",
3358
+ message: "Marketplace is not configured"
3359
+ }
3360
+ };
3361
+ try {
3362
+ const marketplacePlugins = await new PluginStateRepository(db).getMarketplacePlugins();
3363
+ const items = [];
3364
+ for (const plugin of marketplacePlugins) try {
3365
+ const detail = await client.getPlugin(plugin.pluginId);
3366
+ const latest = detail.latestVersion?.version;
3367
+ const installed = plugin.marketplaceVersion ?? plugin.version;
3368
+ if (!latest) continue;
3369
+ const hasUpdate = latest !== installed;
3370
+ let capabilityChanges;
3371
+ let hasCapabilityChanges = false;
3372
+ if (hasUpdate && detail.latestVersion) {
3373
+ capabilityChanges = diffCapabilities(detail.capabilities ?? [], detail.latestVersion.capabilities ?? []);
3374
+ hasCapabilityChanges = capabilityChanges.added.length > 0 || capabilityChanges.removed.length > 0;
3375
+ }
3376
+ items.push({
3377
+ pluginId: plugin.pluginId,
3378
+ installed,
3379
+ latest: latest ?? installed,
3380
+ hasUpdate,
3381
+ hasCapabilityChanges,
3382
+ capabilityChanges: hasCapabilityChanges ? capabilityChanges : void 0,
3383
+ hasRouteVisibilityChanges: false
3384
+ });
3385
+ } catch (err) {
3386
+ console.warn(`Failed to check updates for ${plugin.pluginId}:`, err);
3387
+ }
3388
+ return {
3389
+ success: true,
3390
+ data: { items }
3391
+ };
3392
+ } catch (err) {
3393
+ if (err instanceof MarketplaceUnavailableError) return {
3394
+ success: false,
3395
+ error: {
3396
+ code: "MARKETPLACE_UNAVAILABLE",
3397
+ message: "Marketplace is unavailable"
3398
+ }
3399
+ };
3400
+ console.error("Failed to check marketplace updates:", err);
3401
+ return {
3402
+ success: false,
3403
+ error: {
3404
+ code: "UPDATE_CHECK_FAILED",
3405
+ message: "Failed to check for updates"
3406
+ }
3407
+ };
3408
+ }
3409
+ }
3410
+ async function handleMarketplaceSearch(marketplaceUrl, query, opts) {
3411
+ const client = getClient(marketplaceUrl);
3412
+ if (!client) return {
3413
+ success: false,
3414
+ error: {
3415
+ code: "MARKETPLACE_NOT_CONFIGURED",
3416
+ message: "Marketplace is not configured"
3417
+ }
3418
+ };
3419
+ try {
3420
+ return {
3421
+ success: true,
3422
+ data: await client.search(query, opts)
3423
+ };
3424
+ } catch (err) {
3425
+ if (err instanceof MarketplaceUnavailableError) return {
3426
+ success: false,
3427
+ error: {
3428
+ code: "MARKETPLACE_UNAVAILABLE",
3429
+ message: "Marketplace is unavailable"
3430
+ }
3431
+ };
3432
+ console.error("Failed to search marketplace:", err);
3433
+ return {
3434
+ success: false,
3435
+ error: {
3436
+ code: "SEARCH_FAILED",
3437
+ message: "Failed to search marketplace"
3438
+ }
3439
+ };
3440
+ }
3441
+ }
3442
+ async function handleMarketplaceGetPlugin(marketplaceUrl, pluginId) {
3443
+ const client = getClient(marketplaceUrl);
3444
+ if (!client) return {
3445
+ success: false,
3446
+ error: {
3447
+ code: "MARKETPLACE_NOT_CONFIGURED",
3448
+ message: "Marketplace is not configured"
3449
+ }
3450
+ };
3451
+ try {
3452
+ return {
3453
+ success: true,
3454
+ data: await client.getPlugin(pluginId)
3455
+ };
3456
+ } catch (err) {
3457
+ if (err instanceof MarketplaceError && err.status === 404) return {
3458
+ success: false,
3459
+ error: {
3460
+ code: "NOT_FOUND",
3461
+ message: `Plugin not found: ${pluginId}`
3462
+ }
3463
+ };
3464
+ if (err instanceof MarketplaceUnavailableError) return {
3465
+ success: false,
3466
+ error: {
3467
+ code: "MARKETPLACE_UNAVAILABLE",
3468
+ message: "Marketplace is unavailable"
3469
+ }
3470
+ };
3471
+ console.error("Failed to get marketplace plugin:", err);
3472
+ return {
3473
+ success: false,
3474
+ error: {
3475
+ code: "GET_PLUGIN_FAILED",
3476
+ message: "Failed to get plugin details"
3477
+ }
3478
+ };
3479
+ }
3480
+ }
3481
+ async function handleThemeSearch(marketplaceUrl, query, opts) {
3482
+ const client = getClient(marketplaceUrl);
3483
+ if (!client) return {
3484
+ success: false,
3485
+ error: {
3486
+ code: "MARKETPLACE_NOT_CONFIGURED",
3487
+ message: "Marketplace is not configured"
3488
+ }
3489
+ };
3490
+ try {
3491
+ return {
3492
+ success: true,
3493
+ data: await client.searchThemes(query, opts)
3494
+ };
3495
+ } catch (err) {
3496
+ if (err instanceof MarketplaceUnavailableError) return {
3497
+ success: false,
3498
+ error: {
3499
+ code: "MARKETPLACE_UNAVAILABLE",
3500
+ message: "Marketplace is unavailable"
3501
+ }
3502
+ };
3503
+ console.error("Failed to search themes:", err);
3504
+ return {
3505
+ success: false,
3506
+ error: {
3507
+ code: "THEME_SEARCH_FAILED",
3508
+ message: "Failed to search themes"
3509
+ }
3510
+ };
3511
+ }
3512
+ }
3513
+ async function handleThemeGetDetail(marketplaceUrl, themeId) {
3514
+ const client = getClient(marketplaceUrl);
3515
+ if (!client) return {
3516
+ success: false,
3517
+ error: {
3518
+ code: "MARKETPLACE_NOT_CONFIGURED",
3519
+ message: "Marketplace is not configured"
3520
+ }
3521
+ };
3522
+ try {
3523
+ return {
3524
+ success: true,
3525
+ data: await client.getTheme(themeId)
3526
+ };
3527
+ } catch (err) {
3528
+ if (err instanceof MarketplaceError && err.status === 404) return {
3529
+ success: false,
3530
+ error: {
3531
+ code: "NOT_FOUND",
3532
+ message: `Theme not found: ${themeId}`
3533
+ }
3534
+ };
3535
+ if (err instanceof MarketplaceUnavailableError) return {
3536
+ success: false,
3537
+ error: {
3538
+ code: "MARKETPLACE_UNAVAILABLE",
3539
+ message: "Marketplace is unavailable"
3540
+ }
3541
+ };
3542
+ console.error("Failed to get marketplace theme:", err);
3543
+ return {
3544
+ success: false,
3545
+ error: {
3546
+ code: "GET_THEME_FAILED",
3547
+ message: "Failed to get theme details"
3548
+ }
3549
+ };
3550
+ }
3551
+ }
3552
+
3553
+ //#endregion
3554
+ //#region ../registry-verification/dist/bundle.js
3555
+ /** Maximum accepted gzip payload size. */
3556
+ const MAX_BUNDLE_COMPRESSED_BYTES = 384 * 1024;
3557
+ /** Maximum aggregate size of regular-file contents. */
3558
+ const MAX_BUNDLE_SIZE = 256 * 1024;
3559
+ /** Maximum size of one regular file. */
3560
+ const MAX_BUNDLE_FILE_BYTES = 128 * 1024;
3561
+ /** Maximum number of regular files. */
3562
+ const MAX_BUNDLE_FILE_COUNT = 20;
3563
+ /** Maximum total tar entries, including harmless directory entries. */
3564
+ const MAX_BUNDLE_TAR_ENTRY_COUNT = 32;
3565
+ /**
3566
+ * Maximum tar stream size after decompression. This includes USTAR headers,
3567
+ * file padding, and the end marker in addition to the regular-file contents.
3568
+ */
3569
+ const MAX_BUNDLE_DECOMPRESSED_BYTES = MAX_BUNDLE_SIZE + MAX_BUNDLE_TAR_ENTRY_COUNT * 512 + MAX_BUNDLE_FILE_COUNT * 511 + 2 * 512;
3570
+ const TAR_BLOCK_BYTES = 512;
3571
+ const TAR_END_BYTES = TAR_BLOCK_BYTES * 2;
3572
+ const OCTAL_PATTERN = /^[0-7]+$/;
3573
+ const WINDOWS_DRIVE_PATTERN = /^[a-zA-Z]:/;
3574
+ const decoder = new TextDecoder("utf-8", {
3575
+ fatal: true,
3576
+ ignoreBOM: false
3577
+ });
3578
+ async function validatePluginBundle(compressed, options = {}) {
3579
+ if (compressed.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) return verificationError("BUNDLE_COMPRESSED_SIZE_EXCEEDED", "The compressed plugin bundle exceeds the size limit.");
3580
+ const decompressed = await decompressBundle(compressed);
3581
+ if (!decompressed.success) return decompressed;
3582
+ const files = parseTar(decompressed.value);
3583
+ if (!files.success) return files;
3584
+ const manifestFile = files.value.get("manifest.json");
3585
+ if (!manifestFile) return verificationError("BUNDLE_MISSING_MANIFEST", "The plugin bundle is missing manifest.json.");
3586
+ const backend = files.value.get("backend.js");
3587
+ if (!backend) return verificationError("BUNDLE_MISSING_BACKEND", "The plugin bundle is missing backend.js.");
3588
+ let parsed;
3589
+ try {
3590
+ parsed = JSON.parse(decoder.decode(manifestFile.data));
3591
+ } catch {
3592
+ return verificationError("BUNDLE_INVALID_MANIFEST", "The plugin bundle manifest is not valid JSON.");
3593
+ }
3594
+ const validated = pluginManifestSchema.safeParse(parsed);
3595
+ if (!validated.success) return verificationError("BUNDLE_INVALID_MANIFEST", "The plugin bundle manifest failed schema validation.");
3596
+ const manifest = reconcileManifestAccess(validated.data);
3597
+ if (options.expectedSlug !== void 0 && manifest.id !== options.expectedSlug) return verificationError("BUNDLE_ID_MISMATCH", "The plugin bundle manifest id does not match the expected plugin.");
3598
+ if (options.expectedVersion !== void 0 && manifest.version !== options.expectedVersion) return verificationError("BUNDLE_VERSION_MISMATCH", "The plugin bundle manifest version does not match the expected version.");
3599
+ const result = {
3600
+ manifest,
3601
+ declaredAccess: manifest.declaredAccess ?? {},
3602
+ backend: backend.data
3603
+ };
3604
+ const admin = files.value.get("admin.js");
3605
+ if (admin) result.admin = admin.data;
3606
+ return {
3607
+ success: true,
3608
+ value: result
3609
+ };
3610
+ }
3611
+ async function decompressBundle(bytes) {
3612
+ const source = new ReadableStream({ start(controller) {
3613
+ controller.enqueue(bytes);
3614
+ controller.close();
3615
+ } });
3616
+ let reader;
3617
+ try {
3618
+ reader = source.pipeThrough(createGzipDecoder()).getReader();
3619
+ } catch {
3620
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not valid gzip data.");
3621
+ }
3622
+ const chunks = [];
3623
+ let total = 0;
3624
+ try {
3625
+ while (true) {
3626
+ const { done, value } = await reader.read();
3627
+ if (done) break;
3628
+ if (!value) continue;
3629
+ total += value.byteLength;
3630
+ if (total > MAX_BUNDLE_DECOMPRESSED_BYTES) {
3631
+ await reader.cancel().catch(() => void 0);
3632
+ return verificationError("BUNDLE_DECOMPRESSED_SIZE_EXCEEDED", "The decompressed plugin bundle exceeds the size limit.");
3633
+ }
3634
+ chunks.push(value);
3635
+ }
3636
+ } catch {
3637
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not valid gzip data.");
3638
+ }
3639
+ const output = new Uint8Array(total);
3640
+ let offset = 0;
3641
+ for (const chunk of chunks) {
3642
+ output.set(chunk, offset);
3643
+ offset += chunk.byteLength;
3644
+ }
3645
+ return {
3646
+ success: true,
3647
+ value: output
3648
+ };
3649
+ }
3650
+ function parseTar(bytes) {
3651
+ if (bytes.byteLength < TAR_END_BYTES || bytes.byteLength % TAR_BLOCK_BYTES !== 0) return invalidArchive();
3652
+ const files = /* @__PURE__ */ new Map();
3653
+ const rawPaths = /* @__PURE__ */ new Set();
3654
+ const normalizedPaths = /* @__PURE__ */ new Set();
3655
+ let offset = 0;
3656
+ let fileCount = 0;
3657
+ let entryCount = 0;
3658
+ let totalFileBytes = 0;
3659
+ let ended = false;
3660
+ while (offset + TAR_BLOCK_BYTES <= bytes.byteLength) {
3661
+ const header = bytes.subarray(offset, offset + TAR_BLOCK_BYTES);
3662
+ if (isZeroBlock(header)) {
3663
+ if (!isZeroBlock(bytes.subarray(offset + TAR_BLOCK_BYTES, offset + TAR_END_BYTES))) return invalidArchive();
3664
+ if (bytes.subarray(offset + TAR_END_BYTES).some((byte) => byte !== 0)) return invalidArchive();
3665
+ ended = true;
3666
+ break;
3667
+ }
3668
+ if (!validChecksum(header)) return invalidArchive();
3669
+ entryCount += 1;
3670
+ if (entryCount > MAX_BUNDLE_TAR_ENTRY_COUNT) return verificationError("BUNDLE_FILE_COUNT_EXCEEDED", "The plugin bundle contains too many archive entries.");
3671
+ const rawName = readTarPath(header);
3672
+ if (!rawName.success) return rawName;
3673
+ const typeFlag = header[156];
3674
+ const type = typeFlag === 0 ? "file" : String.fromCharCode(typeFlag ?? 0);
3675
+ const isDirectory = type === "5";
3676
+ const normalized = normalizePath(rawName.value, isDirectory);
3677
+ if (!normalized.success) return normalized;
3678
+ if (rawPaths.has(rawName.value) || normalizedPaths.has(normalized.value)) return verificationError("BUNDLE_PATH_COLLISION", "The plugin bundle contains duplicate or ambiguous paths.");
3679
+ rawPaths.add(rawName.value);
3680
+ normalizedPaths.add(normalized.value);
3681
+ const size = readOctal(header.subarray(124, 136));
3682
+ if (size === null || !Number.isSafeInteger(size)) return invalidArchive();
3683
+ const bodyStart = offset + TAR_BLOCK_BYTES;
3684
+ const nextOffset = bodyStart + Math.ceil(size / TAR_BLOCK_BYTES) * TAR_BLOCK_BYTES;
3685
+ if (nextOffset > bytes.byteLength) return invalidArchive();
3686
+ if (isDirectory) {
3687
+ if (size !== 0) return invalidArchive();
3688
+ } else if (type === "file" || type === "0") {
3689
+ fileCount += 1;
3690
+ if (fileCount > MAX_BUNDLE_FILE_COUNT) return verificationError("BUNDLE_FILE_COUNT_EXCEEDED", "The plugin bundle contains too many files.");
3691
+ if (size > MAX_BUNDLE_FILE_BYTES) return verificationError("BUNDLE_FILE_SIZE_EXCEEDED", "A file in the plugin bundle exceeds the per-file size limit.");
3692
+ totalFileBytes += size;
3693
+ if (totalFileBytes > MAX_BUNDLE_SIZE) return verificationError("BUNDLE_DECOMPRESSED_SIZE_EXCEEDED", "The plugin bundle file contents exceed the size limit.");
3694
+ files.set(normalized.value, {
3695
+ name: normalized.value,
3696
+ data: bytes.slice(bodyStart, bodyStart + size)
3697
+ });
3698
+ } else return verificationError("BUNDLE_UNSUPPORTED_ENTRY", "The plugin bundle contains an unsupported archive entry type.");
3699
+ offset = nextOffset;
3700
+ }
3701
+ if (!ended) return invalidArchive();
3702
+ return {
3703
+ success: true,
3704
+ value: files
3705
+ };
3706
+ }
3707
+ function readTarPath(header) {
3708
+ const name = readTarString(header.subarray(0, 100));
3709
+ const prefix = readTarString(header.subarray(345, 500));
3710
+ if (name === null || prefix === null || name.length === 0) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains a malformed path.");
3711
+ return {
3712
+ success: true,
3713
+ value: prefix ? `${prefix}/${name}` : name
3714
+ };
3715
+ }
3716
+ function readTarString(field) {
3717
+ const terminator = field.indexOf(0);
3718
+ const end = terminator === -1 ? field.length : terminator;
3719
+ if (terminator !== -1 && field.subarray(terminator + 1).some((byte) => byte !== 0)) return null;
3720
+ try {
3721
+ return decoder.decode(field.subarray(0, end));
3722
+ } catch {
3723
+ return null;
3724
+ }
3725
+ }
3726
+ function normalizePath(raw, isDirectory) {
3727
+ if (raw.includes("\\") || raw.startsWith("/") || WINDOWS_DRIVE_PATTERN.test(raw) || hasControlCharacter(raw) || raw.endsWith("/") !== isDirectory) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains an unsafe path.");
3728
+ const parts = raw.split("/");
3729
+ if (isDirectory) parts.pop();
3730
+ const normalized = [];
3731
+ for (const part of parts) {
3732
+ if (part === ".") continue;
3733
+ if (part === "" || part === "..") return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains an unsafe path.");
3734
+ normalized.push(part.normalize("NFC"));
3735
+ }
3736
+ if (normalized.length === 0) return verificationError("BUNDLE_INVALID_PATH", "The plugin bundle contains a malformed path.");
3737
+ return {
3738
+ success: true,
3739
+ value: normalized.join("/")
3740
+ };
3741
+ }
3742
+ function hasControlCharacter(value) {
3743
+ for (const character of value) {
3744
+ const codePoint = character.codePointAt(0);
3745
+ if (codePoint !== void 0 && (codePoint <= 31 || codePoint === 127)) return true;
3746
+ }
3747
+ return false;
3748
+ }
3749
+ function readOctal(field) {
3750
+ const text = new TextDecoder().decode(field).replaceAll("\0", "").trim();
3751
+ if (!OCTAL_PATTERN.test(text)) return null;
3752
+ const value = Number.parseInt(text, 8);
3753
+ return Number.isSafeInteger(value) ? value : null;
3754
+ }
3755
+ function validChecksum(header) {
3756
+ const expected = readOctal(header.subarray(148, 156));
3757
+ if (expected === null) return false;
3758
+ let actual = 0;
3759
+ for (let index = 0; index < header.length; index += 1) actual += index >= 148 && index < 156 ? 32 : header[index] ?? 0;
3760
+ return actual === expected;
3761
+ }
3762
+ function isZeroBlock(block) {
3763
+ return block.byteLength === TAR_BLOCK_BYTES && block.every((byte) => byte === 0);
3764
+ }
3765
+ function invalidArchive() {
3766
+ return verificationError("BUNDLE_INVALID_ARCHIVE", "The plugin bundle is not a valid tar archive.");
3767
+ }
3768
+
3769
+ //#endregion
3770
+ //#region src/registry/artifact-verification.ts
3771
+ const bundleDecoder = new TextDecoder("utf-8", { fatal: true });
3772
+ async function validateRegistryArtifact(bytes, checksum, slug, version) {
3773
+ const checksumReport = await verifyMultihash(bytes, checksum);
3774
+ if (!checksumReport.success) return checksumReport;
3775
+ const [artifactDigest, ...artifactDigests] = await computeArtifactDigestCandidates(bytes);
3776
+ const bundleReport = await validatePluginBundle(bytes, {
3777
+ expectedSlug: slug,
3778
+ expectedVersion: version
3779
+ });
3780
+ if (!bundleReport.success) return bundleReport;
3781
+ const manifest = pluginManifestSchema$1.safeParse(bundleReport.value.manifest);
3782
+ if (!manifest.success) return {
3783
+ success: false,
3784
+ error: {
3785
+ code: "BUNDLE_RUNTIME_UNSUPPORTED",
3786
+ message: "The plugin bundle uses manifest features unsupported by this EmDash version."
3787
+ }
3788
+ };
3789
+ try {
3790
+ return {
3791
+ success: true,
3792
+ value: {
3793
+ bundle: {
3794
+ manifest: reconcileManifestAccess$1(manifest.data),
3795
+ backendCode: bundleDecoder.decode(bundleReport.value.backend),
3796
+ adminCode: bundleReport.value.admin === void 0 ? void 0 : bundleDecoder.decode(bundleReport.value.admin),
3797
+ checksum
3798
+ },
3799
+ artifactDigest,
3800
+ artifactDigests
3801
+ }
3802
+ };
3803
+ } catch {
3804
+ return {
3805
+ success: false,
3806
+ error: {
3807
+ code: "BUNDLE_INVALID_CODE_ENCODING",
3808
+ message: "Plugin bundle code must be valid UTF-8."
3809
+ }
3810
+ };
3811
+ }
3812
+ }
3813
+
3814
+ //#endregion
3815
+ //#region src/registry/plugin-id.ts
3816
+ /**
3817
+ * Plugin identifier helpers for the experimental decentralized plugin
3818
+ * registry.
3819
+ *
3820
+ * Registry plugins are addressed by `(publisher_did, slug)`, but the
3821
+ * EmDash runtime threads a single `pluginId: string` through every
3822
+ * install primitive (R2 storage keys, `PluginStateRepository`,
3823
+ * `syncMarketplacePlugins`, sandbox cache keys). Rather than refactor
3824
+ * everything to carry a composite identifier, we normalize the registry
3825
+ * tuple to an opaque content-addressed id that satisfies the existing
3826
+ * `validatePluginIdentifier` shape (`/^[a-z][a-z0-9_-]*$/`).
3827
+ *
3828
+ * The normalized id is:
3829
+ *
3830
+ * `r_` + base32-encoded SHA-256(publisher_did + "\n" + slug), truncated.
3831
+ *
3832
+ * Properties:
3833
+ *
3834
+ * - Deterministic. The same `(publisher, slug)` always produces the
3835
+ * same id, so re-resolving an installed plugin's metadata against
3836
+ * the aggregator is a straightforward lookup keyed by the columns
3837
+ * stored alongside `plugin_id` in `plugin_states`.
3838
+ * - Collision-resistant. 80 bits of truncated hash; a 50% birthday
3839
+ * collision happens around 2^40 distinct plugins, well beyond what
3840
+ * this registry will ever index.
3841
+ * - R2-safe. Lowercase alphanumerics + underscore (no hyphens), no
3842
+ * `:` or `/`. Existing sandbox cache keys (`${pluginId}:${version}`)
3843
+ * keep working because the id contains no `:`.
3844
+ * - Syntactically distinct from typical marketplace plugin ids: the
3845
+ * `r_` prefix plus exactly 16 base32 characters is unlikely to be
3846
+ * chosen as a marketplace id. Not formally guaranteed by the
3847
+ * validator -- marketplace ids may begin with `r_` and contain
3848
+ * hyphens -- so the install handler also performs an explicit
3849
+ * pre-existing-row check at the derived id and rejects any cross-
3850
+ * source collision (`PLUGIN_ID_COLLISION`).
3851
+ *
3852
+ * Reverse lookup (id → publisher + slug) requires the `plugin_states`
3853
+ * row -- the hash is one-way. That's intentional: any code path that
3854
+ * needs the human-meaningful pair already has the state row in hand.
3855
+ */
3856
+ /** Length (in base32 characters) of the truncated hash portion of the id. */
3857
+ const HASH_LENGTH = 16;
3858
+ /** Total expected length of a registry plugin id. */
3859
+ const REGISTRY_PLUGIN_ID_LENGTH = 2 + HASH_LENGTH;
3860
+ const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
3861
+ /**
3862
+ * RFC 4648 base32 encoding without padding, lowercase. Implemented inline
3863
+ * rather than depending on a multibase library because (a) we only need
3864
+ * lowercase base32 here, (b) we need it to run identically in workerd,
3865
+ * Node, and the browser, and (c) the implementation is fewer lines than
3866
+ * the import statement would be.
3867
+ */
3868
+ function base32Encode(bytes) {
3869
+ let bits = 0;
3870
+ let value = 0;
3871
+ let out = "";
3872
+ for (const byte of bytes) {
3873
+ value = value << 8 | byte;
3874
+ bits += 8;
3875
+ while (bits >= 5) {
3876
+ bits -= 5;
3877
+ out += BASE32_ALPHABET[value >>> bits & 31];
3878
+ }
3879
+ }
3880
+ if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
3881
+ return out;
3882
+ }
3883
+ /**
3884
+ * Derive the normalized plugin id for a registry-published plugin.
3885
+ *
3886
+ * Throws if either input is empty or whitespace-only -- a missing DID
3887
+ * or slug is always a programming error in the install path, not a
3888
+ * recoverable runtime condition.
3889
+ */
3890
+ async function makeRegistryPluginId(publisherDid, slug) {
3891
+ const did = publisherDid.trim();
3892
+ const s = slug.trim();
3893
+ if (!did) throw new Error("makeRegistryPluginId: publisherDid is required");
3894
+ if (!s) throw new Error("makeRegistryPluginId: slug is required");
3895
+ const input = `${did}\n${s}`;
3896
+ const hashBuffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
3897
+ return `r_${base32Encode(new Uint8Array(hashBuffer)).slice(0, HASH_LENGTH)}`;
3898
+ }
3899
+
3900
+ //#endregion
3901
+ //#region src/registry/record-labels.ts
3902
+ function hasCurrentRecordLabel(labels, value, record, now = Date.now()) {
3903
+ return labels.some((label) => {
3904
+ if (label.val !== value || label.uri !== record.uri || label.cid !== record.cid || label.neg === true) return false;
3905
+ if (label.exp === void 0) return true;
3906
+ const expiresAt = Date.parse(label.exp);
3907
+ return Number.isFinite(expiresAt) && expiresAt > now;
3908
+ });
3909
+ }
3910
+
3911
+ //#endregion
3912
+ //#region src/api/handlers/registry.ts
3913
+ /**
3914
+ * Registry installs use aggregator results only for discovery and moderation
3915
+ * metadata. The handler reads profile and release records from the publisher's
3916
+ * PDS, verifies their repository proofs, then validates the bundle checksum,
3917
+ * manifest, policy, and consent before storing or activating executable code.
3918
+ * Applicable labels can block installation but cannot supply any verified
3919
+ * record, checksum, permission, or executable byte.
3920
+ */
3921
+ function verifiedAccessEqual(a, b) {
3922
+ return JSON.stringify(a) === JSON.stringify(canonicalizeDeclaredAccess(b));
3923
+ }
3924
+ function registryArtifactError(code, message, operation) {
3925
+ let apiCode;
3926
+ switch (code) {
3927
+ case "BUNDLE_ID_MISMATCH":
3928
+ apiCode = operation === "install" ? "MANIFEST_ID_MISMATCH" : "BUNDLE_IDENTITY_MISMATCH";
3929
+ break;
3930
+ case "BUNDLE_VERSION_MISMATCH":
3931
+ apiCode = operation === "install" ? "MANIFEST_VERSION_MISMATCH" : code;
3932
+ break;
3933
+ case "CHECKSUM_MISMATCH":
3934
+ case "INVALID_MULTIHASH":
3935
+ case "UNSUPPORTED_MULTIHASH":
3936
+ apiCode = "CHECKSUM_MISMATCH";
3937
+ break;
3938
+ case "FETCH_FAILED":
3939
+ case "HOST_REJECTED":
3940
+ case "REDIRECT_LIMIT_EXCEEDED":
3941
+ case "REDIRECT_LOCATION_MISSING":
3942
+ case "RESOURCE_STATUS_ERROR":
3943
+ case "RESOURCE_TIMEOUT":
3944
+ apiCode = operation === "install" ? "INSTALL_FAILED" : "UPDATE_FAILED";
3945
+ break;
3946
+ default: apiCode = "INVALID_BUNDLE";
3947
+ }
3948
+ return {
3949
+ success: false,
3950
+ error: {
3951
+ code: apiCode,
3952
+ message,
3953
+ details: { verificationCode: code }
3954
+ }
3955
+ };
3956
+ }
3957
+ function registryRecordError(code, message) {
3958
+ return {
3959
+ success: false,
3960
+ error: {
3961
+ code: "RECORD_VERIFICATION_FAILED",
3962
+ message,
3963
+ details: { verificationCode: code }
3964
+ }
3965
+ };
3966
+ }
3967
+ function recordConsentError(input, records) {
3968
+ if (!input.profileCid || !input.releaseCid) return {
3969
+ success: false,
3970
+ error: {
3971
+ code: "RECORD_CONSENT_REQUIRED",
3972
+ message: "Verify the signed package records before confirming this action."
3973
+ }
3974
+ };
3975
+ if (input.profileCid !== records.profile.cid || input.releaseCid !== records.release.cid) return {
3976
+ success: false,
3977
+ error: {
3978
+ code: "RECORD_VERIFICATION_DRIFT",
3979
+ message: "The signed package records changed after review. Verify them again."
3980
+ }
3981
+ };
3982
+ return null;
3983
+ }
3984
+ function recordVerificationSummary(records, report) {
3985
+ return {
3986
+ profileCid: records.profile.cid,
3987
+ releaseCid: records.release.cid,
3988
+ provenance: report.provenance.status,
3989
+ policy: report.value.policy
3990
+ };
3991
+ }
3992
+ /**
3993
+ * Bytes-per-artifact cap on the gzipped tarball we'll download before
3994
+ * decompression. RFC 0001 caps a sandboxed plugin bundle at 256 KiB
3995
+ * decompressed (see `MAX_BUNDLE_SIZE` in @emdash-cms/plugin-cli);
3996
+ * gzip on a mix of JSON manifest + JS code typically gives 0.3-0.6
3997
+ * ratio, so compressed bundles are well under 200 KiB in practice.
3998
+ * 512 KiB leaves margin for unusual file mixes that compress poorly
3999
+ * while still rejecting anything that's obviously not a legitimate
4000
+ * plugin bundle.
4001
+ */
4002
+ const MAX_ARTIFACT_BYTES = 512 * 1024;
4003
+ /**
4004
+ * Maximum number of HTTP redirects followed during artifact download.
4005
+ * Each hop is independently URL-validated, so a malicious server cannot
4006
+ * redirect through a series of allowed-looking origins to reach a
4007
+ * forbidden one.
4008
+ */
4009
+ const MAX_REDIRECTS = 5;
4010
+ /**
4011
+ * Wall-clock cap on any single artifact fetch attempt (per URL).
4012
+ * Defends against slow-loris artifact sources that accept the connection but
4013
+ * never finish sending headers or body.
4014
+ */
4015
+ const ARTIFACT_FETCH_TIMEOUT_MS = 15e3;
4016
+ /**
4017
+ * Total wall-clock budget for the artifact-download phase across all
4018
+ * advertised caches, the publisher PDS, and the declared URL. Even with the
4019
+ * per-URL timeout, unavailable sources could otherwise tie up the install request for
4020
+ * minutes; this caps total time at a budget interactive admins can
4021
+ * tolerate. Tuned so a fast happy path takes <1s of budget per
4022
+ * attempt and a worst case still completes in under a minute.
4023
+ */
4024
+ const ARTIFACT_TOTAL_BUDGET_MS = 45e3;
4025
+ /**
4026
+ * Per-request timeout applied to every aggregator XRPC call
4027
+ * (`resolvePackage`, `getLatestRelease`, `listReleases`). Matches the
4028
+ * per-URL artifact-fetch cap. Without this, a slow-loris aggregator
4029
+ * can stall the install before the artifact phase even starts.
4030
+ */
4031
+ const AGGREGATOR_REQUEST_TIMEOUT_MS = 15e3;
4032
+ /**
4033
+ * Total wall-clock budget for the aggregator-discovery phase
4034
+ * (resolve + selected-release lookup). Mirrors the artifact-download
4035
+ * budget. Worst case with the pinned-version path's 20-page cap is
4036
+ * 20 + 1 calls; capping the total ensures any one stalled call
4037
+ * still bounds the whole phase.
4038
+ */
4039
+ const AGGREGATOR_TOTAL_BUDGET_MS = 3e4;
4040
+ var RegistryArtifactFetchError = class extends Error {
4041
+ constructor(code, message) {
4042
+ super(message);
4043
+ this.code = code;
4044
+ this.name = "RegistryArtifactFetchError";
4045
+ }
4046
+ };
4047
+ /** Build a fetch function that enforces a per-request and per-budget timeout. */
4048
+ function timedFetch(totalDeadline) {
4049
+ return (input, init) => {
4050
+ const now = Date.now();
4051
+ const remaining = Math.max(0, totalDeadline - now);
4052
+ if (remaining === 0) return Promise.reject(/* @__PURE__ */ new Error("Aggregator request budget exhausted"));
4053
+ const timeout = Math.min(AGGREGATOR_REQUEST_TIMEOUT_MS, remaining);
4054
+ const controller = new AbortController();
4055
+ const timer = setTimeout(() => controller.abort(), timeout);
4056
+ const callerSignal = init?.signal;
4057
+ if (callerSignal) if (callerSignal.aborted) controller.abort(callerSignal.reason);
4058
+ else callerSignal.addEventListener("abort", () => controller.abort(callerSignal.reason));
4059
+ return fetch(input, {
4060
+ ...init,
4061
+ signal: controller.signal
4062
+ }).finally(() => {
4063
+ clearTimeout(timer);
4064
+ });
4065
+ };
4066
+ }
4067
+ async function fetchArtifact(artifactCaches, artifact, record, auth) {
4068
+ const result = await fetchReleaseArtifact({
4069
+ artifact,
4070
+ record,
4071
+ artifactCaches,
4072
+ ...auth === void 0 ? {} : { auth }
4073
+ }, {
4074
+ fetch: async (url, init) => {
4075
+ if (!init.signal) throw new Error("Registry artifact fetch requires an abort signal");
4076
+ return fetchRegistryArtifactUrl(url.href, {
4077
+ signal: init.signal,
4078
+ maxResponseBytes: MAX_ARTIFACT_BYTES
4079
+ });
4080
+ },
4081
+ resolveHostname: async (hostname) => (await resolveAndValidateExternalUrlTarget(`https://${hostname}`)).addresses,
4082
+ allowHttpLocalhost: import.meta.env.DEV,
4083
+ headerTimeoutMs: ARTIFACT_FETCH_TIMEOUT_MS,
4084
+ totalTimeoutMs: ARTIFACT_TOTAL_BUDGET_MS,
4085
+ maxBytes: MAX_ARTIFACT_BYTES,
4086
+ maxRedirects: MAX_REDIRECTS
4087
+ });
4088
+ if (!result.success) throw new RegistryArtifactFetchError(result.error.code, result.error.message);
4089
+ return result.value.bytes;
4090
+ }
4091
+ /**
4092
+ * Returns an error when the release is younger than `policy.minimumReleaseAge`,
4093
+ * unless its publisher or package is in `minimumReleaseAgeExclude` or it is a
4094
+ * proven first release.
4095
+ *
4096
+ * `releaseView.indexedAt` is aggregator operational data, not part of the
4097
+ * signed release. The release schema has no publication timestamp, so minimum
4098
+ * age remains a local discovery holdback rather than a cryptographic property.
4099
+ * A missing or malformed timestamp fails closed.
4100
+ */
4101
+ function checkMinimumReleaseAge(registryConfig, publisherDid, slug, packageView, releaseView) {
4102
+ const minimumReleaseAge = registryConfig.policy?.minimumReleaseAge;
4103
+ let minimumReleaseAgeSeconds = 0;
4104
+ if (minimumReleaseAge !== void 0) try {
4105
+ minimumReleaseAgeSeconds = parseDurationSeconds(minimumReleaseAge);
4106
+ } catch (err) {
4107
+ return {
4108
+ success: false,
4109
+ error: {
4110
+ code: "REGISTRY_POLICY_INVALID",
4111
+ message: err instanceof Error ? err.message : "Invalid minimumReleaseAge value in registry config"
4112
+ }
4113
+ };
4114
+ }
4115
+ if (minimumReleaseAgeSeconds > 0) {
4116
+ const exclude = registryConfig.policy?.minimumReleaseAgeExclude?.map((e) => e.trim().toLowerCase());
4117
+ if (!(releaseExemptFromMinimumAge(exclude, publisherDid, slug) || isProvenFirstRelease(packageView))) {
4118
+ const indexedAt = Date.parse(releaseView.indexedAt);
4119
+ if (!Number.isFinite(indexedAt)) return {
4120
+ success: false,
4121
+ error: {
4122
+ code: "RELEASE_TIMESTAMP_INVALID",
4123
+ message: "Release record is missing a valid indexed-at timestamp; cannot evaluate minimum release age policy."
4124
+ }
4125
+ };
4126
+ const ageSeconds = (Date.now() - indexedAt) / 1e3;
4127
+ if (ageSeconds < minimumReleaseAgeSeconds) {
4128
+ const remaining = Math.ceil(minimumReleaseAgeSeconds - ageSeconds);
4129
+ return {
4130
+ success: false,
4131
+ error: {
4132
+ code: "RELEASE_TOO_NEW",
4133
+ message: `This release does not meet the configured minimum release age of ${minimumReleaseAgeSeconds}s. It will be installable in ~${remaining}s.`
4134
+ }
4135
+ };
4136
+ }
4137
+ }
4138
+ }
4139
+ return null;
4140
+ }
4141
+ /**
4142
+ * Gate a release's `requires` constraints against the running host
4143
+ * environment. `requires` is the lexicon-`unknown` value off the signed
4144
+ * release record — never trust its shape; `checkEnvCompatibility` guards it.
4145
+ *
4146
+ * Returns `null` when every advertised constraint is satisfied (or there are
4147
+ * none), or a structured `ENV_INCOMPATIBLE` error naming the unsatisfied
4148
+ * constraints and the host versions. The error carries the guarded `requires`
4149
+ * and `host` maps so the admin can render the same mismatch the UI gate shows.
4150
+ */
4151
+ function assertEnvCompatible(requires, hostEnv) {
4152
+ for (const skipped of findSkippedEnvConstraints(requires, hostEnv)) console.warn(`[registry] env compatibility constraint skipped: ${skipped.key} requires ${skipped.required} but host version is ${skipped.reason}`);
4153
+ const mismatches = checkEnvCompatibility(requires, hostEnv);
4154
+ if (mismatches.length === 0) return null;
4155
+ const guarded = {};
4156
+ for (const m of mismatches) guarded[m.key] = m.required;
4157
+ return {
4158
+ code: "ENV_INCOMPATIBLE",
4159
+ message: `This release is not compatible with the current environment: ${mismatches.map((m) => `${m.key} requires ${m.required} but host is ${m.host}`).join("; ")}.`,
4160
+ details: {
4161
+ requires: guarded,
4162
+ host: hostEnv
4163
+ }
4164
+ };
4165
+ }
4166
+ async function handleRegistryInstall(db, storage, sandboxRunner, registryConfigInput, input, opts) {
4167
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4168
+ if (!registryConfig) return {
4169
+ success: false,
4170
+ error: {
4171
+ code: "REGISTRY_NOT_CONFIGURED",
4172
+ message: "Registry is not configured"
4173
+ }
4174
+ };
4175
+ if (!storage) return {
4176
+ success: false,
4177
+ error: {
4178
+ code: "STORAGE_NOT_CONFIGURED",
4179
+ message: "Storage is required for registry plugin installation"
4180
+ }
4181
+ };
4182
+ if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
4183
+ success: false,
4184
+ error: {
4185
+ code: "SANDBOX_NOT_AVAILABLE",
4186
+ message: withUnavailableReason("Sandbox runner is required for registry plugins", sandboxRunner)
4187
+ }
4188
+ };
4189
+ try {
4190
+ validateAggregatorUrl(registryConfig.aggregatorUrl);
4191
+ } catch (err) {
4192
+ return {
4193
+ success: false,
4194
+ error: {
4195
+ code: "REGISTRY_NOT_CONFIGURED",
4196
+ message: err instanceof Error ? err.message : "Invalid aggregator URL"
4197
+ }
4198
+ };
4199
+ }
4200
+ const { did, slug, version: requestedVersion } = input;
4201
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4202
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4203
+ const discovery = new DiscoveryClient({
4204
+ aggregatorUrl: registryConfig.aggregatorUrl,
4205
+ acceptLabelers: registryConfig.acceptLabelers,
4206
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4207
+ fetch: timedFetch(aggregatorDeadline)
4208
+ });
4209
+ if (!did.startsWith("did:") || did.split(":").length < 3) return {
4210
+ success: false,
4211
+ error: {
4212
+ code: "INVALID_DID",
4213
+ message: "DID must be a valid atproto DID (e.g. did:plc:abc123)"
4214
+ }
4215
+ };
4216
+ try {
4217
+ const publisherDid = did;
4218
+ const packageView = await discovery.getPackage({
4219
+ did: publisherDid,
4220
+ slug
4221
+ });
4222
+ const MAX_LIST_PAGES = 20;
4223
+ const releaseView = await (async () => {
4224
+ if (!requestedVersion) return discovery.getLatestRelease({
4225
+ did: publisherDid,
4226
+ package: slug
4227
+ });
4228
+ let cursor;
4229
+ const seenCursors = /* @__PURE__ */ new Set();
4230
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
4231
+ if (cursor !== void 0) {
4232
+ if (seenCursors.has(cursor)) break;
4233
+ seenCursors.add(cursor);
4234
+ }
4235
+ const result = await discovery.listReleases({
4236
+ did: publisherDid,
4237
+ package: slug,
4238
+ cursor,
4239
+ limit: 50
4240
+ });
4241
+ for (const r of result.releases) if (r.version === requestedVersion) return r;
4242
+ if (!result.cursor) break;
4243
+ cursor = result.cursor;
4244
+ }
4245
+ })();
4246
+ if (!releaseView) return {
4247
+ success: false,
4248
+ error: {
4249
+ code: "NO_RELEASE",
4250
+ message: requestedVersion ? `Version ${requestedVersion} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4251
+ }
4252
+ };
4253
+ if (packageView.did !== publisherDid || packageView.slug !== slug) return {
4254
+ success: false,
4255
+ error: {
4256
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4257
+ message: "Aggregator returned a package view for a different publisher or slug."
4258
+ }
4259
+ };
4260
+ if (releaseView.did !== publisherDid || releaseView.package !== slug || requestedVersion !== void 0 && releaseView.version !== requestedVersion) return {
4261
+ success: false,
4262
+ error: {
4263
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4264
+ message: "Aggregator returned a release view that does not match the requested package or version."
4265
+ }
4266
+ };
4267
+ const version = releaseView.version;
4268
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) return {
4269
+ success: false,
4270
+ error: {
4271
+ code: "RELEASE_YANKED",
4272
+ message: "This release has been withdrawn"
4273
+ }
4274
+ };
4275
+ const authoritative = await (opts?.readAuthoritativeRecords ?? readAuthoritativePackageRelease)(publisherDid, slug, version, opts?.authoritativeRecords);
4276
+ if (!authoritative.success) return registryRecordError(authoritative.error.code, authoritative.error.message);
4277
+ const records = authoritative.value;
4278
+ const { profile, release } = records.inspection.value;
4279
+ if (packageView.uri !== records.profile.uri || packageView.cid !== records.profile.cid || releaseView.uri !== records.release.uri || releaseView.cid !== records.release.cid) return {
4280
+ success: false,
4281
+ error: {
4282
+ code: "AGGREGATOR_RECORD_MISMATCH",
4283
+ message: "Aggregator metadata does not match the publisher's signed records."
4284
+ }
4285
+ };
4286
+ if (!opts?.verifyOnly) {
4287
+ const consentError = recordConsentError({
4288
+ profileCid: input.acknowledgedProfileCid,
4289
+ releaseCid: input.acknowledgedReleaseCid
4290
+ }, records);
4291
+ if (consentError) return consentError;
4292
+ }
4293
+ if (hasCurrentRecordLabel(packageView.labels ?? [], "security:yanked", records.profile) || hasCurrentRecordLabel(packageView.labels ?? [], "security-yanked", records.profile)) return {
4294
+ success: false,
4295
+ error: {
4296
+ code: "RELEASE_YANKED",
4297
+ message: "This release has been withdrawn"
4298
+ }
4299
+ };
4300
+ if (opts?.hostEnv) {
4301
+ const envError = assertEnvCompatible(release.requires, opts.hostEnv);
4302
+ if (envError) return {
4303
+ success: false,
4304
+ error: envError
4305
+ };
4306
+ }
4307
+ const releaseAgeError = checkMinimumReleaseAge(registryConfig, publisherDid, slug, packageView, releaseView);
4308
+ if (releaseAgeError) return releaseAgeError;
4309
+ const pluginId = await makeRegistryPluginId(publisherDid, slug);
4310
+ if (opts?.configuredPluginIds?.has(pluginId)) return {
4311
+ success: false,
4312
+ error: {
4313
+ code: "PLUGIN_ID_CONFLICT",
4314
+ message: "A configured plugin with the same derived id already exists"
4315
+ }
4316
+ };
4317
+ const stateRepo = new PluginStateRepository(db);
4318
+ const existing = await stateRepo.get(pluginId);
4319
+ if (existing) {
4320
+ if (existing.source === "registry") return {
4321
+ success: false,
4322
+ error: {
4323
+ code: "ALREADY_INSTALLED",
4324
+ message: `Plugin ${publisherDid}/${slug} is already installed`
4325
+ }
4326
+ };
4327
+ return {
4328
+ success: false,
4329
+ error: {
4330
+ code: "PLUGIN_ID_COLLISION",
4331
+ message: `A non-registry plugin already exists at the derived id ${pluginId}. Uninstall it before installing this registry plugin.`
4332
+ }
4333
+ };
4334
+ }
4335
+ const packageArtifact = release.artifacts.package;
4336
+ const declaredChecksum = release.artifacts.package.checksum;
4337
+ if (!packageArtifact || !declaredChecksum) return {
4338
+ success: false,
4339
+ error: {
4340
+ code: "INVALID_RELEASE",
4341
+ message: "Release record is missing its package artifact or checksum"
4342
+ }
4343
+ };
4344
+ let artifactBytes;
4345
+ try {
4346
+ artifactBytes = await fetchArtifact(releaseView.artifactCaches ?? [], packageArtifact, {
4347
+ did: publisherDid,
4348
+ collection: NSID.packageRelease,
4349
+ rkey: `${slug}:${version}`,
4350
+ cid: releaseView.cid
4351
+ }, release.auth);
4352
+ } catch (error) {
4353
+ if (error instanceof RegistryArtifactFetchError) return registryArtifactError(error.code, error.message, "install");
4354
+ throw error;
4355
+ }
4356
+ const artifactReport = await validateRegistryArtifact(artifactBytes, declaredChecksum, slug, version);
4357
+ if (!artifactReport.success) return registryArtifactError(artifactReport.error.code, artifactReport.error.message, "install");
4358
+ const { bundle, artifactDigest, artifactDigests } = artifactReport.value;
4359
+ const recordReport = await verifyAuthoritativePackageRelease(records, artifactDigest, {
4360
+ ...opts?.authoritativeRecords,
4361
+ artifactDigests
4362
+ });
4363
+ if (!recordReport.success) return registryRecordError(recordReport.code, recordReport.reasons[0]?.message ?? "The release provenance is invalid.");
4364
+ const verification = recordVerificationSummary(records, recordReport);
4365
+ bundle.manifest = {
4366
+ ...bundle.manifest,
4367
+ id: pluginId
4368
+ };
4369
+ if (!verifiedAccessEqual(recordReport.value.declaredAccess, bundle.manifest.declaredAccess ?? {})) return {
4370
+ success: false,
4371
+ error: {
4372
+ code: "DECLARED_ACCESS_DRIFT",
4373
+ message: "The plugin bundle declares different permissions than its published record. Installation refused."
4374
+ }
4375
+ };
4376
+ const actualCapabilities = canonicalCapabilitiesForDriftCheck(bundle.manifest.capabilities);
4377
+ if (!opts?.verifyOnly && actualCapabilities.length > 0) {
4378
+ if (input.acknowledgedDeclaredAccess === void 0) return {
4379
+ success: false,
4380
+ error: {
4381
+ code: "DECLARED_ACCESS_REQUIRED",
4382
+ message: "This plugin declares capabilities that require consent. Re-open the install dialog to review and acknowledge them."
4383
+ }
4384
+ };
4385
+ const acknowledged = canonicalCapabilitiesForDriftCheck(input.acknowledgedDeclaredAccess);
4386
+ if (acknowledged.length !== actualCapabilities.length || acknowledged.some((cap, i) => cap !== actualCapabilities[i])) return {
4387
+ success: false,
4388
+ error: {
4389
+ code: "DECLARED_ACCESS_DRIFT",
4390
+ message: "Plugin manifest has changed since you consented. Re-open the install dialog to review the new permissions."
4391
+ }
4392
+ };
4393
+ }
4394
+ const actualMcpTools = (bundle.manifest.mcp?.tools ?? []).map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
4395
+ const publicRoutes = diffRouteVisibility(void 0, bundle.manifest).newlyPublic.toSorted();
4396
+ if (!opts?.verifyOnly && publicRoutes.length > 0) {
4397
+ const acknowledgedPublicRoutes = Array.isArray(input.acknowledgedPublicRoutes) ? input.acknowledgedPublicRoutes.filter((route) => typeof route === "string").toSorted() : [];
4398
+ if (JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(publicRoutes)) return {
4399
+ success: false,
4400
+ error: {
4401
+ code: "ROUTE_VISIBILITY_ESCALATION",
4402
+ message: "Plugin install exposes public (unauthenticated) routes",
4403
+ details: {
4404
+ routeVisibilityChanges: { newlyPublic: publicRoutes },
4405
+ mcpTools: actualMcpTools,
4406
+ verification
4407
+ }
4408
+ }
4409
+ };
4410
+ }
4411
+ if (!opts?.verifyOnly && actualMcpTools.length > 0) {
4412
+ if (JSON.stringify(input.acknowledgedMcpTools) !== JSON.stringify(actualMcpTools)) return {
4413
+ success: false,
4414
+ error: {
4415
+ code: "MCP_TOOL_CONSENT_REQUIRED",
4416
+ message: "Plugin MCP tools require explicit consent",
4417
+ details: {
4418
+ mcpTools: actualMcpTools,
4419
+ routeVisibilityChanges: publicRoutes.length > 0 ? { newlyPublic: publicRoutes } : void 0,
4420
+ verification
4421
+ }
4422
+ }
4423
+ };
4424
+ }
4425
+ const result = {
4426
+ pluginId,
4427
+ publisherDid,
4428
+ slug,
4429
+ version,
4430
+ capabilities: bundle.manifest.capabilities,
4431
+ declaredAccess: recordReport.value.releaseExtension.declaredAccess,
4432
+ mcpTools: actualMcpTools,
4433
+ publicRoutes,
4434
+ verification
4435
+ };
4436
+ if (opts?.verifyOnly) return {
4437
+ success: true,
4438
+ data: result
4439
+ };
4440
+ await storeBundleInR2(storage, pluginId, version, bundle, "registry");
4441
+ try {
4442
+ await stateRepo.upsert(pluginId, version, "active", {
4443
+ source: "registry",
4444
+ displayName: profile.name ?? slug,
4445
+ description: profile.description ?? void 0,
4446
+ registryPublisherDid: publisherDid,
4447
+ registrySlug: slug
4448
+ });
4449
+ } catch (stateErr) {
4450
+ let lostRace = false;
4451
+ try {
4452
+ const winner = await stateRepo.get(pluginId);
4453
+ lostRace = winner !== void 0 && winner !== null;
4454
+ } catch (probeErr) {
4455
+ console.warn(`[registry-install] Failed to probe state row for ${pluginId} after state-write failure; treating as orphan:`, probeErr);
4456
+ }
4457
+ if (!lostRace) try {
4458
+ await deleteBundleFromR2(storage, pluginId, version, "registry");
4459
+ } catch (cleanupErr) {
4460
+ console.warn(`[registry-install] Failed to clean up R2 bundle for ${pluginId}@${version} after state-row write failure:`, cleanupErr);
4461
+ }
4462
+ throw stateErr;
4463
+ }
4464
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4465
+ return {
4466
+ success: true,
4467
+ data: result
4468
+ };
4469
+ } catch (err) {
4470
+ if (err instanceof ClientValidationError) return {
4471
+ success: false,
4472
+ error: {
4473
+ code: "AGGREGATOR_RESPONSE_INVALID",
4474
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4475
+ }
4476
+ };
4477
+ if (err instanceof ClientResponseError) {
4478
+ if (err.error === "ListingUnavailable") return {
4479
+ success: false,
4480
+ error: {
4481
+ code: "LISTING_UNAVAILABLE",
4482
+ message: "This plugin is unavailable under the active registry policy"
4483
+ }
4484
+ };
4485
+ return {
4486
+ success: false,
4487
+ error: {
4488
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4489
+ message: `Aggregator returned ${err.status}: ${err.error}`
4490
+ }
4491
+ };
4492
+ }
4493
+ if (err instanceof EmDashStorageError) return {
4494
+ success: false,
4495
+ error: {
4496
+ code: err.code ?? "STORAGE_ERROR",
4497
+ message: "Storage error while installing plugin"
4498
+ }
4499
+ };
4500
+ console.error("[registry-install] Failed:", err);
4501
+ return {
4502
+ success: false,
4503
+ error: {
4504
+ code: "INSTALL_FAILED",
4505
+ message: err instanceof Error ? err.message : "Failed to install plugin from registry"
4506
+ }
4507
+ };
4508
+ }
4509
+ }
4510
+ /**
4511
+ * Uninstall a registry-source plugin. Deletes the R2 bundle under
4512
+ * `registry/<pluginId>/<version>/`, optionally drops the plugin's
4513
+ * `_plugin_storage` rows, and removes the `_plugin_state` row. The
4514
+ * sandbox runtime is reconciled by the route's `syncRegistryPlugins`
4515
+ * call after this returns.
4516
+ *
4517
+ * Refuses to uninstall plugins whose `source` is not `"registry"` to
4518
+ * avoid trashing a marketplace/config plugin that happens to share the
4519
+ * pluginId namespace.
4520
+ */
4521
+ async function handleRegistryUninstall(db, storage, pluginId, opts) {
4522
+ try {
4523
+ const stateRepo = new PluginStateRepository(db);
4524
+ const existing = await stateRepo.get(pluginId);
4525
+ if (!existing || existing.source !== "registry") return {
4526
+ success: false,
4527
+ error: {
4528
+ code: "NOT_FOUND",
4529
+ message: `No registry plugin found: ${pluginId}`
4530
+ }
4531
+ };
4532
+ const version = existing.version;
4533
+ await opts?.beforeDelete?.();
4534
+ let dataDeleted = false;
4535
+ if (opts?.deleteData) {
4536
+ await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
4537
+ dataDeleted = true;
4538
+ }
4539
+ try {
4540
+ await removeAllPluginIndexes(db, pluginId);
4541
+ } catch {}
4542
+ await stateRepo.delete(pluginId);
4543
+ if (storage) await deleteBundleFromR2(storage, pluginId, version, "registry");
4544
+ return {
4545
+ success: true,
4546
+ data: {
4547
+ pluginId,
4548
+ dataDeleted
4549
+ }
4550
+ };
4551
+ } catch (err) {
4552
+ console.error("[registry-uninstall] Failed:", err);
4553
+ return {
4554
+ success: false,
4555
+ error: {
4556
+ code: "UNINSTALL_FAILED",
4557
+ message: "Failed to uninstall plugin"
4558
+ }
4559
+ };
4560
+ }
4561
+ }
4562
+ /**
4563
+ * Update a registry-source plugin to a newer release. Mirrors
4564
+ * `handleMarketplaceUpdate`: resolves the target version via the aggregator,
4565
+ * re-runs the artifact fetch / checksum / extract pipeline, diffs capabilities
4566
+ * and route visibility against the currently installed bundle, and gates
4567
+ * escalations behind `confirmCapabilityChanges` and an exact
4568
+ * `acknowledgedPublicRoutes` match so the admin re-consents to widened permissions.
4569
+ *
4570
+ * Refuses non-registry sources. Refuses when the stored state row is missing
4571
+ * the `(publisherDid, slug)` it needs to resolve against the aggregator.
4572
+ */
4573
+ async function handleRegistryUpdate(db, storage, sandboxRunner, registryConfigInput, pluginId, opts) {
4574
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4575
+ if (!registryConfig) return {
4576
+ success: false,
4577
+ error: {
4578
+ code: "REGISTRY_NOT_CONFIGURED",
4579
+ message: "Registry is not configured"
4580
+ }
4581
+ };
4582
+ if (!storage) return {
4583
+ success: false,
4584
+ error: {
4585
+ code: "STORAGE_NOT_CONFIGURED",
4586
+ message: "Storage is required for registry plugin updates"
4587
+ }
4588
+ };
4589
+ if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
4590
+ success: false,
4591
+ error: {
4592
+ code: "SANDBOX_NOT_AVAILABLE",
4593
+ message: withUnavailableReason("Sandbox runner is required", sandboxRunner)
4594
+ }
4595
+ };
4596
+ try {
4597
+ validateAggregatorUrl(registryConfig.aggregatorUrl);
4598
+ } catch (err) {
4599
+ return {
4600
+ success: false,
4601
+ error: {
4602
+ code: "REGISTRY_NOT_CONFIGURED",
4603
+ message: err instanceof Error ? err.message : "Invalid aggregator URL"
4604
+ }
4605
+ };
4606
+ }
4607
+ try {
4608
+ const stateRepo = new PluginStateRepository(db);
4609
+ const existing = await stateRepo.get(pluginId);
4610
+ if (!existing || existing.source !== "registry") return {
4611
+ success: false,
4612
+ error: {
4613
+ code: "NOT_FOUND",
4614
+ message: `No registry plugin found: ${pluginId}`
4615
+ }
4616
+ };
4617
+ if (!existing.registryPublisherDid || !existing.registrySlug) return {
4618
+ success: false,
4619
+ error: {
4620
+ code: "INVALID_STATE",
4621
+ message: `Registry plugin ${pluginId} is missing publisher DID or slug in state`
4622
+ }
4623
+ };
4624
+ const oldVersion = existing.version;
4625
+ const publisherDid = existing.registryPublisherDid;
4626
+ const slug = existing.registrySlug;
4627
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4628
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4629
+ const discovery = new DiscoveryClient({
4630
+ aggregatorUrl: registryConfig.aggregatorUrl,
4631
+ acceptLabelers: registryConfig.acceptLabelers,
4632
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4633
+ fetch: timedFetch(aggregatorDeadline)
4634
+ });
4635
+ const MAX_LIST_PAGES = 20;
4636
+ const releaseView = await (async () => {
4637
+ if (!opts?.version) return discovery.getLatestRelease({
4638
+ did: publisherDid,
4639
+ package: slug
4640
+ });
4641
+ let cursor;
4642
+ const seenCursors = /* @__PURE__ */ new Set();
4643
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
4644
+ if (cursor !== void 0) {
4645
+ if (seenCursors.has(cursor)) break;
4646
+ seenCursors.add(cursor);
4647
+ }
4648
+ const result = await discovery.listReleases({
4649
+ did: publisherDid,
4650
+ package: slug,
4651
+ cursor,
4652
+ limit: 50
4653
+ });
4654
+ for (const r of result.releases) if (r.version === opts.version) return r;
4655
+ if (!result.cursor) break;
4656
+ cursor = result.cursor;
4657
+ }
4658
+ })();
4659
+ if (!releaseView) return {
4660
+ success: false,
4661
+ error: {
4662
+ code: "NO_VERSION",
4663
+ message: opts?.version ? `Version ${opts.version} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4664
+ }
4665
+ };
4666
+ if (releaseView.did !== publisherDid || releaseView.package !== slug || opts?.version !== void 0 && releaseView.version !== opts.version) return {
4667
+ success: false,
4668
+ error: {
4669
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4670
+ message: "Aggregator returned a release view that does not match the requested package or version."
4671
+ }
4672
+ };
4673
+ const packageView = await discovery.getPackage({
4674
+ did: publisherDid,
4675
+ slug
4676
+ });
4677
+ if (!packageView || packageView.did !== publisherDid || packageView.slug !== slug) return {
4678
+ success: false,
4679
+ error: {
4680
+ code: "AGGREGATOR_IDENTITY_MISMATCH",
4681
+ message: "Aggregator returned a package view that does not match the installed plugin."
4682
+ }
4683
+ };
4684
+ const newVersion = releaseView.version;
4685
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) return {
4686
+ success: false,
4687
+ error: {
4688
+ code: "YANKED",
4689
+ message: "Release has been withdrawn"
4690
+ }
4691
+ };
4692
+ if (newVersion === oldVersion) return {
4693
+ success: false,
4694
+ error: {
4695
+ code: "ALREADY_UP_TO_DATE",
4696
+ message: "Plugin is already at the requested version"
4697
+ }
4698
+ };
4699
+ if (opts?.version !== void 0) {
4700
+ const order = compareVersions(newVersion, oldVersion);
4701
+ if (order === null) return {
4702
+ success: false,
4703
+ error: {
4704
+ code: "INVALID_VERSION",
4705
+ message: "Installed or requested version is not valid semver"
4706
+ }
4707
+ };
4708
+ if (order < 0) return {
4709
+ success: false,
4710
+ error: {
4711
+ code: "DOWNGRADE_NOT_ALLOWED",
4712
+ message: "An update cannot target a version older than the installed one"
4713
+ }
4714
+ };
4715
+ }
4716
+ const releaseAgeError = checkMinimumReleaseAge(registryConfig, publisherDid, slug, packageView, releaseView);
4717
+ if (releaseAgeError) return releaseAgeError;
4718
+ const authoritative = await (opts?.readAuthoritativeRecords ?? readAuthoritativePackageRelease)(publisherDid, slug, newVersion, opts?.authoritativeRecords);
4719
+ if (!authoritative.success) return registryRecordError(authoritative.error.code, authoritative.error.message);
4720
+ const records = authoritative.value;
4721
+ const { profile, release } = records.inspection.value;
4722
+ if (packageView.uri !== records.profile.uri || packageView.cid !== records.profile.cid || releaseView.uri !== records.release.uri || releaseView.cid !== records.release.cid) return {
4723
+ success: false,
4724
+ error: {
4725
+ code: "AGGREGATOR_RECORD_MISMATCH",
4726
+ message: "Aggregator metadata does not match the publisher's signed records."
4727
+ }
4728
+ };
4729
+ if (hasCurrentRecordLabel(packageView.labels ?? [], "security:yanked", records.profile) || hasCurrentRecordLabel(packageView.labels ?? [], "security-yanked", records.profile)) return {
4730
+ success: false,
4731
+ error: {
4732
+ code: "YANKED",
4733
+ message: "Package has been withdrawn"
4734
+ }
4735
+ };
4736
+ if (opts?.confirmCapabilityChanges || (opts?.acknowledgedPublicRoutes?.length ?? 0) > 0 || opts?.confirmMcpTools) {
4737
+ const consentError = recordConsentError({
4738
+ profileCid: opts?.acknowledgedProfileCid,
4739
+ releaseCid: opts?.acknowledgedReleaseCid
4740
+ }, records);
4741
+ if (consentError) return consentError;
4742
+ }
4743
+ if (opts?.hostEnv) {
4744
+ const envError = assertEnvCompatible(release.requires, opts.hostEnv);
4745
+ if (envError) return {
4746
+ success: false,
4747
+ error: envError
4748
+ };
4749
+ }
4750
+ const packageArtifact = release.artifacts.package;
4751
+ const declaredChecksum = packageArtifact?.checksum;
4752
+ if (!packageArtifact || !declaredChecksum) return {
4753
+ success: false,
4754
+ error: {
4755
+ code: "INVALID_RELEASE",
4756
+ message: "Release record is missing its package artifact or checksum"
4757
+ }
4758
+ };
4759
+ let artifactBytes;
4760
+ try {
4761
+ artifactBytes = await fetchArtifact(releaseView.artifactCaches ?? [], packageArtifact, {
4762
+ did: publisherDid,
4763
+ collection: NSID.packageRelease,
4764
+ rkey: `${slug}:${newVersion}`,
4765
+ cid: releaseView.cid
4766
+ }, release.auth);
4767
+ } catch (error) {
4768
+ if (error instanceof RegistryArtifactFetchError) return registryArtifactError(error.code, error.message, "update");
4769
+ throw error;
4770
+ }
4771
+ const artifactReport = await validateRegistryArtifact(artifactBytes, declaredChecksum, slug, newVersion);
4772
+ if (!artifactReport.success) return registryArtifactError(artifactReport.error.code, artifactReport.error.message, "update");
4773
+ const { bundle, artifactDigest, artifactDigests } = artifactReport.value;
4774
+ const recordReport = await verifyAuthoritativePackageRelease(records, artifactDigest, {
4775
+ ...opts?.authoritativeRecords,
4776
+ artifactDigests
4777
+ });
4778
+ if (!recordReport.success) return registryRecordError(recordReport.code, recordReport.reasons[0]?.message ?? "The release provenance is invalid.");
4779
+ const verification = recordVerificationSummary(records, recordReport);
4780
+ bundle.manifest = {
4781
+ ...bundle.manifest,
4782
+ id: pluginId
4783
+ };
4784
+ if (!verifiedAccessEqual(recordReport.value.declaredAccess, bundle.manifest.declaredAccess ?? {})) return {
4785
+ success: false,
4786
+ error: {
4787
+ code: "DECLARED_ACCESS_DRIFT",
4788
+ message: "The plugin bundle declares different permissions than its published record. Update refused."
4789
+ }
4790
+ };
4791
+ const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion, "registry");
4792
+ const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
4793
+ if (capabilityChanges.added.length > 0 && !opts?.confirmCapabilityChanges) return {
4794
+ success: false,
4795
+ error: {
4796
+ code: "CAPABILITY_ESCALATION",
4797
+ message: "Plugin update requires new capabilities",
4798
+ details: {
4799
+ capabilityChanges,
4800
+ verification
4801
+ }
4802
+ }
4803
+ };
4804
+ const newlyPublicRoutes = diffRouteVisibility(oldBundle?.manifest, bundle.manifest).newlyPublic.toSorted();
4805
+ const acknowledgedPublicRoutes = (opts?.acknowledgedPublicRoutes ?? []).filter((route) => typeof route === "string").toSorted();
4806
+ if (newlyPublicRoutes.length > 0 && JSON.stringify(acknowledgedPublicRoutes) !== JSON.stringify(newlyPublicRoutes)) return {
4807
+ success: false,
4808
+ error: {
4809
+ code: "ROUTE_VISIBILITY_ESCALATION",
4810
+ message: "Plugin update exposes new public (unauthenticated) routes",
4811
+ details: {
4812
+ routeVisibilityChanges: { newlyPublic: newlyPublicRoutes },
4813
+ capabilityChanges,
4814
+ verification
4815
+ }
4816
+ }
4817
+ };
4818
+ const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4819
+ const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4820
+ if (JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools) && !opts?.confirmMcpTools) return {
4821
+ success: false,
4822
+ error: {
4823
+ code: "MCP_TOOL_CONSENT_REQUIRED",
4824
+ message: "Plugin update changes its MCP tools",
4825
+ details: {
4826
+ mcpTools: newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool),
4827
+ verification
4828
+ }
4829
+ }
4830
+ };
4831
+ await storeBundleInR2(storage, pluginId, newVersion, bundle, "registry");
4832
+ await stateRepo.upsert(pluginId, newVersion, "active", {
4833
+ source: "registry",
4834
+ registryPublisherDid: publisherDid,
4835
+ registrySlug: slug,
4836
+ displayName: profile.name ?? slug,
4837
+ description: profile.description ?? void 0,
4838
+ mcpToolsEnabled: false,
4839
+ mcpToolsConsent: null
4840
+ });
4841
+ await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4842
+ return {
4843
+ success: true,
4844
+ data: {
4845
+ pluginId,
4846
+ oldVersion,
4847
+ newVersion,
4848
+ capabilityChanges,
4849
+ routeVisibilityChanges: newlyPublicRoutes.length > 0 ? { newlyPublic: newlyPublicRoutes } : void 0,
4850
+ verification
4851
+ }
4852
+ };
4853
+ } catch (err) {
4854
+ if (err instanceof ClientValidationError) return {
4855
+ success: false,
4856
+ error: {
4857
+ code: "AGGREGATOR_RESPONSE_INVALID",
4858
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4859
+ }
4860
+ };
4861
+ if (err instanceof ClientResponseError) {
4862
+ if (err.error === "ListingUnavailable") return {
4863
+ success: false,
4864
+ error: {
4865
+ code: "LISTING_UNAVAILABLE",
4866
+ message: "This plugin is unavailable under the active registry policy"
4867
+ }
4868
+ };
4869
+ return {
4870
+ success: false,
4871
+ error: {
4872
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4873
+ message: `Aggregator returned ${err.status}: ${err.error}`
4874
+ }
4875
+ };
4876
+ }
4877
+ if (err instanceof EmDashStorageError) return {
4878
+ success: false,
4879
+ error: {
4880
+ code: err.code ?? "STORAGE_ERROR",
4881
+ message: "Storage error while updating plugin"
4882
+ }
4883
+ };
4884
+ console.error("[registry-update] Failed:", err);
4885
+ return {
4886
+ success: false,
4887
+ error: {
4888
+ code: "UPDATE_FAILED",
4889
+ message: err instanceof Error ? err.message : "Failed to update plugin"
4890
+ }
4891
+ };
4892
+ }
4893
+ }
4894
+ /**
4895
+ * Bulk update check across every installed registry plugin. Queries the
4896
+ * aggregator for each plugin's latest release and reports `hasUpdate`
4897
+ * based on the version comparison. Plugins whose aggregator lookup fails
4898
+ * (unreachable, delisted, malformed) are skipped silently — one bad
4899
+ * publisher must not blank the whole admin Updates list.
4900
+ */
4901
+ async function handleRegistryUpdateCheck(db, registryConfigInput) {
4902
+ const registryConfig = coerceRegistryConfig(registryConfigInput);
4903
+ if (!registryConfig) return {
4904
+ success: false,
4905
+ error: {
4906
+ code: "REGISTRY_NOT_CONFIGURED",
4907
+ message: "Registry is not configured"
4908
+ }
4909
+ };
4910
+ try {
4911
+ const registryPlugins = await new PluginStateRepository(db).getRegistryPlugins();
4912
+ if (registryPlugins.length === 0) return {
4913
+ success: true,
4914
+ data: { items: [] }
4915
+ };
4916
+ const { DiscoveryClient, registryLabelerPolicy } = await import("@emdash-cms/registry-client/discovery");
4917
+ const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4918
+ const discovery = new DiscoveryClient({
4919
+ aggregatorUrl: registryConfig.aggregatorUrl,
4920
+ acceptLabelers: registryConfig.acceptLabelers,
4921
+ labelerPolicy: registryLabelerPolicy(registryConfig.acceptLabelers),
4922
+ fetch: timedFetch(aggregatorDeadline)
4923
+ });
4924
+ const items = [];
4925
+ for (const plugin of registryPlugins) {
4926
+ if (!plugin.registryPublisherDid || !plugin.registrySlug) continue;
4927
+ try {
4928
+ const releaseView = await discovery.getLatestRelease({
4929
+ did: plugin.registryPublisherDid,
4930
+ package: plugin.registrySlug
4931
+ });
4932
+ if (evaluateRegistryReleaseWithdrawal(releaseView, discovery.labelerPolicy).withdrawn) continue;
4933
+ const latest = releaseView.version;
4934
+ if (!latest) continue;
4935
+ const installed = plugin.version;
4936
+ items.push({
4937
+ pluginId: plugin.pluginId,
4938
+ installed,
4939
+ latest,
4940
+ hasUpdate: latest !== installed,
4941
+ hasCapabilityChanges: false,
4942
+ hasRouteVisibilityChanges: false
4943
+ });
4944
+ } catch (err) {
4945
+ console.warn(`[registry-update-check] Skipped ${plugin.pluginId}:`, err);
4946
+ }
4947
+ }
4948
+ return {
4949
+ success: true,
4950
+ data: { items }
4951
+ };
4952
+ } catch (err) {
4953
+ if (err instanceof ClientValidationError) return {
4954
+ success: false,
4955
+ error: {
4956
+ code: "AGGREGATOR_RESPONSE_INVALID",
4957
+ message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4958
+ }
4959
+ };
4960
+ if (err instanceof ClientResponseError) return {
4961
+ success: false,
4962
+ error: {
4963
+ code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4964
+ message: `Aggregator returned ${err.status}: ${err.error}`
4965
+ }
4966
+ };
4967
+ console.error("[registry-update-check] Failed:", err);
4968
+ return {
4969
+ success: false,
4970
+ error: {
4971
+ code: "UPDATE_CHECK_FAILED",
4972
+ message: "Failed to check for registry updates"
4973
+ }
4974
+ };
4975
+ }
4976
+ }
4977
+
4978
+ //#endregion
4979
+ export { handleContentDelete as A, handleContentSchedule as B, generateManifest as C, handleContentCountScheduled as D, handleContentCompare as E, handleContentList as F, handleScheduledPolicyRejection as G, handleContentUnpublish as H, handleContentListTrashed as I, validateRev as J, storagelessDataKeyError as K, handleContentPermanentDelete as L, handleContentDuplicate as M, handleContentGet as N, handleContentCountTrashed as O, handleContentGetIncludingTrashed as P, handleContentPublish as R, buildManifestCollections as S, handleContentAuthors as T, handleContentUnschedule as U, handleContentTranslations as V, handleContentUpdate as W, handlePluginSettingsGet as _, handleMarketplaceGetPlugin as a, handleRevisionList as b, handleMarketplaceUninstall as c, handleThemeGetDetail as d, handleThemeSearch as f, getPluginSettingsSchema as g, syncDeclaredStorageIndexes as h, handleRegistryUpdateCheck as i, handleContentDiscardDraft as j, handleContentCreate as k, handleMarketplaceUpdate as l, rollbackPluginUpdate as m, handleRegistryUninstall as n, handleMarketplaceInstall as o, loadBundleFromR2 as p, liveReferenceSelection as q, handleRegistryUpdate as r, handleMarketplaceSearch as s, handleRegistryInstall as t, handleMarketplaceUpdateCheck as u, handlePluginSettingsUpdate as v, changedStoragelessDataKeys as w, handleRevisionRestore as x, handleRevisionGet as y, handleContentRestore as z };
4980
+ //# sourceMappingURL=api-CltsXhiX.mjs.map