emdash 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (558) hide show
  1. package/dist/api/route-utils.d.mts +3 -3
  2. package/dist/api/route-utils.mjs +16 -14
  3. package/dist/api/route-utils.mjs.map +1 -1
  4. package/dist/api/schemas/index.d.mts +2 -2
  5. package/dist/api/schemas/index.mjs +4 -4
  6. package/dist/{api-EibxGP-V.mjs → api-DgPbMlng.mjs} +24 -20
  7. package/dist/api-DgPbMlng.mjs.map +1 -0
  8. package/dist/{api-tokens-uPt8UDpx.mjs → api-tokens-p-iMzvXR.mjs} +2 -2
  9. package/dist/{api-tokens-uPt8UDpx.mjs.map → api-tokens-p-iMzvXR.mjs.map} +1 -1
  10. package/dist/{apply-fGHCAwWN.mjs → apply-1_6ra7NP.mjs} +19 -19
  11. package/dist/{apply-fGHCAwWN.mjs.map → apply-1_6ra7NP.mjs.map} +1 -1
  12. package/dist/astro/index.d.mts +12 -12
  13. package/dist/astro/index.mjs +5 -1
  14. package/dist/astro/index.mjs.map +1 -1
  15. package/dist/astro/middleware/auth.d.mts +10 -10
  16. package/dist/astro/middleware/auth.mjs +5 -5
  17. package/dist/astro/middleware/redirect.mjs +5 -5
  18. package/dist/astro/middleware/request-context.mjs +1 -1
  19. package/dist/astro/middleware.d.mts +10 -10
  20. package/dist/astro/middleware.mjs +94 -61
  21. package/dist/astro/middleware.mjs.map +1 -1
  22. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  23. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  24. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +4 -4
  25. package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
  26. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
  27. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +8 -8
  28. package/dist/astro/routes/api/admin/byline-fields/index.mjs +8 -8
  29. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +8 -8
  30. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +15 -14
  31. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs.map +1 -1
  32. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +15 -14
  33. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs.map +1 -1
  34. package/dist/astro/routes/api/admin/bylines/index.mjs +15 -15
  35. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +11 -11
  36. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  37. package/dist/astro/routes/api/admin/comments/bulk.mjs +9 -9
  38. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  39. package/dist/astro/routes/api/admin/comments/index.mjs +9 -9
  40. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  41. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  42. package/dist/astro/routes/api/admin/media-usage/repair.mjs +12 -10
  43. package/dist/astro/routes/api/admin/media-usage/repair.mjs.map +1 -1
  44. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +4 -4
  45. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
  46. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +36 -34
  47. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  48. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +36 -34
  49. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  50. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +36 -34
  51. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  52. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  53. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +36 -34
  54. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  55. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +36 -34
  56. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  57. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +36 -34
  58. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  59. package/dist/astro/routes/api/admin/plugins/index.mjs +36 -34
  60. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  61. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +3 -3
  62. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +36 -34
  63. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  64. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +36 -34
  65. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  66. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +36 -34
  67. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  68. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +36 -34
  69. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  70. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +37 -35
  71. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  72. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +36 -34
  73. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  74. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +37 -35
  75. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  76. package/dist/astro/routes/api/admin/plugins/updates.mjs +36 -34
  77. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  78. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +36 -34
  79. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  80. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +3 -3
  81. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +36 -34
  82. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  83. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
  84. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +2 -2
  85. package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
  86. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
  87. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  88. package/dist/astro/routes/api/auth/dev-bypass.mjs +7 -6
  89. package/dist/astro/routes/api/auth/dev-bypass.mjs.map +1 -1
  90. package/dist/astro/routes/api/auth/invite/accept.mjs +2 -2
  91. package/dist/astro/routes/api/auth/invite/complete.mjs +7 -7
  92. package/dist/astro/routes/api/auth/invite/index.mjs +7 -7
  93. package/dist/astro/routes/api/auth/invite/register-options.mjs +7 -7
  94. package/dist/astro/routes/api/auth/logout.mjs +3 -3
  95. package/dist/astro/routes/api/auth/magic-link/send.mjs +8 -8
  96. package/dist/astro/routes/api/auth/magic-link/verify.mjs +3 -3
  97. package/dist/astro/routes/api/auth/me.mjs +7 -7
  98. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  99. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +2 -2
  100. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +1 -1
  101. package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
  102. package/dist/astro/routes/api/auth/passkey/index.mjs +2 -2
  103. package/dist/astro/routes/api/auth/passkey/options.mjs +8 -8
  104. package/dist/astro/routes/api/auth/passkey/register/options.mjs +7 -7
  105. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +7 -7
  106. package/dist/astro/routes/api/auth/passkey/verify.mjs +7 -7
  107. package/dist/astro/routes/api/auth/signup/complete.mjs +7 -7
  108. package/dist/astro/routes/api/auth/signup/request.mjs +8 -8
  109. package/dist/astro/routes/api/auth/signup/verify.mjs +2 -2
  110. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +11 -11
  111. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +10 -10
  112. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +3 -3
  113. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +3 -3
  114. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  115. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +3 -3
  116. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +9 -9
  117. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +7 -7
  118. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +16 -14
  119. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  120. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +16 -14
  121. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  122. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  123. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +3 -3
  124. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +7 -7
  125. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +14 -13
  126. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs.map +1 -1
  127. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +3 -3
  128. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +3 -3
  129. package/dist/astro/routes/api/content/_collection_/_id_.d.mts.map +1 -1
  130. package/dist/astro/routes/api/content/_collection_/_id_.mjs +8 -8
  131. package/dist/astro/routes/api/content/_collection_/_id_.mjs.map +1 -1
  132. package/dist/astro/routes/api/content/_collection_/authors.mjs +3 -3
  133. package/dist/astro/routes/api/content/_collection_/index.mjs +7 -7
  134. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  135. package/dist/astro/routes/api/dashboard.mjs +7 -7
  136. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  137. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  138. package/dist/astro/routes/api/import/probe.mjs +12 -12
  139. package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
  140. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  141. package/dist/astro/routes/api/import/wordpress/execute.mjs +12 -11
  142. package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
  143. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  144. package/dist/astro/routes/api/import/wordpress/media.mjs +7 -7
  145. package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
  146. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  147. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +11 -9
  148. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
  149. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  150. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +12 -12
  151. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  152. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +20 -19
  153. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
  154. package/dist/astro/routes/api/manifest.mjs +3 -3
  155. package/dist/astro/routes/api/mcp.mjs +41 -41
  156. package/dist/astro/routes/api/media/_id_/confirm.d.mts.map +1 -1
  157. package/dist/astro/routes/api/media/_id_/confirm.mjs +105 -36
  158. package/dist/astro/routes/api/media/_id_/confirm.mjs.map +1 -1
  159. package/dist/astro/routes/api/media/_id_/upload.d.mts +8 -0
  160. package/dist/astro/routes/api/media/_id_/upload.d.mts.map +1 -0
  161. package/dist/astro/routes/api/media/_id_/upload.mjs +168 -0
  162. package/dist/astro/routes/api/media/_id_/upload.mjs.map +1 -0
  163. package/dist/astro/routes/api/media/_id_/usage.mjs +14 -12
  164. package/dist/astro/routes/api/media/_id_/usage.mjs.map +1 -1
  165. package/dist/astro/routes/api/media/_id_.d.mts.map +1 -1
  166. package/dist/astro/routes/api/media/_id_.mjs +21 -14
  167. package/dist/astro/routes/api/media/_id_.mjs.map +1 -1
  168. package/dist/astro/routes/api/media/file/_...key_.mjs +2 -2
  169. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +3 -3
  170. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +3 -3
  171. package/dist/astro/routes/api/media/providers/index.mjs +3 -3
  172. package/dist/astro/routes/api/media/upload-url.d.mts.map +1 -1
  173. package/dist/astro/routes/api/media/upload-url.mjs +34 -23
  174. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  175. package/dist/astro/routes/api/media.mjs +13 -12
  176. package/dist/astro/routes/api/media.mjs.map +1 -1
  177. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +9 -8
  178. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  179. package/dist/astro/routes/api/menus/_name_/items.mjs +9 -8
  180. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  181. package/dist/astro/routes/api/menus/_name_/reorder.mjs +9 -8
  182. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  183. package/dist/astro/routes/api/menus/_name_/translations.mjs +9 -8
  184. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  185. package/dist/astro/routes/api/menus/_name_.mjs +9 -8
  186. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  187. package/dist/astro/routes/api/menus/index.mjs +9 -8
  188. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  189. package/dist/astro/routes/api/oauth/authorize.mjs +5 -5
  190. package/dist/astro/routes/api/oauth/device/authorize.mjs +6 -6
  191. package/dist/astro/routes/api/oauth/device/code.mjs +7 -7
  192. package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
  193. package/dist/astro/routes/api/oauth/register.mjs +3 -3
  194. package/dist/astro/routes/api/oauth/token/refresh.mjs +6 -6
  195. package/dist/astro/routes/api/oauth/token/revoke.mjs +6 -6
  196. package/dist/astro/routes/api/oauth/token.mjs +6 -6
  197. package/dist/astro/routes/api/openapi.json.mjs +30 -8
  198. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  199. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +5 -5
  200. package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
  201. package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
  202. package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
  203. package/dist/astro/routes/api/redirects/index.mjs +11 -11
  204. package/dist/astro/routes/api/relations/_id_/index.mjs +16 -14
  205. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  206. package/dist/astro/routes/api/relations/_id_/translations.mjs +12 -10
  207. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  208. package/dist/astro/routes/api/relations/index.mjs +16 -14
  209. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  210. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +3 -3
  211. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  212. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +36 -34
  213. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  214. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +36 -34
  215. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  216. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +36 -34
  217. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  218. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +36 -34
  219. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  220. package/dist/astro/routes/api/schema/collections/index.mjs +36 -34
  221. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  222. package/dist/astro/routes/api/schema/index.mjs +10 -8
  223. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  224. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +36 -34
  225. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  226. package/dist/astro/routes/api/schema/orphans/index.mjs +36 -34
  227. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  228. package/dist/astro/routes/api/search/enable.mjs +12 -11
  229. package/dist/astro/routes/api/search/enable.mjs.map +1 -1
  230. package/dist/astro/routes/api/search/index.mjs +11 -10
  231. package/dist/astro/routes/api/search/index.mjs.map +1 -1
  232. package/dist/astro/routes/api/search/rebuild.mjs +12 -11
  233. package/dist/astro/routes/api/search/rebuild.mjs.map +1 -1
  234. package/dist/astro/routes/api/search/stats.mjs +8 -7
  235. package/dist/astro/routes/api/search/stats.mjs.map +1 -1
  236. package/dist/astro/routes/api/search/suggest.mjs +11 -10
  237. package/dist/astro/routes/api/search/suggest.mjs.map +1 -1
  238. package/dist/astro/routes/api/sections/_slug_.mjs +10 -10
  239. package/dist/astro/routes/api/sections/index.mjs +10 -10
  240. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +4 -4
  241. package/dist/astro/routes/api/settings/backups/archives/index.mjs +4 -4
  242. package/dist/astro/routes/api/settings/backups/export.mjs +4 -4
  243. package/dist/astro/routes/api/settings/backups/index.mjs +5 -5
  244. package/dist/astro/routes/api/settings/email.mjs +4 -4
  245. package/dist/astro/routes/api/settings.mjs +12 -12
  246. package/dist/astro/routes/api/setup/admin-verify.mjs +8 -8
  247. package/dist/astro/routes/api/setup/admin.mjs +8 -8
  248. package/dist/astro/routes/api/setup/dev-bypass.mjs +24 -22
  249. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  250. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  251. package/dist/astro/routes/api/setup/index.mjs +24 -22
  252. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  253. package/dist/astro/routes/api/setup/status.mjs +3 -3
  254. package/dist/astro/routes/api/snapshot.mjs +5 -5
  255. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +14 -13
  256. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  257. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +14 -13
  258. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  259. package/dist/astro/routes/api/taxonomies/_name_/terms/index.d.mts.map +1 -1
  260. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +19 -15
  261. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  262. package/dist/astro/routes/api/taxonomies/index.mjs +14 -13
  263. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  264. package/dist/astro/routes/api/themes/preview.mjs +4 -4
  265. package/dist/astro/routes/api/typegen.mjs +5 -5
  266. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +1 -1
  267. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +1 -1
  268. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +7 -7
  269. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +10 -10
  270. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +10 -10
  271. package/dist/astro/routes/api/widget-areas/_name_.mjs +6 -6
  272. package/dist/astro/routes/api/widget-areas/index.mjs +10 -10
  273. package/dist/astro/routes/api/widget-components.mjs +2 -2
  274. package/dist/astro/routes/robots.txt.mjs +5 -5
  275. package/dist/astro/routes/sitemap-_collection_.xml.mjs +7 -7
  276. package/dist/astro/routes/sitemap.xml.mjs +5 -5
  277. package/dist/astro/types.d.mts +14 -13
  278. package/dist/astro/types.d.mts.map +1 -1
  279. package/dist/auth/providers/github.d.mts +1 -1
  280. package/dist/auth/providers/google.d.mts +1 -1
  281. package/dist/{authorize-6WPZa1xZ.mjs → authorize-R5iYYrpa.mjs} +2 -2
  282. package/dist/{authorize-6WPZa1xZ.mjs.map → authorize-R5iYYrpa.mjs.map} +1 -1
  283. package/dist/{backup-Qr9PaGUo.mjs → backup-LpQ1V_sR.mjs} +2 -2
  284. package/dist/{backup-Qr9PaGUo.mjs.map → backup-LpQ1V_sR.mjs.map} +1 -1
  285. package/dist/{byline-BTOxUlFF.mjs → byline-C5TAqs8N.mjs} +6 -6
  286. package/dist/{byline-BTOxUlFF.mjs.map → byline-C5TAqs8N.mjs.map} +1 -1
  287. package/dist/{byline-fields-CdU_LTF1.mjs → byline-fields-T9ZLZMxJ.mjs} +1 -1
  288. package/dist/{byline-fields-CdU_LTF1.mjs.map → byline-fields-T9ZLZMxJ.mjs.map} +1 -1
  289. package/dist/{bylines-FyZu6TbJ.mjs → bylines-B8-WGdja.mjs} +6 -6
  290. package/dist/{bylines-FyZu6TbJ.mjs.map → bylines-B8-WGdja.mjs.map} +1 -1
  291. package/dist/{bylines-oVN0iPwX.mjs → bylines-DGuqBLjV.mjs} +5 -5
  292. package/dist/{bylines-oVN0iPwX.mjs.map → bylines-DGuqBLjV.mjs.map} +1 -1
  293. package/dist/{cache-DDwy3JDW.mjs → cache-B26cufFd.mjs} +2 -2
  294. package/dist/{cache-DDwy3JDW.mjs.map → cache-B26cufFd.mjs.map} +1 -1
  295. package/dist/{chunks-Bq-5DPrD.mjs → chunks-D5dlPeRb.mjs} +2 -2
  296. package/dist/{chunks-Bq-5DPrD.mjs.map → chunks-D5dlPeRb.mjs.map} +1 -1
  297. package/dist/cli/index.mjs +20 -19
  298. package/dist/cli/index.mjs.map +1 -1
  299. package/dist/client/cf-access.d.mts +1 -1
  300. package/dist/client/index.d.mts +1 -1
  301. package/dist/client/index.mjs +2 -2
  302. package/dist/{comment-B9cUud8H.mjs → comment-DnTxxVHv.mjs} +2 -2
  303. package/dist/{comment-B9cUud8H.mjs.map → comment-DnTxxVHv.mjs.map} +1 -1
  304. package/dist/{comment-reaction-VUXO981F.mjs → comment-reaction-BUlUz2bh.mjs} +2 -2
  305. package/dist/{comment-reaction-VUXO981F.mjs.map → comment-reaction-BUlUz2bh.mjs.map} +1 -1
  306. package/dist/{comments-PXj1E9Si.mjs → comments-QPKgK3nk.mjs} +3 -3
  307. package/dist/{comments-PXj1E9Si.mjs.map → comments-QPKgK3nk.mjs.map} +1 -1
  308. package/dist/{config-B6b_BobR.mjs → config-DyF3OKg_.mjs} +15 -10
  309. package/dist/config-DyF3OKg_.mjs.map +1 -0
  310. package/dist/{content-BC43pICM.mjs → content-CpfKV9QE.mjs} +9 -9
  311. package/dist/content-CpfKV9QE.mjs.map +1 -0
  312. package/dist/{content-refresh-CPMSauD3.mjs → content-refresh-DgqUBeTv.mjs} +5 -5
  313. package/dist/{content-refresh-CPMSauD3.mjs.map → content-refresh-DgqUBeTv.mjs.map} +1 -1
  314. package/dist/{context-DOurRIrb.mjs → context-kO4YZB03.mjs} +10 -10
  315. package/dist/{context-DOurRIrb.mjs.map → context-kO4YZB03.mjs.map} +1 -1
  316. package/dist/{dashboard-CBm4zhc3.mjs → dashboard-DoBwPnON.mjs} +4 -4
  317. package/dist/{dashboard-CBm4zhc3.mjs.map → dashboard-DoBwPnON.mjs.map} +1 -1
  318. package/dist/db/index.d.mts +2 -2
  319. package/dist/db/index.mjs +3 -2
  320. package/dist/db/index.mjs.map +1 -1
  321. package/dist/{device-flow-BeA6lUS1.mjs → device-flow-DhUsyJU6.mjs} +4 -4
  322. package/dist/{device-flow-BeA6lUS1.mjs.map → device-flow-DhUsyJU6.mjs.map} +1 -1
  323. package/dist/{dialect-helpers-BtOwo2us.mjs → dialect-helpers-DFwyWjTM.mjs} +21 -2
  324. package/dist/dialect-helpers-DFwyWjTM.mjs.map +1 -0
  325. package/dist/{error-DJ98TRbQ.mjs → error-DmmN74gW.mjs} +2 -2
  326. package/dist/{error-DJ98TRbQ.mjs.map → error-DmmN74gW.mjs.map} +1 -1
  327. package/dist/{escape-CFedIB1C.mjs → escape-CdW31WsG.mjs} +1 -1
  328. package/dist/{escape-CFedIB1C.mjs.map → escape-CdW31WsG.mjs.map} +1 -1
  329. package/dist/{field-defs-cache-KfNJ_qLQ.mjs → field-defs-cache-QMVnzTH6.mjs} +2 -2
  330. package/dist/{field-defs-cache-KfNJ_qLQ.mjs.map → field-defs-cache-QMVnzTH6.mjs.map} +1 -1
  331. package/dist/{fts-manager-hyCU9OOp.mjs → fts-manager-vncsZIJm.mjs} +3 -3
  332. package/dist/{fts-manager-hyCU9OOp.mjs.map → fts-manager-vncsZIJm.mjs.map} +1 -1
  333. package/dist/{hash-DFFrkivP.mjs → hash-Cb7U1b5M.mjs} +8 -4
  334. package/dist/hash-Cb7U1b5M.mjs.map +1 -0
  335. package/dist/{hreflang-CbYeCzl9.mjs → hreflang-Bg-zMpkr.mjs} +7 -7
  336. package/dist/{hreflang-CbYeCzl9.mjs.map → hreflang-Bg-zMpkr.mjs.map} +1 -1
  337. package/dist/{hreflang-CIxH_LKz.d.mts → hreflang-CZbSx6Bg.d.mts} +2 -2
  338. package/dist/{hreflang-CIxH_LKz.d.mts.map → hreflang-CZbSx6Bg.d.mts.map} +1 -1
  339. package/dist/{import-oDYCgNYQ.mjs → import-PKhLeXvn.mjs} +2 -2
  340. package/dist/{import-oDYCgNYQ.mjs.map → import-PKhLeXvn.mjs.map} +1 -1
  341. package/dist/{index-BEui-cRd.d.mts → index-BeNto_Vs.d.mts} +3 -3
  342. package/dist/{index-BEui-cRd.d.mts.map → index-BeNto_Vs.d.mts.map} +1 -1
  343. package/dist/{index-BcEH_FfS.d.mts → index-j9rTh3cp.d.mts} +68 -18
  344. package/dist/index-j9rTh3cp.d.mts.map +1 -0
  345. package/dist/index.d.mts +18 -18
  346. package/dist/index.mjs +49 -49
  347. package/dist/{load-Dg5gtWma.mjs → load-BwTdWE8B.mjs} +2 -2
  348. package/dist/{load-Dg5gtWma.mjs.map → load-BwTdWE8B.mjs.map} +1 -1
  349. package/dist/{loader-D4rigvjR.mjs → loader-C1XOLV5b.mjs} +4 -4
  350. package/dist/{loader-D4rigvjR.mjs.map → loader-C1XOLV5b.mjs.map} +1 -1
  351. package/dist/media/index.d.mts +1 -1
  352. package/dist/media/local-runtime.d.mts +12 -12
  353. package/dist/media/local-runtime.mjs +5 -5
  354. package/dist/{media-BJ6SRY3g.mjs → media-DWIzoVFL.mjs} +8 -4
  355. package/dist/{media-BJ6SRY3g.mjs.map → media-DWIzoVFL.mjs.map} +1 -1
  356. package/dist/{media-allowlist-jUppPWFy.mjs → media-allowlist-B7TPD6aq.mjs} +1 -1
  357. package/dist/{media-allowlist-jUppPWFy.mjs.map → media-allowlist-B7TPD6aq.mjs.map} +1 -1
  358. package/dist/{media-its1WLYv.mjs → media-tQDZEdu7.mjs} +60 -15
  359. package/dist/media-tQDZEdu7.mjs.map +1 -0
  360. package/dist/{media-upload-DNu3QySc.mjs → media-upload-Bc9Nc5Zf.mjs} +6 -6
  361. package/dist/{media-upload-DNu3QySc.mjs.map → media-upload-Bc9Nc5Zf.mjs.map} +1 -1
  362. package/dist/{media-usage-DPQ3K4xB.mjs → media-usage-DPJcNaAq.mjs} +6 -6
  363. package/dist/{media-usage-DPQ3K4xB.mjs.map → media-usage-DPJcNaAq.mjs.map} +1 -1
  364. package/dist/{menus-BMGzWyWH.mjs → menus-BxPLFfIc.mjs} +3 -3
  365. package/dist/{menus-BMGzWyWH.mjs.map → menus-BxPLFfIc.mjs.map} +1 -1
  366. package/dist/{menus-CPf_SW7u.mjs → menus-C6qhqP4X.mjs} +8 -8
  367. package/dist/{menus-CPf_SW7u.mjs.map → menus-C6qhqP4X.mjs.map} +1 -1
  368. package/dist/{oauth-authorization-oqfbBuMH.mjs → oauth-authorization-C9tFinly.mjs} +4 -4
  369. package/dist/{oauth-authorization-oqfbBuMH.mjs.map → oauth-authorization-C9tFinly.mjs.map} +1 -1
  370. package/dist/{oauth-clients-BlrUHAsf.mjs → oauth-clients-BwTxE1aE.mjs} +1 -1
  371. package/dist/{oauth-clients-BlrUHAsf.mjs.map → oauth-clients-BwTxE1aE.mjs.map} +1 -1
  372. package/dist/{oauth-state-store-DnvjRMy6.mjs → oauth-state-store-DaRUwPWO.mjs} +1 -1
  373. package/dist/{oauth-state-store-DnvjRMy6.mjs.map → oauth-state-store-DaRUwPWO.mjs.map} +1 -1
  374. package/dist/{oauth-user-lookup-oUllxvAv.mjs → oauth-user-lookup-CzuzOSlF.mjs} +1 -1
  375. package/dist/{oauth-user-lookup-oUllxvAv.mjs.map → oauth-user-lookup-CzuzOSlF.mjs.map} +1 -1
  376. package/dist/object-cache/memory.d.mts +1 -1
  377. package/dist/{options-BqMkWfYa.d.mts → options-aeIs8WFu.d.mts} +3 -3
  378. package/dist/{options-BqMkWfYa.d.mts.map → options-aeIs8WFu.d.mts.map} +1 -1
  379. package/dist/page/index.d.mts +2 -2
  380. package/dist/{parse-53zyxlpv.mjs → parse-BL49yb9D.mjs} +2 -2
  381. package/dist/{parse-53zyxlpv.mjs.map → parse-BL49yb9D.mjs.map} +1 -1
  382. package/dist/{passkey-config-C-SKpc0-.mjs → passkey-config-KMhgFjdQ.mjs} +1 -1
  383. package/dist/{passkey-config-C-SKpc0-.mjs.map → passkey-config-KMhgFjdQ.mjs.map} +1 -1
  384. package/dist/{placeholder-Dop47JMM.d.mts → placeholder-Dxo5Zt58.d.mts} +1 -1
  385. package/dist/{placeholder-Dop47JMM.d.mts.map → placeholder-Dxo5Zt58.d.mts.map} +1 -1
  386. package/dist/plugin-types.d.mts +1 -1
  387. package/dist/plugin-utils.d.mts +10 -10
  388. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  389. package/dist/{portable-text-sDj92Kxv.mjs → portable-text-CNahFfj6.mjs} +1 -1
  390. package/dist/{portable-text-sDj92Kxv.mjs.map → portable-text-CNahFfj6.mjs.map} +1 -1
  391. package/dist/{query-DdFGHzQF.mjs → query-1xOcEy18.mjs} +3 -3
  392. package/dist/{query-DdFGHzQF.mjs.map → query-1xOcEy18.mjs.map} +1 -1
  393. package/dist/{query-BbJQ-dGg.mjs → query-DCiXI7OZ.mjs} +36 -16
  394. package/dist/query-DCiXI7OZ.mjs.map +1 -0
  395. package/dist/{rate-limit-D3IEiUi2.mjs → rate-limit-Vkp9gQ1Y.mjs} +2 -2
  396. package/dist/{rate-limit-D3IEiUi2.mjs.map → rate-limit-Vkp9gQ1Y.mjs.map} +1 -1
  397. package/dist/{redirect-BoUac4NT.mjs → redirect-BJ6d1yHh.mjs} +3 -3
  398. package/dist/{redirect-BoUac4NT.mjs.map → redirect-BJ6d1yHh.mjs.map} +1 -1
  399. package/dist/{redirect-Botom7X6.mjs → redirect-CDgfv9vh.mjs} +1 -1
  400. package/dist/{redirect-Botom7X6.mjs.map → redirect-CDgfv9vh.mjs.map} +1 -1
  401. package/dist/{redirects-D457qwt0.mjs → redirects-BOn2DIUs.mjs} +8 -4
  402. package/dist/redirects-BOn2DIUs.mjs.map +1 -0
  403. package/dist/{redirects-ChbpqKiS.mjs → redirects-Cwkq2H-G.mjs} +3 -3
  404. package/dist/{redirects-ChbpqKiS.mjs.map → redirects-Cwkq2H-G.mjs.map} +1 -1
  405. package/dist/{registry-y21kjhfG.mjs → registry-BP1JK2xh.mjs} +6 -6
  406. package/dist/{registry-y21kjhfG.mjs.map → registry-BP1JK2xh.mjs.map} +1 -1
  407. package/dist/{relation-Du0r04E0.mjs → relation-DJ5DZh7B.mjs} +3 -3
  408. package/dist/{relation-Du0r04E0.mjs.map → relation-DJ5DZh7B.mjs.map} +1 -1
  409. package/dist/{relations-CZMpBqEd.mjs → relations-C4duJnwI.mjs} +2 -2
  410. package/dist/{relations-CZMpBqEd.mjs.map → relations-C4duJnwI.mjs.map} +1 -1
  411. package/dist/{relations-BKybBoOX.d.mts → relations-DHFQGX0h.d.mts} +19 -8
  412. package/dist/relations-DHFQGX0h.d.mts.map +1 -0
  413. package/dist/{relations-DtX1UMBH.mjs → relations-DpTjftCl.mjs} +6 -6
  414. package/dist/{relations-DtX1UMBH.mjs.map → relations-DpTjftCl.mjs.map} +1 -1
  415. package/dist/{resolve-DFr4kq72.mjs → resolve-BUvFE0Lr.mjs} +2 -2
  416. package/dist/{resolve-DFr4kq72.mjs.map → resolve-BUvFE0Lr.mjs.map} +1 -1
  417. package/dist/{runner-BdeLEgad.mjs → runner-BsI18UgP.mjs} +230 -212
  418. package/dist/runner-BsI18UgP.mjs.map +1 -0
  419. package/dist/{runner-Dd8m8k9F.d.mts → runner-CHdkERbt.d.mts} +2 -2
  420. package/dist/{runner-Dd8m8k9F.d.mts.map → runner-CHdkERbt.d.mts.map} +1 -1
  421. package/dist/runtime.d.mts +11 -11
  422. package/dist/runtime.mjs +3 -3
  423. package/dist/{schema-BH8P8vaC.mjs → schema-eqZhkR0S.mjs} +3 -3
  424. package/dist/{schema-BH8P8vaC.mjs.map → schema-eqZhkR0S.mjs.map} +1 -1
  425. package/dist/{scopes-DTIkIaGA.mjs → scopes-Be2d8bSb.mjs} +3 -3
  426. package/dist/{scopes-DTIkIaGA.mjs.map → scopes-Be2d8bSb.mjs.map} +1 -1
  427. package/dist/{search-D-Yhpmvs.mjs → search-CeO678cp.mjs} +6 -6
  428. package/dist/{search-D-Yhpmvs.mjs.map → search-CeO678cp.mjs.map} +1 -1
  429. package/dist/{secrets-CQ-69kF9.mjs → secrets-870d-7yA.mjs} +1 -1
  430. package/dist/{secrets-CQ-69kF9.mjs.map → secrets-870d-7yA.mjs.map} +1 -1
  431. package/dist/{sections-CzVBAKjw.mjs → sections-DSuEfirn.mjs} +3 -3
  432. package/dist/{sections-CzVBAKjw.mjs.map → sections-DSuEfirn.mjs.map} +1 -1
  433. package/dist/seed/index.d.mts +2 -2
  434. package/dist/seed/index.mjs +18 -16
  435. package/dist/seo/index.d.mts +3 -3
  436. package/dist/seo/index.mjs +14 -12
  437. package/dist/seo/index.mjs.map +1 -1
  438. package/dist/{seo-kJzVAmmu.mjs → seo-BAPKiED8.mjs} +2 -2
  439. package/dist/{seo-kJzVAmmu.mjs.map → seo-BAPKiED8.mjs.map} +1 -1
  440. package/dist/{service-CQnc276a.mjs → service-DyFT-k-R.mjs} +3 -3
  441. package/dist/{service-CQnc276a.mjs.map → service-DyFT-k-R.mjs.map} +1 -1
  442. package/dist/{session-user-DbHqKDKe.mjs → session-user-BrK2zz7S.mjs} +1 -1
  443. package/dist/{session-user-DbHqKDKe.mjs.map → session-user-BrK2zz7S.mjs.map} +1 -1
  444. package/dist/{settings-Dtc0DU31.mjs → settings-CREKyj8I.mjs} +3 -3
  445. package/dist/{settings-Dtc0DU31.mjs.map → settings-CREKyj8I.mjs.map} +1 -1
  446. package/dist/{settings-C2PaBS49.mjs → settings-DgKouY2S.mjs} +3 -3
  447. package/dist/{settings-C2PaBS49.mjs.map → settings-DgKouY2S.mjs.map} +1 -1
  448. package/dist/{setup-complete-CdIlqloh.mjs → setup-complete-L7bMK2VI.mjs} +1 -1
  449. package/dist/{setup-complete-CdIlqloh.mjs.map → setup-complete-L7bMK2VI.mjs.map} +1 -1
  450. package/dist/{setup-nonce-DqiIPr-J.mjs → setup-nonce-Ct5tjWcq.mjs} +1 -1
  451. package/dist/{setup-nonce-DqiIPr-J.mjs.map → setup-nonce-Ct5tjWcq.mjs.map} +1 -1
  452. package/dist/{site-url-NGJT6NTU.mjs → site-url-8N3kSyVZ.mjs} +1 -1
  453. package/dist/{site-url-NGJT6NTU.mjs.map → site-url-8N3kSyVZ.mjs.map} +1 -1
  454. package/dist/storage/local.d.mts +1 -1
  455. package/dist/storage/s3.d.mts +1 -1
  456. package/dist/storage/s3.mjs +1 -1
  457. package/dist/storage/s3.mjs.map +1 -1
  458. package/dist/{taxonomies-HI9fnTdp.mjs → taxonomies-B61CRSha.mjs} +94 -39
  459. package/dist/taxonomies-B61CRSha.mjs.map +1 -0
  460. package/dist/{taxonomies-rMeBzOjX.mjs → taxonomies-Dbdki3Un.mjs} +9 -8
  461. package/dist/taxonomies-Dbdki3Un.mjs.map +1 -0
  462. package/dist/{taxonomy-0mCI25HN.mjs → taxonomy-DvwWAPvA.mjs} +3 -3
  463. package/dist/{taxonomy-0mCI25HN.mjs.map → taxonomy-DvwWAPvA.mjs.map} +1 -1
  464. package/dist/{transport-CKrlqSpD.mjs → transport-BWQo0Foy.mjs} +1 -1
  465. package/dist/{transport-CKrlqSpD.mjs.map → transport-BWQo0Foy.mjs.map} +1 -1
  466. package/dist/{transport-Vd7VdqHv.d.mts → transport-DokJOScS.d.mts} +1 -1
  467. package/dist/{transport-Vd7VdqHv.d.mts.map → transport-DokJOScS.d.mts.map} +1 -1
  468. package/dist/{types-DPKhI5ib.d.mts → types-84Bque3-.d.mts} +9 -1
  469. package/dist/types-84Bque3-.d.mts.map +1 -0
  470. package/dist/{types-BvB7gDOD.d.mts → types-BQY7VYw6.d.mts} +2 -2
  471. package/dist/{types-BvB7gDOD.d.mts.map → types-BQY7VYw6.d.mts.map} +1 -1
  472. package/dist/{types-B4vm81VH.d.mts → types-C9P3ysxq.d.mts} +1 -1
  473. package/dist/{types-B4vm81VH.d.mts.map → types-C9P3ysxq.d.mts.map} +1 -1
  474. package/dist/{types-B97jg3aW.d.mts → types-CcSZCcF1.d.mts} +1 -1
  475. package/dist/{types-B97jg3aW.d.mts.map → types-CcSZCcF1.d.mts.map} +1 -1
  476. package/dist/{types-BNfPHfay.d.mts → types-DQLZ58GV.d.mts} +1 -1
  477. package/dist/{types-BNfPHfay.d.mts.map → types-DQLZ58GV.d.mts.map} +1 -1
  478. package/dist/{types-BfYUPJdP.d.mts → types-DqZVPILm.d.mts} +2 -2
  479. package/dist/{types-BfYUPJdP.d.mts.map → types-DqZVPILm.d.mts.map} +1 -1
  480. package/dist/{types-C7U0HlEr.d.mts → types-Dr2GLlwu.d.mts} +1 -1
  481. package/dist/{types-C7U0HlEr.d.mts.map → types-Dr2GLlwu.d.mts.map} +1 -1
  482. package/dist/{types-iVeZ5g6N.d.mts → types-DsAMyD_o.d.mts} +1 -1
  483. package/dist/{types-iVeZ5g6N.d.mts.map → types-DsAMyD_o.d.mts.map} +1 -1
  484. package/dist/{types-CrRUFdej.mjs → types-XrQQ-Aex.mjs} +2 -2
  485. package/dist/{types-CrRUFdej.mjs.map → types-XrQQ-Aex.mjs.map} +1 -1
  486. package/dist/{types-Kmaxdarz.d.mts → types-jISEalTX.d.mts} +1 -1
  487. package/dist/{types-Kmaxdarz.d.mts.map → types-jISEalTX.d.mts.map} +1 -1
  488. package/dist/upload-attempts-C5yd6Gae.mjs +27 -0
  489. package/dist/upload-attempts-C5yd6Gae.mjs.map +1 -0
  490. package/dist/{user-aTXqmXBz.mjs → user-BAumEmpA.mjs} +3 -3
  491. package/dist/{user-aTXqmXBz.mjs.map → user-BAumEmpA.mjs.map} +1 -1
  492. package/dist/{validate-CDT1jl6_.mjs → validate-Bs_wT2ul.mjs} +3 -3
  493. package/dist/{validate-CDT1jl6_.mjs.map → validate-Bs_wT2ul.mjs.map} +1 -1
  494. package/dist/{validate-DULfgpJP.d.mts → validate-CdYcY-Ln.d.mts} +5 -5
  495. package/dist/{validate-DULfgpJP.d.mts.map → validate-CdYcY-Ln.d.mts.map} +1 -1
  496. package/dist/{validation-DlD0E35W.mjs → validation-BngR0nit.mjs} +10 -8
  497. package/dist/{validation-DlD0E35W.mjs.map → validation-BngR0nit.mjs.map} +1 -1
  498. package/dist/version-Bdfb34kk.mjs +7 -0
  499. package/dist/{version-Ci6bw6YK.mjs.map → version-Bdfb34kk.mjs.map} +1 -1
  500. package/dist/{widgets-5fipNkMT.mjs → widgets-L-VndTKD.mjs} +2 -2
  501. package/dist/{widgets-5fipNkMT.mjs.map → widgets-L-VndTKD.mjs.map} +1 -1
  502. package/dist/{wxr-taxonomies-BmUnBNgz.mjs → wxr-taxonomies-BexjtNid.mjs} +4 -4
  503. package/dist/{wxr-taxonomies-BmUnBNgz.mjs.map → wxr-taxonomies-BexjtNid.mjs.map} +1 -1
  504. package/dist/{wxr-taxonomies-B4tMuN5T.d.mts → wxr-taxonomies-DueaLFd9.d.mts} +1 -1
  505. package/dist/{wxr-taxonomies-B4tMuN5T.d.mts.map → wxr-taxonomies-DueaLFd9.d.mts.map} +1 -1
  506. package/dist/{zod-generator-CwkHWz4f.mjs → zod-generator-DMzfga3g.mjs} +3 -3
  507. package/dist/{zod-generator-CwkHWz4f.mjs.map → zod-generator-DMzfga3g.mjs.map} +1 -1
  508. package/package.json +8 -7
  509. package/src/api/handlers/media.ts +4 -4
  510. package/src/api/handlers/taxonomies.ts +10 -9
  511. package/src/api/openapi/document.ts +36 -3
  512. package/src/api/schemas/media.ts +9 -2
  513. package/src/api/schemas/taxonomies.ts +16 -1
  514. package/src/astro/integration/routes.ts +5 -0
  515. package/src/astro/prefetch.ts +7 -2
  516. package/src/astro/routes/api/content/[collection]/[id].ts +3 -1
  517. package/src/astro/routes/api/media/[id]/confirm.ts +148 -59
  518. package/src/astro/routes/api/media/[id]/upload.ts +262 -0
  519. package/src/astro/routes/api/media/[id].ts +19 -10
  520. package/src/astro/routes/api/media/upload-url.ts +28 -31
  521. package/src/astro/routes/api/taxonomies/[name]/terms/index.ts +6 -3
  522. package/src/astro/types.ts +1 -0
  523. package/src/cleanup.ts +24 -1
  524. package/src/components/InlinePortableTextEditor.tsx +4 -0
  525. package/src/components/code-mark.ts +11 -0
  526. package/src/components/widgets/Categories.astro +1 -1
  527. package/src/components/widgets/Tags.astro +1 -1
  528. package/src/database/dialect-helpers.ts +38 -0
  529. package/src/database/migrations/054_media_upload_attempts.ts +41 -0
  530. package/src/database/migrations/runner.ts +2 -0
  531. package/src/database/repositories/content.ts +2 -5
  532. package/src/database/repositories/media.ts +158 -28
  533. package/src/database/types.ts +10 -0
  534. package/src/emdash-runtime.ts +13 -0
  535. package/src/i18n/config.ts +17 -10
  536. package/src/index.ts +1 -0
  537. package/src/media/upload-attempts.ts +33 -0
  538. package/src/query.ts +29 -2
  539. package/src/storage/s3.ts +1 -1
  540. package/src/taxonomies/index.ts +64 -23
  541. package/src/taxonomies/term-counts.ts +54 -24
  542. package/src/utils/hash.ts +14 -3
  543. package/dist/api-EibxGP-V.mjs.map +0 -1
  544. package/dist/config-B6b_BobR.mjs.map +0 -1
  545. package/dist/content-BC43pICM.mjs.map +0 -1
  546. package/dist/dialect-helpers-BtOwo2us.mjs.map +0 -1
  547. package/dist/hash-DFFrkivP.mjs.map +0 -1
  548. package/dist/index-BcEH_FfS.d.mts.map +0 -1
  549. package/dist/media-its1WLYv.mjs.map +0 -1
  550. package/dist/query-BbJQ-dGg.mjs.map +0 -1
  551. package/dist/redirects-D457qwt0.mjs.map +0 -1
  552. package/dist/relations-BKybBoOX.d.mts.map +0 -1
  553. package/dist/runner-BdeLEgad.mjs.map +0 -1
  554. package/dist/taxonomies-HI9fnTdp.mjs.map +0 -1
  555. package/dist/taxonomies-rMeBzOjX.mjs.map +0 -1
  556. package/dist/types-DPKhI5ib.d.mts.map +0 -1
  557. package/dist/version-Ci6bw6YK.mjs +0 -7
  558. /package/dist/{api-tokens-Cvmixds7.mjs → api-tokens-CEsW_jCg.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"device-flow-BeA6lUS1.mjs","names":[],"sources":["../src/api/handlers/device-flow.ts"],"sourcesContent":["/**\n * OAuth Device Flow handlers (RFC 8628).\n *\n * EmDash acts as an OAuth 2.0 authorization server. The CLI requests\n * a device code, displays a URL + user code, and polls for a token.\n * The user opens a browser, logs in, enters the code, and the CLI gets\n * an access + refresh token pair.\n *\n * Uses arctic for code generation and @emdash-cms/auth for token utilities.\n */\n\nimport { clampScopes } from \"@emdash-cms/auth\";\nimport type { RoleLevel } from \"@emdash-cms/auth\";\nimport { generateCodeVerifier } from \"arctic\";\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tgeneratePrefixedToken,\n\thashApiToken,\n\tisValidScope,\n\tTOKEN_PREFIXES,\n} from \"../../auth/api-tokens.js\";\nimport { withTransaction } from \"../../database/transaction.js\";\nimport type { Database } from \"../../database/types.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { lookupOAuthClient } from \"./oauth-clients.js\";\nimport { lookupUserRoleAndStatus } from \"./oauth-user-lookup.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Device codes expire after 15 minutes */\nconst DEVICE_CODE_TTL_SECONDS = 15 * 60;\n\n/** Default polling interval in seconds */\nconst DEFAULT_INTERVAL = 5;\n\n/** RFC 8628 §3.5: interval increase on slow_down */\nconst SLOW_DOWN_INCREMENT = 5;\n\n/** Maximum slow_down interval cap (seconds) */\nconst MAX_SLOW_DOWN_INTERVAL = 60;\n\n/** Access token TTL: 1 hour */\nconst ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\n/** Refresh token TTL: 90 days */\nconst REFRESH_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n/** Default scopes for CLI login */\nconst DEFAULT_SCOPES = [\n\t\"content:read\",\n\t\"content:write\",\n\t\"media:read\",\n\t\"media:write\",\n\t\"schema:read\",\n] as const;\n\n/** Pattern to normalize user codes (strip hyphens) */\nconst HYPHEN_PATTERN = /-/g;\n\n/** Characters for user codes (uppercase, no ambiguous chars like 0/O, 1/I) */\nconst USER_CODE_CHARS = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface DeviceCodeResponse {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval: number;\n}\n\nexport interface TokenResponse {\n\taccess_token: string;\n\trefresh_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n}\n\n// RFC 8628 error codes\nexport type DeviceFlowError =\n\t| \"authorization_pending\"\n\t| \"slow_down\"\n\t| \"expired_token\"\n\t| \"access_denied\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Generate a short human-readable user code (XXXX-XXXX) */\nfunction generateUserCode(): string {\n\tconst bytes = new Uint8Array(8);\n\tcrypto.getRandomValues(bytes);\n\tconst chars = Array.from(bytes, (b) => USER_CODE_CHARS[b % USER_CODE_CHARS.length]).join(\"\");\n\treturn `${chars.slice(0, 4)}-${chars.slice(4, 8)}`;\n}\n\n/** Get an ISO datetime string offset from now */\nfunction expiresAt(seconds: number): string {\n\treturn new Date(Date.now() + seconds * 1000).toISOString();\n}\n\n/** Validate and normalize scopes. Returns validated scope list. */\nfunction normalizeScopes(requested?: string[]): string[] {\n\tif (!requested || requested.length === 0) {\n\t\treturn [...DEFAULT_SCOPES];\n\t}\n\treturn requested.filter(isValidScope);\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\n/**\n * POST /oauth/device/code\n *\n * Issue a device code + user code. The CLI displays the user code\n * and tells the user to open the verification URI.\n */\nexport async function handleDeviceCodeRequest(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tclient_id?: string;\n\t\tscope?: string;\n\t},\n\tverificationUri: string,\n): Promise<ApiResult<DeviceCodeResponse>> {\n\ttry {\n\t\t// Note: client_id is accepted but not validated against _emdash_oauth_clients\n\t\t// because the CLI uses a well-known built-in client ID (\"emdash-cli\") that\n\t\t// isn't stored in the DB. Full client_id validation + scope clamping for the\n\t\t// device flow is tracked as a follow-up.\n\n\t\t// Parse and validate scopes\n\t\tconst requestedScopes = input.scope ? input.scope.split(\" \").filter(Boolean) : [];\n\t\tconst scopes = normalizeScopes(requestedScopes);\n\n\t\tif (scopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_SCOPE\", message: \"No valid scopes requested\" },\n\t\t\t};\n\t\t}\n\n\t\tconst deviceCode = generateCodeVerifier();\n\t\tconst userCode = generateUserCode();\n\t\tconst expires = expiresAt(DEVICE_CODE_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_device_codes\")\n\t\t\t.values({\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tstatus: \"pending\",\n\t\t\t\texpires_at: expires,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tverification_uri: verificationUri,\n\t\t\t\texpires_in: DEVICE_CODE_TTL_SECONDS,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DEVICE_CODE_ERROR\",\n\t\t\t\tmessage: \"Failed to create device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/token\n *\n * CLI polls this endpoint with the device_code. Returns:\n * - 200 with tokens if authorized\n * - 400 with error \"authorization_pending\" while waiting\n * - 400 with error \"slow_down\" if polling too fast\n * - 400 with error \"expired_token\" if the code expired\n * - 400 with error \"access_denied\" if the user denied\n */\nexport async function handleDeviceTokenExchange(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tdevice_code: string;\n\t\tgrant_type: string;\n\t},\n): Promise<\n\tApiResult<TokenResponse> & { deviceFlowError?: DeviceFlowError; deviceFlowInterval?: number }\n> {\n\ttry {\n\t\t// Validate grant_type\n\t\tif (input.grant_type !== \"urn:ietf:params:oauth:grant-type:device_code\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\t// Look up the device code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code\" },\n\t\t\t};\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < now) {\n\t\t\t// Clean up expired code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"expired_token\",\n\t\t\t\terror: { code: \"expired_token\", message: \"The device code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check status\n\t\tif (row.status === \"denied\") {\n\t\t\t// Clean up denied code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"access_denied\",\n\t\t\t\terror: { code: \"access_denied\", message: \"The user denied the request\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status === \"pending\") {\n\t\t\t// RFC 8628 §3.5: slow_down enforcement during polling phase.\n\t\t\t// Only applies while waiting for authorization — once authorized,\n\t\t\t// the final exchange proceeds without throttling.\n\t\t\tif (row.last_polled_at) {\n\t\t\t\tconst lastPolled = new Date(row.last_polled_at);\n\t\t\t\tconst elapsedSeconds = (now.getTime() - lastPolled.getTime()) / 1000;\n\n\t\t\t\tif (elapsedSeconds < row.interval) {\n\t\t\t\t\t// Too fast — increase interval by 5s per RFC 8628 §3.5, capped at 60s\n\t\t\t\t\tconst newInterval = Math.min(row.interval + SLOW_DOWN_INCREMENT, MAX_SLOW_DOWN_INTERVAL);\n\t\t\t\t\tawait db\n\t\t\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tinterval: newInterval,\n\t\t\t\t\t\t\tlast_polled_at: now.toISOString(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t\t\t.execute();\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdeviceFlowError: \"slow_down\",\n\t\t\t\t\t\tdeviceFlowInterval: newInterval,\n\t\t\t\t\t\terror: { code: \"slow_down\", message: \"Polling too fast\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update last_polled_at for future slow_down checks\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ last_polled_at: now.toISOString() })\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"authorization_pending\",\n\t\t\t\terror: { code: \"authorization_pending\", message: \"Authorization pending\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status !== \"authorized\" || !row.user_id) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code state\" },\n\t\t\t};\n\t\t}\n\n\t\t// Generate tokens before consuming the device code so that if\n\t\t// generation fails, the code is still available for retry.\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\t\tconst refreshToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_REFRESH);\n\t\tconst refreshExpires = expiresAt(REFRESH_TOKEN_TTL_SECONDS);\n\n\t\t// Atomically consume the device code and create tokens in a single\n\t\t// transaction. DELETE...RETURNING prevents TOCTOU: two concurrent\n\t\t// requests race on the DELETE, only one gets a row back. Wrapping\n\t\t// in a transaction ensures the code isn't consumed if token storage fails.\n\t\tconst result = await withTransaction(db, async (trx) => {\n\t\t\tconst consumed = await trx\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.where(\"status\", \"=\", \"authorized\")\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (!consumed) return null;\n\n\t\t\tif (!consumed.user_id) return null;\n\n\t\t\tconst scopes = JSON.parse(consumed.scopes) as string[];\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\t\ttoken_type: \"access\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: accessExpires,\n\t\t\t\t\trefresh_token_hash: refreshToken.hash,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: refreshToken.hash,\n\t\t\t\t\ttoken_type: \"refresh\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: refreshExpires,\n\t\t\t\t\trefresh_token_hash: null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\treturn { scopes };\n\t\t});\n\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Device code already consumed\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: refreshToken.raw,\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: result.scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_EXCHANGE_ERROR\",\n\t\t\t\tmessage: \"Failed to exchange device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/authorize\n *\n * The user submits the user_code after logging in via the browser.\n * This authorizes the device code, allowing the CLI to exchange it for tokens.\n *\n * Scopes are clamped to the user's role at this point. The stored scopes\n * are replaced with the intersection of requested scopes and the scopes\n * the user's role permits. This prevents scope escalation.\n */\nexport async function handleDeviceAuthorize(\n\tdb: Kysely<Database>,\n\tuserId: string,\n\tuserRole: RoleLevel,\n\tinput: {\n\t\tuser_code: string;\n\t\taction?: \"approve\" | \"deny\";\n\t},\n): Promise<ApiResult<{ authorized: boolean }>> {\n\ttry {\n\t\t// Normalize user code (strip hyphens, uppercase)\n\t\tconst normalizedCode = input.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase();\n\n\t\t// Look up the device code by user_code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.execute();\n\n\t\t// Find the matching code (strip hyphens for comparison)\n\t\tconst match = row.find(\n\t\t\t(r) => r.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase() === normalizedCode,\n\t\t);\n\n\t\tif (!match) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CODE\", message: \"Invalid or expired code\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(match.expires_at) < new Date()) {\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"EXPIRED_CODE\", message: \"This code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\tconst action = input.action ?? \"approve\";\n\n\t\tif (action === \"deny\") {\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ status: \"denied\" })\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn { success: true, data: { authorized: false } };\n\t\t}\n\n\t\t// Clamp requested scopes to those the user's role permits.\n\t\t// effective_scopes = requested_scopes ∩ scopesForRole(user.role)\n\t\tconst requestedScopes = JSON.parse(match.scopes) as string[];\n\t\tconst effectiveScopes = clampScopes(requestedScopes, userRole);\n\n\t\tif (effectiveScopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INSUFFICIENT_ROLE\",\n\t\t\t\t\tmessage: \"Your role does not permit any of the requested scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Approve: set user_id, status, and clamped scopes\n\t\tawait db\n\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t.set({\n\t\t\t\tstatus: \"authorized\",\n\t\t\t\tuser_id: userId,\n\t\t\t\tscopes: JSON.stringify(effectiveScopes),\n\t\t\t})\n\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t.execute();\n\n\t\treturn { success: true, data: { authorized: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"AUTHORIZE_ERROR\",\n\t\t\t\tmessage: \"Failed to authorize device\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/refresh\n *\n * Exchange a refresh token for a new access token.\n * The refresh token itself is not rotated (per spec: optional rotation).\n */\nexport async function handleTokenRefresh(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\trefresh_token: string;\n\t\tgrant_type: string;\n\t},\n): Promise<ApiResult<TokenResponse>> {\n\ttry {\n\t\tif (input.grant_type !== \"refresh_token\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\tif (!input.refresh_token.startsWith(TOKEN_PREFIXES.OAUTH_REFRESH)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token format\" },\n\t\t\t};\n\t\t}\n\n\t\tconst refreshHash = hashApiToken(input.refresh_token);\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.selectAll()\n\t\t\t.where(\"token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"refresh\")\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < new Date()) {\n\t\t\t// Clean up expired refresh token and its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Refresh token expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// SEC-42: Revalidate user role before issuing new access token.\n\t\t// SEC-43: Reject refresh if user is disabled or deleted.\n\t\tconst userInfo = await lookupUserRoleAndStatus(db, row.user_id);\n\t\tif (!userInfo) {\n\t\t\t// User no longer exists — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User not found\" },\n\t\t\t};\n\t\t}\n\n\t\tif (userInfo.disabled) {\n\t\t\t// User is disabled — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User account is disabled\" },\n\t\t\t};\n\t\t}\n\n\t\t// Revalidate stored scopes against the user's current role.\n\t\t// A demoted user's refresh token may carry stale elevated scopes.\n\t\tconst storedScopes = JSON.parse(row.scopes) as string[];\n\t\tlet scopes = clampScopes(storedScopes, userInfo.role);\n\n\t\t// SEC-41: Intersect with the client's registered scopes (if any).\n\t\t// Same check as the approval path — a client registered with limited\n\t\t// scopes should never receive elevated scopes on refresh, even if the\n\t\t// user's role would allow them.\n\t\tif (row.client_id) {\n\t\t\tconst client = await lookupOAuthClient(db, row.client_id);\n\t\t\tif (client?.scopes?.length) {\n\t\t\t\tscopes = scopes.filter((s: string) => client.scopes!.includes(s));\n\t\t\t}\n\t\t}\n\n\t\tif (scopes.length === 0) {\n\t\t\t// User's role no longer supports any of the token's scopes — revoke\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INVALID_GRANT\",\n\t\t\t\t\tmessage: \"User role no longer supports any of the token's scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Delete old access tokens for this refresh token\n\t\tawait db\n\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"access\")\n\t\t\t.execute();\n\n\t\t// Generate new access token\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t.values({\n\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\ttoken_type: \"access\",\n\t\t\t\tuser_id: row.user_id,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tclient_type: row.client_type,\n\t\t\t\texpires_at: accessExpires,\n\t\t\t\trefresh_token_hash: refreshHash,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: input.refresh_token, // Return same refresh token\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REFRESH_ERROR\",\n\t\t\t\tmessage: \"Failed to refresh token\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/revoke\n *\n * Revoke an access or refresh token. If a refresh token is revoked,\n * also revoke all associated access tokens.\n *\n * Per RFC 7009, this endpoint always returns 200 (even for invalid tokens).\n */\nexport async function handleTokenRevoke(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\ttoken: string;\n\t},\n): Promise<ApiResult<{ revoked: boolean }>> {\n\ttry {\n\t\tconst hash = hashApiToken(input.token);\n\n\t\t// Look up the token\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.select([\"token_hash\", \"token_type\", \"refresh_token_hash\"])\n\t\t\t.where(\"token_hash\", \"=\", hash)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\t// Per RFC 7009: always 200, even for invalid tokens\n\t\t\treturn { success: true, data: { revoked: true } };\n\t\t}\n\n\t\tif (row.token_type === \"refresh\") {\n\t\t\t// Revoke refresh token and all its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"refresh_token_hash\", \"=\", hash).execute();\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t} else {\n\t\t\t// Revoke just the access token\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t}\n\n\t\treturn { success: true, data: { revoked: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REVOKE_ERROR\",\n\t\t\t\tmessage: \"Failed to revoke token\",\n\t\t\t},\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAM,0BAA0B;;AAGhC,MAAM,mBAAmB;;AAGzB,MAAM,sBAAsB;;AAG5B,MAAM,yBAAyB;;AAG/B,MAAM,2BAA2B;;AAGjC,MAAM,4BAA4B,OAAU,KAAK;;AAGjD,MAAM,iBAAiB;CACtB;CACA;CACA;CACA;CACA;CACA;;AAGD,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAkCxB,SAAS,mBAA2B;CACnC,MAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAO,gBAAgB,MAAM;CAC7B,MAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM,gBAAgB,IAAI,IAAwB,CAAC,KAAK,GAAG;AAC5F,QAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,MAAM,GAAG,EAAE;;;AAIjD,SAAS,UAAU,SAAyB;AAC3C,QAAO,IAAI,KAAK,KAAK,KAAK,GAAG,UAAU,IAAK,CAAC,aAAa;;;AAI3D,SAAS,gBAAgB,W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GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;AAGlD,MAAI,IAAI,eAAe,WAAW;AAEjC,SAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,sBAAsB,KAAK,KAAK,CAAC,SAAS;AAC5F,SAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;QAGpF,OAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;AAGrF,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD"}
1
+ {"version":3,"file":"device-flow-DhUsyJU6.mjs","names":[],"sources":["../src/api/handlers/device-flow.ts"],"sourcesContent":["/**\n * OAuth Device Flow handlers (RFC 8628).\n *\n * EmDash acts as an OAuth 2.0 authorization server. The CLI requests\n * a device code, displays a URL + user code, and polls for a token.\n * The user opens a browser, logs in, enters the code, and the CLI gets\n * an access + refresh token pair.\n *\n * Uses arctic for code generation and @emdash-cms/auth for token utilities.\n */\n\nimport { clampScopes } from \"@emdash-cms/auth\";\nimport type { RoleLevel } from \"@emdash-cms/auth\";\nimport { generateCodeVerifier } from \"arctic\";\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tgeneratePrefixedToken,\n\thashApiToken,\n\tisValidScope,\n\tTOKEN_PREFIXES,\n} from \"../../auth/api-tokens.js\";\nimport { withTransaction } from \"../../database/transaction.js\";\nimport type { Database } from \"../../database/types.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { lookupOAuthClient } from \"./oauth-clients.js\";\nimport { lookupUserRoleAndStatus } from \"./oauth-user-lookup.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Device codes expire after 15 minutes */\nconst DEVICE_CODE_TTL_SECONDS = 15 * 60;\n\n/** Default polling interval in seconds */\nconst DEFAULT_INTERVAL = 5;\n\n/** RFC 8628 §3.5: interval increase on slow_down */\nconst SLOW_DOWN_INCREMENT = 5;\n\n/** Maximum slow_down interval cap (seconds) */\nconst MAX_SLOW_DOWN_INTERVAL = 60;\n\n/** Access token TTL: 1 hour */\nconst ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\n/** Refresh token TTL: 90 days */\nconst REFRESH_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n/** Default scopes for CLI login */\nconst DEFAULT_SCOPES = [\n\t\"content:read\",\n\t\"content:write\",\n\t\"media:read\",\n\t\"media:write\",\n\t\"schema:read\",\n] as const;\n\n/** Pattern to normalize user codes (strip hyphens) */\nconst HYPHEN_PATTERN = /-/g;\n\n/** Characters for user codes (uppercase, no ambiguous chars like 0/O, 1/I) */\nconst USER_CODE_CHARS = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface DeviceCodeResponse {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval: number;\n}\n\nexport interface TokenResponse {\n\taccess_token: string;\n\trefresh_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n}\n\n// RFC 8628 error codes\nexport type DeviceFlowError =\n\t| \"authorization_pending\"\n\t| \"slow_down\"\n\t| \"expired_token\"\n\t| \"access_denied\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Generate a short human-readable user code (XXXX-XXXX) */\nfunction generateUserCode(): string {\n\tconst bytes = new Uint8Array(8);\n\tcrypto.getRandomValues(bytes);\n\tconst chars = Array.from(bytes, (b) => USER_CODE_CHARS[b % USER_CODE_CHARS.length]).join(\"\");\n\treturn `${chars.slice(0, 4)}-${chars.slice(4, 8)}`;\n}\n\n/** Get an ISO datetime string offset from now */\nfunction expiresAt(seconds: number): string {\n\treturn new Date(Date.now() + seconds * 1000).toISOString();\n}\n\n/** Validate and normalize scopes. Returns validated scope list. */\nfunction normalizeScopes(requested?: string[]): string[] {\n\tif (!requested || requested.length === 0) {\n\t\treturn [...DEFAULT_SCOPES];\n\t}\n\treturn requested.filter(isValidScope);\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\n/**\n * POST /oauth/device/code\n *\n * Issue a device code + user code. The CLI displays the user code\n * and tells the user to open the verification URI.\n */\nexport async function handleDeviceCodeRequest(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tclient_id?: string;\n\t\tscope?: string;\n\t},\n\tverificationUri: string,\n): Promise<ApiResult<DeviceCodeResponse>> {\n\ttry {\n\t\t// Note: client_id is accepted but not validated against _emdash_oauth_clients\n\t\t// because the CLI uses a well-known built-in client ID (\"emdash-cli\") that\n\t\t// isn't stored in the DB. Full client_id validation + scope clamping for the\n\t\t// device flow is tracked as a follow-up.\n\n\t\t// Parse and validate scopes\n\t\tconst requestedScopes = input.scope ? input.scope.split(\" \").filter(Boolean) : [];\n\t\tconst scopes = normalizeScopes(requestedScopes);\n\n\t\tif (scopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_SCOPE\", message: \"No valid scopes requested\" },\n\t\t\t};\n\t\t}\n\n\t\tconst deviceCode = generateCodeVerifier();\n\t\tconst userCode = generateUserCode();\n\t\tconst expires = expiresAt(DEVICE_CODE_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_device_codes\")\n\t\t\t.values({\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tstatus: \"pending\",\n\t\t\t\texpires_at: expires,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tverification_uri: verificationUri,\n\t\t\t\texpires_in: DEVICE_CODE_TTL_SECONDS,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DEVICE_CODE_ERROR\",\n\t\t\t\tmessage: \"Failed to create device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/token\n *\n * CLI polls this endpoint with the device_code. Returns:\n * - 200 with tokens if authorized\n * - 400 with error \"authorization_pending\" while waiting\n * - 400 with error \"slow_down\" if polling too fast\n * - 400 with error \"expired_token\" if the code expired\n * - 400 with error \"access_denied\" if the user denied\n */\nexport async function handleDeviceTokenExchange(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tdevice_code: string;\n\t\tgrant_type: string;\n\t},\n): Promise<\n\tApiResult<TokenResponse> & { deviceFlowError?: DeviceFlowError; deviceFlowInterval?: number }\n> {\n\ttry {\n\t\t// Validate grant_type\n\t\tif (input.grant_type !== \"urn:ietf:params:oauth:grant-type:device_code\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\t// Look up the device code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code\" },\n\t\t\t};\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < now) {\n\t\t\t// Clean up expired code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"expired_token\",\n\t\t\t\terror: { code: \"expired_token\", message: \"The device code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check status\n\t\tif (row.status === \"denied\") {\n\t\t\t// Clean up denied code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"access_denied\",\n\t\t\t\terror: { code: \"access_denied\", message: \"The user denied the request\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status === \"pending\") {\n\t\t\t// RFC 8628 §3.5: slow_down enforcement during polling phase.\n\t\t\t// Only applies while waiting for authorization — once authorized,\n\t\t\t// the final exchange proceeds without throttling.\n\t\t\tif (row.last_polled_at) {\n\t\t\t\tconst lastPolled = new Date(row.last_polled_at);\n\t\t\t\tconst elapsedSeconds = (now.getTime() - lastPolled.getTime()) / 1000;\n\n\t\t\t\tif (elapsedSeconds < row.interval) {\n\t\t\t\t\t// Too fast — increase interval by 5s per RFC 8628 §3.5, capped at 60s\n\t\t\t\t\tconst newInterval = Math.min(row.interval + SLOW_DOWN_INCREMENT, MAX_SLOW_DOWN_INTERVAL);\n\t\t\t\t\tawait db\n\t\t\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tinterval: newInterval,\n\t\t\t\t\t\t\tlast_polled_at: now.toISOString(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t\t\t.execute();\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdeviceFlowError: \"slow_down\",\n\t\t\t\t\t\tdeviceFlowInterval: newInterval,\n\t\t\t\t\t\terror: { code: \"slow_down\", message: \"Polling too fast\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update last_polled_at for future slow_down checks\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ last_polled_at: now.toISOString() })\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"authorization_pending\",\n\t\t\t\terror: { code: \"authorization_pending\", message: \"Authorization pending\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status !== \"authorized\" || !row.user_id) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code state\" },\n\t\t\t};\n\t\t}\n\n\t\t// Generate tokens before consuming the device code so that if\n\t\t// generation fails, the code is still available for retry.\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\t\tconst refreshToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_REFRESH);\n\t\tconst refreshExpires = expiresAt(REFRESH_TOKEN_TTL_SECONDS);\n\n\t\t// Atomically consume the device code and create tokens in a single\n\t\t// transaction. DELETE...RETURNING prevents TOCTOU: two concurrent\n\t\t// requests race on the DELETE, only one gets a row back. Wrapping\n\t\t// in a transaction ensures the code isn't consumed if token storage fails.\n\t\tconst result = await withTransaction(db, async (trx) => {\n\t\t\tconst consumed = await trx\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.where(\"status\", \"=\", \"authorized\")\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (!consumed) return null;\n\n\t\t\tif (!consumed.user_id) return null;\n\n\t\t\tconst scopes = JSON.parse(consumed.scopes) as string[];\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\t\ttoken_type: \"access\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: accessExpires,\n\t\t\t\t\trefresh_token_hash: refreshToken.hash,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: refreshToken.hash,\n\t\t\t\t\ttoken_type: \"refresh\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: refreshExpires,\n\t\t\t\t\trefresh_token_hash: null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\treturn { scopes };\n\t\t});\n\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Device code already consumed\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: refreshToken.raw,\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: result.scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_EXCHANGE_ERROR\",\n\t\t\t\tmessage: \"Failed to exchange device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/authorize\n *\n * The user submits the user_code after logging in via the browser.\n * This authorizes the device code, allowing the CLI to exchange it for tokens.\n *\n * Scopes are clamped to the user's role at this point. The stored scopes\n * are replaced with the intersection of requested scopes and the scopes\n * the user's role permits. This prevents scope escalation.\n */\nexport async function handleDeviceAuthorize(\n\tdb: Kysely<Database>,\n\tuserId: string,\n\tuserRole: RoleLevel,\n\tinput: {\n\t\tuser_code: string;\n\t\taction?: \"approve\" | \"deny\";\n\t},\n): Promise<ApiResult<{ authorized: boolean }>> {\n\ttry {\n\t\t// Normalize user code (strip hyphens, uppercase)\n\t\tconst normalizedCode = input.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase();\n\n\t\t// Look up the device code by user_code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.execute();\n\n\t\t// Find the matching code (strip hyphens for comparison)\n\t\tconst match = row.find(\n\t\t\t(r) => r.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase() === normalizedCode,\n\t\t);\n\n\t\tif (!match) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CODE\", message: \"Invalid or expired code\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(match.expires_at) < new Date()) {\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"EXPIRED_CODE\", message: \"This code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\tconst action = input.action ?? \"approve\";\n\n\t\tif (action === \"deny\") {\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ status: \"denied\" })\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn { success: true, data: { authorized: false } };\n\t\t}\n\n\t\t// Clamp requested scopes to those the user's role permits.\n\t\t// effective_scopes = requested_scopes ∩ scopesForRole(user.role)\n\t\tconst requestedScopes = JSON.parse(match.scopes) as string[];\n\t\tconst effectiveScopes = clampScopes(requestedScopes, userRole);\n\n\t\tif (effectiveScopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INSUFFICIENT_ROLE\",\n\t\t\t\t\tmessage: \"Your role does not permit any of the requested scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Approve: set user_id, status, and clamped scopes\n\t\tawait db\n\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t.set({\n\t\t\t\tstatus: \"authorized\",\n\t\t\t\tuser_id: userId,\n\t\t\t\tscopes: JSON.stringify(effectiveScopes),\n\t\t\t})\n\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t.execute();\n\n\t\treturn { success: true, data: { authorized: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"AUTHORIZE_ERROR\",\n\t\t\t\tmessage: \"Failed to authorize device\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/refresh\n *\n * Exchange a refresh token for a new access token.\n * The refresh token itself is not rotated (per spec: optional rotation).\n */\nexport async function handleTokenRefresh(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\trefresh_token: string;\n\t\tgrant_type: string;\n\t},\n): Promise<ApiResult<TokenResponse>> {\n\ttry {\n\t\tif (input.grant_type !== \"refresh_token\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\tif (!input.refresh_token.startsWith(TOKEN_PREFIXES.OAUTH_REFRESH)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token format\" },\n\t\t\t};\n\t\t}\n\n\t\tconst refreshHash = hashApiToken(input.refresh_token);\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.selectAll()\n\t\t\t.where(\"token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"refresh\")\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < new Date()) {\n\t\t\t// Clean up expired refresh token and its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Refresh token expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// SEC-42: Revalidate user role before issuing new access token.\n\t\t// SEC-43: Reject refresh if user is disabled or deleted.\n\t\tconst userInfo = await lookupUserRoleAndStatus(db, row.user_id);\n\t\tif (!userInfo) {\n\t\t\t// User no longer exists — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User not found\" },\n\t\t\t};\n\t\t}\n\n\t\tif (userInfo.disabled) {\n\t\t\t// User is disabled — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User account is disabled\" },\n\t\t\t};\n\t\t}\n\n\t\t// Revalidate stored scopes against the user's current role.\n\t\t// A demoted user's refresh token may carry stale elevated scopes.\n\t\tconst storedScopes = JSON.parse(row.scopes) as string[];\n\t\tlet scopes = clampScopes(storedScopes, userInfo.role);\n\n\t\t// SEC-41: Intersect with the client's registered scopes (if any).\n\t\t// Same check as the approval path — a client registered with limited\n\t\t// scopes should never receive elevated scopes on refresh, even if the\n\t\t// user's role would allow them.\n\t\tif (row.client_id) {\n\t\t\tconst client = await lookupOAuthClient(db, row.client_id);\n\t\t\tif (client?.scopes?.length) {\n\t\t\t\tscopes = scopes.filter((s: string) => client.scopes!.includes(s));\n\t\t\t}\n\t\t}\n\n\t\tif (scopes.length === 0) {\n\t\t\t// User's role no longer supports any of the token's scopes — revoke\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INVALID_GRANT\",\n\t\t\t\t\tmessage: \"User role no longer supports any of the token's scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Delete old access tokens for this refresh token\n\t\tawait db\n\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"access\")\n\t\t\t.execute();\n\n\t\t// Generate new access token\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t.values({\n\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\ttoken_type: \"access\",\n\t\t\t\tuser_id: row.user_id,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tclient_type: row.client_type,\n\t\t\t\texpires_at: accessExpires,\n\t\t\t\trefresh_token_hash: refreshHash,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: input.refresh_token, // Return same refresh token\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REFRESH_ERROR\",\n\t\t\t\tmessage: \"Failed to refresh token\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/revoke\n *\n * Revoke an access or refresh token. If a refresh token is revoked,\n * also revoke all associated access tokens.\n *\n * Per RFC 7009, this endpoint always returns 200 (even for invalid tokens).\n */\nexport async function handleTokenRevoke(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\ttoken: string;\n\t},\n): Promise<ApiResult<{ revoked: boolean }>> {\n\ttry {\n\t\tconst hash = hashApiToken(input.token);\n\n\t\t// Look up the token\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.select([\"token_hash\", \"token_type\", \"refresh_token_hash\"])\n\t\t\t.where(\"token_hash\", \"=\", hash)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\t// Per RFC 7009: always 200, even for invalid tokens\n\t\t\treturn { success: true, data: { revoked: true } };\n\t\t}\n\n\t\tif (row.token_type === \"refresh\") {\n\t\t\t// Revoke refresh token and all its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"refresh_token_hash\", \"=\", hash).execute();\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t} else {\n\t\t\t// Revoke just the access token\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t}\n\n\t\treturn { success: true, data: { revoked: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REVOKE_ERROR\",\n\t\t\t\tmessage: \"Failed to revoke token\",\n\t\t\t},\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAM,0BAA0B;;AAGhC,MAAM,mBAAmB;;AAGzB,MAAM,sBAAsB;;AAG5B,MAAM,yBAAyB;;AAG/B,MAAM,2BAA2B;;AAGjC,MAAM,4BAA4B,OAAU,KAAK;;AAGjD,MAAM,iBAAiB;CACtB;CACA;CACA;CACA;CACA;CACA;;AAGD,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAkCxB,SAAS,mBAA2B;CACnC,MAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAO,gBAAgB,MAAM;CAC7B,MAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM,gBAAgB,IAAI,IAAwB,CAAC,KAAK,GAAG;AAC5F,QAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,MAAM,GAAG,EAAE;;;AAIjD,SAAS,UAAU,SAAyB;AAC3C,QAAO,IAAI,KAAK,KAAK,KAAK,GAAG,UAAU,IAAK,CAAC,aAAa;;;AAI3D,SAAS,gBAAgB,WAAgC;AACxD,KAAI,CAAC,aAAa,UAAU,WAAW,EACtC,QAAO,CAAC,GAAG,eAAe;AAE3B,QAAO,UAAU,OAAO,aAAa;;;;;;;;AAatC,eAAsB,wBACrB,IACA,OAIA,iBACyC;AACzC,KAAI;EAQH,MAAM,SAAS,gBADS,MAAM,QAAQ,MAAM,MAAM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AAC,SAAS;QAGpF,OAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;AAGrF,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD"}
@@ -16,6 +16,25 @@ function isPostgres(db) {
16
16
  return detectDialect(db) === "postgres";
17
17
  }
18
18
  /**
19
+ * The backend's compound-SELECT ceiling, or null when it has none worth
20
+ * splitting statements for. Only the adapter knows: the limit is a property of
21
+ * the SQLite build behind the dialect, not of the SQL flavour, so two "sqlite"
22
+ * dialects can answer differently.
23
+ *
24
+ * A declared ceiling must be a positive integer — callers batch by it, and
25
+ * every other value silently misbehaves rather than failing: 0 and negatives
26
+ * never advance the batch cursor, fractions overlap batches and double-count,
27
+ * NaN yields an empty batch. A malformed declaration throws here, where the
28
+ * message can name the adapter.
29
+ */
30
+ function compoundSelectLimit(db) {
31
+ const adapter = db.getExecutor().adapter;
32
+ if (!("compoundSelectLimit" in adapter)) return null;
33
+ const limit = adapter.compoundSelectLimit;
34
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) throw new Error(`${adapter.constructor.name} declares compoundSelectLimit ${String(limit)}; it must be a positive integer.`);
35
+ return limit;
36
+ }
37
+ /**
19
38
  * Default timestamp expression for column defaults.
20
39
  * Wrapped in parens for use in CREATE TABLE ... DEFAULT (...).
21
40
  *
@@ -171,5 +190,5 @@ function pluginDataOrderExpr(db, field) {
171
190
  }
172
191
 
173
192
  //#endregion
174
- export { currentTimestampValue as a, listTablesLike as c, tableExists as d, currentTimestamp as i, pluginDataExtractExpr as l, buildStatusCondition as n, isPostgres as o, columnExists as r, isSqlite as s, binaryType as t, pluginDataOrderExpr as u };
175
- //# sourceMappingURL=dialect-helpers-BtOwo2us.mjs.map
193
+ export { currentTimestamp as a, isSqlite as c, pluginDataOrderExpr as d, tableExists as f, compoundSelectLimit as i, listTablesLike as l, buildStatusCondition as n, currentTimestampValue as o, columnExists as r, isPostgres as s, binaryType as t, pluginDataExtractExpr as u };
194
+ //# sourceMappingURL=dialect-helpers-DFwyWjTM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dialect-helpers-DFwyWjTM.mjs","names":[],"sources":["../src/database/dialect-helpers.ts"],"sourcesContent":["/**\n * Dialect-specific SQL helpers\n *\n * Every function takes a Kysely `db` instance and detects the dialect from\n * the adapter class. No module-level state, no globals, no heuristics —\n * the adapter is the source of truth.\n *\n * This is NOT an ORM abstraction — just targeted helpers for the ~15 places\n * that use raw dialect-specific SQL. Most Kysely schema builder code already\n * works cross-dialect.\n */\n\nimport type { ColumnDataType, Kysely, RawBuilder } from \"kysely\";\nimport { PostgresAdapter, sql } from \"kysely\";\n\nimport type { DatabaseDialectType } from \"../db/adapters.js\";\nimport { validateIdentifier, validateJsonFieldName } from \"./validate.js\";\n\nexport type { DatabaseDialectType };\n\n/**\n * Detect dialect type from a Kysely instance via the adapter class.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function detectDialect(db: Kysely<any>): DatabaseDialectType {\n\tif (db.getExecutor().adapter instanceof PostgresAdapter) return \"postgres\";\n\treturn \"sqlite\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function isSqlite(db: Kysely<any>): boolean {\n\treturn detectDialect(db) === \"sqlite\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function isPostgres(db: Kysely<any>): boolean {\n\treturn detectDialect(db) === \"postgres\";\n}\n\n/**\n * Declared by an adapter whose backend caps the number of terms in a compound\n * SELECT (`UNION ALL`, `INTERSECT`, `EXCEPT`). SQLite's own\n * SQLITE_LIMIT_COMPOUND_SELECT default is 500 — high enough that no query\n * EmDash builds approaches it — but Cloudflare D1 sets it to 5 and rejects\n * anything larger with \"too many terms in compound SELECT\".\n */\nexport interface CompoundSelectLimitedAdapter {\n\t/** Maximum terms per compound SELECT. Must be a positive integer. */\n\treadonly compoundSelectLimit: number;\n}\n\n/**\n * The backend's compound-SELECT ceiling, or null when it has none worth\n * splitting statements for. Only the adapter knows: the limit is a property of\n * the SQLite build behind the dialect, not of the SQL flavour, so two \"sqlite\"\n * dialects can answer differently.\n *\n * A declared ceiling must be a positive integer — callers batch by it, and\n * every other value silently misbehaves rather than failing: 0 and negatives\n * never advance the batch cursor, fractions overlap batches and double-count,\n * NaN yields an empty batch. A malformed declaration throws here, where the\n * message can name the adapter.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function compoundSelectLimit(db: Kysely<any>): number | null {\n\tconst adapter: object = db.getExecutor().adapter;\n\tif (!(\"compoundSelectLimit\" in adapter)) return null;\n\n\tconst limit: unknown = adapter.compoundSelectLimit;\n\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1) {\n\t\tthrow new Error(\n\t\t\t`${adapter.constructor.name} declares compoundSelectLimit ${String(limit)}; it must be a positive integer.`,\n\t\t);\n\t}\n\treturn limit;\n}\n\n/**\n * Default timestamp expression for column defaults.\n * Wrapped in parens for use in CREATE TABLE ... DEFAULT (...).\n *\n * sqlite: (datetime('now'))\n * postgres: CURRENT_TIMESTAMP\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function currentTimestamp(db: Kysely<any>): RawBuilder<string> {\n\tif (isPostgres(db)) {\n\t\treturn sql`CURRENT_TIMESTAMP`;\n\t}\n\treturn sql`(datetime('now'))`;\n}\n\n/**\n * Timestamp expression for use in WHERE clauses and SET expressions.\n * No wrapping parens.\n *\n * sqlite: datetime('now')\n * postgres: CURRENT_TIMESTAMP\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function currentTimestampValue(db: Kysely<any>): RawBuilder<string> {\n\tif (isPostgres(db)) {\n\t\treturn sql`CURRENT_TIMESTAMP`;\n\t}\n\treturn sql`datetime('now')`;\n}\n\n/**\n * Build WHERE clause for status filtering on a content table.\n * When filtering for 'published' status, also include scheduled content\n * whose scheduled_at time has passed (treating it as effectively published).\n *\n * Visibility is computed, not flipped by cron, so a literal\n * `status = 'published'` comparison undercounts scheduled-and-due entries —\n * every \"publicly visible\" filter must go through this helper.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildStatusCondition(\n\tdb: Kysely<any>,\n\tstatus: string,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst statusField = tablePrefix ? `${tablePrefix}.status` : \"status\";\n\tconst scheduledAtField = tablePrefix ? `${tablePrefix}.scheduled_at` : \"scheduled_at\";\n\n\tif (status === \"published\") {\n\t\t// Include both published content AND scheduled content past its publish time.\n\t\t// scheduled_at is stored as text (ISO 8601). On Postgres, we must cast it\n\t\t// to timestamptz for the comparison with CURRENT_TIMESTAMP to work.\n\t\tconst scheduledAtExpr = isPostgres(db)\n\t\t\t? sql`${sql.ref(scheduledAtField)}::timestamptz`\n\t\t\t: sql.ref(scheduledAtField);\n\t\tconst nowExpr = isPostgres(db)\n\t\t\t? currentTimestampValue(db)\n\t\t\t: sql`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;\n\t\treturn sql`(${sql.ref(statusField)} = 'published' OR (${sql.ref(statusField)} = 'scheduled' AND ${scheduledAtExpr} <= ${nowExpr}))`;\n\t}\n\n\treturn sql`${sql.ref(statusField)} = ${status}`;\n}\n\n/**\n * Check if a table exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function tableExists(db: Kysely<any>, tableName: string): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\t// Scope to the active schema (matches indexExists/columnExists below).\n\t\t// Hardcoding 'public' breaks non-public-schema Postgres deployments.\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.tables\n\t\t\t\tWHERE table_schema = current_schema() AND table_name = ${tableName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table' AND name = ${tableName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * Check if an index exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function indexExists(db: Kysely<any>, indexName: string): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM pg_indexes\n\t\t\t\tWHERE schemaname = current_schema() AND indexname = ${indexName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'index' AND name = ${indexName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * Check if a column exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function columnExists(\n\tdb: Kysely<any>,\n\ttableName: string,\n\tcolumnName: string,\n): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\t\tWHERE table_schema = current_schema()\n\t\t\t\t\tAND table_name = ${tableName}\n\t\t\t\t\tAND column_name = ${columnName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM pragma_table_info(${tableName})\n\t\tWHERE name = ${columnName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * List tables matching a LIKE pattern.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function listTablesLike(db: Kysely<any>, pattern: string): Promise<string[]> {\n\tif (isPostgres(db)) {\n\t\t// Scope to the connection's active schema rather than hardcoding\n\t\t// 'public'. A Postgres deployment using a non-public schema (per-tenant\n\t\t// or shared-cluster setups), or per-test schemas, otherwise sees tables\n\t\t// from the wrong schema — or none at all. Mirrors migration 038.\n\t\tconst result = await sql<{ table_name: string }>`\n\t\t\tSELECT table_name FROM information_schema.tables\n\t\t\tWHERE table_schema = current_schema() AND table_name LIKE ${pattern}\n\t\t`.execute(db);\n\t\treturn result.rows.map((r) => r.table_name);\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table' AND name LIKE ${pattern}\n\t`.execute(db);\n\treturn result.rows.map((r) => r.name);\n}\n\n/**\n * Column type for binary data.\n *\n * sqlite: blob\n * postgres: bytea\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function binaryType(db: Kysely<any>): ColumnDataType {\n\tif (isPostgres(db)) {\n\t\treturn \"bytea\";\n\t}\n\treturn \"blob\";\n}\n\n/**\n * SQL expression for extracting a field from a JSON column stored as text.\n *\n * sqlite: json_extract(column, '$.path')\n * postgres: (column)::jsonb->>'path'\n *\n * The Postgres cast is required because JSON columns (e.g.\n * `_plugin_storage.data`) are `text`, and `text ->> unknown` is not an\n * operator. The cast is immutable, so the same expression works in\n * expression indexes — queries and indexes must build it through this\n * helper so the planner can match them.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtractExpr(db: Kysely<any>, column: string, path: string): string {\n\tvalidateIdentifier(column, \"JSON column name\");\n\tvalidateJsonFieldName(path, \"JSON path\");\n\tif (isPostgres(db)) {\n\t\treturn `(${column})::jsonb->>'${path}'`;\n\t}\n\treturn `json_extract(${column}, '$.${path}')`;\n}\n\n/**\n * SQL expression for extracting a queryable field from the plugin-storage\n * `data` column.\n *\n * `_plugin_storage.data` is `text`, so Postgres extraction goes through the\n * `(data)::jsonb->>'field'` cast (#1898) — otherwise `text ->> unknown` is not\n * an operator. But the extracted value is still `text`, so a numeric comparison\n * (`stock >= 10`) compares lexically (`'9' >= '10'` is TRUE) and silently\n * over-counts / oversells; pass `{ numeric: true }` for a numeric comparison.\n *\n * The numeric form is a **type-guarded** cast, not a bare `::numeric`. A bare\n * cast throws `invalid input syntax for type numeric` the moment a single\n * scanned row stores a non-number in that field (documents are schemaless),\n * aborting the whole query — and it would diverge from SQLite, which silently\n * coerces. Guarding with `jsonb_typeof`/`json_type` makes the comparison total\n * and parity-correct on both dialects: a non-number stored value yields `NULL`\n * (no match) instead of an error.\n *\n * The field name is validated before interpolation, so the casts wrap only a\n * safe identifier and add no injection surface.\n *\n * sqlite text: json_extract(data, '$.field')\n * sqlite numeric: CASE WHEN json_type(data, '$.field') IN ('integer', 'real')\n * THEN json_extract(data, '$.field') END\n * postgres text: (data)::jsonb->>'field'\n * postgres numeric: CASE WHEN jsonb_typeof((data)::jsonb->'field') = 'number'\n * THEN ((data)::jsonb->>'field')::numeric END\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function pluginDataExtractExpr(\n\tdb: Kysely<any>,\n\tfield: string,\n\toptions?: { numeric?: boolean },\n): string {\n\tvalidateJsonFieldName(field, \"plugin storage field name\");\n\tif (isPostgres(db)) {\n\t\tconst text = `(data)::jsonb->>'${field}'`;\n\t\tif (!options?.numeric) return text;\n\t\treturn `CASE WHEN jsonb_typeof((data)::jsonb->'${field}') = 'number' THEN (${text})::numeric END`;\n\t}\n\tconst extract = `json_extract(data, '$.${field}')`;\n\tif (!options?.numeric) return extract;\n\treturn `CASE WHEN json_type(data, '$.${field}') IN ('integer', 'real') THEN ${extract} END`;\n}\n\n/**\n * SQL expression for ordering plugin-storage rows by a `data` field.\n *\n * `ORDER BY` has no bound operand to infer numeric-vs-text from, so extracting\n * as text (`->>'field'`) would sort a numeric field lexically on Postgres\n * (`[10, 100, 9]`) while SQLite's `json_extract` sorts it numerically — a\n * cross-dialect divergence. Ordering over the jsonb-native value (`->'field'`,\n * single arrow) fixes this: jsonb btree ordering is numeric among numbers,\n * lexical among strings, and total across heterogeneous values (never throws).\n * SQLite's `json_extract` already orders numerically, so it is unchanged.\n *\n * sqlite: json_extract(data, '$.field')\n * postgres: (data)::jsonb->'field'\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function pluginDataOrderExpr(db: Kysely<any>, field: string): string {\n\tvalidateJsonFieldName(field, \"plugin storage order field name\");\n\tif (isPostgres(db)) {\n\t\treturn `(data)::jsonb->'${field}'`;\n\t}\n\treturn `json_extract(data, '$.${field}')`;\n}\n"],"mappings":";;;;;;;AAwBA,SAAgB,cAAc,IAAsC;AACnE,KAAI,GAAG,aAAa,CAAC,mBAAmB,gBAAiB,QAAO;AAChE,QAAO;;AAIR,SAAgB,SAAS,IAA0B;AAClD,QAAO,cAAc,GAAG,KAAK;;AAI9B,SAAgB,WAAW,IAA0B;AACpD,QAAO,cAAc,GAAG,KAAK;;;;;;;;;;;;;;AA4B9B,SAAgB,oBAAoB,IAAgC;CACnE,MAAM,UAAkB,GAAG,aAAa,CAAC;AACzC,KAAI,EAAE,yBAAyB,SAAU,QAAO;CAEhD,MAAM,QAAiB,QAAQ;AAC/B,KAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,MAAM,IAAI,QAAQ,EACpE,OAAM,IAAI,MACT,GAAG,QAAQ,YAAY,KAAK,gCAAgC,OAAO,MAAM,CAAC,kCAC1E;AAEF,QAAO;;;;;;;;;AAWR,SAAgB,iBAAiB,IAAqC;AACrE,KAAI,WAAW,GAAG,CACjB,QAAO,GAAG;AAEX,QAAO,GAAG;;;;;;;;;AAWX,SAAgB,sBAAsB,IAAqC;AAC1E,KAAI,WAAW,GAAG,CACjB,QAAO,GAAG;AAEX,QAAO,GAAG;;;;;;;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;;;;;AAUtC,SAAgB,WAAW,IAAiC;AAC3D,KAAI,WAAW,GAAG,CACjB,QAAO;AAER,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDR,SAAgB,sBACf,IACA,OACA,SACS;AACT,uBAAsB,OAAO,4BAA4B;AACzD,KAAI,WAAW,GAAG,EAAE;EACnB,MAAM,OAAO,oBAAoB,MAAM;AACvC,MAAI,CAAC,SAAS,QAAS,QAAO;AAC9B,SAAO,0CAA0C,MAAM,sBAAsB,KAAK;;CAEnF,MAAM,UAAU,yBAAyB,MAAM;AAC/C,KAAI,CAAC,SAAS,QAAS,QAAO;AAC9B,QAAO,gCAAgC,MAAM,iCAAiC,QAAQ;;;;;;;;;;;;;;;;AAkBvF,SAAgB,oBAAoB,IAAiB,OAAuB;AAC3E,uBAAsB,OAAO,kCAAkC;AAC/D,KAAI,WAAW,GAAG,CACjB,QAAO,mBAAmB,MAAM;AAEjC,QAAO,yBAAyB,MAAM"}
@@ -1,4 +1,4 @@
1
- import { n as InvalidCursorError } from "./types-CrRUFdej.mjs";
1
+ import { n as InvalidCursorError } from "./types-XrQQ-Aex.mjs";
2
2
  import { n as mapErrorStatus } from "./errors-DtEXIQQV.mjs";
