emdash 0.24.1 → 0.25.1

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 (340) hide show
  1. package/dist/api/route-utils.d.mts +2 -2
  2. package/dist/api/route-utils.mjs +9 -8
  3. package/dist/api/route-utils.mjs.map +1 -1
  4. package/dist/api/schemas/index.d.mts +1 -1
  5. package/dist/api/schemas/index.mjs +2 -2
  6. package/dist/{api-d_0wi9fW.mjs → api-D2_sbavn.mjs} +16 -12
  7. package/dist/api-D2_sbavn.mjs.map +1 -0
  8. package/dist/{apply-BE9UaWX0.mjs → apply-Bk2mAuLn.mjs} +11 -10
  9. package/dist/apply-Bk2mAuLn.mjs.map +1 -0
  10. package/dist/astro/index.d.mts +6 -6
  11. package/dist/astro/index.mjs +2 -2
  12. package/dist/astro/middleware/auth.d.mts +5 -5
  13. package/dist/astro/middleware/auth.mjs +1 -1
  14. package/dist/astro/middleware/redirect.mjs +2 -2
  15. package/dist/astro/middleware.d.mts.map +1 -1
  16. package/dist/astro/middleware.mjs +66 -37
  17. package/dist/astro/middleware.mjs.map +1 -1
  18. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +4 -4
  19. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +4 -4
  20. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +1 -1
  21. package/dist/astro/routes/api/admin/api-tokens/index.mjs +2 -2
  22. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +2 -2
  23. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +5 -5
  24. package/dist/astro/routes/api/admin/byline-fields/index.mjs +5 -5
  25. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +5 -5
  26. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +7 -7
  27. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +7 -7
  28. package/dist/astro/routes/api/admin/bylines/index.mjs +7 -7
  29. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +5 -5
  30. package/dist/astro/routes/api/admin/comments/_id_.mjs +2 -2
  31. package/dist/astro/routes/api/admin/comments/bulk.mjs +5 -5
  32. package/dist/astro/routes/api/admin/comments/counts.mjs +2 -2
  33. package/dist/astro/routes/api/admin/comments/index.mjs +5 -5
  34. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +3 -3
  35. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +2 -2
  36. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +2 -2
  37. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +2 -2
  38. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +20 -20
  39. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +20 -20
  40. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +20 -20
  41. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +20 -20
  42. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +20 -20
  43. package/dist/astro/routes/api/admin/plugins/index.mjs +20 -20
  44. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
  45. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +20 -20
  46. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +20 -20
  47. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +20 -20
  48. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +20 -20
  49. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +21 -21
  50. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +20 -20
  51. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +21 -21
  52. package/dist/astro/routes/api/admin/plugins/updates.mjs +20 -20
  53. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +20 -20
  54. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +2 -2
  55. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +20 -20
  56. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +1 -1
  57. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
  58. package/dist/astro/routes/api/admin/users/_id_/index.mjs +4 -4
  59. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +1 -1
  60. package/dist/astro/routes/api/admin/users/index.mjs +4 -4
  61. package/dist/astro/routes/api/auth/dev-bypass.mjs +1 -1
  62. package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
  63. package/dist/astro/routes/api/auth/invite/complete.mjs +4 -4
  64. package/dist/astro/routes/api/auth/invite/index.mjs +4 -4
  65. package/dist/astro/routes/api/auth/invite/register-options.mjs +4 -4
  66. package/dist/astro/routes/api/auth/logout.mjs +1 -1
  67. package/dist/astro/routes/api/auth/magic-link/send.mjs +5 -5
  68. package/dist/astro/routes/api/auth/magic-link/verify.mjs +1 -1
  69. package/dist/astro/routes/api/auth/me.mjs +4 -4
  70. package/dist/astro/routes/api/auth/passkey/_id_.mjs +4 -4
  71. package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
  72. package/dist/astro/routes/api/auth/passkey/options.mjs +5 -5
  73. package/dist/astro/routes/api/auth/passkey/register/options.mjs +4 -4
  74. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +4 -4
  75. package/dist/astro/routes/api/auth/passkey/verify.mjs +4 -4
  76. package/dist/astro/routes/api/auth/signup/complete.mjs +4 -4
  77. package/dist/astro/routes/api/auth/signup/request.mjs +5 -5
  78. package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
  79. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +4 -4
  80. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +4 -4
  81. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
  82. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +2 -2
  83. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +2 -2
  84. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
  85. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +5 -5
  86. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +5 -5
  87. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +2 -2
  88. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
  89. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +5 -5
  90. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +8 -8
  91. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
  92. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +2 -2
  93. package/dist/astro/routes/api/content/_collection_/_id_.mjs +5 -5
  94. package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
  95. package/dist/astro/routes/api/content/_collection_/index.mjs +5 -5
  96. package/dist/astro/routes/api/content/_collection_/trash.mjs +5 -5
  97. package/dist/astro/routes/api/dashboard.mjs +5 -5
  98. package/dist/astro/routes/api/dev/emails.mjs +1 -1
  99. package/dist/astro/routes/api/import/probe.mjs +5 -5
  100. package/dist/astro/routes/api/import/wordpress/analyze.mjs +2 -2
  101. package/dist/astro/routes/api/import/wordpress/execute.d.mts +5 -5
  102. package/dist/astro/routes/api/import/wordpress/execute.mjs +4 -4
  103. package/dist/astro/routes/api/import/wordpress/media.d.mts +13 -1
  104. package/dist/astro/routes/api/import/wordpress/media.d.mts.map +1 -1
  105. package/dist/astro/routes/api/import/wordpress/media.mjs +12 -8
  106. package/dist/astro/routes/api/import/wordpress/media.mjs.map +1 -1
  107. package/dist/astro/routes/api/import/wordpress/prepare.mjs +6 -6
  108. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +7 -7
  109. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +5 -5
  110. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +5 -5
  111. package/dist/astro/routes/api/manifest.mjs +2 -2
  112. package/dist/astro/routes/api/mcp.mjs +20 -20
  113. package/dist/astro/routes/api/media/_id_/confirm.d.mts.map +1 -1
  114. package/dist/astro/routes/api/media/_id_/confirm.mjs +43 -7
  115. package/dist/astro/routes/api/media/_id_/confirm.mjs.map +1 -1
  116. package/dist/astro/routes/api/media/_id_.mjs +5 -5
  117. package/dist/astro/routes/api/media/file/_...key_.mjs +1 -1
  118. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
  119. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
  120. package/dist/astro/routes/api/media/providers/index.mjs +2 -2
  121. package/dist/astro/routes/api/media/upload-url.mjs +7 -7
  122. package/dist/astro/routes/api/media.mjs +21 -20
  123. package/dist/astro/routes/api/media.mjs.map +1 -1
  124. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +5 -5
  125. package/dist/astro/routes/api/menus/_name_/items.mjs +5 -5
  126. package/dist/astro/routes/api/menus/_name_/reorder.mjs +5 -5
  127. package/dist/astro/routes/api/menus/_name_/translations.mjs +5 -5
  128. package/dist/astro/routes/api/menus/_name_.mjs +5 -5
  129. package/dist/astro/routes/api/menus/index.mjs +5 -5
  130. package/dist/astro/routes/api/oauth/device/authorize.mjs +2 -2
  131. package/dist/astro/routes/api/oauth/device/code.mjs +3 -3
  132. package/dist/astro/routes/api/oauth/device/token.mjs +3 -3
  133. package/dist/astro/routes/api/oauth/register.mjs +1 -1
  134. package/dist/astro/routes/api/oauth/token/refresh.mjs +2 -2
  135. package/dist/astro/routes/api/oauth/token/revoke.mjs +2 -2
  136. package/dist/astro/routes/api/oauth/token.mjs +1 -1
  137. package/dist/astro/routes/api/openapi.json.mjs +2 -2
  138. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +2 -2
  139. package/dist/astro/routes/api/redirects/404s/index.mjs +5 -5
  140. package/dist/astro/routes/api/redirects/404s/summary.mjs +5 -5
  141. package/dist/astro/routes/api/redirects/_id_.mjs +6 -6
  142. package/dist/astro/routes/api/redirects/index.mjs +6 -6
  143. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
  144. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +2 -2
  145. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +20 -20
  146. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +20 -20
  147. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +20 -20
  148. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +20 -20
  149. package/dist/astro/routes/api/schema/collections/index.mjs +20 -20
  150. package/dist/astro/routes/api/schema/index.mjs +3 -3
  151. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +20 -20
  152. package/dist/astro/routes/api/schema/orphans/index.mjs +20 -20
  153. package/dist/astro/routes/api/search/enable.mjs +7 -7
  154. package/dist/astro/routes/api/search/index.mjs +6 -6
  155. package/dist/astro/routes/api/search/rebuild.mjs +7 -7
  156. package/dist/astro/routes/api/search/stats.mjs +4 -4
  157. package/dist/astro/routes/api/search/suggest.mjs +6 -6
  158. package/dist/astro/routes/api/sections/_slug_.mjs +7 -7
  159. package/dist/astro/routes/api/sections/index.mjs +7 -7
  160. package/dist/astro/routes/api/settings/email.mjs +3 -3
  161. package/dist/astro/routes/api/settings.mjs +9 -9
  162. package/dist/astro/routes/api/setup/admin-verify.mjs +4 -4
  163. package/dist/astro/routes/api/setup/admin.mjs +4 -4
  164. package/dist/astro/routes/api/setup/dev-bypass.mjs +7 -7
  165. package/dist/astro/routes/api/setup/dev-reset.mjs +1 -1
  166. package/dist/astro/routes/api/setup/index.mjs +10 -10
  167. package/dist/astro/routes/api/setup/status.mjs +1 -1
  168. package/dist/astro/routes/api/snapshot.mjs +2 -2
  169. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +8 -8
  170. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +8 -8
  171. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +8 -8
  172. package/dist/astro/routes/api/taxonomies/index.mjs +8 -8
  173. package/dist/astro/routes/api/themes/preview.mjs +2 -2
  174. package/dist/astro/routes/api/typegen.mjs +3 -3
  175. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +5 -5
  176. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +7 -7
  177. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +7 -7
  178. package/dist/astro/routes/api/widget-areas/_name_.mjs +4 -4
  179. package/dist/astro/routes/api/widget-areas/index.mjs +7 -7
  180. package/dist/astro/routes/api/widget-components.mjs +1 -1
  181. package/dist/astro/routes/robots.txt.mjs +3 -3
  182. package/dist/astro/routes/sitemap-_collection_.xml.mjs +4 -4
  183. package/dist/astro/routes/sitemap.xml.mjs +4 -4
  184. package/dist/astro/types.d.mts +7 -7
  185. package/dist/{authorize-B__u-iZJ.mjs → authorize-CuxZ0i2t.mjs} +2 -2
  186. package/dist/{authorize-B__u-iZJ.mjs.map → authorize-CuxZ0i2t.mjs.map} +1 -1
  187. package/dist/{byline-fields-Ca56gaT6.d.mts → byline-fields-KD3JFRuH.d.mts} +24 -6
  188. package/dist/byline-fields-KD3JFRuH.d.mts.map +1 -0
  189. package/dist/{byline-fields-B-KXkg5R.mjs → byline-fields-eyJMblSr.mjs} +2 -2
  190. package/dist/{byline-fields-B-KXkg5R.mjs.map → byline-fields-eyJMblSr.mjs.map} +1 -1
  191. package/dist/{bylines-BMtJnPnG.mjs → bylines-CPc_q2Vd.mjs} +4 -4
  192. package/dist/{bylines-BMtJnPnG.mjs.map → bylines-CPc_q2Vd.mjs.map} +1 -1
  193. package/dist/{cache-BUJe2w6Z.mjs → cache-C35VWD5D.mjs} +1 -1
  194. package/dist/{cache-BUJe2w6Z.mjs.map → cache-C35VWD5D.mjs.map} +1 -1
  195. package/dist/cli/index.mjs +8 -8
  196. package/dist/{content-PoVGKjp0.mjs → content-B43-YrIq.mjs} +7 -5
  197. package/dist/content-B43-YrIq.mjs.map +1 -0
  198. package/dist/{context-Dvws41_A.mjs → context-BW3N7wyt.mjs} +12 -6
  199. package/dist/context-BW3N7wyt.mjs.map +1 -0
  200. package/dist/{dashboard-DsYU8JKS.mjs → dashboard-FIe0S512.mjs} +3 -3
  201. package/dist/{dashboard-DsYU8JKS.mjs.map → dashboard-FIe0S512.mjs.map} +1 -1
  202. package/dist/{db-errors-UXB1CK42.mjs → db-errors-CK46D-ly.mjs} +1 -1
  203. package/dist/{db-errors-UXB1CK42.mjs.map → db-errors-CK46D-ly.mjs.map} +1 -1
  204. package/dist/{placeholder-B0s2mWu5.mjs → enrich-BQ0mxJRs.mjs} +61 -10
  205. package/dist/enrich-BQ0mxJRs.mjs.map +1 -0
  206. package/dist/{error-lq_fL-RS.mjs → error-DXnK2wF4.mjs} +2 -1
  207. package/dist/error-DXnK2wF4.mjs.map +1 -0
  208. package/dist/{index-BroXT-vD.d.mts → index-Cz6_JBL3.d.mts} +21 -8
  209. package/dist/index-Cz6_JBL3.d.mts.map +1 -0
  210. package/dist/index.d.mts +8 -8
  211. package/dist/index.mjs +28 -28
  212. package/dist/{loader-BR2SgfEc.mjs → loader-DrpofRon.mjs} +2 -2
  213. package/dist/{loader-BR2SgfEc.mjs.map → loader-DrpofRon.mjs.map} +1 -1
  214. package/dist/{manifest-schema-BWKnQYQF.mjs → manifest-schema-BOfPXse0.mjs} +2 -1
  215. package/dist/manifest-schema-BOfPXse0.mjs.map +1 -0
  216. package/dist/media/image-endpoint.mjs +1 -1
  217. package/dist/media/index.d.mts +45 -2
  218. package/dist/media/index.d.mts.map +1 -1
  219. package/dist/media/index.mjs +5 -3
  220. package/dist/media/index.mjs.map +1 -1
  221. package/dist/media/local-runtime.d.mts +6 -6
  222. package/dist/media/local-runtime.d.mts.map +1 -1
  223. package/dist/media/local-runtime.mjs +15 -3
  224. package/dist/media/local-runtime.mjs.map +1 -1
  225. package/dist/{media-CTjJoJTh.mjs → media-BjKxjzk8.mjs} +3 -1
  226. package/dist/media-BjKxjzk8.mjs.map +1 -0
  227. package/dist/{media-allowlist-B77I5_bw.mjs → media-allowlist-Du8t1u6a.mjs} +2 -2
  228. package/dist/{media-allowlist-B77I5_bw.mjs.map → media-allowlist-Du8t1u6a.mjs.map} +1 -1
  229. package/dist/{menus-GvRSpgIA.mjs → menus-CxqJ-z-N.mjs} +46 -4
  230. package/dist/menus-CxqJ-z-N.mjs.map +1 -0
  231. package/dist/{mime-BTzvzJ8M.mjs → mime-CCEzze7W.mjs} +1 -1
  232. package/dist/{mime-BTzvzJ8M.mjs.map → mime-CCEzze7W.mjs.map} +1 -1
  233. package/dist/{normalize-ClbNIenm.mjs → normalize-CeglrBT9.mjs} +11 -2
  234. package/dist/normalize-CeglrBT9.mjs.map +1 -0
  235. package/dist/{options-CqECG0gM.d.mts → options-BvClpP5Q.d.mts} +2 -2
  236. package/dist/{options-CqECG0gM.d.mts.map → options-BvClpP5Q.d.mts.map} +1 -1
  237. package/dist/page/index.d.mts +1 -1
  238. package/dist/{parse-DHI873qU.mjs → parse-DqMWHQ8x.mjs} +2 -2
  239. package/dist/{parse-DHI873qU.mjs.map → parse-DqMWHQ8x.mjs.map} +1 -1
  240. package/dist/{placeholder-QoI4gEzP.d.mts → placeholder-Cuce9U-m.d.mts} +20 -5
  241. package/dist/placeholder-Cuce9U-m.d.mts.map +1 -0
  242. package/dist/plugin-types.d.mts +2 -1
  243. package/dist/plugin-types.d.mts.map +1 -1
  244. package/dist/plugin-utils.d.mts +5 -5
  245. package/dist/plugins/adapt-sandbox-entry.d.mts +5 -5
  246. package/dist/plugins/adapt-sandbox-entry.mjs +1 -1
  247. package/dist/{query-DZdlS6Cu.mjs → query-34pfm02Q.mjs} +11 -11
  248. package/dist/{query-DZdlS6Cu.mjs.map → query-34pfm02Q.mjs.map} +1 -1
  249. package/dist/{rate-limit-D1Y6VFVP.mjs → rate-limit-CBQK4ygJ.mjs} +2 -2
  250. package/dist/{rate-limit-D1Y6VFVP.mjs.map → rate-limit-CBQK4ygJ.mjs.map} +1 -1
  251. package/dist/{redirects-x9eFPeyi.mjs → redirects-Dcbuisoj.mjs} +2 -1
  252. package/dist/redirects-Dcbuisoj.mjs.map +1 -0
  253. package/dist/{registry-CJkCubOJ.mjs → registry-3aOAS4My.mjs} +11 -1
  254. package/dist/registry-3aOAS4My.mjs.map +1 -0
  255. package/dist/runtime.d.mts +6 -6
  256. package/dist/runtime.mjs +1 -1
  257. package/dist/{schema-DMjXuvNU.mjs → schema-BGwx8AQY.mjs} +3 -3
  258. package/dist/{schema-DMjXuvNU.mjs.map → schema-BGwx8AQY.mjs.map} +1 -1
  259. package/dist/{search-D1wKk3lc.mjs → search-Gl747zMP.mjs} +2 -2
  260. package/dist/{search-D1wKk3lc.mjs.map → search-Gl747zMP.mjs.map} +1 -1
  261. package/dist/{sections-CCMic8dB.mjs → sections-C-umuuLj.mjs} +2 -2
  262. package/dist/{sections-CCMic8dB.mjs.map → sections-C-umuuLj.mjs.map} +1 -1
  263. package/dist/seed/index.d.mts +1 -1
  264. package/dist/seed/index.mjs +6 -6
  265. package/dist/seo/index.d.mts +1 -1
  266. package/dist/{seo-3QrZ1EPT.mjs → seo-BNzkiK_W.mjs} +1 -1
  267. package/dist/{seo-3QrZ1EPT.mjs.map → seo-BNzkiK_W.mjs.map} +1 -1
  268. package/dist/{seo-DCEF-AVr.mjs → seo-BkhuuaaE.mjs} +25 -3
  269. package/dist/seo-BkhuuaaE.mjs.map +1 -0
  270. package/dist/{settings-D9rvaLuY.mjs → settings-C4tXRYiG.mjs} +3 -3
  271. package/dist/{settings-D9rvaLuY.mjs.map → settings-C4tXRYiG.mjs.map} +1 -1
  272. package/dist/{settings-C3Yi5Co3.mjs → settings-fPSR6dJa.mjs} +2 -2
  273. package/dist/{settings-C3Yi5Co3.mjs.map → settings-fPSR6dJa.mjs.map} +1 -1
  274. package/dist/{taxonomies-DhLaNJji.mjs → taxonomies-DbAtL6m4.mjs} +2 -2
  275. package/dist/{taxonomies-DhLaNJji.mjs.map → taxonomies-DbAtL6m4.mjs.map} +1 -1
  276. package/dist/{taxonomies-CurpLtNC.mjs → taxonomies-n8w72lLQ.mjs} +4 -4
  277. package/dist/{taxonomies-CurpLtNC.mjs.map → taxonomies-n8w72lLQ.mjs.map} +1 -1
  278. package/dist/{types-CTLJYMhN.d.mts → types-CNlaBFzx.d.mts} +11 -1
  279. package/dist/{types-CTLJYMhN.d.mts.map → types-CNlaBFzx.d.mts.map} +1 -1
  280. package/dist/{types-BWh2MjmA.d.mts → types-ETmO_jQr.d.mts} +2 -2
  281. package/dist/{types-BWh2MjmA.d.mts.map → types-ETmO_jQr.d.mts.map} +1 -1
  282. package/dist/{types-TTx8uP7V.d.mts → types-h2Cwbzi2.d.mts} +6 -3
  283. package/dist/{types-TTx8uP7V.d.mts.map → types-h2Cwbzi2.d.mts.map} +1 -1
  284. package/dist/types-tM44hEcf.mjs.map +1 -1
  285. package/dist/{validate-DOFrIb-c.d.mts → validate-Va_An3qb.d.mts} +2 -2
  286. package/dist/{validate-DOFrIb-c.d.mts.map → validate-Va_An3qb.d.mts.map} +1 -1
  287. package/dist/{validation-CY1gk4Ar.mjs → validation-B6DKPTtU.mjs} +3 -3
  288. package/dist/{validation-CY1gk4Ar.mjs.map → validation-B6DKPTtU.mjs.map} +1 -1
  289. package/dist/version-DHdCA24u.mjs +7 -0
  290. package/dist/{version-C0JPFUG8.mjs.map → version-DHdCA24u.mjs.map} +1 -1
  291. package/dist/{widgets-Dri0spI4.mjs → widgets-C2RbFN0G.mjs} +2 -2
  292. package/dist/{widgets-Dri0spI4.mjs.map → widgets-C2RbFN0G.mjs.map} +1 -1
  293. package/package.json +6 -6
  294. package/src/api/errors.ts +1 -0
  295. package/src/api/handlers/content.ts +4 -4
  296. package/src/api/handlers/seo.ts +30 -2
  297. package/src/api/schemas/schema.ts +1 -0
  298. package/src/astro/middleware.ts +14 -1
  299. package/src/astro/routes/api/import/wordpress/media.ts +9 -3
  300. package/src/astro/routes/api/media/[id]/confirm.ts +62 -2
  301. package/src/astro/routes/api/media.ts +17 -19
  302. package/src/components/EmDashImage.astro +4 -7
  303. package/src/components/Image.astro +14 -4
  304. package/src/components/InlinePortableTextEditor.tsx +48 -1
  305. package/src/database/repositories/content.ts +8 -5
  306. package/src/database/repositories/media.ts +9 -1
  307. package/src/emdash-runtime.ts +39 -1
  308. package/src/media/enrich.ts +78 -0
  309. package/src/media/index.ts +1 -0
  310. package/src/media/local-runtime.ts +19 -0
  311. package/src/media/normalize.ts +20 -1
  312. package/src/media/placeholder.ts +29 -9
  313. package/src/media/types.ts +14 -0
  314. package/src/plugin-types.ts +2 -0
  315. package/src/plugins/context.ts +8 -0
  316. package/src/plugins/hooks.ts +45 -0
  317. package/src/plugins/index.ts +1 -0
  318. package/src/plugins/manager.ts +11 -0
  319. package/src/plugins/manifest-schema.ts +1 -0
  320. package/src/plugins/types.ts +7 -0
  321. package/src/schema/registry.ts +25 -0
  322. package/src/schema/types.ts +10 -0
  323. package/src/seed/apply.ts +1 -0
  324. package/dist/api-d_0wi9fW.mjs.map +0 -1
  325. package/dist/apply-BE9UaWX0.mjs.map +0 -1
  326. package/dist/byline-fields-Ca56gaT6.d.mts.map +0 -1
  327. package/dist/content-PoVGKjp0.mjs.map +0 -1
  328. package/dist/context-Dvws41_A.mjs.map +0 -1
  329. package/dist/error-lq_fL-RS.mjs.map +0 -1
  330. package/dist/index-BroXT-vD.d.mts.map +0 -1
  331. package/dist/manifest-schema-BWKnQYQF.mjs.map +0 -1
  332. package/dist/media-CTjJoJTh.mjs.map +0 -1
  333. package/dist/menus-GvRSpgIA.mjs.map +0 -1
  334. package/dist/normalize-ClbNIenm.mjs.map +0 -1
  335. package/dist/placeholder-B0s2mWu5.mjs.map +0 -1
  336. package/dist/placeholder-QoI4gEzP.d.mts.map +0 -1
  337. package/dist/redirects-x9eFPeyi.mjs.map +0 -1
  338. package/dist/registry-CJkCubOJ.mjs.map +0 -1
  339. package/dist/seo-DCEF-AVr.mjs.map +0 -1
  340. package/dist/version-C0JPFUG8.mjs +0 -7
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-BW3N7wyt.mjs","names":[],"sources":["../src/plugins/storage-query.ts","../src/database/repositories/plugin-storage.ts","../src/plugins/context.ts"],"sourcesContent":["/**\n * Plugin Storage Query Validation and Building\n *\n * Validates that queries only use indexed fields and builds SQL WHERE clauses.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Query Validation\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { jsonExtractExpr } from \"../database/dialect-helpers.js\";\nimport { validateJsonFieldName } from \"../database/validate.js\";\nimport type { WhereClause, WhereValue, RangeFilter, InFilter, StartsWithFilter } from \"./types.js\";\n\n/**\n * Error thrown when querying non-indexed fields\n */\nexport class StorageQueryError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\tpublic field?: string,\n\t\tpublic suggestion?: string,\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"StorageQueryError\";\n\t}\n}\n\n/**\n * Check if a value is a range filter\n */\nexport function isRangeFilter(value: WhereValue): value is RangeFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"gt\" in value || \"gte\" in value || \"lt\" in value || \"lte\" in value;\n}\n\n/**\n * Check if a value is an IN filter\n */\nexport function isInFilter(value: WhereValue): value is InFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"in\" in value && Array.isArray(value.in);\n}\n\n/**\n * Check if a value is a startsWith filter\n */\nexport function isStartsWithFilter(value: WhereValue): value is StartsWithFilter {\n\tif (typeof value !== \"object\" || value === null) return false;\n\treturn \"startsWith\" in value && typeof value.startsWith === \"string\";\n}\n\n/**\n * Get the set of indexed fields from index declarations\n */\nexport function getIndexedFields(indexes: Array<string | string[]>): Set<string> {\n\tconst fields = new Set<string>();\n\tfor (const index of indexes) {\n\t\tif (Array.isArray(index)) {\n\t\t\tfor (const field of index) {\n\t\t\t\tfields.add(field);\n\t\t\t}\n\t\t} else {\n\t\t\tfields.add(index);\n\t\t}\n\t}\n\treturn fields;\n}\n\n/**\n * Validate that all fields in a where clause are indexed\n */\nexport function validateWhereClause(\n\twhere: WhereClause,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(where)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot query on non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable this query.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Validate orderBy fields are indexed\n */\nexport function validateOrderByClause(\n\torderBy: Record<string, \"asc\" | \"desc\">,\n\tindexedFields: Set<string>,\n\tpluginId: string,\n\tcollection: string,\n): void {\n\tfor (const field of Object.keys(orderBy)) {\n\t\tif (!indexedFields.has(field)) {\n\t\t\tthrow new StorageQueryError(\n\t\t\t\t`Cannot order by non-indexed field '${field}'.`,\n\t\t\t\tfield,\n\t\t\t\t`Add '${field}' to storage.${collection}.indexes in plugin '${pluginId}' to enable ordering by this field.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * SQL expression for extracting JSON field.\n *\n * Validates the field name before interpolation to prevent SQL injection\n * via crafted JSON path expressions.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtract(db: Kysely<any>, field: string): string {\n\tvalidateJsonFieldName(field, \"query field name\");\n\treturn jsonExtractExpr(db, \"data\", field);\n}\n\n/**\n * Build a WHERE clause condition for a single field\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildCondition(\n\tdb: Kysely<any>,\n\tfield: string,\n\tvalue: WhereValue,\n): { sql: string; params: unknown[] } {\n\tconst extract = jsonExtract(db, field);\n\n\tif (value === null) {\n\t\treturn { sql: `${extract} IS NULL`, params: [] };\n\t}\n\n\tif (typeof value === \"string\" || typeof value === \"number\") {\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (typeof value === \"boolean\") {\n\t\t// JSON booleans are stored as true/false strings\n\t\treturn { sql: `${extract} = ?`, params: [value] };\n\t}\n\n\tif (isInFilter(value)) {\n\t\tconst placeholders = value.in.map(() => \"?\").join(\", \");\n\t\treturn {\n\t\t\tsql: `${extract} IN (${placeholders})`,\n\t\t\tparams: value.in,\n\t\t};\n\t}\n\n\tif (isStartsWithFilter(value)) {\n\t\treturn {\n\t\t\tsql: `${extract} LIKE ?`,\n\t\t\tparams: [`${value.startsWith}%`],\n\t\t};\n\t}\n\n\tif (isRangeFilter(value)) {\n\t\tconst conditions: string[] = [];\n\t\tconst params: unknown[] = [];\n\n\t\tif (value.gt !== undefined) {\n\t\t\tconditions.push(`${extract} > ?`);\n\t\t\tparams.push(value.gt);\n\t\t}\n\t\tif (value.gte !== undefined) {\n\t\t\tconditions.push(`${extract} >= ?`);\n\t\t\tparams.push(value.gte);\n\t\t}\n\t\tif (value.lt !== undefined) {\n\t\t\tconditions.push(`${extract} < ?`);\n\t\t\tparams.push(value.lt);\n\t\t}\n\t\tif (value.lte !== undefined) {\n\t\t\tconditions.push(`${extract} <= ?`);\n\t\t\tparams.push(value.lte);\n\t\t}\n\n\t\treturn {\n\t\t\tsql: conditions.join(\" AND \"),\n\t\t\tparams,\n\t\t};\n\t}\n\n\tthrow new StorageQueryError(`Unknown filter type for field '${field}'`);\n}\n\n/**\n * Build a complete WHERE clause from a WhereClause object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildWhereClause(\n\tdb: Kysely<any>,\n\twhere: WhereClause,\n): {\n\tsql: string;\n\tparams: unknown[];\n} {\n\tconst conditions: string[] = [];\n\tconst params: unknown[] = [];\n\n\tfor (const [field, value] of Object.entries(where)) {\n\t\tconst condition = buildCondition(db, field, value);\n\t\tconditions.push(condition.sql);\n\t\tparams.push(...condition.params);\n\t}\n\n\tif (conditions.length === 0) {\n\t\treturn { sql: \"\", params: [] };\n\t}\n\n\treturn {\n\t\tsql: conditions.join(\" AND \"),\n\t\tparams,\n\t};\n}\n\n/**\n * Build ORDER BY clause\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildOrderByClause(\n\tdb: Kysely<any>,\n\torderBy: Record<string, \"asc\" | \"desc\">,\n): string {\n\tconst clauses: string[] = [];\n\n\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\tclauses.push(`${jsonExtract(db, field)} ${direction.toUpperCase()}`);\n\t}\n\n\tif (clauses.length === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn `ORDER BY ${clauses.join(\", \")}`;\n}\n","/**\n * Plugin Storage Repository\n *\n * Provides a document store API for plugin data storage.\n * Uses a single _plugin_storage table with JSON documents and expression indexes.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage > Full API Reference\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport {\n\tbuildWhereClause,\n\tvalidateWhereClause,\n\tvalidateOrderByClause,\n\tgetIndexedFields,\n\tjsonExtract,\n} from \"../../plugins/storage-query.js\";\nimport type {\n\tStorageCollection,\n\tQueryOptions,\n\tPaginatedResult,\n\tWhereClause,\n} from \"../../plugins/types.js\";\nimport { withTransaction } from \"../transaction.js\";\nimport type { Database } from \"../types.js\";\nimport { encodeCursor, decodeCursor } from \"./types.js\";\n\n/**\n * Plugin Storage Repository\n *\n * Implements the StorageCollection interface for a specific plugin and collection.\n */\nexport class PluginStorageRepository<T = unknown> implements StorageCollection<T> {\n\tprivate indexedFields: Set<string>;\n\n\tconstructor(\n\t\tprivate db: Kysely<Database>,\n\t\tprivate pluginId: string,\n\t\tprivate collection: string,\n\t\tindexes: Array<string | string[]>,\n\t) {\n\t\tthis.indexedFields = getIndexedFields(indexes);\n\t}\n\n\t/**\n\t * Get a document by ID\n\t */\n\tasync get(id: string): Promise<T | null> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"data\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) return null;\n\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\treturn JSON.parse(row.data) as T;\n\t}\n\n\t/**\n\t * Store a document\n\t */\n\tasync put(id: string, data: T): Promise<void> {\n\t\tconst now = new Date().toISOString();\n\t\tconst jsonData = JSON.stringify(data);\n\n\t\tawait this.db\n\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t.values({\n\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\tcollection: this.collection,\n\t\t\t\tid,\n\t\t\t\tdata: jsonData,\n\t\t\t\tcreated_at: now,\n\t\t\t\tupdated_at: now,\n\t\t\t})\n\t\t\t.onConflict((oc) =>\n\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\tdata: jsonData,\n\t\t\t\t\tupdated_at: now,\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Delete a document\n\t */\n\tasync delete(id: string): Promise<boolean> {\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn (result.numDeletedRows ?? 0) > 0;\n\t}\n\n\t/**\n\t * Check if a document exists\n\t */\n\tasync exists(id: string): Promise<boolean> {\n\t\tconst row = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"=\", id)\n\t\t\t.executeTakeFirst();\n\n\t\treturn !!row;\n\t}\n\n\t/**\n\t * Get multiple documents by ID\n\t */\n\tasync getMany(ids: string[]): Promise<Map<string, T>> {\n\t\tif (ids.length === 0) return new Map();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.execute();\n\n\t\tconst result = new Map<string, T>();\n\t\tfor (const row of rows) {\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tresult.set(row.id, JSON.parse(row.data) as T);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Store multiple documents\n\t */\n\tasync putMany(items: Array<{ id: string; data: T }>): Promise<void> {\n\t\tif (items.length === 0) return;\n\n\t\tconst now = new Date().toISOString();\n\n\t\t// SQLite doesn't support batch upserts well, so we do them one at a time\n\t\t// In a transaction for atomicity\n\t\tawait withTransaction(this.db, async (trx) => {\n\t\t\tfor (const item of items) {\n\t\t\t\tconst jsonData = JSON.stringify(item.data);\n\t\t\t\tawait trx\n\t\t\t\t\t.insertInto(\"_plugin_storage\")\n\t\t\t\t\t.values({\n\t\t\t\t\t\tplugin_id: this.pluginId,\n\t\t\t\t\t\tcollection: this.collection,\n\t\t\t\t\t\tid: item.id,\n\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t})\n\t\t\t\t\t.onConflict((oc) =>\n\t\t\t\t\t\toc.columns([\"plugin_id\", \"collection\", \"id\"]).doUpdateSet({\n\t\t\t\t\t\t\tdata: jsonData,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.execute();\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Delete multiple documents\n\t */\n\tasync deleteMany(ids: string[]): Promise<number> {\n\t\tif (ids.length === 0) return 0;\n\n\t\tconst result = await this.db\n\t\t\t.deleteFrom(\"_plugin_storage\")\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection)\n\t\t\t.where(\"id\", \"in\", ids)\n\t\t\t.executeTakeFirst();\n\n\t\treturn Number(result.numDeletedRows ?? 0);\n\t}\n\n\t/**\n\t * Query documents with filters\n\t */\n\tasync query(options: QueryOptions = {}): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\tconst { where = {}, orderBy = {}, cursor } = options;\n\t\tconst limit = Math.min(options.limit ?? 50, 100);\n\n\t\t// Validate that all queried fields are indexed\n\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tvalidateOrderByClause(orderBy, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\t// Build base query\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select([\"id\", \"data\", \"created_at\"])\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\tif (whereResult.sql) {\n\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\tlet paramIndex = 0;\n\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\tif (i > 0) {\n\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t}\n\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t}\n\t\t\t}\n\t\t\tquery = query.where(({ eb }) => eb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")));\n\t\t}\n\n\t\t// Handle cursor-based pagination — throws on invalid cursor.\n\t\tif (cursor) {\n\t\t\tconst decoded = decodeCursor(cursor);\n\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\teb(sql`(created_at, id)`, \">\", sql`(${decoded.orderValue}, ${decoded.id})`),\n\t\t\t);\n\t\t}\n\n\t\t// Build ORDER BY using sql template\n\t\tif (Object.keys(orderBy).length > 0) {\n\t\t\tfor (const [field, direction] of Object.entries(orderBy)) {\n\t\t\t\tconst extract = jsonExtract(this.db, field);\n\t\t\t\tconst orderExpr =\n\t\t\t\t\tdirection === \"desc\" ? sql`${sql.raw(extract)} desc` : sql`${sql.raw(extract)} asc`;\n\t\t\t\tquery = query.orderBy(orderExpr);\n\t\t\t}\n\t\t} else {\n\t\t\t// Default ordering for consistent pagination\n\t\t\tquery = query.orderBy(\"created_at\", \"asc\").orderBy(\"id\", \"asc\");\n\t\t}\n\n\t\t// Apply limit (fetch one extra to detect if there's more)\n\t\tquery = query.limit(limit + 1);\n\n\t\tconst rows = await query.execute();\n\n\t\tconst hasMore = rows.length > limit;\n\t\tconst items = rows.slice(0, limit).map((row) => ({\n\t\t\tid: row.id,\n\t\t\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- JSON.parse returns any; generic callers provide T\n\t\t\tdata: JSON.parse(row.data) as T,\n\t\t}));\n\n\t\t// Generate cursor for next page if there are more results\n\t\tlet nextCursor: string | undefined;\n\t\tif (hasMore) {\n\t\t\tconst lastItem = rows[limit - 1];\n\t\t\tif (lastItem) {\n\t\t\t\tnextCursor = encodeCursor(lastItem.created_at, lastItem.id);\n\t\t\t}\n\t\t}\n\n\t\treturn { items, cursor: nextCursor, hasMore };\n\t}\n\n\t/**\n\t * Count documents matching a filter\n\t */\n\tasync count(where?: WhereClause): Promise<number> {\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tvalidateWhereClause(where, this.indexedFields, this.pluginId, this.collection);\n\t\t}\n\n\t\tlet query = this.db\n\t\t\t.selectFrom(\"_plugin_storage\")\n\t\t\t.select(sql<number>`COUNT(*)`.as(\"count\"))\n\t\t\t.where(\"plugin_id\", \"=\", this.pluginId)\n\t\t\t.where(\"collection\", \"=\", this.collection);\n\n\t\t// Add JSON extraction WHERE conditions\n\t\tif (where && Object.keys(where).length > 0) {\n\t\t\tconst whereResult = buildWhereClause(this.db, where);\n\t\t\tif (whereResult.sql) {\n\t\t\t\t// Use sql template to add the raw WHERE conditions with params\n\t\t\t\tconst whereSqlParts: ReturnType<typeof sql>[] = [];\n\t\t\t\tlet paramIndex = 0;\n\t\t\t\tconst sqlParts = whereResult.sql.split(\"?\");\n\t\t\t\tfor (let i = 0; i < sqlParts.length; i++) {\n\t\t\t\t\tif (i > 0) {\n\t\t\t\t\t\twhereSqlParts.push(sql`${whereResult.params[paramIndex++]}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (sqlParts[i]) {\n\t\t\t\t\t\twhereSqlParts.push(sql.raw(sqlParts[i]));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tquery = query.where(({ eb }) =>\n\t\t\t\t\teb(sql.join(whereSqlParts, sql.raw(\"\")), \"=\", sql.raw(\"1\")),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn result?.count ?? 0;\n\t}\n}\n\n/**\n * Create a scoped storage accessor for a plugin\n */\nexport function createPluginStorageAccessor(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: Record<\n\t\tstring,\n\t\t{ indexes: Array<string | string[]>; uniqueIndexes?: Array<string | string[]> }\n\t>,\n): Record<string, StorageCollection> {\n\tconst accessor: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\taccessor[collectionName] = new PluginStorageRepository(\n\t\t\tdb,\n\t\t\tpluginId,\n\t\t\tcollectionName,\n\t\t\tallIndexes,\n\t\t);\n\t}\n\n\treturn accessor;\n}\n\n/**\n * Delete all storage data for a plugin\n */\nexport async function deleteAllPluginStorage(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n\n/**\n * Delete all storage data for a plugin collection\n */\nexport async function deletePluginCollection(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollection: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.deleteFrom(\"_plugin_storage\")\n\t\t.where(\"plugin_id\", \"=\", pluginId)\n\t\t.where(\"collection\", \"=\", collection)\n\t\t.executeTakeFirst();\n\n\treturn Number(result.numDeletedRows ?? 0);\n}\n","/**\n * Plugin Context v2\n *\n * Creates the unified context object provided to plugins in all hooks and routes.\n *\n */\n\nimport type { Kysely } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport { ContentRepository } from \"../database/repositories/content.js\";\nimport { MediaRepository } from \"../database/repositories/media.js\";\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport { PluginStorageRepository } from \"../database/repositories/plugin-storage.js\";\nimport { SeoRepository } from \"../database/repositories/seo.js\";\nimport { UserRepository } from \"../database/repositories/user.js\";\nimport { withTransaction } from \"../database/transaction.js\";\nimport type { Database } from \"../database/types.js\";\nimport {\n\tresolveAndValidateExternalUrl,\n\tSsrfError,\n\tstripCredentialHeaders,\n} from \"../import/ssrf.js\";\nimport { enrichImageMetadata } from \"../media/enrich.js\";\nimport { invalidateSiteSettingsCache } from \"../settings/index.js\";\nimport type { Storage } from \"../storage/types.js\";\nimport { CronAccessImpl } from \"./cron.js\";\nimport type { EmailPipeline } from \"./email.js\";\nimport type {\n\tResolvedPlugin,\n\tPluginContext,\n\tPluginStorageConfig,\n\tStorageCollection,\n\tKVAccess,\n\tCronAccess,\n\tEmailAccess,\n\tContentAccess,\n\tContentAccessWithWrite,\n\tMediaAccess,\n\tMediaAccessWithWrite,\n\tHttpAccess,\n\tLogAccess,\n\tSiteInfo,\n\tUserAccess,\n\tUserInfo,\n\tContentItem,\n\tContentItemSeoInput,\n\tContentWriteInput,\n\tMediaItem,\n\tPaginatedResult,\n\tQueryOptions,\n\tContentListOptions,\n\tMediaListOptions,\n} from \"./types.js\";\n\n// =============================================================================\n// KV Access\n// =============================================================================\n\n/**\n * Create KV accessor for a plugin\n * All keys are automatically prefixed with the plugin ID\n */\nexport function createKVAccess(optionsRepo: OptionsRepository, pluginId: string): KVAccess {\n\tconst prefix = `plugin:${pluginId}:`;\n\n\treturn {\n\t\tasync get<T>(key: string): Promise<T | null> {\n\t\t\treturn optionsRepo.get<T>(`${prefix}${key}`);\n\t\t},\n\n\t\tasync set(key: string, value: unknown): Promise<void> {\n\t\t\tawait optionsRepo.set(`${prefix}${key}`, value);\n\t\t},\n\n\t\tasync delete(key: string): Promise<boolean> {\n\t\t\treturn optionsRepo.delete(`${prefix}${key}`);\n\t\t},\n\n\t\tasync list(keyPrefix?: string): Promise<Array<{ key: string; value: unknown }>> {\n\t\t\tconst fullPrefix = `${prefix}${keyPrefix ?? \"\"}`;\n\t\t\tconst entriesMap = await optionsRepo.getByPrefix(fullPrefix);\n\t\t\tconst result: Array<{ key: string; value: unknown }> = [];\n\t\t\tfor (const [fullKey, value] of entriesMap) {\n\t\t\t\tresult.push({\n\t\t\t\t\tkey: fullKey.slice(prefix.length),\n\t\t\t\t\tvalue,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Storage Access\n// =============================================================================\n\n/**\n * Create storage collection accessor for a plugin\n * Wraps PluginStorageRepository with the v2 interface (no async iterators)\n */\nfunction createStorageCollection<T>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tcollectionName: string,\n\tindexes: Array<string | string[]>,\n): StorageCollection<T> {\n\tconst repo = new PluginStorageRepository<T>(db, pluginId, collectionName, indexes);\n\n\treturn {\n\t\tget: (id) => repo.get(id),\n\t\tput: (id, data) => repo.put(id, data),\n\t\tdelete: (id) => repo.delete(id),\n\t\texists: (id) => repo.exists(id),\n\t\tgetMany: (ids) => repo.getMany(ids),\n\t\tputMany: (items) => repo.putMany(items),\n\t\tdeleteMany: (ids) => repo.deleteMany(ids),\n\t\tcount: (where) => repo.count(where),\n\n\t\t// Query returns PaginatedResult instead of the old format\n\t\tasync query(options?: QueryOptions): Promise<PaginatedResult<{ id: string; data: T }>> {\n\t\t\tconst result = await repo.query({\n\t\t\t\twhere: options?.where,\n\t\t\t\torderBy: options?.orderBy,\n\t\t\t\tlimit: options?.limit,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items,\n\t\t\t\tcursor: result.cursor,\n\t\t\t\thasMore: result.hasMore,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create storage accessor with all declared collections\n */\nexport function createStorageAccess<T extends PluginStorageConfig>(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tstorageConfig: T,\n): Record<string, StorageCollection> {\n\tconst storage: Record<string, StorageCollection> = {};\n\n\tfor (const [collectionName, config] of Object.entries(storageConfig)) {\n\t\tconst allIndexes = [...config.indexes, ...(config.uniqueIndexes ?? [])];\n\t\tstorage[collectionName] = createStorageCollection(db, pluginId, collectionName, allIndexes);\n\t}\n\n\treturn storage;\n}\n\n// =============================================================================\n// Content Access\n// =============================================================================\n\n/**\n * Extract `seo` from a plugin-supplied content write input and return both\n * parts. Mutates nothing — returns a new field map without the `seo` key.\n */\nfunction splitSeoFromInput(input: ContentWriteInput): {\n\tfields: Record<string, unknown>;\n\tseo: ContentItemSeoInput | undefined;\n} {\n\tconst { seo, ...fields } = input;\n\t// Reject non-object seo values rather than silently dropping them.\n\tif (seo !== undefined && (seo === null || typeof seo !== \"object\" || Array.isArray(seo))) {\n\t\tthrow new Error(\"content.seo must be an object\");\n\t}\n\treturn { fields, seo };\n}\n\n/**\n * Reject writing SEO to a collection that does not have it enabled.\n * Matches the REST API behavior (VALIDATION_ERROR).\n */\nasync function assertSeoEnabled(\n\tseoRepo: SeoRepository,\n\tcollection: string,\n\tseo: ContentItemSeoInput | undefined,\n): Promise<boolean> {\n\tconst hasSeo = await seoRepo.isEnabled(collection);\n\tif (seo !== undefined && !hasSeo) {\n\t\tthrow new Error(\n\t\t\t`Collection \"${collection}\" does not have SEO enabled. ` +\n\t\t\t\t`Remove the seo field or enable SEO on this collection.`,\n\t\t);\n\t}\n\treturn hasSeo;\n}\n\n/**\n * Create read-only content access\n */\nexport function createContentAccess(db: Kysely<Database>): ContentAccess {\n\tconst contentRepo = new ContentRepository(db);\n\tconst seoRepo = new SeoRepository(db);\n\n\treturn {\n\t\tasync get(collection: string, id: string): Promise<ContentItem | null> {\n\t\t\tconst item = await contentRepo.findById(collection, id);\n\t\t\tif (!item) return null;\n\n\t\t\tconst result: ContentItem = {\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t};\n\n\t\t\tif (await seoRepo.isEnabled(collection)) {\n\t\t\t\tresult.seo = await seoRepo.get(collection, item.id);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t},\n\n\t\tasync list(\n\t\t\tcollection: string,\n\t\t\toptions?: ContentListOptions,\n\t\t): Promise<PaginatedResult<ContentItem>> {\n\t\t\t// Convert orderBy format if provided\n\t\t\tlet orderBy: { field: string; direction: \"asc\" | \"desc\" } | undefined;\n\t\t\tif (options?.orderBy) {\n\t\t\t\tconst entries = Object.entries(options.orderBy);\n\t\t\t\tconst first = entries[0];\n\t\t\t\tif (first) {\n\t\t\t\t\torderBy = { field: first[0], direction: first[1] };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst result = await contentRepo.findMany(collection, {\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\torderBy,\n\t\t\t\twhere: options?.where,\n\t\t\t});\n\n\t\t\tconst items: ContentItem[] = result.items.map((item) => ({\n\t\t\t\tid: item.id,\n\t\t\t\ttype: item.type,\n\t\t\t\tslug: item.slug,\n\t\t\t\tstatus: item.status,\n\t\t\t\tdata: item.data,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\tlocale: item.locale,\n\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t}));\n\n\t\t\tif (items.length > 0 && (await seoRepo.isEnabled(collection))) {\n\t\t\t\tconst seoMap = await seoRepo.getMany(\n\t\t\t\t\tcollection,\n\t\t\t\t\titems.map((i) => i.id),\n\t\t\t\t);\n\t\t\t\tfor (const item of items) {\n\t\t\t\t\tconst seo = seoMap.get(item.id);\n\t\t\t\t\tif (seo) item.seo = seo;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\titems,\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full content access with write operations.\n *\n * `create` and `update` accept a reserved `seo` key in their `data`\n * argument. When present, it is routed to the core SEO panel\n * (`_emdash_seo`) via `SeoRepository.upsert`, in the same transaction as\n * the content write. The returned `ContentItem.seo` reflects the resulting\n * SEO state for SEO-enabled collections.\n */\nexport function createContentAccessWithWrite(db: Kysely<Database>): ContentAccessWithWrite {\n\tconst readAccess = createContentAccess(db);\n\n\treturn {\n\t\t...readAccess,\n\n\t\tasync create(collection: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\tconst item = await trxContentRepo.create({\n\t\t\t\t\ttype: collection,\n\t\t\t\t\tdata: fields,\n\t\t\t\t});\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync update(collection: string, id: string, data: ContentWriteInput): Promise<ContentItem> {\n\t\t\tconst { fields, seo } = splitSeoFromInput(data);\n\n\t\t\treturn withTransaction(db, async (trx) => {\n\t\t\t\tconst trxContentRepo = new ContentRepository(trx);\n\t\t\t\tconst trxSeoRepo = new SeoRepository(trx);\n\n\t\t\t\tconst hasSeo = await assertSeoEnabled(trxSeoRepo, collection, seo);\n\n\t\t\t\t// Pass the `data` payload to ContentRepository.update only when\n\t\t\t\t// there are field updates — passing an empty object would still\n\t\t\t\t// bump updated_at/version, but we want a seo-only call to touch\n\t\t\t\t// only the SEO table. ContentRepository.update handles the no-op\n\t\t\t\t// path by returning the current row.\n\t\t\t\tconst hasFieldUpdates = Object.keys(fields).length > 0;\n\t\t\t\tconst item = hasFieldUpdates\n\t\t\t\t\t? await trxContentRepo.update(collection, id, { data: fields })\n\t\t\t\t\t: await (async () => {\n\t\t\t\t\t\t\tconst existing = await trxContentRepo.findById(collection, id);\n\t\t\t\t\t\t\tif (!existing) throw new Error(\"Content not found\");\n\t\t\t\t\t\t\treturn existing;\n\t\t\t\t\t\t})();\n\n\t\t\t\tconst result: ContentItem = {\n\t\t\t\t\tid: item.id,\n\t\t\t\t\ttype: item.type,\n\t\t\t\t\tslug: item.slug,\n\t\t\t\t\tstatus: item.status,\n\t\t\t\t\tdata: item.data,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t\tupdatedAt: item.updatedAt,\n\t\t\t\t\tlocale: item.locale,\n\t\t\t\t\tpublishedAt: item.publishedAt,\n\t\t\t\t};\n\n\t\t\t\tif (hasSeo) {\n\t\t\t\t\tresult.seo =\n\t\t\t\t\t\tseo !== undefined\n\t\t\t\t\t\t\t? await trxSeoRepo.upsert(collection, item.id, seo)\n\t\t\t\t\t\t\t: await trxSeoRepo.get(collection, item.id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t});\n\t\t},\n\n\t\tasync delete(collection: string, id: string): Promise<boolean> {\n\t\t\tconst contentRepo = new ContentRepository(db);\n\t\t\treturn contentRepo.delete(collection, id);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Media Access\n// =============================================================================\n\n/**\n * Create read-only media access\n */\nexport function createMediaAccess(db: Kysely<Database>): MediaAccess {\n\tconst mediaRepo = new MediaRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<MediaItem | null> {\n\t\t\tconst item = await mediaRepo.findById(id);\n\t\t\tif (!item) return null;\n\n\t\t\treturn {\n\t\t\t\tid: item.id,\n\t\t\t\tfilename: item.filename,\n\t\t\t\tmimeType: item.mimeType,\n\t\t\t\tsize: item.size,\n\t\t\t\t// Construct URL from storage key (or use a sensible default path)\n\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t};\n\t\t},\n\n\t\tasync list(options?: MediaListOptions): Promise<PaginatedResult<MediaItem>> {\n\t\t\tconst result = await mediaRepo.findMany({\n\t\t\t\tlimit: options?.limit ?? 50,\n\t\t\t\tcursor: options?.cursor,\n\t\t\t\tmimeType: options?.mimeType,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map((item) => ({\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tfilename: item.filename,\n\t\t\t\t\tmimeType: item.mimeType,\n\t\t\t\t\tsize: item.size,\n\t\t\t\t\turl: `/media/${item.id}/${item.filename}`,\n\t\t\t\t\tcreatedAt: item.createdAt,\n\t\t\t\t})),\n\t\t\t\tcursor: result.nextCursor,\n\t\t\t\thasMore: !!result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Create full media access with write operations.\n *\n * `getUploadUrlFn` is optional: when omitted, `getUploadUrl()` is derived from\n * `storage` (create a pending record + a signed PUT URL), mirroring the REST\n * `/_emdash/api/media/upload-url` endpoint. `upload()` only needs `storage`.\n * If storage is not provided, both throw at call time.\n */\nexport function createMediaAccessWithWrite(\n\tdb: Kysely<Database>,\n\tgetUploadUrlFn:\n\t\t| ((filename: string, contentType: string) => Promise<{ uploadUrl: string; mediaId: string }>)\n\t\t| undefined,\n\tstorage?: Storage,\n): MediaAccessWithWrite {\n\tconst mediaRepo = new MediaRepository(db);\n\tconst readAccess = createMediaAccess(db);\n\n\tconst getUploadUrl =\n\t\tgetUploadUrlFn ??\n\t\t(async (filename: string, contentType: string) => {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media getUploadUrl() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${ulid()}${ext}`;\n\n\t\t\tconst media = await mediaRepo.createPending({\n\t\t\t\tfilename: basename,\n\t\t\t\tmimeType: contentType,\n\t\t\t\tstorageKey,\n\t\t\t});\n\n\t\t\tconst signed = await storage.getSignedUploadUrl({\n\t\t\t\tkey: storageKey,\n\t\t\t\tcontentType,\n\t\t\t\texpiresIn: 3600,\n\t\t\t});\n\n\t\t\treturn { uploadUrl: signed.url, mediaId: media.id };\n\t\t});\n\n\treturn {\n\t\t...readAccess,\n\n\t\tgetUploadUrl,\n\n\t\tasync upload(\n\t\t\tfilename: string,\n\t\t\tcontentType: string,\n\t\t\tbytes: ArrayBuffer,\n\t\t): Promise<{ mediaId: string; storageKey: string; url: string }> {\n\t\t\tif (!storage) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Media upload() requires a storage backend. Configure storage in PluginContextFactoryOptions.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Generate a storage key with a unique prefix\n\t\t\tconst keyPrefix = ulid();\n\t\t\t// Extract extension from basename (ignore path separators)\n\t\t\tconst basename = filename.split(\"/\").pop() ?? filename;\n\t\t\tconst dotIdx = basename.lastIndexOf(\".\");\n\t\t\tconst ext = dotIdx > 0 ? basename.slice(dotIdx).toLowerCase() : \"\";\n\t\t\tconst storageKey = `${keyPrefix}${ext}`;\n\n\t\t\t// Upload to storage first\n\t\t\tawait storage.upload({\n\t\t\t\tkey: storageKey,\n\t\t\t\tbody: new Uint8Array(bytes),\n\t\t\t\tcontentType,\n\t\t\t});\n\n\t\t\t// Derive dimensions + LQIP placeholders (no-op for non-images).\n\t\t\tconst enriched = await enrichImageMetadata(new Uint8Array(bytes), contentType);\n\n\t\t\t// Create DB record — clean up storage on failure\n\t\t\tlet media;\n\t\t\ttry {\n\t\t\t\tmedia = await mediaRepo.create({\n\t\t\t\t\tfilename: basename,\n\t\t\t\t\tmimeType: contentType,\n\t\t\t\t\tsize: bytes.byteLength,\n\t\t\t\t\tstorageKey,\n\t\t\t\t\tstatus: \"ready\",\n\t\t\t\t\twidth: enriched.width,\n\t\t\t\t\theight: enriched.height,\n\t\t\t\t\tblurhash: enriched.blurhash,\n\t\t\t\t\tdominantColor: enriched.dominantColor,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tawait storage.delete(storageKey);\n\t\t\t\t} catch {\n\t\t\t\t\t// Best-effort cleanup\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tmediaId: media.id,\n\t\t\t\tstorageKey,\n\t\t\t\turl: `/_emdash/api/media/file/${storageKey}`,\n\t\t\t};\n\t\t},\n\n\t\tasync delete(id: string): Promise<boolean> {\n\t\t\tconst deleted = await mediaRepo.delete(id);\n\t\t\t// Plugins can delete media that's referenced by site settings\n\t\t\t// (`logo`, `favicon`, `seo.defaultOgImage`); the worker-scoped\n\t\t\t// resolved-URL cache must be dropped or it will keep serving\n\t\t\t// 404s. Matches the invalidation in\n\t\t\t// `EmDashRuntime.handleMediaDelete`.\n\t\t\tif (deleted) {\n\t\t\t\tinvalidateSiteSettingsCache();\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\n// =============================================================================\n// HTTP Access\n// =============================================================================\n\n/** Maximum number of redirects to follow in plugin HTTP access */\nconst MAX_PLUGIN_REDIRECTS = 5;\n\n/**\n * Check if a hostname matches any pattern in the allowed list.\n * Patterns: \"*\" matches all, \"*.example.com\" matches subdomains AND bare \"example.com\",\n * \"api.example.com\" matches exactly.\n */\nfunction isHostAllowed(host: string, allowedHosts: string[]): boolean {\n\treturn allowedHosts.some((pattern) => {\n\t\tif (pattern === \"*\") return true;\n\t\tif (pattern.startsWith(\"*.\")) {\n\t\t\tconst suffix = pattern.slice(1); // \".example.com\"\n\t\t\t// Match subdomains (foo.example.com) and bare domain (example.com)\n\t\t\treturn host.endsWith(suffix) || host === pattern.slice(2);\n\t\t}\n\t\treturn host === pattern;\n\t});\n}\n\n/**\n * Create HTTP access with host validation.\n *\n * Uses redirect: \"manual\" to re-validate each redirect target against\n * the allowedHosts list, preventing redirects to unauthorized hosts.\n */\nexport function createHttpAccess(pluginId: string, allowedHosts: string[]): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\t// Deny by default — plugins must declare allowed hosts\n\t\t\tif (allowedHosts.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Plugin \"${pluginId}\" has no allowed hosts configured. ` +\n\t\t\t\t\t\t`Add hosts to the plugin's allowedHosts array to enable HTTP requests.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\tconst hostname = new URL(currentUrl).hostname;\n\t\t\t\tif (!isHostAllowed(hostname, allowedHosts)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\" is not allowed to fetch from host \"${hostname}\". ` +\n\t\t\t\t\t\t\t`Allowed hosts: ${allowedHosts.join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create unrestricted HTTP access (for plugins with network:fetch:any capability).\n * No host validation, but applies SSRF protection on redirect targets to\n * prevent plugins from being tricked into reaching internal services.\n */\nexport function createUnrestrictedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(url: string, init?: RequestInit): Promise<Response> {\n\t\t\tlet currentUrl = url;\n\t\t\tlet currentInit = init;\n\n\t\t\tfor (let i = 0; i <= MAX_PLUGIN_REDIRECTS; i++) {\n\t\t\t\t// Validate each URL against SSRF rules (private IPs, metadata\n\t\t\t\t// endpoints, wildcard DNS, resolved-IP private ranges).\n\t\t\t\ttry {\n\t\t\t\t\tawait resolveAndValidateExternalUrl(currentUrl);\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconst msg = e instanceof SsrfError ? e.message : \"SSRF validation failed\";\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Plugin \"${pluginId}\": blocked fetch to \"${new URL(currentUrl).hostname}\": ${msg}`,\n\t\t\t\t\t\t{ cause: e },\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst response = await globalThis.fetch(currentUrl, {\n\t\t\t\t\t...currentInit,\n\t\t\t\t\tredirect: \"manual\",\n\t\t\t\t});\n\n\t\t\t\t// Not a redirect -- return directly\n\t\t\t\tif (response.status < 300 || response.status >= 400) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Extract redirect target\n\t\t\t\tconst location = response.headers.get(\"Location\");\n\t\t\t\tif (!location) {\n\t\t\t\t\treturn response;\n\t\t\t\t}\n\n\t\t\t\t// Resolve relative redirects; strip credentials on cross-origin hops\n\t\t\t\tconst previousOrigin = new URL(currentUrl).origin;\n\t\t\t\tcurrentUrl = new URL(location, currentUrl).href;\n\t\t\t\tconst nextOrigin = new URL(currentUrl).origin;\n\n\t\t\t\tif (previousOrigin !== nextOrigin && currentInit) {\n\t\t\t\t\tcurrentInit = stripCredentialHeaders(currentInit);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new Error(`Plugin \"${pluginId}\": too many redirects (max ${MAX_PLUGIN_REDIRECTS})`);\n\t\t},\n\t};\n}\n\n/**\n * Create blocked HTTP access (for plugins without network:request capability)\n */\nexport function createBlockedHttpAccess(pluginId: string): HttpAccess {\n\treturn {\n\t\tasync fetch(): Promise<never> {\n\t\t\tthrow new Error(\n\t\t\t\t`Plugin \"${pluginId}\" does not have the \"network:request\" capability. ` +\n\t\t\t\t\t`Add \"network:request\" to the plugin's capabilities to enable HTTP requests.`,\n\t\t\t);\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Log Access\n// =============================================================================\n\n/**\n * Create logger for a plugin\n */\nexport function createLogAccess(pluginId: string): LogAccess {\n\tconst prefix = `[plugin:${pluginId}]`;\n\n\treturn {\n\t\tdebug(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.debug(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.debug(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\tinfo(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.info(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.info(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\twarn(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.warn(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.warn(prefix, message);\n\t\t\t}\n\t\t},\n\n\t\terror(message: string, data?: unknown): void {\n\t\t\tif (data !== undefined) {\n\t\t\t\tconsole.error(prefix, message, data);\n\t\t\t} else {\n\t\t\t\tconsole.error(prefix, message);\n\t\t\t}\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Site Info\n// =============================================================================\n\nconst TRAILING_SLASH_RE = /\\/$/;\n\n/**\n * Options for creating site info\n */\nexport interface SiteInfoOptions {\n\t/** Site name from options table */\n\tsiteName?: string;\n\t/** Site URL from options table or Astro config */\n\tsiteUrl?: string;\n\t/** Site locale from options table */\n\tlocale?: string;\n}\n\n/**\n * Create site info from config and settings.\n *\n * Resolution order for URL:\n * 1. options table (emdash:site_url)\n * 2. Astro `site` config\n * 3. fallback to empty string\n */\nexport function createSiteInfo(options: SiteInfoOptions): SiteInfo {\n\treturn {\n\t\tname: options.siteName ?? \"\",\n\t\turl: (options.siteUrl ?? \"\").replace(TRAILING_SLASH_RE, \"\"), // strip trailing slash\n\t\tlocale: options.locale ?? \"en\",\n\t};\n}\n\n/**\n * Create a URL helper that generates absolute URLs from relative paths.\n * Validates that path starts with \"/\" and rejects protocol-relative paths (\"//\").\n */\nexport function createUrlHelper(siteUrl: string): (path: string) => string {\n\tconst base = siteUrl.replace(TRAILING_SLASH_RE, \"\"); // strip trailing slash\n\n\treturn (path: string): string => {\n\t\tif (!path.startsWith(\"/\")) {\n\t\t\tthrow new Error(`URL path must start with \"/\", got: \"${path}\"`);\n\t\t}\n\t\tif (path.startsWith(\"//\")) {\n\t\t\tthrow new Error(`URL path must not be protocol-relative, got: \"${path}\"`);\n\t\t}\n\t\treturn `${base}${path}`;\n\t};\n}\n\n// =============================================================================\n// User Access\n// =============================================================================\n\n/**\n * Convert a UserRepository user to the plugin-facing UserInfo shape.\n * Strips sensitive fields (avatarUrl, emailVerified, data).\n */\nfunction toUserInfo(user: {\n\tid: string;\n\temail: string;\n\tname: string | null;\n\trole: number;\n\tcreatedAt: string;\n}): UserInfo {\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name,\n\t\trole: user.role,\n\t\tcreatedAt: user.createdAt,\n\t};\n}\n\n/**\n * Create read-only user access for plugins.\n * Excludes sensitive fields (password hashes, sessions, passkeys, avatar URL, data).\n */\nexport function createUserAccess(db: Kysely<Database>): UserAccess {\n\tconst userRepo = new UserRepository(db);\n\n\treturn {\n\t\tasync get(id: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findById(id);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync getByEmail(email: string): Promise<UserInfo | null> {\n\t\t\tconst user = await userRepo.findByEmail(email);\n\t\t\tif (!user) return null;\n\t\t\treturn toUserInfo(user);\n\t\t},\n\n\t\tasync list(opts?: {\n\t\t\trole?: number;\n\t\t\tlimit?: number;\n\t\t\tcursor?: string;\n\t\t}): Promise<{ items: UserInfo[]; nextCursor?: string }> {\n\t\t\tconst result = await userRepo.findMany({\n\t\t\t\trole: opts?.role as 10 | 20 | 30 | 40 | 50 | undefined,\n\t\t\t\tcursor: opts?.cursor,\n\t\t\t\tlimit: opts?.limit,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\titems: result.items.map(toUserInfo),\n\t\t\t\tnextCursor: result.nextCursor,\n\t\t\t};\n\t\t},\n\t};\n}\n\n// =============================================================================\n// Plugin Context Factory\n// =============================================================================\n\nexport interface PluginContextFactoryOptions {\n\tdb: Kysely<Database>;\n\t/**\n\t * Resolver for the database connection, preferred over `db` when present.\n\t * Called per `createContext()` so connection-backed adapters (e.g. Postgres\n\t * over Hyperdrive) get the current request/event-scoped connection from ALS\n\t * rather than a snapshot of the per-isolate singleton — reusing the\n\t * singleton's socket from a later event trips workerd's cross-request I/O\n\t * guard. When omitted, `db` is used directly (correct for stateless\n\t * adapters like D1 and Node SQLite). `db` remains required as the fallback.\n\t */\n\tgetDb?: () => Kysely<Database>;\n\t/**\n\t * Storage backend for direct media uploads.\n\t * If not provided, upload() will throw.\n\t */\n\tstorage?: Storage;\n\t/**\n\t * Explicit provider for `ctx.media.getUploadUrl()`. Optional: when omitted\n\t * but `storage` is configured, the factory derives a working `getUploadUrl()`\n\t * (and `upload()`) from storage. Only when neither `getUploadUrl` nor\n\t * `storage` is present do media write operations become unavailable.\n\t */\n\tgetUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\t/**\n\t * Site information for ctx.site and ctx.url().\n\t * If not provided, site info will have empty defaults.\n\t */\n\tsiteInfo?: SiteInfoOptions;\n\t/**\n\t * Callback to notify the cron scheduler that the next due time may have changed.\n\t * If not provided, ctx.cron will not be available.\n\t */\n\tcronReschedule?: () => void;\n\t/**\n\t * Email pipeline instance for ctx.email.\n\t * If not provided (or no provider configured), ctx.email will be undefined.\n\t */\n\temailPipeline?: EmailPipeline;\n\t/**\n\t * Pre-resolved list of trusted proxy header names (from the runtime\n\t * `EmDashConfig.trustedProxyHeaders` or the env var). Plugin route\n\t * handlers pass this to `extractRequestMeta` so plugins see the same\n\t * client IP the core auth path does.\n\t */\n\ttrustedProxyHeaders?: string[];\n}\n\n/**\n * Factory for creating plugin contexts\n */\nexport class PluginContextFactory {\n\tprivate resolveDb: () => Kysely<Database>;\n\tprivate storage?: Storage;\n\tprivate getUploadUrl?: (\n\t\tfilename: string,\n\t\tcontentType: string,\n\t) => Promise<{ uploadUrl: string; mediaId: string }>;\n\tprivate site: SiteInfo;\n\tprivate urlHelper: (path: string) => string;\n\tprivate cronReschedule?: () => void;\n\tprivate emailPipeline?: EmailPipeline;\n\t/**\n\t * Plugin IDs already warned about a missing media-write backend, so the\n\t * warning fires once per factory instead of on every hook/route context\n\t * creation (which would spam logs for hook-participating plugins).\n\t */\n\tprivate warnedMissingMediaBackend = new Set<string>();\n\n\tconstructor(options: PluginContextFactoryOptions) {\n\t\tconst fixedDb = options.db;\n\t\tthis.resolveDb = options.getDb ?? (() => fixedDb);\n\t\tthis.storage = options.storage;\n\t\tthis.getUploadUrl = options.getUploadUrl;\n\t\tthis.site = createSiteInfo(options.siteInfo ?? {});\n\t\tthis.urlHelper = createUrlHelper(this.site.url);\n\t\tthis.cronReschedule = options.cronReschedule;\n\t\tthis.emailPipeline = options.emailPipeline;\n\t}\n\n\t/**\n\t * Create the unified plugin context\n\t */\n\tcreateContext(plugin: ResolvedPlugin): PluginContext {\n\t\tconst capabilities = new Set(plugin.capabilities);\n\n\t\t// Resolve the connection once per context. For stateless adapters this\n\t\t// is the singleton; for connection-backed adapters it's the current\n\t\t// request/event-scoped connection from ALS. All repos below are built\n\t\t// from this local `db` so a hook never queries a stale singleton socket.\n\t\tconst db = this.resolveDb();\n\t\tconst optionsRepo = new OptionsRepository(db);\n\n\t\t// Always available\n\t\tconst kv = createKVAccess(optionsRepo, plugin.id);\n\t\tconst log = createLogAccess(plugin.id);\n\t\tconst storage = createStorageAccess(db, plugin.id, plugin.storage);\n\n\t\t// Capability-gated: content\n\t\t// Note: capabilities reach this point already normalized to the\n\t\t// canonical names by definePlugin / adaptSandboxEntry. Deprecated\n\t\t// names (\"read:content\", \"write:content\") never appear here.\n\t\tlet content: ContentAccess | ContentAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"content:write\")) {\n\t\t\tcontent = createContentAccessWithWrite(db);\n\t\t} else if (capabilities.has(\"content:read\")) {\n\t\t\tcontent = createContentAccess(db);\n\t\t}\n\n\t\t// Capability-gated: media\n\t\t// `upload()` only needs `storage`; `getUploadUrl()` is derived from\n\t\t// storage when no explicit provider is wired. Granting write access on\n\t\t// either avoids silently degrading media:write to read-only — the bug\n\t\t// where the runtime threads `storage` but not `getUploadUrl`.\n\t\tlet media: MediaAccess | MediaAccessWithWrite | undefined;\n\t\tif (capabilities.has(\"media:write\")) {\n\t\t\tif (this.getUploadUrl || this.storage) {\n\t\t\t\tmedia = createMediaAccessWithWrite(db, this.getUploadUrl, this.storage);\n\t\t\t} else {\n\t\t\t\tif (!this.warnedMissingMediaBackend.has(plugin.id)) {\n\t\t\t\t\tthis.warnedMissingMediaBackend.add(plugin.id);\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\"declares the media:write capability but no storage backend is configured; upload() is unavailable.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (capabilities.has(\"media:read\")) {\n\t\t\t\t\tmedia = createMediaAccess(db);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (capabilities.has(\"media:read\")) {\n\t\t\tmedia = createMediaAccess(db);\n\t\t}\n\n\t\t// Capability-gated: http\n\t\tlet http: HttpAccess | undefined;\n\t\tif (capabilities.has(\"network:request:unrestricted\")) {\n\t\t\thttp = createUnrestrictedHttpAccess(plugin.id);\n\t\t} else if (capabilities.has(\"network:request\")) {\n\t\t\thttp = createHttpAccess(plugin.id, plugin.allowedHosts);\n\t\t}\n\n\t\t// Capability-gated: users\n\t\tlet users: UserAccess | undefined;\n\t\tif (capabilities.has(\"users:read\")) {\n\t\t\tusers = createUserAccess(db);\n\t\t}\n\n\t\t// Cron access — always available (scoped to plugin), but only if\n\t\t// the runtime provided a reschedule callback (i.e. cron is wired up).\n\t\tlet cron: CronAccess | undefined;\n\t\tif (this.cronReschedule) {\n\t\t\tcron = new CronAccessImpl(db, plugin.id, this.cronReschedule);\n\t\t}\n\n\t\t// Email access — requires email:send capability AND a configured provider\n\t\tlet email: EmailAccess | undefined;\n\t\tif (capabilities.has(\"email:send\") && this.emailPipeline?.isAvailable()) {\n\t\t\tconst pipeline = this.emailPipeline;\n\t\t\tconst pluginId = plugin.id;\n\t\t\temail = {\n\t\t\t\tsend: (message) => pipeline.send(message, pluginId),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tplugin: {\n\t\t\t\tid: plugin.id,\n\t\t\t\tversion: plugin.version,\n\t\t\t},\n\t\t\tstorage,\n\t\t\tkv,\n\t\t\tcontent,\n\t\t\tmedia,\n\t\t\thttp,\n\t\t\tlog,\n\t\t\tsite: this.site,\n\t\t\turl: this.urlHelper,\n\t\t\tusers,\n\t\t\tcron,\n\t\t\temail,\n\t\t};\n\t}\n}\n\n/**\n * Create a plugin context for a resolved plugin\n */\nexport function createPluginContext(\n\toptions: PluginContextFactoryOptions,\n\tplugin: ResolvedPlugin,\n): PluginContext {\n\tconst factory = new PluginContextFactory(options);\n\treturn factory.create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AI;AACJ,MAAI,aAAa,IAAI,cAAc,CAClC,KAAI,KAAK,gBAAgB,KAAK,QAC7B,SAAQ,2BAA2B,IAAI,KAAK,cAAc,KAAK,QAAQ;OACjE;AACN,OAAI,CAAC,KAAK,0BAA0B,IAAI,OAAO,GAAG,EAAE;AACnD,SAAK,0BAA0B,IAAI,OAAO,GAAG;AAC7C,QAAI,KACH,qGACA;;AAEF,OAAI,aAAa,IAAI,aAAa,CACjC,SAAQ,kBAAkB,GAAG;;WAGrB,aAAa,IAAI,aAAa,CACxC,SAAQ,kBAAkB,GAAG;EAI9B,IAAI;AACJ,MAAI,aAAa,IAAI,+BAA+B,CACnD,QAAO,6BAA6B,OAAO,GAAG;WACpC,aAAa,IAAI,kBAAkB,CAC7C,QAAO,iBAAiB,OAAO,IAAI,OAAO,aAAa;EAIxD,IAAI;AACJ,MAAI,aAAa,IAAI,aAAa,CACjC,SAAQ,iBAAiB,GAAG;EAK7B,IAAI;AACJ,MAAI,KAAK,eACR,QAAO,IAAI,eAAe,IAAI,OAAO,IAAI,KAAK,eAAe;EAI9D,IAAI;AACJ,MAAI,aAAa,IAAI,aAAa,IAAI,KAAK,eAAe,aAAa,EAAE;GACxE,MAAM,WAAW,KAAK;GACtB,MAAM,WAAW,OAAO;AACxB,WAAQ,EACP,OAAO,YAAY,SAAS,KAAK,SAAS,SAAS,EACnD;;AAGF,SAAO;GACN,QAAQ;IACP,IAAI,OAAO;IACX,SAAS,OAAO;IAChB;GACD;GACA;GACA;GACA;GACA;GACA;GACA,MAAM,KAAK;GACX,KAAK,KAAK;GACV;GACA;GACA;GACA"}
@@ -1,6 +1,6 @@
1
1
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
2
- import { t as ContentRepository } from "./content-PoVGKjp0.mjs";
3
- import { t as MediaRepository } from "./media-CTjJoJTh.mjs";
2
+ import { t as ContentRepository } from "./content-B43-YrIq.mjs";
3
+ import { t as MediaRepository } from "./media-BjKxjzk8.mjs";
4
4
  import { t as UserRepository } from "./user-JAuc8VUf.mjs";
