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