3
3
 
4
4
  //#region src/api/error.ts
@@ -87,4 +87,4 @@ function unwrapResult(result, successStatus = 200) {
87
87
 
88
88
  //#endregion
89
89
  export { unwrapResult as a, requireDb as i, apiSuccess as n, handleError as r, apiError as t };
90
- //# sourceMappingURL=error-DJ98TRbQ.mjs.map
90
+ //# sourceMappingURL=error-DmmN74gW.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-DJ98TRbQ.mjs","names":[],"sources":["../src/api/error.ts"],"sourcesContent":["/**\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 `{ success: false, error: { code, message } }` with correct\n * Content-Type. 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({ success: false, error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ success: true, 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({ success: true, 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":";;;;;;;;;;;;;;;;AAoBA,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,SAAS;EAAO;EAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxF,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK;EAAE,SAAS;EAAM;EAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWtF,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
+ {"version":3,"file":"error-DmmN74gW.mjs","names":[],"sources":["../src/api/error.ts"],"sourcesContent":["/**\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 `{ success: false, error: { code, message } }` with correct\n * Content-Type. 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({ success: false, error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ success: true, 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({ success: true, 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":";;;;;;;;;;;;;;;;AAoBA,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,SAAS;EAAO;EAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxF,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK;EAAE,SAAS;EAAM;EAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWtF,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"}
@@ -6,4 +6,4 @@ function escapeHtml(str) {
6
6
 
7
7
  //#endregion
8
8
  export { escapeHtml as t };
9
- //# sourceMappingURL=escape-CFedIB1C.mjs.map
9
+ //# sourceMappingURL=escape-CdW31WsG.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"escape-CFedIB1C.mjs","names":[],"sources":["../src/api/escape.ts"],"sourcesContent":["/** HTML-escape a string to prevent XSS when interpolated into HTML/JS */\nexport function escapeHtml(str: string): string {\n\treturn str\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#x27;\");\n}\n"],"mappings":";;AACA,SAAgB,WAAW,KAAqB;AAC/C,QAAO,IACL,WAAW,KAAK,QAAQ,CACxB,WAAW,KAAK,OAAO,CACvB,WAAW,KAAK,OAAO,CACvB,WAAW,MAAK,SAAS,CACzB,WAAW,KAAK,SAAS"}
1
+ {"version":3,"file":"escape-CdW31WsG.mjs","names":[],"sources":["../src/api/escape.ts"],"sourcesContent":["/** HTML-escape a string to prevent XSS when interpolated into HTML/JS */\nexport function escapeHtml(str: string): string {\n\treturn str\n\t\t.replaceAll(\"&\", \"&amp;\")\n\t\t.replaceAll(\"<\", \"&lt;\")\n\t\t.replaceAll(\">\", \"&gt;\")\n\t\t.replaceAll('\"', \"&quot;\")\n\t\t.replaceAll(\"'\", \"&#x27;\");\n}\n"],"mappings":";;AACA,SAAgB,WAAW,KAAqB;AAC/C,QAAO,IACL,WAAW,KAAK,QAAQ,CACxB,WAAW,KAAK,OAAO,CACvB,WAAW,KAAK,OAAO,CACvB,WAAW,MAAK,SAAS,CACzB,WAAW,KAAK,SAAS"}
@@ -1,4 +1,4 @@
1
- import { o as __exportAll } from "./runner-BdeLEgad.mjs";
1
+ import { o as __exportAll } from "./runner-BsI18UgP.mjs";
2
2
  import { t as after } from "./after-B1IIdH3Y.mjs";
3
3
  import { getRequestContext } from "./request-context.mjs";
4
4
  import { r as requestCached } from "./request-cache-BSUptuJR.mjs";
@@ -74,4 +74,4 @@ async function getBylineFieldDefs(db) {
74
74
 
75
75
  //#endregion
76
76
  export { getBylineFieldDefs as n, field_defs_cache_exports as t };
77
- //# sourceMappingURL=field-defs-cache-KfNJ_qLQ.mjs.map
77
+ //# sourceMappingURL=field-defs-cache-QMVnzTH6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"field-defs-cache-KfNJ_qLQ.mjs","names":[],"sources":["../src/bylines/field-defs-cache.ts"],"sourcesContent":["/**\n * Byline field-definitions cache\n *\n * Discussion #1174 / Phase 3. Two-tier cache for the byline custom-field\n * registry, mirroring the `settings/index.ts` pattern.\n *\n * **Tier 1 — per-isolate (globalThis).** Field definitions change rarely\n * but are read on every byline hydration (admin pages, content rendering,\n * API responses). Caching at the isolate level drops the SELECT-from-\n * `_emdash_byline_fields` from once-per-hydration to once-per-isolate-\n * after-bump. The cache holds the resolved *value* behind a reclaimable\n * single-flight lock (see `utils/single-flight-cache.ts`), never an\n * in-flight promise: concurrent cold-isolate readers coalesce onto one\n * query by polling the published value, so a reader whose request is\n * cancelled mid-query can never strand later byline hydrations on the\n * isolate (the workerd never-settling-promise hazard that produced 524s).\n *\n * Stored on globalThis under `Symbol.for(\"emdash:byline-field-defs\")` so\n * Vite SSR chunk duplication can't produce two independent caches (same\n * pattern as `request-cache.ts` and `request-context.ts`).\n *\n * **Tier 2 — per-request.** Wraps both the version read and the defs\n * fetch in `requestCached` so a single page render that hits byline\n * hydration multiple times (e.g. list view + individual byline lookups\n * in a sidebar) pays at most one version read and one defs fetch in\n * total. The defs cache key includes the version, so a (highly\n * unlikely) mid-request bump still produces a self-consistent view —\n * the second call sees a different key and refetches.\n *\n * **Invalidation.** `options.byline_fields_version` is bumped by every\n * `BylineSchemaRegistry` mutation (Phase 2). Each isolate independently\n * reads the persisted version on the next request and compares against\n * its cached version; mismatch triggers a refetch and overwrite. Other\n * isolates see the change within one request after the bump propagates.\n *\n * **Isolated databases bypass the global cache.** Playground and DO\n * preview sessions set `requestContext.dbIsIsolated = true`, signalling\n * the per-request `db` points at an isolated schema that may diverge\n * from the singleton. Schema-derived caches keyed by the singleton's\n * version would silently leak the singleton's defs into the isolated\n * request. We follow the `loader.ts:74` `getTaxonomyNames` precedent:\n * skip both reading from and writing to the global holder when the\n * request is isolated. The per-request cache (`requestCached`) is keyed\n * by the WeakMap'd `EmDashRequestContext`, so it can't cross-pollinate\n * between requests — it stays in play even for isolated DBs.\n *\n * **Why a versioned cache and not a TTL?** The version counter gives\n * deterministic invalidation without the staleness window a TTL would\n * impose. Field-definition changes need to be visible to the next\n * request, not eventually. The cost is one cheap `options` read per\n * request — cheaper than the field-defs fetch it replaces, and cheaper\n * than maintaining a TTL state machine.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport type { Database } from \"../database/types.js\";\nimport { requestCached } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { BylineSchemaRegistry } from \"../schema/byline-registry.js\";\nimport type { BylineFieldDefinition } from \"../schema/types.js\";\nimport { createInitLock, type InitLock, initWithLock } from \"../utils/init-lock.js\";\n\ninterface FieldDefsHolder {\n\t/** Last resolved defs, valid only when `hasValue` is true. */\n\tvalue: BylineFieldDefinition[] | null;\n\t/** Presence flag, separate from `value` so an empty-array result still caches. */\n\thasValue: boolean;\n\t/** Persisted-version value that `value` was fetched against. */\n\tcachedVersion: number;\n\t/** Reclaimable single-flight lock so a cancelled owner can't wedge readers. */\n\tlock: InitLock;\n}\n\nconst HOLDER_KEY = Symbol.for(\"emdash:byline-field-defs\");\nconst g = globalThis as Record<symbol, unknown>;\nconst holder: FieldDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-cache.ts)\n\t(g[HOLDER_KEY] as FieldDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: FieldDefsHolder = {\n\t\t\tvalue: null,\n\t\t\thasValue: false,\n\t\t\tcachedVersion: -1,\n\t\t\tlock: createInitLock(),\n\t\t};\n\t\tg[HOLDER_KEY] = h;\n\t\treturn h;\n\t})();\n\nconst REQUEST_CACHE_KEY_VERSION = \"byline-fields-version\";\nconst REQUEST_CACHE_KEY_DEFS_PREFIX = \"byline-field-defs:\";\n\n/**\n * Reclaim window for the single-flight lock: if an owner holds it past\n * this without publishing (e.g. its request was cancelled and the\n * anchored fetch hasn't completed yet), the next reader reclaims and\n * refetches. `listFields` is a single fast SELECT, so this only needs to\n * cover a genuinely slow/stranded query. Mutable solely so tests can\n * shorten it; production never changes it.\n */\nlet reclaimDeadlineMs = 10_000;\n\n/**\n * Read the persisted `options.byline_fields_version` counter. Cached for\n * the duration of the current request via `requestCached`. Returns `0`\n * when the row is missing (matches `BylineSchemaRegistry.getVersion`).\n */\nasync function getBylineFieldsVersion(db: Kysely<Database>): Promise<number> {\n\treturn requestCached(REQUEST_CACHE_KEY_VERSION, () => new BylineSchemaRegistry(db).getVersion());\n}\n\n/**\n * Resolve registered byline custom-field definitions. Two-tier cache:\n * per-request via `requestCached`, then per-isolate via the global\n * holder.\n *\n * The global holder is bypassed for isolated requests (playground / DO\n * preview, which point at a divergent schema) and for dirty versions\n * (odd counter — see `BylineSchemaRegistry`'s class JSDoc — indicates\n * an in-flight or crashed mutation). Both bypass paths still hit the\n * per-request cache, so a single render dedupes within itself.\n *\n * Always returns an array. Empty = no custom fields registered.\n */\nexport async function getBylineFieldDefs(db: Kysely<Database>): Promise<BylineFieldDefinition[]> {\n\tconst isolated = getRequestContext()?.dbIsIsolated === true;\n\tconst version = await getBylineFieldsVersion(db);\n\tconst dirty = version % 2 !== 0;\n\treturn requestCached(`${REQUEST_CACHE_KEY_DEFS_PREFIX}${version}`, async () => {\n\t\tif (isolated || dirty) {\n\t\t\treturn new BylineSchemaRegistry(db).listFields();\n\t\t}\n\t\t// Per-isolate single-flight cache keyed on the persisted version.\n\t\t// Coalesce concurrent cold readers via the lock and read the\n\t\t// published value; never await another request's in-flight promise\n\t\t// (a cancelled owner would otherwise strand every later byline\n\t\t// hydration on the isolate). The fetch is anchored so a cancelled\n\t\t// originator still drives it to completion and populates the cache.\n\t\treturn initWithLock<BylineFieldDefinition[]>(\n\t\t\tholder.lock,\n\t\t\t() => (holder.hasValue && holder.cachedVersion === version ? holder.value : null),\n\t\t\t(isCurrentClaim) =>\n\t\t\t\t(async () => {\n\t\t\t\t\tconst defs = await new BylineSchemaRegistry(db).listFields();\n\t\t\t\t\t// Publish only while still the current claim, and never\n\t\t\t\t\t// regress over a newer version a concurrent reader stored.\n\t\t\t\t\tif (isCurrentClaim() && version >= holder.cachedVersion) {\n\t\t\t\t\t\tholder.value = defs;\n\t\t\t\t\t\tholder.hasValue = true;\n\t\t\t\t\t\tholder.cachedVersion = version;\n\t\t\t\t\t}\n\t\t\t\t\treturn defs;\n\t\t\t\t})(),\n\t\t\t{ deadlineMs: reclaimDeadlineMs, anchor: (promise) => after(() => promise) },\n\t\t);\n\t});\n}\n\n/**\n * Test/internal helper: clear the per-isolate cache. Useful for unit\n * tests that mutate the registry directly and need to force a refetch\n * without going through the full version-bump path.\n *\n * Production code paths should rely on the version counter for\n * invalidation — calling this from a write path would bypass the\n * coordination that lets other isolates see the change.\n */\nexport function resetBylineFieldDefsCacheForTests(): void {\n\tholder.value = null;\n\tholder.hasValue = false;\n\tholder.cachedVersion = -1;\n\tholder.lock.ownerStartedAt = null;\n\tholder.lock.generation = 0;\n\treclaimDeadlineMs = 10_000;\n}\n\n/**\n * Test-only: shorten the single-flight reclaim window so a \"stranded\n * owner\" scenario can be exercised without waiting out the production\n * deadline. Reset by `resetBylineFieldDefsCacheForTests`.\n *\n * @internal\n */\nexport function setBylineFieldDefsReclaimDeadlineForTests(ms: number): void {\n\treclaimDeadlineMs = ms;\n}\n"],"mappings":";;;;;;;;;AA2EA,MAAM,aAAa,OAAO,IAAI,2BAA2B;AACzD,MAAM,IAAI;AACV,MAAM,SAEJ,EAAE,sBACI;CACN,MAAM,IAAqB;EAC1B,OAAO;EACP,UAAU;EACV,eAAe;EACf,MAAM,gBAAgB;EACtB;AACD,GAAE,cAAc;AAChB,QAAO;IACJ;AAEL,MAAM,4BAA4B;AAClC,MAAM,gCAAgC;;;;;;;;;AAUtC,IAAI,oBAAoB;;;;;;AAOxB,eAAe,uBAAuB,IAAuC;AAC5E,QAAO,cAAc,iCAAiC,IAAI,qBAAqB,GAAG,CAAC,YAAY,CAAC;;;;;;;;;;;;;;;AAgBjG,eAAsB,mBAAmB,IAAwD;CAChG,MAAM,WAAW,mBAAmB,EAAE,iBAAiB;CACvD,MAAM,UAAU,MAAM,uBAAuB,GAAG;CAChD,MAAM,QAAQ,UAAU,MAAM;AAC9B,QAAO,cAAc,GAAG,gCAAgC,WAAW,YAAY;AAC9E,MAAI,YAAY,MACf,QAAO,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAQjD,SAAO,aACN,OAAO,YACA,OAAO,YAAY,OAAO,kBAAkB,UAAU,OAAO,QAAQ,OAC3E,oBACC,YAAY;GACZ,MAAM,OAAO,MAAM,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAG5D,OAAI,gBAAgB,IAAI,WAAW,OAAO,eAAe;AACxD,WAAO,QAAQ;AACf,WAAO,WAAW;AAClB,WAAO,gBAAgB;;AAExB,UAAO;MACJ,EACL;GAAE,YAAY;GAAmB,SAAS,YAAY,YAAY,QAAQ;GAAE,CAC5E;GACA"}
1
+ {"version":3,"file":"field-defs-cache-QMVnzTH6.mjs","names":[],"sources":["../src/bylines/field-defs-cache.ts"],"sourcesContent":["/**\n * Byline field-definitions cache\n *\n * Discussion #1174 / Phase 3. Two-tier cache for the byline custom-field\n * registry, mirroring the `settings/index.ts` pattern.\n *\n * **Tier 1 — per-isolate (globalThis).** Field definitions change rarely\n * but are read on every byline hydration (admin pages, content rendering,\n * API responses). Caching at the isolate level drops the SELECT-from-\n * `_emdash_byline_fields` from once-per-hydration to once-per-isolate-\n * after-bump. The cache holds the resolved *value* behind a reclaimable\n * single-flight lock (see `utils/single-flight-cache.ts`), never an\n * in-flight promise: concurrent cold-isolate readers coalesce onto one\n * query by polling the published value, so a reader whose request is\n * cancelled mid-query can never strand later byline hydrations on the\n * isolate (the workerd never-settling-promise hazard that produced 524s).\n *\n * Stored on globalThis under `Symbol.for(\"emdash:byline-field-defs\")` so\n * Vite SSR chunk duplication can't produce two independent caches (same\n * pattern as `request-cache.ts` and `request-context.ts`).\n *\n * **Tier 2 — per-request.** Wraps both the version read and the defs\n * fetch in `requestCached` so a single page render that hits byline\n * hydration multiple times (e.g. list view + individual byline lookups\n * in a sidebar) pays at most one version read and one defs fetch in\n * total. The defs cache key includes the version, so a (highly\n * unlikely) mid-request bump still produces a self-consistent view —\n * the second call sees a different key and refetches.\n *\n * **Invalidation.** `options.byline_fields_version` is bumped by every\n * `BylineSchemaRegistry` mutation (Phase 2). Each isolate independently\n * reads the persisted version on the next request and compares against\n * its cached version; mismatch triggers a refetch and overwrite. Other\n * isolates see the change within one request after the bump propagates.\n *\n * **Isolated databases bypass the global cache.** Playground and DO\n * preview sessions set `requestContext.dbIsIsolated = true`, signalling\n * the per-request `db` points at an isolated schema that may diverge\n * from the singleton. Schema-derived caches keyed by the singleton's\n * version would silently leak the singleton's defs into the isolated\n * request. We follow the `loader.ts:74` `getTaxonomyNames` precedent:\n * skip both reading from and writing to the global holder when the\n * request is isolated. The per-request cache (`requestCached`) is keyed\n * by the WeakMap'd `EmDashRequestContext`, so it can't cross-pollinate\n * between requests — it stays in play even for isolated DBs.\n *\n * **Why a versioned cache and not a TTL?** The version counter gives\n * deterministic invalidation without the staleness window a TTL would\n * impose. Field-definition changes need to be visible to the next\n * request, not eventually. The cost is one cheap `options` read per\n * request — cheaper than the field-defs fetch it replaces, and cheaper\n * than maintaining a TTL state machine.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport type { Database } from \"../database/types.js\";\nimport { requestCached } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { BylineSchemaRegistry } from \"../schema/byline-registry.js\";\nimport type { BylineFieldDefinition } from \"../schema/types.js\";\nimport { createInitLock, type InitLock, initWithLock } from \"../utils/init-lock.js\";\n\ninterface FieldDefsHolder {\n\t/** Last resolved defs, valid only when `hasValue` is true. */\n\tvalue: BylineFieldDefinition[] | null;\n\t/** Presence flag, separate from `value` so an empty-array result still caches. */\n\thasValue: boolean;\n\t/** Persisted-version value that `value` was fetched against. */\n\tcachedVersion: number;\n\t/** Reclaimable single-flight lock so a cancelled owner can't wedge readers. */\n\tlock: InitLock;\n}\n\nconst HOLDER_KEY = Symbol.for(\"emdash:byline-field-defs\");\nconst g = globalThis as Record<symbol, unknown>;\nconst holder: FieldDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-cache.ts)\n\t(g[HOLDER_KEY] as FieldDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: FieldDefsHolder = {\n\t\t\tvalue: null,\n\t\t\thasValue: false,\n\t\t\tcachedVersion: -1,\n\t\t\tlock: createInitLock(),\n\t\t};\n\t\tg[HOLDER_KEY] = h;\n\t\treturn h;\n\t})();\n\nconst REQUEST_CACHE_KEY_VERSION = \"byline-fields-version\";\nconst REQUEST_CACHE_KEY_DEFS_PREFIX = \"byline-field-defs:\";\n\n/**\n * Reclaim window for the single-flight lock: if an owner holds it past\n * this without publishing (e.g. its request was cancelled and the\n * anchored fetch hasn't completed yet), the next reader reclaims and\n * refetches. `listFields` is a single fast SELECT, so this only needs to\n * cover a genuinely slow/stranded query. Mutable solely so tests can\n * shorten it; production never changes it.\n */\nlet reclaimDeadlineMs = 10_000;\n\n/**\n * Read the persisted `options.byline_fields_version` counter. Cached for\n * the duration of the current request via `requestCached`. Returns `0`\n * when the row is missing (matches `BylineSchemaRegistry.getVersion`).\n */\nasync function getBylineFieldsVersion(db: Kysely<Database>): Promise<number> {\n\treturn requestCached(REQUEST_CACHE_KEY_VERSION, () => new BylineSchemaRegistry(db).getVersion());\n}\n\n/**\n * Resolve registered byline custom-field definitions. Two-tier cache:\n * per-request via `requestCached`, then per-isolate via the global\n * holder.\n *\n * The global holder is bypassed for isolated requests (playground / DO\n * preview, which point at a divergent schema) and for dirty versions\n * (odd counter — see `BylineSchemaRegistry`'s class JSDoc — indicates\n * an in-flight or crashed mutation). Both bypass paths still hit the\n * per-request cache, so a single render dedupes within itself.\n *\n * Always returns an array. Empty = no custom fields registered.\n */\nexport async function getBylineFieldDefs(db: Kysely<Database>): Promise<BylineFieldDefinition[]> {\n\tconst isolated = getRequestContext()?.dbIsIsolated === true;\n\tconst version = await getBylineFieldsVersion(db);\n\tconst dirty = version % 2 !== 0;\n\treturn requestCached(`${REQUEST_CACHE_KEY_DEFS_PREFIX}${version}`, async () => {\n\t\tif (isolated || dirty) {\n\t\t\treturn new BylineSchemaRegistry(db).listFields();\n\t\t}\n\t\t// Per-isolate single-flight cache keyed on the persisted version.\n\t\t// Coalesce concurrent cold readers via the lock and read the\n\t\t// published value; never await another request's in-flight promise\n\t\t// (a cancelled owner would otherwise strand every later byline\n\t\t// hydration on the isolate). The fetch is anchored so a cancelled\n\t\t// originator still drives it to completion and populates the cache.\n\t\treturn initWithLock<BylineFieldDefinition[]>(\n\t\t\tholder.lock,\n\t\t\t() => (holder.hasValue && holder.cachedVersion === version ? holder.value : null),\n\t\t\t(isCurrentClaim) =>\n\t\t\t\t(async () => {\n\t\t\t\t\tconst defs = await new BylineSchemaRegistry(db).listFields();\n\t\t\t\t\t// Publish only while still the current claim, and never\n\t\t\t\t\t// regress over a newer version a concurrent reader stored.\n\t\t\t\t\tif (isCurrentClaim() && version >= holder.cachedVersion) {\n\t\t\t\t\t\tholder.value = defs;\n\t\t\t\t\t\tholder.hasValue = true;\n\t\t\t\t\t\tholder.cachedVersion = version;\n\t\t\t\t\t}\n\t\t\t\t\treturn defs;\n\t\t\t\t})(),\n\t\t\t{ deadlineMs: reclaimDeadlineMs, anchor: (promise) => after(() => promise) },\n\t\t);\n\t});\n}\n\n/**\n * Test/internal helper: clear the per-isolate cache. Useful for unit\n * tests that mutate the registry directly and need to force a refetch\n * without going through the full version-bump path.\n *\n * Production code paths should rely on the version counter for\n * invalidation — calling this from a write path would bypass the\n * coordination that lets other isolates see the change.\n */\nexport function resetBylineFieldDefsCacheForTests(): void {\n\tholder.value = null;\n\tholder.hasValue = false;\n\tholder.cachedVersion = -1;\n\tholder.lock.ownerStartedAt = null;\n\tholder.lock.generation = 0;\n\treclaimDeadlineMs = 10_000;\n}\n\n/**\n * Test-only: shorten the single-flight reclaim window so a \"stranded\n * owner\" scenario can be exercised without waiting out the production\n * deadline. Reset by `resetBylineFieldDefsCacheForTests`.\n *\n * @internal\n */\nexport function setBylineFieldDefsReclaimDeadlineForTests(ms: number): void {\n\treclaimDeadlineMs = ms;\n}\n"],"mappings":";;;;;;;;;AA2EA,MAAM,aAAa,OAAO,IAAI,2BAA2B;AACzD,MAAM,IAAI;AACV,MAAM,SAEJ,EAAE,sBACI;CACN,MAAM,IAAqB;EAC1B,OAAO;EACP,UAAU;EACV,eAAe;EACf,MAAM,gBAAgB;EACtB;AACD,GAAE,cAAc;AAChB,QAAO;IACJ;AAEL,MAAM,4BAA4B;AAClC,MAAM,gCAAgC;;;;;;;;;AAUtC,IAAI,oBAAoB;;;;;;AAOxB,eAAe,uBAAuB,IAAuC;AAC5E,QAAO,cAAc,iCAAiC,IAAI,qBAAqB,GAAG,CAAC,YAAY,CAAC;;;;;;;;;;;;;;;AAgBjG,eAAsB,mBAAmB,IAAwD;CAChG,MAAM,WAAW,mBAAmB,EAAE,iBAAiB;CACvD,MAAM,UAAU,MAAM,uBAAuB,GAAG;CAChD,MAAM,QAAQ,UAAU,MAAM;AAC9B,QAAO,cAAc,GAAG,gCAAgC,WAAW,YAAY;AAC9E,MAAI,YAAY,MACf,QAAO,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAQjD,SAAO,aACN,OAAO,YACA,OAAO,YAAY,OAAO,kBAAkB,UAAU,OAAO,QAAQ,OAC3E,oBACC,YAAY;GACZ,MAAM,OAAO,MAAM,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAG5D,OAAI,gBAAgB,IAAI,WAAW,OAAO,eAAe;AACxD,WAAO,QAAQ;AACf,WAAO,WAAW;AAClB,WAAO,gBAAgB;;AAExB,UAAO;MACJ,EACL;GAAE,YAAY;GAAmB,SAAS,YAAY,YAAY,QAAQ;GAAE,CAC5E;GACA"}
@@ -1,6 +1,6 @@
1
- import { o as __exportAll } from "./runner-BdeLEgad.mjs";
1
+ import { o as __exportAll } from "./runner-BsI18UgP.mjs";
2
2
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
3
- import { d as tableExists, s as isSqlite } from "./dialect-helpers-BtOwo2us.mjs";
3
+ import { c as isSqlite, f as tableExists } from "./dialect-helpers-DFwyWjTM.mjs";
4
4
  import { sql } from "kysely";
5
5
 
6
6
  //#region src/search/fts-manager.ts
@@ -360,4 +360,4 @@ var FTSManager = class {
360
360
 
361
361
  //#endregion
362
362
  export { fts_manager_exports as n, FTSManager as t };
363
- //# sourceMappingURL=fts-manager-hyCU9OOp.mjs.map
363
+ //# sourceMappingURL=fts-manager-vncsZIJm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fts-manager-hyCU9OOp.mjs","names":["dialectTableExists"],"sources":["../src/search/fts-manager.ts"],"sourcesContent":["/**\n * FTS5 Manager\n *\n * Manages FTS5 virtual tables and triggers for search indexing.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { isSqlite, tableExists as dialectTableExists } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { SearchConfig } from \"./types.js\";\n\n/**\n * FTS5 Manager\n *\n * Handles creation, deletion, and management of FTS5 virtual tables\n * for full-text search on content collections.\n */\nexport class FTSManager {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Validate a collection slug and its searchable field names.\n\t * Must be called before any raw SQL interpolation.\n\t */\n\tprivate validateInputs(collectionSlug: string, searchableFields?: string[]): void {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\tif (searchableFields) {\n\t\t\tfor (const field of searchableFields) {\n\t\t\t\tvalidateIdentifier(field, \"searchable field name\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the FTS table name for a collection\n\t * Uses _emdash_ prefix to clearly mark as internal/system table\n\t */\n\tgetFtsTableName(collectionSlug: string): string {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\treturn `_emdash_fts_${collectionSlug}`;\n\t}\n\n\t/**\n\t * Get the content table name for a collection\n\t */\n\tgetContentTableName(collectionSlug: string): string {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\treturn `ec_${collectionSlug}`;\n\t}\n\n\t/**\n\t * Check if an FTS table exists for a collection\n\t */\n\tasync ftsTableExists(collectionSlug: string): Promise<boolean> {\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\treturn dialectTableExists(this.db, ftsTable);\n\t}\n\n\t/**\n\t * Create an FTS5 virtual table for a collection.\n\t * FTS5 is SQLite-only; on other dialects this is a no-op.\n\t *\n\t * @param collectionSlug - The collection slug\n\t * @param searchableFields - Array of field names to index\n\t * @param weights - Optional field weights for ranking\n\t */\n\tasync createFtsTable(\n\t\tcollectionSlug: string,\n\t\tsearchableFields: string[],\n\t\t_weights?: Record<string, number>,\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\n\t\t// Build the column list for FTS5\n\t\t// id and locale are UNINDEXED (used for joining/filtering, not searched)\n\t\tconst columns = [\"id UNINDEXED\", \"locale UNINDEXED\", ...searchableFields].join(\", \");\n\n\t\t// Create the FTS5 virtual table.\n\t\t// `content='<table>'` makes this an *external content* FTS5 table:\n\t\t// the inverted index lives in the FTS shadow tables, but the actual\n\t\t// row data lives in the backing content table. The triggers in\n\t\t// `createTriggers` keep the index in sync; they MUST use the\n\t\t// external-content-safe `'delete'` command (see notes there) to\n\t\t// avoid `SQLITE_CORRUPT_VTAB` on UPDATE/DELETE.\n\t\t// tokenize='porter unicode61' enables stemming (run matches running, ran, etc.)\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE VIRTUAL TABLE IF NOT EXISTS \"${ftsTable}\" USING fts5(\n\t\t\t\t${columns},\n\t\t\t\tcontent='${contentTable}',\n\t\t\t\tcontent_rowid='rowid',\n\t\t\t\ttokenize='porter unicode61'\n\t\t\t)\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Create triggers for automatic sync\n\t\tawait this.createTriggers(collectionSlug, searchableFields);\n\t}\n\n\t/**\n\t * Create triggers to keep FTS table in sync with content table.\n\t *\n\t * The insert and update triggers only add rows to the FTS index when\n\t * `deleted_at IS NULL`. This keeps soft-deleted content out of the\n\t * search index and ensures the FTS row count matches the non-deleted\n\t * content count (which `verifyAndRepairIndex` relies on).\n\t *\n\t * IMPORTANT: The FTS5 virtual table is created with `content='ec_<slug>'`\n\t * which makes it an *external content* FTS5 table. For external-content\n\t * tables, removing a row must use the documented `'delete'` command and\n\t * supply the OLD column values explicitly, e.g.:\n\t *\n\t * INSERT INTO fts(fts, rowid, col1, col2)\n\t * VALUES('delete', OLD.rowid, OLD.col1, OLD.col2);\n\t *\n\t * Using `DELETE FROM fts WHERE rowid = OLD.rowid` is the correct form\n\t * for *contentless* tables but is unsafe for external-content tables:\n\t * FTS5 then reads column values from the backing content table, which\n\t * in an AFTER UPDATE trigger already holds the NEW values. The wrong\n\t * tokens get removed and the inverted index drifts out of sync until\n\t * SQLite raises `SQLITE_CORRUPT_VTAB` on the next mutation. See\n\t * https://www.sqlite.org/fts5.html#external_content_tables.\n\t *\n\t * The UPDATE and DELETE triggers gate the `'delete'` on\n\t * `OLD.deleted_at IS NULL` because the INSERT trigger never indexed\n\t * rows that were already soft-deleted. Issuing `'delete'` for a rowid\n\t * that was never inserted into the FTS index is itself a corruption\n\t * trigger -- FTS5's `'delete'` is not a no-op on missing rowids and\n\t * raises `SQLITE_CORRUPT_VTAB`. Affected paths include restore-from-\n\t * trash (UPDATE where `OLD.deleted_at IS NOT NULL`), permanent-delete\n\t * from trash (DELETE on a soft-deleted row), and any edit on a row\n\t * that's currently in the trash.\n\t */\n\tprivate async createTriggers(collectionSlug: string, searchableFields: string[]): Promise<void> {\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tif (searchableFields.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot create FTS triggers for collection \"${collectionSlug}\": no searchable fields. ` +\n\t\t\t\t\t`Mark at least one field as searchable before enabling search.`,\n\t\t\t);\n\t\t}\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fieldList = searchableFields.join(\", \");\n\t\tconst newFieldList = searchableFields.map((f) => `NEW.${f}`).join(\", \");\n\t\t// `'delete'` takes the FTS5 virtual table name as the first column,\n\t\t// then the rowid being removed, then the OLD value of every column\n\t\t// declared on the FTS5 table (in declaration order: id, locale,\n\t\t// then each searchable field).\n\t\tconst oldFieldList = searchableFields.map((f) => `OLD.${f}`).join(\", \");\n\n\t\t// Insert trigger - only index non-deleted content\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_insert\" \n\t\t\tAFTER INSERT ON \"${contentTable}\" \n\t\t\tWHEN NEW.deleted_at IS NULL\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\t\tVALUES (NEW.rowid, NEW.id, NEW.locale, ${newFieldList});\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Update trigger - remove the old row from the FTS index using the\n\t\t// external-content-safe `'delete'` command (which uses OLD column\n\t\t// values, captured before the row was modified), then re-insert\n\t\t// the new values when the row is still visible.\n\t\t//\n\t\t// `'delete'` is gated on `OLD.deleted_at IS NULL` because rows that\n\t\t// were soft-deleted are not in the FTS index (the INSERT trigger\n\t\t// skips them). Issuing `'delete'` for a missing rowid raises\n\t\t// `SQLITE_CORRUPT_VTAB`, which would break restore-from-trash and\n\t\t// edits to soft-deleted rows.\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_update\" \n\t\t\tAFTER UPDATE ON \"${contentTable}\" \n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(\"${ftsTable}\", rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT 'delete', OLD.rowid, OLD.id, OLD.locale, ${oldFieldList}\n\t\t\t\tWHERE OLD.deleted_at IS NULL;\n\t\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT NEW.rowid, NEW.id, NEW.locale, ${newFieldList}\n\t\t\t\tWHERE NEW.deleted_at IS NULL;\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Delete trigger - same external-content-safe `'delete'` form,\n\t\t// gated on `OLD.deleted_at IS NULL` for the same reason as the\n\t\t// UPDATE trigger: permanent-delete from trash hits a row whose\n\t\t// `deleted_at` is already set and which was never indexed.\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_delete\" \n\t\t\tAFTER DELETE ON \"${contentTable}\" \n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(\"${ftsTable}\", rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT 'delete', OLD.rowid, OLD.id, OLD.locale, ${oldFieldList}\n\t\t\t\tWHERE OLD.deleted_at IS NULL;\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\t}\n\n\t/**\n\t * Drop triggers for a collection\n\t */\n\tprivate async dropTriggers(collectionSlug: string): Promise<void> {\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_insert\"`).execute(this.db);\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_update\"`).execute(this.db);\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_delete\"`).execute(this.db);\n\t}\n\n\t/**\n\t * Drop the FTS table and triggers for a collection\n\t */\n\tasync dropFtsTable(collectionSlug: string): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\n\t\t// Drop triggers first\n\t\tawait this.dropTriggers(collectionSlug);\n\n\t\t// Drop the FTS table\n\t\tawait sql.raw(`DROP TABLE IF EXISTS \"${ftsTable}\"`).execute(this.db);\n\t}\n\n\t/**\n\t * Rebuild the FTS index for a collection\n\t *\n\t * This is useful after bulk imports or if the index gets out of sync.\n\t */\n\tasync rebuildIndex(\n\t\tcollectionSlug: string,\n\t\tsearchableFields: string[],\n\t\tweights?: Record<string, number>,\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\t// Drop existing table and triggers\n\t\tawait this.dropFtsTable(collectionSlug);\n\n\t\t// Recreate table and triggers\n\t\tawait this.createFtsTable(collectionSlug, searchableFields, weights);\n\n\t\t// Populate from existing content\n\t\tawait this.populateFromContent(collectionSlug, searchableFields);\n\t}\n\n\t/**\n\t * Populate the FTS table from existing content\n\t */\n\tasync populateFromContent(collectionSlug: string, searchableFields: string[]): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fieldList = searchableFields.join(\", \");\n\n\t\t// Insert all existing content into FTS table\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\tSELECT rowid, id, locale, ${fieldList} FROM \"${contentTable}\"\n\t\t\tWHERE deleted_at IS NULL\n\t\t`)\n\t\t\t.execute(this.db);\n\t}\n\n\t/**\n\t * Get the search configuration for a collection\n\t */\n\tasync getSearchConfig(collectionSlug: string): Promise<SearchConfig | null> {\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"search_config\")\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!result?.search_config) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(result.search_config);\n\t\t\tif (\n\t\t\t\ttypeof parsed !== \"object\" ||\n\t\t\t\tparsed === null ||\n\t\t\t\t!(\"enabled\" in parsed) ||\n\t\t\t\ttypeof parsed.enabled !== \"boolean\"\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst config: SearchConfig = { enabled: parsed.enabled };\n\t\t\tif (\"weights\" in parsed && typeof parsed.weights === \"object\" && parsed.weights !== null) {\n\t\t\t\t// weights is a JSON-parsed object — safe to treat as Record<string, number>\n\t\t\t\tconst weights: Record<string, number> = {};\n\t\t\t\tfor (const [k, v] of Object.entries(parsed.weights)) {\n\t\t\t\t\tif (typeof v === \"number\") {\n\t\t\t\t\t\tweights[k] = v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconfig.weights = weights;\n\t\t\t}\n\t\t\treturn config;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Update the search configuration for a collection\n\t */\n\tasync setSearchConfig(collectionSlug: string, config: SearchConfig): Promise<void> {\n\t\tawait this.db\n\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t.set({ search_config: JSON.stringify(config) })\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Get searchable fields for a collection\n\t */\n\tasync getSearchableFields(collectionSlug: string): Promise<string[]> {\n\t\tconst collection = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!collection) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst fields = await this.db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t.where(\"searchable\", \"=\", 1)\n\t\t\t.execute();\n\n\t\treturn fields.map((f) => f.slug);\n\t}\n\n\t/**\n\t * Whether a collection has a user-defined `title` field.\n\t *\n\t * `title` is not a system column on `ec_*` tables -- it exists only when a\n\t * collection defines a field with slug `title`. Search and suggestion SQL\n\t * that selects `c.title` must check this first; otherwise collections\n\t * without a title field raise \"no such column: c.title\" (#1178).\n\t */\n\tasync hasTitleColumn(collectionSlug: string): Promise<boolean> {\n\t\tconst withTitle = await this.getCollectionsWithTitleColumn([collectionSlug]);\n\t\treturn withTitle.has(collectionSlug);\n\t}\n\n\t/**\n\t * Bulk variant of `hasTitleColumn()`: which of the given collections have\n\t * a user-defined `title` field. One query instead of one `hasTitleColumn`\n\t * round-trip pair per collection -- callers that check this once per\n\t * collection in a loop (multi-collection search, suggestions) should use\n\t * this instead (AGENTS.md: \"one query beats two\").\n\t */\n\tasync getCollectionsWithTitleColumn(collectionSlugs: string[]): Promise<Set<string>> {\n\t\tif (collectionSlugs.length === 0) return new Set();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t\t.select([\"c.slug as collection_slug\"])\n\t\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t\t.execute();\n\n\t\tconst withTitle = new Set(rows.map((r) => r.collection_slug));\n\t\treturn new Set(collectionSlugs.filter((slug) => withTitle.has(slug)));\n\t}\n\n\t/**\n\t * Enable search for a collection.\n\t *\n\t * Uses rebuildIndex to ensure a clean state -- drop any existing FTS\n\t * table/triggers, recreate them, and populate from content. This avoids\n\t * duplicate rows when triggers have already populated the index (e.g.\n\t * during seeding where content is inserted before search is enabled).\n\t */\n\tasync enableSearch(\n\t\tcollectionSlug: string,\n\t\toptions?: { weights?: Record<string, number> },\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) {\n\t\t\tthrow new Error(\"Full-text search is only available with SQLite databases\");\n\t\t}\n\t\t// Get searchable fields\n\t\tconst searchableFields = await this.getSearchableFields(collectionSlug);\n\n\t\tif (searchableFields.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`No searchable fields defined for collection \"${collectionSlug}\". ` +\n\t\t\t\t\t`Mark at least one field as searchable before enabling search.`,\n\t\t\t);\n\t\t}\n\n\t\t// Rebuild from scratch to ensure clean state (no duplicate rows)\n\t\tawait this.rebuildIndex(collectionSlug, searchableFields, options?.weights);\n\n\t\t// Update search config\n\t\tawait this.setSearchConfig(collectionSlug, {\n\t\t\tenabled: true,\n\t\t\tweights: options?.weights,\n\t\t});\n\t}\n\n\t/**\n\t * Disable search for a collection\n\t *\n\t * Drops the FTS table and triggers.\n\t */\n\tasync disableSearch(collectionSlug: string): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tawait this.dropFtsTable(collectionSlug);\n\t\tconst existing = await this.getSearchConfig(collectionSlug);\n\t\tawait this.setSearchConfig(collectionSlug, { enabled: false, weights: existing?.weights });\n\t}\n\n\t/**\n\t * Get index statistics for a collection\n\t */\n\tasync getIndexStats(\n\t\tcollectionSlug: string,\n\t): Promise<{ indexed: number; lastRebuilt?: string } | null> {\n\t\tif (!isSqlite(this.db)) return null;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst ftsDocsizeTable = `${ftsTable}_docsize`;\n\n\t\t// Check if table exists\n\t\tif (!(await this.ftsTableExists(collectionSlug))) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Count indexed rows\n\t\tconst result = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM \"${sql.raw(ftsDocsizeTable)}\"\n\t\t`.execute(this.db);\n\n\t\treturn {\n\t\t\tindexed: result.rows[0]?.count ?? 0,\n\t\t};\n\t}\n\n\t/**\n\t * Verify FTS index integrity and rebuild if drift is detected.\n\t *\n\t * Cheap belt-and-braces check, run lazily on the first search request\n\t * per isolate. The expensive cases (corrupted indexes from pre-fix\n\t * EmDash versions, broken legacy triggers) are handled at boot time by\n\t * migration `039_fix_fts5_triggers`, not here. This routine sticks to:\n\t *\n\t * 1. FTS table missing while config says search is enabled -> rebuild.\n\t * 2. Row count mismatch between content table and FTS docsize -> rebuild.\n\t *\n\t * Returns true if the index was rebuilt, false if it was healthy.\n\t */\n\tasync verifyAndRepairIndex(collectionSlug: string): Promise<boolean> {\n\t\tif (!isSqlite(this.db)) return false;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst ftsDocsizeTable = `${ftsTable}_docsize`;\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fields = await this.getSearchableFields(collectionSlug);\n\t\tconst config = await this.getSearchConfig(collectionSlug);\n\n\t\tif (!(await this.ftsTableExists(collectionSlug))) {\n\t\t\tif (!config?.enabled || fields.length === 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconsole.warn(`FTS index for \"${collectionSlug}\" is missing. Rebuilding.`);\n\t\t\tawait this.rebuildIndex(collectionSlug, fields, config.weights);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Row count parity check. For external-content FTS tables, COUNT(*)\n\t\t// on the virtual table is answered from the backing content table\n\t\t// (including soft-deleted rows), so we use the docsize shadow table\n\t\t// which tracks rows actually present in the full-text index.\n\t\tconst contentCount = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM ${sql.ref(contentTable)}\n\t\t\tWHERE deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tconst ftsCount = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM \"${sql.raw(ftsDocsizeTable)}\"\n\t\t`.execute(this.db);\n\n\t\tconst contentRows = contentCount.rows[0]?.count ?? 0;\n\t\tconst ftsRows = ftsCount.rows[0]?.count ?? 0;\n\n\t\tif (contentRows !== ftsRows) {\n\t\t\tconsole.warn(\n\t\t\t\t`FTS index for \"${collectionSlug}\" has ${ftsRows} rows but content table has ${contentRows}. Rebuilding.`,\n\t\t\t);\n\t\t\tif (fields.length > 0) {\n\t\t\t\tawait this.rebuildIndex(collectionSlug, fields, config?.weights);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Verify and repair FTS indexes for all search-enabled collections.\n\t *\n\t * Intended to run at startup to auto-heal any corruption from\n\t * previous process crashes.\n\t */\n\tasync verifyAndRepairAll(): Promise<number> {\n\t\tif (!isSqlite(this.db)) return 0;\n\n\t\tconst collections = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"search_config\", \"is not\", null)\n\t\t\t.execute();\n\n\t\tlet repaired = 0;\n\t\tfor (const { slug } of collections) {\n\t\t\tconst config = await this.getSearchConfig(slug);\n\t\t\tif (!config?.enabled) continue;\n\n\t\t\ttry {\n\t\t\t\tconst wasRepaired = await this.verifyAndRepairIndex(slug);\n\t\t\t\tif (wasRepaired) repaired++;\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(`Failed to verify/repair FTS index for \"${slug}\":`, error);\n\t\t\t}\n\t\t}\n\n\t\treturn repaired;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAa,aAAb,MAAwB;CACvB,YAAY,AAAQ,IAAsB;EAAtB;;;;;;CAMpB,AAAQ,eAAe,gBAAwB,kBAAmC;AACjF,qBAAmB,gBAAgB,kBAAkB;AACrD,MAAI,iBACH,MAAK,MAAM,SAAS,iBACnB,oBAAmB,OAAO,wBAAwB;;;;;;CASrD,gBAAgB,gBAAgC;AAC/C,qBAAmB,gBAAgB,kBAAkB;AACrD,SAAO,eAAe;;;;;CAMvB,oBAAoB,gBAAgC;AACnD,qBAAmB,gBAAgB,kBAAkB;AACrD,SAAO,MAAM;;;;;CAMd,MAAM,eAAe,gBAA0C;EAC9D,MAAM,WAAW,KAAK,g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KAAK,GAC7B,WAAW,sBAAsB,CACjC,OAAO,OAAO,CACd,MAAM,iBAAiB,UAAU,KAAK,CACtC,SAAS;EAEX,IAAI,WAAW;AACf,OAAK,MAAM,EAAE,UAAU,aAAa;AAEnC,OAAI,EADW,MAAM,KAAK,gBAAgB,KAAK,GAClC,QAAS;AAEtB,OAAI;AAEH,QADoB,MAAM,KAAK,qBAAqB,KAAK,CACxC;YACT,OAAO;AACf,YAAQ,MAAM,0CAA0C,KAAK,KAAK,MAAM;;;AAI1E,SAAO"}
1
+ {"version":3,"file":"fts-manager-vncsZIJm.mjs","names":["dialectTableExists"],"sources":["../src/search/fts-manager.ts"],"sourcesContent":["/**\n * FTS5 Manager\n *\n * Manages FTS5 virtual tables and triggers for search indexing.\n */\n\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { isSqlite, tableExists as dialectTableExists } from \"../database/dialect-helpers.js\";\nimport type { Database } from \"../database/types.js\";\nimport { validateIdentifier } from \"../database/validate.js\";\nimport type { SearchConfig } from \"./types.js\";\n\n/**\n * FTS5 Manager\n *\n * Handles creation, deletion, and management of FTS5 virtual tables\n * for full-text search on content collections.\n */\nexport class FTSManager {\n\tconstructor(private db: Kysely<Database>) {}\n\n\t/**\n\t * Validate a collection slug and its searchable field names.\n\t * Must be called before any raw SQL interpolation.\n\t */\n\tprivate validateInputs(collectionSlug: string, searchableFields?: string[]): void {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\tif (searchableFields) {\n\t\t\tfor (const field of searchableFields) {\n\t\t\t\tvalidateIdentifier(field, \"searchable field name\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the FTS table name for a collection\n\t * Uses _emdash_ prefix to clearly mark as internal/system table\n\t */\n\tgetFtsTableName(collectionSlug: string): string {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\treturn `_emdash_fts_${collectionSlug}`;\n\t}\n\n\t/**\n\t * Get the content table name for a collection\n\t */\n\tgetContentTableName(collectionSlug: string): string {\n\t\tvalidateIdentifier(collectionSlug, \"collection slug\");\n\t\treturn `ec_${collectionSlug}`;\n\t}\n\n\t/**\n\t * Check if an FTS table exists for a collection\n\t */\n\tasync ftsTableExists(collectionSlug: string): Promise<boolean> {\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\treturn dialectTableExists(this.db, ftsTable);\n\t}\n\n\t/**\n\t * Create an FTS5 virtual table for a collection.\n\t * FTS5 is SQLite-only; on other dialects this is a no-op.\n\t *\n\t * @param collectionSlug - The collection slug\n\t * @param searchableFields - Array of field names to index\n\t * @param weights - Optional field weights for ranking\n\t */\n\tasync createFtsTable(\n\t\tcollectionSlug: string,\n\t\tsearchableFields: string[],\n\t\t_weights?: Record<string, number>,\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\n\t\t// Build the column list for FTS5\n\t\t// id and locale are UNINDEXED (used for joining/filtering, not searched)\n\t\tconst columns = [\"id UNINDEXED\", \"locale UNINDEXED\", ...searchableFields].join(\", \");\n\n\t\t// Create the FTS5 virtual table.\n\t\t// `content='<table>'` makes this an *external content* FTS5 table:\n\t\t// the inverted index lives in the FTS shadow tables, but the actual\n\t\t// row data lives in the backing content table. The triggers in\n\t\t// `createTriggers` keep the index in sync; they MUST use the\n\t\t// external-content-safe `'delete'` command (see notes there) to\n\t\t// avoid `SQLITE_CORRUPT_VTAB` on UPDATE/DELETE.\n\t\t// tokenize='porter unicode61' enables stemming (run matches running, ran, etc.)\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE VIRTUAL TABLE IF NOT EXISTS \"${ftsTable}\" USING fts5(\n\t\t\t\t${columns},\n\t\t\t\tcontent='${contentTable}',\n\t\t\t\tcontent_rowid='rowid',\n\t\t\t\ttokenize='porter unicode61'\n\t\t\t)\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Create triggers for automatic sync\n\t\tawait this.createTriggers(collectionSlug, searchableFields);\n\t}\n\n\t/**\n\t * Create triggers to keep FTS table in sync with content table.\n\t *\n\t * The insert and update triggers only add rows to the FTS index when\n\t * `deleted_at IS NULL`. This keeps soft-deleted content out of the\n\t * search index and ensures the FTS row count matches the non-deleted\n\t * content count (which `verifyAndRepairIndex` relies on).\n\t *\n\t * IMPORTANT: The FTS5 virtual table is created with `content='ec_<slug>'`\n\t * which makes it an *external content* FTS5 table. For external-content\n\t * tables, removing a row must use the documented `'delete'` command and\n\t * supply the OLD column values explicitly, e.g.:\n\t *\n\t * INSERT INTO fts(fts, rowid, col1, col2)\n\t * VALUES('delete', OLD.rowid, OLD.col1, OLD.col2);\n\t *\n\t * Using `DELETE FROM fts WHERE rowid = OLD.rowid` is the correct form\n\t * for *contentless* tables but is unsafe for external-content tables:\n\t * FTS5 then reads column values from the backing content table, which\n\t * in an AFTER UPDATE trigger already holds the NEW values. The wrong\n\t * tokens get removed and the inverted index drifts out of sync until\n\t * SQLite raises `SQLITE_CORRUPT_VTAB` on the next mutation. See\n\t * https://www.sqlite.org/fts5.html#external_content_tables.\n\t *\n\t * The UPDATE and DELETE triggers gate the `'delete'` on\n\t * `OLD.deleted_at IS NULL` because the INSERT trigger never indexed\n\t * rows that were already soft-deleted. Issuing `'delete'` for a rowid\n\t * that was never inserted into the FTS index is itself a corruption\n\t * trigger -- FTS5's `'delete'` is not a no-op on missing rowids and\n\t * raises `SQLITE_CORRUPT_VTAB`. Affected paths include restore-from-\n\t * trash (UPDATE where `OLD.deleted_at IS NOT NULL`), permanent-delete\n\t * from trash (DELETE on a soft-deleted row), and any edit on a row\n\t * that's currently in the trash.\n\t */\n\tprivate async createTriggers(collectionSlug: string, searchableFields: string[]): Promise<void> {\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tif (searchableFields.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot create FTS triggers for collection \"${collectionSlug}\": no searchable fields. ` +\n\t\t\t\t\t`Mark at least one field as searchable before enabling search.`,\n\t\t\t);\n\t\t}\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fieldList = searchableFields.join(\", \");\n\t\tconst newFieldList = searchableFields.map((f) => `NEW.${f}`).join(\", \");\n\t\t// `'delete'` takes the FTS5 virtual table name as the first column,\n\t\t// then the rowid being removed, then the OLD value of every column\n\t\t// declared on the FTS5 table (in declaration order: id, locale,\n\t\t// then each searchable field).\n\t\tconst oldFieldList = searchableFields.map((f) => `OLD.${f}`).join(\", \");\n\n\t\t// Insert trigger - only index non-deleted content\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_insert\" \n\t\t\tAFTER INSERT ON \"${contentTable}\" \n\t\t\tWHEN NEW.deleted_at IS NULL\n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\t\tVALUES (NEW.rowid, NEW.id, NEW.locale, ${newFieldList});\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Update trigger - remove the old row from the FTS index using the\n\t\t// external-content-safe `'delete'` command (which uses OLD column\n\t\t// values, captured before the row was modified), then re-insert\n\t\t// the new values when the row is still visible.\n\t\t//\n\t\t// `'delete'` is gated on `OLD.deleted_at IS NULL` because rows that\n\t\t// were soft-deleted are not in the FTS index (the INSERT trigger\n\t\t// skips them). Issuing `'delete'` for a missing rowid raises\n\t\t// `SQLITE_CORRUPT_VTAB`, which would break restore-from-trash and\n\t\t// edits to soft-deleted rows.\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_update\" \n\t\t\tAFTER UPDATE ON \"${contentTable}\" \n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(\"${ftsTable}\", rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT 'delete', OLD.rowid, OLD.id, OLD.locale, ${oldFieldList}\n\t\t\t\tWHERE OLD.deleted_at IS NULL;\n\t\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT NEW.rowid, NEW.id, NEW.locale, ${newFieldList}\n\t\t\t\tWHERE NEW.deleted_at IS NULL;\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\n\t\t// Delete trigger - same external-content-safe `'delete'` form,\n\t\t// gated on `OLD.deleted_at IS NULL` for the same reason as the\n\t\t// UPDATE trigger: permanent-delete from trash hits a row whose\n\t\t// `deleted_at` is already set and which was never indexed.\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tCREATE TRIGGER IF NOT EXISTS \"${ftsTable}_delete\" \n\t\t\tAFTER DELETE ON \"${contentTable}\" \n\t\t\tBEGIN\n\t\t\t\tINSERT INTO \"${ftsTable}\"(\"${ftsTable}\", rowid, id, locale, ${fieldList})\n\t\t\t\tSELECT 'delete', OLD.rowid, OLD.id, OLD.locale, ${oldFieldList}\n\t\t\t\tWHERE OLD.deleted_at IS NULL;\n\t\t\tEND\n\t\t`)\n\t\t\t.execute(this.db);\n\t}\n\n\t/**\n\t * Drop triggers for a collection\n\t */\n\tprivate async dropTriggers(collectionSlug: string): Promise<void> {\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_insert\"`).execute(this.db);\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_update\"`).execute(this.db);\n\t\tawait sql.raw(`DROP TRIGGER IF EXISTS \"${ftsTable}_delete\"`).execute(this.db);\n\t}\n\n\t/**\n\t * Drop the FTS table and triggers for a collection\n\t */\n\tasync dropFtsTable(collectionSlug: string): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\n\t\t// Drop triggers first\n\t\tawait this.dropTriggers(collectionSlug);\n\n\t\t// Drop the FTS table\n\t\tawait sql.raw(`DROP TABLE IF EXISTS \"${ftsTable}\"`).execute(this.db);\n\t}\n\n\t/**\n\t * Rebuild the FTS index for a collection\n\t *\n\t * This is useful after bulk imports or if the index gets out of sync.\n\t */\n\tasync rebuildIndex(\n\t\tcollectionSlug: string,\n\t\tsearchableFields: string[],\n\t\tweights?: Record<string, number>,\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\t// Drop existing table and triggers\n\t\tawait this.dropFtsTable(collectionSlug);\n\n\t\t// Recreate table and triggers\n\t\tawait this.createFtsTable(collectionSlug, searchableFields, weights);\n\n\t\t// Populate from existing content\n\t\tawait this.populateFromContent(collectionSlug, searchableFields);\n\t}\n\n\t/**\n\t * Populate the FTS table from existing content\n\t */\n\tasync populateFromContent(collectionSlug: string, searchableFields: string[]): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tthis.validateInputs(collectionSlug, searchableFields);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fieldList = searchableFields.join(\", \");\n\n\t\t// Insert all existing content into FTS table\n\t\tawait sql\n\t\t\t.raw(`\n\t\t\tINSERT INTO \"${ftsTable}\"(rowid, id, locale, ${fieldList})\n\t\t\tSELECT rowid, id, locale, ${fieldList} FROM \"${contentTable}\"\n\t\t\tWHERE deleted_at IS NULL\n\t\t`)\n\t\t\t.execute(this.db);\n\t}\n\n\t/**\n\t * Get the search configuration for a collection\n\t */\n\tasync getSearchConfig(collectionSlug: string): Promise<SearchConfig | null> {\n\t\tconst result = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"search_config\")\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!result?.search_config) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(result.search_config);\n\t\t\tif (\n\t\t\t\ttypeof parsed !== \"object\" ||\n\t\t\t\tparsed === null ||\n\t\t\t\t!(\"enabled\" in parsed) ||\n\t\t\t\ttypeof parsed.enabled !== \"boolean\"\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst config: SearchConfig = { enabled: parsed.enabled };\n\t\t\tif (\"weights\" in parsed && typeof parsed.weights === \"object\" && parsed.weights !== null) {\n\t\t\t\t// weights is a JSON-parsed object — safe to treat as Record<string, number>\n\t\t\t\tconst weights: Record<string, number> = {};\n\t\t\t\tfor (const [k, v] of Object.entries(parsed.weights)) {\n\t\t\t\t\tif (typeof v === \"number\") {\n\t\t\t\t\t\tweights[k] = v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconfig.weights = weights;\n\t\t\t}\n\t\t\treturn config;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Update the search configuration for a collection\n\t */\n\tasync setSearchConfig(collectionSlug: string, config: SearchConfig): Promise<void> {\n\t\tawait this.db\n\t\t\t.updateTable(\"_emdash_collections\")\n\t\t\t.set({ search_config: JSON.stringify(config) })\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.execute();\n\t}\n\n\t/**\n\t * Get searchable fields for a collection\n\t */\n\tasync getSearchableFields(collectionSlug: string): Promise<string[]> {\n\t\tconst collection = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"id\")\n\t\t\t.where(\"slug\", \"=\", collectionSlug)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!collection) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst fields = await this.db\n\t\t\t.selectFrom(\"_emdash_fields\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"collection_id\", \"=\", collection.id)\n\t\t\t.where(\"searchable\", \"=\", 1)\n\t\t\t.execute();\n\n\t\treturn fields.map((f) => f.slug);\n\t}\n\n\t/**\n\t * Whether a collection has a user-defined `title` field.\n\t *\n\t * `title` is not a system column on `ec_*` tables -- it exists only when a\n\t * collection defines a field with slug `title`. Search and suggestion SQL\n\t * that selects `c.title` must check this first; otherwise collections\n\t * without a title field raise \"no such column: c.title\" (#1178).\n\t */\n\tasync hasTitleColumn(collectionSlug: string): Promise<boolean> {\n\t\tconst withTitle = await this.getCollectionsWithTitleColumn([collectionSlug]);\n\t\treturn withTitle.has(collectionSlug);\n\t}\n\n\t/**\n\t * Bulk variant of `hasTitleColumn()`: which of the given collections have\n\t * a user-defined `title` field. One query instead of one `hasTitleColumn`\n\t * round-trip pair per collection -- callers that check this once per\n\t * collection in a loop (multi-collection search, suggestions) should use\n\t * this instead (AGENTS.md: \"one query beats two\").\n\t */\n\tasync getCollectionsWithTitleColumn(collectionSlugs: string[]): Promise<Set<string>> {\n\t\tif (collectionSlugs.length === 0) return new Set();\n\n\t\tconst rows = await this.db\n\t\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t\t.select([\"c.slug as collection_slug\"])\n\t\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t\t.execute();\n\n\t\tconst withTitle = new Set(rows.map((r) => r.collection_slug));\n\t\treturn new Set(collectionSlugs.filter((slug) => withTitle.has(slug)));\n\t}\n\n\t/**\n\t * Enable search for a collection.\n\t *\n\t * Uses rebuildIndex to ensure a clean state -- drop any existing FTS\n\t * table/triggers, recreate them, and populate from content. This avoids\n\t * duplicate rows when triggers have already populated the index (e.g.\n\t * during seeding where content is inserted before search is enabled).\n\t */\n\tasync enableSearch(\n\t\tcollectionSlug: string,\n\t\toptions?: { weights?: Record<string, number> },\n\t): Promise<void> {\n\t\tif (!isSqlite(this.db)) {\n\t\t\tthrow new Error(\"Full-text search is only available with SQLite databases\");\n\t\t}\n\t\t// Get searchable fields\n\t\tconst searchableFields = await this.getSearchableFields(collectionSlug);\n\n\t\tif (searchableFields.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`No searchable fields defined for collection \"${collectionSlug}\". ` +\n\t\t\t\t\t`Mark at least one field as searchable before enabling search.`,\n\t\t\t);\n\t\t}\n\n\t\t// Rebuild from scratch to ensure clean state (no duplicate rows)\n\t\tawait this.rebuildIndex(collectionSlug, searchableFields, options?.weights);\n\n\t\t// Update search config\n\t\tawait this.setSearchConfig(collectionSlug, {\n\t\t\tenabled: true,\n\t\t\tweights: options?.weights,\n\t\t});\n\t}\n\n\t/**\n\t * Disable search for a collection\n\t *\n\t * Drops the FTS table and triggers.\n\t */\n\tasync disableSearch(collectionSlug: string): Promise<void> {\n\t\tif (!isSqlite(this.db)) return;\n\t\tawait this.dropFtsTable(collectionSlug);\n\t\tconst existing = await this.getSearchConfig(collectionSlug);\n\t\tawait this.setSearchConfig(collectionSlug, { enabled: false, weights: existing?.weights });\n\t}\n\n\t/**\n\t * Get index statistics for a collection\n\t */\n\tasync getIndexStats(\n\t\tcollectionSlug: string,\n\t): Promise<{ indexed: number; lastRebuilt?: string } | null> {\n\t\tif (!isSqlite(this.db)) return null;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst ftsDocsizeTable = `${ftsTable}_docsize`;\n\n\t\t// Check if table exists\n\t\tif (!(await this.ftsTableExists(collectionSlug))) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Count indexed rows\n\t\tconst result = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM \"${sql.raw(ftsDocsizeTable)}\"\n\t\t`.execute(this.db);\n\n\t\treturn {\n\t\t\tindexed: result.rows[0]?.count ?? 0,\n\t\t};\n\t}\n\n\t/**\n\t * Verify FTS index integrity and rebuild if drift is detected.\n\t *\n\t * Cheap belt-and-braces check, run lazily on the first search request\n\t * per isolate. The expensive cases (corrupted indexes from pre-fix\n\t * EmDash versions, broken legacy triggers) are handled at boot time by\n\t * migration `039_fix_fts5_triggers`, not here. This routine sticks to:\n\t *\n\t * 1. FTS table missing while config says search is enabled -> rebuild.\n\t * 2. Row count mismatch between content table and FTS docsize -> rebuild.\n\t *\n\t * Returns true if the index was rebuilt, false if it was healthy.\n\t */\n\tasync verifyAndRepairIndex(collectionSlug: string): Promise<boolean> {\n\t\tif (!isSqlite(this.db)) return false;\n\t\tthis.validateInputs(collectionSlug);\n\t\tconst ftsTable = this.getFtsTableName(collectionSlug);\n\t\tconst ftsDocsizeTable = `${ftsTable}_docsize`;\n\t\tconst contentTable = this.getContentTableName(collectionSlug);\n\t\tconst fields = await this.getSearchableFields(collectionSlug);\n\t\tconst config = await this.getSearchConfig(collectionSlug);\n\n\t\tif (!(await this.ftsTableExists(collectionSlug))) {\n\t\t\tif (!config?.enabled || fields.length === 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconsole.warn(`FTS index for \"${collectionSlug}\" is missing. Rebuilding.`);\n\t\t\tawait this.rebuildIndex(collectionSlug, fields, config.weights);\n\t\t\treturn true;\n\t\t}\n\n\t\t// Row count parity check. For external-content FTS tables, COUNT(*)\n\t\t// on the virtual table is answered from the backing content table\n\t\t// (including soft-deleted rows), so we use the docsize shadow table\n\t\t// which tracks rows actually present in the full-text index.\n\t\tconst contentCount = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM ${sql.ref(contentTable)}\n\t\t\tWHERE deleted_at IS NULL\n\t\t`.execute(this.db);\n\n\t\tconst ftsCount = await sql<{ count: number }>`\n\t\t\tSELECT COUNT(*) as count FROM \"${sql.raw(ftsDocsizeTable)}\"\n\t\t`.execute(this.db);\n\n\t\tconst contentRows = contentCount.rows[0]?.count ?? 0;\n\t\tconst ftsRows = ftsCount.rows[0]?.count ?? 0;\n\n\t\tif (contentRows !== ftsRows) {\n\t\t\tconsole.warn(\n\t\t\t\t`FTS index for \"${collectionSlug}\" has ${ftsRows} rows but content table has ${contentRows}. Rebuilding.`,\n\t\t\t);\n\t\t\tif (fields.length > 0) {\n\t\t\t\tawait this.rebuildIndex(collectionSlug, fields, config?.weights);\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Verify and repair FTS indexes for all search-enabled collections.\n\t *\n\t * Intended to run at startup to auto-heal any corruption from\n\t * previous process crashes.\n\t */\n\tasync verifyAndRepairAll(): Promise<number> {\n\t\tif (!isSqlite(this.db)) return 0;\n\n\t\tconst collections = await this.db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select(\"slug\")\n\t\t\t.where(\"search_config\", \"is not\", null)\n\t\t\t.execute();\n\n\t\tlet repaired = 0;\n\t\tfor (const { slug } of collections) {\n\t\t\tconst config = await this.getSearchConfig(slug);\n\t\t\tif (!config?.enabled) continue;\n\n\t\t\ttry {\n\t\t\t\tconst wasRepaired = await this.verifyAndRepairIndex(slug);\n\t\t\t\tif (wasRepaired) repaired++;\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(`Failed to verify/repair FTS index for \"${slug}\":`, error);\n\t\t\t}\n\t\t}\n\n\t\treturn repaired;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAa,aAAb,MAAwB;CACvB,YAAY,AAAQ,IAAsB;EAAtB;;;;;;CAMpB,AAAQ,eAAe,gBAAwB,kBAAmC;AACjF,qBAAmB,gBAAgB,kBAAkB;AACrD,MAAI,iBACH,MAAK,MAAM,SAAS,iBACnB,oBAAmB,OAAO,wBAAwB;;;;;;CASrD,gBAAgB,gBAAgC;AAC/C,qBAAmB,gBAAgB,kBAAkB;AACrD,SAAO,eAAe;;;;;CAMvB,oBAAoB,gBAAgC;AACnD,qBAAmB,gBAAgB,kBAAkB;AACrD,SAAO,MAAM;;;;;CAMd,MAAM,eAAe,gBAA0C;EAC9D,MAAM,WAAW,KAAK,gBAAgB,eAAe;AACrD,SAAOA,YAAmB,KAAK,IAAI,SAAS;;;;;;;;;;CAW7C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U,KAAK,CACtC,SAAS;EAEX,IAAI,WAAW;AACf,OAAK,MAAM,EAAE,UAAU,aAAa;AAEnC,OAAI,EADW,MAAM,KAAK,gBAAgB,KAAK,GAClC,QAAS;AAEtB,OAAI;AAEH,QADoB,MAAM,KAAK,qBAAqB,KAAK,CACxC;YACT,OAAO;AACf,YAAQ,MAAM,0CAA0C,KAAK,KAAK,MAAM;;;AAI1E,SAAO"}
@@ -1,4 +1,8 @@
1
1
  //#region src/utils/hash.ts
2
+ const MAX_CONTENT_HASH_BYTES = 8 * 1024 * 1024;
3
+ function formatContentHash(hash) {
4
+ return `sha1:${Array.from(hash, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
5
+ }
2
6
  /**
3
7
  * SHA-256 hash of a string, truncated to 16 hex chars (64 bits).
4
8
  * For cache invalidation / ETags — not for security.
@@ -19,15 +23,15 @@ async function hashString(content) {
19
23
  async function computeContentHash(content) {
20
24
  let buf;
21
25
  if (content instanceof ArrayBuffer) buf = content;
26
+ else if (content.buffer instanceof ArrayBuffer && content.byteOffset === 0 && content.byteLength === content.buffer.byteLength) buf = content.buffer;
22
27
  else {
23
28
  buf = new ArrayBuffer(content.byteLength);
24
29
  new Uint8Array(buf).set(content);
25
30
  }
26
31
  const hashBuffer = await crypto.subtle.digest("SHA-1", buf);
27
- const hashArray = new Uint8Array(hashBuffer);
28
- return `sha1:${Array.from(hashArray, (b) => b.toString(16).padStart(2, "0")).join("")}`;
32
+ return formatContentHash(new Uint8Array(hashBuffer));
29
33
  }
30
34
 
31
35
  //#endregion
32
- export { hashString as n, computeContentHash as t };
33
- //# sourceMappingURL=hash-DFFrkivP.mjs.map
36
+ export { computeContentHash as n, hashString as r, MAX_CONTENT_HASH_BYTES as t };
37
+ //# sourceMappingURL=hash-Cb7U1b5M.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-Cb7U1b5M.mjs","names":[],"sources":["../src/utils/hash.ts"],"sourcesContent":["export const MAX_CONTENT_HASH_BYTES = 8 * 1024 * 1024;\n\nfunction formatContentHash(hash: Uint8Array): string {\n\tconst hashHex = Array.from(hash, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn `sha1:${hashHex}`;\n}\n\n/**\n * SHA-256 hash of a string, truncated to 16 hex chars (64 bits).\n * For cache invalidation / ETags — not for security.\n */\nexport async function hashString(content: string): Promise<string> {\n\tconst buf = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(content));\n\treturn Array.from(new Uint8Array(buf).slice(0, 8), (b) => b.toString(16).padStart(2, \"0\")).join(\n\t\t\"\",\n\t);\n}\n\n/**\n * Compute content hash using Web Crypto API\n *\n * Uses SHA-1 which is the fastest option in SubtleCrypto.\n * SHA-1 is cryptographically weak but fine for content deduplication\n * where we only need to detect identical files, not resist attacks.\n *\n * Returns hex string prefixed with \"sha1:\" for future-proofing\n */\nexport async function computeContentHash(content: Uint8Array | ArrayBuffer): Promise<string> {\n\t// SubtleCrypto.digest() requires BufferSource (ArrayBuffer | ArrayBufferView<ArrayBuffer>).\n\t// Uint8Array.buffer is ArrayBufferLike which may include SharedArrayBuffer in the type system,\n\t// so we ensure we have a plain ArrayBuffer.\n\tlet buf: ArrayBuffer;\n\tif (content instanceof ArrayBuffer) {\n\t\tbuf = content;\n\t} else if (\n\t\tcontent.buffer instanceof ArrayBuffer &&\n\t\tcontent.byteOffset === 0 &&\n\t\tcontent.byteLength === content.buffer.byteLength\n\t) {\n\t\tbuf = content.buffer;\n\t} else {\n\t\tbuf = new ArrayBuffer(content.byteLength);\n\t\tnew Uint8Array(buf).set(content);\n\t}\n\tconst hashBuffer = await crypto.subtle.digest(\"SHA-1\", buf);\n\treturn formatContentHash(new Uint8Array(hashBuffer));\n}\n"],"mappings":";AAAA,MAAa,yBAAyB,IAAI,OAAO;AAEjD,SAAS,kBAAkB,MAA0B;AAEpD,QAAO,QADS,MAAM,KAAK,OAAO,SAAS,KAAK,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;;;;;;AAQxF,eAAsB,WAAW,SAAkC;CAClE,MAAM,MAAM,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,aAAa,CAAC,OAAO,QAAQ,CAAC;AACpF,QAAO,MAAM,KAAK,IAAI,WAAW,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,MAAM,EAAE,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,KAC1F,GACA;;;;;;;;;;;AAYF,eAAsB,mBAAmB,SAAoD;CAI5F,IAAI;AACJ,KAAI,mBAAmB,YACtB,OAAM;UAEN,QAAQ,kBAAkB,eAC1B,QAAQ,eAAe,KACvB,QAAQ,eAAe,QAAQ,OAAO,WAEtC,OAAM,QAAQ;MACR;AACN,QAAM,IAAI,YAAY,QAAQ,WAAW;AACzC,MAAI,WAAW,IAAI,CAAC,IAAI,QAAQ;;CAEjC,MAAM,aAAa,MAAM,OAAO,OAAO,OAAO,SAAS,IAAI;AAC3D,QAAO,kBAAkB,IAAI,WAAW,WAAW,CAAC"}
@@ -1,9 +1,9 @@
1
- import { n as getI18nConfig, r as isI18nEnabled } from "./config-B6b_BobR.mjs";
2
- import { t as ContentRepository } from "./content-BC43pICM.mjs";
1
+ import { n as getI18nConfig, r as isI18nEnabled } from "./config-DyF3OKg_.mjs";
2
+ import { t as ContentRepository } from "./content-CpfKV9QE.mjs";
3
3
  import { r as requestCached } from "./request-cache-BSUptuJR.mjs";
4
- import { n as localizePath, t as interpolateUrlPattern } from "./resolve-DFr4kq72.mjs";
5
- import { n as getCollectionInfoWithDb } from "./query-DdFGHzQF.mjs";
6
- import { a as getSiteSettingsWithDb } from "./settings-C2PaBS49.mjs";
4
+ import { n as localizePath, t as interpolateUrlPattern } from "./resolve-BUvFE0Lr.mjs";
5
+ import { n as getCollectionInfoWithDb } from "./query-1xOcEy18.mjs";
6
+ import { a as getSiteSettingsWithDb } from "./settings-DgKouY2S.mjs";
7
7
 
8
8
  //#region src/seo/hreflang.ts
9
9
  const TRAILING_SLASH_RE = /\/$/;
@@ -39,7 +39,7 @@ async function findNoindexIds(db, collection, ids) {
39
39
  async function getHreflangAlternates(collection, entryId, options = {}) {
40
40
  if (!isI18nEnabled()) return [];
41
41
  return requestCached(`hreflang:${collection}:${entryId}:${options.siteUrl ?? ""}`, async () => {
42
- const { getDb } = await import("./loader-D4rigvjR.mjs").then((n) => n.o);
42
+ const { getDb } = await import("./loader-C1XOLV5b.mjs").then((n) => n.o);
43
43
  return getHreflangAlternatesWithDb(await getDb(), collection, entryId, options);
44
44
  });
45
45
  }
@@ -99,4 +99,4 @@ async function getHreflangAlternatesWithDb(db, collection, entryId, options = {}
99
99
 
100
100
  //#endregion
101
101
  export { getHreflangAlternatesWithDb as n, getHreflangAlternates as t };
102
- //# sourceMappingURL=hreflang-CbYeCzl9.mjs.map
102
+ //# sourceMappingURL=hreflang-Bg-zMpkr.mjs.map