emdash 0.35.0 → 0.37.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 (971) hide show
  1. package/dist/activation-K0kGBWuJ.mjs +382 -0
  2. package/dist/activation-K0kGBWuJ.mjs.map +1 -0
  3. package/dist/{adapters-Bb1vG41D.d.mts → adapters-BDQwg236.d.mts} +6 -4
  4. package/dist/{adapters-Bb1vG41D.d.mts.map → adapters-BDQwg236.d.mts.map} +1 -1
  5. package/dist/{allowed-origins-DW7sYyqg.mjs → allowed-origins-BGglilcs.mjs} +2 -2
  6. package/dist/{allowed-origins-DW7sYyqg.mjs.map → allowed-origins-BGglilcs.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -3
  8. package/dist/api/route-utils.mjs +23 -21
  9. package/dist/api/route-utils.mjs.map +1 -1
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +5 -5
  12. package/dist/api-Dz6rgoa3.mjs +10040 -0
  13. package/dist/api-Dz6rgoa3.mjs.map +1 -0
  14. package/dist/{api-tokens-KO24G1Fd.mjs → api-tokens-BSsQACNe.mjs} +2 -2
  15. package/dist/{api-tokens-KO24G1Fd.mjs.map → api-tokens-BSsQACNe.mjs.map} +1 -1
  16. package/dist/{apply-kUDt80-G.mjs → apply-B4SIOxR1.mjs} +34 -35
  17. package/dist/{apply-kUDt80-G.mjs.map → apply-B4SIOxR1.mjs.map} +1 -1
  18. package/dist/astro/image-endpoint.mjs +2 -2
  19. package/dist/astro/image-endpoint.mjs.map +1 -1
  20. package/dist/astro/index.d.mts +12 -12
  21. package/dist/astro/index.d.mts.map +1 -1
  22. package/dist/astro/index.mjs +128 -44
  23. package/dist/astro/index.mjs.map +1 -1
  24. package/dist/astro/middleware/auth.d.mts +10 -10
  25. package/dist/astro/middleware/auth.d.mts.map +1 -1
  26. package/dist/astro/middleware/auth.mjs +10 -7
  27. package/dist/astro/middleware/auth.mjs.map +1 -1
  28. package/dist/astro/middleware/media-usage-write-fence.mjs +2 -2
  29. package/dist/astro/middleware/redirect.mjs +4 -4
  30. package/dist/astro/middleware/request-context.mjs +3 -3
  31. package/dist/astro/middleware/setup.mjs +1 -1
  32. package/dist/astro/middleware.d.mts +11 -12
  33. package/dist/astro/middleware.d.mts.map +1 -1
  34. package/dist/astro/middleware.mjs +237 -1412
  35. package/dist/astro/middleware.mjs.map +1 -1
  36. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  37. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  38. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +3 -3
  39. package/dist/astro/routes/api/admin/api-tokens/index.d.mts.map +1 -1
  40. package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
  41. package/dist/astro/routes/api/admin/api-tokens/index.mjs.map +1 -1
  42. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
  43. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +9 -9
  44. package/dist/astro/routes/api/admin/byline-fields/index.mjs +9 -9
  45. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +9 -9
  46. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +16 -16
  47. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +16 -16
  48. package/dist/astro/routes/api/admin/bylines/index.mjs +16 -16
  49. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +13 -13
  50. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  51. package/dist/astro/routes/api/admin/comments/bulk.mjs +10 -10
  52. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  53. package/dist/astro/routes/api/admin/comments/index.mjs +10 -10
  54. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  55. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  56. package/dist/astro/routes/api/admin/media-usage/activation.d.mts +9 -0
  57. package/dist/astro/routes/api/admin/media-usage/activation.d.mts.map +1 -0
  58. package/dist/astro/routes/api/admin/media-usage/activation.mjs +46 -0
  59. package/dist/astro/routes/api/admin/media-usage/activation.mjs.map +1 -0
  60. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +14 -13
  61. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs.map +1 -1
  62. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +14 -13
  63. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs.map +1 -1
  64. package/dist/astro/routes/api/admin/media-usage/progress.d.mts +9 -0
  65. package/dist/astro/routes/api/admin/media-usage/progress.d.mts.map +1 -0
  66. package/dist/astro/routes/api/admin/media-usage/progress.mjs +44 -0
  67. package/dist/astro/routes/api/admin/media-usage/progress.mjs.map +1 -0
  68. package/dist/astro/routes/api/admin/media-usage/repair.mjs +16 -11
  69. package/dist/astro/routes/api/admin/media-usage/repair.mjs.map +1 -1
  70. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +14 -13
  71. package/dist/astro/routes/api/admin/media-usage/work/index.mjs.map +1 -1
  72. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +14 -13
  73. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs.map +1 -1
  74. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +4 -4
  75. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs.map +1 -1
  76. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
  77. package/dist/astro/routes/api/admin/oauth-clients/index.mjs.map +1 -1
  78. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +55 -49
  79. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  80. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +55 -49
  81. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +53 -47
  83. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  85. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +53 -47
  86. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  87. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +54 -48
  88. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  89. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +54 -48
  90. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  91. package/dist/astro/routes/api/admin/plugins/index.mjs +53 -47
  92. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  93. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
  94. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +53 -47
  95. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  96. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +54 -48
  97. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  98. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +53 -47
  99. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  100. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +54 -48
  101. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  102. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.d.mts.map +1 -1
  103. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +60 -50
  104. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  105. package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts.map +1 -1
  106. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +179 -139
  107. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  108. package/dist/astro/routes/api/admin/plugins/registry/install.d.mts.map +1 -1
  109. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +61 -51
  110. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  111. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts +8 -0
  112. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts.map +1 -0
  113. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +93 -0
  114. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -0
  115. package/dist/astro/routes/api/admin/plugins/updates.mjs +53 -47
  116. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  117. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +53 -47
  118. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  119. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +2 -2
  120. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +53 -47
  121. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  122. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
  123. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
  124. package/dist/astro/routes/api/admin/users/_id_/index.mjs +7 -7
  125. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
  126. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  127. package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
  128. package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
  129. package/dist/astro/routes/api/auth/invite/complete.mjs +11 -11
  130. package/dist/astro/routes/api/auth/invite/index.mjs +8 -8
  131. package/dist/astro/routes/api/auth/invite/register-options.mjs +10 -10
  132. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  133. package/dist/astro/routes/api/auth/magic-link/send.mjs +10 -10
  134. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  135. package/dist/astro/routes/api/auth/me.d.mts.map +1 -1
  136. package/dist/astro/routes/api/auth/me.mjs +19 -9
  137. package/dist/astro/routes/api/auth/me.mjs.map +1 -1
  138. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  139. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  140. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  141. package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
  142. package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
  143. package/dist/astro/routes/api/auth/passkey/options.mjs +12 -12
  144. package/dist/astro/routes/api/auth/passkey/register/options.mjs +10 -10
  145. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +11 -11
  146. package/dist/astro/routes/api/auth/passkey/verify.mjs +11 -11
  147. package/dist/astro/routes/api/auth/signup/complete.mjs +11 -11
  148. package/dist/astro/routes/api/auth/signup/request.mjs +10 -10
  149. package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
  150. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +14 -14
  151. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +13 -13
  152. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
  153. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.d.mts.map +1 -1
  154. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +14 -5
  155. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs.map +1 -1
  156. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  157. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
  158. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +11 -11
  159. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +13 -10
  160. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs.map +1 -1
  161. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +17 -15
  162. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  163. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +17 -15
  164. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  165. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  166. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
  167. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +8 -8
  168. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +14 -14
  169. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
  170. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.d.mts.map +1 -1
  171. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +14 -5
  172. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs.map +1 -1
  173. package/dist/astro/routes/api/content/_collection_/_id_.mjs +8 -8
  174. package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
  175. package/dist/astro/routes/api/content/_collection_/index.mjs +8 -8
  176. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  177. package/dist/astro/routes/api/dashboard.mjs +8 -8
  178. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  179. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  180. package/dist/astro/routes/api/import/probe.mjs +17 -17
  181. package/dist/astro/routes/api/import/wordpress/analyze.mjs +2 -2
  182. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  183. package/dist/astro/routes/api/import/wordpress/execute.mjs +13 -13
  184. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  185. package/dist/astro/routes/api/import/wordpress/media.mjs +11 -11
  186. package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
  187. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  188. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +12 -10
  189. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
  190. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  191. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +17 -17
  192. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  193. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +27 -27
  194. package/dist/astro/routes/api/manifest.mjs +4 -4
  195. package/dist/astro/routes/api/manifest.mjs.map +1 -1
  196. package/dist/astro/routes/api/mcp.mjs +188 -65
  197. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  198. package/dist/astro/routes/api/media/_id_/confirm.mjs +11 -11
  199. package/dist/astro/routes/api/media/_id_/replace.d.mts +8 -0
  200. package/dist/astro/routes/api/media/_id_/replace.d.mts.map +1 -0
  201. package/dist/astro/routes/api/media/_id_/replace.mjs +91 -0
  202. package/dist/astro/routes/api/media/_id_/replace.mjs.map +1 -0
  203. package/dist/astro/routes/api/media/_id_/upload.mjs +6 -6
  204. package/dist/astro/routes/api/media/_id_/usage.mjs +18 -13
  205. package/dist/astro/routes/api/media/_id_/usage.mjs.map +1 -1
  206. package/dist/astro/routes/api/media/_id_.d.mts.map +1 -1
  207. package/dist/astro/routes/api/media/_id_.mjs +21 -13
  208. package/dist/astro/routes/api/media/_id_.mjs.map +1 -1
  209. package/dist/astro/routes/api/media/file/_...key_.d.mts.map +1 -1
  210. package/dist/astro/routes/api/media/file/_...key_.mjs +3 -2
  211. package/dist/astro/routes/api/media/file/_...key_.mjs.map +1 -1
  212. package/dist/astro/routes/api/media/folders/_id_.d.mts +10 -0
  213. package/dist/astro/routes/api/media/folders/_id_.d.mts.map +1 -0
  214. package/dist/astro/routes/api/media/folders/_id_.mjs +52 -0
  215. package/dist/astro/routes/api/media/folders/_id_.mjs.map +1 -0
  216. package/dist/astro/routes/api/media/folders/index.d.mts +9 -0
  217. package/dist/astro/routes/api/media/folders/index.d.mts.map +1 -0
  218. package/dist/astro/routes/api/media/folders/index.mjs +41 -0
  219. package/dist/astro/routes/api/media/folders/index.mjs.map +1 -0
  220. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
  221. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
  222. package/dist/astro/routes/api/media/providers/index.mjs +2 -2
  223. package/dist/astro/routes/api/media/upload-url.mjs +16 -14
  224. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  225. package/dist/astro/routes/api/media.d.mts.map +1 -1
  226. package/dist/astro/routes/api/media.mjs +59 -27
  227. package/dist/astro/routes/api/media.mjs.map +1 -1
  228. package/dist/astro/routes/api/menus/_name_/items/_id_.d.mts.map +1 -1
  229. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +20 -13
  230. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  231. package/dist/astro/routes/api/menus/_name_/items.d.mts.map +1 -1
  232. package/dist/astro/routes/api/menus/_name_/items.mjs +15 -11
  233. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  234. package/dist/astro/routes/api/menus/_name_/reorder.d.mts.map +1 -1
  235. package/dist/astro/routes/api/menus/_name_/reorder.mjs +15 -11
  236. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  237. package/dist/astro/routes/api/menus/_name_/translations.d.mts.map +1 -1
  238. package/dist/astro/routes/api/menus/_name_/translations.mjs +16 -12
  239. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  240. package/dist/astro/routes/api/menus/_name_.d.mts.map +1 -1
  241. package/dist/astro/routes/api/menus/_name_.mjs +21 -14
  242. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  243. package/dist/astro/routes/api/menus/index.d.mts.map +1 -1
  244. package/dist/astro/routes/api/menus/index.mjs +15 -11
  245. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  246. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  247. package/dist/astro/routes/api/oauth/device/authorize.mjs +5 -5
  248. package/dist/astro/routes/api/oauth/device/code.mjs +8 -8
  249. package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
  250. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  251. package/dist/astro/routes/api/oauth/token/refresh.mjs +5 -5
  252. package/dist/astro/routes/api/oauth/token/revoke.mjs +5 -5
  253. package/dist/astro/routes/api/oauth/token.mjs +5 -5
  254. package/dist/astro/routes/api/openapi.json.mjs +253 -40
  255. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  256. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
  257. package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
  258. package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
  259. package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
  260. package/dist/astro/routes/api/redirects/index.mjs +11 -11
  261. package/dist/astro/routes/api/relations/_id_/index.mjs +17 -15
  262. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  263. package/dist/astro/routes/api/relations/_id_/translations.mjs +12 -10
  264. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  265. package/dist/astro/routes/api/relations/index.mjs +17 -15
  266. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  267. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
  268. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  269. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +53 -47
  270. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  271. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +53 -47
  272. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  273. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +53 -47
  274. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  275. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +53 -47
  276. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  277. package/dist/astro/routes/api/schema/collections/index.mjs +53 -47
  278. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  279. package/dist/astro/routes/api/schema/collections/reorder.mjs +53 -47
  280. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  281. package/dist/astro/routes/api/schema/index.mjs +10 -8
  282. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  283. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +53 -47
  284. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  285. package/dist/astro/routes/api/schema/orphans/index.mjs +53 -47
  286. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  287. package/dist/astro/routes/api/search/enable.mjs +10 -10
  288. package/dist/astro/routes/api/search/index.mjs +9 -9
  289. package/dist/astro/routes/api/search/rebuild.mjs +10 -10
  290. package/dist/astro/routes/api/search/stats.mjs +5 -5
  291. package/dist/astro/routes/api/search/suggest.mjs +9 -9
  292. package/dist/astro/routes/api/sections/_slug_.mjs +9 -9
  293. package/dist/astro/routes/api/sections/index.mjs +9 -9
  294. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +6 -6
  295. package/dist/astro/routes/api/settings/backups/archives/index.mjs +5 -5
  296. package/dist/astro/routes/api/settings/backups/export.mjs +6 -6
  297. package/dist/astro/routes/api/settings/backups/index.mjs +7 -7
  298. package/dist/astro/routes/api/settings/email.mjs +5 -5
  299. package/dist/astro/routes/api/settings/email.mjs.map +1 -1
  300. package/dist/astro/routes/api/settings.d.mts.map +1 -1
  301. package/dist/astro/routes/api/settings.mjs +20 -16
  302. package/dist/astro/routes/api/settings.mjs.map +1 -1
  303. package/dist/astro/routes/api/setup/admin-verify.mjs +12 -12
  304. package/dist/astro/routes/api/setup/admin.mjs +11 -11
  305. package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
  306. package/dist/astro/routes/api/setup/dev-bypass.mjs +35 -28
  307. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  308. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  309. package/dist/astro/routes/api/setup/index.mjs +32 -30
  310. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  311. package/dist/astro/routes/api/setup/status.mjs +3 -3
  312. package/dist/astro/routes/api/snapshot.mjs +7 -7
  313. package/dist/astro/routes/api/taxonomies/_name_/reorder.d.mts.map +1 -1
  314. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +20 -16
  315. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -1
  316. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.d.mts.map +1 -1
  317. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +21 -17
  318. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  319. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.d.mts.map +1 -1
  320. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +25 -18
  321. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  322. package/dist/astro/routes/api/taxonomies/_name_/terms/index.d.mts.map +1 -1
  323. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +20 -16
  324. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  325. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +14 -14
  326. package/dist/astro/routes/api/taxonomies/_name_.d.mts.map +1 -1
  327. package/dist/astro/routes/api/taxonomies/_name_.mjs +26 -19
  328. package/dist/astro/routes/api/taxonomies/_name_.mjs.map +1 -1
  329. package/dist/astro/routes/api/taxonomies/index.d.mts.map +1 -1
  330. package/dist/astro/routes/api/taxonomies/index.mjs +20 -16
  331. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  332. package/dist/astro/routes/api/themes/preview.mjs +5 -5
  333. package/dist/astro/routes/api/typegen.mjs +4 -4
  334. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  335. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  336. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  337. package/dist/astro/routes/api/widget-areas/_name_/reorder.d.mts.map +1 -1
  338. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +10 -8
  339. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs.map +1 -1
  340. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.d.mts.map +1 -1
  341. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +17 -13
  342. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs.map +1 -1
  343. package/dist/astro/routes/api/widget-areas/_name_/widgets.d.mts.map +1 -1
  344. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +15 -12
  345. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs.map +1 -1
  346. package/dist/astro/routes/api/widget-areas/_name_.d.mts.map +1 -1
  347. package/dist/astro/routes/api/widget-areas/_name_.mjs +8 -6
  348. package/dist/astro/routes/api/widget-areas/_name_.mjs.map +1 -1
  349. package/dist/astro/routes/api/widget-areas/index.d.mts.map +1 -1
  350. package/dist/astro/routes/api/widget-areas/index.mjs +15 -12
  351. package/dist/astro/routes/api/widget-areas/index.mjs.map +1 -1
  352. package/dist/astro/routes/api/widget-components.mjs +2 -2
  353. package/dist/astro/routes/robots.txt.mjs +7 -7
  354. package/dist/astro/routes/sitemap-_collection_.xml.mjs +10 -10
  355. package/dist/astro/routes/sitemap.xml.mjs +8 -8
  356. package/dist/astro/types.d.mts +37 -17
  357. package/dist/astro/types.d.mts.map +1 -1
  358. package/dist/auth/providers/github.d.mts +1 -1
  359. package/dist/auth/providers/google.d.mts +1 -1
  360. package/dist/{authorize-DUElxgOQ.mjs → authorize-Bkf_UHhD.mjs} +2 -2
  361. package/dist/{authorize-DUElxgOQ.mjs.map → authorize-Bkf_UHhD.mjs.map} +1 -1
  362. package/dist/{backup-DWYpJlLj.mjs → backup-rwVAl9NI.mjs} +5 -5
  363. package/dist/{backup-DWYpJlLj.mjs.map → backup-rwVAl9NI.mjs.map} +1 -1
  364. package/dist/{bundle-vn56sLos.mjs → bundle-C8S2Zl6U.mjs} +4 -4
  365. package/dist/{bundle-vn56sLos.mjs.map → bundle-C8S2Zl6U.mjs.map} +1 -1
  366. package/dist/{byline-yjvWq4ip.mjs → byline-DuhF7NWl.mjs} +27 -14
  367. package/dist/byline-DuhF7NWl.mjs.map +1 -0
  368. package/dist/{byline-fields-txaLGoME.mjs → byline-fields-BovY4KYM.mjs} +2 -2
  369. package/dist/{byline-fields-txaLGoME.mjs.map → byline-fields-BovY4KYM.mjs.map} +1 -1
  370. package/dist/{byline-registry-DDun8sxh.mjs → byline-registry-Bpu9-MVs.mjs} +2 -2
  371. package/dist/{byline-registry-DDun8sxh.mjs.map → byline-registry-Bpu9-MVs.mjs.map} +1 -1
  372. package/dist/{bylines-DjXS5p0P.mjs → bylines-CJ5nd6Lw.mjs} +7 -7
  373. package/dist/{bylines-DjXS5p0P.mjs.map → bylines-CJ5nd6Lw.mjs.map} +1 -1
  374. package/dist/{bylines-Bu7pchQ4.mjs → bylines-RwBAeOF1.mjs} +3 -3
  375. package/dist/{bylines-Bu7pchQ4.mjs.map → bylines-RwBAeOF1.mjs.map} +1 -1
  376. package/dist/{cache-C46-3Irl.mjs → cache-BF5Kvn59.mjs} +4 -4
  377. package/dist/{cache-C46-3Irl.mjs.map → cache-BF5Kvn59.mjs.map} +1 -1
  378. package/dist/capture-triggers-CNW1q3HK.mjs +362 -0
  379. package/dist/capture-triggers-CNW1q3HK.mjs.map +1 -0
  380. package/dist/{challenge-store-SIL5DsF2.mjs → challenge-store-DQN_Yrck.mjs} +5 -3
  381. package/dist/challenge-store-DQN_Yrck.mjs.map +1 -0
  382. package/dist/chrome-tags-D8fiZG94.mjs +24 -0
  383. package/dist/chrome-tags-D8fiZG94.mjs.map +1 -0
  384. package/dist/{chunks-fiZ8G9RJ.mjs → chunks-C4szrD8o.mjs} +2 -2
  385. package/dist/{chunks-fiZ8G9RJ.mjs.map → chunks-C4szrD8o.mjs.map} +1 -1
  386. package/dist/cli/index.mjs +37 -53
  387. package/dist/cli/index.mjs.map +1 -1
  388. package/dist/client/cf-access.d.mts +1 -1
  389. package/dist/client/index.d.mts +74 -4
  390. package/dist/client/index.d.mts.map +1 -1
  391. package/dist/client/index.mjs +54 -2
  392. package/dist/client/index.mjs.map +1 -1
  393. package/dist/{collection-deletion-DQPvMD8R.mjs → collection-deletion-Bj07NHbj.mjs} +13 -356
  394. package/dist/collection-deletion-Bj07NHbj.mjs.map +1 -0
  395. package/dist/{comment-reaction-D-2J84UE.mjs → comment-reaction-BhrvSHml.mjs} +2 -2
  396. package/dist/{comment-reaction-D-2J84UE.mjs.map → comment-reaction-BhrvSHml.mjs.map} +1 -1
  397. package/dist/{comment-Dxlep6cE.mjs → comment-vxOzWbZN.mjs} +2 -2
  398. package/dist/{comment-Dxlep6cE.mjs.map → comment-vxOzWbZN.mjs.map} +1 -1
  399. package/dist/{comments-CTfZtLmM.mjs → comments-Ct4ensnf.mjs} +2 -2
  400. package/dist/{comments-CTfZtLmM.mjs.map → comments-Ct4ensnf.mjs.map} +1 -1
  401. package/dist/{components-CQy3lh9x.mjs → components-DJbo1z0S.mjs} +1 -1
  402. package/dist/{components-CQy3lh9x.mjs.map → components-DJbo1z0S.mjs.map} +1 -1
  403. package/dist/{config-COQzTe5Q.d.mts → config-B9eZ340f.d.mts} +1 -1
  404. package/dist/{config-COQzTe5Q.d.mts.map → config-B9eZ340f.d.mts.map} +1 -1
  405. package/dist/config-it29yDLA.mjs +1163 -0
  406. package/dist/config-it29yDLA.mjs.map +1 -0
  407. package/dist/{content-ZHCc1ngN.mjs → content-DjvM0T92.mjs} +86 -45
  408. package/dist/content-DjvM0T92.mjs.map +1 -0
  409. package/dist/{content-list-query-wJ2WN8Vp.d.mts → content-list-query-Btqd4uV2.d.mts} +1 -1
  410. package/dist/{content-list-query-wJ2WN8Vp.d.mts.map → content-list-query-Btqd4uV2.d.mts.map} +1 -1
  411. package/dist/{content-refresh-B_8SJzuU.mjs → content-refresh-Bwp-8yGy.mjs} +1139 -111
  412. package/dist/content-refresh-Bwp-8yGy.mjs.map +1 -0
  413. package/dist/{media-usage-BZCydfvu.mjs → content-repair-Czdp7jz5.mjs} +5 -196
  414. package/dist/content-repair-Czdp7jz5.mjs.map +1 -0
  415. package/dist/{context-ZldbZcle.mjs → context-CX6gxOLW.mjs} +55 -20
  416. package/dist/context-CX6gxOLW.mjs.map +1 -0
  417. package/dist/{cron-Y9aLtgrA.mjs → cron-C6o7VppJ.mjs} +1 -1
  418. package/dist/{cron-Y9aLtgrA.mjs.map → cron-C6o7VppJ.mjs.map} +1 -1
  419. package/dist/{dashboard-DvHbk_cv.mjs → dashboard-C2kTeeRI.mjs} +5 -5
  420. package/dist/{dashboard-DvHbk_cv.mjs.map → dashboard-C2kTeeRI.mjs.map} +1 -1
  421. package/dist/db/index.d.mts +3 -3
  422. package/dist/db/index.mjs +3 -3
  423. package/dist/db/index.mjs.map +1 -1
  424. package/dist/db/libsql-migrations.d.mts +1 -1
  425. package/dist/db/libsql-migrations.mjs +4 -4
  426. package/dist/db/libsql.d.mts +1 -1
  427. package/dist/db/postgres-migrations.d.mts +1 -1
  428. package/dist/db/postgres-migrations.mjs +4 -4
  429. package/dist/db/postgres.d.mts +1 -1
  430. package/dist/db/postgres.d.mts.map +1 -1
  431. package/dist/db/postgres.mjs +19 -3
  432. package/dist/db/postgres.mjs.map +1 -1
  433. package/dist/db/sqlite-migrations.d.mts +1 -1
  434. package/dist/db/sqlite-migrations.mjs +4 -4
  435. package/dist/db/sqlite.d.mts +1 -1
  436. package/dist/db/sqlite.mjs +3 -3
  437. package/dist/db/sqlite.mjs.map +1 -1
  438. package/dist/{default-DdDl3fxv.mjs → default-Clra32mw.mjs} +1 -1
  439. package/dist/{default-DdDl3fxv.mjs.map → default-Clra32mw.mjs.map} +1 -1
  440. package/dist/{deferred-tasks-SDWxrgzJ.d.mts → deferred-tasks-CvDETTJO.d.mts} +1 -1
  441. package/dist/{deferred-tasks-SDWxrgzJ.d.mts.map → deferred-tasks-CvDETTJO.d.mts.map} +1 -1
  442. package/dist/dev-typegen-DzOPfsNj.mjs +29 -0
  443. package/dist/dev-typegen-DzOPfsNj.mjs.map +1 -0
  444. package/dist/{device-flow-C0GdD_z8.mjs → device-flow-D2oCWvLJ.mjs} +5 -5
  445. package/dist/{device-flow-C0GdD_z8.mjs.map → device-flow-D2oCWvLJ.mjs.map} +1 -1
  446. package/dist/{direct-executor-CDXeJCSs.mjs → direct-executor-Bfa5_ToE.mjs} +3 -3
  447. package/dist/{direct-executor-CDXeJCSs.mjs.map → direct-executor-Bfa5_ToE.mjs.map} +1 -1
  448. package/dist/{dist-D_6CKR8z.mjs → dist-89xCrGqi.mjs} +1 -1
  449. package/dist/{dist-D_6CKR8z.mjs.map → dist-89xCrGqi.mjs.map} +1 -1
  450. package/dist/{email-console-BHNjIwiB.mjs → email-console-Dzb6uGYa.mjs} +1 -1
  451. package/dist/{email-console-BHNjIwiB.mjs.map → email-console-Dzb6uGYa.mjs.map} +1 -1
  452. package/dist/{enrich-_ySMEvEE.mjs → enrich-BX0IDp4z.mjs} +3 -3
  453. package/dist/{enrich-_ySMEvEE.mjs.map → enrich-BX0IDp4z.mjs.map} +1 -1
  454. package/dist/{error-DupyJZE2.mjs → error-DFrQjppn.mjs} +2 -2
  455. package/dist/{error-DupyJZE2.mjs.map → error-DFrQjppn.mjs.map} +1 -1
  456. package/dist/{errors-CLUPm7aD.mjs → errors-DsVoDUjJ.mjs} +24 -2
  457. package/dist/errors-DsVoDUjJ.mjs.map +1 -0
  458. package/dist/{escape-DUY2r2Zs.mjs → escape-HmHTC1Is.mjs} +1 -1
  459. package/dist/{escape-DUY2r2Zs.mjs.map → escape-HmHTC1Is.mjs.map} +1 -1
  460. package/dist/{field-defs-cache-BzwBlJrR.mjs → field-defs-cache-BM4SIRqH.mjs} +5 -5
  461. package/dist/{field-defs-cache-BzwBlJrR.mjs.map → field-defs-cache-BM4SIRqH.mjs.map} +1 -1
  462. package/dist/focal-point-BeWFo6Xx.mjs +23 -0
  463. package/dist/focal-point-BeWFo6Xx.mjs.map +1 -0
  464. package/dist/{fts-manager-DyZEohZC.mjs → fts-manager-Do1BlW2r.mjs} +3 -3
  465. package/dist/{fts-manager-DyZEohZC.mjs.map → fts-manager-Do1BlW2r.mjs.map} +1 -1
  466. package/dist/{hash-Cg0TXJPV.mjs → hash-3JJPlHF2.mjs} +1 -1
  467. package/dist/{hash-Cg0TXJPV.mjs.map → hash-3JJPlHF2.mjs.map} +1 -1
  468. package/dist/hook-result-DCh2WUpe.d.mts +31 -0
  469. package/dist/hook-result-DCh2WUpe.d.mts.map +1 -0
  470. package/dist/{hreflang-DwT2E0Sa.d.mts → hreflang-B6hbAuuO.d.mts} +2 -2
  471. package/dist/{hreflang-DwT2E0Sa.d.mts.map → hreflang-B6hbAuuO.d.mts.map} +1 -1
  472. package/dist/{hreflang-BBe83kKa.mjs → hreflang-DQbPZliA.mjs} +7 -7
  473. package/dist/{hreflang-BBe83kKa.mjs.map → hreflang-DQbPZliA.mjs.map} +1 -1
  474. package/dist/{identity-Ys6Dlc9C.mjs → identity-DksvEazf.mjs} +3 -3
  475. package/dist/{identity-Ys6Dlc9C.mjs.map → identity-DksvEazf.mjs.map} +1 -1
  476. package/dist/{import-DPkLmeXO.mjs → import-CJpaBBBT.mjs} +6 -6
  477. package/dist/{import-DPkLmeXO.mjs.map → import-CJpaBBBT.mjs.map} +1 -1
  478. package/dist/{index-BVBZj4-7.d.mts → index-BJNMCWmu.d.mts} +267 -82
  479. package/dist/index-BJNMCWmu.d.mts.map +1 -0
  480. package/dist/{index-C9KuQyO-.d.mts → index-Du8K7bWa.d.mts} +3 -3
  481. package/dist/{index-C9KuQyO-.d.mts.map → index-Du8K7bWa.d.mts.map} +1 -1
  482. package/dist/index.d.mts +22 -21
  483. package/dist/index.mjs +79 -73
  484. package/dist/{init-lock-6b309ZrF.mjs → init-lock-DJkX6Hto.mjs} +1 -1
  485. package/dist/{init-lock-6b309ZrF.mjs.map → init-lock-DJkX6Hto.mjs.map} +1 -1
  486. package/dist/{load-YJ2xl3ra.mjs → load-CawHjTOH.mjs} +2 -2
  487. package/dist/{load-YJ2xl3ra.mjs.map → load-CawHjTOH.mjs.map} +1 -1
  488. package/dist/{loader-CdG_Ci3H.mjs → loader-Z8vl7zTq.mjs} +48 -13
  489. package/dist/loader-Z8vl7zTq.mjs.map +1 -0
  490. package/dist/{manifest-builder-B252yQUf.mjs → manifest-builder-COtzuca2.mjs} +2 -2
  491. package/dist/{manifest-builder-B252yQUf.mjs.map → manifest-builder-COtzuca2.mjs.map} +1 -1
  492. package/dist/{manifest-schema-BXbUAHod.mjs → manifest-schema-BNWwR8Vd.mjs} +5 -5
  493. package/dist/manifest-schema-BNWwR8Vd.mjs.map +1 -0
  494. package/dist/media/image-endpoint.d.mts +4 -2
  495. package/dist/media/image-endpoint.d.mts.map +1 -1
  496. package/dist/media/image-endpoint.mjs +6 -4
  497. package/dist/media/image-endpoint.mjs.map +1 -1
  498. package/dist/media/index.d.mts +1 -1
  499. package/dist/media/index.mjs +13 -3
  500. package/dist/media/index.mjs.map +1 -1
  501. package/dist/media/local-runtime.d.mts +14 -12
  502. package/dist/media/local-runtime.d.mts.map +1 -1
  503. package/dist/media/local-runtime.mjs +12 -6
  504. package/dist/media/local-runtime.mjs.map +1 -1
  505. package/dist/{media-CzhAn2--.mjs → media-BBm8Wg3f.mjs} +69 -12
  506. package/dist/media-BBm8Wg3f.mjs.map +1 -0
  507. package/dist/{media-BWWWb8kg.mjs → media-BHjus86Y.mjs} +133 -9
  508. package/dist/media-BHjus86Y.mjs.map +1 -0
  509. package/dist/{media-allowlist-D6x-Us02.mjs → media-allowlist-CoTBWoDp.mjs} +3 -2
  510. package/dist/media-allowlist-CoTBWoDp.mjs.map +1 -0
  511. package/dist/media-folders-BGkATs8n.mjs +210 -0
  512. package/dist/media-folders-BGkATs8n.mjs.map +1 -0
  513. package/dist/{media-upload-CHBVn6m-.mjs → media-upload-BCidR-EY.mjs} +9 -9
  514. package/dist/{media-upload-CHBVn6m-.mjs.map → media-upload-BCidR-EY.mjs.map} +1 -1
  515. package/dist/{media-url-BvoX88FA.mjs → media-url-DHoPr0hq.mjs} +1 -1
  516. package/dist/{media-url-BvoX88FA.mjs.map → media-url-DHoPr0hq.mjs.map} +1 -1
  517. package/dist/media-usage-CdY5jhSR.mjs +1833 -0
  518. package/dist/media-usage-CdY5jhSR.mjs.map +1 -0
  519. package/dist/media-usage-activation-BgeMtK5C.mjs +78 -0
  520. package/dist/media-usage-activation-BgeMtK5C.mjs.map +1 -0
  521. package/dist/{media-usage-work-CLo_6tct.mjs → media-usage-work-CnGCdHxx.mjs} +4 -4
  522. package/dist/{media-usage-work-CLo_6tct.mjs.map → media-usage-work-CnGCdHxx.mjs.map} +1 -1
  523. package/dist/{media-usage-work-DrCbqBcl.mjs → media-usage-work-D6D9sMCA.mjs} +221 -59
  524. package/dist/media-usage-work-D6D9sMCA.mjs.map +1 -0
  525. package/dist/{media-usage-write-fence-aHEgN1zB.mjs → media-usage-write-fence-hjeD4u7s.mjs} +2 -2
  526. package/dist/{media-usage-write-fence-aHEgN1zB.mjs.map → media-usage-write-fence-hjeD4u7s.mjs.map} +1 -1
  527. package/dist/{menus-DSo5QeW0.mjs → menus-6qSwTNxG.mjs} +375 -107
  528. package/dist/menus-6qSwTNxG.mjs.map +1 -0
  529. package/dist/{menus-TCNSd2vp.mjs → menus-uvPLXMZf.mjs} +4 -4
  530. package/dist/{menus-TCNSd2vp.mjs.map → menus-uvPLXMZf.mjs.map} +1 -1
  531. package/dist/migrations/index.d.mts +1 -1
  532. package/dist/migrations/index.mjs +3 -3
  533. package/dist/{mime-DfIVjNkr.mjs → mime-CUIG6x84.mjs} +1 -1
  534. package/dist/mime-CUIG6x84.mjs.map +1 -0
  535. package/dist/{mode-BDoH_WcF.mjs → mode-DN_WneRx.mjs} +1 -1
  536. package/dist/{mode-BDoH_WcF.mjs.map → mode-DN_WneRx.mjs.map} +1 -1
  537. package/dist/node-sqlite-compat-BuJXIeMz.mjs +46 -0
  538. package/dist/node-sqlite-compat-BuJXIeMz.mjs.map +1 -0
  539. package/dist/{normalize-Bc-s_r-a.mjs → normalize-C2xNjTSG.mjs} +36 -5
  540. package/dist/normalize-C2xNjTSG.mjs.map +1 -0
  541. package/dist/{oauth-authorization-iOikmrJd.mjs → oauth-authorization-Dj6Kwc21.mjs} +5 -5
  542. package/dist/{oauth-authorization-iOikmrJd.mjs.map → oauth-authorization-Dj6Kwc21.mjs.map} +1 -1
  543. package/dist/{oauth-clients-CvI0nHMJ.mjs → oauth-clients-FD7I0J8m.mjs} +1 -1
  544. package/dist/{oauth-clients-CvI0nHMJ.mjs.map → oauth-clients-FD7I0J8m.mjs.map} +1 -1
  545. package/dist/{oauth-state-store-Ba8KZlwW.mjs → oauth-state-store-DkmDOmHs.mjs} +1 -1
  546. package/dist/{oauth-state-store-Ba8KZlwW.mjs.map → oauth-state-store-DkmDOmHs.mjs.map} +1 -1
  547. package/dist/{oauth-user-lookup-C5SQwGYC.mjs → oauth-user-lookup-CvIwGpYd.mjs} +1 -1
  548. package/dist/{oauth-user-lookup-C5SQwGYC.mjs.map → oauth-user-lookup-CvIwGpYd.mjs.map} +1 -1
  549. package/dist/object-cache/memory.d.mts +1 -1
  550. package/dist/{object-cache-71tPfV4A.mjs → object-cache-DVKnyOfy.mjs} +19 -3
  551. package/dist/object-cache-DVKnyOfy.mjs.map +1 -0
  552. package/dist/{options-CBXIHUoT.mjs → options-BHPeIbBd.mjs} +1 -1
  553. package/dist/{options-CBXIHUoT.mjs.map → options-BHPeIbBd.mjs.map} +1 -1
  554. package/dist/{options--hhz-jZ1.d.mts → options-CYb4y7hM.d.mts} +24 -11
  555. package/dist/options-CYb4y7hM.d.mts.map +1 -0
  556. package/dist/page/index.d.mts +2 -2
  557. package/dist/{parse-DFbuc-Fh.mjs → parse-Ckpg-Qfp.mjs} +2 -2
  558. package/dist/{parse-DFbuc-Fh.mjs.map → parse-Ckpg-Qfp.mjs.map} +1 -1
  559. package/dist/{passkey-config-DFAmUyuE.mjs → passkey-config-O_lj3y0k.mjs} +1 -1
  560. package/dist/{passkey-config-DFAmUyuE.mjs.map → passkey-config-O_lj3y0k.mjs.map} +1 -1
  561. package/dist/{patterns-CiyXeDgr.mjs → patterns-D9iDO3j8.mjs} +1 -1
  562. package/dist/{patterns-CiyXeDgr.mjs.map → patterns-D9iDO3j8.mjs.map} +1 -1
  563. package/dist/{placeholder-Dp0K3RkD.d.mts → placeholder-4X9BrRrp.d.mts} +7 -1
  564. package/dist/placeholder-4X9BrRrp.d.mts.map +1 -0
  565. package/dist/plugin-types.d.mts +8 -3
  566. package/dist/plugin-types.d.mts.map +1 -1
  567. package/dist/plugin-utils.d.mts +10 -10
  568. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  569. package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
  570. package/dist/{policy-TluUIxuu.mjs → policy-Dhtwntrt.mjs} +2 -2
  571. package/dist/{policy-TluUIxuu.mjs.map → policy-Dhtwntrt.mjs.map} +1 -1
  572. package/dist/{portable-text-imBW5cHK.mjs → portable-text-U85hOafW.mjs} +1 -1
  573. package/dist/{portable-text-imBW5cHK.mjs.map → portable-text-U85hOafW.mjs.map} +1 -1
  574. package/dist/{preview-PW-nOnq4.mjs → preview-B_vJLvf8.mjs} +2 -2
  575. package/dist/{preview-PW-nOnq4.mjs.map → preview-B_vJLvf8.mjs.map} +1 -1
  576. package/dist/{protocol-DjsJHTlK.d.mts → protocol-JdD2YhY9.d.mts} +2 -2
  577. package/dist/{protocol-DjsJHTlK.d.mts.map → protocol-JdD2YhY9.d.mts.map} +1 -1
  578. package/dist/{public-url-CWoFhQT8.mjs → public-url-CarhZJgf.mjs} +1 -1
  579. package/dist/{public-url-CWoFhQT8.mjs.map → public-url-CarhZJgf.mjs.map} +1 -1
  580. package/dist/{query-zTVAR1Sl.mjs → query-BZKZcG5b.mjs} +15 -15
  581. package/dist/{query-zTVAR1Sl.mjs.map → query-BZKZcG5b.mjs.map} +1 -1
  582. package/dist/{query-BWs7O5Il.mjs → query-BndaFxxp.mjs} +5 -5
  583. package/dist/{query-BWs7O5Il.mjs.map → query-BndaFxxp.mjs.map} +1 -1
  584. package/dist/{rate-limit-Bx4g9m3p.mjs → rate-limit-BZmATC6W.mjs} +2 -2
  585. package/dist/{rate-limit-Bx4g9m3p.mjs.map → rate-limit-BZmATC6W.mjs.map} +1 -1
  586. package/dist/{redirect-COsS6SWJ.mjs → redirect-CZkbozu9.mjs} +2 -2
  587. package/dist/{redirect-COsS6SWJ.mjs.map → redirect-CZkbozu9.mjs.map} +1 -1
  588. package/dist/{redirect-BgAOGHDq.mjs → redirect-CzqnLxK-.mjs} +1 -1
  589. package/dist/{redirect-BgAOGHDq.mjs.map → redirect-CzqnLxK-.mjs.map} +1 -1
  590. package/dist/{redirects-DTDHWH31.mjs → redirects-BLNOWQTn.mjs} +64 -29
  591. package/dist/redirects-BLNOWQTn.mjs.map +1 -0
  592. package/dist/{redirects-DyChwDkG.mjs → redirects-CqzNM0KM.mjs} +5 -5
  593. package/dist/{redirects-DyChwDkG.mjs.map → redirects-CqzNM0KM.mjs.map} +1 -1
  594. package/dist/{registry-Cqa2I749.mjs → registry-AZAsRsor.mjs} +30 -126
  595. package/dist/registry-AZAsRsor.mjs.map +1 -0
  596. package/dist/{relation-BnHB0T4J.mjs → relation-04DfKRTO.mjs} +2 -2
  597. package/dist/{relation-BnHB0T4J.mjs.map → relation-04DfKRTO.mjs.map} +1 -1
  598. package/dist/{relations-BBApI4e2.mjs → relations-C4htk5sb.mjs} +7 -7
  599. package/dist/relations-C4htk5sb.mjs.map +1 -0
  600. package/dist/{relations-D5sM5fW0.mjs → relations-CcFwDJdJ.mjs} +4 -4
  601. package/dist/{relations-D5sM5fW0.mjs.map → relations-CcFwDJdJ.mjs.map} +1 -1
  602. package/dist/{relations-BHo5A8Zf.d.mts → relations-DnRK4YIT.d.mts} +347 -54
  603. package/dist/relations-DnRK4YIT.d.mts.map +1 -0
  604. package/dist/{request-cache-BSUptuJR.mjs → request-cache-DH9zdCOD.mjs} +1 -1
  605. package/dist/{request-cache-BSUptuJR.mjs.map → request-cache-DH9zdCOD.mjs.map} +1 -1
  606. package/dist/request-context.d.mts +1 -1
  607. package/dist/{request-meta-DgZJh3zG.mjs → request-meta-DYxLlnmz.mjs} +2 -2
  608. package/dist/{request-meta-DgZJh3zG.mjs.map → request-meta-DYxLlnmz.mjs.map} +1 -1
  609. package/dist/{resolve-DOhVEvty.mjs → resolve-prZ3mP7l.mjs} +1 -1
  610. package/dist/{resolve-DOhVEvty.mjs.map → resolve-prZ3mP7l.mjs.map} +1 -1
  611. package/dist/{runner-C1T11CfC.mjs → runner-BLIDKpmA.mjs} +471 -290
  612. package/dist/runner-BLIDKpmA.mjs.map +1 -0
  613. package/dist/{runner-BYHZn3Jy.d.mts → runner-YKfIMnaF.d.mts} +3 -2
  614. package/dist/runner-YKfIMnaF.d.mts.map +1 -0
  615. package/dist/runtime.d.mts +11 -11
  616. package/dist/runtime.mjs +1 -1
  617. package/dist/{schema-DZ5YVVZj.mjs → schema-CGnBeLiW.mjs} +3 -3
  618. package/dist/{schema-DZ5YVVZj.mjs.map → schema-CGnBeLiW.mjs.map} +1 -1
  619. package/dist/{schema-2AOsSn2v.mjs → schema-DYr-Vd-L.mjs} +36 -6
  620. package/dist/{schema-2AOsSn2v.mjs.map → schema-DYr-Vd-L.mjs.map} +1 -1
  621. package/dist/{scopes-8ClPF2bC.mjs → scopes-BhWvBavj.mjs} +3 -3
  622. package/dist/{scopes-8ClPF2bC.mjs.map → scopes-BhWvBavj.mjs.map} +1 -1
  623. package/dist/{search-u1QYdOCG.mjs → search-C-qDk4kx.mjs} +4 -4
  624. package/dist/{search-u1QYdOCG.mjs.map → search-C-qDk4kx.mjs.map} +1 -1
  625. package/dist/{secrets-BEgsAQEU.mjs → secrets-rEtHt-6z.mjs} +3 -3
  626. package/dist/{secrets-BEgsAQEU.mjs.map → secrets-rEtHt-6z.mjs.map} +1 -1
  627. package/dist/{sections-DmHviGyM.mjs → sections-B_nYvlwn.mjs} +2 -2
  628. package/dist/{sections-DmHviGyM.mjs.map → sections-B_nYvlwn.mjs.map} +1 -1
  629. package/dist/seed/index.d.mts +2 -2
  630. package/dist/seed/index.mjs +25 -23
  631. package/dist/seo/index.d.mts +3 -3
  632. package/dist/seo/index.mjs +17 -15
  633. package/dist/seo/index.mjs.map +1 -1
  634. package/dist/{seo-Dq4G-RrO.mjs → seo-926NRIgt.mjs} +3 -3
  635. package/dist/{seo-Dq4G-RrO.mjs.map → seo-926NRIgt.mjs.map} +1 -1
  636. package/dist/{seo-AFpVvTqr.mjs → seo-CVWkdv6x.mjs} +1 -1
  637. package/dist/{seo-AFpVvTqr.mjs.map → seo-CVWkdv6x.mjs.map} +1 -1
  638. package/dist/{service-BpArayPr.mjs → service-CJl3ZAYs.mjs} +3 -3
  639. package/dist/{service-BpArayPr.mjs.map → service-CJl3ZAYs.mjs.map} +1 -1
  640. package/dist/{session-user-BEorKVT-.mjs → session-user-BlMgqCHS.mjs} +1 -1
  641. package/dist/{session-user-BEorKVT-.mjs.map → session-user-BlMgqCHS.mjs.map} +1 -1
  642. package/dist/{settings-xRdoUZr0.mjs → settings--wobrkkC.mjs} +21 -8
  643. package/dist/settings--wobrkkC.mjs.map +1 -0
  644. package/dist/{settings-DE9xtzqd.mjs → settings-Cwm6o2jY.mjs} +3 -3
  645. package/dist/{settings-DE9xtzqd.mjs.map → settings-Cwm6o2jY.mjs.map} +1 -1
  646. package/dist/{setup-complete-BnT8pq_C.mjs → setup-complete-DQbClIN2.mjs} +2 -2
  647. package/dist/{setup-complete-BnT8pq_C.mjs.map → setup-complete-DQbClIN2.mjs.map} +1 -1
  648. package/dist/{setup-nonce-CBitf_oQ.mjs → setup-nonce-DZCFS2sn.mjs} +1 -1
  649. package/dist/{setup-nonce-CBitf_oQ.mjs.map → setup-nonce-DZCFS2sn.mjs.map} +1 -1
  650. package/dist/{single-flight-cache-B0eLKS6K.mjs → single-flight-cache-BPuGPdcN.mjs} +2 -2
  651. package/dist/{single-flight-cache-B0eLKS6K.mjs.map → single-flight-cache-BPuGPdcN.mjs.map} +1 -1
  652. package/dist/{site-url-DjpIXMXJ.mjs → site-url-BrxA_E9H.mjs} +3 -3
  653. package/dist/{site-url-DjpIXMXJ.mjs.map → site-url-BrxA_E9H.mjs.map} +1 -1
  654. package/dist/{snapshot-BBlGkb2q.mjs → snapshot--OCDTqdb.mjs} +1 -1
  655. package/dist/{snapshot-BBlGkb2q.mjs.map → snapshot--OCDTqdb.mjs.map} +1 -1
  656. package/dist/{ssrf-Cpvg_n3A.mjs → ssrf-5sIM5jzl.mjs} +23 -6
  657. package/dist/{ssrf-Cpvg_n3A.mjs.map → ssrf-5sIM5jzl.mjs.map} +1 -1
  658. package/dist/{state-DYwPue40.mjs → state-BpFVsJZB.mjs} +12 -4
  659. package/dist/state-BpFVsJZB.mjs.map +1 -0
  660. package/dist/{status-CWVYpbD8.mjs → status-B777-dXz.mjs} +1 -1
  661. package/dist/{status-CWVYpbD8.mjs.map → status-B777-dXz.mjs.map} +1 -1
  662. package/dist/storage/local.d.mts +2 -1
  663. package/dist/storage/local.d.mts.map +1 -1
  664. package/dist/storage/local.mjs +1 -1
  665. package/dist/storage/local.mjs.map +1 -1
  666. package/dist/storage/s3.d.mts +2 -1
  667. package/dist/storage/s3.d.mts.map +1 -1
  668. package/dist/storage/s3.mjs +3 -2
  669. package/dist/storage/s3.mjs.map +1 -1
  670. package/dist/{target-DixqqV5i.mjs → target-BmR0iTwz.mjs} +1 -1
  671. package/dist/{target-DixqqV5i.mjs.map → target-BmR0iTwz.mjs.map} +1 -1
  672. package/dist/{taxonomies-OHUIiIpI.mjs → taxonomies-DkAkMupr.mjs} +17 -14
  673. package/dist/taxonomies-DkAkMupr.mjs.map +1 -0
  674. package/dist/{taxonomies-BlrncHi9.mjs → taxonomies-Wfy_Lg12.mjs} +43 -17
  675. package/dist/taxonomies-Wfy_Lg12.mjs.map +1 -0
  676. package/dist/{taxonomy-BqCZ1TdU.mjs → taxonomy-tJepplLL.mjs} +5 -5
  677. package/dist/{taxonomy-BqCZ1TdU.mjs.map → taxonomy-tJepplLL.mjs.map} +1 -1
  678. package/dist/{tokens-C39klX8R.mjs → tokens-BCO1oruF.mjs} +1 -1
  679. package/dist/{tokens-C39klX8R.mjs.map → tokens-BCO1oruF.mjs.map} +1 -1
  680. package/dist/{transaction-NQj4VJ7Z.mjs → transaction-0KOpOyMu.mjs} +2 -1
  681. package/dist/{transaction-NQj4VJ7Z.mjs.map → transaction-0KOpOyMu.mjs.map} +1 -1
  682. package/dist/{transport-DBJwa-Si.mjs → transport-Dr3qtwXC.mjs} +4 -3
  683. package/dist/{transport-DBJwa-Si.mjs.map → transport-Dr3qtwXC.mjs.map} +1 -1
  684. package/dist/{transport-RQE36APG.d.mts → transport-xh6YKW2G.d.mts} +1 -1
  685. package/dist/{transport-RQE36APG.d.mts.map → transport-xh6YKW2G.d.mts.map} +1 -1
  686. package/dist/{trusted-proxy-CEVekpby.mjs → trusted-proxy-BR5F1Otp.mjs} +1 -1
  687. package/dist/{trusted-proxy-CEVekpby.mjs.map → trusted-proxy-BR5F1Otp.mjs.map} +1 -1
  688. package/dist/{types-BW1syrlw.mjs → types-3qNFPlci.mjs} +1 -1
  689. package/dist/{types-BW1syrlw.mjs.map → types-3qNFPlci.mjs.map} +1 -1
  690. package/dist/types-75KIqzL9.mjs.map +1 -1
  691. package/dist/{types-DrJrVCT1.d.mts → types-B6GrPic4.d.mts} +9 -3
  692. package/dist/{types-DrJrVCT1.d.mts.map → types-B6GrPic4.d.mts.map} +1 -1
  693. package/dist/{types-DN64_zzZ.d.mts → types-BuHW4xDE.d.mts} +11 -10
  694. package/dist/types-BuHW4xDE.d.mts.map +1 -0
  695. package/dist/{types-DWRhk9xZ.d.mts → types-C00oyCZp.d.mts} +1 -1
  696. package/dist/{types-DWRhk9xZ.d.mts.map → types-C00oyCZp.d.mts.map} +1 -1
  697. package/dist/{types-BntycPTF.d.mts → types-CDtkNSFQ.d.mts} +1 -1
  698. package/dist/{types-BntycPTF.d.mts.map → types-CDtkNSFQ.d.mts.map} +1 -1
  699. package/dist/{types-Dfk8KI5R.d.mts → types-CPeXo1wF.d.mts} +1 -1
  700. package/dist/{types-Dfk8KI5R.d.mts.map → types-CPeXo1wF.d.mts.map} +1 -1
  701. package/dist/types-CQPWhPxE.mjs.map +1 -1
  702. package/dist/{types-BcqdcT-r.d.mts → types-CXFkwEGC.d.mts} +3 -2
  703. package/dist/types-CXFkwEGC.d.mts.map +1 -0
  704. package/dist/{types-CtzytVXn.mjs → types-DM3vioBY.mjs} +1 -1
  705. package/dist/{types-CtzytVXn.mjs.map → types-DM3vioBY.mjs.map} +1 -1
  706. package/dist/{types-CXnOzDe1.d.mts → types-DczELMop.d.mts} +1 -1
  707. package/dist/{types-CXnOzDe1.d.mts.map → types-DczELMop.d.mts.map} +1 -1
  708. package/dist/types-DfuTR6dL.mjs +3 -0
  709. package/dist/{types-DQIDRKF2.d.mts → types-FV23hEoW.d.mts} +10 -1
  710. package/dist/types-FV23hEoW.d.mts.map +1 -0
  711. package/dist/{types-C2pMvO62.d.mts → types-xDMtUFnO.d.mts} +2 -1
  712. package/dist/types-xDMtUFnO.d.mts.map +1 -0
  713. package/dist/{upload-attempts-D4FS8LT6.mjs → upload-attempts-BsqoQ1fn.mjs} +1 -1
  714. package/dist/{upload-attempts-D4FS8LT6.mjs.map → upload-attempts-BsqoQ1fn.mjs.map} +1 -1
  715. package/dist/{url-pattern-BHS0V5Ng.mjs → url-pattern-D4c2czpJ.mjs} +1 -1
  716. package/dist/{url-pattern-BHS0V5Ng.mjs.map → url-pattern-D4c2czpJ.mjs.map} +1 -1
  717. package/dist/{user-DJZfUJVE.mjs → user-BTZ40aq6.mjs} +2 -2
  718. package/dist/{user-DJZfUJVE.mjs.map → user-BTZ40aq6.mjs.map} +1 -1
  719. package/dist/{utils-D4vD_Y98.mjs → utils-BKvNjjhY.mjs} +1 -1
  720. package/dist/{utils-D4vD_Y98.mjs.map → utils-BKvNjjhY.mjs.map} +1 -1
  721. package/dist/{validate-BMLBvxOC.mjs → validate-DE_LRwo9.mjs} +2 -2
  722. package/dist/{validate-BMLBvxOC.mjs.map → validate-DE_LRwo9.mjs.map} +1 -1
  723. package/dist/{validate-CTqt5nuE.d.mts → validate-DUP27OYD.d.mts} +5 -5
  724. package/dist/{validate-CTqt5nuE.d.mts.map → validate-DUP27OYD.d.mts.map} +1 -1
  725. package/dist/{validation-npvENUCB.mjs → validation-BMImFJ11.mjs} +10 -8
  726. package/dist/{validation-npvENUCB.mjs.map → validation-BMImFJ11.mjs.map} +1 -1
  727. package/dist/version-Bii3suaO.mjs +7 -0
  728. package/dist/{version-DB_fqCSI.mjs.map → version-Bii3suaO.mjs.map} +1 -1
  729. package/dist/{widgets-BD3ho7Rq.mjs → widgets-D3gJ10xU.mjs} +18 -5
  730. package/dist/widgets-D3gJ10xU.mjs.map +1 -0
  731. package/dist/{wxr-taxonomies-Ca68766D.d.mts → wxr-taxonomies-B2Og_6rU.d.mts} +1 -1
  732. package/dist/{wxr-taxonomies-Ca68766D.d.mts.map → wxr-taxonomies-B2Og_6rU.d.mts.map} +1 -1
  733. package/dist/{wxr-taxonomies-B1R3vBoD.mjs → wxr-taxonomies-Cxngsjwo.mjs} +4 -4
  734. package/dist/{wxr-taxonomies-B1R3vBoD.mjs.map → wxr-taxonomies-Cxngsjwo.mjs.map} +1 -1
  735. package/dist/{zod-generator-LC-on_Vb.mjs → zod-generator-BuYSQJB7.mjs} +32 -22
  736. package/dist/zod-generator-BuYSQJB7.mjs.map +1 -0
  737. package/package.json +20 -9
  738. package/src/api/errors.ts +22 -0
  739. package/src/api/handlers/content.ts +49 -11
  740. package/src/api/handlers/index.ts +18 -0
  741. package/src/api/handlers/manifest.ts +161 -12
  742. package/src/api/handlers/media-allowlist.ts +1 -0
  743. package/src/api/handlers/media-folders.ts +130 -0
  744. package/src/api/handlers/media-usage-activation.ts +102 -0
  745. package/src/api/handlers/media-usage.ts +108 -0
  746. package/src/api/handlers/media.ts +92 -2
  747. package/src/api/handlers/registry.ts +483 -561
  748. package/src/api/handlers/taxonomies.ts +16 -9
  749. package/src/api/openapi/document.ts +277 -7
  750. package/src/api/parse.ts +1 -1
  751. package/src/api/schemas/auth.ts +4 -4
  752. package/src/api/schemas/bylines.ts +3 -3
  753. package/src/api/schemas/comments.ts +1 -1
  754. package/src/api/schemas/common.ts +3 -2
  755. package/src/api/schemas/content.ts +78 -22
  756. package/src/api/schemas/media-usage.ts +77 -0
  757. package/src/api/schemas/media.ts +121 -0
  758. package/src/api/schemas/redirects.ts +6 -1
  759. package/src/api/schemas/schema.ts +4 -0
  760. package/src/api/schemas/setup.ts +1 -1
  761. package/src/api/schemas/taxonomies.ts +2 -2
  762. package/src/api/schemas/users.ts +1 -1
  763. package/src/api/types.ts +23 -10
  764. package/src/astro/dev-typegen.ts +35 -0
  765. package/src/astro/image-endpoint.ts +2 -2
  766. package/src/astro/integration/dev-typegen.ts +91 -0
  767. package/src/astro/integration/index.ts +9 -44
  768. package/src/astro/integration/routes.ts +23 -0
  769. package/src/astro/integration/vite-config.ts +23 -9
  770. package/src/astro/middleware/auth.ts +4 -0
  771. package/src/astro/middleware.ts +5 -7
  772. package/src/astro/routes/api/admin/api-tokens/index.ts +4 -1
  773. package/src/astro/routes/api/admin/media-usage/activation.ts +42 -0
  774. package/src/astro/routes/api/admin/media-usage/progress.ts +37 -0
  775. package/src/astro/routes/api/admin/oauth-clients/[id].ts +1 -1
  776. package/src/astro/routes/api/admin/oauth-clients/index.ts +1 -1
  777. package/src/astro/routes/api/admin/plugins/registry/[id]/update.ts +4 -0
  778. package/src/astro/routes/api/admin/plugins/registry/artifact.ts +247 -101
  779. package/src/astro/routes/api/admin/plugins/registry/install.ts +4 -0
  780. package/src/astro/routes/api/admin/plugins/registry/verify.ts +60 -0
  781. package/src/astro/routes/api/auth/me.ts +14 -2
  782. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +8 -2
  783. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +2 -1
  784. package/src/astro/routes/api/content/[collection]/[id]/unpublish.ts +6 -2
  785. package/src/astro/routes/api/manifest.ts +1 -1
  786. package/src/astro/routes/api/media/[id]/replace.ts +114 -0
  787. package/src/astro/routes/api/media/[id].ts +3 -0
  788. package/src/astro/routes/api/media/file/[...key].ts +4 -1
  789. package/src/astro/routes/api/media/folders/[id].ts +55 -0
  790. package/src/astro/routes/api/media/folders/index.ts +37 -0
  791. package/src/astro/routes/api/media/upload-url.ts +8 -4
  792. package/src/astro/routes/api/media.ts +66 -10
  793. package/src/astro/routes/api/menus/[name]/items/[id].ts +7 -2
  794. package/src/astro/routes/api/menus/[name]/items.ts +4 -1
  795. package/src/astro/routes/api/menus/[name]/reorder.ts +4 -1
  796. package/src/astro/routes/api/menus/[name]/translations.ts +4 -1
  797. package/src/astro/routes/api/menus/[name].ts +7 -2
  798. package/src/astro/routes/api/menus/index.ts +4 -1
  799. package/src/astro/routes/api/settings/email.ts +1 -1
  800. package/src/astro/routes/api/settings.ts +4 -1
  801. package/src/astro/routes/api/setup/dev-bypass.ts +12 -0
  802. package/src/astro/routes/api/taxonomies/[name]/reorder.ts +4 -1
  803. package/src/astro/routes/api/taxonomies/[name]/terms/[slug]/translations.ts +4 -1
  804. package/src/astro/routes/api/taxonomies/[name]/terms/[slug].ts +7 -2
  805. package/src/astro/routes/api/taxonomies/[name]/terms/index.ts +4 -1
  806. package/src/astro/routes/api/taxonomies/[name].ts +7 -2
  807. package/src/astro/routes/api/taxonomies/index.ts +4 -1
  808. package/src/astro/routes/api/widget-areas/[name]/reorder.ts +3 -1
  809. package/src/astro/routes/api/widget-areas/[name]/widgets/[id].ts +5 -2
  810. package/src/astro/routes/api/widget-areas/[name]/widgets.ts +3 -1
  811. package/src/astro/routes/api/widget-areas/[name].ts +3 -1
  812. package/src/astro/routes/api/widget-areas/index.ts +3 -1
  813. package/src/astro/types.ts +34 -6
  814. package/src/auth/challenge-store.ts +3 -1
  815. package/src/aws-sdk.d.ts +1 -0
  816. package/src/cache/chrome-tags.ts +24 -0
  817. package/src/client/index.ts +140 -2
  818. package/src/client/transport.ts +6 -2
  819. package/src/components/EmDashImage.astro +156 -51
  820. package/src/components/EmDashMedia.astro +2 -1
  821. package/src/components/Gallery.astro +7 -0
  822. package/src/components/InlinePortableTextEditor.tsx +136 -2
  823. package/src/components/LiveSearch.astro +23 -0
  824. package/src/components/inline-code-block.tsx +180 -49
  825. package/src/components/widgets/Archives.astro +2 -37
  826. package/src/content/converters/gallery.ts +2 -0
  827. package/src/content/converters/index.ts +2 -0
  828. package/src/content/converters/mark-safety.ts +1 -0
  829. package/src/content/converters/portable-text-identity.ts +139 -0
  830. package/src/content/converters/portable-text-to-prosemirror.ts +202 -69
  831. package/src/content/converters/prosemirror-to-portable-text.ts +96 -25
  832. package/src/content/converters/types.ts +3 -0
  833. package/src/database/connection.ts +2 -31
  834. package/src/database/index.ts +1 -1
  835. package/src/database/json-recordset.ts +16 -0
  836. package/src/database/migrations/017_authorization_codes.ts +14 -4
  837. package/src/database/migrations/019_i18n.ts +1 -1
  838. package/src/database/migrations/071_restore_content_bylines_table.ts +43 -0
  839. package/src/database/migrations/072_media_folders.ts +72 -0
  840. package/src/database/migrations/073_media_focal_point.ts +57 -0
  841. package/src/database/migrations/074_content_deleted_scheduled_index.ts +55 -0
  842. package/src/database/migrations/runner.ts +11 -3
  843. package/src/database/repositories/byline.ts +32 -16
  844. package/src/database/repositories/content.ts +119 -51
  845. package/src/database/repositories/media-folders.ts +115 -0
  846. package/src/database/repositories/media-usage-work.ts +395 -111
  847. package/src/database/repositories/media-usage.ts +1104 -47
  848. package/src/database/repositories/media.ts +156 -29
  849. package/src/database/repositories/plugin-storage.ts +74 -9
  850. package/src/database/repositories/types.ts +8 -7
  851. package/src/database/transaction.ts +1 -0
  852. package/src/database/types.ts +13 -0
  853. package/src/db/adapters.ts +10 -3
  854. package/src/db/node-sqlite-compat.ts +78 -0
  855. package/src/db/postgres.ts +23 -0
  856. package/src/db/sqlite.ts +3 -3
  857. package/src/emdash-runtime.ts +186 -251
  858. package/src/fields/boolean.ts +1 -1
  859. package/src/fields/datetime.ts +1 -1
  860. package/src/fields/file.ts +1 -1
  861. package/src/fields/image.ts +7 -1
  862. package/src/fields/integer.ts +1 -1
  863. package/src/fields/json.ts +1 -1
  864. package/src/fields/multiselect.ts +1 -1
  865. package/src/fields/number.ts +1 -1
  866. package/src/fields/portable-text.ts +1 -1
  867. package/src/fields/richtext.ts +1 -1
  868. package/src/fields/select.ts +1 -1
  869. package/src/fields/slug.ts +1 -1
  870. package/src/fields/text.ts +1 -1
  871. package/src/fields/textarea.ts +1 -1
  872. package/src/fields/types.ts +8 -4
  873. package/src/index.ts +30 -3
  874. package/src/loader.ts +63 -10
  875. package/src/mcp/server.ts +228 -24
  876. package/src/media/focal-point.ts +37 -0
  877. package/src/media/image-endpoint.ts +5 -2
  878. package/src/media/local-runtime.ts +8 -0
  879. package/src/media/mime.ts +1 -0
  880. package/src/media/normalize.ts +25 -4
  881. package/src/media/types.ts +10 -0
  882. package/src/media/usage/activation.ts +162 -35
  883. package/src/media/usage/capture-triggers.ts +19 -3
  884. package/src/media/usage/cleanup.ts +9 -8
  885. package/src/media/usage/collection-deletion-processor.ts +7 -3
  886. package/src/media/usage/collection-deletion.ts +10 -0
  887. package/src/media/usage/content-refresh.ts +258 -39
  888. package/src/media/usage/content-snapshots.ts +128 -31
  889. package/src/media/usage/extractor.ts +32 -13
  890. package/src/media/usage/maintenance-engine.ts +166 -0
  891. package/src/media/usage/reconciliation-processor.ts +106 -29
  892. package/src/media/usage/reconciliation.ts +90 -7
  893. package/src/media/usage/work-processor.ts +342 -101
  894. package/src/menus/index.ts +16 -0
  895. package/src/object-cache/index.ts +44 -2
  896. package/src/plugin-types.ts +18 -1
  897. package/src/plugins/hooks.ts +4 -1
  898. package/src/plugins/index.ts +7 -0
  899. package/src/plugins/manager.ts +2 -1
  900. package/src/plugins/manifest-schema.ts +1 -1
  901. package/src/plugins/routes.ts +3 -1
  902. package/src/plugins/sandbox/hook-result.ts +52 -0
  903. package/src/plugins/sandbox/index.ts +10 -0
  904. package/src/plugins/save-rejection.ts +20 -0
  905. package/src/plugins/scheduler/node.ts +1 -13
  906. package/src/plugins/scheduler/types.ts +0 -2
  907. package/src/plugins/state.ts +13 -3
  908. package/src/plugins/types.ts +6 -0
  909. package/src/registry/artifact-checksum.ts +15 -0
  910. package/src/registry/artifact-fetch.ts +530 -0
  911. package/src/registry/artifact-verification.ts +85 -0
  912. package/src/registry/authoritative-records.ts +180 -0
  913. package/src/registry/config.ts +24 -6
  914. package/src/registry/record-labels.ts +28 -0
  915. package/src/registry/types.ts +12 -15
  916. package/src/schema/registry.ts +26 -3
  917. package/src/schema/types.ts +1 -0
  918. package/src/schema/zod-generator.ts +28 -17
  919. package/src/security/ssrf.ts +26 -4
  920. package/src/seed/apply.ts +4 -4
  921. package/src/settings/index.ts +16 -0
  922. package/src/storage/local.ts +1 -0
  923. package/src/storage/s3.ts +2 -0
  924. package/src/storage/types.ts +2 -0
  925. package/src/taxonomies/index.ts +40 -20
  926. package/src/ui.ts +2 -0
  927. package/src/widgets/archives.ts +67 -0
  928. package/src/widgets/index.ts +16 -0
  929. package/dist/api-BeBglVxU.mjs +0 -4695
  930. package/dist/api-BeBglVxU.mjs.map +0 -1
  931. package/dist/byline-yjvWq4ip.mjs.map +0 -1
  932. package/dist/challenge-store-SIL5DsF2.mjs.map +0 -1
  933. package/dist/collection-deletion-DQPvMD8R.mjs.map +0 -1
  934. package/dist/content-ZHCc1ngN.mjs.map +0 -1
  935. package/dist/content-refresh-B_8SJzuU.mjs.map +0 -1
  936. package/dist/context-ZldbZcle.mjs.map +0 -1
  937. package/dist/errors-CLUPm7aD.mjs.map +0 -1
  938. package/dist/index-BVBZj4-7.d.mts.map +0 -1
  939. package/dist/loader-CdG_Ci3H.mjs.map +0 -1
  940. package/dist/manifest-schema-BXbUAHod.mjs.map +0 -1
  941. package/dist/media-BWWWb8kg.mjs.map +0 -1
  942. package/dist/media-CzhAn2--.mjs.map +0 -1
  943. package/dist/media-allowlist-D6x-Us02.mjs.map +0 -1
  944. package/dist/media-usage-BZCydfvu.mjs.map +0 -1
  945. package/dist/media-usage-work-DrCbqBcl.mjs.map +0 -1
  946. package/dist/menus-DSo5QeW0.mjs.map +0 -1
  947. package/dist/mime-DfIVjNkr.mjs.map +0 -1
  948. package/dist/normalize-Bc-s_r-a.mjs.map +0 -1
  949. package/dist/object-cache-71tPfV4A.mjs.map +0 -1
  950. package/dist/options--hhz-jZ1.d.mts.map +0 -1
  951. package/dist/placeholder-Dp0K3RkD.d.mts.map +0 -1
  952. package/dist/redirects-DTDHWH31.mjs.map +0 -1
  953. package/dist/registry-Cqa2I749.mjs.map +0 -1
  954. package/dist/relations-BBApI4e2.mjs.map +0 -1
  955. package/dist/relations-BHo5A8Zf.d.mts.map +0 -1
  956. package/dist/runner-BYHZn3Jy.d.mts.map +0 -1
  957. package/dist/runner-C1T11CfC.mjs.map +0 -1
  958. package/dist/settings-xRdoUZr0.mjs.map +0 -1
  959. package/dist/state-DYwPue40.mjs.map +0 -1
  960. package/dist/taxonomies-BlrncHi9.mjs.map +0 -1
  961. package/dist/taxonomies-OHUIiIpI.mjs.map +0 -1
  962. package/dist/types-BcqdcT-r.d.mts.map +0 -1
  963. package/dist/types-C2pMvO62.d.mts.map +0 -1
  964. package/dist/types-CP1CflWf.mjs +0 -3
  965. package/dist/types-DN64_zzZ.d.mts.map +0 -1
  966. package/dist/types-DQIDRKF2.d.mts.map +0 -1
  967. package/dist/version-DB_fqCSI.mjs +0 -7
  968. package/dist/widgets-BD3ho7Rq.mjs.map +0 -1
  969. package/dist/zod-generator-LC-on_Vb.mjs.map +0 -1
  970. /package/dist/{api-tokens-rIXC6LdE.mjs → api-tokens-BfYts-sq.mjs} +0 -0
  971. /package/dist/{ssrf-DpXgKsna.mjs → ssrf-Dg3cIT-b.mjs} +0 -0
@@ -1,4695 +0,0 @@
1
- import { i as validateStorageCollectionName, n as validateJsonFieldName, r as validatePluginIdentifier, t as validateIdentifier } from "./validate-BpwoDOgt.mjs";
2
- import { c as isSqlite, l as jsonExtractExpr, s as isPostgres } from "./dialect-helpers-BSbfaO3F.mjs";
3
- import { a as resolveConfiguredLocale, i as isI18nEnabled, r as getI18nConfig } from "./config-C3EBstHi.mjs";
4
- import { t as after } from "./after-CBU2vkoO.mjs";
5
- import { i as RevisionRepository, r as isSystemOrderField, t as ContentRepository } from "./content-ZHCc1ngN.mjs";
6
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-fiZ8G9RJ.mjs";
7
- import { n as isMissingTableError, t as isMissingColumnError } from "./db-errors-Cl-sKYTm.mjs";
8
- import { i as encodeBase64, t as decodeBase64 } from "./base64-CvLhUKQv.mjs";
9
- import { a as ScheduledNotDueError, i as InvalidCursorError, n as ContentMutationConflictError, r as EmDashValidationError, t as ContentCollectionNotFoundError } from "./types-CQPWhPxE.mjs";
10
- import { t as MediaRepository } from "./media-CzhAn2--.mjs";
11
- import { t as UserRepository } from "./user-DJZfUJVE.mjs";
12
- import { t as withTransaction } from "./transaction-NQj4VJ7Z.mjs";
13
- import { t as TaxonomyRepository } from "./taxonomy-BqCZ1TdU.mjs";
14
- import { t as CommentRepository } from "./comment-Dxlep6cE.mjs";
15
- import { t as OptionsRepository } from "./options-CBXIHUoT.mjs";
16
- import { t as RedirectRepository } from "./redirect-COsS6SWJ.mjs";
17
- import { r as requestCached } from "./request-cache-BSUptuJR.mjs";
18
- import { t as BylineRepository } from "./byline-yjvWq4ip.mjs";
19
- import { r as parseAllowedMimeTypes, t as matchesMimeAllowlist } from "./mime-DfIVjNkr.mjs";
20
- import { t as SeoRepository } from "./seo-Dq4G-RrO.mjs";
21
- import { n as invalidateRedirectCache } from "./cache-C46-3Irl.mjs";
22
- import { t as FTSManager } from "./fts-manager-DyZEohZC.mjs";
23
- import { u as invalidateTermCache } from "./taxonomies-BlrncHi9.mjs";
24
- import { r as hashString } from "./hash-Cg0TXJPV.mjs";
25
- import { t as ErrorCode } from "./errors-CLUPm7aD.mjs";
26
- import { t as PluginStateRepository } from "./state-DYwPue40.mjs";
27
- import { a as reconcileManifestAccess, i as pluginManifestSchema, r as normalizeManifestRoute } from "./manifest-schema-BXbUAHod.mjs";
28
- import { a as normalizeCapabilities, r as declaredAccessToCapabilities } from "./types-CP1CflWf.mjs";
29
- import { t as EmDashStorageError } from "./types-BW1syrlw.mjs";
30
- import { n as resolveAndValidateExternalUrl, t as SsrfError } from "./ssrf-Cpvg_n3A.mjs";
31
- import { sql } from "kysely";
32
- import { createGzipDecoder, unpackTar } from "modern-tar";
33
- import { ClientResponseError, ClientValidationError } from "@atcute/client";
34
- import { checkEnvCompatibility, findSkippedEnvConstraints } from "@emdash-cms/registry-client/env";
35
-
36
- //#region src/api/rev.ts
37
- /**
38
- * Generate a _rev token from a content item's version and updatedAt.
39
- */
40
- function encodeRev(item) {
41
- return encodeBase64(`${item.version}:${item.updatedAt}`);
42
- }
43
- /**
44
- * Decode a _rev token into its components.
45
- * Returns null if the token is malformed.
46
- */
47
- function decodeRev(rev) {
48
- try {
49
- const decoded = decodeBase64(rev);
50
- const colonIdx = decoded.indexOf(":");
51
- if (colonIdx === -1) return null;
52
- const version = parseInt(decoded.slice(0, colonIdx), 10);
53
- const updatedAt = decoded.slice(colonIdx + 1);
54
- if (isNaN(version) || !updatedAt) return null;
55
- return {
56
- version,
57
- updatedAt
58
- };
59
- } catch {
60
- return null;
61
- }
62
- }
63
- /**
64
- * Validate a _rev token against a content item.
65
- * Returns null if valid (or if no _rev provided), or an error message if invalid.
66
- */
67
- function validateRev(rev, item) {
68
- if (!rev) return { valid: true };
69
- const decoded = decodeRev(rev);
70
- if (!decoded) return {
71
- valid: false,
72
- message: "Malformed _rev token"
73
- };
74
- if (decoded.version !== item.version || decoded.updatedAt !== item.updatedAt) return {
75
- valid: false,
76
- message: "Content has been modified since last read (version conflict)"
77
- };
78
- return { valid: true };
79
- }
80
-
81
- //#endregion
82
- //#region src/api/handlers/validate-media-fields.ts
83
- function asMediaRef(value) {
84
- if (value === null || value === void 0) return null;
85
- if (typeof value !== "object" || Array.isArray(value)) return null;
86
- return value;
87
- }
88
- function fail(message) {
89
- return {
90
- success: false,
91
- error: {
92
- code: "INVALID_MIME_FOR_FIELD",
93
- message
94
- }
95
- };
96
- }
97
- async function loadMediaFieldsForCollection(db, collectionSlug) {
98
- const rows = await db.selectFrom("_emdash_fields").innerJoin("_emdash_collections", "_emdash_collections.id", "_emdash_fields.collection_id").select([
99
- "_emdash_fields.slug",
100
- "_emdash_fields.type",
101
- "_emdash_fields.validation"
102
- ]).where("_emdash_collections.slug", "=", collectionSlug).where("_emdash_fields.type", "in", ["file", "image"]).execute();
103
- const out = [];
104
- for (const row of rows) {
105
- const list = parseAllowedMimeTypes(row.validation);
106
- if (!list) continue;
107
- out.push({
108
- slug: row.slug,
109
- type: row.type,
110
- allowedMimeTypes: list
111
- });
112
- }
113
- return out;
114
- }
115
- async function validateMediaFields(db, collectionSlug, data) {
116
- const fields = await requestCached(`mediaFields:${collectionSlug}`, () => loadMediaFieldsForCollection(db, collectionSlug));
117
- if (fields.length === 0) return {
118
- success: true,
119
- data: true
120
- };
121
- const localIds = /* @__PURE__ */ new Set();
122
- for (const field of fields) {
123
- const ref = asMediaRef(data[field.slug]);
124
- if (!ref) continue;
125
- if ((typeof ref.provider === "string" ? ref.provider : "local") === "local" && typeof ref.id === "string") localIds.add(ref.id);
126
- }
127
- const idList = [...localIds];
128
- const mimeById = /* @__PURE__ */ new Map();
129
- if (idList.length > 0) for (const batch of chunks(idList, SQL_BATCH_SIZE)) {
130
- const rows = await db.selectFrom("media").select(["id", "mime_type"]).where("id", "in", batch).execute();
131
- for (const r of rows) mimeById.set(r.id, r.mime_type);
132
- }
133
- for (const field of fields) {
134
- const value = data[field.slug];
135
- if (value === null || value === void 0) continue;
136
- const ref = asMediaRef(value);
137
- if (!ref) continue;
138
- const provider = typeof ref.provider === "string" ? ref.provider : "local";
139
- let mime;
140
- if (provider === "local") {
141
- if (typeof ref.id !== "string") return fail(`Field '${field.slug}' references media with an invalid id`);
142
- mime = mimeById.get(ref.id);
143
- if (!mime) return fail(`Field '${field.slug}' references media with unknown MIME type`);
144
- } else {
145
- if (typeof ref.mimeType !== "string") return fail(`Field '${field.slug}' requires a mimeType declaration for non-local media`);
146
- mime = ref.mimeType;
147
- }
148
- if (!matchesMimeAllowlist(mime, field.allowedMimeTypes)) return fail(`Field '${field.slug}' does not accept ${mime}`);
149
- }
150
- return {
151
- success: true,
152
- data: true
153
- };
154
- }
155
-
156
- //#endregion
157
- //#region src/api/handlers/content.ts
158
- /**
159
- * Narrow a caught error to one carrying a structured `apiError` discriminant.
160
- * Used by transaction callbacks that want to surface a specific error code
161
- * through the standard Error throwing path.
162
- */
163
- function hasApiError(error) {
164
- if (!(error instanceof Error) || !("apiError" in error)) return false;
165
- const { apiError } = error;
166
- return typeof apiError === "object" && apiError !== null && "code" in apiError && typeof apiError.code === "string";
167
- }
168
- /**
169
- * Extract a slug source (title or name) from content data.
170
- * Returns null if no suitable string field is found.
171
- */
172
- function getSlugSource(data) {
173
- if (typeof data.title === "string" && data.title.length > 0) return data.title;
174
- if (typeof data.name === "string" && data.name.length > 0) return data.name;
175
- return null;
176
- }
177
- /** Default SEO values for content without an explicit SEO row */
178
- const SEO_DEFAULTS = {
179
- title: null,
180
- description: null,
181
- image: null,
182
- canonical: null,
183
- noIndex: false
184
- };
185
- /**
186
- * Check if a collection has SEO enabled.
187
- */
188
- async function collectionHasSeo(db, collection) {
189
- return (await db.selectFrom("_emdash_collections").select("has_seo").where("slug", "=", collection).executeTakeFirst())?.has_seo === 1;
190
- }
191
- async function getCollectionPublishConfig(db, collection) {
192
- const row = await db.selectFrom("_emdash_collections").select(["supports", "routable"]).where("slug", "=", collection).executeTakeFirst();
193
- const supports = row?.supports ? JSON.parse(row.supports) : [];
194
- return {
195
- supportsRevisions: Array.isArray(supports) && supports.includes("revisions"),
196
- routable: row?.routable !== 0
197
- };
198
- }
199
- function requireRoutablePublishSlug(routable, slug) {
200
- if (routable && !slug?.trim()) throw new EmDashValidationError("Cannot publish routable content without a slug");
201
- }
202
- /**
203
- * Hydrate SEO data on a single content item if the collection has SEO enabled.
204
- */
205
- async function hydrateSeo(db, collection, item, hasSeo) {
206
- if (!hasSeo) return;
207
- item.seo = await new SeoRepository(db).get(collection, item.id);
208
- }
209
- /**
210
- * Hydrate SEO data on multiple content items using a single batch query.
211
- */
212
- async function hydrateSeoMany(db, collection, items, hasSeo) {
213
- if (!hasSeo || items.length === 0) return;
214
- const seoMap = await new SeoRepository(db).getMany(collection, items.map((i) => i.id));
215
- for (const item of items) item.seo = seoMap.get(item.id) ?? { ...SEO_DEFAULTS };
216
- }
217
- async function hydrateBylines(db, collection, item) {
218
- const bylineRepo = new BylineRepository(db);
219
- const localeOpt = item.locale ? { locale: item.locale } : void 0;
220
- const bylines = await bylineRepo.getContentBylines(collection, item.id, localeOpt);
221
- if (bylines.length > 0) {
222
- item.bylines = bylines.map((c) => ({
223
- ...c,
224
- source: "explicit"
225
- }));
226
- item.byline = bylines[0]?.byline ?? null;
227
- return;
228
- }
229
- if (item.primaryBylineId) {
230
- item.bylines = [];
231
- item.byline = null;
232
- return;
233
- }
234
- if (item.authorId) {
235
- const fallback = await bylineRepo.findByUserId(item.authorId, localeOpt);
236
- if (fallback) {
237
- item.bylines = [{
238
- byline: fallback,
239
- sortOrder: 0,
240
- roleLabel: null,
241
- source: "inferred"
242
- }];
243
- item.byline = fallback;
244
- return;
245
- }
246
- }
247
- item.bylines = [];
248
- item.byline = null;
249
- }
250
- /**
251
- * Batch-hydrate bylines for multiple items using two bulk queries instead of N+1.
252
- *
253
- * Items may live at different locales (e.g. a list endpoint returning the
254
- * translations of an entry). Group by `item.locale` and call the strict
255
- * per-locale repo method once per group so each item resolves against its
256
- * own locale's byline rows.
257
- */
258
- async function hydrateBylinesMany(db, collection, items) {
259
- if (items.length === 0) return;
260
- const bylineRepo = new BylineRepository(db);
261
- const localeBuckets = /* @__PURE__ */ new Map();
262
- for (const item of items) {
263
- const key = item.locale ?? null;
264
- const bucket = localeBuckets.get(key);
265
- if (bucket) bucket.push(item);
266
- else localeBuckets.set(key, [item]);
267
- }
268
- const bylinesByItem = /* @__PURE__ */ new Map();
269
- const itemsNeedingAuthorCheck = [];
270
- for (const [locale, bucket] of localeBuckets) {
271
- const localeOpt = locale ? { locale } : void 0;
272
- const ids = bucket.map((i) => i.id);
273
- const credits = await bylineRepo.getContentBylinesMany(collection, ids, localeOpt);
274
- for (const [id, list] of credits) bylinesByItem.set(id, list);
275
- for (const item of bucket) {
276
- if (credits.has(item.id) && credits.get(item.id).length > 0) continue;
277
- if (item.authorId) itemsNeedingAuthorCheck.push(item);
278
- }
279
- }
280
- const fallbackByItem = /* @__PURE__ */ new Map();
281
- if (itemsNeedingAuthorCheck.length > 0) {
282
- const authorBuckets = /* @__PURE__ */ new Map();
283
- for (const item of itemsNeedingAuthorCheck) {
284
- if (item.primaryBylineId) continue;
285
- const key = item.locale ?? null;
286
- const bucket = authorBuckets.get(key);
287
- if (bucket) bucket.push(item);
288
- else authorBuckets.set(key, [item]);
289
- }
290
- for (const [locale, bucket] of authorBuckets) {
291
- const localeOpt = locale ? { locale } : void 0;
292
- const authorIds = bucket.map((i) => i.authorId).filter((id) => id !== null);
293
- const uniqueAuthorIds = [...new Set(authorIds)];
294
- if (uniqueAuthorIds.length === 0) continue;
295
- const authorMap = await bylineRepo.findByUserIds(uniqueAuthorIds, localeOpt);
296
- for (const item of bucket) {
297
- if (!item.authorId) continue;
298
- const f = authorMap.get(item.authorId);
299
- if (f) fallbackByItem.set(item.id, f);
300
- }
301
- }
302
- }
303
- for (const item of items) {
304
- const explicit = bylinesByItem.get(item.id);
305
- if (explicit && explicit.length > 0) {
306
- item.bylines = explicit.map((c) => ({
307
- ...c,
308
- source: "explicit"
309
- }));
310
- item.byline = explicit[0]?.byline ?? null;
311
- continue;
312
- }
313
- const fallback = fallbackByItem.get(item.id);
314
- if (fallback) {
315
- item.bylines = [{
316
- byline: fallback,
317
- sortOrder: 0,
318
- roleLabel: null,
319
- source: "inferred"
320
- }];
321
- item.byline = fallback;
322
- continue;
323
- }
324
- item.bylines = [];
325
- item.byline = null;
326
- }
327
- }
328
- /**
329
- * Resolve an identifier (ID or slug) to a real content ID.
330
- * Returns the ID if found, null if not found.
331
- * When locale is provided, slug lookups are scoped to that locale.
332
- */
333
- async function resolveId(repo, collection, identifier, locale) {
334
- return (await repo.findByIdOrSlug(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
335
- }
336
- /**
337
- * Resolve an identifier (ID or slug) to a real content ID,
338
- * including trashed (soft-deleted) items.
339
- */
340
- async function resolveIdIncludingTrashed(repo, collection, identifier, locale) {
341
- return (await repo.findByIdOrSlugIncludingTrashed(collection, identifier, locale ? resolveConfiguredLocale(locale) : void 0))?.id ?? null;
342
- }
343
- /**
344
- * Resolve the columns a content-list search should match against. Always
345
- * includes `slug` (a standard column), adds the configured `titleField` plus
346
- * the `title`/`name` display fields when the collection actually defines them,
347
- * mirroring the admin's item-title resolution (titleField -> title -> name ->
348
- * slug), and includes every field explicitly marked searchable. Returning only
349
- * schema-backed columns avoids "no such column" errors.
350
- */
351
- async function resolveSearchColumns(db, collection) {
352
- const row = await db.selectFrom("_emdash_collections").select(["id", "title_field"]).where("slug", "=", collection).executeTakeFirst();
353
- if (!row) return ["slug"];
354
- const fields = await db.selectFrom("_emdash_fields").select(["slug", "searchable"]).where("collection_id", "=", row.id).orderBy("sort_order", "asc").execute();
355
- const columns = new Set(["slug"]);
356
- const fieldSlugs = new Set(fields.map((f) => f.slug));
357
- if (row.title_field && fieldSlugs.has(row.title_field)) columns.add(row.title_field);
358
- for (const candidate of ["title", "name"]) if (fieldSlugs.has(candidate)) columns.add(candidate);
359
- for (const field of fields) if (field.searchable === 1) columns.add(field.slug);
360
- return [...columns];
361
- }
362
- /**
363
- * Decide whether the content-list `q` filter can be served from the
364
- * collection's FTS5 index instead of a full-scan substring LIKE (#1517).
365
- *
366
- * Requires SQLite (FTS5 is SQLite-only), search enabled on the collection,
367
- * every non-slug display column present in the searchable-field set (or the
368
- * index would miss matches the LIKE finds), and the index table actually
369
- * existing.
370
- */
371
- async function canUseFtsForListFilter(db, collection, searchColumns) {
372
- if (!isSqlite(db)) return false;
373
- const ftsManager = new FTSManager(db);
374
- if (!(await ftsManager.getSearchConfig(collection))?.enabled) return false;
375
- const searchable = new Set(await ftsManager.getSearchableFields(collection));
376
- if (!searchColumns.every((col) => col === "slug" || searchable.has(col))) return false;
377
- return ftsManager.ftsTableExists(collection);
378
- }
379
- /**
380
- * Create a 301 auto-redirect from an entry's old URL to its new one after a
381
- * slug change, using the collection's URL pattern. Shared by
382
- * handleContentUpdate (direct slug edits) and handleContentPublish (slug edits
383
- * staged as `_slug` in a draft revision, which only land on publish).
384
- */
385
- async function createSlugChangeRedirect(db, collection, oldSlug, newSlug, contentId) {
386
- if (await slugStillTaken(db, collection, oldSlug, contentId)) return;
387
- const collectionRow = await db.selectFrom("_emdash_collections").select("url_pattern").where("slug", "=", collection).executeTakeFirst();
388
- await new RedirectRepository(db).createAutoRedirect(collection, oldSlug, newSlug, contentId, collectionRow?.url_pattern ?? null);
389
- invalidateRedirectCache();
390
- }
391
- /** Whether a row other than `contentId` still holds `slug` in this collection. */
392
- async function slugStillTaken(db, collection, slug, contentId) {
393
- validateIdentifier(collection, "collection slug");
394
- return (await sql`
395
- SELECT id FROM ${sql.ref(`ec_${collection}`)}
396
- WHERE slug = ${slug}
397
- AND id != ${contentId}
398
- AND deleted_at IS NULL
399
- LIMIT 1
400
- `.execute(db)).rows.length > 0;
401
- }
402
- /** Matches a date-only `YYYY-MM-DD` bound (no time component). */
403
- const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
404
- /**
405
- * Normalize a date-range bound to an ISO datetime for lexicographic comparison
406
- * against stored ISO 8601 timestamps. A bare `YYYY-MM-DD` is widened to the
407
- * appropriate UTC day boundary so the range stays inclusive: a `start` bound
408
- * becomes the start of the day and an `end` bound the end of the day.
409
- * Otherwise a date-only upper bound would exclude every same-day row (since
410
- * `2024-06-01T12:00:00Z` sorts after `2024-06-01`). Full datetimes pass
411
- * through unchanged.
412
- */
413
- function normalizeDateBound(value, edge) {
414
- if (!value) return void 0;
415
- if (!DATE_ONLY_RE.test(value)) return value;
416
- return edge === "start" ? `${value}T00:00:00.000Z` : `${value}T23:59:59.999Z`;
417
- }
418
- /**
419
- * Build the repository's byline filter from the wire params.
420
- *
421
- * `locale` is the locale the list is scoped to, which is the locale an
422
- * inferred credit has to resolve at — the admin list is always scoped to the
423
- * locale picked in its switcher.
424
- */
425
- function resolveBylineFilter(params, locale) {
426
- const includeInferred = params.includeInferredBylines === true;
427
- if (params.bylinesNone) return {
428
- mode: "none",
429
- includeInferred,
430
- locale
431
- };
432
- const bylineIds = params.bylines ?? [];
433
- if (bylineIds.length === 0) return void 0;
434
- return {
435
- mode: "any",
436
- bylineIds,
437
- includeInferred,
438
- locale
439
- };
440
- }
441
- /**
442
- * Create content list handler
443
- */
444
- async function handleContentList(db, collection, params) {
445
- try {
446
- const repo = new ContentRepository(db);
447
- const where = {};
448
- if (params.status) where.status = params.status;
449
- const locale = params.locale ? resolveConfiguredLocale(params.locale) : void 0;
450
- if (locale) where.locale = locale;
451
- if (params.authorId) where.authorId = params.authorId;
452
- if (params.fieldFilters && Object.keys(params.fieldFilters).length > 0) where.fieldFilters = params.fieldFilters;
453
- const bylineFilter = resolveBylineFilter(params, locale);
454
- if (bylineFilter) where.bylineFilter = bylineFilter;
455
- if (params.dateField && (params.dateFrom || params.dateTo)) where.dateFilter = {
456
- field: params.dateField,
457
- from: normalizeDateBound(params.dateFrom, "start"),
458
- to: normalizeDateBound(params.dateTo, "end")
459
- };
460
- const q = params.q?.trim();
461
- if (q) {
462
- where.q = q;
463
- where.searchColumns = await resolveSearchColumns(db, collection);
464
- where.useFts = await canUseFtsForListFilter(db, collection, where.searchColumns);
465
- }
466
- let sortableExtras;
467
- if (params.orderBy && !isSystemOrderField(params.orderBy)) {
468
- const coll = await db.selectFrom("_emdash_collections").select(["title_field", "date_field"]).where("slug", "=", collection).executeTakeFirst();
469
- sortableExtras = [coll?.title_field, coll?.date_field].filter((slug) => !!slug);
470
- }
471
- const result = await repo.findMany(collection, {
472
- cursor: params.cursor,
473
- limit: params.limit || 50,
474
- where: Object.keys(where).length > 0 ? where : void 0,
475
- orderBy: params.orderBy ? {
476
- field: params.orderBy,
477
- direction: params.order || "desc"
478
- } : void 0,
479
- sortableExtras
480
- });
481
- const hasSeo = await collectionHasSeo(db, collection);
482
- await hydrateSeoMany(db, collection, result.items, hasSeo);
483
- await hydrateBylinesMany(db, collection, result.items);
484
- return {
485
- success: true,
486
- data: {
487
- items: result.items,
488
- nextCursor: result.nextCursor,
489
- total: result.total
490
- }
491
- };
492
- } catch (error) {
493
- if (error instanceof InvalidCursorError) return {
494
- success: false,
495
- error: {
496
- code: "INVALID_CURSOR",
497
- message: error.message
498
- }
499
- };
500
- if (error instanceof ContentCollectionNotFoundError || isMissingTableError(error)) return {
501
- success: false,
502
- error: {
503
- code: "COLLECTION_NOT_FOUND",
504
- message: `Collection '${collection}' not found`
505
- }
506
- };
507
- if (isMissingColumnError(error, "deleted_at")) return {
508
- success: false,
509
- error: {
510
- code: "COLLECTION_SCHEMA_MISMATCH",
511
- message: `Collection '${collection}' backing table is missing the 'deleted_at' column`
512
- }
513
- };
514
- if (error instanceof EmDashValidationError) return {
515
- success: false,
516
- error: {
517
- code: "VALIDATION_ERROR",
518
- message: error.message
519
- }
520
- };
521
- console.error("Content list error:", error);
522
- return {
523
- success: false,
524
- error: {
525
- code: "CONTENT_LIST_ERROR",
526
- message: "Failed to list content"
527
- }
528
- };
529
- }
530
- }
531
- /**
532
- * List the distinct authors of a collection's live content.
533
- *
534
- * Backs the admin content-list author filter. Unlike `/admin/users` (ADMIN
535
- * only), this is gated on `content:read`, so any editor can filter by author.
536
- * Returns only users who have authored at least one non-trashed entry, sorted
537
- * by display name then email for a stable dropdown order.
538
- */
539
- async function handleContentAuthors(db, collection) {
540
- try {
541
- const authorIds = await new ContentRepository(db).findDistinctAuthorIds(collection);
542
- if (authorIds.length === 0) return {
543
- success: true,
544
- data: { items: [] }
545
- };
546
- return {
547
- success: true,
548
- data: { items: (await new UserRepository(db).findByIds(authorIds)).map((u) => ({
549
- id: u.id,
550
- name: u.name,
551
- email: u.email,
552
- avatarUrl: u.avatarUrl
553
- })).toSorted((a, b) => (a.name ?? a.email).localeCompare(b.name ?? b.email)) }
554
- };
555
- } catch (error) {
556
- if (isMissingTableError(error)) return {
557
- success: false,
558
- error: {
559
- code: "COLLECTION_NOT_FOUND",
560
- message: `Collection '${collection}' not found`
561
- }
562
- };
563
- console.error("Content authors error:", error);
564
- return {
565
- success: false,
566
- error: {
567
- code: "CONTENT_AUTHORS_ERROR",
568
- message: "Failed to list content authors"
569
- }
570
- };
571
- }
572
- }
573
- /**
574
- * Get single content item
575
- */
576
- async function handleContentGet(db, collection, id, locale) {
577
- try {
578
- const item = await new ContentRepository(db).findByIdOrSlug(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
579
- if (!item) return {
580
- success: false,
581
- error: {
582
- code: "NOT_FOUND",
583
- message: `Content item not found: ${id}`
584
- }
585
- };
586
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
587
- await hydrateBylines(db, collection, item);
588
- return {
589
- success: true,
590
- data: {
591
- item,
592
- _rev: encodeRev(item)
593
- }
594
- };
595
- } catch (error) {
596
- console.error("Content get error:", error);
597
- return {
598
- success: false,
599
- error: {
600
- code: "CONTENT_GET_ERROR",
601
- message: "Failed to get content"
602
- }
603
- };
604
- }
605
- }
606
- /**
607
- * Get a content item by id, including trashed items.
608
- * Used by restore endpoint for ownership checks on soft-deleted items.
609
- */
610
- async function handleContentGetIncludingTrashed(db, collection, id, locale) {
611
- try {
612
- const item = await new ContentRepository(db).findByIdOrSlugIncludingTrashed(collection, id, locale ? resolveConfiguredLocale(locale) : void 0);
613
- if (!item) return {
614
- success: false,
615
- error: {
616
- code: "NOT_FOUND",
617
- message: `Content item not found: ${id}`
618
- }
619
- };
620
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
621
- await hydrateBylines(db, collection, item);
622
- return {
623
- success: true,
624
- data: {
625
- item,
626
- _rev: encodeRev(item)
627
- }
628
- };
629
- } catch (error) {
630
- console.error("Content get error:", error);
631
- return {
632
- success: false,
633
- error: {
634
- code: "CONTENT_GET_ERROR",
635
- message: "Failed to get content"
636
- }
637
- };
638
- }
639
- }
640
- /**
641
- * Create content item.
642
- *
643
- * Content + SEO writes are wrapped in a transaction so either both succeed
644
- * or neither does. If `body.seo` is provided for a non-SEO collection, the
645
- * API returns a validation error rather than silently dropping it.
646
- */
647
- async function handleContentCreate(db, collection, body) {
648
- try {
649
- const hasSeo = await collectionHasSeo(db, collection);
650
- if (body.seo && !hasSeo) return {
651
- success: false,
652
- error: {
653
- code: "VALIDATION_ERROR",
654
- message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
655
- }
656
- };
657
- const mimeCheck = await validateMediaFields(db, collection, body.data);
658
- if (!mimeCheck.success) return mimeCheck;
659
- const item = await withTransaction(db, async (trx) => {
660
- const repo = new ContentRepository(trx);
661
- const bylineRepo = new BylineRepository(trx);
662
- const effectiveLocale = body.locale ? resolveConfiguredLocale(body.locale) : getI18nConfig()?.defaultLocale;
663
- let slug = body.slug;
664
- if (!slug) {
665
- const slugSource = getSlugSource(body.data);
666
- if (slugSource) slug = await repo.generateUniqueSlug(collection, slugSource, effectiveLocale);
667
- }
668
- if (body.status === "published") requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, slug);
669
- const created = await repo.create({
670
- type: collection,
671
- slug,
672
- data: body.data,
673
- status: body.status || "draft",
674
- authorId: body.authorId,
675
- locale: effectiveLocale,
676
- translationOf: body.translationOf,
677
- createdAt: body.createdAt,
678
- publishedAt: body.publishedAt
679
- });
680
- if (body.bylines !== void 0) created.primaryBylineId = (await bylineRepo.setContentBylines(collection, created.id, body.bylines))[0]?.byline.translationGroup ?? null;
681
- if (body.translationOf) {
682
- if (body.bylines === void 0) {
683
- await bylineRepo.copyContentBylines(collection, body.translationOf, created.id);
684
- const source = await repo.findById(collection, body.translationOf);
685
- if (source) created.primaryBylineId = source.primaryBylineId;
686
- }
687
- }
688
- await hydrateBylines(trx, collection, created);
689
- if (body.seo && hasSeo) created.seo = await new SeoRepository(trx).upsert(collection, created.id, body.seo);
690
- else if (hasSeo) created.seo = { ...SEO_DEFAULTS };
691
- if (body.taxonomies) await assignTaxonomies(trx, collection, created.id, effectiveLocale, body.taxonomies);
692
- return created;
693
- });
694
- return {
695
- success: true,
696
- data: {
697
- item,
698
- _rev: encodeRev(item)
699
- }
700
- };
701
- } catch (error) {
702
- if (isMissingTableError(error)) return {
703
- success: false,
704
- error: {
705
- code: "COLLECTION_NOT_FOUND",
706
- message: `Collection '${collection}' not found`
707
- }
708
- };
709
- if (error instanceof EmDashValidationError) return {
710
- success: false,
711
- error: {
712
- code: "VALIDATION_ERROR",
713
- message: error.message
714
- }
715
- };
716
- const message = error instanceof Error ? error.message.toLowerCase() : "";
717
- if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
718
- if (message.includes("slug")) return {
719
- success: false,
720
- error: {
721
- code: "SLUG_CONFLICT",
722
- message: `Slug '${body.slug ?? "(auto-generated)"}' already exists in collection '${collection}'`
723
- }
724
- };
725
- return {
726
- success: false,
727
- error: {
728
- code: "CONFLICT",
729
- message: "Unique constraint violation"
730
- }
731
- };
732
- }
733
- console.error("Content create error:", error);
734
- return {
735
- success: false,
736
- error: {
737
- code: "CONTENT_CREATE_ERROR",
738
- message: "Failed to create content"
739
- }
740
- };
741
- }
742
- }
743
- /**
744
- * Update content item.
745
- * If `_rev` is provided, validates it against the current version before writing.
746
- * No `_rev` = blind write (backwards-compatible for admin UI).
747
- *
748
- * Content + SEO writes are wrapped in a transaction for atomicity.
749
- */
750
- async function handleContentUpdate(db, collection, id, body) {
751
- try {
752
- const hasSeo = await collectionHasSeo(db, collection);
753
- if (body.seo && !hasSeo) return {
754
- success: false,
755
- error: {
756
- code: "VALIDATION_ERROR",
757
- message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`
758
- }
759
- };
760
- if (body.data) {
761
- const mimeCheck = await validateMediaFields(db, collection, body.data);
762
- if (!mimeCheck.success) return mimeCheck;
763
- }
764
- const resolvedId = await resolveId(new ContentRepository(db), collection, id, body.locale) ?? id;
765
- const item = await withTransaction(db, async (trx) => {
766
- const trxRepo = new ContentRepository(trx);
767
- const bylineRepo = new BylineRepository(trx);
768
- const existing = body._rev || body.slug !== void 0 || body.status === "published" ? await trxRepo.findById(collection, resolvedId) : null;
769
- if (body._rev) {
770
- if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
771
- const revCheck = validateRev(body._rev, existing);
772
- if (!revCheck.valid) throw Object.assign(new Error(revCheck.message), { apiError: { code: "CONFLICT" } });
773
- }
774
- let oldSlug;
775
- if (body.slug && existing?.slug && existing.slug !== body.slug) oldSlug = existing.slug;
776
- if ((body.status ?? existing?.status) === "published") {
777
- if (!existing) throw Object.assign(/* @__PURE__ */ new Error(`Content item not found: ${id}`), { apiError: { code: "NOT_FOUND" } });
778
- const publishConfig = await getCollectionPublishConfig(trx, collection);
779
- const intendedSlug = body.slug !== void 0 ? body.slug : existing.slug;
780
- requireRoutablePublishSlug(publishConfig.routable, intendedSlug);
781
- }
782
- const updated = await trxRepo.update(collection, resolvedId, {
783
- data: body.data,
784
- slug: body.slug,
785
- status: body.status,
786
- authorId: body.authorId,
787
- publishedAt: body.publishedAt
788
- });
789
- if (body.bylines !== void 0) updated.primaryBylineId = (await bylineRepo.setContentBylines(collection, resolvedId, body.bylines))[0]?.byline.translationGroup ?? null;
790
- if (oldSlug && body.slug) await createSlugChangeRedirect(trx, collection, oldSlug, body.slug, resolvedId);
791
- if (isI18nEnabled() && body.data && updated.translationGroup) await syncNonTranslatableFields(trx, collection, updated.id, updated.translationGroup, body.data);
792
- if (body.seo && hasSeo) updated.seo = await new SeoRepository(trx).upsert(collection, resolvedId, body.seo);
793
- else if (hasSeo) updated.seo = await new SeoRepository(trx).get(collection, resolvedId);
794
- await hydrateBylines(trx, collection, updated);
795
- if (body.taxonomies) await assignTaxonomies(trx, collection, resolvedId, updated.locale ?? body.locale, body.taxonomies);
796
- return updated;
797
- });
798
- return {
799
- success: true,
800
- data: {
801
- item,
802
- _rev: encodeRev(item)
803
- }
804
- };
805
- } catch (error) {
806
- if (hasApiError(error)) return {
807
- success: false,
808
- error: {
809
- code: error.apiError.code,
810
- message: error.message
811
- }
812
- };
813
- if (isMissingTableError(error)) return {
814
- success: false,
815
- error: {
816
- code: "COLLECTION_NOT_FOUND",
817
- message: `Collection '${collection}' not found`
818
- }
819
- };
820
- if (error instanceof EmDashValidationError) return {
821
- success: false,
822
- error: {
823
- code: "VALIDATION_ERROR",
824
- message: error.message
825
- }
826
- };
827
- const message = error instanceof Error ? error.message.toLowerCase() : "";
828
- if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
829
- if (message.includes("slug")) return {
830
- success: false,
831
- error: {
832
- code: "SLUG_CONFLICT",
833
- message: `Slug '${body.slug ?? id}' already exists in collection '${collection}'`
834
- }
835
- };
836
- return {
837
- success: false,
838
- error: {
839
- code: "CONFLICT",
840
- message: "Unique constraint violation"
841
- }
842
- };
843
- }
844
- console.error("Content update error:", error);
845
- return {
846
- success: false,
847
- error: {
848
- code: "CONTENT_UPDATE_ERROR",
849
- message: "Failed to update content"
850
- }
851
- };
852
- }
853
- }
854
- /**
855
- * Duplicate content item.
856
- *
857
- * Only copies SEO data if the collection has SEO enabled.
858
- * Always returns consistent `seo` shape for SEO-enabled collections.
859
- */
860
- async function handleContentDuplicate(db, collection, id, authorId) {
861
- try {
862
- const hasSeo = await collectionHasSeo(db, collection);
863
- return {
864
- success: true,
865
- data: { item: await withTransaction(db, async (trx) => {
866
- const repo = new ContentRepository(trx);
867
- const bylineRepo = new BylineRepository(trx);
868
- const resolvedId = await resolveId(repo, collection, id) ?? id;
869
- const dup = await repo.duplicate(collection, resolvedId, authorId);
870
- const existingBylines = await bylineRepo.getContentBylines(collection, resolvedId);
871
- if (existingBylines.length > 0) await bylineRepo.setContentBylines(collection, dup.id, existingBylines.map((entry) => ({
872
- bylineId: entry.byline.id,
873
- roleLabel: entry.roleLabel
874
- })));
875
- if (hasSeo) {
876
- const seoRepo = new SeoRepository(trx);
877
- await seoRepo.copyForDuplicate(collection, resolvedId, dup.id);
878
- dup.seo = await seoRepo.get(collection, dup.id);
879
- }
880
- await hydrateBylines(trx, collection, dup);
881
- return dup;
882
- }) }
883
- };
884
- } catch (err) {
885
- if (err instanceof EmDashValidationError) return {
886
- success: false,
887
- error: {
888
- code: "NOT_FOUND",
889
- message: err.message
890
- }
891
- };
892
- console.error("Content duplicate error:", err);
893
- return {
894
- success: false,
895
- error: {
896
- code: "CONTENT_DUPLICATE_ERROR",
897
- message: "Failed to duplicate content"
898
- }
899
- };
900
- }
901
- }
902
- /**
903
- * Delete content item (soft delete - moves to trash)
904
- */
905
- async function handleContentDelete(db, collection, id) {
906
- try {
907
- const result = await withTransaction(db, async (trx) => {
908
- const repo = new ContentRepository(trx);
909
- const resolvedId = await resolveId(repo, collection, id) ?? id;
910
- return {
911
- id: resolvedId,
912
- deleted: await repo.delete(collection, resolvedId)
913
- };
914
- });
915
- if (!result.deleted) return {
916
- success: false,
917
- error: {
918
- code: "NOT_FOUND",
919
- message: `Content item not found: ${id}`
920
- }
921
- };
922
- return {
923
- success: true,
924
- data: {
925
- deleted: true,
926
- id: result.id
927
- }
928
- };
929
- } catch (error) {
930
- console.error("Content delete error:", error);
931
- return {
932
- success: false,
933
- error: {
934
- code: "CONTENT_DELETE_ERROR",
935
- message: "Failed to delete content"
936
- }
937
- };
938
- }
939
- }
940
- /**
941
- * Restore content item from trash
942
- */
943
- async function handleContentRestore(db, collection, id) {
944
- try {
945
- const item = await withTransaction(db, async (trx) => {
946
- const repo = new ContentRepository(trx);
947
- const resolvedId = await resolveIdIncludingTrashed(repo, collection, id) ?? id;
948
- return repo.restore(collection, resolvedId);
949
- });
950
- if (!item) return {
951
- success: false,
952
- error: {
953
- code: "NOT_FOUND",
954
- message: `Trashed content item not found: ${id}`
955
- }
956
- };
957
- return {
958
- success: true,
959
- data: {
960
- restored: true,
961
- item
962
- }
963
- };
964
- } catch (error) {
965
- console.error("Content restore error:", error);
966
- return {
967
- success: false,
968
- error: {
969
- code: "CONTENT_RESTORE_ERROR",
970
- message: "Failed to restore content"
971
- }
972
- };
973
- }
974
- }
975
- /**
976
- * Permanently delete content item (cannot be undone).
977
- * Also cleans up associated SEO data.
978
- */
979
- async function handleContentPermanentDelete(db, collection, id) {
980
- try {
981
- const resolvedId = await resolveIdIncludingTrashed(new ContentRepository(db), collection, id) ?? id;
982
- if (!await withTransaction(db, async (trx) => {
983
- const wasDeleted = await new ContentRepository(trx).permanentDelete(collection, resolvedId);
984
- if (wasDeleted) {
985
- await new SeoRepository(trx).delete(collection, resolvedId);
986
- await new CommentRepository(trx).deleteByContent(collection, resolvedId);
987
- await new RevisionRepository(trx).deleteByEntry(collection, resolvedId);
988
- }
989
- return wasDeleted;
990
- })) return {
991
- success: false,
992
- error: {
993
- code: "NOT_FOUND",
994
- message: `Content item not found: ${id}`
995
- }
996
- };
997
- return {
998
- success: true,
999
- data: {
1000
- deleted: true,
1001
- id: resolvedId
1002
- }
1003
- };
1004
- } catch (error) {
1005
- console.error("Content permanent delete error:", error);
1006
- return {
1007
- success: false,
1008
- error: {
1009
- code: "CONTENT_DELETE_ERROR",
1010
- message: "Failed to permanently delete content"
1011
- }
1012
- };
1013
- }
1014
- }
1015
- /**
1016
- * List trashed content items
1017
- */
1018
- async function handleContentListTrashed(db, collection, options = {}) {
1019
- try {
1020
- const result = await new ContentRepository(db).findTrashed(collection, {
1021
- limit: options.limit,
1022
- cursor: options.cursor
1023
- });
1024
- return {
1025
- success: true,
1026
- data: {
1027
- items: result.items.map((item) => ({
1028
- id: item.id,
1029
- type: item.type,
1030
- slug: item.slug,
1031
- status: item.status,
1032
- data: item.data,
1033
- authorId: item.authorId,
1034
- createdAt: item.createdAt,
1035
- updatedAt: item.updatedAt,
1036
- publishedAt: item.publishedAt,
1037
- deletedAt: item.deletedAt
1038
- })),
1039
- nextCursor: result.nextCursor
1040
- }
1041
- };
1042
- } catch (error) {
1043
- if (error instanceof InvalidCursorError) return {
1044
- success: false,
1045
- error: {
1046
- code: "INVALID_CURSOR",
1047
- message: error.message
1048
- }
1049
- };
1050
- console.error("Content list trashed error:", error);
1051
- return {
1052
- success: false,
1053
- error: {
1054
- code: "CONTENT_LIST_ERROR",
1055
- message: "Failed to list trashed content"
1056
- }
1057
- };
1058
- }
1059
- }
1060
- /**
1061
- * Count trashed content items
1062
- */
1063
- async function handleContentCountTrashed(db, collection) {
1064
- try {
1065
- return {
1066
- success: true,
1067
- data: { count: await new ContentRepository(db).countTrashed(collection) }
1068
- };
1069
- } catch (error) {
1070
- console.error("Content count trashed error:", error);
1071
- return {
1072
- success: false,
1073
- error: {
1074
- code: "CONTENT_COUNT_ERROR",
1075
- message: "Failed to count trashed content"
1076
- }
1077
- };
1078
- }
1079
- }
1080
- /**
1081
- * Schedule content for future publishing
1082
- */
1083
- async function handleContentSchedule(db, collection, id, scheduledAt) {
1084
- try {
1085
- const item = await withTransaction(db, async (trx) => {
1086
- const repo = new ContentRepository(trx);
1087
- const existing = await repo.findByIdOrSlug(collection, id);
1088
- const resolvedId = existing?.id ?? id;
1089
- if (existing) requireRoutablePublishSlug((await getCollectionPublishConfig(trx, collection)).routable, existing.slug);
1090
- return repo.schedule(collection, resolvedId, scheduledAt);
1091
- });
1092
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1093
- return {
1094
- success: true,
1095
- data: { item }
1096
- };
1097
- } catch (error) {
1098
- if (error instanceof EmDashValidationError) return {
1099
- success: false,
1100
- error: {
1101
- code: "VALIDATION_ERROR",
1102
- message: error.message
1103
- }
1104
- };
1105
- console.error("Content schedule error:", error);
1106
- return {
1107
- success: false,
1108
- error: {
1109
- code: "CONTENT_SCHEDULE_ERROR",
1110
- message: "Failed to schedule content"
1111
- }
1112
- };
1113
- }
1114
- }
1115
- /**
1116
- * Unschedule content (revert to draft)
1117
- */
1118
- async function handleContentUnschedule(db, collection, id) {
1119
- try {
1120
- const item = await withTransaction(db, async (trx) => {
1121
- const repo = new ContentRepository(trx);
1122
- const resolvedId = await resolveId(repo, collection, id) ?? id;
1123
- return repo.unschedule(collection, resolvedId);
1124
- });
1125
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1126
- return {
1127
- success: true,
1128
- data: { item }
1129
- };
1130
- } catch (error) {
1131
- if (error instanceof EmDashValidationError) return {
1132
- success: false,
1133
- error: {
1134
- code: "VALIDATION_ERROR",
1135
- message: error.message
1136
- }
1137
- };
1138
- console.error("Content unschedule error:", error);
1139
- return {
1140
- success: false,
1141
- error: {
1142
- code: "CONTENT_UNSCHEDULE_ERROR",
1143
- message: "Failed to unschedule content"
1144
- }
1145
- };
1146
- }
1147
- }
1148
- /**
1149
- * Publish content immediately.
1150
- *
1151
- * Publication is one atomic content-row statement. On databases that support
1152
- * transactions, the existing slug-redirect side write remains grouped with it.
1153
- */
1154
- async function handleContentPublish(db, collection, id, options = {}) {
1155
- try {
1156
- const item = await withTransaction(db, async (trx) => {
1157
- const repo = new ContentRepository(trx);
1158
- const resolvedId = await resolveId(repo, collection, id) ?? id;
1159
- const publishConfig = await getCollectionPublishConfig(trx, collection);
1160
- const existing = await repo.findById(collection, resolvedId);
1161
- const published = await repo.publish(collection, resolvedId, options.publishedAt, options.requireScheduledDue, options.expectedScheduledAt, publishConfig.supportsRevisions, publishConfig.routable);
1162
- if (existing?.status === "published" && existing.slug && published.slug && existing.slug !== published.slug) await createSlugChangeRedirect(trx, collection, existing.slug, published.slug, resolvedId);
1163
- return published;
1164
- });
1165
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1166
- return {
1167
- success: true,
1168
- data: { item }
1169
- };
1170
- } catch (error) {
1171
- if (error instanceof ContentMutationConflictError) return {
1172
- success: false,
1173
- error: {
1174
- code: "CONFLICT",
1175
- message: error.message
1176
- }
1177
- };
1178
- if (error instanceof ScheduledNotDueError) return {
1179
- success: false,
1180
- error: {
1181
- code: "NOT_DUE",
1182
- message: error.message
1183
- }
1184
- };
1185
- if (error instanceof EmDashValidationError) {
1186
- const details = error.details;
1187
- return {
1188
- success: false,
1189
- error: {
1190
- code: typeof details === "object" && details !== null && "code" in details && details.code === "SLUG_CONFLICT" ? "SLUG_CONFLICT" : "VALIDATION_ERROR",
1191
- message: error.message
1192
- }
1193
- };
1194
- }
1195
- const message = error instanceof Error ? error.message.toLowerCase() : "";
1196
- if ((message.includes("unique constraint failed") || message.includes("duplicate key")) && message.includes("slug")) return {
1197
- success: false,
1198
- error: {
1199
- code: "SLUG_CONFLICT",
1200
- message: `The staged slug is already used by another entry in collection '${collection}'`
1201
- }
1202
- };
1203
- console.error("Content publish error:", error);
1204
- return {
1205
- success: false,
1206
- error: {
1207
- code: "CONTENT_PUBLISH_ERROR",
1208
- message: "Failed to publish content"
1209
- }
1210
- };
1211
- }
1212
- }
1213
- /**
1214
- * Unpublish content (revert to draft).
1215
- *
1216
- * Wrapped in a transaction — unpublish may create a draft revision
1217
- * from the live version then update the status, which is multi-step.
1218
- */
1219
- async function handleContentUnpublish(db, collection, id) {
1220
- try {
1221
- const item = await withTransaction(db, async (trx) => {
1222
- const repo = new ContentRepository(trx);
1223
- const resolvedId = await resolveId(repo, collection, id) ?? id;
1224
- return repo.unpublish(collection, resolvedId);
1225
- });
1226
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1227
- return {
1228
- success: true,
1229
- data: { item }
1230
- };
1231
- } catch (error) {
1232
- if (error instanceof EmDashValidationError) return {
1233
- success: false,
1234
- error: {
1235
- code: "VALIDATION_ERROR",
1236
- message: error.message
1237
- }
1238
- };
1239
- console.error("Content unpublish error:", error);
1240
- return {
1241
- success: false,
1242
- error: {
1243
- code: "CONTENT_UNPUBLISH_ERROR",
1244
- message: "Failed to unpublish content"
1245
- }
1246
- };
1247
- }
1248
- }
1249
- /**
1250
- * Count scheduled content items
1251
- */
1252
- async function handleContentCountScheduled(db, collection) {
1253
- try {
1254
- return {
1255
- success: true,
1256
- data: { count: await new ContentRepository(db).countScheduled(collection) }
1257
- };
1258
- } catch (error) {
1259
- console.error("Content count scheduled error:", error);
1260
- return {
1261
- success: false,
1262
- error: {
1263
- code: "CONTENT_COUNT_ERROR",
1264
- message: "Failed to count scheduled content"
1265
- }
1266
- };
1267
- }
1268
- }
1269
- /**
1270
- * Discard draft changes (revert to live version)
1271
- */
1272
- async function handleContentDiscardDraft(db, collection, id) {
1273
- try {
1274
- const item = await withTransaction(db, async (trx) => {
1275
- const repo = new ContentRepository(trx);
1276
- const resolvedId = await resolveId(repo, collection, id) ?? id;
1277
- return repo.discardDraft(collection, resolvedId);
1278
- });
1279
- await hydrateSeo(db, collection, item, await collectionHasSeo(db, collection));
1280
- return {
1281
- success: true,
1282
- data: { item }
1283
- };
1284
- } catch (error) {
1285
- if (error instanceof EmDashValidationError) return {
1286
- success: false,
1287
- error: {
1288
- code: "NOT_FOUND",
1289
- message: error.message
1290
- }
1291
- };
1292
- console.error("Content discard draft error:", error);
1293
- return {
1294
- success: false,
1295
- error: {
1296
- code: "CONTENT_DISCARD_DRAFT_ERROR",
1297
- message: "Failed to discard draft"
1298
- }
1299
- };
1300
- }
1301
- }
1302
- /**
1303
- * Compare live and draft revisions
1304
- */
1305
- async function handleContentCompare(db, collection, id) {
1306
- try {
1307
- const entry = await new ContentRepository(db).findByIdOrSlug(collection, id);
1308
- if (!entry) return {
1309
- success: false,
1310
- error: {
1311
- code: "NOT_FOUND",
1312
- message: `Content item not found: ${id}`
1313
- }
1314
- };
1315
- const revisionRepo = new RevisionRepository(db);
1316
- const live = entry.liveRevisionId ? await revisionRepo.findById(entry.liveRevisionId) : null;
1317
- const draft = entry.draftRevisionId ? await revisionRepo.findById(entry.draftRevisionId) : null;
1318
- return {
1319
- success: true,
1320
- data: {
1321
- hasChanges: entry.draftRevisionId !== null && entry.draftRevisionId !== entry.liveRevisionId,
1322
- live: live?.data ?? null,
1323
- draft: draft?.data ?? null
1324
- }
1325
- };
1326
- } catch (error) {
1327
- console.error("Content compare error:", error);
1328
- return {
1329
- success: false,
1330
- error: {
1331
- code: "CONTENT_COMPARE_ERROR",
1332
- message: "Failed to compare revisions"
1333
- }
1334
- };
1335
- }
1336
- }
1337
- /**
1338
- * Get all translations for a content item.
1339
- * Returns the item's translation group members with locale and status info.
1340
- */
1341
- async function handleContentTranslations(db, collection, id) {
1342
- try {
1343
- const repo = new ContentRepository(db);
1344
- const item = await repo.findByIdOrSlug(collection, id);
1345
- if (!item) return {
1346
- success: false,
1347
- error: {
1348
- code: "NOT_FOUND",
1349
- message: `Content item not found: ${id}`
1350
- }
1351
- };
1352
- if (!item.translationGroup) return {
1353
- success: true,
1354
- data: {
1355
- translationGroup: item.id,
1356
- translations: [{
1357
- id: item.id,
1358
- locale: item.locale,
1359
- slug: item.slug,
1360
- status: item.status,
1361
- updatedAt: item.updatedAt
1362
- }]
1363
- }
1364
- };
1365
- const translations = await repo.findTranslations(collection, item.translationGroup);
1366
- return {
1367
- success: true,
1368
- data: {
1369
- translationGroup: item.translationGroup,
1370
- translations: translations.map((t) => ({
1371
- id: t.id,
1372
- locale: t.locale,
1373
- slug: t.slug,
1374
- status: t.status,
1375
- updatedAt: t.updatedAt
1376
- }))
1377
- }
1378
- };
1379
- } catch (error) {
1380
- if (error instanceof Error) console.error("Content translations error:", error);
1381
- return {
1382
- success: false,
1383
- error: {
1384
- code: "CONTENT_TRANSLATIONS_ERROR",
1385
- message: "Failed to get translations"
1386
- }
1387
- };
1388
- }
1389
- }
1390
- /**
1391
- * Sync non-translatable fields to sibling locales.
1392
- *
1393
- * When a content item is updated and it belongs to a translation group,
1394
- * any non-translatable fields in the update data are written to all other
1395
- * rows in the same translation group within the same transaction.
1396
- *
1397
- * Non-translatable fields are **copied, not linked** — each row owns its
1398
- * own data. This keeps queries simple and avoids cross-row joins.
1399
- */
1400
- async function syncNonTranslatableFields(trx, collectionSlug, updatedItemId, translationGroup, data) {
1401
- const collection = await trx.selectFrom("_emdash_collections").select("id").where("slug", "=", collectionSlug).executeTakeFirst();
1402
- if (!collection) return;
1403
- const nonTranslatableSlugs = (await trx.selectFrom("_emdash_fields").select("slug").where("collection_id", "=", collection.id).where("translatable", "=", 0).execute()).map((f) => f.slug);
1404
- if (nonTranslatableSlugs.length === 0) return;
1405
- const syncData = {};
1406
- for (const slug of nonTranslatableSlugs) if (slug in data) syncData[slug] = data[slug];
1407
- if (Object.keys(syncData).length === 0) return;
1408
- validateIdentifier(collectionSlug, "collection slug");
1409
- const tableName = `ec_${collectionSlug}`;
1410
- const setClauses = Object.entries(syncData).map(([key, value]) => {
1411
- validateIdentifier(key, "field slug");
1412
- const serialized = typeof value === "object" && value !== null ? JSON.stringify(value) : value;
1413
- return sql`${sql.ref(key)} = ${serialized}`;
1414
- });
1415
- await sql`
1416
- UPDATE ${sql.ref(tableName)}
1417
- SET ${sql.join(setClauses, sql`, `)}
1418
- WHERE translation_group = ${translationGroup}
1419
- AND id != ${updatedItemId}
1420
- `.execute(trx);
1421
- }
1422
- /**
1423
- * Resolve a `{ taxonomyName: [slug, ...] }` map to term IDs and replace the
1424
- * entry's assignments for each named taxonomy.
1425
- *
1426
- * Shared by handleContentCreate and handleContentUpdate so both MCP entry
1427
- * points behave identically. Slug resolution is scoped to `locale`; passing
1428
- * `undefined` lets `findBySlug` fall back to its default (lowest locale code)
1429
- * so callers on single-locale sites don't need to know the site's default.
1430
- *
1431
- * Throws EmDashValidationError on unknown slug or wrong shape; the calling
1432
- * handler translates that into a VALIDATION_ERROR response.
1433
- */
1434
- async function assignTaxonomies(trx, collection, entryId, locale, taxonomies) {
1435
- const taxRepo = new TaxonomyRepository(trx);
1436
- let anyChange = false;
1437
- for (const [taxonomyName, slugs] of Object.entries(taxonomies)) {
1438
- if (!Array.isArray(slugs)) throw new EmDashValidationError(`taxonomies.${taxonomyName} must be an array of term slugs`);
1439
- const termIds = [];
1440
- for (const slug of slugs) {
1441
- if (typeof slug !== "string" || slug.length === 0) throw new EmDashValidationError(`taxonomies.${taxonomyName} contains a non-string or empty slug`);
1442
- const term = await taxRepo.findBySlug(taxonomyName, slug, locale);
1443
- if (!term) throw new EmDashValidationError(`Unknown taxonomy term: ${taxonomyName}='${slug}'${locale ? ` (locale '${locale}')` : ""}`);
1444
- termIds.push(term.id);
1445
- }
1446
- await taxRepo.setTermsForEntry(collection, entryId, taxonomyName, termIds);
1447
- anyChange = true;
1448
- }
1449
- if (anyChange) invalidateTermCache();
1450
- }
1451
-
1452
- //#endregion
1453
- //#region src/api/handlers/manifest.ts
1454
- /**
1455
- * Manifest generation handlers
1456
- */
1457
- /** Pattern to add spaces before capital letters */
1458
- const CAMEL_CASE_PATTERN = /([A-Z])/g;
1459
- const FIRST_CHAR_PATTERN = /^./;
1460
- /**
1461
- * Generate admin manifest from collections
1462
- */
1463
- async function generateManifest(collections, plugins = {}) {
1464
- const manifestCollections = {};
1465
- for (const [name, definition] of Object.entries(collections)) {
1466
- const fields = extractFieldDescriptors(definition.schema);
1467
- manifestCollections[name] = {
1468
- label: definition.admin.label,
1469
- labelSingular: definition.admin.labelSingular || definition.admin.label,
1470
- supports: definition.admin.supports || [],
1471
- routable: definition.admin.routable ?? true,
1472
- fields
1473
- };
1474
- }
1475
- return {
1476
- version: "0.1.0",
1477
- hash: await hashString(JSON.stringify(manifestCollections)),
1478
- collections: manifestCollections,
1479
- plugins
1480
- };
1481
- }
1482
- /**
1483
- * Extract field descriptors from Zod schema
1484
- * Note: This is a simplified implementation that handles common types
1485
- */
1486
- function extractFieldDescriptors(schema) {
1487
- const fields = {};
1488
- const shape = typeof schema._def?.shape === "function" ? schema._def.shape() : schema.shape || {};
1489
- for (const [name, fieldSchema] of Object.entries(shape)) fields[name] = extractFieldType(name, fieldSchema);
1490
- return fields;
1491
- }
1492
- /**
1493
- * Extract field type from Zod schema
1494
- */
1495
- /** Type guard: check if a value is a non-null object */
1496
- function isObject(value) {
1497
- return typeof value === "object" && value !== null;
1498
- }
1499
- function extractFieldType(name, schema) {
1500
- if (!isObject(schema)) return {
1501
- kind: "string",
1502
- label: formatLabel(name)
1503
- };
1504
- if (schema.isPortableText) return {
1505
- kind: "portableText",
1506
- label: formatLabel(name)
1507
- };
1508
- if (schema.isImage) return {
1509
- kind: "image",
1510
- label: formatLabel(name)
1511
- };
1512
- if (schema.isReference) return {
1513
- kind: "reference",
1514
- label: formatLabel(name)
1515
- };
1516
- const def = isObject(schema._def) ? schema._def : void 0;
1517
- switch (typeof def?.typeName === "string" ? def.typeName : void 0) {
1518
- case "ZodString": return {
1519
- kind: "string",
1520
- label: formatLabel(name)
1521
- };
1522
- case "ZodNumber": return {
1523
- kind: "number",
1524
- label: formatLabel(name)
1525
- };
1526
- case "ZodBoolean": return {
1527
- kind: "boolean",
1528
- label: formatLabel(name)
1529
- };
1530
- case "ZodDate": return {
1531
- kind: "datetime",
1532
- label: formatLabel(name)
1533
- };
1534
- case "ZodEnum": {
1535
- const values = Array.isArray(def?.values) ? def.values : [];
1536
- return {
1537
- kind: "select",
1538
- label: formatLabel(name),
1539
- options: values.filter((v) => typeof v === "string").map((v) => ({
1540
- value: v,
1541
- label: v.charAt(0).toUpperCase() + v.slice(1)
1542
- }))
1543
- };
1544
- }
1545
- case "ZodArray": return {
1546
- kind: "array",
1547
- label: formatLabel(name)
1548
- };
1549
- case "ZodObject": return {
1550
- kind: "object",
1551
- label: formatLabel(name)
1552
- };
1553
- case "ZodOptional":
1554
- case "ZodDefault":
1555
- if (def?.innerType) return extractFieldType(name, def.innerType);
1556
- return {
1557
- kind: "string",
1558
- label: formatLabel(name)
1559
- };
1560
- default: return {
1561
- kind: "string",
1562
- label: formatLabel(name)
1563
- };
1564
- }
1565
- }
1566
- /**
1567
- * Format field name as label
1568
- */
1569
- function formatLabel(name) {
1570
- return name.replace(CAMEL_CASE_PATTERN, " $1").replace(FIRST_CHAR_PATTERN, (str) => str.toUpperCase()).trim();
1571
- }
1572
-
1573
- //#endregion
1574
- //#region src/api/handlers/revision.ts
1575
- /**
1576
- * List revisions for a content entry
1577
- */
1578
- async function handleRevisionList(db, collection, entryId, params = {}) {
1579
- try {
1580
- const repo = new RevisionRepository(db);
1581
- const [items, total] = await Promise.all([repo.findByEntry(collection, entryId, { limit: Math.min(params.limit || 50, 100) }), repo.countByEntry(collection, entryId)]);
1582
- return {
1583
- success: true,
1584
- data: {
1585
- items,
1586
- total
1587
- }
1588
- };
1589
- } catch {
1590
- return {
1591
- success: false,
1592
- error: {
1593
- code: "REVISION_LIST_ERROR",
1594
- message: "Failed to list revisions"
1595
- }
1596
- };
1597
- }
1598
- }
1599
- /**
1600
- * Get a specific revision
1601
- */
1602
- async function handleRevisionGet(db, revisionId) {
1603
- try {
1604
- const item = await new RevisionRepository(db).findById(revisionId);
1605
- if (!item) return {
1606
- success: false,
1607
- error: {
1608
- code: "NOT_FOUND",
1609
- message: `Revision not found: ${revisionId}`
1610
- }
1611
- };
1612
- return {
1613
- success: true,
1614
- data: { item }
1615
- };
1616
- } catch {
1617
- return {
1618
- success: false,
1619
- error: {
1620
- code: "REVISION_GET_ERROR",
1621
- message: "Failed to get revision"
1622
- }
1623
- };
1624
- }
1625
- }
1626
- /**
1627
- * Restore a revision (updates content to this revision's data and creates new revision)
1628
- */
1629
- async function handleRevisionRestore(db, revisionId, callerUserId) {
1630
- try {
1631
- const revision = await new RevisionRepository(db).findById(revisionId);
1632
- if (!revision) return {
1633
- success: false,
1634
- error: {
1635
- code: "NOT_FOUND",
1636
- message: `Revision not found: ${revisionId}`
1637
- }
1638
- };
1639
- const { _slug, ...fieldData } = revision.data;
1640
- const { item, queuedRevisionId } = await withTransaction(db, async (trx) => {
1641
- const trxContentRepo = new ContentRepository(trx);
1642
- const trxRevisionRepo = new RevisionRepository(trx);
1643
- return {
1644
- item: await trxContentRepo.update(revision.collection, revision.entryId, {
1645
- data: fieldData,
1646
- slug: typeof _slug === "string" ? _slug : void 0
1647
- }),
1648
- queuedRevisionId: (await trxRevisionRepo.create({
1649
- collection: revision.collection,
1650
- entryId: revision.entryId,
1651
- data: revision.data,
1652
- authorId: callerUserId
1653
- })).id
1654
- };
1655
- });
1656
- const pruneRepo = new RevisionRepository(db);
1657
- after(async () => {
1658
- try {
1659
- await pruneRepo.pruneQueuedEntry(revision.collection, revision.entryId, queuedRevisionId, 50);
1660
- } catch (error) {
1661
- console.error(`[revisions] Failed to prune revisions for ${revision.collection}/${revision.entryId}:`, error);
1662
- }
1663
- });
1664
- return {
1665
- success: true,
1666
- data: { item }
1667
- };
1668
- } catch {
1669
- return {
1670
- success: false,
1671
- error: {
1672
- code: "REVISION_RESTORE_ERROR",
1673
- message: "Failed to restore revision"
1674
- }
1675
- };
1676
- }
1677
- }
1678
-
1679
- //#endregion
1680
- //#region src/api/handlers/media.ts
1681
- /**
1682
- * List media items
1683
- */
1684
- async function handleMediaList(db, params) {
1685
- try {
1686
- const result = await new MediaRepository(db).findMany({
1687
- cursor: params.cursor,
1688
- limit: Math.min(params.limit || 50, 100),
1689
- mimeType: params.mimeType,
1690
- q: params.q
1691
- });
1692
- return {
1693
- success: true,
1694
- data: {
1695
- items: result.items,
1696
- nextCursor: result.nextCursor
1697
- }
1698
- };
1699
- } catch (error) {
1700
- if (error instanceof InvalidCursorError) return {
1701
- success: false,
1702
- error: {
1703
- code: "INVALID_CURSOR",
1704
- message: error.message
1705
- }
1706
- };
1707
- return {
1708
- success: false,
1709
- error: {
1710
- code: "MEDIA_LIST_ERROR",
1711
- message: "Failed to list media"
1712
- }
1713
- };
1714
- }
1715
- }
1716
- /**
1717
- * Get single media item
1718
- */
1719
- async function handleMediaGet(db, id) {
1720
- try {
1721
- const item = await new MediaRepository(db).findById(id);
1722
- if (!item) return {
1723
- success: false,
1724
- error: {
1725
- code: "NOT_FOUND",
1726
- message: `Media item not found: ${id}`
1727
- }
1728
- };
1729
- return {
1730
- success: true,
1731
- data: { item }
1732
- };
1733
- } catch {
1734
- return {
1735
- success: false,
1736
- error: {
1737
- code: "MEDIA_GET_ERROR",
1738
- message: "Failed to get media"
1739
- }
1740
- };
1741
- }
1742
- }
1743
- /**
1744
- * Create media item (after file upload)
1745
- */
1746
- async function handleMediaCreate(db, input) {
1747
- try {
1748
- return {
1749
- success: true,
1750
- data: { item: await new MediaRepository(db).create(input) }
1751
- };
1752
- } catch {
1753
- return {
1754
- success: false,
1755
- error: {
1756
- code: "MEDIA_CREATE_ERROR",
1757
- message: "Failed to create media"
1758
- }
1759
- };
1760
- }
1761
- }
1762
- /**
1763
- * Update media metadata
1764
- */
1765
- async function handleMediaUpdate(db, id, input) {
1766
- try {
1767
- const item = await new MediaRepository(db).update(id, input);
1768
- if (!item) return {
1769
- success: false,
1770
- error: {
1771
- code: "NOT_FOUND",
1772
- message: `Media item not found: ${id}`
1773
- }
1774
- };
1775
- return {
1776
- success: true,
1777
- data: { item }
1778
- };
1779
- } catch {
1780
- return {
1781
- success: false,
1782
- error: {
1783
- code: "MEDIA_UPDATE_ERROR",
1784
- message: "Failed to update media"
1785
- }
1786
- };
1787
- }
1788
- }
1789
- /**
1790
- * Delete media item
1791
- */
1792
- async function handleMediaDelete(db, id) {
1793
- try {
1794
- const storageKey = await new MediaRepository(db).deleteWithStorageKey(id);
1795
- if (!storageKey) return {
1796
- success: false,
1797
- error: {
1798
- code: "NOT_FOUND",
1799
- message: `Media item not found: ${id}`
1800
- }
1801
- };
1802
- return {
1803
- success: true,
1804
- data: {
1805
- deleted: true,
1806
- storageKey
1807
- }
1808
- };
1809
- } catch {
1810
- return {
1811
- success: false,
1812
- error: {
1813
- code: "MEDIA_DELETE_ERROR",
1814
- message: "Failed to delete media"
1815
- }
1816
- };
1817
- }
1818
- }
1819
-
1820
- //#endregion
1821
- //#region src/api/handlers/plugins.ts
1822
- function marketplaceIconUrl(marketplaceUrl, pluginId) {
1823
- return `${marketplaceUrl}/api/v1/plugins/${encodeURIComponent(pluginId)}/icon`;
1824
- }
1825
- /**
1826
- * Get plugin info from configured plugin and database state
1827
- */
1828
- function buildPluginInfo(plugin, state, marketplaceUrl) {
1829
- const status = state?.status ?? "active";
1830
- const enabled = status === "active";
1831
- const isMarketplace = (state?.source ?? "config") === "marketplace";
1832
- return {
1833
- id: plugin.id,
1834
- name: state?.displayName || plugin.id,
1835
- version: plugin.version,
1836
- package: void 0,
1837
- enabled,
1838
- status,
1839
- source: state?.source ?? "config",
1840
- marketplaceVersion: state?.marketplaceVersion ?? void 0,
1841
- registryPublisherDid: state?.registryPublisherDid ?? void 0,
1842
- registrySlug: state?.registrySlug ?? void 0,
1843
- capabilities: plugin.capabilities,
1844
- hasAdminPages: (plugin.admin.pages?.length ?? 0) > 0,
1845
- hasDashboardWidgets: (plugin.admin.widgets?.length ?? 0) > 0,
1846
- hasHooks: Object.keys(plugin.hooks ?? {}).length > 0,
1847
- hasSettings: Object.keys(plugin.admin.settingsSchema ?? {}).length > 0,
1848
- installedAt: state?.installedAt?.toISOString(),
1849
- activatedAt: state?.activatedAt?.toISOString() ?? void 0,
1850
- deactivatedAt: state?.deactivatedAt?.toISOString() ?? void 0,
1851
- description: state?.description ?? void 0,
1852
- iconUrl: isMarketplace && marketplaceUrl ? marketplaceIconUrl(marketplaceUrl, plugin.id) : void 0,
1853
- mcpToolsEnabled: state?.mcpToolsEnabled ?? false,
1854
- mcpTools: Object.entries(plugin.mcp?.tools ?? {}).flatMap(([name, tool]) => {
1855
- const permission = plugin.routes[tool.route]?.permission;
1856
- return permission ? [{
1857
- name,
1858
- description: tool.description,
1859
- route: tool.route,
1860
- permission,
1861
- destructive: tool.destructive ?? false
1862
- }] : [];
1863
- })
1864
- };
1865
- }
1866
- /**
1867
- * Build plugin info for a statically-sandboxed plugin entry
1868
- */
1869
- function buildSandboxedPluginInfo(entry, state) {
1870
- const status = state?.status ?? "active";
1871
- const enabled = status === "active";
1872
- return {
1873
- id: entry.id,
1874
- name: state?.displayName || entry.id,
1875
- version: entry.version,
1876
- package: void 0,
1877
- enabled,
1878
- status,
1879
- source: "config",
1880
- sandboxed: true,
1881
- capabilities: entry.capabilities,
1882
- hasAdminPages: (entry.adminPages?.length ?? 0) > 0,
1883
- hasDashboardWidgets: (entry.adminWidgets?.length ?? 0) > 0,
1884
- hasHooks: false,
1885
- hasSettings: Object.keys(entry.settingsSchema ?? {}).length > 0,
1886
- installedAt: state?.installedAt?.toISOString(),
1887
- activatedAt: state?.activatedAt?.toISOString() ?? void 0,
1888
- deactivatedAt: state?.deactivatedAt?.toISOString() ?? void 0,
1889
- description: state?.description ?? void 0,
1890
- mcpToolsEnabled: state?.mcpToolsEnabled ?? false,
1891
- mcpTools: entry.mcp?.tools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool) ?? []
1892
- };
1893
- }
1894
- /**
1895
- * List all configured plugins with their state
1896
- */
1897
- async function handlePluginList(db, configuredPlugins, sandboxedPluginEntries, marketplaceUrl, runtimeSettingsSchemaLookup) {
1898
- try {
1899
- const allStates = await new PluginStateRepository(db).getAll();
1900
- const stateMap = new Map(allStates.map((s) => [s.pluginId, s]));
1901
- const configuredIds = new Set(configuredPlugins.map((p) => p.id));
1902
- const items = configuredPlugins.map((plugin) => {
1903
- return buildPluginInfo(plugin, stateMap.get(plugin.id) ?? null, marketplaceUrl);
1904
- });
1905
- for (const entry of sandboxedPluginEntries) {
1906
- if (configuredIds.has(entry.id)) continue;
1907
- configuredIds.add(entry.id);
1908
- items.push(buildSandboxedPluginInfo(entry, stateMap.get(entry.id) ?? null));
1909
- }
1910
- for (const state of allStates) {
1911
- if (state.source !== "marketplace" && state.source !== "registry") continue;
1912
- if (configuredIds.has(state.pluginId)) continue;
1913
- items.push({
1914
- id: state.pluginId,
1915
- name: state.displayName || state.pluginId,
1916
- version: state.marketplaceVersion ?? state.version,
1917
- enabled: state.status === "active",
1918
- status: state.status,
1919
- source: state.source,
1920
- marketplaceVersion: state.marketplaceVersion ?? void 0,
1921
- registryPublisherDid: state.registryPublisherDid ?? void 0,
1922
- registrySlug: state.registrySlug ?? void 0,
1923
- capabilities: [],
1924
- hasAdminPages: false,
1925
- hasDashboardWidgets: false,
1926
- hasHooks: false,
1927
- hasSettings: Object.keys(runtimeSettingsSchemaLookup?.(state.pluginId) ?? {}).length > 0,
1928
- installedAt: state.installedAt?.toISOString(),
1929
- activatedAt: state.activatedAt?.toISOString() ?? void 0,
1930
- deactivatedAt: state.deactivatedAt?.toISOString() ?? void 0,
1931
- description: state.description ?? void 0,
1932
- iconUrl: state.source === "marketplace" && marketplaceUrl ? marketplaceIconUrl(marketplaceUrl, state.pluginId) : void 0,
1933
- mcpToolsEnabled: state.mcpToolsEnabled,
1934
- mcpTools: []
1935
- });
1936
- }
1937
- return {
1938
- success: true,
1939
- data: { items }
1940
- };
1941
- } catch {
1942
- return {
1943
- success: false,
1944
- error: {
1945
- code: "PLUGIN_LIST_ERROR",
1946
- message: "Failed to list plugins"
1947
- }
1948
- };
1949
- }
1950
- }
1951
- /**
1952
- * Get a single plugin's info
1953
- */
1954
- async function handlePluginGet(db, configuredPlugins, sandboxedPluginEntries, pluginId, marketplaceUrl) {
1955
- try {
1956
- const stateRepo = new PluginStateRepository(db);
1957
- const plugin = configuredPlugins.find((p) => p.id === pluginId);
1958
- if (plugin) return {
1959
- success: true,
1960
- data: { item: buildPluginInfo(plugin, await stateRepo.get(pluginId), marketplaceUrl) }
1961
- };
1962
- const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
1963
- if (sandboxed) return {
1964
- success: true,
1965
- data: { item: buildSandboxedPluginInfo(sandboxed, await stateRepo.get(pluginId)) }
1966
- };
1967
- return {
1968
- success: false,
1969
- error: {
1970
- code: "NOT_FOUND",
1971
- message: `Plugin not found: ${pluginId}`
1972
- }
1973
- };
1974
- } catch {
1975
- return {
1976
- success: false,
1977
- error: {
1978
- code: "PLUGIN_GET_ERROR",
1979
- message: "Failed to get plugin"
1980
- }
1981
- };
1982
- }
1983
- }
1984
- /**
1985
- * Build a minimal `PluginInfo` for a plugin that exists only as a
1986
- * `_plugin_state` row (marketplace or registry install), with no
1987
- * matching `configuredPlugins` entry. Runtime-installed plugins don't
1988
- * have ResolvedPlugin metadata until they're loaded into the sandbox,
1989
- * so the enable/disable response surfaces the state-row view as a
1990
- * stable shape the admin UI already understands.
1991
- */
1992
- function buildStateOnlyPluginInfo(state) {
1993
- return {
1994
- id: state.pluginId,
1995
- name: state.displayName || state.pluginId,
1996
- version: state.marketplaceVersion ?? state.version,
1997
- enabled: state.status === "active",
1998
- status: state.status,
1999
- source: state.source,
2000
- marketplaceVersion: state.marketplaceVersion ?? void 0,
2001
- registryPublisherDid: state.registryPublisherDid ?? void 0,
2002
- registrySlug: state.registrySlug ?? void 0,
2003
- capabilities: [],
2004
- hasAdminPages: false,
2005
- hasDashboardWidgets: false,
2006
- hasHooks: false,
2007
- hasSettings: false,
2008
- installedAt: state.installedAt?.toISOString(),
2009
- activatedAt: state.activatedAt?.toISOString() ?? void 0,
2010
- deactivatedAt: state.deactivatedAt?.toISOString() ?? void 0,
2011
- description: state.description ?? void 0,
2012
- mcpToolsEnabled: state.mcpToolsEnabled,
2013
- mcpTools: []
2014
- };
2015
- }
2016
- /**
2017
- * Enable a plugin
2018
- */
2019
- async function handlePluginEnable(db, configuredPlugins, sandboxedPluginEntries, pluginId) {
2020
- try {
2021
- const stateRepo = new PluginStateRepository(db);
2022
- const plugin = configuredPlugins.find((p) => p.id === pluginId);
2023
- if (plugin) return {
2024
- success: true,
2025
- data: { item: buildPluginInfo(plugin, await stateRepo.enable(pluginId, plugin.version)) }
2026
- };
2027
- const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
2028
- if (sandboxed) return {
2029
- success: true,
2030
- data: { item: buildSandboxedPluginInfo(sandboxed, await stateRepo.enable(pluginId, sandboxed.version)) }
2031
- };
2032
- const existing = await stateRepo.get(pluginId);
2033
- if (!existing || existing.source !== "marketplace" && existing.source !== "registry") return {
2034
- success: false,
2035
- error: {
2036
- code: "NOT_FOUND",
2037
- message: `Plugin not found: ${pluginId}`
2038
- }
2039
- };
2040
- return {
2041
- success: true,
2042
- data: { item: buildStateOnlyPluginInfo(await stateRepo.enable(pluginId, existing.version)) }
2043
- };
2044
- } catch {
2045
- return {
2046
- success: false,
2047
- error: {
2048
- code: "PLUGIN_ENABLE_ERROR",
2049
- message: "Failed to enable plugin"
2050
- }
2051
- };
2052
- }
2053
- }
2054
- /**
2055
- * Disable a plugin
2056
- */
2057
- async function handlePluginDisable(db, configuredPlugins, sandboxedPluginEntries, pluginId) {
2058
- try {
2059
- const stateRepo = new PluginStateRepository(db);
2060
- const plugin = configuredPlugins.find((p) => p.id === pluginId);
2061
- if (plugin) return {
2062
- success: true,
2063
- data: { item: buildPluginInfo(plugin, await stateRepo.disable(pluginId, plugin.version)) }
2064
- };
2065
- const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
2066
- if (sandboxed) return {
2067
- success: true,
2068
- data: { item: buildSandboxedPluginInfo(sandboxed, await stateRepo.disable(pluginId, sandboxed.version)) }
2069
- };
2070
- const existing = await stateRepo.get(pluginId);
2071
- if (!existing || existing.source !== "marketplace" && existing.source !== "registry") return {
2072
- success: false,
2073
- error: {
2074
- code: "NOT_FOUND",
2075
- message: `Plugin not found: ${pluginId}`
2076
- }
2077
- };
2078
- return {
2079
- success: true,
2080
- data: { item: buildStateOnlyPluginInfo(await stateRepo.disable(pluginId, existing.version)) }
2081
- };
2082
- } catch {
2083
- return {
2084
- success: false,
2085
- error: {
2086
- code: "PLUGIN_DISABLE_ERROR",
2087
- message: "Failed to disable plugin"
2088
- }
2089
- };
2090
- }
2091
- }
2092
-
2093
- //#endregion
2094
- //#region src/api/handlers/plugin-settings.ts
2095
- function settingsKey(pluginId, key) {
2096
- return `plugin:${pluginId}:settings:${key}`;
2097
- }
2098
- /**
2099
- * Resolve a plugin's settings schema from either the configured
2100
- * (in-process) plugin list or the statically-sandboxed entries.
2101
- * Returns null when the plugin doesn't exist, undefined-equivalent
2102
- * empty object when it declares no schema.
2103
- */
2104
- function getPluginSettingsSchema(configuredPlugins, sandboxedPluginEntries, pluginId) {
2105
- const plugin = configuredPlugins.find((p) => p.id === pluginId);
2106
- if (plugin) return plugin.admin.settingsSchema ?? {};
2107
- const sandboxed = sandboxedPluginEntries.find((e) => e.id === pluginId);
2108
- if (sandboxed) return sandboxed.settingsSchema ?? {};
2109
- return null;
2110
- }
2111
- /**
2112
- * Validate a single value against its schema field.
2113
- * Returns an error message, or null when valid.
2114
- */
2115
- function validateValue(key, field, value) {
2116
- switch (field.type) {
2117
- case "string":
2118
- case "secret":
2119
- case "url":
2120
- case "email":
2121
- if (typeof value !== "string") return `Setting "${key}" must be a string`;
2122
- if (field.type === "url" && value !== "" && !URL.canParse(value)) return `Setting "${key}" must be a valid URL`;
2123
- if (field.type === "email" && value !== "" && !value.includes("@")) return `Setting "${key}" must be a valid email address`;
2124
- return null;
2125
- case "number":
2126
- if (typeof value !== "number" || Number.isNaN(value)) return `Setting "${key}" must be a number`;
2127
- if (field.min !== void 0 && value < field.min) return `Setting "${key}" must be at least ${field.min}`;
2128
- if (field.max !== void 0 && value > field.max) return `Setting "${key}" must be at most ${field.max}`;
2129
- return null;
2130
- case "boolean": return typeof value === "boolean" ? null : `Setting "${key}" must be a boolean`;
2131
- case "select":
2132
- if (typeof value !== "string" || !field.options.some((o) => o.value === value)) return `Setting "${key}" must be one of the defined options`;
2133
- return null;
2134
- default: return `Setting "${key}" has an unknown field type`;
2135
- }
2136
- }
2137
- async function buildSettingsResponse(optionsRepo, pluginId, schema) {
2138
- const keys = Object.keys(schema);
2139
- const stored = await optionsRepo.getMany(keys.map((key) => settingsKey(pluginId, key)));
2140
- const values = {};
2141
- const secretsSet = {};
2142
- for (const key of keys) {
2143
- const field = schema[key];
2144
- if (!field) continue;
2145
- const storedValue = stored.get(settingsKey(pluginId, key));
2146
- if (field.type === "secret") {
2147
- secretsSet[key] = typeof storedValue === "string" && storedValue.length > 0;
2148
- continue;
2149
- }
2150
- if (storedValue !== void 0 && storedValue !== null) values[key] = storedValue;
2151
- else if ("default" in field && field.default !== void 0) values[key] = field.default;
2152
- else values[key] = null;
2153
- }
2154
- return {
2155
- schema,
2156
- values,
2157
- secretsSet
2158
- };
2159
- }
2160
- /**
2161
- * Get a plugin's settings (schema + current values, secrets masked)
2162
- */
2163
- async function handlePluginSettingsGet(db, pluginId, schema) {
2164
- try {
2165
- return {
2166
- success: true,
2167
- data: await buildSettingsResponse(new OptionsRepository(db), pluginId, schema)
2168
- };
2169
- } catch {
2170
- return {
2171
- success: false,
2172
- error: {
2173
- code: ErrorCode.PLUGIN_SETTINGS_READ_ERROR,
2174
- message: "Failed to read plugin settings"
2175
- }
2176
- };
2177
- }
2178
- }
2179
- /**
2180
- * Update a plugin's settings.
2181
- *
2182
- * Only keys present in `updates` are written. A `null` value deletes the
2183
- * stored value (reverting to the schema default). Secret fields are
2184
- * write-only: they accept a new string value or `null` to clear, and the
2185
- * response never echoes them back.
2186
- */
2187
- async function handlePluginSettingsUpdate(db, pluginId, schema, updates) {
2188
- try {
2189
- for (const [key, value] of Object.entries(updates)) {
2190
- const field = schema[key];
2191
- if (!field) return {
2192
- success: false,
2193
- error: {
2194
- code: ErrorCode.VALIDATION_ERROR,
2195
- message: `Unknown setting "${key}" for plugin "${pluginId}"`
2196
- }
2197
- };
2198
- if (value === null) continue;
2199
- const error = validateValue(key, field, value);
2200
- if (error) return {
2201
- success: false,
2202
- error: {
2203
- code: ErrorCode.VALIDATION_ERROR,
2204
- message: error
2205
- }
2206
- };
2207
- }
2208
- return {
2209
- success: true,
2210
- data: await withTransaction(db, async (trx) => {
2211
- const txRepo = new OptionsRepository(trx);
2212
- for (const [key, value] of Object.entries(updates)) if (value === null) await txRepo.delete(settingsKey(pluginId, key));
2213
- else await txRepo.set(settingsKey(pluginId, key), value);
2214
- return buildSettingsResponse(txRepo, pluginId, schema);
2215
- })
2216
- };
2217
- } catch {
2218
- return {
2219
- success: false,
2220
- error: {
2221
- code: ErrorCode.PLUGIN_SETTINGS_UPDATE_ERROR,
2222
- message: "Failed to update plugin settings"
2223
- }
2224
- };
2225
- }
2226
- }
2227
-
2228
- //#endregion
2229
- //#region src/plugins/marketplace.ts
2230
- /**
2231
- * MarketplaceClient — HTTP client for the EmDash Plugin Marketplace
2232
- *
2233
- * Used by the install/update/proxy endpoints in EmDash core to communicate
2234
- * with the marketplace Worker. The marketplace is a distribution channel,
2235
- * not a runtime dependency — bundles are copied to site-local R2 at install time.
2236
- */
2237
- const TRAILING_SLASHES$1 = /\/+$/;
2238
- const LEADING_DOT_SLASH = /^\.\//;
2239
- var MarketplaceError = class extends Error {
2240
- constructor(message, status, code) {
2241
- super(message);
2242
- this.status = status;
2243
- this.code = code;
2244
- this.name = "MarketplaceError";
2245
- }
2246
- };
2247
- var MarketplaceUnavailableError = class extends MarketplaceError {
2248
- constructor(cause) {
2249
- super("Plugin marketplace is unavailable", void 0, "MARKETPLACE_UNAVAILABLE");
2250
- if (cause) this.cause = cause;
2251
- }
2252
- };
2253
- var MarketplaceClientImpl = class {
2254
- baseUrl;
2255
- siteOrigin;
2256
- constructor(baseUrl, siteOrigin) {
2257
- this.baseUrl = baseUrl.replace(TRAILING_SLASHES$1, "");
2258
- this.siteOrigin = siteOrigin;
2259
- }
2260
- async search(query, opts) {
2261
- const params = new URLSearchParams();
2262
- if (query) params.set("q", query);
2263
- if (opts?.category) params.set("category", opts.category);
2264
- if (opts?.capability) params.set("capability", opts.capability);
2265
- if (opts?.sort) params.set("sort", opts.sort);
2266
- if (opts?.cursor) params.set("cursor", opts.cursor);
2267
- if (opts?.limit) params.set("limit", String(opts.limit));
2268
- const qs = params.toString();
2269
- const url = `${this.baseUrl}/api/v1/plugins${qs ? `?${qs}` : ""}`;
2270
- return await this.fetchJson(url);
2271
- }
2272
- async getPlugin(id) {
2273
- const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}`;
2274
- return this.fetchJson(url);
2275
- }
2276
- async getVersions(id) {
2277
- const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/versions`;
2278
- return (await this.fetchJson(url)).items;
2279
- }
2280
- async downloadBundle(id, version) {
2281
- const bundleUrl = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/versions/${encodeURIComponent(version)}/bundle`;
2282
- const marketplaceOrigin = new URL(this.baseUrl).origin;
2283
- const MAX_REDIRECTS = 5;
2284
- let response;
2285
- try {
2286
- let currentUrl = bundleUrl;
2287
- response = await fetch(currentUrl, { redirect: "manual" });
2288
- for (let i = 0; i < MAX_REDIRECTS; i++) {
2289
- if (response.status < 300 || response.status >= 400) break;
2290
- const location = response.headers.get("location");
2291
- if (!location) break;
2292
- const target = new URL(location, currentUrl);
2293
- if (target.origin !== marketplaceOrigin) throw new MarketplaceError(`Bundle download redirected to untrusted host: ${target.origin}`, response.status, "BUNDLE_REDIRECT_UNTRUSTED");
2294
- currentUrl = target.href;
2295
- response = await fetch(currentUrl, { redirect: "manual" });
2296
- }
2297
- if (response.status >= 300 && response.status < 400) throw new MarketplaceError(`Bundle download exceeded maximum redirects (${MAX_REDIRECTS})`, response.status, "BUNDLE_TOO_MANY_REDIRECTS");
2298
- } catch (err) {
2299
- if (err instanceof MarketplaceError) throw err;
2300
- throw new MarketplaceUnavailableError(err);
2301
- }
2302
- if (!response.ok) throw new MarketplaceError(`Failed to download bundle: ${response.status} ${response.statusText}`, response.status, "BUNDLE_DOWNLOAD_FAILED");
2303
- const tarballBytes = new Uint8Array(await response.arrayBuffer());
2304
- try {
2305
- return await extractBundle(tarballBytes);
2306
- } catch (err) {
2307
- if (err instanceof MarketplaceError) throw err;
2308
- throw new MarketplaceError("Failed to extract plugin bundle", void 0, "BUNDLE_EXTRACT_FAILED");
2309
- }
2310
- }
2311
- async reportInstall(id, version) {
2312
- const siteHash = await generateSiteHash(this.siteOrigin);
2313
- const url = `${this.baseUrl}/api/v1/plugins/${encodeURIComponent(id)}/installs`;
2314
- try {
2315
- await fetch(url, {
2316
- method: "POST",
2317
- headers: { "Content-Type": "application/json" },
2318
- body: JSON.stringify({
2319
- siteHash,
2320
- version
2321
- })
2322
- });
2323
- } catch {}
2324
- }
2325
- async searchThemes(query, opts) {
2326
- const params = new URLSearchParams();
2327
- if (query) params.set("q", query);
2328
- if (opts?.keyword) params.set("keyword", opts.keyword);
2329
- if (opts?.sort) params.set("sort", opts.sort);
2330
- if (opts?.cursor) params.set("cursor", opts.cursor);
2331
- if (opts?.limit) params.set("limit", String(opts.limit));
2332
- const qs = params.toString();
2333
- const url = `${this.baseUrl}/api/v1/themes${qs ? `?${qs}` : ""}`;
2334
- return this.fetchJson(url);
2335
- }
2336
- async getTheme(id) {
2337
- const url = `${this.baseUrl}/api/v1/themes/${encodeURIComponent(id)}`;
2338
- return this.fetchJson(url);
2339
- }
2340
- async fetchJson(url) {
2341
- let response;
2342
- try {
2343
- response = await fetch(url, { headers: { Accept: "application/json" } });
2344
- } catch (err) {
2345
- throw new MarketplaceUnavailableError(err);
2346
- }
2347
- if (!response.ok) {
2348
- let errorMessage = `Marketplace request failed: ${response.status}`;
2349
- try {
2350
- const body = await response.json();
2351
- if (body.error) errorMessage = body.error;
2352
- } catch {}
2353
- throw new MarketplaceError(errorMessage, response.status);
2354
- }
2355
- return await response.json();
2356
- }
2357
- };
2358
- /**
2359
- * Extract manifest + code files from a tarball.
2360
- *
2361
- * The tarball is a gzipped tar archive containing:
2362
- * - manifest.json
2363
- * - backend.js
2364
- * - admin.js (optional)
2365
- *
2366
- * We use a minimal tar parser since we only need to read a few small files.
2367
- */
2368
- /**
2369
- * Exported so the experimental registry install handler can reuse the
2370
- * same parse / validate / hash primitive. Despite the file name, this
2371
- * function predates the marketplace-vs-registry split and is generic
2372
- * over plugin bundle tarballs regardless of distribution channel.
2373
- */
2374
- const MAX_DECOMPRESSED_BUNDLE_BYTES = 256 * 1024;
2375
- const MAX_BUNDLE_TAR_ENTRIES = 32;
2376
- async function extractBundle(tarballBytes) {
2377
- const reader = new ReadableStream({ start(controller) {
2378
- controller.enqueue(tarballBytes);
2379
- controller.close();
2380
- } }).pipeThrough(createGzipDecoder()).getReader();
2381
- const chunks = [];
2382
- let total = 0;
2383
- while (true) {
2384
- const { done, value } = await reader.read();
2385
- if (done) break;
2386
- if (!value) continue;
2387
- total += value.byteLength;
2388
- if (total > MAX_DECOMPRESSED_BUNDLE_BYTES) {
2389
- try {
2390
- await reader.cancel();
2391
- } catch {}
2392
- throw new MarketplaceError(`Bundle decompressed size exceeds limit (${MAX_DECOMPRESSED_BUNDLE_BYTES} bytes)`, void 0, "INVALID_BUNDLE");
2393
- }
2394
- chunks.push(value);
2395
- }
2396
- const decompressedBytes = new Uint8Array(total);
2397
- {
2398
- let offset = 0;
2399
- for (const chunk of chunks) {
2400
- decompressedBytes.set(chunk, offset);
2401
- offset += chunk.byteLength;
2402
- }
2403
- }
2404
- const entries = await unpackTar(new ReadableStream({ start(controller) {
2405
- controller.enqueue(decompressedBytes);
2406
- controller.close();
2407
- } }));
2408
- if (entries.length > MAX_BUNDLE_TAR_ENTRIES) throw new MarketplaceError(`Bundle has too many tar entries (${entries.length} > ${MAX_BUNDLE_TAR_ENTRIES})`, void 0, "INVALID_BUNDLE");
2409
- const decoder = new TextDecoder();
2410
- const files = /* @__PURE__ */ new Map();
2411
- for (const entry of entries) if (entry.data && entry.header.type === "file") {
2412
- const name = entry.header.name.replace(LEADING_DOT_SLASH, "");
2413
- files.set(name, decoder.decode(entry.data));
2414
- }
2415
- const manifestJson = files.get("manifest.json");
2416
- const backendCode = files.get("backend.js");
2417
- if (!manifestJson) throw new MarketplaceError("Invalid bundle: missing manifest.json", void 0, "INVALID_BUNDLE");
2418
- if (!backendCode) throw new MarketplaceError("Invalid bundle: missing backend.js", void 0, "INVALID_BUNDLE");
2419
- let manifest;
2420
- try {
2421
- const parsed = JSON.parse(manifestJson);
2422
- const result = pluginManifestSchema.safeParse(parsed);
2423
- if (!result.success) throw new MarketplaceError("Invalid bundle: manifest.json failed validation", void 0, "INVALID_BUNDLE");
2424
- manifest = reconcileManifestAccess(result.data);
2425
- } catch (err) {
2426
- if (err instanceof MarketplaceError) throw err;
2427
- throw new MarketplaceError("Invalid bundle: malformed manifest.json", void 0, "INVALID_BUNDLE");
2428
- }
2429
- const hashBuffer = await crypto.subtle.digest("SHA-256", tarballBytes);
2430
- const hashArray = new Uint8Array(hashBuffer);
2431
- const checksum = Array.from(hashArray, (b) => b.toString(16).padStart(2, "0")).join("");
2432
- return {
2433
- manifest,
2434
- backendCode,
2435
- adminCode: files.get("admin.js"),
2436
- checksum
2437
- };
2438
- }
2439
- /**
2440
- * Generate a stable non-identifying site hash from the site origin.
2441
- * The same origin always produces the same hash, so the marketplace
2442
- * installs table deduplicates correctly per (plugin_id, site_hash).
2443
- */
2444
- async function generateSiteHash(siteOrigin) {
2445
- const seed = siteOrigin ? `emdash-site:${siteOrigin}` : `emdash-anonymous`;
2446
- try {
2447
- const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(seed));
2448
- const arr = new Uint8Array(hash);
2449
- return Array.from(arr.slice(0, 8), (b) => b.toString(16).padStart(2, "0")).join("");
2450
- } catch {
2451
- let h = 2166136261;
2452
- for (let i = 0; i < seed.length; i++) {
2453
- h ^= seed.charCodeAt(i);
2454
- h = Math.imul(h, 16777619);
2455
- }
2456
- const h2 = h ^ h >>> 16;
2457
- return (h >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
2458
- }
2459
- }
2460
- /**
2461
- * Create a MarketplaceClient for the given marketplace URL.
2462
- *
2463
- * @param baseUrl - The marketplace API base URL (e.g. "https://marketplace.emdashcms.com")
2464
- * @param siteOrigin - The origin of the EmDash site (e.g. "https://myblog.example.com").
2465
- * Used to generate a stable, non-identifying site hash for install deduplication.
2466
- */
2467
- function createMarketplaceClient(baseUrl, siteOrigin) {
2468
- return new MarketplaceClientImpl(baseUrl, siteOrigin);
2469
- }
2470
-
2471
- //#endregion
2472
- //#region src/plugins/storage-indexes.ts
2473
- /**
2474
- * Generate a deterministic index name.
2475
- * Unique indexes use a `uidx_` prefix to avoid collisions with regular indexes on the same fields.
2476
- */
2477
- function generateIndexName(pluginId, collection, fields, options) {
2478
- return `${options?.unique ? "uidx" : "idx"}_plugin_${pluginId}_${collection}_${fields.join("_")}`.substring(0, 128);
2479
- }
2480
- /**
2481
- * Generate a Kysely sql expression for creating an expression index.
2482
- *
2483
- * Validates all inputs before interpolation. The collection uses the
2484
- * permissive manifest-key rules rather than SQL-identifier rules — it is
2485
- * stored as opaque text and only reaches SQL inside the generated index
2486
- * name — so kebab-case collections index like any other.
2487
- */
2488
- function generateCreateIndexSql(db, pluginId, collection, fields, options) {
2489
- validatePluginIdentifier(pluginId, "plugin ID");
2490
- validateStorageCollectionName(collection, "collection name");
2491
- for (const field of fields) validateJsonFieldName(field, "index field name");
2492
- const indexName = generateIndexName(pluginId, collection, fields, options);
2493
- const expressions = fields.map((field) => {
2494
- if (isPostgres(db)) return `(${jsonExtractExpr(db, "data", field)})`;
2495
- return jsonExtractExpr(db, "data", field);
2496
- }).join(", ");
2497
- const createKeyword = options?.unique ? "CREATE UNIQUE INDEX" : "CREATE INDEX";
2498
- return sql`${sql.raw(createKeyword)} IF NOT EXISTS ${sql.ref(indexName)}
2499
- ON _plugin_storage(plugin_id, collection, ${sql.raw(expressions)})
2500
- `;
2501
- }
2502
- /**
2503
- * Generate a Kysely sql expression for dropping an index.
2504
- *
2505
- * Uses sql.ref() for safe identifier quoting.
2506
- */
2507
- function generateDropIndexSql(indexName) {
2508
- return sql`DROP INDEX IF EXISTS ${sql.ref(indexName)}`;
2509
- }
2510
- /**
2511
- * Normalize index declarations to arrays of field arrays
2512
- */
2513
- function normalizeIndexes(indexes) {
2514
- return indexes.map((index) => Array.isArray(index) ? index : [index]);
2515
- }
2516
- /**
2517
- * Create all declared indexes for a plugin collection
2518
- */
2519
- async function createStorageIndexes(db, pluginId, collection, indexes, options) {
2520
- const normalized = normalizeIndexes(indexes);
2521
- const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2522
- const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2523
- const allEntries = [...normalized.filter((f) => !uniqueSet.has(f.join(","))).map((fields) => ({
2524
- fields,
2525
- unique: false
2526
- })), ...uniqueNormalized.map((fields) => ({
2527
- fields,
2528
- unique: true
2529
- }))];
2530
- const created = [];
2531
- const errors = [];
2532
- for (const entry of allEntries) {
2533
- const { fields } = entry;
2534
- const indexName = generateIndexName(pluginId, collection, fields, { unique: entry.unique });
2535
- try {
2536
- await generateCreateIndexSql(db, pluginId, collection, fields, { unique: entry.unique }).execute(db);
2537
- await db.insertInto("_plugin_indexes").values({
2538
- plugin_id: pluginId,
2539
- collection,
2540
- index_name: indexName,
2541
- fields: JSON.stringify(fields)
2542
- }).onConflict((oc) => oc.columns([
2543
- "plugin_id",
2544
- "collection",
2545
- "index_name"
2546
- ]).doUpdateSet({ fields: JSON.stringify(fields) })).execute();
2547
- created.push(indexName);
2548
- } catch (error) {
2549
- errors.push({
2550
- index: indexName,
2551
- error: error instanceof Error ? error.message : String(error)
2552
- });
2553
- }
2554
- }
2555
- return {
2556
- created,
2557
- errors
2558
- };
2559
- }
2560
- /**
2561
- * Remove indexes that are no longer declared
2562
- */
2563
- async function removeOrphanedIndexes(db, pluginId, collection, currentIndexes, options) {
2564
- const normalized = normalizeIndexes(currentIndexes);
2565
- const uniqueNormalized = options?.uniqueIndexes ? normalizeIndexes(options.uniqueIndexes) : [];
2566
- const uniqueSet = new Set(uniqueNormalized.map((f) => f.join(",")));
2567
- const currentIndexNames = /* @__PURE__ */ new Set();
2568
- for (const fields of normalized) if (!uniqueSet.has(fields.join(","))) currentIndexNames.add(generateIndexName(pluginId, collection, fields));
2569
- for (const fields of uniqueNormalized) currentIndexNames.add(generateIndexName(pluginId, collection, fields, { unique: true }));
2570
- const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name"]).where("plugin_id", "=", pluginId).where("collection", "=", collection).execute();
2571
- const removed = [];
2572
- const errors = [];
2573
- for (const { index_name } of existingIndexes) if (!currentIndexNames.has(index_name)) try {
2574
- await generateDropIndexSql(index_name).execute(db);
2575
- await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).where("collection", "=", collection).where("index_name", "=", index_name).execute();
2576
- removed.push(index_name);
2577
- } catch (error) {
2578
- errors.push({
2579
- index: index_name,
2580
- error: error instanceof Error ? error.message : String(error)
2581
- });
2582
- }
2583
- return {
2584
- removed,
2585
- errors
2586
- };
2587
- }
2588
- /**
2589
- * Sync indexes for a plugin collection (create new, remove old)
2590
- */
2591
- async function syncStorageIndexes(db, pluginId, collection, indexes, options) {
2592
- const [createResult, removeResult] = await Promise.all([createStorageIndexes(db, pluginId, collection, indexes, options), removeOrphanedIndexes(db, pluginId, collection, indexes, options)]);
2593
- return {
2594
- created: createResult.created,
2595
- removed: removeResult.removed,
2596
- errors: [...createResult.errors, ...removeResult.errors]
2597
- };
2598
- }
2599
- /**
2600
- * Materialize the storage indexes a set of plugins declare in their
2601
- * manifests. Failures are logged per collection and never thrown — a missing
2602
- * index affects query performance, not correctness, so it must not fail an
2603
- * install or a scheduler tick.
2604
- */
2605
- async function syncDeclaredStorageIndexes(db, plugins) {
2606
- for (const plugin of plugins) for (const [collection, config] of Object.entries(plugin.storage ?? {})) try {
2607
- const result = await syncStorageIndexes(db, plugin.id, collection, config.indexes, { uniqueIndexes: config.uniqueIndexes });
2608
- for (const failure of result.errors) console.error(`[plugins] Failed to sync storage index ${failure.index} for ${plugin.id}/${collection}: ${failure.error}`);
2609
- } catch (error) {
2610
- console.error(`[plugins] Failed to sync storage indexes for ${plugin.id}/${collection}:`, error);
2611
- }
2612
- }
2613
- /**
2614
- * Remove all indexes for a plugin
2615
- */
2616
- async function removeAllPluginIndexes(db, pluginId) {
2617
- const existingIndexes = await db.selectFrom("_plugin_indexes").select(["index_name", "collection"]).where("plugin_id", "=", pluginId).execute();
2618
- const removed = [];
2619
- const errors = [];
2620
- for (const { index_name } of existingIndexes) try {
2621
- await generateDropIndexSql(index_name).execute(db);
2622
- removed.push(index_name);
2623
- } catch (error) {
2624
- errors.push({
2625
- index: index_name,
2626
- error: error instanceof Error ? error.message : String(error)
2627
- });
2628
- }
2629
- await db.deleteFrom("_plugin_indexes").where("plugin_id", "=", pluginId).execute();
2630
- return {
2631
- removed,
2632
- errors
2633
- };
2634
- }
2635
-
2636
- //#endregion
2637
- //#region src/api/handlers/marketplace.ts
2638
- /** Semver-like pattern: digits, dots, hyphens, plus signs (e.g. 1.0.0, 1.0.0-beta.1) */
2639
- const VERSION_PATTERN = /^[a-z0-9][a-z0-9._+-]*$/i;
2640
- function validateVersion(version) {
2641
- if (version.includes("..")) throw new Error("Invalid version format");
2642
- if (!VERSION_PATTERN.test(version)) throw new Error("Invalid version format");
2643
- }
2644
- function getClient(marketplaceUrl, siteOrigin) {
2645
- if (!marketplaceUrl) return null;
2646
- return createMarketplaceClient(marketplaceUrl, siteOrigin);
2647
- }
2648
- function diffCapabilities(oldCaps, newCaps) {
2649
- const oldNorm = normalizeCapabilities(oldCaps);
2650
- const newNorm = normalizeCapabilities(newCaps);
2651
- const oldSet = new Set(oldNorm);
2652
- const newSet = new Set(newNorm);
2653
- return {
2654
- added: newNorm.filter((c) => !oldSet.has(c)),
2655
- removed: oldNorm.filter((c) => !newSet.has(c))
2656
- };
2657
- }
2658
- /**
2659
- * Diff route visibility between two manifests.
2660
- * Returns routes that changed from private to public (newly exposed).
2661
- */
2662
- function diffRouteVisibility(oldManifest, newManifest) {
2663
- const oldPublicRoutes = /* @__PURE__ */ new Set();
2664
- if (oldManifest) for (const entry of oldManifest.routes) {
2665
- const normalized = normalizeManifestRoute(entry);
2666
- if (normalized.public === true) oldPublicRoutes.add(normalized.name);
2667
- }
2668
- const newlyPublic = [];
2669
- for (const entry of newManifest.routes) {
2670
- const normalized = normalizeManifestRoute(entry);
2671
- if (normalized.public === true && !oldPublicRoutes.has(normalized.name)) newlyPublic.push(normalized.name);
2672
- }
2673
- return { newlyPublic };
2674
- }
2675
- async function resolveVersionMetadata(client, pluginId, pluginDetail, version) {
2676
- if (pluginDetail.latestVersion?.version === version) return {
2677
- version: pluginDetail.latestVersion.version,
2678
- minEmDashVersion: pluginDetail.latestVersion.minEmDashVersion,
2679
- bundleSize: pluginDetail.latestVersion.bundleSize,
2680
- checksum: pluginDetail.latestVersion.checksum,
2681
- changelog: pluginDetail.latestVersion.changelog,
2682
- capabilities: pluginDetail.latestVersion.capabilities,
2683
- status: pluginDetail.latestVersion.status,
2684
- auditVerdict: pluginDetail.latestVersion.audit?.verdict ?? null,
2685
- imageAuditVerdict: pluginDetail.latestVersion.imageAudit?.verdict ?? null,
2686
- publishedAt: pluginDetail.latestVersion.publishedAt
2687
- };
2688
- return (await client.getVersions(pluginId)).find((v) => v.version === version) ?? null;
2689
- }
2690
- function validateBundleIdentity(bundle, pluginId, version) {
2691
- if (bundle.manifest.id !== pluginId) return {
2692
- success: false,
2693
- error: {
2694
- code: "MANIFEST_MISMATCH",
2695
- message: `Bundle manifest ID (${bundle.manifest.id}) does not match requested plugin (${pluginId})`
2696
- }
2697
- };
2698
- if (bundle.manifest.version !== version) return {
2699
- success: false,
2700
- error: {
2701
- code: "MANIFEST_VERSION_MISMATCH",
2702
- message: `Bundle manifest version (${bundle.manifest.version}) does not match requested version (${version})`
2703
- }
2704
- };
2705
- return null;
2706
- }
2707
- function bundlePrefix(source, pluginId, version) {
2708
- return `${source}/${pluginId}/${version}`;
2709
- }
2710
- async function storeBundleInR2(storage, pluginId, version, bundle, source = "marketplace") {
2711
- validatePluginIdentifier(pluginId, "plugin ID");
2712
- validateVersion(version);
2713
- const prefix = bundlePrefix(source, pluginId, version);
2714
- await storage.upload({
2715
- key: `${prefix}/manifest.json`,
2716
- body: new TextEncoder().encode(JSON.stringify(bundle.manifest)),
2717
- contentType: "application/json"
2718
- });
2719
- await storage.upload({
2720
- key: `${prefix}/backend.js`,
2721
- body: new TextEncoder().encode(bundle.backendCode),
2722
- contentType: "application/javascript"
2723
- });
2724
- if (bundle.adminCode) await storage.upload({
2725
- key: `${prefix}/admin.js`,
2726
- body: new TextEncoder().encode(bundle.adminCode),
2727
- contentType: "application/javascript"
2728
- });
2729
- }
2730
- /** Read a ReadableStream to string */
2731
- async function streamToText(stream) {
2732
- return new Response(stream).text();
2733
- }
2734
- /**
2735
- * Load a plugin bundle from site-local R2 storage.
2736
- *
2737
- * `source` selects the R2 key prefix: marketplace plugins are stored
2738
- * under `marketplace/<id>/<version>/`, registry plugins under
2739
- * `registry/<id>/<version>/`. Defaults to `"marketplace"` for
2740
- * backwards compatibility with pre-registry call sites.
2741
- */
2742
- async function loadBundleFromR2(storage, pluginId, version, source = "marketplace") {
2743
- validatePluginIdentifier(pluginId, "plugin ID");
2744
- validateVersion(version);
2745
- const prefix = bundlePrefix(source, pluginId, version);
2746
- try {
2747
- const manifestResult = await storage.download(`${prefix}/manifest.json`);
2748
- const backendResult = await storage.download(`${prefix}/backend.js`);
2749
- const manifestText = await streamToText(manifestResult.body);
2750
- const backendCode = await streamToText(backendResult.body);
2751
- const parsed = JSON.parse(manifestText);
2752
- const result = pluginManifestSchema.safeParse(parsed);
2753
- if (!result.success) return null;
2754
- const manifest = reconcileManifestAccess(result.data);
2755
- let adminCode;
2756
- try {
2757
- adminCode = await streamToText((await storage.download(`${prefix}/admin.js`)).body);
2758
- } catch {}
2759
- return {
2760
- manifest,
2761
- backendCode,
2762
- adminCode
2763
- };
2764
- } catch {
2765
- return null;
2766
- }
2767
- }
2768
- /** Delete a plugin bundle from site-local R2 storage */
2769
- async function deleteBundleFromR2(storage, pluginId, version, source = "marketplace") {
2770
- validatePluginIdentifier(pluginId, "plugin ID");
2771
- validateVersion(version);
2772
- const prefix = bundlePrefix(source, pluginId, version);
2773
- for (const file of [
2774
- "manifest.json",
2775
- "backend.js",
2776
- "admin.js"
2777
- ]) try {
2778
- await storage.delete(`${prefix}/${file}`);
2779
- } catch {}
2780
- }
2781
- async function handleMarketplaceInstall(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
2782
- const client = getClient(marketplaceUrl, opts?.siteOrigin);
2783
- if (!client) return {
2784
- success: false,
2785
- error: {
2786
- code: "MARKETPLACE_NOT_CONFIGURED",
2787
- message: "Marketplace is not configured"
2788
- }
2789
- };
2790
- if (!storage) return {
2791
- success: false,
2792
- error: {
2793
- code: "STORAGE_NOT_CONFIGURED",
2794
- message: "Storage is required for marketplace plugin installation"
2795
- }
2796
- };
2797
- if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
2798
- success: false,
2799
- error: {
2800
- code: "SANDBOX_NOT_AVAILABLE",
2801
- message: "Sandbox runner is required for marketplace plugins"
2802
- }
2803
- };
2804
- try {
2805
- const stateRepo = new PluginStateRepository(db);
2806
- const existing = await stateRepo.get(pluginId);
2807
- if (existing && existing.source === "marketplace") return {
2808
- success: false,
2809
- error: {
2810
- code: "ALREADY_INSTALLED",
2811
- message: `Plugin ${pluginId} is already installed`
2812
- }
2813
- };
2814
- if (opts?.configuredPluginIds?.has(pluginId)) return {
2815
- success: false,
2816
- error: {
2817
- code: "PLUGIN_ID_CONFLICT",
2818
- message: `Cannot install marketplace plugin "${pluginId}" — a configured plugin with the same ID already exists`
2819
- }
2820
- };
2821
- const pluginDetail = await client.getPlugin(pluginId);
2822
- const version = opts?.version ?? pluginDetail.latestVersion?.version;
2823
- if (!version) return {
2824
- success: false,
2825
- error: {
2826
- code: "NO_VERSION",
2827
- message: `No published versions found for plugin ${pluginId}`
2828
- }
2829
- };
2830
- const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, version);
2831
- if (!versionMetadata) return {
2832
- success: false,
2833
- error: {
2834
- code: "NO_VERSION",
2835
- message: `Version ${version} was not found for plugin ${pluginId}`
2836
- }
2837
- };
2838
- if (versionMetadata.auditVerdict === "fail" || versionMetadata.auditVerdict === "warn") return {
2839
- success: false,
2840
- error: {
2841
- code: "AUDIT_FAILED",
2842
- message: versionMetadata.auditVerdict === "fail" ? "Plugin failed security audit and cannot be installed" : "Plugin audit was inconclusive and cannot be installed until reviewed"
2843
- }
2844
- };
2845
- const bundle = await client.downloadBundle(pluginId, version);
2846
- if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
2847
- success: false,
2848
- error: {
2849
- code: "CHECKSUM_MISMATCH",
2850
- message: "Bundle checksum does not match marketplace record. Download may be corrupted."
2851
- }
2852
- };
2853
- const bundleIdentityError = validateBundleIdentity(bundle, pluginId, version);
2854
- if (bundleIdentityError) return bundleIdentityError;
2855
- if ((bundle.manifest.mcp?.tools.length ?? 0) > 0 && !opts?.confirmMcpTools) return {
2856
- success: false,
2857
- error: {
2858
- code: "MCP_TOOL_CONSENT_REQUIRED",
2859
- message: "Plugin MCP tools require explicit consent",
2860
- details: { mcpTools: bundle.manifest.mcp?.tools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool) }
2861
- }
2862
- };
2863
- await storeBundleInR2(storage, pluginId, version, bundle);
2864
- await stateRepo.upsert(pluginId, version, "active", {
2865
- source: "marketplace",
2866
- marketplaceVersion: version,
2867
- displayName: pluginDetail.name,
2868
- description: pluginDetail.description ?? void 0
2869
- });
2870
- await syncDeclaredStorageIndexes(db, [bundle.manifest]);
2871
- client.reportInstall(pluginId, version).catch(() => {});
2872
- return {
2873
- success: true,
2874
- data: {
2875
- pluginId,
2876
- version,
2877
- capabilities: bundle.manifest.capabilities
2878
- }
2879
- };
2880
- } catch (err) {
2881
- if (err instanceof MarketplaceUnavailableError) return {
2882
- success: false,
2883
- error: {
2884
- code: "MARKETPLACE_UNAVAILABLE",
2885
- message: "Plugin marketplace is currently unavailable"
2886
- }
2887
- };
2888
- if (err instanceof MarketplaceError) return {
2889
- success: false,
2890
- error: {
2891
- code: err.code ?? "MARKETPLACE_ERROR",
2892
- message: err.message
2893
- }
2894
- };
2895
- if (err instanceof EmDashStorageError) return {
2896
- success: false,
2897
- error: {
2898
- code: err.code ?? "STORAGE_ERROR",
2899
- message: "Storage error while installing plugin"
2900
- }
2901
- };
2902
- if (err && typeof err === "object" && "code" in err) {
2903
- const code = err.code;
2904
- if (typeof code === "string" && code.trim()) return {
2905
- success: false,
2906
- error: {
2907
- code,
2908
- message: "Failed to install plugin from marketplace"
2909
- }
2910
- };
2911
- }
2912
- console.error("Failed to install marketplace plugin:", err);
2913
- return {
2914
- success: false,
2915
- error: {
2916
- code: "INSTALL_FAILED",
2917
- message: "Failed to install plugin from marketplace"
2918
- }
2919
- };
2920
- }
2921
- }
2922
- async function handleMarketplaceUpdate(db, storage, sandboxRunner, marketplaceUrl, pluginId, opts) {
2923
- const client = getClient(marketplaceUrl);
2924
- if (!client) return {
2925
- success: false,
2926
- error: {
2927
- code: "MARKETPLACE_NOT_CONFIGURED",
2928
- message: "Marketplace is not configured"
2929
- }
2930
- };
2931
- if (!storage) return {
2932
- success: false,
2933
- error: {
2934
- code: "STORAGE_NOT_CONFIGURED",
2935
- message: "Storage is required"
2936
- }
2937
- };
2938
- if (!opts?.sandboxBypassed && (!sandboxRunner || !sandboxRunner.isAvailable())) return {
2939
- success: false,
2940
- error: {
2941
- code: "SANDBOX_NOT_AVAILABLE",
2942
- message: "Sandbox runner is required"
2943
- }
2944
- };
2945
- try {
2946
- const stateRepo = new PluginStateRepository(db);
2947
- const existing = await stateRepo.get(pluginId);
2948
- if (!existing || existing.source !== "marketplace") return {
2949
- success: false,
2950
- error: {
2951
- code: "NOT_FOUND",
2952
- message: `No marketplace plugin found: ${pluginId}`
2953
- }
2954
- };
2955
- const oldVersion = existing.marketplaceVersion ?? existing.version;
2956
- const pluginDetail = await client.getPlugin(pluginId);
2957
- const newVersion = opts?.version ?? pluginDetail.latestVersion?.version;
2958
- if (!newVersion) return {
2959
- success: false,
2960
- error: {
2961
- code: "NO_VERSION",
2962
- message: "No newer version available"
2963
- }
2964
- };
2965
- if (newVersion === oldVersion) return {
2966
- success: false,
2967
- error: {
2968
- code: "ALREADY_UP_TO_DATE",
2969
- message: "Plugin is already up to date"
2970
- }
2971
- };
2972
- const versionMetadata = await resolveVersionMetadata(client, pluginId, pluginDetail, newVersion);
2973
- if (!versionMetadata) return {
2974
- success: false,
2975
- error: {
2976
- code: "NO_VERSION",
2977
- message: `Version ${newVersion} was not found for plugin ${pluginId}`
2978
- }
2979
- };
2980
- const bundle = await client.downloadBundle(pluginId, newVersion);
2981
- if (versionMetadata.checksum && bundle.checksum !== versionMetadata.checksum) return {
2982
- success: false,
2983
- error: {
2984
- code: "CHECKSUM_MISMATCH",
2985
- message: "Bundle checksum does not match marketplace record. Download may be corrupted."
2986
- }
2987
- };
2988
- const bundleIdentityError = validateBundleIdentity(bundle, pluginId, newVersion);
2989
- if (bundleIdentityError) return bundleIdentityError;
2990
- const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion);
2991
- const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
2992
- if (capabilityChanges.added.length > 0 && !opts?.confirmCapabilityChanges) return {
2993
- success: false,
2994
- error: {
2995
- code: "CAPABILITY_ESCALATION",
2996
- message: "Plugin update requires new capabilities",
2997
- details: { capabilityChanges }
2998
- }
2999
- };
3000
- const routeVisibilityChanges = diffRouteVisibility(oldBundle?.manifest, bundle.manifest);
3001
- const hasNewPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
3002
- if (hasNewPublicRoutes && !opts?.confirmRouteVisibilityChanges) return {
3003
- success: false,
3004
- error: {
3005
- code: "ROUTE_VISIBILITY_ESCALATION",
3006
- message: "Plugin update exposes new public (unauthenticated) routes",
3007
- details: {
3008
- routeVisibilityChanges,
3009
- capabilityChanges
3010
- }
3011
- }
3012
- };
3013
- const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3014
- const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
3015
- if (JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools) && !opts?.confirmMcpTools) return {
3016
- success: false,
3017
- error: {
3018
- code: "MCP_TOOL_CONSENT_REQUIRED",
3019
- message: "Plugin update changes its MCP tools",
3020
- details: { mcpTools: newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool) }
3021
- }
3022
- };
3023
- await storeBundleInR2(storage, pluginId, newVersion, bundle);
3024
- await stateRepo.upsert(pluginId, newVersion, "active", {
3025
- source: "marketplace",
3026
- marketplaceVersion: newVersion,
3027
- displayName: pluginDetail.name,
3028
- description: pluginDetail.description ?? void 0,
3029
- mcpToolsEnabled: false,
3030
- mcpToolsConsent: null
3031
- });
3032
- await syncDeclaredStorageIndexes(db, [bundle.manifest]);
3033
- deleteBundleFromR2(storage, pluginId, oldVersion).catch(() => {});
3034
- return {
3035
- success: true,
3036
- data: {
3037
- pluginId,
3038
- oldVersion,
3039
- newVersion,
3040
- capabilityChanges,
3041
- routeVisibilityChanges: hasNewPublicRoutes ? routeVisibilityChanges : void 0
3042
- }
3043
- };
3044
- } catch (err) {
3045
- if (err instanceof MarketplaceUnavailableError) return {
3046
- success: false,
3047
- error: {
3048
- code: "MARKETPLACE_UNAVAILABLE",
3049
- message: "Marketplace is unavailable"
3050
- }
3051
- };
3052
- if (err instanceof MarketplaceError) return {
3053
- success: false,
3054
- error: {
3055
- code: err.code ?? "MARKETPLACE_ERROR",
3056
- message: err.message
3057
- }
3058
- };
3059
- console.error("Failed to update marketplace plugin:", err);
3060
- return {
3061
- success: false,
3062
- error: {
3063
- code: "UPDATE_FAILED",
3064
- message: "Failed to update plugin"
3065
- }
3066
- };
3067
- }
3068
- }
3069
- async function handleMarketplaceUninstall(db, storage, pluginId, opts) {
3070
- try {
3071
- const stateRepo = new PluginStateRepository(db);
3072
- const existing = await stateRepo.get(pluginId);
3073
- if (!existing || existing.source !== "marketplace") return {
3074
- success: false,
3075
- error: {
3076
- code: "NOT_FOUND",
3077
- message: `No marketplace plugin found: ${pluginId}`
3078
- }
3079
- };
3080
- const version = existing.marketplaceVersion ?? existing.version;
3081
- if (storage) await deleteBundleFromR2(storage, pluginId, version);
3082
- let dataDeleted = false;
3083
- if (opts?.deleteData) try {
3084
- await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
3085
- dataDeleted = true;
3086
- } catch {}
3087
- try {
3088
- await removeAllPluginIndexes(db, pluginId);
3089
- } catch {}
3090
- await stateRepo.delete(pluginId);
3091
- return {
3092
- success: true,
3093
- data: {
3094
- pluginId,
3095
- dataDeleted
3096
- }
3097
- };
3098
- } catch (err) {
3099
- console.error("Failed to uninstall marketplace plugin:", err);
3100
- return {
3101
- success: false,
3102
- error: {
3103
- code: "UNINSTALL_FAILED",
3104
- message: "Failed to uninstall plugin"
3105
- }
3106
- };
3107
- }
3108
- }
3109
- async function handleMarketplaceUpdateCheck(db, marketplaceUrl) {
3110
- const client = getClient(marketplaceUrl);
3111
- if (!client) return {
3112
- success: false,
3113
- error: {
3114
- code: "MARKETPLACE_NOT_CONFIGURED",
3115
- message: "Marketplace is not configured"
3116
- }
3117
- };
3118
- try {
3119
- const marketplacePlugins = await new PluginStateRepository(db).getMarketplacePlugins();
3120
- const items = [];
3121
- for (const plugin of marketplacePlugins) try {
3122
- const detail = await client.getPlugin(plugin.pluginId);
3123
- const latest = detail.latestVersion?.version;
3124
- const installed = plugin.marketplaceVersion ?? plugin.version;
3125
- if (!latest) continue;
3126
- const hasUpdate = latest !== installed;
3127
- let capabilityChanges;
3128
- let hasCapabilityChanges = false;
3129
- if (hasUpdate && detail.latestVersion) {
3130
- capabilityChanges = diffCapabilities(detail.capabilities ?? [], detail.latestVersion.capabilities ?? []);
3131
- hasCapabilityChanges = capabilityChanges.added.length > 0 || capabilityChanges.removed.length > 0;
3132
- }
3133
- items.push({
3134
- pluginId: plugin.pluginId,
3135
- installed,
3136
- latest: latest ?? installed,
3137
- hasUpdate,
3138
- hasCapabilityChanges,
3139
- capabilityChanges: hasCapabilityChanges ? capabilityChanges : void 0,
3140
- hasRouteVisibilityChanges: false
3141
- });
3142
- } catch (err) {
3143
- console.warn(`Failed to check updates for ${plugin.pluginId}:`, err);
3144
- }
3145
- return {
3146
- success: true,
3147
- data: { items }
3148
- };
3149
- } catch (err) {
3150
- if (err instanceof MarketplaceUnavailableError) return {
3151
- success: false,
3152
- error: {
3153
- code: "MARKETPLACE_UNAVAILABLE",
3154
- message: "Marketplace is unavailable"
3155
- }
3156
- };
3157
- console.error("Failed to check marketplace updates:", err);
3158
- return {
3159
- success: false,
3160
- error: {
3161
- code: "UPDATE_CHECK_FAILED",
3162
- message: "Failed to check for updates"
3163
- }
3164
- };
3165
- }
3166
- }
3167
- async function handleMarketplaceSearch(marketplaceUrl, query, opts) {
3168
- const client = getClient(marketplaceUrl);
3169
- if (!client) return {
3170
- success: false,
3171
- error: {
3172
- code: "MARKETPLACE_NOT_CONFIGURED",
3173
- message: "Marketplace is not configured"
3174
- }
3175
- };
3176
- try {
3177
- return {
3178
- success: true,
3179
- data: await client.search(query, opts)
3180
- };
3181
- } catch (err) {
3182
- if (err instanceof MarketplaceUnavailableError) return {
3183
- success: false,
3184
- error: {
3185
- code: "MARKETPLACE_UNAVAILABLE",
3186
- message: "Marketplace is unavailable"
3187
- }
3188
- };
3189
- console.error("Failed to search marketplace:", err);
3190
- return {
3191
- success: false,
3192
- error: {
3193
- code: "SEARCH_FAILED",
3194
- message: "Failed to search marketplace"
3195
- }
3196
- };
3197
- }
3198
- }
3199
- async function handleMarketplaceGetPlugin(marketplaceUrl, pluginId) {
3200
- const client = getClient(marketplaceUrl);
3201
- if (!client) return {
3202
- success: false,
3203
- error: {
3204
- code: "MARKETPLACE_NOT_CONFIGURED",
3205
- message: "Marketplace is not configured"
3206
- }
3207
- };
3208
- try {
3209
- return {
3210
- success: true,
3211
- data: await client.getPlugin(pluginId)
3212
- };
3213
- } catch (err) {
3214
- if (err instanceof MarketplaceError && err.status === 404) return {
3215
- success: false,
3216
- error: {
3217
- code: "NOT_FOUND",
3218
- message: `Plugin not found: ${pluginId}`
3219
- }
3220
- };
3221
- if (err instanceof MarketplaceUnavailableError) return {
3222
- success: false,
3223
- error: {
3224
- code: "MARKETPLACE_UNAVAILABLE",
3225
- message: "Marketplace is unavailable"
3226
- }
3227
- };
3228
- console.error("Failed to get marketplace plugin:", err);
3229
- return {
3230
- success: false,
3231
- error: {
3232
- code: "GET_PLUGIN_FAILED",
3233
- message: "Failed to get plugin details"
3234
- }
3235
- };
3236
- }
3237
- }
3238
- async function handleThemeSearch(marketplaceUrl, query, opts) {
3239
- const client = getClient(marketplaceUrl);
3240
- if (!client) return {
3241
- success: false,
3242
- error: {
3243
- code: "MARKETPLACE_NOT_CONFIGURED",
3244
- message: "Marketplace is not configured"
3245
- }
3246
- };
3247
- try {
3248
- return {
3249
- success: true,
3250
- data: await client.searchThemes(query, opts)
3251
- };
3252
- } catch (err) {
3253
- if (err instanceof MarketplaceUnavailableError) return {
3254
- success: false,
3255
- error: {
3256
- code: "MARKETPLACE_UNAVAILABLE",
3257
- message: "Marketplace is unavailable"
3258
- }
3259
- };
3260
- console.error("Failed to search themes:", err);
3261
- return {
3262
- success: false,
3263
- error: {
3264
- code: "THEME_SEARCH_FAILED",
3265
- message: "Failed to search themes"
3266
- }
3267
- };
3268
- }
3269
- }
3270
- async function handleThemeGetDetail(marketplaceUrl, themeId) {
3271
- const client = getClient(marketplaceUrl);
3272
- if (!client) return {
3273
- success: false,
3274
- error: {
3275
- code: "MARKETPLACE_NOT_CONFIGURED",
3276
- message: "Marketplace is not configured"
3277
- }
3278
- };
3279
- try {
3280
- return {
3281
- success: true,
3282
- data: await client.getTheme(themeId)
3283
- };
3284
- } catch (err) {
3285
- if (err instanceof MarketplaceError && err.status === 404) return {
3286
- success: false,
3287
- error: {
3288
- code: "NOT_FOUND",
3289
- message: `Theme not found: ${themeId}`
3290
- }
3291
- };
3292
- if (err instanceof MarketplaceUnavailableError) return {
3293
- success: false,
3294
- error: {
3295
- code: "MARKETPLACE_UNAVAILABLE",
3296
- message: "Marketplace is unavailable"
3297
- }
3298
- };
3299
- console.error("Failed to get marketplace theme:", err);
3300
- return {
3301
- success: false,
3302
- error: {
3303
- code: "GET_THEME_FAILED",
3304
- message: "Failed to get theme details"
3305
- }
3306
- };
3307
- }
3308
- }
3309
-
3310
- //#endregion
3311
- //#region src/registry/config.ts
3312
- /**
3313
- * Canonicalize a capabilities list for set-style comparison.
3314
- *
3315
- * Capabilities (the legacy declared-access shape used by the current
3316
- * sandbox enforcer) are conceptually a *set*: order, duplicates, and
3317
- * non-string entries don't carry meaning. The install handler's drift
3318
- * check compares the admin's acknowledged set against the bundle
3319
- * manifest's set; both sides pass through this canonicalizer first so
3320
- * an aggregator-supplied array with unstable order or junk entries
3321
- * can't cause a spurious drift rejection.
3322
- *
3323
- * Filters non-strings, deduplicates, and sorts lexically. Named to
3324
- * avoid shadowing `@emdash-cms/plugin-types`'s existing
3325
- * `normalizeCapabilities` (which dedupes + applies the deprecated →
3326
- * current alias map but does not filter junk or sort).
3327
- *
3328
- * Exported so the same shape is produced by the browser before sending
3329
- * the `acknowledgedDeclaredAccess` payload and by the server before
3330
- * comparing against the bundle.
3331
- */
3332
- function canonicalCapabilitiesForDriftCheck(value) {
3333
- if (!Array.isArray(value)) return [];
3334
- const seen = /* @__PURE__ */ new Set();
3335
- for (const entry of value) if (typeof entry === "string" && entry.length > 0) seen.add(entry);
3336
- return [...seen].toSorted();
3337
- }
3338
- /**
3339
- * Returns whether a `(publisher_did, slug)` pair is on the
3340
- * minimum-release-age exemption list. Exported so the same matcher is
3341
- * used by the browser policy filter and the server-side install
3342
- * enforcement.
3343
- *
3344
- * Matching is DID-only. Handles are aggregator-supplied envelope data
3345
- * (mutable, controlled by an attacker who compromises the aggregator)
3346
- * and cannot be used as a trust input -- a compromised aggregator
3347
- * could claim any handle for any package and bypass the holdback. DIDs
3348
- * are part of the AT URI of the package record and are independently
3349
- * resolvable, so even a compromised aggregator can't lie about the
3350
- * publisher DID without also breaking checksum verification downstream.
3351
- *
3352
- * Entries from config are already lowercased at manifest-build time.
3353
- * Runtime values are lowercased here at compare time.
3354
- */
3355
- function releaseExemptFromMinimumAge(exclude, publisherDid, slug) {
3356
- if (!exclude || exclude.length === 0) return false;
3357
- const didLower = publisherDid.toLowerCase();
3358
- const fullDid = `${didLower}/${slug.toLowerCase()}`;
3359
- for (const entry of exclude) {
3360
- if (entry === didLower) return true;
3361
- if (entry === fullDid) return true;
3362
- }
3363
- return false;
3364
- }
3365
- const DURATION_PATTERN = /^(\d+)(s|m|h|d|w)$/;
3366
- /** Trailing slashes on the aggregator URL, stripped during normalization. */
3367
- const TRAILING_SLASHES = /\/+$/;
3368
- /** Trailing dot on a hostname, stripped before URL host comparisons. */
3369
- const TRAILING_DOT$1 = /\.$/;
3370
- /**
3371
- * Parse a duration string or raw second count into a non-negative
3372
- * integer count of seconds. Throws on unrecognised input so config
3373
- * mistakes fail at startup rather than silently disabling the policy.
3374
- */
3375
- function parseDurationSeconds(duration) {
3376
- if (typeof duration === "number") {
3377
- if (!Number.isFinite(duration) || duration < 0) throw new Error(`Invalid duration: ${duration} (must be a non-negative finite number)`);
3378
- return Math.floor(duration);
3379
- }
3380
- const match = duration.match(DURATION_PATTERN);
3381
- if (!match) throw new Error(`Invalid duration format: "${duration}". Use a duration string like "48h", "7d", "30m", or a number of seconds.`);
3382
- const value = parseInt(match[1], 10);
3383
- const unit = match[2];
3384
- switch (unit) {
3385
- case "s": return value;
3386
- case "m": return value * 60;
3387
- case "h": return value * 60 * 60;
3388
- case "d": return value * 24 * 60 * 60;
3389
- case "w": return value * 7 * 24 * 60 * 60;
3390
- default: throw new Error(`Unknown duration unit: ${unit}`);
3391
- }
3392
- }
3393
- /**
3394
- * Validate that `aggregatorUrl` is a safe outbound target for the
3395
- * registry's XRPC calls. Same posture as artifact downloads: HTTPS
3396
- * required in production; `http://localhost` allowed only in dev.
3397
- *
3398
- * The aggregator's responses are the trust source for release records,
3399
- * checksums, labels, mirrors, and `indexedAt` (until full MST
3400
- * verification lands). Allowing plain HTTP here would let a network
3401
- * attacker swap a release record and point the artifact URL at their
3402
- * own HTTPS bundle, defeating the checksum trust chain because the
3403
- * attacker controls the unsigned transport that supplied the checksum.
3404
- */
3405
- function validateAggregatorUrl(aggregatorUrl) {
3406
- let parsed;
3407
- try {
3408
- parsed = new URL(aggregatorUrl);
3409
- } catch {
3410
- throw new Error(`registry.aggregatorUrl is not a valid URL: ${aggregatorUrl}`);
3411
- }
3412
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error(`registry.aggregatorUrl must use http or https: ${aggregatorUrl}`);
3413
- if (parsed.username || parsed.password) throw new Error("registry.aggregatorUrl must not contain embedded credentials (user:pass@)");
3414
- const rawHostname = parsed.hostname.toLowerCase().replace(TRAILING_DOT$1, "");
3415
- const hostname = rawHostname.startsWith("[") && rawHostname.endsWith("]") ? rawHostname.slice(1, -1) : rawHostname;
3416
- const isLocalhost = hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "::1" || hostname.startsWith("::ffff:127.") || hostname.startsWith("::ffff:7f00:");
3417
- if (!import.meta.env.DEV) {
3418
- if (parsed.protocol === "http:") throw new Error(`registry.aggregatorUrl must use https in production: ${aggregatorUrl}`);
3419
- if (isLocalhost) throw new Error(`registry.aggregatorUrl points at localhost; allowed only in dev: ${aggregatorUrl}`);
3420
- } else if (parsed.protocol === "http:" && !isLocalhost) throw new Error(`registry.aggregatorUrl must use https (http allowed only for localhost in dev): ${aggregatorUrl}`);
3421
- return parsed;
3422
- }
3423
- /**
3424
- * Expand the `RegistryConfigInput` shorthand into the full
3425
- * `RegistryConfig` object shape.
3426
- *
3427
- * Users can pass a bare aggregator URL string for the common case
3428
- * (`experimental.registry: "https://registry.emdashcms.com"`); the
3429
- * normalizer handles either form transparently.
3430
- *
3431
- * Returns `undefined` for `undefined` input so callers can chain with
3432
- * optional chaining.
3433
- */
3434
- function coerceRegistryConfig(input) {
3435
- if (input === void 0) return void 0;
3436
- if (typeof input === "string") return { aggregatorUrl: input };
3437
- return input;
3438
- }
3439
- /**
3440
- * Normalize the user-supplied `RegistryConfigInput` into the shape that
3441
- * ships to the admin browser via the manifest endpoint.
3442
- *
3443
- * Accepts either the shorthand string form
3444
- * (`"https://registry.emdashcms.com"`) or the full `RegistryConfig`
3445
- * object. Returns `null` when `input` is undefined so callers can
3446
- * spread the result directly into the manifest object.
3447
- *
3448
- * Throws if the aggregator URL is malformed, points at a forbidden host,
3449
- * or `policy.minimumReleaseAge` is unparseable. These surface at
3450
- * runtime startup as 500s from the manifest endpoint -- intended,
3451
- * because the alternative is silently disabling the registry on
3452
- * misconfigured sites.
3453
- *
3454
- * TODO: switch to a Zod schema for richer per-field error messages and
3455
- * to surface misconfigurations to the admin UI as a banner instead of
3456
- * a manifest 500.
3457
- */
3458
- function normalizeRegistryConfig(input) {
3459
- const config = coerceRegistryConfig(input);
3460
- if (!config) return null;
3461
- const aggregatorUrl = config.aggregatorUrl?.trim();
3462
- if (!aggregatorUrl) throw new Error("registry.aggregatorUrl is required when registry is configured");
3463
- validateAggregatorUrl(aggregatorUrl);
3464
- const out = { aggregatorUrl: aggregatorUrl.replace(TRAILING_SLASHES, "") };
3465
- if (config.acceptLabelers) out.acceptLabelers = config.acceptLabelers;
3466
- const policy = {};
3467
- let hasPolicy = false;
3468
- if (config.policy?.minimumReleaseAge !== void 0) {
3469
- policy.minimumReleaseAgeSeconds = parseDurationSeconds(config.policy.minimumReleaseAge);
3470
- hasPolicy = true;
3471
- }
3472
- if (config.policy?.minimumReleaseAgeExclude !== void 0) {
3473
- const list = config.policy.minimumReleaseAgeExclude.map((entry) => {
3474
- const trimmed = entry.trim();
3475
- if (!trimmed) throw new Error("registry.policy.minimumReleaseAgeExclude entries cannot be empty");
3476
- return trimmed.toLowerCase();
3477
- });
3478
- if (list.length > 0) {
3479
- policy.minimumReleaseAgeExclude = list;
3480
- hasPolicy = true;
3481
- }
3482
- }
3483
- if (hasPolicy) out.policy = policy;
3484
- return out;
3485
- }
3486
-
3487
- //#endregion
3488
- //#region src/registry/plugin-id.ts
3489
- /**
3490
- * Plugin identifier helpers for the experimental decentralized plugin
3491
- * registry.
3492
- *
3493
- * Registry plugins are addressed by `(publisher_did, slug)`, but the
3494
- * EmDash runtime threads a single `pluginId: string` through every
3495
- * install primitive (R2 storage keys, `PluginStateRepository`,
3496
- * `syncMarketplacePlugins`, sandbox cache keys). Rather than refactor
3497
- * everything to carry a composite identifier, we normalize the registry
3498
- * tuple to an opaque content-addressed id that satisfies the existing
3499
- * `validatePluginIdentifier` shape (`/^[a-z][a-z0-9_-]*$/`).
3500
- *
3501
- * The normalized id is:
3502
- *
3503
- * `r_` + base32-encoded SHA-256(publisher_did + "\n" + slug), truncated.
3504
- *
3505
- * Properties:
3506
- *
3507
- * - Deterministic. The same `(publisher, slug)` always produces the
3508
- * same id, so re-resolving an installed plugin's metadata against
3509
- * the aggregator is a straightforward lookup keyed by the columns
3510
- * stored alongside `plugin_id` in `plugin_states`.
3511
- * - Collision-resistant. 80 bits of truncated hash; a 50% birthday
3512
- * collision happens around 2^40 distinct plugins, well beyond what
3513
- * this registry will ever index.
3514
- * - R2-safe. Lowercase alphanumerics + underscore (no hyphens), no
3515
- * `:` or `/`. Existing sandbox cache keys (`${pluginId}:${version}`)
3516
- * keep working because the id contains no `:`.
3517
- * - Syntactically distinct from typical marketplace plugin ids: the
3518
- * `r_` prefix plus exactly 16 base32 characters is unlikely to be
3519
- * chosen as a marketplace id. Not formally guaranteed by the
3520
- * validator -- marketplace ids may begin with `r_` and contain
3521
- * hyphens -- so the install handler also performs an explicit
3522
- * pre-existing-row check at the derived id and rejects any cross-
3523
- * source collision (`PLUGIN_ID_COLLISION`).
3524
- *
3525
- * Reverse lookup (id → publisher + slug) requires the `plugin_states`
3526
- * row -- the hash is one-way. That's intentional: any code path that
3527
- * needs the human-meaningful pair already has the state row in hand.
3528
- */
3529
- /** Length (in base32 characters) of the truncated hash portion of the id. */
3530
- const HASH_LENGTH = 16;
3531
- /** Total expected length of a registry plugin id. */
3532
- const REGISTRY_PLUGIN_ID_LENGTH = 2 + HASH_LENGTH;
3533
- const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
3534
- /**
3535
- * RFC 4648 base32 encoding without padding, lowercase. Implemented inline
3536
- * rather than depending on a multibase library because (a) we only need
3537
- * lowercase base32 here, (b) we need it to run identically in workerd,
3538
- * Node, and the browser, and (c) the implementation is fewer lines than
3539
- * the import statement would be.
3540
- */
3541
- function base32Encode(bytes) {
3542
- let bits = 0;
3543
- let value = 0;
3544
- let out = "";
3545
- for (const byte of bytes) {
3546
- value = value << 8 | byte;
3547
- bits += 8;
3548
- while (bits >= 5) {
3549
- bits -= 5;
3550
- out += BASE32_ALPHABET[value >>> bits & 31];
3551
- }
3552
- }
3553
- if (bits > 0) out += BASE32_ALPHABET[value << 5 - bits & 31];
3554
- return out;
3555
- }
3556
- /**
3557
- * Derive the normalized plugin id for a registry-published plugin.
3558
- *
3559
- * Throws if either input is empty or whitespace-only -- a missing DID
3560
- * or slug is always a programming error in the install path, not a
3561
- * recoverable runtime condition.
3562
- */
3563
- async function makeRegistryPluginId(publisherDid, slug) {
3564
- const did = publisherDid.trim();
3565
- const s = slug.trim();
3566
- if (!did) throw new Error("makeRegistryPluginId: publisherDid is required");
3567
- if (!s) throw new Error("makeRegistryPluginId: slug is required");
3568
- const input = `${did}\n${s}`;
3569
- const hashBuffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
3570
- return `r_${base32Encode(new Uint8Array(hashBuffer)).slice(0, HASH_LENGTH)}`;
3571
- }
3572
-
3573
- //#endregion
3574
- //#region src/api/handlers/registry.ts
3575
- /**
3576
- * Registry plugin install handler.
3577
- *
3578
- * Installs a plugin published to the experimental decentralized plugin
3579
- * registry described in RFC 0001. The install flow:
3580
- *
3581
- * 1. Resolve `(handle, slug)` to a publisher DID via the configured
3582
- * aggregator's `resolvePackage` XRPC.
3583
- * 2. Look up the requested release (or the policy-filtered latest one)
3584
- * via `getLatestRelease` / `listReleases`.
3585
- * 3. Reject the install if the aggregator surfaces a `security:yanked`
3586
- * hard-enforcement label or the release is below the configured
3587
- * minimum release age.
3588
- * 4. Fetch the bundle artifact, walking aggregator mirrors first and
3589
- * falling back to the publisher-declared URL.
3590
- * 5. Verify the artifact's multibase checksum against the signed
3591
- * release record's `artifacts.package.checksum`.
3592
- * 6. Extract `manifest.json` + `backend.js` + optional `admin.js` from
3593
- * the gzipped tar bundle.
3594
- * 7. Store the extracted files in site-local R2 under the
3595
- * `registry/<plugin-id>/<version>/` prefix.
3596
- * 8. Write a `plugin_states` row with `source = "registry"` and the
3597
- * `(publisher_did, slug)` pair so updates can be resolved later.
3598
- * 9. Sync the runtime so the plugin becomes active immediately.
3599
- *
3600
- * Known gaps (tracked separately):
3601
- *
3602
- * - The aggregator-supplied records are not yet cryptographically
3603
- * verified against the publisher's MST signature. The signed bytes
3604
- * and CIDs are passed through verbatim per the lexicon, but full
3605
- * PDS-direct verification with proof traversal is follow-up work.
3606
- * The artifact checksum is verified end-to-end against the value
3607
- * in the (aggregator-relayed) release record, which is the actual
3608
- * trust boundary for the bytes that end up in the sandbox.
3609
- * - `acceptLabelers` is forwarded as-is to the aggregator; this
3610
- * handler does not independently re-fetch and verify labels from
3611
- * each labeller's DID. Aggregator label envelope tampering is
3612
- * mitigated by the artifact checksum but not detected.
3613
- */
3614
- const RELEASE_EXTENSION_NSID = "com.emdashcms.experimental.package.releaseExtension";
3615
- /**
3616
- * Whether two `declaredAccess` blocks grant exactly the same enforced access --
3617
- * the same capabilities AND the same host allow-list. Both are lowered through
3618
- * the canonical converter so that constraint content (`allowedHosts`), not just
3619
- * the capability set, is part of the comparison. The capability-set consent
3620
- * gate is blind to host scope; this is what keeps a bundle from being installed
3621
- * with a wider (or simply different) host allow-list than its published record
3622
- * advertised and the user consented to.
3623
- */
3624
- function enforcedAccessEqual(a, b) {
3625
- const aa = declaredAccessToCapabilities(a);
3626
- const bb = declaredAccessToCapabilities(b);
3627
- return JSON.stringify(aa.capabilities.toSorted()) === JSON.stringify(bb.capabilities.toSorted()) && JSON.stringify(aa.allowedHosts.toSorted()) === JSON.stringify(bb.allowedHosts.toSorted());
3628
- }
3629
- /** Matches a bare 64-character lowercase/uppercase hex SHA-256 digest. */
3630
- const SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/i;
3631
- /** Compute the SHA-256 of `bytes` as a lowercase hex string. */
3632
- async function sha256Hex(bytes) {
3633
- const buf = await crypto.subtle.digest("SHA-256", bytes);
3634
- const arr = new Uint8Array(buf);
3635
- return Array.from(arr, (b) => b.toString(16).padStart(2, "0")).join("");
3636
- }
3637
- /** multihash code for sha2-256 (single-byte varint). */
3638
- const MULTIHASH_SHA256_CODE = 18;
3639
- /** sha2-256 digest length in bytes (single-byte varint). */
3640
- const MULTIHASH_SHA256_LENGTH = 32;
3641
- /**
3642
- * Compute the multibase-multihash sha2-256 checksum of `bytes`, in the
3643
- * same `b<base32>` shape the registry CLI publishes
3644
- * (`packages/plugin-cli/src/multihash.ts`). Returns a 56-character
3645
- * string starting with `b`.
3646
- *
3647
- * The trust contract is: if both sides produce the same string for
3648
- * the same bytes, the bytes are unchanged. We don't decode the
3649
- * publisher-supplied checksum -- we just re-encode our own and compare,
3650
- * which is equivalent and avoids needing a base32 decoder.
3651
- */
3652
- async function sha256MultibaseMultihash(bytes) {
3653
- const digestBuf = await crypto.subtle.digest("SHA-256", bytes);
3654
- const digest = new Uint8Array(digestBuf);
3655
- const multihash = new Uint8Array(2 + digest.length);
3656
- multihash[0] = MULTIHASH_SHA256_CODE;
3657
- multihash[1] = MULTIHASH_SHA256_LENGTH;
3658
- multihash.set(digest, 2);
3659
- const { toBase32 } = await import("@atcute/multibase");
3660
- return `b${toBase32(multihash)}`;
3661
- }
3662
- /**
3663
- * Verify that a checksum string from a release record's
3664
- * `artifact.checksum` field corresponds to the SHA-256 of the given
3665
- * bytes.
3666
- *
3667
- * Accepts two formats:
3668
- *
3669
- * - Bare lowercase/uppercase hex SHA-256 (64 chars). Convenience for
3670
- * publishers / tools that emit hex rather than multibase.
3671
- * - Multibase-multihash with the `b` (base32) prefix and sha2-256.
3672
- * This is the format RFC 0001 mandates and the registry CLI emits
3673
- * (see `packages/plugin-cli/src/multihash.ts`).
3674
- *
3675
- * Hash functions other than sha2-256 are out of scope for this
3676
- * initial release; the install fails closed.
3677
- */
3678
- async function verifyChecksum(bytes, checksum) {
3679
- if (SHA256_HEX_PATTERN.test(checksum)) {
3680
- const actual = await sha256Hex(bytes);
3681
- return checksum.toLowerCase() === actual;
3682
- }
3683
- if (checksum.length === 56 && checksum.startsWith("b")) return (await sha256MultibaseMultihash(bytes)).toLowerCase() === checksum.toLowerCase();
3684
- return false;
3685
- }
3686
- /**
3687
- * Bytes-per-artifact cap on the gzipped tarball we'll download before
3688
- * decompression. RFC 0001 caps a sandboxed plugin bundle at 256 KiB
3689
- * decompressed (see `MAX_BUNDLE_SIZE` in cli/commands/bundle-utils.ts);
3690
- * gzip on a mix of JSON manifest + JS code typically gives 0.3-0.6
3691
- * ratio, so compressed bundles are well under 200 KiB in practice.
3692
- * 512 KiB leaves margin for unusual file mixes that compress poorly
3693
- * while still rejecting anything that's obviously not a legitimate
3694
- * plugin bundle.
3695
- */
3696
- const MAX_ARTIFACT_BYTES = 512 * 1024;
3697
- /**
3698
- * Maximum number of HTTP redirects followed during artifact download.
3699
- * Each hop is independently URL-validated, so a malicious server cannot
3700
- * redirect through a series of allowed-looking origins to reach a
3701
- * forbidden one.
3702
- */
3703
- const MAX_REDIRECTS = 5;
3704
- /**
3705
- * Wall-clock cap on any single artifact fetch attempt (per URL).
3706
- * Defends against slow-loris mirrors that accept the connection but
3707
- * never finish sending headers or body.
3708
- */
3709
- const ARTIFACT_FETCH_TIMEOUT_MS = 15e3;
3710
- /**
3711
- * Total wall-clock budget for the artifact-download phase across all
3712
- * mirrors and the declared URL. Even with the per-URL timeout, a
3713
- * malicious mirror list could otherwise tie up the install request for
3714
- * minutes; this caps total time at a budget interactive admins can
3715
- * tolerate. Tuned so a fast happy path takes <1s of budget per
3716
- * attempt and a worst case still completes in under a minute.
3717
- */
3718
- const ARTIFACT_TOTAL_BUDGET_MS = 45e3;
3719
- /**
3720
- * Cap on the number of mirror URLs we try before falling back to the
3721
- * publisher-declared URL. Matches the aggregator lexicon's
3722
- * `mirrors` array length cap (16) but enforced here independently so
3723
- * a misbehaving aggregator can't slow-loris us through hundreds of
3724
- * URLs.
3725
- */
3726
- const MAX_MIRRORS = 16;
3727
- /**
3728
- * Per-request timeout applied to every aggregator XRPC call
3729
- * (`resolvePackage`, `getLatestRelease`, `listReleases`). Matches the
3730
- * per-URL artifact-fetch cap. Without this, a slow-loris aggregator
3731
- * can stall the install before the artifact phase even starts.
3732
- */
3733
- const AGGREGATOR_REQUEST_TIMEOUT_MS = 15e3;
3734
- /**
3735
- * Total wall-clock budget for the aggregator-discovery phase
3736
- * (resolve + selected-release lookup). Mirrors the artifact-download
3737
- * budget. Worst case with the pinned-version path's 20-page cap is
3738
- * 20 + 1 calls; capping the total ensures any one stalled call
3739
- * still bounds the whole phase.
3740
- */
3741
- const AGGREGATOR_TOTAL_BUDGET_MS = 3e4;
3742
- /** Build a fetch function that enforces a per-request and per-budget timeout. */
3743
- function timedFetch(totalDeadline) {
3744
- return (input, init) => {
3745
- const now = Date.now();
3746
- const remaining = Math.max(0, totalDeadline - now);
3747
- if (remaining === 0) return Promise.reject(/* @__PURE__ */ new Error("Aggregator request budget exhausted"));
3748
- const timeout = Math.min(AGGREGATOR_REQUEST_TIMEOUT_MS, remaining);
3749
- const controller = new AbortController();
3750
- const timer = setTimeout(() => controller.abort(), timeout);
3751
- const callerSignal = init?.signal;
3752
- if (callerSignal) if (callerSignal.aborted) controller.abort(callerSignal.reason);
3753
- else callerSignal.addEventListener("abort", () => controller.abort(callerSignal.reason));
3754
- return fetch(input, {
3755
- ...init,
3756
- signal: controller.signal
3757
- }).finally(() => {
3758
- clearTimeout(timer);
3759
- });
3760
- };
3761
- }
3762
- /**
3763
- * Localhost-equivalent hostnames the artifact fetcher rejects in
3764
- * production. The full literal-IP / DNS-rebinding blocklist lives in
3765
- * `#security/ssrf.js` and is invoked via `resolveAndValidateExternalUrl`
3766
- * below; this small set exists only because the artifact handler has
3767
- * a dev-mode escape hatch that lets `http://localhost` through.
3768
- */
3769
- const FORBIDDEN_HOSTNAMES = new Set([
3770
- "localhost",
3771
- "localhost.localdomain",
3772
- "ip6-localhost",
3773
- "ip6-loopback"
3774
- ]);
3775
- /** Trailing dot on a hostname, stripped before URL host comparisons. */
3776
- const TRAILING_DOT = /\.$/;
3777
- /** Hostnames that resolve to the local machine; rejected outright in production. */
3778
- function isLocalhostHostname(hostname) {
3779
- const stripped = hostname.toLowerCase().replace(TRAILING_DOT, "");
3780
- const h = stripped.startsWith("[") && stripped.endsWith("]") ? stripped.slice(1, -1) : stripped;
3781
- if (FORBIDDEN_HOSTNAMES.has(h)) return true;
3782
- if (h === "localhost") return true;
3783
- if (h.endsWith(".localhost")) return true;
3784
- if (h === "127.0.0.1" || h === "::1") return true;
3785
- if (h.startsWith("::ffff:127.") || h.startsWith("::ffff:7f00:")) return true;
3786
- return false;
3787
- }
3788
- /**
3789
- * Validate that `urlString` is a safe outbound target for artifact
3790
- * downloads. Rejects non-HTTPS (except localhost in dev), embedded
3791
- * credentials, any host that's a loopback / private / link-local
3792
- * literal address, and any hostname whose resolved A or AAAA records
3793
- * point at one of those addresses (closes the DNS-rebinding gap).
3794
- *
3795
- * Wraps `resolveAndValidateExternalUrl` from the import-pipeline SSRF
3796
- * module so both code paths share one DoH cache, one resolver, one
3797
- * blocklist, and one set of regression tests. Layers an
3798
- * artifact-specific protocol/dev-localhost policy on top.
3799
- *
3800
- * `import.meta.env.DEV` is a Vite/Astro compile-time constant, so
3801
- * production bundles cannot enable the dev escape hatch at runtime.
3802
- */
3803
- async function assertSafeArtifactUrl(urlString) {
3804
- let url;
3805
- try {
3806
- url = new URL(urlString);
3807
- } catch {
3808
- throw new Error(`Invalid artifact URL: ${urlString}`);
3809
- }
3810
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Artifact URL protocol not allowed: ${url.protocol}`);
3811
- if (url.username || url.password) throw new Error("Artifact URL must not contain embedded credentials");
3812
- const rawHostname = url.hostname.toLowerCase().replace(TRAILING_DOT, "");
3813
- const hostname = rawHostname.startsWith("[") && rawHostname.endsWith("]") ? rawHostname.slice(1, -1) : rawHostname;
3814
- const localhost = isLocalhostHostname(hostname);
3815
- if (!import.meta.env.DEV) {
3816
- if (url.protocol === "http:") throw new Error("Artifact URL must use https");
3817
- if (localhost) throw new Error(`Artifact URL points to localhost: ${hostname}`);
3818
- } else if (url.protocol === "http:" && !localhost) throw new Error("Artifact URL must use https (http allowed only for localhost in dev)");
3819
- if (localhost) return url;
3820
- try {
3821
- return await resolveAndValidateExternalUrl(url.href);
3822
- } catch (err) {
3823
- if (err instanceof SsrfError) throw new Error(`Artifact URL rejected: ${err.message}`, { cause: err });
3824
- throw err;
3825
- }
3826
- }
3827
- /**
3828
- * Fetch one URL with manual redirect handling so every hop is
3829
- * URL-validated, a hard byte cap so a malicious response body cannot
3830
- * exhaust memory before the checksum check rejects it, and a wall-clock
3831
- * timeout that covers connect, headers, and body together. The timeout
3832
- * is the minimum of the per-URL cap and the remaining total budget so
3833
- * a late-arriving mirror still respects the install's global budget.
3834
- */
3835
- async function fetchWithLimits(initialUrl, totalDeadline) {
3836
- const now = Date.now();
3837
- const remaining = Math.max(0, totalDeadline - now);
3838
- if (remaining === 0) throw new Error("Artifact download budget exhausted");
3839
- const perUrlTimeout = Math.min(ARTIFACT_FETCH_TIMEOUT_MS, remaining);
3840
- const controller = new AbortController();
3841
- const timer = setTimeout(() => controller.abort(), perUrlTimeout);
3842
- try {
3843
- let current = await assertSafeArtifactUrl(initialUrl);
3844
- let response;
3845
- for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
3846
- response = await fetch(current.href, {
3847
- redirect: "manual",
3848
- signal: controller.signal
3849
- });
3850
- if (response.status < 300 || response.status >= 400) break;
3851
- const location = response.headers.get("location");
3852
- if (!location) break;
3853
- if (hop === MAX_REDIRECTS) throw new Error(`Too many redirects fetching artifact (>${MAX_REDIRECTS})`);
3854
- current = await assertSafeArtifactUrl(new URL(location, current).href);
3855
- }
3856
- const finalResponse = response;
3857
- if (!finalResponse.ok) throw new Error(`HTTP ${finalResponse.status}`);
3858
- const lengthHeader = finalResponse.headers.get("content-length");
3859
- if (lengthHeader) {
3860
- const declared = Number(lengthHeader);
3861
- if (Number.isFinite(declared) && declared > MAX_ARTIFACT_BYTES) throw new Error(`Artifact too large (declared ${declared} bytes, limit ${MAX_ARTIFACT_BYTES})`);
3862
- }
3863
- const body = finalResponse.body;
3864
- if (!body) {
3865
- const buf = new Uint8Array(await finalResponse.arrayBuffer());
3866
- if (buf.byteLength > MAX_ARTIFACT_BYTES) throw new Error(`Artifact too large (limit ${MAX_ARTIFACT_BYTES} bytes)`);
3867
- return buf;
3868
- }
3869
- const reader = body.getReader();
3870
- const chunks = [];
3871
- let total = 0;
3872
- while (true) {
3873
- const { done, value } = await reader.read();
3874
- if (done) break;
3875
- if (!value) continue;
3876
- total += value.byteLength;
3877
- if (total > MAX_ARTIFACT_BYTES) {
3878
- try {
3879
- await reader.cancel();
3880
- } catch {}
3881
- throw new Error(`Artifact too large (limit ${MAX_ARTIFACT_BYTES} bytes)`);
3882
- }
3883
- chunks.push(value);
3884
- }
3885
- const out = new Uint8Array(total);
3886
- let offset = 0;
3887
- for (const chunk of chunks) {
3888
- out.set(chunk, offset);
3889
- offset += chunk.byteLength;
3890
- }
3891
- return out;
3892
- } finally {
3893
- clearTimeout(timer);
3894
- }
3895
- }
3896
- /**
3897
- * Strip query string and fragment from a URL for use in
3898
- * client-visible error messages. Registry artifacts are often hosted
3899
- * on storage backends that include presigned tokens in the query
3900
- * string; surfacing the raw URL on a failed install leaks those
3901
- * tokens into the admin's HTTP response and any log drain that
3902
- * captures the error chain. Origin + pathname is enough to identify
3903
- * the host and resource without exposing credentials.
3904
- *
3905
- * Falls back to a generic placeholder when the URL is malformed.
3906
- */
3907
- function redactUrlForError(raw) {
3908
- try {
3909
- const u = new URL(raw);
3910
- return `${u.origin}${u.pathname}`;
3911
- } catch {
3912
- return "<malformed url>";
3913
- }
3914
- }
3915
- /** Walk artifact source URLs in priority order and return the first that fetches successfully. */
3916
- async function fetchArtifact(mirrors, declaredUrl) {
3917
- const urls = [...mirrors.slice(0, MAX_MIRRORS), declaredUrl];
3918
- const clientErrors = [];
3919
- const totalDeadline = Date.now() + ARTIFACT_TOTAL_BUDGET_MS;
3920
- for (const url of urls) {
3921
- if (Date.now() >= totalDeadline) {
3922
- clientErrors.push("(total artifact download budget exhausted)");
3923
- break;
3924
- }
3925
- try {
3926
- return await fetchWithLimits(url, totalDeadline);
3927
- } catch (err) {
3928
- const message = err instanceof Error ? err.message : String(err);
3929
- console.warn(`[registry-install] Artifact fetch failed from ${url}:`, message);
3930
- clientErrors.push(`${redactUrlForError(url)}: ${message}`);
3931
- }
3932
- }
3933
- throw new Error(`Failed to download artifact from any source. Tried:\n ${clientErrors.join("\n ")}`);
3934
- }
3935
- /**
3936
- * Gate a release's `requires` constraints against the running host
3937
- * environment. `requires` is the lexicon-`unknown` value off the signed
3938
- * release record — never trust its shape; `checkEnvCompatibility` guards it.
3939
- *
3940
- * Returns `null` when every advertised constraint is satisfied (or there are
3941
- * none), or a structured `ENV_INCOMPATIBLE` error naming the unsatisfied
3942
- * constraints and the host versions. The error carries the guarded `requires`
3943
- * and `host` maps so the admin can render the same mismatch the UI gate shows.
3944
- */
3945
- function assertEnvCompatible(requires, hostEnv) {
3946
- 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}`);
3947
- const mismatches = checkEnvCompatibility(requires, hostEnv);
3948
- if (mismatches.length === 0) return null;
3949
- const guarded = {};
3950
- for (const m of mismatches) guarded[m.key] = m.required;
3951
- return {
3952
- code: "ENV_INCOMPATIBLE",
3953
- message: `This release is not compatible with the current environment: ${mismatches.map((m) => `${m.key} requires ${m.required} but host is ${m.host}`).join("; ")}.`,
3954
- details: {
3955
- requires: guarded,
3956
- host: hostEnv
3957
- }
3958
- };
3959
- }
3960
- async function handleRegistryInstall(db, storage, sandboxRunner, registryConfigInput, input, opts) {
3961
- const registryConfig = coerceRegistryConfig(registryConfigInput);
3962
- if (!registryConfig) return {
3963
- success: false,
3964
- error: {
3965
- code: "REGISTRY_NOT_CONFIGURED",
3966
- message: "Registry is not configured"
3967
- }
3968
- };
3969
- if (!storage) return {
3970
- success: false,
3971
- error: {
3972
- code: "STORAGE_NOT_CONFIGURED",
3973
- message: "Storage is required for registry plugin installation"
3974
- }
3975
- };
3976
- if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
3977
- success: false,
3978
- error: {
3979
- code: "SANDBOX_NOT_AVAILABLE",
3980
- message: "Sandbox runner is required for registry plugins"
3981
- }
3982
- };
3983
- try {
3984
- validateAggregatorUrl(registryConfig.aggregatorUrl);
3985
- } catch (err) {
3986
- return {
3987
- success: false,
3988
- error: {
3989
- code: "REGISTRY_NOT_CONFIGURED",
3990
- message: err instanceof Error ? err.message : "Invalid aggregator URL"
3991
- }
3992
- };
3993
- }
3994
- const { did, slug, version: requestedVersion } = input;
3995
- const { DiscoveryClient } = await import("@emdash-cms/registry-client/discovery");
3996
- const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
3997
- const discovery = new DiscoveryClient({
3998
- aggregatorUrl: registryConfig.aggregatorUrl,
3999
- acceptLabelers: registryConfig.acceptLabelers,
4000
- fetch: timedFetch(aggregatorDeadline)
4001
- });
4002
- if (!did.startsWith("did:") || did.split(":").length < 3) return {
4003
- success: false,
4004
- error: {
4005
- code: "INVALID_DID",
4006
- message: "DID must be a valid atproto DID (e.g. did:plc:abc123)"
4007
- }
4008
- };
4009
- try {
4010
- const publisherDid = did;
4011
- const packageView = await discovery.getPackage({
4012
- did: publisherDid,
4013
- slug
4014
- });
4015
- const MAX_LIST_PAGES = 20;
4016
- const releaseView = await (async () => {
4017
- if (!requestedVersion) return discovery.getLatestRelease({
4018
- did: publisherDid,
4019
- package: slug
4020
- });
4021
- let cursor;
4022
- const seenCursors = /* @__PURE__ */ new Set();
4023
- for (let page = 0; page < MAX_LIST_PAGES; page++) {
4024
- if (cursor !== void 0) {
4025
- if (seenCursors.has(cursor)) break;
4026
- seenCursors.add(cursor);
4027
- }
4028
- const result = await discovery.listReleases({
4029
- did: publisherDid,
4030
- package: slug,
4031
- cursor,
4032
- limit: 50
4033
- });
4034
- for (const r of result.releases) if (r.version === requestedVersion) return r;
4035
- if (!result.cursor) break;
4036
- cursor = result.cursor;
4037
- }
4038
- })();
4039
- if (!releaseView) return {
4040
- success: false,
4041
- error: {
4042
- code: "NO_RELEASE",
4043
- message: requestedVersion ? `Version ${requestedVersion} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4044
- }
4045
- };
4046
- const signedRelease = releaseView.release;
4047
- if (packageView.did !== publisherDid || packageView.slug !== slug) return {
4048
- success: false,
4049
- error: {
4050
- code: "AGGREGATOR_IDENTITY_MISMATCH",
4051
- message: "Aggregator returned a package view for a different publisher or slug."
4052
- }
4053
- };
4054
- if (releaseView.did !== publisherDid || releaseView.package !== slug || signedRelease?.package !== slug || requestedVersion !== void 0 && releaseView.version !== requestedVersion || signedRelease?.version !== releaseView.version) return {
4055
- success: false,
4056
- error: {
4057
- code: "AGGREGATOR_IDENTITY_MISMATCH",
4058
- message: "Aggregator returned a release view that does not match the requested package or version."
4059
- }
4060
- };
4061
- const version = releaseView.version;
4062
- const yanked = (packageView.labels ?? []).some((l) => l.val === "security:yanked");
4063
- const releaseYanked = (releaseView.labels ?? []).some((l) => l.val === "security:yanked");
4064
- if (yanked || releaseYanked) return {
4065
- success: false,
4066
- error: {
4067
- code: "RELEASE_YANKED",
4068
- message: "This release has been withdrawn (security:yanked label)."
4069
- }
4070
- };
4071
- if (opts?.hostEnv) {
4072
- const envError = assertEnvCompatible(releaseView.release?.requires, opts.hostEnv);
4073
- if (envError) return {
4074
- success: false,
4075
- error: envError
4076
- };
4077
- }
4078
- const minimumReleaseAge = registryConfig.policy?.minimumReleaseAge;
4079
- let minimumReleaseAgeSeconds = 0;
4080
- if (minimumReleaseAge !== void 0) try {
4081
- minimumReleaseAgeSeconds = parseDurationSeconds(minimumReleaseAge);
4082
- } catch (err) {
4083
- return {
4084
- success: false,
4085
- error: {
4086
- code: "REGISTRY_POLICY_INVALID",
4087
- message: err instanceof Error ? err.message : "Invalid minimumReleaseAge value in registry config"
4088
- }
4089
- };
4090
- }
4091
- if (minimumReleaseAgeSeconds > 0) {
4092
- const exclude = registryConfig.policy?.minimumReleaseAgeExclude?.map((e) => e.trim().toLowerCase());
4093
- if (!releaseExemptFromMinimumAge(exclude, publisherDid, slug)) {
4094
- const indexedAt = Date.parse(releaseView.indexedAt);
4095
- if (!Number.isFinite(indexedAt)) return {
4096
- success: false,
4097
- error: {
4098
- code: "RELEASE_TIMESTAMP_INVALID",
4099
- message: "Release record is missing a valid indexed-at timestamp; cannot evaluate minimum release age policy."
4100
- }
4101
- };
4102
- const ageSeconds = (Date.now() - indexedAt) / 1e3;
4103
- if (ageSeconds < minimumReleaseAgeSeconds) {
4104
- const remaining = Math.ceil(minimumReleaseAgeSeconds - ageSeconds);
4105
- return {
4106
- success: false,
4107
- error: {
4108
- code: "RELEASE_TOO_NEW",
4109
- message: `This release does not meet the configured minimum release age of ${minimumReleaseAgeSeconds}s. It will be installable in ~${remaining}s.`
4110
- }
4111
- };
4112
- }
4113
- }
4114
- }
4115
- const pluginId = await makeRegistryPluginId(publisherDid, slug);
4116
- if (opts?.configuredPluginIds?.has(pluginId)) return {
4117
- success: false,
4118
- error: {
4119
- code: "PLUGIN_ID_CONFLICT",
4120
- message: "A configured plugin with the same derived id already exists"
4121
- }
4122
- };
4123
- const stateRepo = new PluginStateRepository(db);
4124
- const existing = await stateRepo.get(pluginId);
4125
- if (existing) {
4126
- if (existing.source === "registry") return {
4127
- success: false,
4128
- error: {
4129
- code: "ALREADY_INSTALLED",
4130
- message: `Plugin ${publisherDid}/${slug} is already installed`
4131
- }
4132
- };
4133
- return {
4134
- success: false,
4135
- error: {
4136
- code: "PLUGIN_ID_COLLISION",
4137
- message: `A non-registry plugin already exists at the derived id ${pluginId}. Uninstall it before installing this registry plugin.`
4138
- }
4139
- };
4140
- }
4141
- const release = releaseView.release;
4142
- const declaredUrl = release?.artifacts?.package?.url;
4143
- const declaredChecksum = release?.artifacts?.package?.checksum;
4144
- if (!declaredUrl || !declaredChecksum) return {
4145
- success: false,
4146
- error: {
4147
- code: "INVALID_RELEASE",
4148
- message: "Release record is missing artifact url or checksum"
4149
- }
4150
- };
4151
- const artifactBytes = await fetchArtifact(releaseView.mirrors ?? [], declaredUrl);
4152
- if (!await verifyChecksum(artifactBytes, declaredChecksum)) return {
4153
- success: false,
4154
- error: {
4155
- code: "CHECKSUM_MISMATCH",
4156
- message: "Artifact bytes do not match the release record's checksum, or the checksum encoding is unsupported."
4157
- }
4158
- };
4159
- let bundle;
4160
- try {
4161
- bundle = await extractBundle(artifactBytes);
4162
- } catch (err) {
4163
- return {
4164
- success: false,
4165
- error: {
4166
- code: "INVALID_BUNDLE",
4167
- message: err instanceof Error ? err.message : "Failed to extract plugin bundle"
4168
- }
4169
- };
4170
- }
4171
- if (bundle.manifest.version !== version) return {
4172
- success: false,
4173
- error: {
4174
- code: "MANIFEST_VERSION_MISMATCH",
4175
- message: `Bundle manifest version (${bundle.manifest.version}) does not match release version (${version})`
4176
- }
4177
- };
4178
- if (bundle.manifest.id !== slug) return {
4179
- success: false,
4180
- error: {
4181
- code: "MANIFEST_ID_MISMATCH",
4182
- message: `Bundle manifest id (${bundle.manifest.id}) does not match registry slug (${slug})`
4183
- }
4184
- };
4185
- bundle.manifest = {
4186
- ...bundle.manifest,
4187
- id: pluginId
4188
- };
4189
- const recordExt = (release?.extensions)?.[RELEASE_EXTENSION_NSID];
4190
- if (!enforcedAccessEqual(recordExt?.declaredAccess ?? {}, bundle.manifest.declaredAccess ?? {})) return {
4191
- success: false,
4192
- error: {
4193
- code: "DECLARED_ACCESS_DRIFT",
4194
- message: "The plugin bundle declares different permissions than its published record. Installation refused."
4195
- }
4196
- };
4197
- const actualCapabilities = canonicalCapabilitiesForDriftCheck(bundle.manifest.capabilities);
4198
- if (actualCapabilities.length > 0) {
4199
- if (input.acknowledgedDeclaredAccess === void 0) return {
4200
- success: false,
4201
- error: {
4202
- code: "DECLARED_ACCESS_REQUIRED",
4203
- message: "This plugin declares capabilities that require consent. Re-open the install dialog to review and acknowledge them."
4204
- }
4205
- };
4206
- const acknowledged = canonicalCapabilitiesForDriftCheck(input.acknowledgedDeclaredAccess);
4207
- if (acknowledged.length !== actualCapabilities.length || acknowledged.some((cap, i) => cap !== actualCapabilities[i])) return {
4208
- success: false,
4209
- error: {
4210
- code: "DECLARED_ACCESS_DRIFT",
4211
- message: "Plugin manifest has changed since you consented. Re-open the install dialog to review the new permissions."
4212
- }
4213
- };
4214
- }
4215
- const actualMcpTools = (bundle.manifest.mcp?.tools ?? []).map(({ inputSchema: _, outputSchema: __, ...tool }) => tool);
4216
- if (actualMcpTools.length > 0) {
4217
- if (JSON.stringify(input.acknowledgedMcpTools) !== JSON.stringify(actualMcpTools)) return {
4218
- success: false,
4219
- error: {
4220
- code: "MCP_TOOL_CONSENT_REQUIRED",
4221
- message: "Plugin MCP tools require explicit consent",
4222
- details: { mcpTools: actualMcpTools }
4223
- }
4224
- };
4225
- }
4226
- await storeBundleInR2(storage, pluginId, version, bundle, "registry");
4227
- const profile = packageView.profile;
4228
- try {
4229
- await stateRepo.upsert(pluginId, version, "active", {
4230
- source: "registry",
4231
- displayName: profile?.name ?? slug,
4232
- description: profile?.description ?? void 0,
4233
- registryPublisherDid: publisherDid,
4234
- registrySlug: slug
4235
- });
4236
- } catch (stateErr) {
4237
- let lostRace = false;
4238
- try {
4239
- const winner = await stateRepo.get(pluginId);
4240
- lostRace = winner !== void 0 && winner !== null;
4241
- } catch (probeErr) {
4242
- console.warn(`[registry-install] Failed to probe state row for ${pluginId} after state-write failure; treating as orphan:`, probeErr);
4243
- }
4244
- if (!lostRace) try {
4245
- await deleteBundleFromR2(storage, pluginId, version, "registry");
4246
- } catch (cleanupErr) {
4247
- console.warn(`[registry-install] Failed to clean up R2 bundle for ${pluginId}@${version} after state-row write failure:`, cleanupErr);
4248
- }
4249
- throw stateErr;
4250
- }
4251
- await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4252
- return {
4253
- success: true,
4254
- data: {
4255
- pluginId,
4256
- publisherDid,
4257
- slug,
4258
- version,
4259
- capabilities: bundle.manifest.capabilities
4260
- }
4261
- };
4262
- } catch (err) {
4263
- if (err instanceof ClientValidationError) return {
4264
- success: false,
4265
- error: {
4266
- code: "AGGREGATOR_RESPONSE_INVALID",
4267
- message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4268
- }
4269
- };
4270
- if (err instanceof ClientResponseError) return {
4271
- success: false,
4272
- error: {
4273
- code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4274
- message: `Aggregator returned ${err.status}: ${err.error}`
4275
- }
4276
- };
4277
- if (err instanceof EmDashStorageError) return {
4278
- success: false,
4279
- error: {
4280
- code: err.code ?? "STORAGE_ERROR",
4281
- message: "Storage error while installing plugin"
4282
- }
4283
- };
4284
- console.error("[registry-install] Failed:", err);
4285
- return {
4286
- success: false,
4287
- error: {
4288
- code: "INSTALL_FAILED",
4289
- message: err instanceof Error ? err.message : "Failed to install plugin from registry"
4290
- }
4291
- };
4292
- }
4293
- }
4294
- /**
4295
- * Uninstall a registry-source plugin. Deletes the R2 bundle under
4296
- * `registry/<pluginId>/<version>/`, optionally drops the plugin's
4297
- * `_plugin_storage` rows, and removes the `_plugin_state` row. The
4298
- * sandbox runtime is reconciled by the route's `syncRegistryPlugins`
4299
- * call after this returns.
4300
- *
4301
- * Refuses to uninstall plugins whose `source` is not `"registry"` to
4302
- * avoid trashing a marketplace/config plugin that happens to share the
4303
- * pluginId namespace.
4304
- */
4305
- async function handleRegistryUninstall(db, storage, pluginId, opts) {
4306
- try {
4307
- const stateRepo = new PluginStateRepository(db);
4308
- const existing = await stateRepo.get(pluginId);
4309
- if (!existing || existing.source !== "registry") return {
4310
- success: false,
4311
- error: {
4312
- code: "NOT_FOUND",
4313
- message: `No registry plugin found: ${pluginId}`
4314
- }
4315
- };
4316
- const version = existing.version;
4317
- let dataDeleted = false;
4318
- if (opts?.deleteData) {
4319
- await db.deleteFrom("_plugin_storage").where("plugin_id", "=", pluginId).execute();
4320
- dataDeleted = true;
4321
- }
4322
- if (storage) await deleteBundleFromR2(storage, pluginId, version, "registry");
4323
- try {
4324
- await removeAllPluginIndexes(db, pluginId);
4325
- } catch {}
4326
- await stateRepo.delete(pluginId);
4327
- return {
4328
- success: true,
4329
- data: {
4330
- pluginId,
4331
- dataDeleted
4332
- }
4333
- };
4334
- } catch (err) {
4335
- console.error("[registry-uninstall] Failed:", err);
4336
- return {
4337
- success: false,
4338
- error: {
4339
- code: "UNINSTALL_FAILED",
4340
- message: "Failed to uninstall plugin"
4341
- }
4342
- };
4343
- }
4344
- }
4345
- /**
4346
- * Update a registry-source plugin to a newer release. Mirrors
4347
- * `handleMarketplaceUpdate`: resolves the target version via the aggregator,
4348
- * re-runs the artifact fetch / checksum / extract pipeline, diffs capabilities
4349
- * and route visibility against the currently installed bundle, and gates
4350
- * escalations behind `confirmCapabilityChanges` / `confirmRouteVisibilityChanges`
4351
- * so the admin re-consents to widened permissions.
4352
- *
4353
- * Refuses non-registry sources. Refuses when the stored state row is missing
4354
- * the `(publisherDid, slug)` it needs to resolve against the aggregator.
4355
- */
4356
- async function handleRegistryUpdate(db, storage, sandboxRunner, registryConfigInput, pluginId, opts) {
4357
- const registryConfig = coerceRegistryConfig(registryConfigInput);
4358
- if (!registryConfig) return {
4359
- success: false,
4360
- error: {
4361
- code: "REGISTRY_NOT_CONFIGURED",
4362
- message: "Registry is not configured"
4363
- }
4364
- };
4365
- if (!storage) return {
4366
- success: false,
4367
- error: {
4368
- code: "STORAGE_NOT_CONFIGURED",
4369
- message: "Storage is required for registry plugin updates"
4370
- }
4371
- };
4372
- if (!sandboxRunner || !sandboxRunner.isAvailable()) return {
4373
- success: false,
4374
- error: {
4375
- code: "SANDBOX_NOT_AVAILABLE",
4376
- message: "Sandbox runner is required"
4377
- }
4378
- };
4379
- try {
4380
- validateAggregatorUrl(registryConfig.aggregatorUrl);
4381
- } catch (err) {
4382
- return {
4383
- success: false,
4384
- error: {
4385
- code: "REGISTRY_NOT_CONFIGURED",
4386
- message: err instanceof Error ? err.message : "Invalid aggregator URL"
4387
- }
4388
- };
4389
- }
4390
- try {
4391
- const stateRepo = new PluginStateRepository(db);
4392
- const existing = await stateRepo.get(pluginId);
4393
- if (!existing || existing.source !== "registry") return {
4394
- success: false,
4395
- error: {
4396
- code: "NOT_FOUND",
4397
- message: `No registry plugin found: ${pluginId}`
4398
- }
4399
- };
4400
- if (!existing.registryPublisherDid || !existing.registrySlug) return {
4401
- success: false,
4402
- error: {
4403
- code: "INVALID_STATE",
4404
- message: `Registry plugin ${pluginId} is missing publisher DID or slug in state`
4405
- }
4406
- };
4407
- const oldVersion = existing.version;
4408
- const publisherDid = existing.registryPublisherDid;
4409
- const slug = existing.registrySlug;
4410
- const { DiscoveryClient } = await import("@emdash-cms/registry-client/discovery");
4411
- const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4412
- const discovery = new DiscoveryClient({
4413
- aggregatorUrl: registryConfig.aggregatorUrl,
4414
- acceptLabelers: registryConfig.acceptLabelers,
4415
- fetch: timedFetch(aggregatorDeadline)
4416
- });
4417
- const MAX_LIST_PAGES = 20;
4418
- const releaseView = await (async () => {
4419
- if (!opts?.version) return discovery.getLatestRelease({
4420
- did: publisherDid,
4421
- package: slug
4422
- });
4423
- let cursor;
4424
- const seenCursors = /* @__PURE__ */ new Set();
4425
- for (let page = 0; page < MAX_LIST_PAGES; page++) {
4426
- if (cursor !== void 0) {
4427
- if (seenCursors.has(cursor)) break;
4428
- seenCursors.add(cursor);
4429
- }
4430
- const result = await discovery.listReleases({
4431
- did: publisherDid,
4432
- package: slug,
4433
- cursor,
4434
- limit: 50
4435
- });
4436
- for (const r of result.releases) if (r.version === opts.version) return r;
4437
- if (!result.cursor) break;
4438
- cursor = result.cursor;
4439
- }
4440
- })();
4441
- if (!releaseView) return {
4442
- success: false,
4443
- error: {
4444
- code: "NO_VERSION",
4445
- message: opts?.version ? `Version ${opts.version} not found for ${publisherDid}/${slug}` : `No installable release found for ${publisherDid}/${slug}`
4446
- }
4447
- };
4448
- const signedRelease = releaseView.release;
4449
- if (releaseView.did !== publisherDid || releaseView.package !== slug || signedRelease?.package !== slug || opts?.version !== void 0 && releaseView.version !== opts.version || signedRelease?.version !== releaseView.version) return {
4450
- success: false,
4451
- error: {
4452
- code: "AGGREGATOR_IDENTITY_MISMATCH",
4453
- message: "Aggregator returned a release view that does not match the requested package or version."
4454
- }
4455
- };
4456
- const newVersion = releaseView.version;
4457
- if (newVersion === oldVersion) return {
4458
- success: false,
4459
- error: {
4460
- code: "ALREADY_UP_TO_DATE",
4461
- message: "Plugin is already at the requested version"
4462
- }
4463
- };
4464
- if ((releaseView.labels ?? []).some((l) => l.val === "security:yanked")) return {
4465
- success: false,
4466
- error: {
4467
- code: "YANKED",
4468
- message: "Release has been yanked by a trusted labeller"
4469
- }
4470
- };
4471
- if (opts?.hostEnv) {
4472
- const envError = assertEnvCompatible(signedRelease.requires, opts.hostEnv);
4473
- if (envError) return {
4474
- success: false,
4475
- error: envError
4476
- };
4477
- }
4478
- const declaredUrl = signedRelease.artifacts?.package?.url;
4479
- const declaredChecksum = signedRelease.artifacts?.package?.checksum;
4480
- if (!declaredUrl || !declaredChecksum) return {
4481
- success: false,
4482
- error: {
4483
- code: "INVALID_RELEASE",
4484
- message: "Release record is missing artifact url or checksum"
4485
- }
4486
- };
4487
- await assertSafeArtifactUrl(declaredUrl);
4488
- const mirrors = (releaseView.mirrors ?? []).slice(0, MAX_MIRRORS);
4489
- for (const mirror of mirrors) await assertSafeArtifactUrl(mirror);
4490
- const artifactBytes = await fetchArtifact(mirrors, declaredUrl);
4491
- if (!await verifyChecksum(artifactBytes, declaredChecksum)) return {
4492
- success: false,
4493
- error: {
4494
- code: "CHECKSUM_MISMATCH",
4495
- message: "Artifact bytes do not match the release's published checksum"
4496
- }
4497
- };
4498
- const bundle = await extractBundle(artifactBytes);
4499
- if (bundle.manifest.version !== newVersion) return {
4500
- success: false,
4501
- error: {
4502
- code: "BUNDLE_VERSION_MISMATCH",
4503
- message: `Bundle manifest version (${bundle.manifest.version}) does not match release version (${newVersion})`
4504
- }
4505
- };
4506
- if (bundle.manifest.id !== slug) return {
4507
- success: false,
4508
- error: {
4509
- code: "BUNDLE_IDENTITY_MISMATCH",
4510
- message: `Bundle manifest id (${bundle.manifest.id}) does not match registry slug (${slug})`
4511
- }
4512
- };
4513
- bundle.manifest = {
4514
- ...bundle.manifest,
4515
- id: pluginId
4516
- };
4517
- const recordExt = (signedRelease?.extensions)?.[RELEASE_EXTENSION_NSID];
4518
- if (!enforcedAccessEqual(recordExt?.declaredAccess ?? {}, bundle.manifest.declaredAccess ?? {})) return {
4519
- success: false,
4520
- error: {
4521
- code: "DECLARED_ACCESS_DRIFT",
4522
- message: "The plugin bundle declares different permissions than its published record. Update refused."
4523
- }
4524
- };
4525
- const oldBundle = await loadBundleFromR2(storage, pluginId, oldVersion, "registry");
4526
- const capabilityChanges = diffCapabilities(oldBundle?.manifest.capabilities ?? [], bundle.manifest.capabilities);
4527
- if (capabilityChanges.added.length > 0 && !opts?.confirmCapabilityChanges) return {
4528
- success: false,
4529
- error: {
4530
- code: "CAPABILITY_ESCALATION",
4531
- message: "Plugin update requires new capabilities",
4532
- details: { capabilityChanges }
4533
- }
4534
- };
4535
- const routeVisibilityChanges = diffRouteVisibility(oldBundle?.manifest, bundle.manifest);
4536
- const hasNewPublicRoutes = routeVisibilityChanges.newlyPublic.length > 0;
4537
- if (hasNewPublicRoutes && !opts?.confirmRouteVisibilityChanges) return {
4538
- success: false,
4539
- error: {
4540
- code: "ROUTE_VISIBILITY_ESCALATION",
4541
- message: "Plugin update exposes new public (unauthenticated) routes",
4542
- details: {
4543
- routeVisibilityChanges,
4544
- capabilityChanges
4545
- }
4546
- }
4547
- };
4548
- const oldMcpTools = [...oldBundle?.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4549
- const newMcpTools = [...bundle.manifest.mcp?.tools ?? []].toSorted((a, b) => a.name.localeCompare(b.name));
4550
- if (JSON.stringify(oldMcpTools) !== JSON.stringify(newMcpTools) && !opts?.confirmMcpTools) return {
4551
- success: false,
4552
- error: {
4553
- code: "MCP_TOOL_CONSENT_REQUIRED",
4554
- message: "Plugin update changes its MCP tools",
4555
- details: { mcpTools: newMcpTools.map(({ inputSchema: _, outputSchema: __, ...tool }) => tool) }
4556
- }
4557
- };
4558
- await storeBundleInR2(storage, pluginId, newVersion, bundle, "registry");
4559
- await stateRepo.upsert(pluginId, newVersion, "active", {
4560
- source: "registry",
4561
- registryPublisherDid: publisherDid,
4562
- registrySlug: slug,
4563
- displayName: existing.displayName ?? slug,
4564
- description: existing.description ?? void 0,
4565
- mcpToolsEnabled: false,
4566
- mcpToolsConsent: null
4567
- });
4568
- await syncDeclaredStorageIndexes(db, [bundle.manifest]);
4569
- deleteBundleFromR2(storage, pluginId, oldVersion, "registry").catch(() => {});
4570
- return {
4571
- success: true,
4572
- data: {
4573
- pluginId,
4574
- oldVersion,
4575
- newVersion,
4576
- capabilityChanges,
4577
- routeVisibilityChanges: hasNewPublicRoutes ? routeVisibilityChanges : void 0
4578
- }
4579
- };
4580
- } catch (err) {
4581
- if (err instanceof ClientValidationError) return {
4582
- success: false,
4583
- error: {
4584
- code: "AGGREGATOR_RESPONSE_INVALID",
4585
- message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4586
- }
4587
- };
4588
- if (err instanceof ClientResponseError) return {
4589
- success: false,
4590
- error: {
4591
- code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4592
- message: `Aggregator returned ${err.status}: ${err.error}`
4593
- }
4594
- };
4595
- if (err instanceof EmDashStorageError) return {
4596
- success: false,
4597
- error: {
4598
- code: err.code ?? "STORAGE_ERROR",
4599
- message: "Storage error while updating plugin"
4600
- }
4601
- };
4602
- console.error("[registry-update] Failed:", err);
4603
- return {
4604
- success: false,
4605
- error: {
4606
- code: "UPDATE_FAILED",
4607
- message: err instanceof Error ? err.message : "Failed to update plugin"
4608
- }
4609
- };
4610
- }
4611
- }
4612
- /**
4613
- * Bulk update check across every installed registry plugin. Queries the
4614
- * aggregator for each plugin's latest release and reports `hasUpdate`
4615
- * based on the version comparison. Plugins whose aggregator lookup fails
4616
- * (unreachable, delisted, malformed) are skipped silently — one bad
4617
- * publisher must not blank the whole admin Updates list.
4618
- */
4619
- async function handleRegistryUpdateCheck(db, registryConfigInput) {
4620
- const registryConfig = coerceRegistryConfig(registryConfigInput);
4621
- if (!registryConfig) return {
4622
- success: false,
4623
- error: {
4624
- code: "REGISTRY_NOT_CONFIGURED",
4625
- message: "Registry is not configured"
4626
- }
4627
- };
4628
- try {
4629
- const registryPlugins = await new PluginStateRepository(db).getRegistryPlugins();
4630
- if (registryPlugins.length === 0) return {
4631
- success: true,
4632
- data: { items: [] }
4633
- };
4634
- const { DiscoveryClient } = await import("@emdash-cms/registry-client/discovery");
4635
- const aggregatorDeadline = Date.now() + AGGREGATOR_TOTAL_BUDGET_MS;
4636
- const discovery = new DiscoveryClient({
4637
- aggregatorUrl: registryConfig.aggregatorUrl,
4638
- acceptLabelers: registryConfig.acceptLabelers,
4639
- fetch: timedFetch(aggregatorDeadline)
4640
- });
4641
- const items = [];
4642
- for (const plugin of registryPlugins) {
4643
- if (!plugin.registryPublisherDid || !plugin.registrySlug) continue;
4644
- try {
4645
- const latest = (await discovery.getLatestRelease({
4646
- did: plugin.registryPublisherDid,
4647
- package: plugin.registrySlug
4648
- })).version;
4649
- if (!latest) continue;
4650
- const installed = plugin.version;
4651
- items.push({
4652
- pluginId: plugin.pluginId,
4653
- installed,
4654
- latest,
4655
- hasUpdate: latest !== installed,
4656
- hasCapabilityChanges: false,
4657
- hasRouteVisibilityChanges: false
4658
- });
4659
- } catch (err) {
4660
- console.warn(`[registry-update-check] Skipped ${plugin.pluginId}:`, err);
4661
- }
4662
- }
4663
- return {
4664
- success: true,
4665
- data: { items }
4666
- };
4667
- } catch (err) {
4668
- if (err instanceof ClientValidationError) return {
4669
- success: false,
4670
- error: {
4671
- code: "AGGREGATOR_RESPONSE_INVALID",
4672
- message: `Aggregator returned a response that does not conform to its lexicon (${err.target})`
4673
- }
4674
- };
4675
- if (err instanceof ClientResponseError) return {
4676
- success: false,
4677
- error: {
4678
- code: err.status === 404 ? "AGGREGATOR_NOT_FOUND" : "AGGREGATOR_HTTP_ERROR",
4679
- message: `Aggregator returned ${err.status}: ${err.error}`
4680
- }
4681
- };
4682
- console.error("[registry-update-check] Failed:", err);
4683
- return {
4684
- success: false,
4685
- error: {
4686
- code: "UPDATE_CHECK_FAILED",
4687
- message: "Failed to check for registry updates"
4688
- }
4689
- };
4690
- }
4691
- }
4692
-
4693
- //#endregion
4694
- export { handleContentUnschedule as $, handleMediaUpdate as A, handleContentDelete as B, handlePluginEnable as C, handleMediaDelete as D, handleMediaCreate as E, handleContentAuthors as F, handleContentList as G, handleContentDuplicate as H, handleContentCompare as I, handleContentPublish as J, handleContentListTrashed as K, handleContentCountScheduled as L, handleRevisionList as M, handleRevisionRestore as N, handleMediaGet as O, generateManifest as P, handleContentUnpublish as Q, handleContentCountTrashed as R, handlePluginDisable as S, handlePluginList as T, handleContentGet as U, handleContentDiscardDraft as V, handleContentGetIncludingTrashed as W, handleContentSchedule as X, handleContentRestore as Y, handleContentTranslations as Z, loadBundleFromR2 as _, handleRegistryUpdateCheck as a, handlePluginSettingsGet as b, validateAggregatorUrl as c, handleMarketplaceSearch as d, handleContentUpdate as et, handleMarketplaceUninstall as f, handleThemeSearch as g, handleThemeGetDetail as h, handleRegistryUpdate as i, handleRevisionGet as j, handleMediaList as k, handleMarketplaceGetPlugin as l, handleMarketplaceUpdateCheck as m, handleRegistryInstall as n, coerceRegistryConfig as o, handleMarketplaceUpdate as p, handleContentPermanentDelete as q, handleRegistryUninstall as r, normalizeRegistryConfig as s, assertSafeArtifactUrl as t, validateRev as tt, handleMarketplaceInstall as u, syncDeclaredStorageIndexes as v, handlePluginGet as w, handlePluginSettingsUpdate as x, getPluginSettingsSchema as y, handleContentCreate as z };
4695
- //# sourceMappingURL=api-BeBglVxU.mjs.map