5
5
  import { sql } from "kysely";
6
6
 
@@ -102,4 +102,4 @@ async function fetchRecentItems(db, collections) {
102
102
 
103
103
  //#endregion
104
104
  export { handleDashboardStats as t };
105
- //# sourceMappingURL=dashboard-DsYU8JKS.mjs.map
105
+ //# sourceMappingURL=dashboard-FIe0S512.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard-DsYU8JKS.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GAAG;EAC7C,MAAM,kBAAqC,MAAM,QAAQ,IACxD,YAAY,IAAI,OAAO,QAAQ;GAC9B,MAAM,QAAQ,MAAM,YAAY,SAAS,IAAI,KAAK;AAClD,UAAO;IACN,MAAM,IAAI;IACV,OAAO,IAAI;IACX,OAAO,MAAM;IACb,WAAW,MAAM;IACjB,OAAO,MAAM;IACb;IACA,CACF;EAGD,MAAM,YAAY,IAAI,gBAAgB,GAAG;EACzC,MAAM,WAAW,IAAI,eAAe,GAAG;EACvC,MAAM,CAAC,YAAY,aAAa,MAAM,QAAQ,IAAI,CAAC,UAAU,OAAO,EAAE,SAAS,OAAO,CAAC,CAAC;AAKxF,SAAO;GACN,SAAS;GACT,MAAM;IACL,aAAa;IACb;IACA;IACA,aARkB,MAAM,iBAAiB,IAAI,YAAY;IASzD;GACD;UACO,OAAO;AACf,UAAQ,MAAM,0BAA0B,MAAM;AAC9C,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;;;;;;;;;;;;;AA0BH,eAAe,iBACd,IACA,aACwB;AACxB,KAAI,YAAY,WAAW,EAAG,QAAO,EAAE;CAGvC,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,UAAU,4BAA4B,QAAQ,kBAAkB,CAChE,OAAO,CAAC,4BAA4B,CAAC,CACrC,MAAM,UAAU,KAAK,QAAQ,CAC7B,SAAS;CAEX,MAAM,uBAAuB,IAAI,IAAI,YAAY,KAAK,MAAM,EAAE,gBAAgB,CAAC;AA2C/E,SApCsB,MAAM,QAAQ,IACnC,YAAY,IAAI,OAAO,QAAQ;AAC9B,qBAAmB,IAAI,KAAK;EAC5B,MAAM,QAAQ,MAAM,IAAI;EAKxB,MAAM,YAJW,qBAAqB,IAAI,IAAI,KAAK,GAItB,GAAG,8BAA8B,GAAG;AAiBjE,UAfe,MAAM,GAAkB;;;OAGnC,IAAI,IAAI,IAAI,KAAK,CAAC;OAClB,IAAI,IAAI,IAAI,MAAM,CAAC;OACnB,UAAU;;;;;WAKN,IAAI,IAAI,MAAM,CAAC;;;;KAIrB,QAAQ,GAAG,EACC;GACb,CACF,EAIC,MAAM,CACN,UAAU,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE,aAAa,EAAE,aAAa,KAAK,EAAG,CAC5F,MAAM,GAAG,GAAG,CAGA,KAAK,SAAS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
1
+ {"version":3,"file":"dashboard-FIe0S512.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GAAG;EAC7C,MAAM,kBAAqC,MAAM,QAAQ,IACxD,YAAY,IAAI,OAAO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,GAAG,EACC;GACb,CACF,EAIC,MAAM,CACN,UAAU,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE,aAAa,EAAE,aAAa,KAAK,EAAG,CAC5F,MAAM,GAAG,GAAG,CAGA,KAAK,SAAS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
@@ -50,4 +50,4 @@ function isMissingTableError(error) {
50
50
 
51
51
  //#endregion
52
52
  export { isMissingTableError as n, isMissingColumnError as t };
53
- //# sourceMappingURL=db-errors-UXB1CK42.mjs.map
53
+ //# sourceMappingURL=db-errors-CK46D-ly.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"db-errors-UXB1CK42.mjs","names":[],"sources":["../src/utils/db-errors.ts"],"sourcesContent":["/**\n * Shared detection helpers for database-layer error messages.\n *\n * Different SQL dialects phrase \"table or relation does not exist\" differently:\n *\n * - SQLite / D1: \"no such table: foo\"\n * - PostgreSQL: 'relation \"foo\" does not exist'\n * 'table \"foo\" does not exist'\n * - MySQL (future): \"Table 'db.foo' doesn't exist\"\n *\n * Runtime code paths that short-circuit on missing tables (pre-migration\n * probes, optional feature tables, etc.) should use these helpers rather\n * than hand-rolling string matches per call-site.\n */\n\n/**\n * Extract a lowercase error message from any unknown value, safely.\n */\nfunction messageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message.toLowerCase();\n\tif (typeof error === \"string\") return error.toLowerCase();\n\treturn \"\";\n}\n\n/**\n * Returns true when `error` is a \"column does not exist\" error.\n * Used to handle where filters that reference non-existent field names\n * gracefully (return empty results) instead of propagating a SQL error.\n */\nexport function isMissingColumnError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1: \"no such column: foo\"\n\tif (message.includes(\"no such column\")) return true;\n\n\t// PostgreSQL SQLSTATE 42703: 'column \"foo\" does not exist'\n\t// Exclude \"relation\" to avoid false positives on table names containing \"column\"\n\tif (\n\t\tmessage.includes(\"does not exist\") &&\n\t\tmessage.includes(\"column\") &&\n\t\t!message.includes(\"relation\")\n\t)\n\t\treturn true;\n\n\treturn false;\n}\n\n/**\n * Returns true when `error` is a \"table does not exist\" error across the\n * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime\n * probes to treat pre-migration databases as empty without logging a scary\n * warning, while still propagating unrelated errors (permissions, connection\n * loss, syntax issues) to callers.\n */\nexport function isMissingTableError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1\n\tif (message.includes(\"no such table\")) return true;\n\n\t// PostgreSQL (and some MySQL variants): \"relation ... does not exist\" /\n\t// \"table ... does not exist\" / \"doesn't exist\".\n\tif (message.includes(\"does not exist\") || message.includes(\"doesn't exist\")) {\n\t\treturn message.includes(\"relation\") || message.includes(\"table\");\n\t}\n\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,OAAwB;AAC1C,KAAI,iBAAiB,MAAO,QAAO,MAAM,QAAQ,aAAa;AAC9D,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,aAAa;AACzD,QAAO;;;;;;;AAQR,SAAgB,qBAAqB,OAAyB;CAC7D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,iBAAiB,CAAE,QAAO;AAI/C,KACC,QAAQ,SAAS,iBAAiB,IAClC,QAAQ,SAAS,SAAS,IAC1B,CAAC,QAAQ,SAAS,WAAW,CAE7B,QAAO;AAER,QAAO;;;;;;;;;AAUR,SAAgB,oBAAoB,OAAyB;CAC5D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,gBAAgB,CAAE,QAAO;AAI9C,KAAI,QAAQ,SAAS,iBAAiB,IAAI,QAAQ,SAAS,gBAAgB,CAC1E,QAAO,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,QAAQ;AAGjE,QAAO"}
1
+ {"version":3,"file":"db-errors-CK46D-ly.mjs","names":[],"sources":["../src/utils/db-errors.ts"],"sourcesContent":["/**\n * Shared detection helpers for database-layer error messages.\n *\n * Different SQL dialects phrase \"table or relation does not exist\" differently:\n *\n * - SQLite / D1: \"no such table: foo\"\n * - PostgreSQL: 'relation \"foo\" does not exist'\n * 'table \"foo\" does not exist'\n * - MySQL (future): \"Table 'db.foo' doesn't exist\"\n *\n * Runtime code paths that short-circuit on missing tables (pre-migration\n * probes, optional feature tables, etc.) should use these helpers rather\n * than hand-rolling string matches per call-site.\n */\n\n/**\n * Extract a lowercase error message from any unknown value, safely.\n */\nfunction messageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message.toLowerCase();\n\tif (typeof error === \"string\") return error.toLowerCase();\n\treturn \"\";\n}\n\n/**\n * Returns true when `error` is a \"column does not exist\" error.\n * Used to handle where filters that reference non-existent field names\n * gracefully (return empty results) instead of propagating a SQL error.\n */\nexport function isMissingColumnError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1: \"no such column: foo\"\n\tif (message.includes(\"no such column\")) return true;\n\n\t// PostgreSQL SQLSTATE 42703: 'column \"foo\" does not exist'\n\t// Exclude \"relation\" to avoid false positives on table names containing \"column\"\n\tif (\n\t\tmessage.includes(\"does not exist\") &&\n\t\tmessage.includes(\"column\") &&\n\t\t!message.includes(\"relation\")\n\t)\n\t\treturn true;\n\n\treturn false;\n}\n\n/**\n * Returns true when `error` is a \"table does not exist\" error across the\n * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime\n * probes to treat pre-migration databases as empty without logging a scary\n * warning, while still propagating unrelated errors (permissions, connection\n * loss, syntax issues) to callers.\n */\nexport function isMissingTableError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1\n\tif (message.includes(\"no such table\")) return true;\n\n\t// PostgreSQL (and some MySQL variants): \"relation ... does not exist\" /\n\t// \"table ... does not exist\" / \"doesn't exist\".\n\tif (message.includes(\"does not exist\") || message.includes(\"doesn't exist\")) {\n\t\treturn message.includes(\"relation\") || message.includes(\"table\");\n\t}\n\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,OAAwB;AAC1C,KAAI,iBAAiB,MAAO,QAAO,MAAM,QAAQ,aAAa;AAC9D,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,aAAa;AACzD,QAAO;;;;;;;AAQR,SAAgB,qBAAqB,OAAyB;CAC7D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,iBAAiB,CAAE,QAAO;AAI/C,KACC,QAAQ,SAAS,iBAAiB,IAClC,QAAQ,SAAS,SAAS,IAC1B,CAAC,QAAQ,SAAS,WAAW,CAE7B,QAAO;AAER,QAAO;;;;;;;;;AAUR,SAAgB,oBAAoB,OAAyB;CAC5D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,gBAAgB,CAAE,QAAO;AAI9C,KAAI,QAAQ,SAAS,iBAAiB,IAAI,QAAQ,SAAS,gBAAgB,CAC1E,QAAO,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,QAAQ;AAGjE,QAAO"}
@@ -1,3 +1,4 @@
1
+ import { n as normalizeMime } from "./mime-CCEzze7W.mjs";
1
2
  import { encode } from "blurhash";
2
3
  import { imageSize } from "image-size";
3
4
 
@@ -67,8 +68,12 @@ function extractDominantColor(data, width, height) {
67
68
  }
68
69
  /**
69
70
  * Read image dimensions from headers without decoding pixel data.
71
+ * Returns null when the header cannot be parsed.
72
+ *
73
+ * Shared by every caller that needs pixel dimensions so the header is parsed
74
+ * once per buffer, not re-read inside generatePlaceholder.
70
75
  */
71
- function getImageDimensions(buffer) {
76
+ function readDimensions(buffer) {
72
77
  try {
73
78
  const result = imageSize(buffer);
74
79
  if (result.width != null && result.height != null) return {
@@ -84,17 +89,21 @@ function getImageDimensions(buffer) {
84
89
  * Generate blurhash and dominant color from an image buffer.
85
90
  * Returns null for non-image MIME types or on failure.
86
91
  *
87
- * @param dimensions - Optional pre-known dimensions. Used as a fallback when
88
- * image-size cannot parse the buffer (e.g. truncated headers). When the
89
- * decoded size (width * height * 4) exceeds MAX_DECODED_BYTES, placeholder
90
- * generation is skipped to avoid OOM on memory-constrained runtimes.
92
+ * @param dimensions - Optional pre-known dimensions. When present they are
93
+ * trusted verbatim (the caller has typically already read them via
94
+ * readDimensions); otherwise dimensions are read from this buffer's header.
95
+ * Generation is skipped (returns null) when no dimensions are available at
96
+ * all, or when the decoded size (width * height * 4) exceeds
97
+ * MAX_DECODED_BYTES — both guards avoid OOM from unbounded decodes on
98
+ * memory-constrained runtimes.
91
99
  */
92
100
  async function generatePlaceholder(buffer, mimeType, dimensions) {
93
- const format = SUPPORTED_TYPES[mimeType];
101
+ const format = SUPPORTED_TYPES[normalizeMime(mimeType)];
94
102
  if (!format) return null;
95
103
  try {
96
- const dims = getImageDimensions(buffer) ?? dimensions;
97
- if (dims && dims.width * dims.height * 4 > MAX_DECODED_BYTES) return null;
104
+ const dims = dimensions ?? readDimensions(buffer);
105
+ if (!dims) return null;
106
+ if (dims.width * dims.height * 4 > MAX_DECODED_BYTES) return null;
98
107
  const { width, height, data } = format === "jpeg" ? await decodeJpeg(buffer) : await decodePng(buffer);
99
108
  if (width === 0 || height === 0) return null;
100
109
  let encodePixels;
@@ -139,5 +148,47 @@ function downsample(src, srcW, srcH, dstW, dstH) {
139
148
  }
140
149
 
141
150
  //#endregion
142
- export { generatePlaceholder as t };
143
- //# sourceMappingURL=placeholder-B0s2mWu5.mjs.map
151
+ //#region src/media/enrich.ts
152
+ /**
153
+ * Image Metadata Enrichment
154
+ *
155
+ * Single seam that derives image dimensions and LQIP placeholders (blurhash,
156
+ * dominant color) from raw image bytes. Every server-side media-creation path
157
+ * routes through this so records are populated consistently. Pure-JS and
158
+ * Workers-safe (image-size reads headers only; generatePlaceholder guards
159
+ * decode size).
160
+ */
161
+ /**
162
+ * Derive dimensions + LQIP placeholders from image bytes.
163
+ *
164
+ * - Non-image content types return `{}`.
165
+ * - `knownDimensions` (e.g. browser `naturalWidth/Height`) win over `image-size`
166
+ * for the *stored record* because the browser applies EXIF orientation;
167
+ * `image-size` reports raw header dimensions, which are swapped for
168
+ * 90°/270°-rotated JPEGs. They are NOT used for the decode OOM guard — see below.
169
+ * - The placeholder OOM guard uses only header dimensions read from the bytes
170
+ * actually decoded. Caller-supplied `knownDimensions` are untrusted for the
171
+ * guard: a client could claim a tiny size for a huge image to bypass the cap.
172
+ * - `placeholder` lets a caller decode a smaller thumbnail for the blurhash to
173
+ * avoid OOM on large originals; dimensions still come from `bytes`.
174
+ * - Placeholders are jpeg/png only (the generator's supported formats); other
175
+ * image types still get dimensions.
176
+ */
177
+ async function enrichImageMetadata(bytes, contentType, opts) {
178
+ const normalizedContentType = normalizeMime(contentType);
179
+ if (!normalizedContentType.startsWith("image/")) return {};
180
+ const headerDims = readDimensions(bytes) ?? void 0;
181
+ const recordDims = opts?.knownDimensions ?? headerDims;
182
+ const override = opts?.placeholder;
183
+ const placeholder = await generatePlaceholder(override ? override.bytes : bytes, override ? normalizeMime(override.contentType) : normalizedContentType, override ? void 0 : headerDims);
184
+ return {
185
+ width: recordDims?.width,
186
+ height: recordDims?.height,
187
+ blurhash: placeholder?.blurhash,
188
+ dominantColor: placeholder?.dominantColor
189
+ };
190
+ }
191
+
192
+ //#endregion
193
+ export { generatePlaceholder as n, enrichImageMetadata as t };
194
+ //# sourceMappingURL=enrich-BQ0mxJRs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich-BQ0mxJRs.mjs","names":[],"sources":["../src/media/placeholder.ts","../src/media/enrich.ts"],"sourcesContent":["/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nimport { normalizeMime } from \"./mime.js\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n * Returns null when the header cannot be parsed.\n *\n * Shared by every caller that needs pixel dimensions so the header is parsed\n * once per buffer, not re-read inside generatePlaceholder.\n */\nexport function readDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. When present they are\n * trusted verbatim (the caller has typically already read them via\n * readDimensions); otherwise dimensions are read from this buffer's header.\n * Generation is skipped (returns null) when no dimensions are available at\n * all, or when the decoded size (width * height * 4) exceeds\n * MAX_DECODED_BYTES — both guards avoid OOM from unbounded decodes on\n * memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[normalizeMime(mimeType)];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Trust caller-supplied dimensions when present (the caller has usually\n\t\t// already read them via readDimensions); otherwise read them from this\n\t\t// buffer. The header is parsed at most once per call.\n\t\tconst dims = dimensions ?? readDimensions(buffer);\n\n\t\t// Safety net: the decoders allocate the full RGBA buffer with no internal\n\t\t// cap, so refuse to decode unless we can bound the output size. When we\n\t\t// have no parseable header AND no known dimensions, the decoded size is\n\t\t// unbounded — a crafted/truncated PNG whose header image-size can't read\n\t\t// could still be decodable by upng-js, so we must bail to avoid OOM on\n\t\t// memory-constrained runtimes. LQIP is progressive enhancement; missing\n\t\t// it is preferable to crashing the request.\n\t\tif (!dims) return null;\n\t\tif (dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n","/**\n * Image Metadata Enrichment\n *\n * Single seam that derives image dimensions and LQIP placeholders (blurhash,\n * dominant color) from raw image bytes. Every server-side media-creation path\n * routes through this so records are populated consistently. Pure-JS and\n * Workers-safe (image-size reads headers only; generatePlaceholder guards\n * decode size).\n */\n\nimport { normalizeMime } from \"./mime.js\";\nimport { generatePlaceholder, readDimensions } from \"./placeholder.js\";\n\nexport interface EnrichedImageMetadata {\n\twidth?: number;\n\theight?: number;\n\tblurhash?: string;\n\tdominantColor?: string;\n}\n\n/**\n * Derive dimensions + LQIP placeholders from image bytes.\n *\n * - Non-image content types return `{}`.\n * - `knownDimensions` (e.g. browser `naturalWidth/Height`) win over `image-size`\n * for the *stored record* because the browser applies EXIF orientation;\n * `image-size` reports raw header dimensions, which are swapped for\n * 90°/270°-rotated JPEGs. They are NOT used for the decode OOM guard — see below.\n * - The placeholder OOM guard uses only header dimensions read from the bytes\n * actually decoded. Caller-supplied `knownDimensions` are untrusted for the\n * guard: a client could claim a tiny size for a huge image to bypass the cap.\n * - `placeholder` lets a caller decode a smaller thumbnail for the blurhash to\n * avoid OOM on large originals; dimensions still come from `bytes`.\n * - Placeholders are jpeg/png only (the generator's supported formats); other\n * image types still get dimensions.\n */\nexport async function enrichImageMetadata(\n\tbytes: Uint8Array,\n\tcontentType: string,\n\topts?: {\n\t\tknownDimensions?: { width: number; height: number };\n\t\tplaceholder?: { bytes: Uint8Array; contentType: string };\n\t},\n): Promise<EnrichedImageMetadata> {\n\tconst normalizedContentType = normalizeMime(contentType);\n\tif (!normalizedContentType.startsWith(\"image/\")) return {};\n\n\t// Header dimensions are read once from the actual bytes. They feed the\n\t// placeholder OOM guard, which must never trust caller-supplied dimensions:\n\t// `knownDimensions` is decoupled from the buffer, so a client could claim a\n\t// tiny size for a huge image and slip past the decoded-size cap, making the\n\t// decoder allocate an unbounded RGBA buffer and OOM the runtime. Only dims\n\t// read from the buffer that actually gets decoded can bound the decode.\n\tconst headerDims = readDimensions(bytes) ?? undefined;\n\n\t// Dimensions published on the record prefer the caller's knownDimensions\n\t// (e.g. browser naturalWidth/Height, which apply EXIF orientation) over the\n\t// raw header dims, which are swapped for 90°/270°-rotated JPEGs.\n\tconst recordDims = opts?.knownDimensions ?? headerDims;\n\n\t// When a smaller thumbnail override is supplied, decode that for the blurhash\n\t// and let generatePlaceholder read the thumbnail's own header for the OOM\n\t// guard (the override buffer is what actually gets decoded). On the common\n\t// no-override path pass the header dims already read from this same buffer.\n\tconst override = opts?.placeholder;\n\tconst placeholder = await generatePlaceholder(\n\t\toverride ? override.bytes : bytes,\n\t\toverride ? normalizeMime(override.contentType) : normalizedContentType,\n\t\toverride ? undefined : headerDims,\n\t);\n\n\treturn {\n\t\twidth: recordDims?.width,\n\t\theight: recordDims?.height,\n\t\tblurhash: placeholder?.blurhash,\n\t\tdominantColor: placeholder?.dominantColor,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,kBAAkD;CACvD,cAAc;CACd,aAAa;CACb,aAAa;CACb;;AAGD,MAAM,mBAAmB;;AAGzB,MAAM,oBAAoB,KAAK,OAAO;;;;AAWtC,eAAe,WAAW,QAA2C;CACpE,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,OAAO,QAAQ,EAAE,WAAW,MAAM,CAAC;AAClD,QAAO;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,MAAM,OAAO;EAAM;;;;;;AAOzE,eAAe,UAAU,QAA2C;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,MAAM,aAAa,MAAM,mBAAmB;CAM5C,MAAM,WAAW,MAAM;CACvB,MAAM,cAAc,MAAM,oBACzB,WAAW,SAAS,QAAQ,OAC5B,WAAW,cAAc,SAAS,YAAY,GAAG,uBACjD,WAAW,SAAY,WACvB;AAED,QAAO;EACN,OAAO,YAAY;EACnB,QAAQ,YAAY;EACpB,UAAU,aAAa;EACvB,eAAe,aAAa;EAC5B"}
@@ -64,6 +64,7 @@ const ErrorCode = {
64
64
  COLLECTION_NOT_FOUND: "COLLECTION_NOT_FOUND",
65
65
  TABLE_NOT_FOUND: "TABLE_NOT_FOUND",
66
66
  FIELD_EXISTS: "FIELD_EXISTS",
67
+ FIELD_TYPE_COLUMN_CHANGE: "FIELD_TYPE_COLUMN_CHANGE",
67
68
  RESERVED_SLUG: "RESERVED_SLUG",
68
69
  INVALID_SLUG: "INVALID_SLUG",
69
70
  CREATE_FAILED: "CREATE_FAILED",
@@ -448,4 +449,4 @@ function unwrapResult(result, successStatus = 200) {
448
449
 
449
450
  //#endregion
450
451
  export { unwrapResult as a, requireDb as i, apiSuccess as n, mapErrorStatus as o, handleError as r, apiError as t };
451
- //# sourceMappingURL=error-lq_fL-RS.mjs.map
452
+ //# sourceMappingURL=error-DXnK2wF4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-DXnK2wF4.mjs","names":[],"sources":["../src/api/errors.ts","../src/api/error.ts"],"sourcesContent":["/**\n * Typed error codes and status mapping for the EmDash REST API.\n *\n * All handler-level and route-level error codes are defined here.\n * Routes and handlers should import error codes from this module\n * instead of using ad-hoc strings.\n */\n\nexport const ErrorCode = {\n\t// Shared (used across domains)\n\tNOT_FOUND: \"NOT_FOUND\",\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tINVALID_INPUT: \"INVALID_INPUT\",\n\tINVALID_JSON: \"INVALID_JSON\",\n\tINVALID_CURSOR: \"INVALID_CURSOR\",\n\tCONFLICT: \"CONFLICT\",\n\tSLUG_CONFLICT: \"SLUG_CONFLICT\",\n\tNOT_CONFIGURED: \"NOT_CONFIGURED\",\n\tUNAUTHORIZED: \"UNAUTHORIZED\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tRATE_LIMITED: \"RATE_LIMITED\",\n\tNOT_AUTHENTICATED: \"NOT_AUTHENTICATED\",\n\tNOT_IMPLEMENTED: \"NOT_IMPLEMENTED\",\n\tNOT_SUPPORTED: \"NOT_SUPPORTED\",\n\tMISSING_PARAM: \"MISSING_PARAM\",\n\tCSRF_REJECTED: \"CSRF_REJECTED\",\n\n\t// Content\n\tCONTENT_CREATE_ERROR: \"CONTENT_CREATE_ERROR\",\n\tCONTENT_UPDATE_ERROR: \"CONTENT_UPDATE_ERROR\",\n\tCONTENT_DELETE_ERROR: \"CONTENT_DELETE_ERROR\",\n\tCONTENT_LIST_ERROR: \"CONTENT_LIST_ERROR\",\n\tCONTENT_GET_ERROR: \"CONTENT_GET_ERROR\",\n\tCONTENT_DUPLICATE_ERROR: \"CONTENT_DUPLICATE_ERROR\",\n\tCONTENT_RESTORE_ERROR: \"CONTENT_RESTORE_ERROR\",\n\tCONTENT_PUBLISH_ERROR: \"CONTENT_PUBLISH_ERROR\",\n\tCONTENT_UNPUBLISH_ERROR: \"CONTENT_UNPUBLISH_ERROR\",\n\tCONTENT_SCHEDULE_ERROR: \"CONTENT_SCHEDULE_ERROR\",\n\tCONTENT_UNSCHEDULE_ERROR: \"CONTENT_UNSCHEDULE_ERROR\",\n\tCONTENT_DISCARD_DRAFT_ERROR: \"CONTENT_DISCARD_DRAFT_ERROR\",\n\tCONTENT_COMPARE_ERROR: \"CONTENT_COMPARE_ERROR\",\n\tCONTENT_TRANSLATIONS_ERROR: \"CONTENT_TRANSLATIONS_ERROR\",\n\tCONTENT_COUNT_ERROR: \"CONTENT_COUNT_ERROR\",\n\n\t// Revisions\n\tREVISION_LIST_ERROR: \"REVISION_LIST_ERROR\",\n\tREVISION_GET_ERROR: \"REVISION_GET_ERROR\",\n\tREVISION_RESTORE_ERROR: \"REVISION_RESTORE_ERROR\",\n\tINVALID_REVISION: \"INVALID_REVISION\",\n\n\t// Schema\n\tSCHEMA_LIST_ERROR: \"SCHEMA_LIST_ERROR\",\n\tSCHEMA_GET_ERROR: \"SCHEMA_GET_ERROR\",\n\tSCHEMA_CREATE_ERROR: \"SCHEMA_CREATE_ERROR\",\n\tSCHEMA_UPDATE_ERROR: \"SCHEMA_UPDATE_ERROR\",\n\tSCHEMA_DELETE_ERROR: \"SCHEMA_DELETE_ERROR\",\n\tSCHEMA_EXPORT_ERROR: \"SCHEMA_EXPORT_ERROR\",\n\tSCHEMA_FIELD_LIST_ERROR: \"SCHEMA_FIELD_LIST_ERROR\",\n\tSCHEMA_FIELD_GET_ERROR: \"SCHEMA_FIELD_GET_ERROR\",\n\tSCHEMA_FIELD_CREATE_ERROR: \"SCHEMA_FIELD_CREATE_ERROR\",\n\tSCHEMA_FIELD_UPDATE_ERROR: \"SCHEMA_FIELD_UPDATE_ERROR\",\n\tSCHEMA_FIELD_DELETE_ERROR: \"SCHEMA_FIELD_DELETE_ERROR\",\n\tSCHEMA_FIELD_REORDER_ERROR: \"SCHEMA_FIELD_REORDER_ERROR\",\n\t// Byline schema (Discussion #1174). Reuses RESERVED_SLUG, INVALID_SLUG,\n\t// INVALID_TYPE, FIELD_EXISTS, NOT_FOUND, VALIDATION_ERROR where the\n\t// semantics match; the two below are byline-domain specific:\n\tTRANSLATABLE_LOCKED: \"TRANSLATABLE_LOCKED\",\n\tREORDER_MISMATCH: \"REORDER_MISMATCH\",\n\tORPHAN_LIST_ERROR: \"ORPHAN_LIST_ERROR\",\n\tORPHAN_REGISTER_ERROR: \"ORPHAN_REGISTER_ERROR\",\n\tCOLLECTION_EXISTS: \"COLLECTION_EXISTS\",\n\tCOLLECTION_NOT_FOUND: \"COLLECTION_NOT_FOUND\",\n\tTABLE_NOT_FOUND: \"TABLE_NOT_FOUND\",\n\tFIELD_EXISTS: \"FIELD_EXISTS\",\n\tFIELD_TYPE_COLUMN_CHANGE: \"FIELD_TYPE_COLUMN_CHANGE\",\n\tRESERVED_SLUG: \"RESERVED_SLUG\",\n\tINVALID_SLUG: \"INVALID_SLUG\",\n\tCREATE_FAILED: \"CREATE_FAILED\",\n\tUPDATE_FAILED: \"UPDATE_FAILED\",\n\tREGISTER_FAILED: \"REGISTER_FAILED\",\n\n\t// Media\n\tMEDIA_LIST_ERROR: \"MEDIA_LIST_ERROR\",\n\tMEDIA_GET_ERROR: \"MEDIA_GET_ERROR\",\n\tMEDIA_CREATE_ERROR: \"MEDIA_CREATE_ERROR\",\n\tMEDIA_UPDATE_ERROR: \"MEDIA_UPDATE_ERROR\",\n\tMEDIA_DELETE_ERROR: \"MEDIA_DELETE_ERROR\",\n\tNO_STORAGE: \"NO_STORAGE\",\n\tNO_FILE: \"NO_FILE\",\n\tINVALID_TYPE: \"INVALID_TYPE\",\n\tUPLOAD_ERROR: \"UPLOAD_ERROR\",\n\tUPLOAD_URL_ERROR: \"UPLOAD_URL_ERROR\",\n\tCONFIRM_ERROR: \"CONFIRM_ERROR\",\n\tCONFIRM_FAILED: \"CONFIRM_FAILED\",\n\tFILE_NOT_FOUND: \"FILE_NOT_FOUND\",\n\tINVALID_STATE: \"INVALID_STATE\",\n\tFILE_SERVE_ERROR: \"FILE_SERVE_ERROR\",\n\tSTORAGE_NOT_CONFIGURED: \"STORAGE_NOT_CONFIGURED\",\n\tPROVIDER_LIST_ERROR: \"PROVIDER_LIST_ERROR\",\n\tPROVIDER_UPLOAD_ERROR: \"PROVIDER_UPLOAD_ERROR\",\n\tPROVIDER_GET_ERROR: \"PROVIDER_GET_ERROR\",\n\tPROVIDER_DELETE_ERROR: \"PROVIDER_DELETE_ERROR\",\n\n\t// Comments\n\tCOMMENT_LIST_ERROR: \"COMMENT_LIST_ERROR\",\n\tCOMMENT_GET_ERROR: \"COMMENT_GET_ERROR\",\n\tCOMMENT_STATUS_ERROR: \"COMMENT_STATUS_ERROR\",\n\tCOMMENT_DELETE_ERROR: \"COMMENT_DELETE_ERROR\",\n\tCOMMENT_BULK_ERROR: \"COMMENT_BULK_ERROR\",\n\tCOMMENT_INBOX_ERROR: \"COMMENT_INBOX_ERROR\",\n\tCOMMENT_COUNTS_ERROR: \"COMMENT_COUNTS_ERROR\",\n\tCOMMENT_CREATE_ERROR: \"COMMENT_CREATE_ERROR\",\n\tCOMMENTS_DISABLED: \"COMMENTS_DISABLED\",\n\tCOMMENTS_CLOSED: \"COMMENTS_CLOSED\",\n\tCOMMENT_REJECTED: \"COMMENT_REJECTED\",\n\n\t// Auth\n\tACCOUNT_DISABLED: \"ACCOUNT_DISABLED\",\n\tADMIN_EXISTS: \"ADMIN_EXISTS\",\n\tSETUP_COMPLETE: \"SETUP_COMPLETE\",\n\tCREDENTIAL_EXISTS: \"CREDENTIAL_EXISTS\",\n\tCHALLENGE_EXPIRED: \"CHALLENGE_EXPIRED\",\n\tPASSKEY_REGISTER_ERROR: \"PASSKEY_REGISTER_ERROR\",\n\tPASSKEY_REGISTER_OPTIONS_ERROR: \"PASSKEY_REGISTER_OPTIONS_ERROR\",\n\tPASSKEY_OPTIONS_ERROR: \"PASSKEY_OPTIONS_ERROR\",\n\tPASSKEY_VERIFY_ERROR: \"PASSKEY_VERIFY_ERROR\",\n\tPASSKEY_LIST_ERROR: \"PASSKEY_LIST_ERROR\",\n\tPASSKEY_RENAME_ERROR: \"PASSKEY_RENAME_ERROR\",\n\tPASSKEY_DELETE_ERROR: \"PASSKEY_DELETE_ERROR\",\n\tPASSKEY_LIMIT: \"PASSKEY_LIMIT\",\n\tLAST_PASSKEY: \"LAST_PASSKEY\",\n\tLOGOUT_ERROR: \"LOGOUT_ERROR\",\n\tSELF_ROLE_CHANGE: \"SELF_ROLE_CHANGE\",\n\tEMAIL_IN_USE: \"EMAIL_IN_USE\",\n\tEMAIL_NOT_CONFIGURED: \"EMAIL_NOT_CONFIGURED\",\n\tUSER_EXISTS: \"USER_EXISTS\",\n\tINVALID_TOKEN: \"INVALID_TOKEN\",\n\tTOKEN_EXPIRED: \"TOKEN_EXPIRED\",\n\tDOMAIN_NOT_ALLOWED: \"DOMAIN_NOT_ALLOWED\",\n\tINVITE_CREATE_ERROR: \"INVITE_CREATE_ERROR\",\n\tINVITE_VALIDATE_ERROR: \"INVITE_VALIDATE_ERROR\",\n\tINVITE_COMPLETE_ERROR: \"INVITE_COMPLETE_ERROR\",\n\tSIGNUP_VERIFY_ERROR: \"SIGNUP_VERIFY_ERROR\",\n\tSIGNUP_COMPLETE_ERROR: \"SIGNUP_COMPLETE_ERROR\",\n\tRECOVERY_SEND_ERROR: \"RECOVERY_SEND_ERROR\",\n\tUSER_LIST_ERROR: \"USER_LIST_ERROR\",\n\tUSER_DETAIL_ERROR: \"USER_DETAIL_ERROR\",\n\tUSER_UPDATE_ERROR: \"USER_UPDATE_ERROR\",\n\tUSER_DISABLE_ERROR: \"USER_DISABLE_ERROR\",\n\tUSER_ENABLE_ERROR: \"USER_ENABLE_ERROR\",\n\n\t// OAuth (internal codes -- distinct from RFC OAuthErrorCode)\n\tUNSUPPORTED_RESPONSE_TYPE: \"UNSUPPORTED_RESPONSE_TYPE\",\n\tINVALID_REDIRECT_URI: \"INVALID_REDIRECT_URI\",\n\tINVALID_CLIENT: \"INVALID_CLIENT\",\n\tINVALID_SCOPE: \"INVALID_SCOPE\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tINVALID_GRANT: \"INVALID_GRANT\",\n\tUNSUPPORTED_GRANT_TYPE: \"UNSUPPORTED_GRANT_TYPE\",\n\tINVALID_CODE: \"INVALID_CODE\",\n\tEXPIRED_CODE: \"EXPIRED_CODE\",\n\tINSUFFICIENT_ROLE: \"INSUFFICIENT_ROLE\",\n\tINSUFFICIENT_SCOPE: \"INSUFFICIENT_SCOPE\",\n\tINSUFFICIENT_PERMISSIONS: \"INSUFFICIENT_PERMISSIONS\",\n\tTOKEN_EXCHANGE_ERROR: \"TOKEN_EXCHANGE_ERROR\",\n\tTOKEN_REFRESH_ERROR: \"TOKEN_REFRESH_ERROR\",\n\tTOKEN_REVOKE_ERROR: \"TOKEN_REVOKE_ERROR\",\n\tTOKEN_CREATE_ERROR: \"TOKEN_CREATE_ERROR\",\n\tTOKEN_LIST_ERROR: \"TOKEN_LIST_ERROR\",\n\tTOKEN_ERROR: \"TOKEN_ERROR\",\n\tDEVICE_CODE_ERROR: \"DEVICE_CODE_ERROR\",\n\tAUTHORIZE_ERROR: \"AUTHORIZE_ERROR\",\n\tCLIENT_LIST_ERROR: \"CLIENT_LIST_ERROR\",\n\tCLIENT_GET_ERROR: \"CLIENT_GET_ERROR\",\n\tCLIENT_CREATE_ERROR: \"CLIENT_CREATE_ERROR\",\n\tCLIENT_UPDATE_ERROR: \"CLIENT_UPDATE_ERROR\",\n\tCLIENT_DELETE_ERROR: \"CLIENT_DELETE_ERROR\",\n\n\t// Allowed domains\n\tDOMAIN_LIST_ERROR: \"DOMAIN_LIST_ERROR\",\n\tDOMAIN_CREATE_ERROR: \"DOMAIN_CREATE_ERROR\",\n\tDOMAIN_UPDATE_ERROR: \"DOMAIN_UPDATE_ERROR\",\n\tDOMAIN_DELETE_ERROR: \"DOMAIN_DELETE_ERROR\",\n\n\t// Plugins / Marketplace\n\tPLUGIN_LIST_ERROR: \"PLUGIN_LIST_ERROR\",\n\tPLUGIN_GET_ERROR: \"PLUGIN_GET_ERROR\",\n\tPLUGIN_ENABLE_ERROR: \"PLUGIN_ENABLE_ERROR\",\n\tPLUGIN_DISABLE_ERROR: \"PLUGIN_DISABLE_ERROR\",\n\tPLUGIN_ID_CONFLICT: \"PLUGIN_ID_CONFLICT\",\n\tMARKETPLACE_NOT_CONFIGURED: \"MARKETPLACE_NOT_CONFIGURED\",\n\tMARKETPLACE_UNAVAILABLE: \"MARKETPLACE_UNAVAILABLE\",\n\tMARKETPLACE_ERROR: \"MARKETPLACE_ERROR\",\n\tSANDBOX_NOT_AVAILABLE: \"SANDBOX_NOT_AVAILABLE\",\n\tALREADY_INSTALLED: \"ALREADY_INSTALLED\",\n\tALREADY_UP_TO_DATE: \"ALREADY_UP_TO_DATE\",\n\tNO_VERSION: \"NO_VERSION\",\n\tMANIFEST_MISMATCH: \"MANIFEST_MISMATCH\",\n\tMANIFEST_VERSION_MISMATCH: \"MANIFEST_VERSION_MISMATCH\",\n\tAUDIT_FAILED: \"AUDIT_FAILED\",\n\tCHECKSUM_MISMATCH: \"CHECKSUM_MISMATCH\",\n\tINVALID_BUNDLE: \"INVALID_BUNDLE\",\n\tBUNDLE_EXTRACT_FAILED: \"BUNDLE_EXTRACT_FAILED\",\n\tBUNDLE_DOWNLOAD_FAILED: \"BUNDLE_DOWNLOAD_FAILED\",\n\tAGGREGATOR_RESPONSE_INVALID: \"AGGREGATOR_RESPONSE_INVALID\",\n\tAGGREGATOR_HTTP_ERROR: \"AGGREGATOR_HTTP_ERROR\",\n\tAGGREGATOR_NOT_FOUND: \"AGGREGATOR_NOT_FOUND\",\n\tCAPABILITY_ESCALATION: \"CAPABILITY_ESCALATION\",\n\tROUTE_VISIBILITY_ESCALATION: \"ROUTE_VISIBILITY_ESCALATION\",\n\tENV_INCOMPATIBLE: \"ENV_INCOMPATIBLE\",\n\tINSTALL_FAILED: \"INSTALL_FAILED\",\n\tUNINSTALL_FAILED: \"UNINSTALL_FAILED\",\n\tSEARCH_FAILED: \"SEARCH_FAILED\",\n\tGET_PLUGIN_FAILED: \"GET_PLUGIN_FAILED\",\n\tGET_THEME_FAILED: \"GET_THEME_FAILED\",\n\tTHEME_SEARCH_FAILED: \"THEME_SEARCH_FAILED\",\n\tUPDATE_CHECK_FAILED: \"UPDATE_CHECK_FAILED\",\n\tEXCLUSIVE_HOOKS_LIST_ERROR: \"EXCLUSIVE_HOOKS_LIST_ERROR\",\n\tEXCLUSIVE_HOOK_SET_ERROR: \"EXCLUSIVE_HOOK_SET_ERROR\",\n\n\t// Menus\n\tMENU_LIST_ERROR: \"MENU_LIST_ERROR\",\n\tMENU_CREATE_ERROR: \"MENU_CREATE_ERROR\",\n\tMENU_GET_ERROR: \"MENU_GET_ERROR\",\n\tMENU_UPDATE_ERROR: \"MENU_UPDATE_ERROR\",\n\tMENU_DELETE_ERROR: \"MENU_DELETE_ERROR\",\n\tMENU_ITEM_CREATE_ERROR: \"MENU_ITEM_CREATE_ERROR\",\n\tMENU_ITEM_UPDATE_ERROR: \"MENU_ITEM_UPDATE_ERROR\",\n\tMENU_ITEM_DELETE_ERROR: \"MENU_ITEM_DELETE_ERROR\",\n\tMENU_REORDER_ERROR: \"MENU_REORDER_ERROR\",\n\t// Returned when a menu name resolves to multiple locale variants and\n\t// the caller did not pass `locale` to disambiguate. (name, locale) is\n\t// unique, so this only fires for omitted-locale lookups.\n\tAMBIGUOUS_LOCALE: \"AMBIGUOUS_LOCALE\",\n\n\t// Taxonomies\n\tTAXONOMY_LIST_ERROR: \"TAXONOMY_LIST_ERROR\",\n\tTAXONOMY_CREATE_ERROR: \"TAXONOMY_CREATE_ERROR\",\n\tTERM_LIST_ERROR: \"TERM_LIST_ERROR\",\n\tTERM_CREATE_ERROR: \"TERM_CREATE_ERROR\",\n\tTERM_GET_ERROR: \"TERM_GET_ERROR\",\n\tTERM_UPDATE_ERROR: \"TERM_UPDATE_ERROR\",\n\tTERM_DELETE_ERROR: \"TERM_DELETE_ERROR\",\n\tTERMS_GET_ERROR: \"TERMS_GET_ERROR\",\n\tTERMS_SET_ERROR: \"TERMS_SET_ERROR\",\n\n\t// Sections\n\tSECTION_LIST_ERROR: \"SECTION_LIST_ERROR\",\n\tSECTION_CREATE_ERROR: \"SECTION_CREATE_ERROR\",\n\tSECTION_GET_ERROR: \"SECTION_GET_ERROR\",\n\tSECTION_UPDATE_ERROR: \"SECTION_UPDATE_ERROR\",\n\tSECTION_DELETE_ERROR: \"SECTION_DELETE_ERROR\",\n\n\t// Redirects\n\tREDIRECT_LIST_ERROR: \"REDIRECT_LIST_ERROR\",\n\tREDIRECT_CREATE_ERROR: \"REDIRECT_CREATE_ERROR\",\n\tREDIRECT_GET_ERROR: \"REDIRECT_GET_ERROR\",\n\tREDIRECT_UPDATE_ERROR: \"REDIRECT_UPDATE_ERROR\",\n\tREDIRECT_DELETE_ERROR: \"REDIRECT_DELETE_ERROR\",\n\tNOT_FOUND_LIST_ERROR: \"NOT_FOUND_LIST_ERROR\",\n\tNOT_FOUND_SUMMARY_ERROR: \"NOT_FOUND_SUMMARY_ERROR\",\n\tNOT_FOUND_CLEAR_ERROR: \"NOT_FOUND_CLEAR_ERROR\",\n\tNOT_FOUND_PRUNE_ERROR: \"NOT_FOUND_PRUNE_ERROR\",\n\n\t// Widgets\n\tWIDGET_AREA_LIST_ERROR: \"WIDGET_AREA_LIST_ERROR\",\n\tWIDGET_AREA_CREATE_ERROR: \"WIDGET_AREA_CREATE_ERROR\",\n\tWIDGET_AREA_GET_ERROR: \"WIDGET_AREA_GET_ERROR\",\n\tWIDGET_AREA_DELETE_ERROR: \"WIDGET_AREA_DELETE_ERROR\",\n\tWIDGET_CREATE_ERROR: \"WIDGET_CREATE_ERROR\",\n\tWIDGET_UPDATE_ERROR: \"WIDGET_UPDATE_ERROR\",\n\tWIDGET_DELETE_ERROR: \"WIDGET_DELETE_ERROR\",\n\tWIDGET_REORDER_ERROR: \"WIDGET_REORDER_ERROR\",\n\tWIDGET_COMPONENTS_ERROR: \"WIDGET_COMPONENTS_ERROR\",\n\n\t// Setup\n\tALREADY_CONFIGURED: \"ALREADY_CONFIGURED\",\n\tINVALID_SEED: \"INVALID_SEED\",\n\tINVALID_REDIRECT: \"INVALID_REDIRECT\",\n\tSETUP_ERROR: \"SETUP_ERROR\",\n\tSETUP_STATUS_ERROR: \"SETUP_STATUS_ERROR\",\n\tSETUP_ADMIN_ERROR: \"SETUP_ADMIN_ERROR\",\n\tSETUP_VERIFY_ERROR: \"SETUP_VERIFY_ERROR\",\n\tDEV_BYPASS_ERROR: \"DEV_BYPASS_ERROR\",\n\tDEV_RESET_ERROR: \"DEV_RESET_ERROR\",\n\tMIGRATION_ERROR: \"MIGRATION_ERROR\",\n\tSEED_ERROR: \"SEED_ERROR\",\n\n\t// Settings\n\tSETTINGS_READ_ERROR: \"SETTINGS_READ_ERROR\",\n\tSETTINGS_UPDATE_ERROR: \"SETTINGS_UPDATE_ERROR\",\n\tEMAIL_SETTINGS_READ_ERROR: \"EMAIL_SETTINGS_READ_ERROR\",\n\tEMAIL_TEST_ERROR: \"EMAIL_TEST_ERROR\",\n\n\t// Search\n\tSEARCH_ERROR: \"SEARCH_ERROR\",\n\tSTATS_ERROR: \"STATS_ERROR\",\n\tSUGGESTION_ERROR: \"SUGGESTION_ERROR\",\n\tREBUILD_ERROR: \"REBUILD_ERROR\",\n\n\t// Import\n\tWXR_ANALYZE_ERROR: \"WXR_ANALYZE_ERROR\",\n\tWXR_PREPARE_ERROR: \"WXR_PREPARE_ERROR\",\n\tWXR_IMPORT_ERROR: \"WXR_IMPORT_ERROR\",\n\tIMPORT_ERROR: \"IMPORT_ERROR\",\n\tREWRITE_ERROR: \"REWRITE_ERROR\",\n\tWP_PLUGIN_ANALYZE_ERROR: \"WP_PLUGIN_ANALYZE_ERROR\",\n\tWP_PLUGIN_IMPORT_ERROR: \"WP_PLUGIN_IMPORT_ERROR\",\n\tSSRF_BLOCKED: \"SSRF_BLOCKED\",\n\tPROBE_ERROR: \"PROBE_ERROR\",\n\n\t// Dashboard\n\tDASHBOARD_ERROR: \"DASHBOARD_ERROR\",\n\tDASHBOARD_STATS_ERROR: \"DASHBOARD_STATS_ERROR\",\n\n\t// Misc\n\tSNAPSHOT_ERROR: \"SNAPSHOT_ERROR\",\n\tTYPEGEN_ERROR: \"TYPEGEN_ERROR\",\n\tSITEMAP_ERROR: \"SITEMAP_ERROR\",\n\tNO_DB: \"NO_DB\",\n\tINVALID_REQUEST: \"INVALID_REQUEST\",\n\tUNKNOWN_ACTION: \"UNKNOWN_ACTION\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\n/**\n * OAuth RFC 6749 error codes.\n *\n * These MUST be lowercase per the RFC spec. Used only by OAuth token endpoints.\n * Separate from ErrorCode to prevent mixing conventions.\n */\nexport const OAuthErrorCode = {\n\tINVALID_GRANT: \"invalid_grant\",\n\tUNSUPPORTED_GRANT_TYPE: \"unsupported_grant_type\",\n\tEXPIRED_TOKEN: \"expired_token\",\n\tACCESS_DENIED: \"access_denied\",\n\tAUTHORIZATION_PENDING: \"authorization_pending\",\n} as const;\n\nexport type OAuthErrorCode = (typeof OAuthErrorCode)[keyof typeof OAuthErrorCode];\n\n/**\n * Map a handler error code to an HTTP status code.\n *\n * Shared codes have explicit mappings. Domain-specific `*_ERROR` codes\n * (used in catch blocks via handleError) default to 500. Everything else\n * defaults to 400 (client error).\n */\nexport function mapErrorStatus(code: string | undefined): number {\n\tswitch (code) {\n\t\t// 400 Bad Request\n\t\tcase ErrorCode.VALIDATION_ERROR:\n\t\tcase ErrorCode.INVALID_INPUT:\n\t\tcase ErrorCode.INVALID_JSON:\n\t\tcase ErrorCode.INVALID_CURSOR:\n\t\tcase ErrorCode.MISSING_PARAM:\n\t\tcase ErrorCode.INVALID_REQUEST:\n\t\tcase ErrorCode.NOT_SUPPORTED:\n\t\tcase ErrorCode.INVALID_SLUG:\n\t\tcase ErrorCode.RESERVED_SLUG:\n\t\tcase ErrorCode.INVALID_TYPE:\n\t\tcase ErrorCode.NO_FILE:\n\t\tcase ErrorCode.INVALID_STATE:\n\t\tcase ErrorCode.INVALID_SEED:\n\t\tcase ErrorCode.INVALID_REDIRECT:\n\t\tcase ErrorCode.INVALID_TOKEN:\n\t\tcase ErrorCode.INVALID_REVISION:\n\t\tcase ErrorCode.INVALID_CODE:\n\t\tcase ErrorCode.CHALLENGE_EXPIRED:\n\t\tcase ErrorCode.EXPIRED_CODE:\n\t\tcase ErrorCode.LAST_PASSKEY:\n\t\tcase ErrorCode.PASSKEY_LIMIT:\n\t\tcase ErrorCode.ADMIN_EXISTS:\n\t\tcase ErrorCode.SETUP_COMPLETE:\n\t\tcase ErrorCode.SELF_ROLE_CHANGE:\n\t\tcase ErrorCode.SSRF_BLOCKED:\n\t\tcase ErrorCode.UNKNOWN_ACTION:\n\t\tcase ErrorCode.AMBIGUOUS_LOCALE:\n\t\tcase ErrorCode.REORDER_MISMATCH:\n\t\t\treturn 400;\n\n\t\t// 401 Unauthorized\n\t\tcase ErrorCode.UNAUTHORIZED:\n\t\tcase ErrorCode.NOT_AUTHENTICATED:\n\t\t\treturn 401;\n\n\t\t// 403 Forbidden\n\t\tcase ErrorCode.FORBIDDEN:\n\t\tcase ErrorCode.CSRF_REJECTED:\n\t\tcase ErrorCode.ACCOUNT_DISABLED:\n\t\tcase ErrorCode.COMMENTS_DISABLED:\n\t\tcase ErrorCode.COMMENTS_CLOSED:\n\t\tcase ErrorCode.COMMENT_REJECTED:\n\t\tcase ErrorCode.DOMAIN_NOT_ALLOWED:\n\t\tcase ErrorCode.INSUFFICIENT_ROLE:\n\t\tcase ErrorCode.INSUFFICIENT_SCOPE:\n\t\tcase ErrorCode.INSUFFICIENT_PERMISSIONS:\n\t\tcase ErrorCode.CAPABILITY_ESCALATION:\n\t\tcase ErrorCode.ROUTE_VISIBILITY_ESCALATION:\n\t\tcase ErrorCode.AUDIT_FAILED:\n\t\t\treturn 403;\n\n\t\t// 404 Not Found\n\t\tcase ErrorCode.NOT_FOUND:\n\t\tcase ErrorCode.TABLE_NOT_FOUND:\n\t\tcase ErrorCode.COLLECTION_NOT_FOUND:\n\t\tcase ErrorCode.FILE_NOT_FOUND:\n\t\tcase ErrorCode.NO_VERSION:\n\t\tcase ErrorCode.AGGREGATOR_NOT_FOUND:\n\t\t\treturn 404;\n\n\t\t// 409 Conflict\n\t\tcase ErrorCode.CONFLICT:\n\t\tcase ErrorCode.SLUG_CONFLICT:\n\t\tcase ErrorCode.COLLECTION_EXISTS:\n\t\tcase ErrorCode.FIELD_EXISTS:\n\t\tcase ErrorCode.CREDENTIAL_EXISTS:\n\t\tcase ErrorCode.EMAIL_IN_USE:\n\t\tcase ErrorCode.USER_EXISTS:\n\t\tcase ErrorCode.PLUGIN_ID_CONFLICT:\n\t\tcase ErrorCode.ALREADY_INSTALLED:\n\t\tcase ErrorCode.ALREADY_CONFIGURED:\n\t\tcase ErrorCode.ALREADY_UP_TO_DATE:\n\t\tcase ErrorCode.TRANSLATABLE_LOCKED:\n\t\tcase ErrorCode.ENV_INCOMPATIBLE:\n\t\t\treturn 409;\n\n\t\t// 410 Gone\n\t\tcase ErrorCode.TOKEN_EXPIRED:\n\t\t\treturn 410;\n\n\t\t// 422 Unprocessable Entity\n\t\tcase ErrorCode.CHECKSUM_MISMATCH:\n\t\tcase ErrorCode.INVALID_BUNDLE:\n\t\tcase ErrorCode.BUNDLE_EXTRACT_FAILED:\n\t\t\treturn 422;\n\n\t\t// 429 Too Many Requests\n\t\tcase ErrorCode.RATE_LIMITED:\n\t\t\treturn 429;\n\n\t\t// 500 Internal Server Error\n\t\tcase ErrorCode.NOT_CONFIGURED:\n\t\tcase ErrorCode.NO_STORAGE:\n\t\tcase ErrorCode.NO_DB:\n\t\tcase ErrorCode.STORAGE_NOT_CONFIGURED:\n\t\tcase ErrorCode.EMAIL_NOT_CONFIGURED:\n\t\t\treturn 500;\n\n\t\t// 501 Not Implemented\n\t\tcase ErrorCode.NOT_IMPLEMENTED:\n\t\t\treturn 501;\n\n\t\t// 502 Bad Gateway\n\t\tcase ErrorCode.BUNDLE_DOWNLOAD_FAILED:\n\t\tcase ErrorCode.AGGREGATOR_RESPONSE_INVALID:\n\t\tcase ErrorCode.AGGREGATOR_HTTP_ERROR:\n\t\t\treturn 502;\n\n\t\t// 503 Service Unavailable\n\t\tcase ErrorCode.MARKETPLACE_UNAVAILABLE:\n\t\tcase ErrorCode.MARKETPLACE_NOT_CONFIGURED:\n\t\tcase ErrorCode.SANDBOX_NOT_AVAILABLE:\n\t\t\treturn 503;\n\n\t\t// Domain-specific *_ERROR codes are catch-block codes -- always 500.\n\t\t// WARNING: If adding a new code that ends in _ERROR but represents a\n\t\t// client error (4xx), add it to an explicit case above or it will\n\t\t// be incorrectly mapped to 500.\n\t\tdefault:\n\t\t\treturn code?.endsWith(\"_ERROR\") ? 500 : 400;\n\t}\n}\n","/**\n * Standardized API error responses.\n *\n * All API routes should use these utilities instead of inline\n * `new Response(JSON.stringify({ error: ... }), ...)` patterns.\n */\n\nimport { InvalidCursorError } from \"../database/repositories/types.js\";\nimport { mapErrorStatus } from \"./errors.js\";\nimport type { ApiResult } from \"./types.js\";\n\n// Re-export everything from errors.ts so existing `import { mapErrorStatus } from \"./error.js\"` still works\nexport * from \"./errors.js\";\n\n/**\n * Standard cache headers for all API responses.\n *\n * Cache-Control: private, no-store -- prevents CDN/proxy caching of authenticated data.\n * no-store already tells caches not to store the response, so Vary is unnecessary.\n */\nconst API_CACHE_HEADERS: HeadersInit = {\n\t\"Cache-Control\": \"private, no-store\",\n};\n\n/**\n * Create a standardized error response.\n *\n * Always returns `{ error: { code, message } }` with correct Content-Type.\n * Use this for all error responses in API routes.\n */\nexport function apiError(\n\tcode: string,\n\tmessage: string,\n\tstatus: number,\n\tdetails?: Record<string, unknown>,\n): Response {\n\tconst error: { code: string; message: string; details?: Record<string, unknown> } = {\n\t\tcode,\n\t\tmessage,\n\t};\n\tif (details !== undefined) error.details = details;\n\treturn Response.json({ error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ data: T }` with correct status code.\n * Use this for all success responses in API routes.\n */\nexport function apiSuccess<T>(data: T, status = 200): Response {\n\treturn Response.json({ data }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Handle an unknown error in a catch block.\n *\n * - Logs the full error server-side\n * - Returns a generic message to the client (never leaks error.message)\n * - Use `fallbackMessage` for the public-facing message\n * - Use `fallbackCode` for the error code\n */\nexport function handleError(\n\terror: unknown,\n\tfallbackMessage: string,\n\tfallbackCode: string,\n): Response {\n\t// Bubble malformed-cursor errors as a structured 400 instead of a\n\t// generic 500.\n\tif (error instanceof InvalidCursorError) {\n\t\treturn apiError(\"INVALID_CURSOR\", error.message, 400);\n\t}\n\tconsole.error(`[${fallbackCode}]`, error);\n\treturn apiError(fallbackCode, fallbackMessage, 500);\n}\n\n/**\n * Standard initialization check.\n *\n * Returns an error response if EmDash is not initialized, or null if OK.\n * Usage: `const err = requireInit(emdash); if (err) return err;`\n */\nexport function requireInit(emdash: unknown): Response | null {\n\tif (!emdash || typeof emdash !== \"object\") {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Standard database check.\n *\n * Returns an error response if the database is not available, or null if OK.\n * Usage: `const err = requireDb(emdash?.db); if (err) return err;`\n */\nexport function requireDb(db: unknown): Response | null {\n\tif (!db) {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Convert an ApiResult into an HTTP Response.\n *\n * Collapses the handler-to-response boilerplate:\n * - Success: returns `apiSuccess(result.data, successStatus)`\n * - Error: returns `apiError(code, message, mapErrorStatus(code))`\n */\nexport function unwrapResult<T>(result: ApiResult<T>, successStatus = 200): Response {\n\tif (!result.success) {\n\t\treturn apiError(\n\t\t\tresult.error.code,\n\t\t\tresult.error.message,\n\t\t\tmapErrorStatus(result.error.code),\n\t\t\tresult.error.details,\n\t\t);\n\t}\n\treturn apiSuccess(result.data, successStatus);\n}\n"],"mappings":";;;;;;;;;;AAQA,MAAa,YAAY;CAExB,WAAW;CACX,kBAAkB;CAClB,eAAe;CACf,cAAc;CACd,gBAAgB;CAChB,UAAU;CACV,eAAe;CACf,gBAAgB;CAChB,cAAc;CACd,WAAW;CACX,cAAc;CACd,mBAAmB;CACnB,iBAAiB;CACjB,eAAe;CACf,eAAe;CACf,eAAe;CAGf,sBAAsB;CACtB,sBAAsB;CACtB,sBAAsB;CACtB,oBAAoB;CACpB,mBAAmB;CACnB,yBAAyB;CACzB,uBAAuB;CACvB,uBAAuB;CACvB,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sBACd,QAAO;EAMR,QACC,QAAO,MAAM,SAAS,SAAS,GAAG,MAAM;;;;;;;;;;;;;;;;;;ACnc3C,MAAM,oBAAiC,EACtC,iBAAiB,qBACjB;;;;;;;AAQD,SAAgB,SACf,MACA,SACA,QACA,SACW;CACX,MAAM,QAA8E;EACnF;EACA;EACA;AACD,KAAI,YAAY,OAAW,OAAM,UAAU;AAC3C,QAAO,SAAS,KAAK,EAAE,OAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxE,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK,EAAE,MAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWvE,SAAgB,YACf,OACA,iBACA,cACW;AAGX,KAAI,iBAAiB,mBACpB,QAAO,SAAS,kBAAkB,MAAM,SAAS,IAAI;AAEtD,SAAQ,MAAM,IAAI,aAAa,IAAI,MAAM;AACzC,QAAO,SAAS,cAAc,iBAAiB,IAAI;;;;;;;;AAsBpD,SAAgB,UAAU,IAA8B;AACvD,KAAI,CAAC,GACJ,QAAO,SAAS,kBAAkB,6BAA6B,IAAI;AAEpE,QAAO;;;;;;;;;AAUR,SAAgB,aAAgB,QAAsB,gBAAgB,KAAe;AACpF,KAAI,CAAC,OAAO,QACX,QAAO,SACN,OAAO,MAAM,MACb,OAAO,MAAM,SACb,eAAe,OAAO,MAAM,KAAK,EACjC,OAAO,MAAM,QACb;AAEF,QAAO,WAAW,OAAO,MAAM,cAAc"}
@@ -1,9 +1,9 @@
1
- import { _ as UpdateFieldInput, f as FieldValidation, g as UpdateCollectionInput, i as CollectionWithFields, o as CreateCollectionInput, s as CreateFieldInput, t as Collection, u as Field } from "./types-CTLJYMhN.mjs";
2
- import { f as UpdateContentInput, i as ContentItem, l as FindManyOptions, o as ContentSeoInput, r as ContentDateField, s as CreateContentInput, t as BylineSummary, u as FindManyResult } from "./types-BWh2MjmA.mjs";
3
- import { d as ContentListResponse, f as ContentResponse, h as ManifestResponse, u as ApiResult } from "./options-CqECG0gM.mjs";
1
+ import { _ as UpdateFieldInput, f as FieldValidation, g as UpdateCollectionInput, i as CollectionWithFields, o as CreateCollectionInput, s as CreateFieldInput, t as Collection, u as Field } from "./types-CNlaBFzx.mjs";
2
+ import { f as UpdateContentInput, i as ContentItem, l as FindManyOptions, o as ContentSeoInput, r as ContentDateField, s as CreateContentInput, t as BylineSummary, u as FindManyResult } from "./types-ETmO_jQr.mjs";
3
+ import { d as ContentListResponse, f as ContentResponse, h as ManifestResponse, u as ApiResult } from "./options-BvClpP5Q.mjs";
4
4
  import { t as Database } from "./types-B-gIxFCE.mjs";
5
- import { Dt as WhereClause, G as MediaItem$1, I as HttpAccess, J as PageFragmentContribution, M as EmailMessage, N as FieldWidgetConfig, Q as PageMetadataEvent, S as CronEvent, St as StorageCollection, Y as PageFragmentEvent, Z as PageMetadataContribution, _t as RequestMeta, c as CommentBeforeCreateEvent, ct as PluginDefinition, ft as PluginStorageConfig, gt as QueryOptions, i as CommentAfterCreateEvent, nt as PaginatedResult, o as CommentAfterModerateEvent, pt as PortableTextBlockConfig, ut as PluginManifest, yt as ResolvedPlugin } from "./types-TTx8uP7V.mjs";
6
- import { _ as MediaValue, m as MediaProviderDescriptor } from "./placeholder-QoI4gEzP.mjs";
5
+ import { $ as PageMetadataEvent, C as CronEvent, Ct as StorageCollection, K as MediaItem$1, L as HttpAccess, N as EmailMessage, Ot as WhereClause, P as FieldWidgetConfig, Q as PageMetadataContribution, X as PageFragmentEvent, Y as PageFragmentContribution, _t as QueryOptions, bt as ResolvedPlugin, c as CommentBeforeCreateEvent, dt as PluginManifest, i as CommentAfterCreateEvent, lt as PluginDefinition, mt as PortableTextBlockConfig, o as CommentAfterModerateEvent, pt as PluginStorageConfig, rt as PaginatedResult, vt as RequestMeta } from "./types-h2Cwbzi2.mjs";
6
+ import { _ as MediaValue, m as MediaProviderDescriptor } from "./placeholder-Cuce9U-m.mjs";
7
7
  import { C as ContentBylineInput } from "./index-qbL02uhs.mjs";
8
8
  import { i as SiteSettings, r as SiteSettingKey } from "./types-BG8_XTLj.mjs";
9
9
  import { d as Storage } from "./types-DrYMm9s5.mjs";
@@ -107,7 +107,7 @@ declare class ContentRepository {
107
107
  /**
108
108
  * Restore content from trash
109
109
  */
110
- restore(type: string, id: string): Promise<boolean>;
110
+ restore(type: string, id: string): Promise<ContentItem | null>;
111
111
  /**
112
112
  * Permanently delete content (cannot be undone)
113
113
  */
@@ -338,6 +338,8 @@ declare class MediaRepository {
338
338
  width?: number;
339
339
  height?: number;
340
340
  size?: number;
341
+ blurhash?: string;
342
+ dominantColor?: string;
341
343
  }): Promise<MediaItem | null>;
342
344
  /**
343
345
  * Mark upload as failed
@@ -776,6 +778,7 @@ declare function handleContentDelete(db: Kysely<Database>, collection: string, i
776
778
  */
777
779
  declare function handleContentRestore(db: Kysely<Database>, collection: string, id: string): Promise<ApiResult<{
778
780
  restored: true;
781
+ item: ContentItem;
779
782
  }>>;
780
783
  /**
781
784
  * Permanently delete content item (cannot be undone).
@@ -3149,6 +3152,7 @@ declare const pluginManifestSchema: z$1.ZodObject<{
3149
3152
  "content:afterDelete": "content:afterDelete";
3150
3153
  "content:afterPublish": "content:afterPublish";
3151
3154
  "content:afterUnpublish": "content:afterUnpublish";
3155
+ "content:afterRestore": "content:afterRestore";
3152
3156
  "media:beforeUpload": "media:beforeUpload";
3153
3157
  "media:afterUpload": "media:afterUpload";
3154
3158
  cron: "cron";
@@ -3173,6 +3177,7 @@ declare const pluginManifestSchema: z$1.ZodObject<{
3173
3177
  "content:afterDelete": "content:afterDelete";
3174
3178
  "content:afterPublish": "content:afterPublish";
3175
3179
  "content:afterUnpublish": "content:afterUnpublish";
3180
+ "content:afterRestore": "content:afterRestore";
3176
3181
  "media:beforeUpload": "media:beforeUpload";
3177
3182
  "media:afterUpload": "media:afterUpload";
3178
3183
  cron: "cron";
@@ -3285,7 +3290,7 @@ declare const pluginManifestSchema: z$1.ZodObject<{
3285
3290
  type ValidatedPluginManifest = z$1.infer<typeof pluginManifestSchema>;
3286
3291
  //#endregion
3287
3292
  //#region src/plugins/hooks.d.ts
3288
- type HookNameV2 = "plugin:install" | "plugin:activate" | "plugin:deactivate" | "plugin:uninstall" | "content:beforeSave" | "content:afterSave" | "content:beforeDelete" | "content:afterDelete" | "content:afterPublish" | "content:afterUnpublish" | "media:beforeUpload" | "media:afterUpload" | "cron" | "email:beforeSend" | "email:deliver" | "email:afterSend" | "comment:beforeCreate" | "comment:moderate" | "comment:afterCreate" | "comment:afterModerate" | "page:metadata" | "page:fragments";
3293
+ type HookNameV2 = "plugin:install" | "plugin:activate" | "plugin:deactivate" | "plugin:uninstall" | "content:beforeSave" | "content:afterSave" | "content:beforeDelete" | "content:afterDelete" | "content:afterPublish" | "content:afterUnpublish" | "content:afterRestore" | "media:beforeUpload" | "media:afterUpload" | "cron" | "email:beforeSend" | "email:deliver" | "email:afterSend" | "comment:beforeCreate" | "comment:moderate" | "comment:afterCreate" | "comment:afterModerate" | "page:metadata" | "page:fragments";
3289
3294
  /**
3290
3295
  * Hook execution result
3291
3296
  */
@@ -3416,6 +3421,10 @@ declare class HookPipeline {
3416
3421
  * Run content:afterUnpublish hooks (fire-and-forget).
3417
3422
  */
3418
3423
  runContentAfterUnpublish(content: Record<string, unknown>, collection: string): Promise<HookResult<void>[]>;
3424
+ /**
3425
+ * Run content:afterRestore hooks (fire-and-forget).
3426
+ */
3427
+ runContentAfterRestore(content: Record<string, unknown>, collection: string): Promise<HookResult<void>[]>;
3419
3428
  /**
3420
3429
  * Run media:beforeUpload hooks
3421
3430
  */
@@ -3858,6 +3867,10 @@ declare class PluginManager {
3858
3867
  * Run content:afterUnpublish hooks across all active plugins
3859
3868
  */
3860
3869
  runContentAfterUnpublish(content: Record<string, unknown>, collection: string): Promise<HookResult<void>[]>;
3870
+ /**
3871
+ * Run content:afterRestore hooks across all active plugins
3872
+ */
3873
+ runContentAfterRestore(content: Record<string, unknown>, collection: string): Promise<HookResult<void>[]>;
3861
3874
  /**
3862
3875
  * Run media:beforeUpload hooks across all active plugins
3863
3876
  */
@@ -5183,4 +5196,4 @@ declare function extractPlainText(blocks: PortableTextBlock[] | string | null |
5183
5196
  declare function extractSearchableFields(entry: Record<string, unknown>, fields: string[]): Record<string, string>;
5184
5197
  //#endregion
5185
5198
  export { ReorderMenuItemsInput as $, ProseMirrorDocument as $n, portableText as $r, invalidateCollectionCache as $t, getEntriesByTerm as A, createEditable as An, handleRevisionList as Ar, createPluginManager as At, TaxonomyTerm as B, sanitizeHref as Bn, handleContentDuplicate as Br, EmDashConfig as Bt, ReorderWidgetsInput as C, getEmDashCollection as Cn, handleMediaDelete as Cr, NoopSandboxRunner as Ct, WidgetComponentDef as D, CMSAnnotation as Dn, RevisionListResponse as Dr, CronScheduler as Dt, WidgetArea as E, resolveEmDashPath as En, handleMediaUpdate as Er, NodeCronScheduler as Et, getTerm as F, WhereRange as Fn, handleContentCountScheduled as Fr, HookPipeline as Ft, getEntriesByByline as G, PortableTextCodeBlock as Gn, handleContentPermanentDelete as Gr, StorageDescriptor as Gt, UpdateTermInput as H, hashString as Hn, handleContentGetIncludingTrashed as Hr, getStoredConfig as Ht, getTermsForEntries as I, WhereValue as In, handleContentCountTrashed as Ir, HookResult as It, CreateMenuInput as J, PortableTextLinkMark as Jn, handleContentSchedule as Jr, CachedQueryOptions as Jt, getMenu as K, PortableTextHtmlBlock as Kn, handleContentPublish as Kr, definePlugin as Kt, invalidateTermCache as L, emdashLoader as Ln, handleContentCreate as Lr, createHookPipeline as Lt, getTaxonomyDef as M, CollectionFilter$1 as Mn, generateManifest as Mr, createHttpAccess as Mt, getTaxonomyDefs as N, EntryData as Nn, handleContentAuthors as Nr, createUnrestrictedHttpAccess as Nt, WidgetType as O, EditProxy as On, RevisionResponse as Or, SystemCleanupFn as Ot, getTaxonomyTerms as P, EntryFilter as Pn, handleContentCompare as Pr, EmailPipeline as Pt, MenuItemType as Q, PortableTextUnknownBlock as Qn, handleContentUpdate as Qr, invalidateBylineObjectCache as Qt, CreateTermInput as R, getDb as Rn, handleContentDelete as Rr, ValidatedPluginManifest as Rt, PropDef as S, getEditMeta as Sn, handleMediaCreate as Sr, verifyPreviewToken as St, Widget as T, getTranslations as Tn, handleMediaList as Tr, createNoopSandboxRunner as Tt, getByline as U, portableTextToProsemirror as Un, handleContentList as Ur, LocalStorageConfig as Ut, TaxonomyTermRow as V, computeContentHash as Vn, handleContentGet as Vr, PluginDescriptor as Vt, getBylineBySlug as W, prosemirrorToPortableText as Wn, handleContentListTrashed as Wr, S3StorageConfig as Wt, Menu as X, PortableTextSpan as Xn, handleContentUnpublish as Xr, contentNamespace as Xt, CreateMenuItemInput as Y, PortableTextMarkDef as Yn, handleContentTranslations as Yr, cachedQuery as Yt, MenuItem as Z, PortableTextTextBlock as Zn, handleContentUnschedule as Zr, contentNamespaces as Zt, getWidgetArea as _, EntryResult as _n, getCollectionInfo as _r, PreviewTokenPayload as _t, search as a, FileValue as ai, I18nConfig as an, SandboxRunner as ar, getComments as at, CreateWidgetAreaInput as b, TranslationSummary as bn, MediaListResponse as br, generatePreviewToken as bt, FTSManager as c, PluginStorageRepository as ci, isI18nEnabled as cn, SandboxedPluginInstance as cr, getSiteSetting as ct, SearchOptions as d, MediaItem as di, CacheHint as dn, getSections as dr, getPreviewToken as dt, reference as ei, invalidateCommentObjectCache as en, ProseMirrorMark as er, UpdateMenuInput as et, SearchResponse as f, MediaRepository as fi, CollectionFilter as fn, CreateSectionInput as fr, isPreviewRequest as ft, Suggestion as g, EmDashCollections as gn, UpdateSectionInput as gr, GeneratePreviewTokenOptions as gt, SuggestOptions as h, EmDashDatabaseError as hi, EditFieldMeta as hn, SectionSource as hr, getPreviewUrl as ht, getSuggestions as i, FieldUIHints as ii, invalidateTaxonomyObjectCache as in, SandboxOptions as ir, getCommentCount as it, getEntryTerms as j, createNoop as jn, handleRevisionRestore as jr, PluginRouteError as jt, getAllTermsForEntries as k, FieldAnnotation as kn, handleRevisionGet as kr, PluginManager as kt, CollectionSearchOptions as l, UserRepository as li, WaitUntilFn as ln, SerializedRequest as lr, getSiteSettings as lt, SearchStats as m, DatabaseConfig as mi, ContentEntry as mn, Section as mr, buildPreviewUrl as mt, extractSearchableFields as n, image as ni, invalidateObjectCache as nn, SandboxEmailMessage as nr, GetCommentsOptions as nt, searchCollection as o, ImageValue as oi, getFallbackChain as on, SandboxRunnerFactory as or, getPluginSetting as ot, SearchResult as p, ContentRepository as pi, CollectionResult as pn, GetSectionsOptions as pr, GetPreviewUrlOptions as pt, getMenus as q, PortableTextImageBlock as qn, handleContentRestore as qr, CacheNamespace as qt, getSearchStats as r, FieldDefinition as ri, invalidateSchemaObjectCache as rn, SandboxEmailSendCallback as rr, GetCommentsResult as rt, searchWithDb as s, PortableTextBlock$1 as si, getI18nConfig as sn, SandboxUnavailableError as sr, getPluginSettings as st, extractPlainText as t, file as ti, invalidateMenuObjectCache as tn, ProseMirrorNode as tr, UpdateMenuItemInput as tt, SearchConfig as u, CreateMediaInput as ui, after as un, getSection as ur, setSiteSettings as ut, getWidgetAreas as v, InferCollectionData as vn, SchemaError as vr, VerifyPreviewTokenOptions as vt, UpdateWidgetInput as w, getEmDashEntry as wn, handleMediaGet as wr, SandboxNotAvailableError as wt, CreateWidgetInput as x, TranslationsResult as xn, MediaResponse as xr, parseContentId as xt, getWidgetComponents as y, ResolvePathResult as yn, SchemaRegistry as yr, VerifyPreviewTokenResult as yt, TaxonomyDef as z, isSafeHref as zn, handleContentDiscardDraft as zr, pluginManifestSchema as zt };
5186
- //# sourceMappingURL=index-BroXT-vD.d.mts.map
5199
+ //# sourceMappingURL=index-Cz6_JBL3.d.mts.map