emdash 0.21.0 → 0.23.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 (655) hide show
  1. package/dist/{adapters-BxSmgtbF.d.mts → adapters-DAAjOID4.d.mts} +1 -1
  2. package/dist/{adapters-BxSmgtbF.d.mts.map → adapters-DAAjOID4.d.mts.map} +1 -1
  3. package/dist/after-B1IIdH3Y.mjs +29 -0
  4. package/dist/after-B1IIdH3Y.mjs.map +1 -0
  5. package/dist/{allowed-origins-BqC8cul8.mjs → allowed-origins-D5FxMUo8.mjs} +2 -2
  6. package/dist/{allowed-origins-BqC8cul8.mjs.map → allowed-origins-D5FxMUo8.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -3
  8. package/dist/api/route-utils.mjs +20 -19
  9. package/dist/api/route-utils.mjs.map +1 -1
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +4 -4
  12. package/dist/{api-DxjIV2o8.mjs → api-BQ_yKRdG.mjs} +31 -25
  13. package/dist/api-BQ_yKRdG.mjs.map +1 -0
  14. package/dist/{api-tokens-BFFkB0jB.mjs → api-tokens-D6ppjIVi.mjs} +13 -3
  15. package/dist/api-tokens-D6ppjIVi.mjs.map +1 -0
  16. package/dist/{apply-CLjxheyb.mjs → apply-CWRyxIoO.mjs} +18 -18
  17. package/dist/{apply-CLjxheyb.mjs.map → apply-CWRyxIoO.mjs.map} +1 -1
  18. package/dist/astro/image-endpoint.d.mts +8 -0
  19. package/dist/astro/image-endpoint.d.mts.map +1 -0
  20. package/dist/astro/image-endpoint.mjs +55 -0
  21. package/dist/astro/image-endpoint.mjs.map +1 -0
  22. package/dist/astro/index.d.mts +36 -11
  23. package/dist/astro/index.d.mts.map +1 -1
  24. package/dist/astro/index.mjs +122 -26
  25. package/dist/astro/index.mjs.map +1 -1
  26. package/dist/astro/middleware/auth.d.mts +9 -9
  27. package/dist/astro/middleware/auth.d.mts.map +1 -1
  28. package/dist/astro/middleware/auth.mjs +12 -10
  29. package/dist/astro/middleware/auth.mjs.map +1 -1
  30. package/dist/astro/middleware/redirect.mjs +6 -6
  31. package/dist/astro/middleware/request-context.d.mts.map +1 -1
  32. package/dist/astro/middleware/request-context.mjs +8 -6
  33. package/dist/astro/middleware/request-context.mjs.map +1 -1
  34. package/dist/astro/middleware/setup.mjs +1 -1
  35. package/dist/astro/middleware.d.mts +1 -1
  36. package/dist/astro/middleware.d.mts.map +1 -1
  37. package/dist/astro/middleware.mjs +444 -149
  38. package/dist/astro/middleware.mjs.map +1 -1
  39. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +7 -7
  40. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +7 -7
  41. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +5 -5
  42. package/dist/astro/routes/api/admin/api-tokens/index.mjs +6 -6
  43. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +6 -6
  44. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +10 -10
  45. package/dist/astro/routes/api/admin/byline-fields/index.mjs +10 -10
  46. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +10 -10
  47. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +18 -16
  48. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs.map +1 -1
  49. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +18 -16
  50. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs.map +1 -1
  51. package/dist/astro/routes/api/admin/bylines/index.mjs +18 -16
  52. package/dist/astro/routes/api/admin/bylines/index.mjs.map +1 -1
  53. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +15 -13
  54. package/dist/astro/routes/api/admin/comments/_id_/status.mjs.map +1 -1
  55. package/dist/astro/routes/api/admin/comments/_id_.mjs +8 -6
  56. package/dist/astro/routes/api/admin/comments/_id_.mjs.map +1 -1
  57. package/dist/astro/routes/api/admin/comments/bulk.mjs +12 -10
  58. package/dist/astro/routes/api/admin/comments/bulk.mjs.map +1 -1
  59. package/dist/astro/routes/api/admin/comments/counts.mjs +8 -6
  60. package/dist/astro/routes/api/admin/comments/counts.mjs.map +1 -1
  61. package/dist/astro/routes/api/admin/comments/index.mjs +12 -10
  62. package/dist/astro/routes/api/admin/comments/index.mjs.map +1 -1
  63. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +6 -6
  64. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +5 -5
  65. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +5 -5
  66. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +5 -5
  67. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +41 -39
  68. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  69. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +41 -39
  70. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  71. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +40 -38
  72. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  73. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +40 -38
  74. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  75. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +40 -38
  76. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  77. package/dist/astro/routes/api/admin/plugins/index.mjs +40 -38
  78. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  79. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +4 -4
  80. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +40 -38
  81. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +40 -38
  83. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +40 -38
  85. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +40 -38
  87. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +41 -39
  89. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  90. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +40 -38
  91. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  92. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +41 -39
  93. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  94. package/dist/astro/routes/api/admin/plugins/updates.mjs +40 -38
  95. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  96. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +40 -38
  97. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  98. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +4 -4
  99. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +40 -38
  100. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  101. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +4 -4
  102. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +3 -3
  103. package/dist/astro/routes/api/admin/users/_id_/index.mjs +8 -8
  104. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +5 -5
  105. package/dist/astro/routes/api/admin/users/index.mjs +7 -7
  106. package/dist/astro/routes/api/auth/dev-bypass.mjs +6 -6
  107. package/dist/astro/routes/api/auth/invite/accept.mjs +3 -3
  108. package/dist/astro/routes/api/auth/invite/complete.mjs +12 -12
  109. package/dist/astro/routes/api/auth/invite/index.mjs +9 -9
  110. package/dist/astro/routes/api/auth/invite/register-options.mjs +11 -11
  111. package/dist/astro/routes/api/auth/logout.mjs +4 -4
  112. package/dist/astro/routes/api/auth/magic-link/send.mjs +11 -11
  113. package/dist/astro/routes/api/auth/magic-link/verify.mjs +4 -4
  114. package/dist/astro/routes/api/auth/me.mjs +8 -8
  115. package/dist/astro/routes/api/auth/mode.mjs +1 -1
  116. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  117. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  118. package/dist/astro/routes/api/auth/passkey/_id_.mjs +7 -7
  119. package/dist/astro/routes/api/auth/passkey/index.mjs +3 -3
  120. package/dist/astro/routes/api/auth/passkey/options.mjs +13 -13
  121. package/dist/astro/routes/api/auth/passkey/register/options.mjs +11 -11
  122. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +12 -12
  123. package/dist/astro/routes/api/auth/passkey/verify.mjs +12 -12
  124. package/dist/astro/routes/api/auth/signup/complete.mjs +12 -12
  125. package/dist/astro/routes/api/auth/signup/request.mjs +11 -11
  126. package/dist/astro/routes/api/auth/signup/verify.mjs +3 -3
  127. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +16 -15
  128. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs.map +1 -1
  129. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.d.mts +9 -0
  130. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.d.mts.map +1 -0
  131. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +179 -0
  132. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs.map +1 -0
  133. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +4 -4
  134. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +4 -4
  135. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +4 -4
  136. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +4 -4
  137. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +13 -13
  138. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +8 -8
  139. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +4 -4
  140. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +4 -4
  141. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +8 -8
  142. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +17 -15
  143. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs.map +1 -1
  144. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +4 -4
  145. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +4 -4
  146. package/dist/astro/routes/api/content/_collection_/_id_.mjs +8 -8
  147. package/dist/astro/routes/api/content/_collection_/authors.mjs +4 -4
  148. package/dist/astro/routes/api/content/_collection_/index.mjs +8 -8
  149. package/dist/astro/routes/api/content/_collection_/trash.mjs +8 -8
  150. package/dist/astro/routes/api/dashboard.mjs +10 -8
  151. package/dist/astro/routes/api/dashboard.mjs.map +1 -1
  152. package/dist/astro/routes/api/dev/emails.mjs +4 -4
  153. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  154. package/dist/astro/routes/api/import/probe.mjs +12 -12
  155. package/dist/astro/routes/api/import/wordpress/analyze.mjs +5 -5
  156. package/dist/astro/routes/api/import/wordpress/execute.d.mts +9 -9
  157. package/dist/astro/routes/api/import/wordpress/execute.mjs +17 -15
  158. package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
  159. package/dist/astro/routes/api/import/wordpress/media.mjs +10 -10
  160. package/dist/astro/routes/api/import/wordpress/prepare.mjs +11 -11
  161. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +10 -10
  162. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  163. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +12 -12
  164. package/dist/astro/routes/api/import/wordpress-plugin/callback.mjs +1 -1
  165. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +1 -1
  166. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +19 -17
  167. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
  168. package/dist/astro/routes/api/manifest.mjs +5 -5
  169. package/dist/astro/routes/api/mcp.mjs +213 -46
  170. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  171. package/dist/astro/routes/api/media/_id_/confirm.mjs +8 -8
  172. package/dist/astro/routes/api/media/_id_.mjs +8 -8
  173. package/dist/astro/routes/api/media/file/_...key_.mjs +3 -3
  174. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +4 -4
  175. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +4 -4
  176. package/dist/astro/routes/api/media/providers/index.mjs +4 -4
  177. package/dist/astro/routes/api/media/upload-url.mjs +10 -10
  178. package/dist/astro/routes/api/media.mjs +13 -13
  179. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +11 -9
  180. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  181. package/dist/astro/routes/api/menus/_name_/items.mjs +11 -9
  182. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  183. package/dist/astro/routes/api/menus/_name_/reorder.mjs +11 -9
  184. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  185. package/dist/astro/routes/api/menus/_name_/translations.mjs +11 -9
  186. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  187. package/dist/astro/routes/api/menus/_name_.mjs +11 -9
  188. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  189. package/dist/astro/routes/api/menus/index.mjs +11 -9
  190. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  191. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  192. package/dist/astro/routes/api/oauth/device/authorize.mjs +7 -7
  193. package/dist/astro/routes/api/oauth/device/code.mjs +10 -10
  194. package/dist/astro/routes/api/oauth/device/token.mjs +9 -9
  195. package/dist/astro/routes/api/oauth/register.mjs +4 -4
  196. package/dist/astro/routes/api/oauth/token/refresh.mjs +7 -7
  197. package/dist/astro/routes/api/oauth/token/revoke.mjs +7 -7
  198. package/dist/astro/routes/api/oauth/token.mjs +7 -7
  199. package/dist/astro/routes/api/openapi.json.mjs +5 -5
  200. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +5 -5
  201. package/dist/astro/routes/api/redirects/404s/index.mjs +11 -11
  202. package/dist/astro/routes/api/redirects/404s/summary.mjs +11 -11
  203. package/dist/astro/routes/api/redirects/_id_.mjs +12 -12
  204. package/dist/astro/routes/api/redirects/index.mjs +12 -12
  205. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +4 -4
  206. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +4 -4
  207. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +40 -38
  208. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  209. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +40 -38
  210. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  211. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +40 -38
  212. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  213. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +40 -38
  214. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  215. package/dist/astro/routes/api/schema/collections/index.mjs +40 -38
  216. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  217. package/dist/astro/routes/api/schema/index.mjs +9 -8
  218. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  219. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +40 -38
  220. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  221. package/dist/astro/routes/api/schema/orphans/index.mjs +40 -38
  222. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  223. package/dist/astro/routes/api/search/enable.mjs +11 -11
  224. package/dist/astro/routes/api/search/index.mjs +10 -10
  225. package/dist/astro/routes/api/search/rebuild.mjs +11 -11
  226. package/dist/astro/routes/api/search/stats.mjs +7 -7
  227. package/dist/astro/routes/api/search/suggest.mjs +10 -10
  228. package/dist/astro/routes/api/sections/_slug_.mjs +10 -10
  229. package/dist/astro/routes/api/sections/index.mjs +10 -10
  230. package/dist/astro/routes/api/settings/email.mjs +6 -6
  231. package/dist/astro/routes/api/settings.mjs +16 -15
  232. package/dist/astro/routes/api/settings.mjs.map +1 -1
  233. package/dist/astro/routes/api/setup/admin-verify.mjs +13 -13
  234. package/dist/astro/routes/api/setup/admin.mjs +12 -12
  235. package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
  236. package/dist/astro/routes/api/setup/dev-bypass.mjs +30 -27
  237. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  238. package/dist/astro/routes/api/setup/dev-reset.mjs +4 -4
  239. package/dist/astro/routes/api/setup/index.mjs +30 -28
  240. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  241. package/dist/astro/routes/api/setup/status.mjs +5 -5
  242. package/dist/astro/routes/api/snapshot.d.mts.map +1 -1
  243. package/dist/astro/routes/api/snapshot.mjs +10 -9
  244. package/dist/astro/routes/api/snapshot.mjs.map +1 -1
  245. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +16 -14
  246. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  247. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +16 -14
  248. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  249. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +16 -14
  250. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  251. package/dist/astro/routes/api/taxonomies/index.mjs +16 -14
  252. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  253. package/dist/astro/routes/api/themes/preview.mjs +8 -8
  254. package/dist/astro/routes/api/typegen.mjs +6 -6
  255. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  256. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  257. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  258. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +8 -8
  259. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +11 -11
  260. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +11 -11
  261. package/dist/astro/routes/api/widget-areas/_name_.mjs +7 -7
  262. package/dist/astro/routes/api/widget-areas/index.mjs +11 -11
  263. package/dist/astro/routes/api/widget-components.mjs +4 -4
  264. package/dist/astro/routes/robots.txt.mjs +10 -9
  265. package/dist/astro/routes/robots.txt.mjs.map +1 -1
  266. package/dist/astro/routes/sitemap-_collection_.xml.mjs +13 -12
  267. package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
  268. package/dist/astro/routes/sitemap.xml.mjs +11 -10
  269. package/dist/astro/routes/sitemap.xml.mjs.map +1 -1
  270. package/dist/astro/types.d.mts +16 -12
  271. package/dist/astro/types.d.mts.map +1 -1
  272. package/dist/auth/providers/github.d.mts +1 -1
  273. package/dist/auth/providers/google.d.mts +1 -1
  274. package/dist/{authorize-D5gfBVU5.mjs → authorize-Cse0k7B0.mjs} +2 -2
  275. package/dist/{authorize-D5gfBVU5.mjs.map → authorize-Cse0k7B0.mjs.map} +1 -1
  276. package/dist/{base64-CqR-7kqF.mjs → base64-CmWvODNW.mjs} +1 -1
  277. package/dist/{base64-CqR-7kqF.mjs.map → base64-CmWvODNW.mjs.map} +1 -1
  278. package/dist/{byline-V_Qp1Ziw.mjs → byline-DVo-liaP.mjs} +27 -76
  279. package/dist/byline-DVo-liaP.mjs.map +1 -0
  280. package/dist/{byline-fields-B0NO1yUB.mjs → byline-fields-B-KXkg5R.mjs} +3 -3
  281. package/dist/{byline-fields-B0NO1yUB.mjs.map → byline-fields-B-KXkg5R.mjs.map} +1 -1
  282. package/dist/{byline-fields-nBVqK_Ff.mjs → byline-fields-DaMKzkhO.mjs} +2 -2
  283. package/dist/{byline-fields-nBVqK_Ff.mjs.map → byline-fields-DaMKzkhO.mjs.map} +1 -1
  284. package/dist/{byline-fields-CQJRIQkn.d.mts → byline-fields-RFPkDLRw.d.mts} +56 -31
  285. package/dist/byline-fields-RFPkDLRw.d.mts.map +1 -0
  286. package/dist/{byline-registry-DedidtqC.mjs → byline-registry-BOjqDOim.mjs} +3 -3
  287. package/dist/{byline-registry-DedidtqC.mjs.map → byline-registry-BOjqDOim.mjs.map} +1 -1
  288. package/dist/{bylines-DfGDnred.mjs → bylines-f5ppBpD5.mjs} +8 -8
  289. package/dist/{bylines-DfGDnred.mjs.map → bylines-f5ppBpD5.mjs.map} +1 -1
  290. package/dist/{bylines-B2NWnIwS.mjs → bylines-pIKgc_TL.mjs} +10 -4
  291. package/dist/{bylines-B2NWnIwS.mjs.map → bylines-pIKgc_TL.mjs.map} +1 -1
  292. package/dist/{cache-DTTHWD8n.mjs → cache-Q6V4U-Xz.mjs} +3 -3
  293. package/dist/{cache-DTTHWD8n.mjs.map → cache-Q6V4U-Xz.mjs.map} +1 -1
  294. package/dist/{challenge-store-woE0bbCf.mjs → challenge-store-LhiqMccz.mjs} +1 -1
  295. package/dist/{challenge-store-woE0bbCf.mjs.map → challenge-store-LhiqMccz.mjs.map} +1 -1
  296. package/dist/{chunks-BerYVuve.mjs → chunks-SyjZaYwV.mjs} +2 -2
  297. package/dist/{chunks-BerYVuve.mjs.map → chunks-SyjZaYwV.mjs.map} +1 -1
  298. package/dist/cli/index.mjs +29 -27
  299. package/dist/cli/index.mjs.map +1 -1
  300. package/dist/client/cf-access.d.mts +1 -1
  301. package/dist/client/index.d.mts +1 -1
  302. package/dist/client/index.mjs +2 -1
  303. package/dist/client/index.mjs.map +1 -1
  304. package/dist/{comment-sqQxNpN3.mjs → comment-80UyJJUR.mjs} +11 -3
  305. package/dist/comment-80UyJJUR.mjs.map +1 -0
  306. package/dist/comment-reaction-Dyb-AutY.mjs +85 -0
  307. package/dist/comment-reaction-Dyb-AutY.mjs.map +1 -0
  308. package/dist/{comments-D2hNuxNa.mjs → comments-Cczx7AvD.mjs} +3 -3
  309. package/dist/{comments-D2hNuxNa.mjs.map → comments-Cczx7AvD.mjs.map} +1 -1
  310. package/dist/{components-DYKp2gmo.mjs → components-CYt4uVK9.mjs} +1 -1
  311. package/dist/{components-DYKp2gmo.mjs.map → components-CYt4uVK9.mjs.map} +1 -1
  312. package/dist/{content-BIlVx-RX.mjs → content-2PTDNnoh.mjs} +22 -7
  313. package/dist/content-2PTDNnoh.mjs.map +1 -0
  314. package/dist/{context-Cm4pt1Ws.mjs → context-B1W8soLv.mjs} +64 -26
  315. package/dist/context-B1W8soLv.mjs.map +1 -0
  316. package/dist/{cron-DdEVrQ2Y.mjs → cron-C5LVoNmP.mjs} +14 -2
  317. package/dist/cron-C5LVoNmP.mjs.map +1 -0
  318. package/dist/{dashboard-C-UYpps0.mjs → dashboard-CYjpQZ6-.mjs} +4 -4
  319. package/dist/{dashboard-C-UYpps0.mjs.map → dashboard-CYjpQZ6-.mjs.map} +1 -1
  320. package/dist/database/instrumentation.d.mts +19 -0
  321. package/dist/database/instrumentation.d.mts.map +1 -1
  322. package/dist/database/instrumentation.mjs +8 -1
  323. package/dist/database/instrumentation.mjs.map +1 -1
  324. package/dist/db/index.d.mts +3 -3
  325. package/dist/db/index.mjs +1 -1
  326. package/dist/db/libsql.d.mts +1 -1
  327. package/dist/db/postgres.d.mts +1 -1
  328. package/dist/db/sqlite.d.mts +1 -1
  329. package/dist/{db-errors-BluWkwGI.mjs → db-errors-UXB1CK42.mjs} +1 -1
  330. package/dist/{db-errors-BluWkwGI.mjs.map → db-errors-UXB1CK42.mjs.map} +1 -1
  331. package/dist/{default-NHGuJzQ3.mjs → default-CeRG-Ot4.mjs} +1 -1
  332. package/dist/{default-NHGuJzQ3.mjs.map → default-CeRG-Ot4.mjs.map} +1 -1
  333. package/dist/{device-flow-BQApWgnW.mjs → device-flow-DENDCQ9F.mjs} +5 -5
  334. package/dist/{device-flow-BQApWgnW.mjs.map → device-flow-DENDCQ9F.mjs.map} +1 -1
  335. package/dist/{email-console-BbU3RbWv.mjs → email-console-DJP32ucW.mjs} +1 -1
  336. package/dist/{email-console-BbU3RbWv.mjs.map → email-console-DJP32ucW.mjs.map} +1 -1
  337. package/dist/{error-CNn_w7jf.mjs → error-Bl6kZgtt.mjs} +2 -2
  338. package/dist/{error-CNn_w7jf.mjs.map → error-Bl6kZgtt.mjs.map} +1 -1
  339. package/dist/{escape-DPgcxcpL.mjs → escape-Bjio4ZsM.mjs} +1 -1
  340. package/dist/{escape-DPgcxcpL.mjs.map → escape-Bjio4ZsM.mjs.map} +1 -1
  341. package/dist/field-defs-cache-ztrdzUGb.mjs +77 -0
  342. package/dist/field-defs-cache-ztrdzUGb.mjs.map +1 -0
  343. package/dist/{fts-manager-Cx5z8jdA.mjs → fts-manager-CQuHt-vS.mjs} +2 -2
  344. package/dist/{fts-manager-Cx5z8jdA.mjs.map → fts-manager-CQuHt-vS.mjs.map} +1 -1
  345. package/dist/{hash-DlvIFn0b.mjs → hash-DrvzIXcz.mjs} +1 -1
  346. package/dist/{hash-DlvIFn0b.mjs.map → hash-DrvzIXcz.mjs.map} +1 -1
  347. package/dist/{import-KyxT1Mbs.mjs → import-Bb1T9WJS.mjs} +4 -4
  348. package/dist/{import-KyxT1Mbs.mjs.map → import-Bb1T9WJS.mjs.map} +1 -1
  349. package/dist/{index-D2VAiumu.d.mts → index-BaIj5hIq.d.mts} +198 -21
  350. package/dist/index-BaIj5hIq.d.mts.map +1 -0
  351. package/dist/{index-uT2yR66F.d.mts → index-qbL02uhs.d.mts} +3 -3
  352. package/dist/{index-uT2yR66F.d.mts.map → index-qbL02uhs.d.mts.map} +1 -1
  353. package/dist/index.d.mts +18 -17
  354. package/dist/index.mjs +64 -61
  355. package/dist/{init-lock-DlBHjf9-.mjs → init-lock-6b309ZrF.mjs} +2 -29
  356. package/dist/init-lock-6b309ZrF.mjs.map +1 -0
  357. package/dist/{load-Dq91b_DK.mjs → load-BNo-ER8C.mjs} +2 -2
  358. package/dist/{load-Dq91b_DK.mjs.map → load-BNo-ER8C.mjs.map} +1 -1
  359. package/dist/{loader-BqWjcH3h.mjs → loader-Dn74CG1b.mjs} +70 -11
  360. package/dist/loader-Dn74CG1b.mjs.map +1 -0
  361. package/dist/{manifest-schema-DFPeqMAn.mjs → manifest-schema-BWKnQYQF.mjs} +1 -1
  362. package/dist/{manifest-schema-DFPeqMAn.mjs.map → manifest-schema-BWKnQYQF.mjs.map} +1 -1
  363. package/dist/media/image-endpoint.d.mts +74 -0
  364. package/dist/media/image-endpoint.d.mts.map +1 -0
  365. package/dist/media/image-endpoint.mjs +162 -0
  366. package/dist/media/image-endpoint.mjs.map +1 -0
  367. package/dist/media/index.d.mts +1 -1
  368. package/dist/media/index.mjs +2 -2
  369. package/dist/media/local-runtime.d.mts +19 -11
  370. package/dist/media/local-runtime.d.mts.map +1 -1
  371. package/dist/media/local-runtime.mjs +16 -13
  372. package/dist/media/local-runtime.mjs.map +1 -1
  373. package/dist/{media-JOf3pNkw.mjs → media-Bw0sA6rb.mjs} +2 -2
  374. package/dist/{media-JOf3pNkw.mjs.map → media-Bw0sA6rb.mjs.map} +1 -1
  375. package/dist/{media-allowlist-_A0SuDn4.mjs → media-allowlist-B77I5_bw.mjs} +2 -2
  376. package/dist/{media-allowlist-_A0SuDn4.mjs.map → media-allowlist-B77I5_bw.mjs.map} +1 -1
  377. package/dist/{media-url-CqLd69IO.mjs → media-url-O4rm9-SQ.mjs} +1 -1
  378. package/dist/{media-url-CqLd69IO.mjs.map → media-url-O4rm9-SQ.mjs.map} +1 -1
  379. package/dist/{menus-DX4_E01q.mjs → menus-CYs0WZoL.mjs} +20 -6
  380. package/dist/menus-CYs0WZoL.mjs.map +1 -0
  381. package/dist/{menus-Ryk9L7fT.mjs → menus-DS8VTZgo.mjs} +167 -24
  382. package/dist/menus-DS8VTZgo.mjs.map +1 -0
  383. package/dist/{mime-YbtlEtvS.mjs → mime-BTzvzJ8M.mjs} +1 -1
  384. package/dist/{mime-YbtlEtvS.mjs.map → mime-BTzvzJ8M.mjs.map} +1 -1
  385. package/dist/{mode-CGXzIbD8.mjs → mode-BB0F8xTC.mjs} +1 -1
  386. package/dist/{mode-CGXzIbD8.mjs.map → mode-BB0F8xTC.mjs.map} +1 -1
  387. package/dist/{normalize-DKsg36ty.mjs → normalize-ClbNIenm.mjs} +1 -1
  388. package/dist/{normalize-DKsg36ty.mjs.map → normalize-ClbNIenm.mjs.map} +1 -1
  389. package/dist/{oauth-authorization-C2kVyjXI.mjs → oauth-authorization-CsvzIp_F.mjs} +5 -5
  390. package/dist/{oauth-authorization-C2kVyjXI.mjs.map → oauth-authorization-CsvzIp_F.mjs.map} +1 -1
  391. package/dist/{oauth-clients-BC873NCV.mjs → oauth-clients-C9SYwEbZ.mjs} +1 -1
  392. package/dist/{oauth-clients-BC873NCV.mjs.map → oauth-clients-C9SYwEbZ.mjs.map} +1 -1
  393. package/dist/{oauth-state-store-Cd--TUaq.mjs → oauth-state-store---zrApfB.mjs} +1 -1
  394. package/dist/{oauth-state-store-Cd--TUaq.mjs.map → oauth-state-store---zrApfB.mjs.map} +1 -1
  395. package/dist/{oauth-user-lookup-e4wOvDud.mjs → oauth-user-lookup-SHsWRlG9.mjs} +1 -1
  396. package/dist/{oauth-user-lookup-e4wOvDud.mjs.map → oauth-user-lookup-SHsWRlG9.mjs.map} +1 -1
  397. package/dist/object-cache/memory.d.mts +15 -0
  398. package/dist/object-cache/memory.d.mts.map +1 -0
  399. package/dist/object-cache/memory.mjs +56 -0
  400. package/dist/object-cache/memory.mjs.map +1 -0
  401. package/dist/object-cache-SEb2IM4Z.mjs +373 -0
  402. package/dist/object-cache-SEb2IM4Z.mjs.map +1 -0
  403. package/dist/{options-9kLgkE8m.d.mts → options-CqECG0gM.d.mts} +3 -3
  404. package/dist/{options-9kLgkE8m.d.mts.map → options-CqECG0gM.d.mts.map} +1 -1
  405. package/dist/{options-BPCVnesz.mjs → options-DTTML-Tx.mjs} +1 -1
  406. package/dist/{options-BPCVnesz.mjs.map → options-DTTML-Tx.mjs.map} +1 -1
  407. package/dist/page/index.d.mts +2 -2
  408. package/dist/{parse-DzSrk1t8.mjs → parse-C9hpjUyY.mjs} +2 -2
  409. package/dist/{parse-DzSrk1t8.mjs.map → parse-C9hpjUyY.mjs.map} +1 -1
  410. package/dist/{passkey-config-BpjbE_Uv.mjs → passkey-config-C0YfSBko.mjs} +1 -1
  411. package/dist/{passkey-config-BpjbE_Uv.mjs.map → passkey-config-C0YfSBko.mjs.map} +1 -1
  412. package/dist/{patterns-p-RBdTbM.mjs → patterns-BKmjvM7K.mjs} +1 -1
  413. package/dist/{patterns-p-RBdTbM.mjs.map → patterns-BKmjvM7K.mjs.map} +1 -1
  414. package/dist/{placeholder-2xumZh4g.mjs → placeholder-B0s2mWu5.mjs} +1 -1
  415. package/dist/{placeholder-2xumZh4g.mjs.map → placeholder-B0s2mWu5.mjs.map} +1 -1
  416. package/dist/{placeholder-BevVKfay.d.mts → placeholder-QoI4gEzP.d.mts} +1 -1
  417. package/dist/{placeholder-BevVKfay.d.mts.map → placeholder-QoI4gEzP.d.mts.map} +1 -1
  418. package/dist/plugin-types.d.mts +1 -1
  419. package/dist/plugin-utils.d.mts +9 -9
  420. package/dist/plugins/adapt-sandbox-entry.d.mts +9 -9
  421. package/dist/plugins/adapt-sandbox-entry.mjs +4 -2
  422. package/dist/plugins/adapt-sandbox-entry.mjs.map +1 -1
  423. package/dist/{transport-1cIrOb1Y.mjs → portable-text-BICg8bTk.mjs} +2 -135
  424. package/dist/portable-text-BICg8bTk.mjs.map +1 -0
  425. package/dist/{preview-Dqv2hwXr.mjs → preview-DKGCt2_p.mjs} +2 -2
  426. package/dist/{preview-Dqv2hwXr.mjs.map → preview-DKGCt2_p.mjs.map} +1 -1
  427. package/dist/{public-url-D_zARuvZ.mjs → public-url-CTVqgMmg.mjs} +1 -1
  428. package/dist/{public-url-D_zARuvZ.mjs.map → public-url-CTVqgMmg.mjs.map} +1 -1
  429. package/dist/{query-Crm038Mc.mjs → query-DgUHZLWB.mjs} +230 -31
  430. package/dist/query-DgUHZLWB.mjs.map +1 -0
  431. package/dist/{rate-limit-hRTBqmw1.mjs → rate-limit-BuQ5d4X_.mjs} +2 -2
  432. package/dist/{rate-limit-hRTBqmw1.mjs.map → rate-limit-BuQ5d4X_.mjs.map} +1 -1
  433. package/dist/{redirect-CRWIt8Zj.mjs → redirect-Bifv_yHv.mjs} +3 -3
  434. package/dist/{redirect-CRWIt8Zj.mjs.map → redirect-Bifv_yHv.mjs.map} +1 -1
  435. package/dist/{redirect-C-OOkyku.mjs → redirect-CS-PHtNh.mjs} +1 -1
  436. package/dist/{redirect-C-OOkyku.mjs.map → redirect-CS-PHtNh.mjs.map} +1 -1
  437. package/dist/{redirects-CP3TnTLO.mjs → redirects-BZ8Mxn8H.mjs} +6 -6
  438. package/dist/{redirects-CP3TnTLO.mjs.map → redirects-BZ8Mxn8H.mjs.map} +1 -1
  439. package/dist/{redirects-6Zg2SoYo.mjs → redirects-x9eFPeyi.mjs} +10 -3
  440. package/dist/redirects-x9eFPeyi.mjs.map +1 -0
  441. package/dist/{registry-diMzD1Wf.mjs → registry-CK1SS6pi.mjs} +6 -6
  442. package/dist/{registry-diMzD1Wf.mjs.map → registry-CK1SS6pi.mjs.map} +1 -1
  443. package/dist/{request-cache-UwmBAiUK.mjs → request-cache-KCNHp_RJ.mjs} +1 -1
  444. package/dist/{request-cache-UwmBAiUK.mjs.map → request-cache-KCNHp_RJ.mjs.map} +1 -1
  445. package/dist/{request-meta-DPechd0W.mjs → request-meta-CmS1tDFf.mjs} +2 -2
  446. package/dist/{request-meta-DPechd0W.mjs.map → request-meta-CmS1tDFf.mjs.map} +1 -1
  447. package/dist/{resolve-B3NUUtVY.mjs → resolve-C7I0qiR0.mjs} +1 -1
  448. package/dist/{resolve-B3NUUtVY.mjs.map → resolve-C7I0qiR0.mjs.map} +1 -1
  449. package/dist/{runner-C8vcbvCe.d.mts → runner-CEtq-6Sm.d.mts} +2 -2
  450. package/dist/{runner-C8vcbvCe.d.mts.map → runner-CEtq-6Sm.d.mts.map} +1 -1
  451. package/dist/{runner--4wMWwKM.mjs → runner-DYYnW530.mjs} +201 -170
  452. package/dist/runner-DYYnW530.mjs.map +1 -0
  453. package/dist/runtime.d.mts +10 -10
  454. package/dist/runtime.mjs +3 -3
  455. package/dist/{schema-BDOkd3OU.mjs → schema-CbFRFoM7.mjs} +13 -8
  456. package/dist/schema-CbFRFoM7.mjs.map +1 -0
  457. package/dist/{search-Bs_J_EW-.mjs → search-C-waE_YW.mjs} +4 -4
  458. package/dist/{search-Bs_J_EW-.mjs.map → search-C-waE_YW.mjs.map} +1 -1
  459. package/dist/{secrets-C8xmE6mR.mjs → secrets-BSf9pRRY.mjs} +5 -5
  460. package/dist/{secrets-C8xmE6mR.mjs.map → secrets-BSf9pRRY.mjs.map} +1 -1
  461. package/dist/{sections-P0zuBlyz.mjs → sections-osX9U-YJ.mjs} +3 -3
  462. package/dist/{sections-P0zuBlyz.mjs.map → sections-osX9U-YJ.mjs.map} +1 -1
  463. package/dist/seed/index.d.mts +2 -2
  464. package/dist/seed/index.mjs +23 -21
  465. package/dist/seo/index.d.mts +1 -1
  466. package/dist/seo/index.mjs +1 -1
  467. package/dist/{seo-DpNgGQjF.mjs → seo-4FovMwNS.mjs} +5 -2
  468. package/dist/seo-4FovMwNS.mjs.map +1 -0
  469. package/dist/{seo-CLhm-Fmb.mjs → seo-DCEF-AVr.mjs} +1 -1
  470. package/dist/{seo-CLhm-Fmb.mjs.map → seo-DCEF-AVr.mjs.map} +1 -1
  471. package/dist/{service-CDQQnT8W.mjs → service-jby1RRmU.mjs} +3 -3
  472. package/dist/{service-CDQQnT8W.mjs.map → service-jby1RRmU.mjs.map} +1 -1
  473. package/dist/session-user-B8aLtKAH.mjs +51 -0
  474. package/dist/session-user-B8aLtKAH.mjs.map +1 -0
  475. package/dist/{settings-sO0Fif4p.mjs → settings-4bRT2NIf.mjs} +3 -3
  476. package/dist/{settings-sO0Fif4p.mjs.map → settings-4bRT2NIf.mjs.map} +1 -1
  477. package/dist/{settings-BjBsmVAo.mjs → settings-t-H2jPuJ.mjs} +18 -10
  478. package/dist/settings-t-H2jPuJ.mjs.map +1 -0
  479. package/dist/{setup-complete-CMMr-oZU.mjs → setup-complete-gEiySUc-.mjs} +2 -2
  480. package/dist/{setup-complete-CMMr-oZU.mjs.map → setup-complete-gEiySUc-.mjs.map} +1 -1
  481. package/dist/{setup-nonce-169xl4fV.mjs → setup-nonce-DzS50zme.mjs} +1 -1
  482. package/dist/{setup-nonce-169xl4fV.mjs.map → setup-nonce-DzS50zme.mjs.map} +1 -1
  483. package/dist/{single-flight-cache-C0UV1Npg.mjs → single-flight-cache-Cdfkic3t.mjs} +2 -2
  484. package/dist/{single-flight-cache-C0UV1Npg.mjs.map → single-flight-cache-Cdfkic3t.mjs.map} +1 -1
  485. package/dist/{site-url-vtsuOvSD.mjs → site-url-BLebyON8.mjs} +2 -2
  486. package/dist/{site-url-vtsuOvSD.mjs.map → site-url-BLebyON8.mjs.map} +1 -1
  487. package/dist/{slugify-Cjh1ssOZ.mjs → slugify-Cce3dTdg.mjs} +1 -1
  488. package/dist/{slugify-Cjh1ssOZ.mjs.map → slugify-Cce3dTdg.mjs.map} +1 -1
  489. package/dist/{ssrf-XO05Voq6.mjs → ssrf-BRKb343l.mjs} +1 -1
  490. package/dist/{ssrf-XO05Voq6.mjs.map → ssrf-BRKb343l.mjs.map} +1 -1
  491. package/dist/{status-2gZklYuj.mjs → status-vUK0SA17.mjs} +1 -1
  492. package/dist/{status-2gZklYuj.mjs.map → status-vUK0SA17.mjs.map} +1 -1
  493. package/dist/storage/local.d.mts +1 -1
  494. package/dist/storage/local.mjs +1 -1
  495. package/dist/storage/s3.d.mts +1 -1
  496. package/dist/storage/s3.mjs +1 -1
  497. package/dist/{taxonomies-DuESHWKI.mjs → taxonomies-BBB8O-CU.mjs} +7 -7
  498. package/dist/{taxonomies-DuESHWKI.mjs.map → taxonomies-BBB8O-CU.mjs.map} +1 -1
  499. package/dist/{taxonomies-BBxYA38v.mjs → taxonomies-Dxrc_szG.mjs} +177 -123
  500. package/dist/taxonomies-Dxrc_szG.mjs.map +1 -0
  501. package/dist/{taxonomy-CdllE4oq.mjs → taxonomy-B2HQuVf5.mjs} +19 -6
  502. package/dist/taxonomy-B2HQuVf5.mjs.map +1 -0
  503. package/dist/{tokens-DMkVjxrx.mjs → tokens-LeuXF9gG.mjs} +2 -2
  504. package/dist/{tokens-DMkVjxrx.mjs.map → tokens-LeuXF9gG.mjs.map} +1 -1
  505. package/dist/{transaction-x2tJQ-A1.mjs → transaction-qfqpPVpu.mjs} +1 -1
  506. package/dist/{transaction-x2tJQ-A1.mjs.map → transaction-qfqpPVpu.mjs.map} +1 -1
  507. package/dist/{transport-jdvsZEIt.d.mts → transport-BZ-03aFT.d.mts} +1 -1
  508. package/dist/{transport-jdvsZEIt.d.mts.map → transport-BZ-03aFT.d.mts.map} +1 -1
  509. package/dist/transport-_2nBz7e9.mjs +135 -0
  510. package/dist/transport-_2nBz7e9.mjs.map +1 -0
  511. package/dist/{trusted-proxy-CHp41Fjj.mjs → trusted-proxy-DZY5WCn2.mjs} +1 -1
  512. package/dist/{trusted-proxy-CHp41Fjj.mjs.map → trusted-proxy-DZY5WCn2.mjs.map} +1 -1
  513. package/dist/{types-Del0VMij.d.mts → types-B-gIxFCE.d.mts} +9 -1
  514. package/dist/{types-Del0VMij.d.mts.map → types-B-gIxFCE.d.mts.map} +1 -1
  515. package/dist/{types-DdkL6fyv.d.mts → types-BG8_XTLj.d.mts} +1 -1
  516. package/dist/{types-DdkL6fyv.d.mts.map → types-BG8_XTLj.d.mts.map} +1 -1
  517. package/dist/{types-BTnnBYVX.d.mts → types-BWh2MjmA.d.mts} +15 -2
  518. package/dist/types-BWh2MjmA.d.mts.map +1 -0
  519. package/dist/{types-CkEuk-Zr.d.mts → types-BWqGVhFn.d.mts} +1 -1
  520. package/dist/{types-CkEuk-Zr.d.mts.map → types-BWqGVhFn.d.mts.map} +1 -1
  521. package/dist/{types-DejCHqWT.mjs → types-CQAugunJ.mjs} +1 -1
  522. package/dist/{types-DejCHqWT.mjs.map → types-CQAugunJ.mjs.map} +1 -1
  523. package/dist/{types-Bzfk2yC8.d.mts → types-CTLJYMhN.d.mts} +1 -1
  524. package/dist/{types-Bzfk2yC8.d.mts.map → types-CTLJYMhN.d.mts.map} +1 -1
  525. package/dist/{types-BFgYtuKd.d.mts → types-CUsXGRVj.d.mts} +1 -1
  526. package/dist/{types-BFgYtuKd.d.mts.map → types-CUsXGRVj.d.mts.map} +1 -1
  527. package/dist/{types-BXSUSAjt.mjs → types-DXOIbece.mjs} +3 -3
  528. package/dist/types-DXOIbece.mjs.map +1 -0
  529. package/dist/{types-u_XxjbS8.d.mts → types-DrYMm9s5.d.mts} +1 -1
  530. package/dist/{types-u_XxjbS8.d.mts.map → types-DrYMm9s5.d.mts.map} +1 -1
  531. package/dist/{types-DO7whVYU.d.mts → types-TTx8uP7V.d.mts} +2 -2
  532. package/dist/{types-DO7whVYU.d.mts.map → types-TTx8uP7V.d.mts.map} +1 -1
  533. package/dist/types-fS7-VTdR.d.mts +124 -0
  534. package/dist/types-fS7-VTdR.d.mts.map +1 -0
  535. package/dist/{types-BIduXPJk.mjs → types-tM44hEcf.mjs} +1 -1
  536. package/dist/{types-BIduXPJk.mjs.map → types-tM44hEcf.mjs.map} +1 -1
  537. package/dist/{user-C0um7wrg.mjs → user-Db-Rti_z.mjs} +3 -3
  538. package/dist/{user-C0um7wrg.mjs.map → user-Db-Rti_z.mjs.map} +1 -1
  539. package/dist/{utils-C4M981Br.mjs → utils-B7A57fm9.mjs} +2 -2
  540. package/dist/{utils-C4M981Br.mjs.map → utils-B7A57fm9.mjs.map} +1 -1
  541. package/dist/{validate-DGhQPXzI.mjs → validate-0Utjspbs.mjs} +3 -3
  542. package/dist/{validate-DGhQPXzI.mjs.map → validate-0Utjspbs.mjs.map} +1 -1
  543. package/dist/{validate-cJOiOvT2.d.mts → validate-DOFrIb-c.d.mts} +5 -5
  544. package/dist/{validate-cJOiOvT2.d.mts.map → validate-DOFrIb-c.d.mts.map} +1 -1
  545. package/dist/{validation-DVHjPM1M.mjs → validation-D9EnzH1T.mjs} +6 -6
  546. package/dist/{validation-DVHjPM1M.mjs.map → validation-D9EnzH1T.mjs.map} +1 -1
  547. package/dist/version-BgVM_1MU.mjs +7 -0
  548. package/dist/{version-BOjj_cfz.mjs.map → version-BgVM_1MU.mjs.map} +1 -1
  549. package/dist/{widgets-Ci6hLwfO.mjs → widgets-BSTzPUYa.mjs} +4 -4
  550. package/dist/{widgets-Ci6hLwfO.mjs.map → widgets-BSTzPUYa.mjs.map} +1 -1
  551. package/dist/{zod-generator-CarzgPAu.mjs → zod-generator-ElVQOav7.mjs} +51 -15
  552. package/dist/zod-generator-ElVQOav7.mjs.map +1 -0
  553. package/package.json +19 -6
  554. package/src/api/handlers/api-tokens.ts +19 -0
  555. package/src/api/handlers/comment-reactions.ts +165 -0
  556. package/src/api/handlers/schema.ts +8 -0
  557. package/src/api/schemas/bylines.ts +8 -0
  558. package/src/api/schemas/comments.ts +10 -0
  559. package/src/astro/image-endpoint.ts +84 -0
  560. package/src/astro/index.ts +6 -0
  561. package/src/astro/integration/index.ts +83 -22
  562. package/src/astro/integration/routes.ts +5 -0
  563. package/src/astro/integration/runtime.ts +65 -1
  564. package/src/astro/integration/virtual-modules.ts +40 -0
  565. package/src/astro/integration/vite-config.ts +25 -1
  566. package/src/astro/middleware/auth.ts +4 -3
  567. package/src/astro/middleware/request-context.ts +6 -1
  568. package/src/astro/middleware/scoped-db.ts +131 -0
  569. package/src/astro/middleware/stream-end-metrics.ts +15 -9
  570. package/src/astro/middleware.ts +131 -31
  571. package/src/astro/object-cache/adapters.ts +50 -0
  572. package/src/astro/prefetch.ts +77 -0
  573. package/src/astro/routes/admin.astro +5 -1
  574. package/src/astro/routes/api/comments/[collection]/[contentId]/reactions.ts +97 -0
  575. package/src/astro/routes/api/schema/index.ts +9 -3
  576. package/src/astro/routes/api/setup/dev-bypass.ts +5 -1
  577. package/src/astro/routes/api/snapshot.ts +3 -1
  578. package/src/astro/session-user.ts +57 -0
  579. package/src/astro/types.ts +1 -0
  580. package/src/cli/commands/export-seed.ts +10 -7
  581. package/src/comments/query.ts +78 -7
  582. package/src/comments/ranking.ts +58 -0
  583. package/src/components/Block.astro +71 -0
  584. package/src/components/Comments.astro +136 -1
  585. package/src/components/EmDashMedia.astro +1 -2
  586. package/src/components/Image.astro +36 -2
  587. package/src/components/InlinePortableTextEditor.tsx +10 -2
  588. package/src/components/index.ts +5 -0
  589. package/src/components/portable-text-text-align.ts +38 -0
  590. package/src/content/converters/portable-text-to-prosemirror.ts +5 -1
  591. package/src/content/converters/prosemirror-to-portable-text.ts +8 -0
  592. package/src/content/converters/types.ts +1 -0
  593. package/src/database/instrumentation.ts +21 -1
  594. package/src/database/migrations/044_comment_reactions.ts +56 -0
  595. package/src/database/migrations/runner.ts +2 -0
  596. package/src/database/repositories/byline.ts +27 -0
  597. package/src/database/repositories/comment-reaction.ts +132 -0
  598. package/src/database/repositories/comment.ts +10 -0
  599. package/src/database/repositories/content.ts +25 -3
  600. package/src/database/repositories/menu.ts +13 -1
  601. package/src/database/repositories/seo.ts +3 -0
  602. package/src/database/repositories/taxonomy.ts +13 -1
  603. package/src/database/repositories/types.ts +13 -0
  604. package/src/database/types.ts +9 -0
  605. package/src/emdash-runtime.ts +244 -75
  606. package/src/index.ts +22 -0
  607. package/src/loader.ts +97 -5
  608. package/src/mcp/server.ts +307 -20
  609. package/src/media/image-endpoint.ts +167 -0
  610. package/src/media/local-runtime.ts +18 -5
  611. package/src/menus/index.ts +11 -4
  612. package/src/object-cache/codec.ts +73 -0
  613. package/src/object-cache/index.ts +495 -0
  614. package/src/object-cache/memory.ts +91 -0
  615. package/src/object-cache/types.ts +124 -0
  616. package/src/plugins/adapt-sandbox-entry.ts +11 -1
  617. package/src/plugins/context.ts +94 -22
  618. package/src/plugins/cron.ts +18 -2
  619. package/src/plugins/routes.ts +40 -1
  620. package/src/query.ts +304 -18
  621. package/src/schema/query.ts +11 -4
  622. package/src/schema/zod-generator.ts +53 -8
  623. package/src/settings/index.ts +18 -5
  624. package/src/taxonomies/index.ts +263 -165
  625. package/src/ui.ts +5 -0
  626. package/src/virtual-modules.d.ts +24 -0
  627. package/dist/api-DxjIV2o8.mjs.map +0 -1
  628. package/dist/api-tokens-BFFkB0jB.mjs.map +0 -1
  629. package/dist/byline-V_Qp1Ziw.mjs.map +0 -1
  630. package/dist/byline-fields-CQJRIQkn.d.mts.map +0 -1
  631. package/dist/comment-sqQxNpN3.mjs.map +0 -1
  632. package/dist/content-BIlVx-RX.mjs.map +0 -1
  633. package/dist/context-Cm4pt1Ws.mjs.map +0 -1
  634. package/dist/cron-DdEVrQ2Y.mjs.map +0 -1
  635. package/dist/index-D2VAiumu.d.mts.map +0 -1
  636. package/dist/init-lock-DlBHjf9-.mjs.map +0 -1
  637. package/dist/loader-BqWjcH3h.mjs.map +0 -1
  638. package/dist/menus-DX4_E01q.mjs.map +0 -1
  639. package/dist/menus-Ryk9L7fT.mjs.map +0 -1
  640. package/dist/query-Crm038Mc.mjs.map +0 -1
  641. package/dist/redirects-6Zg2SoYo.mjs.map +0 -1
  642. package/dist/runner--4wMWwKM.mjs.map +0 -1
  643. package/dist/schema-BDOkd3OU.mjs.map +0 -1
  644. package/dist/seo-DpNgGQjF.mjs.map +0 -1
  645. package/dist/settings-BjBsmVAo.mjs.map +0 -1
  646. package/dist/taxonomies-BBxYA38v.mjs.map +0 -1
  647. package/dist/taxonomy-CdllE4oq.mjs.map +0 -1
  648. package/dist/transport-1cIrOb1Y.mjs.map +0 -1
  649. package/dist/types-BTnnBYVX.d.mts.map +0 -1
  650. package/dist/types-BXSUSAjt.mjs.map +0 -1
  651. package/dist/version-BOjj_cfz.mjs +0 -7
  652. package/dist/zod-generator-CarzgPAu.mjs.map +0 -1
  653. /package/dist/{api-tokens-C7ywRx7l.mjs → api-tokens-B4BQybOp.mjs} +0 -0
  654. /package/dist/{ssrf-CRZGzjdL.mjs → ssrf-CcX9zvMK.mjs} +0 -0
  655. /package/dist/{types-BoRm8-pp.mjs → types-BvbeGEtr.mjs} +0 -0
@@ -21,9 +21,21 @@ const STALE_LOCK_MINUTES = 10;
21
21
  * Stateless — all state lives in the database.
22
22
  */
23
23
  var CronExecutor = class {
24
+ /**
25
+ * Resolves the database connection to use for this tick. A resolver (not a
26
+ * captured instance) so connection-backed adapters work across events: on
27
+ * Cloudflare the `scheduled()` handler installs an event-scoped connection
28
+ * in ALS, and this resolves to it instead of the per-isolate singleton
29
+ * whose socket belongs to an earlier request. Accepts a plain `Kysely` too
30
+ * (wrapped in a constant resolver) for callers/tests that don't need ALS.
31
+ */
32
+ resolveDb;
24
33
  constructor(db, invokeCronHook) {
25
- this.db = db;
26
34
  this.invokeCronHook = invokeCronHook;
35
+ this.resolveDb = typeof db === "function" ? db : () => db;
36
+ }
37
+ get db() {
38
+ return this.resolveDb();
27
39
  }
28
40
  /**
29
41
  * Process all overdue tasks.
@@ -262,4 +274,4 @@ function validateSchedule(schedule) {
262
274
 
263
275
  //#endregion
264
276
  export { CronExecutor as n, setCronTasksEnabled as r, CronAccessImpl as t };
265
- //# sourceMappingURL=cron-DdEVrQ2Y.mjs.map
277
+ //# sourceMappingURL=cron-C5LVoNmP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-C5LVoNmP.mjs","names":[],"sources":["../src/plugins/cron.ts"],"sourcesContent":["/**\n * Plugin Cron System\n *\n * Provides scheduled task execution for plugins:\n * - CronExecutor: claims overdue tasks, invokes per-plugin cron hook, updates next run.\n * - CronAccessImpl: per-plugin API for schedule/cancel/list.\n *\n */\n\nimport { Cron } from \"croner\";\nimport type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\nimport { ulid } from \"ulidx\";\n\nimport type { Database } from \"../database/types.js\";\nimport type { CronAccess, CronEvent, CronTaskInfo } from \"./types.js\";\n\n/** Stale lock threshold in minutes */\nconst STALE_LOCK_MINUTES = 10;\n\n/**\n * Callback to invoke a plugin's cron hook.\n * Provided by PluginManager so CronExecutor stays decoupled from the hook pipeline.\n */\nexport type InvokeCronHookFn = (pluginId: string, event: CronEvent) => Promise<void>;\n\n/**\n * Callback to notify the scheduler that the next due time may have changed.\n */\nexport type RescheduleFn = () => void;\n\n// ─── CronExecutor ──────────────────────────────────────────────────────────\n\n/**\n * Executes overdue cron tasks.\n *\n * Called by the platform driver: the NodeCronScheduler timer on Node, or the\n * Worker's `scheduled()` handler (via runScheduledTasks) on Cloudflare.\n * Stateless — all state lives in the database.\n */\nexport class CronExecutor {\n\t/**\n\t * Resolves the database connection to use for this tick. A resolver (not a\n\t * captured instance) so connection-backed adapters work across events: on\n\t * Cloudflare the `scheduled()` handler installs an event-scoped connection\n\t * in ALS, and this resolves to it instead of the per-isolate singleton\n\t * whose socket belongs to an earlier request. Accepts a plain `Kysely` too\n\t * (wrapped in a constant resolver) for callers/tests that don't need ALS.\n\t */\n\tprivate readonly resolveDb: () => Kysely<Database>;\n\n\tconstructor(\n\t\tdb: Kysely<Database> | (() => Kysely<Database>),\n\t\tprivate invokeCronHook: InvokeCronHookFn,\n\t) {\n\t\tthis.resolveDb = typeof db === \"function\" ? db : () => db;\n\t}\n\n\tprivate get db(): Kysely<Database> {\n\t\treturn this.resolveDb();\n\t}\n\n\t/**\n\t * Process all overdue tasks.\n\t *\n\t * 1. Atomically claim tasks whose next_run_at <= now, status = idle, enabled = 1.\n\t * 2. For each claimed task, invoke the plugin's cron hook.\n\t * 3. On success: compute next_run_at and reset to idle, or delete one-shots.\n\t * 4. On failure: reset to idle (retry on next tick).\n\t */\n\tasync tick(): Promise<number> {\n\t\tconst now = new Date().toISOString();\n\t\tlet processed = 0;\n\n\t\t// Claim overdue tasks atomically\n\t\tconst claimed = await sql<{\n\t\t\tid: string;\n\t\t\tplugin_id: string;\n\t\t\ttask_name: string;\n\t\t\tschedule: string;\n\t\t\tis_oneshot: number;\n\t\t\tdata: string | null;\n\t\t\tnext_run_at: string;\n\t\t}>`\n\t\t\tUPDATE _emdash_cron_tasks\n\t\t\tSET status = 'running', locked_at = ${now}\n\t\t\tWHERE id IN (\n\t\t\t\tSELECT id FROM _emdash_cron_tasks\n\t\t\t\tWHERE next_run_at <= ${now}\n\t\t\t\t AND status = 'idle'\n\t\t\t\t AND enabled = 1\n\t\t\t\tORDER BY next_run_at ASC\n\t\t\t\tLIMIT 10\n\t\t\t)\n\t\t\tRETURNING id, plugin_id, task_name, schedule, is_oneshot, data, next_run_at\n\t\t`.execute(this.db);\n\n\t\tfor (const task of claimed.rows) {\n\t\t\t// Parse task data safely ��� malformed JSON must not crash the entire batch\n\t\t\tlet parsedData: Record<string, unknown> | undefined;\n\t\t\tif (task.data) {\n\t\t\t\ttry {\n\t\t\t\t\tparsedData = JSON.parse(task.data) as Record<string, unknown>;\n\t\t\t\t} catch {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[cron] Invalid JSON data for ${task.plugin_id}:${task.task_name}, skipping`,\n\t\t\t\t\t);\n\t\t\t\t\tawait sql`\n\t\t\t\t\t\tUPDATE _emdash_cron_tasks\n\t\t\t\t\t\tSET status = 'idle', locked_at = NULL\n\t\t\t\t\t\tWHERE id = ${task.id}\n\t\t\t\t\t`.execute(this.db);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst event: CronEvent = {\n\t\t\t\tname: task.task_name,\n\t\t\t\tdata: parsedData,\n\t\t\t\tscheduledAt: task.next_run_at,\n\t\t\t};\n\n\t\t\tlet hookFailed = false;\n\t\t\ttry {\n\t\t\t\tawait this.invokeCronHook(task.plugin_id, event);\n\t\t\t} catch (error) {\n\t\t\t\thookFailed = true;\n\t\t\t\tconsole.error(`[cron] Hook failed for ${task.plugin_id}:${task.task_name}:`, error);\n\t\t\t}\n\n\t\t\tif (task.is_oneshot) {\n\t\t\t\tif (hookFailed) {\n\t\t\t\t\t// Retry metadata is namespaced under __emdash to avoid collisions\n\t\t\t\t\t// with plugin-controlled data fields.\n\t\t\t\t\tconst meta =\n\t\t\t\t\t\tparsedData?.__emdash != null && typeof parsedData.__emdash === \"object\"\n\t\t\t\t\t\t\t? (parsedData.__emdash as Record<string, unknown>)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\tconst raw = meta?.retryCount;\n\t\t\t\t\tconst retryCount =\n\t\t\t\t\t\ttypeof raw === \"number\" && Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;\n\t\t\t\t\tconst MAX_ONESHOT_RETRIES = 5;\n\n\t\t\t\t\tif (retryCount >= MAX_ONESHOT_RETRIES) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`[cron] One-shot task ${task.plugin_id}:${task.task_name} exceeded ${MAX_ONESHOT_RETRIES} retries, removing`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait sql`\n\t\t\t\t\t\tDELETE FROM _emdash_cron_tasks WHERE id = ${task.id}\n\t\t\t\t\t`.execute(this.db);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Retry with exponential backoff: 1m, 2m, 4m, 8m, 16m\n\t\t\t\t\t\tconst backoffMs = 60_000 * Math.pow(2, retryCount);\n\t\t\t\t\t\tconst retryAt = new Date(Date.now() + backoffMs).toISOString();\n\t\t\t\t\t\tconst updatedData = JSON.stringify({\n\t\t\t\t\t\t\t...parsedData,\n\t\t\t\t\t\t\t__emdash: { ...meta, retryCount: retryCount + 1 },\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait sql`\n\t\t\t\t\t\tUPDATE _emdash_cron_tasks\n\t\t\t\t\t\tSET status = 'idle', locked_at = NULL, next_run_at = ${retryAt}, data = ${updatedData}\n\t\t\t\t\t\tWHERE id = ${task.id}\n\t\t\t\t\t`.execute(this.db);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Success: delete the one-shot task\n\t\t\t\t\tawait sql`\n\t\t\t\t\t\tDELETE FROM _emdash_cron_tasks WHERE id = ${task.id}\n\t\t\t\t\t`.execute(this.db);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Recurring: compute next run and reset\n\t\t\t\tconst nextRun = nextCronTime(task.schedule);\n\t\t\t\tawait sql`\n\t\t\t\t\tUPDATE _emdash_cron_tasks\n\t\t\t\t\tSET status = 'idle',\n\t\t\t\t\t\tlocked_at = NULL,\n\t\t\t\t\t\tlast_run_at = ${now},\n\t\t\t\t\t\tnext_run_at = ${nextRun}\n\t\t\t\t\tWHERE id = ${task.id}\n\t\t\t\t`.execute(this.db);\n\t\t\t}\n\n\t\t\tprocessed++;\n\t\t}\n\n\t\treturn processed;\n\t}\n\n\t/**\n\t * Recover tasks stuck in 'running' for more than STALE_LOCK_MINUTES.\n\t * These likely crashed mid-execution.\n\t */\n\tasync recoverStaleLocks(): Promise<number> {\n\t\tconst cutoff = new Date(Date.now() - STALE_LOCK_MINUTES * 60 * 1000).toISOString();\n\n\t\tconst result = await sql`\n\t\t\tUPDATE _emdash_cron_tasks\n\t\t\tSET status = 'idle', locked_at = NULL\n\t\t\tWHERE status = 'running'\n\t\t\t AND locked_at < ${cutoff}\n\t\t`.execute(this.db);\n\n\t\treturn Number(result.numAffectedRows ?? 0);\n\t}\n\n\t/**\n\t * Get the next due time across all enabled tasks.\n\t * Returns null if no tasks are scheduled.\n\t */\n\tasync getNextDueTime(): Promise<string | null> {\n\t\tconst result = await sql<{ next: string | null }>`\n\t\t\tSELECT MIN(next_run_at) as next\n\t\t\tFROM _emdash_cron_tasks\n\t\t\tWHERE status = 'idle' AND enabled = 1\n\t\t`.execute(this.db);\n\n\t\treturn result.rows[0]?.next ?? null;\n\t}\n}\n\n// ─── CronAccessImpl ────────────────────────────────────────────────────────\n\n/**\n * Per-plugin cron API implementation.\n * Scoped to a single plugin ID — plugins cannot see or modify other plugins' tasks.\n */\nexport class CronAccessImpl implements CronAccess {\n\tconstructor(\n\t\tprivate db: Kysely<Database>,\n\t\tprivate pluginId: string,\n\t\tprivate reschedule: RescheduleFn,\n\t) {}\n\n\tasync schedule(\n\t\tname: string,\n\t\topts: { schedule: string; data?: Record<string, unknown> },\n\t): Promise<void> {\n\t\tvalidateTaskName(name);\n\t\tvalidateSchedule(opts.schedule);\n\n\t\tconst oneshot = isOneShot(opts.schedule);\n\t\tconst nextRun = oneshot ? opts.schedule : nextCronTime(opts.schedule);\n\t\tconst dataJson = opts.data ? JSON.stringify(opts.data) : null;\n\t\tconst id = ulid();\n\n\t\t// Upsert: if task already exists for this plugin+name, update it.\n\t\t// Guard: don't clobber a task that is currently executing.\n\t\tawait sql`\n\t\t\tINSERT INTO _emdash_cron_tasks (id, plugin_id, task_name, schedule, is_oneshot, data, next_run_at, status, enabled)\n\t\t\tVALUES (${id}, ${this.pluginId}, ${name}, ${opts.schedule}, ${oneshot ? 1 : 0}, ${dataJson}, ${nextRun}, 'idle', 1)\n\t\t\tON CONFLICT (plugin_id, task_name) DO UPDATE SET\n\t\t\t\tschedule = ${opts.schedule},\n\t\t\t\tis_oneshot = ${oneshot ? 1 : 0},\n\t\t\t\tdata = ${dataJson},\n\t\t\t\tnext_run_at = ${nextRun},\n\t\t\t\tstatus = CASE WHEN _emdash_cron_tasks.status = 'running' THEN 'running' ELSE 'idle' END,\n\t\t\t\tlocked_at = CASE WHEN _emdash_cron_tasks.status = 'running' THEN _emdash_cron_tasks.locked_at ELSE NULL END,\n\t\t\t\tenabled = 1\n\t\t`.execute(this.db);\n\n\t\tthis.reschedule();\n\t}\n\n\tasync cancel(name: string): Promise<void> {\n\t\tawait sql`\n\t\t\tDELETE FROM _emdash_cron_tasks\n\t\t\tWHERE plugin_id = ${this.pluginId} AND task_name = ${name}\n\t\t`.execute(this.db);\n\n\t\tthis.reschedule();\n\t}\n\n\tasync list(): Promise<CronTaskInfo[]> {\n\t\tconst rows = await sql<{\n\t\t\ttask_name: string;\n\t\t\tschedule: string;\n\t\t\tnext_run_at: string;\n\t\t\tlast_run_at: string | null;\n\t\t}>`\n\t\t\tSELECT task_name, schedule, next_run_at, last_run_at\n\t\t\tFROM _emdash_cron_tasks\n\t\t\tWHERE plugin_id = ${this.pluginId} AND enabled = 1\n\t\t\tORDER BY next_run_at ASC\n\t\t`.execute(this.db);\n\n\t\treturn rows.rows.map((row) => ({\n\t\t\tname: row.task_name,\n\t\t\tschedule: row.schedule,\n\t\t\tnextRunAt: row.next_run_at,\n\t\t\tlastRunAt: row.last_run_at,\n\t\t}));\n\t}\n}\n\n// ─── Cron task lifecycle helpers ────────────────────────────────────────────\n\n/**\n * Enable or disable all cron tasks for a plugin.\n * Called by admin disable/enable endpoints and PluginManager lifecycle.\n * Gracefully handles the cron table not existing yet (pre-migration).\n */\nexport async function setCronTasksEnabled(\n\tdb: Kysely<Database>,\n\tpluginId: string,\n\tenabled: boolean,\n): Promise<void> {\n\ttry {\n\t\tawait sql`\n\t\t\tUPDATE _emdash_cron_tasks\n\t\t\tSET enabled = ${enabled ? 1 : 0}\n\t\t\tWHERE plugin_id = ${pluginId}\n\t\t`.execute(db);\n\t} catch {\n\t\t// Cron table may not exist yet (pre-migration). Non-fatal.\n\t}\n}\n\n// ─── Cron utilities ────────────────────────────────────────────────────────\n\n/**\n * Compute the next fire time for a cron expression.\n * Supports standard cron (5-field), extended (6-field with seconds), and\n * aliases like @daily, @weekly, @hourly, @monthly, @yearly.\n */\nexport function nextCronTime(expression: string): string {\n\tconst job = new Cron(expression);\n\tconst next = job.nextRun();\n\tif (!next) {\n\t\tthrow new Error(`Invalid cron expression or no future run: \"${expression}\"`);\n\t}\n\treturn next.toISOString();\n}\n\n/**\n * Check whether a string is a valid cron expression.\n */\nfunction isCronExpression(schedule: string): boolean {\n\ttry {\n\t\t// Cron constructor validates; we discard the instance immediately.\n\t\tconst _cron = new Cron(schedule);\n\t\tvoid _cron;\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Check if a schedule string is a one-shot (ISO 8601 datetime) rather than\n * a recurring cron expression.\n *\n * Tries to parse as a cron expression first. Only if that fails does it\n * attempt Date.parse. This avoids misclassifying cron range expressions\n * like \"1-5 * * * *\" which Date.parse accepts as valid dates.\n */\nexport function isOneShot(schedule: string): boolean {\n\tif (schedule.startsWith(\"@\")) return false;\n\tif (isCronExpression(schedule)) return false;\n\treturn !isNaN(Date.parse(schedule));\n}\n\n/** Max length for a task name */\nconst MAX_TASK_NAME_LENGTH = 128;\n/** Task name pattern: alphanumeric, dashes, underscores */\nconst TASK_NAME_RE = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\n\n/**\n * Validate a cron task name.\n * Must be non-empty, ≤128 chars, alphanumeric with dashes/underscores.\n */\nexport function validateTaskName(name: string): void {\n\tif (!name || name.length > MAX_TASK_NAME_LENGTH) {\n\t\tthrow new Error(\n\t\t\t`Invalid task name: must be 1-${MAX_TASK_NAME_LENGTH} characters, got ${name.length}`,\n\t\t);\n\t}\n\tif (!TASK_NAME_RE.test(name)) {\n\t\tthrow new Error(\n\t\t\t`Invalid task name \"${name}\": must start with a letter and contain only letters, numbers, dashes, or underscores`,\n\t\t);\n\t}\n}\n\n/**\n * Validate a schedule string at registration time.\n * Must be a valid cron expression or a parseable ISO 8601 datetime.\n */\nexport function validateSchedule(schedule: string): void {\n\tif (!schedule || schedule.length > 256) {\n\t\tthrow new Error(`Invalid schedule: must be 1-256 characters, got ${schedule.length}`);\n\t}\n\n\t// Try cron first\n\tif (isCronExpression(schedule)) return;\n\n\tconst parsed = Date.parse(schedule);\n\tif (isNaN(parsed)) {\n\t\tthrow new Error(\n\t\t\t`Invalid schedule \"${schedule}\": must be a valid cron expression or ISO 8601 datetime`,\n\t\t);\n\t}\n}\n"],"m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AAK,SAAS,qBAC1B,OAAM,IAAI,MACT,gCAAgC,qBAAqB,mBAAmB,KAAK,SAC7E;AAEF,KAAI,CAAC,aAAa,KAAK,KAAK,CAC3B,OAAM,IAAI,MACT,sBAAsB,KAAK,uFAC3B;;;;;;AAQH,SAAgB,iBAAiB,UAAwB;AACxD,KAAI,CAAC,YAAY,SAAS,SAAS,IAClC,OAAM,IAAI,MAAM,mDAAmD,SAAS,SAAS;AAItF,KAAI,iBAAiB,SAAS,CAAE;CAEhC,MAAM,SAAS,KAAK,MAAM,SAAS;AACnC,KAAI,MAAM,OAAO,CAChB,OAAM,IAAI,MACT,qBAAqB,SAAS,yDAC9B"}
@@ -1,7 +1,7 @@
1
1
  import { t as validateIdentifier } from "./validate-VPnKoIzW.mjs";
2
- import { t as ContentRepository } from "./content-BIlVx-RX.mjs";
3
- import { t as MediaRepository } from "./media-JOf3pNkw.mjs";
4
- import { t as UserRepository } from "./user-C0um7wrg.mjs";
2
+ import { t as ContentRepository } from "./content-2PTDNnoh.mjs";
3
+ import { t as MediaRepository } from "./media-Bw0sA6rb.mjs";
4
+ import { t as UserRepository } from "./user-Db-Rti_z.mjs";
5
5
  import { sql } from "kysely";
6
6
 
7
7
  //#region src/api/handlers/dashboard.ts
@@ -102,4 +102,4 @@ async function fetchRecentItems(db, collections) {
102
102
 
103
103
  //#endregion
104
104
  export { handleDashboardStats as t };
105
- //# sourceMappingURL=dashboard-C-UYpps0.mjs.map
105
+ //# sourceMappingURL=dashboard-CYjpQZ6-.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dashboard-C-UYpps0.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GA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nB,UAAU;;;;;WAKN,IAAI,IAAI,MAAM,CAAC;;;;KAIrB,QAAQ,GAAG,EACC;GACb,CACF,EAIC,MAAM,CACN,UAAU,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE,aAAa,EAAE,aAAa,KAAK,EAAG,CAC5F,MAAM,GAAG,GAAG,CAGA,KAAK,SAAS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
1
+ {"version":3,"file":"dashboard-CYjpQZ6-.mjs","names":[],"sources":["../src/api/handlers/dashboard.ts"],"sourcesContent":["/**\n * Dashboard stats handler\n *\n * Returns summary data for the admin dashboard in a single request:\n * collection content counts, media count, user count, and recent\n * content across all collections.\n */\n\nimport { sql, type Kysely } from \"kysely\";\n\nimport { ContentRepository } from \"../../database/repositories/content.js\";\nimport { MediaRepository } from \"../../database/repositories/media.js\";\nimport { UserRepository } from \"../../database/repositories/user.js\";\nimport type { Database } from \"../../database/types.js\";\nimport { validateIdentifier } from \"../../database/validate.js\";\nimport type { ApiResult } from \"../types.js\";\n\nexport interface CollectionStats {\n\tslug: string;\n\tlabel: string;\n\ttotal: number;\n\tpublished: number;\n\tdraft: number;\n}\n\nexport interface RecentItem {\n\tid: string;\n\tcollection: string;\n\tcollectionLabel: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdatedAt: string;\n\tauthorId: string | null;\n}\n\nexport interface DashboardStats {\n\tcollections: CollectionStats[];\n\tmediaCount: number;\n\tuserCount: number;\n\trecentItems: RecentItem[];\n}\n\n/**\n * Fetch dashboard statistics.\n *\n * Queries are intentionally lightweight — counts use indexed columns,\n * and recent items are capped at 10.\n */\nexport async function handleDashboardStats(\n\tdb: Kysely<Database>,\n): Promise<ApiResult<DashboardStats>> {\n\ttry {\n\t\t// Discover collections from the system table\n\t\tconst collections = await db\n\t\t\t.selectFrom(\"_emdash_collections\")\n\t\t\t.select([\"slug\", \"label\"])\n\t\t\t.orderBy(\"slug\", \"asc\")\n\t\t\t.execute();\n\n\t\t// Gather per-collection counts in parallel\n\t\tconst contentRepo = new ContentRepository(db);\n\t\tconst collectionStats: CollectionStats[] = await Promise.all(\n\t\t\tcollections.map(async (col) => {\n\t\t\t\tconst stats = await contentRepo.getStats(col.slug);\n\t\t\t\treturn {\n\t\t\t\t\tslug: col.slug,\n\t\t\t\t\tlabel: col.label,\n\t\t\t\t\ttotal: stats.total,\n\t\t\t\t\tpublished: stats.published,\n\t\t\t\t\tdraft: stats.draft,\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\n\t\t// Media and user counts\n\t\tconst mediaRepo = new MediaRepository(db);\n\t\tconst userRepo = new UserRepository(db);\n\t\tconst [mediaCount, userCount] = await Promise.all([mediaRepo.count(), userRepo.count()]);\n\n\t\t// Recent items across all collections (last 10 updated, any status)\n\t\tconst recentItems = await fetchRecentItems(db, collections);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tcollections: collectionStats,\n\t\t\t\tmediaCount,\n\t\t\t\tuserCount,\n\t\t\t\trecentItems,\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Dashboard stats error:\", error);\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DASHBOARD_STATS_ERROR\",\n\t\t\t\tmessage: \"Failed to load dashboard statistics\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/** Raw row shape from the UNION ALL query — all snake_case. */\ninterface RecentItemRow {\n\tid: string;\n\tcollection: string;\n\tcollection_label: string;\n\ttitle: string;\n\tslug: string | null;\n\tstatus: string;\n\tupdated_at: string;\n\tauthor_id: string | null;\n}\n\n/**\n * Fetch the 10 most recently updated items across all collections.\n *\n * Uses UNION ALL over each ec_* table. The query is safe because\n * collection slugs come from the system table and are validated.\n *\n * `title` is not a standard column — it's a user-defined field. We query\n * `_emdash_fields` to discover which collections have one and fall back\n * to `slug` (which is always present) otherwise.\n */\nasync function fetchRecentItems(\n\tdb: Kysely<Database>,\n\tcollections: Array<{ slug: string; label: string }>,\n): Promise<RecentItem[]> {\n\tif (collections.length === 0) return [];\n\n\t// Discover which collections have a \"title\" column\n\tconst titleFields = await db\n\t\t.selectFrom(\"_emdash_fields as f\")\n\t\t.innerJoin(\"_emdash_collections as c\", \"c.id\", \"f.collection_id\")\n\t\t.select([\"c.slug as collection_slug\"])\n\t\t.where(\"f.slug\", \"=\", \"title\")\n\t\t.execute();\n\n\tconst collectionsWithTitle = new Set(titleFields.map((r) => r.collection_slug));\n\n\t// Issue one query per collection in parallel, then merge in JS.\n\t// A single UNION ALL across N collections trips D1's\n\t// SQLITE_LIMIT_COMPOUND_SELECT cap when N is large enough (#895);\n\t// per-collection queries side-step that. Each query fetches at most\n\t// 10 rows, so the merge handles at most N * 10 rows before slicing.\n\tconst perCollection = await Promise.all(\n\t\tcollections.map(async (col) => {\n\t\t\tvalidateIdentifier(col.slug);\n\t\t\tconst table = `ec_${col.slug}`;\n\t\t\tconst hasTitle = collectionsWithTitle.has(col.slug);\n\n\t\t\t// Use title column if it exists, otherwise fall back to slug, id.\n\t\t\t// All output uses snake_case to avoid SQLite quoting issues on D1.\n\t\t\tconst titleExpr = hasTitle ? sql`COALESCE(title, slug, id)` : sql`COALESCE(slug, id)`;\n\n\t\t\tconst result = await sql<RecentItemRow>`\n\t\t\t\tSELECT\n\t\t\t\t\tid,\n\t\t\t\t\t${sql.lit(col.slug)} AS collection,\n\t\t\t\t\t${sql.lit(col.label)} AS collection_label,\n\t\t\t\t\t${titleExpr} AS title,\n\t\t\t\t\tslug,\n\t\t\t\t\tstatus,\n\t\t\t\t\tupdated_at,\n\t\t\t\t\tauthor_id\n\t\t\t\tFROM ${sql.ref(table)}\n\t\t\t\tWHERE deleted_at IS NULL\n\t\t\t\tORDER BY updated_at DESC\n\t\t\t\tLIMIT 10\n\t\t\t`.execute(db);\n\t\t\treturn result.rows;\n\t\t}),\n\t);\n\n\t// Merge across collections, sort by updated_at desc, take top 10.\n\tconst merged = perCollection\n\t\t.flat()\n\t\t.toSorted((a, b) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0))\n\t\t.slice(0, 10);\n\n\t// Map snake_case DB rows to camelCase API shape\n\treturn merged.map((row) => ({\n\t\tid: row.id,\n\t\tcollection: row.collection,\n\t\tcollectionLabel: row.collection_label,\n\t\ttitle: row.title,\n\t\tslug: row.slug,\n\t\tstatus: row.status,\n\t\tupdatedAt: row.updated_at,\n\t\tauthorId: row.author_id,\n\t}));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,eAAsB,qBACrB,IACqC;AACrC,KAAI;EAEH,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,OAAO,CAAC,QAAQ,QAAQ,CAAC,CACzB,QAAQ,QAAQ,MAAM,CACtB,SAAS;EAGX,MAAM,cAAc,IAAI,kBAAkB,GAAG;EAC7C,MAAM,kBAAqC,MAAM,QAAQ,IACxD,YAAY,IAAI,OAAO,QAAQ;GAC9B,MAAM,QAAQ,MAAM,YAAY,SAAS,IAAI,KAAK;AAClD,UAAO;IACN,MAAM,IAAI;IACV,OAAO,IAAI;IACX,OAAO,MAAM;IACb,WAAW,MAAM;IACjB,OAAO,MAAM;IACb;IACA,CACF;EAGD,MAAM,YAAY,IAAI,gBAAgB,GAAG;EACzC,MAAM,WAAW,IAAI,eAAe,GAAG;EACvC,MAAM,CAAC,YAAY,aAAa,MAAM,QAAQ,IAAI,CAAC,UAAU,OAAO,EAAE,SAAS,OAAO,CAAC,CAAC;AAKxF,SAAO;GACN,SAAS;GACT,MAAM;IACL,aAAa;IACb;IACA;IACA,aARkB,MAAM,iBAAiB,IAAI,YAAY;IASzD;GACD;UACO,OAAO;AACf,UAAQ,MAAM,0BAA0B,MAAM;AAC9C,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;;;;;;;;;;;;;AA0BH,eAAe,iBACd,IACA,aACwB;AACxB,KAAI,YAAY,WAAW,EAAG,QAAO,EAAE;CAGvC,MAAM,cAAc,MAAM,GACxB,WAAW,sBAAsB,CACjC,UAAU,4BAA4B,QAAQ,kBAAkB,CAChE,OAAO,CAAC,4BAA4B,CAAC,CACrC,MAAM,UAAU,KAAK,QAAQ,CAC7B,SAAS;CAEX,MAAM,uBAAuB,IAAI,IAAI,YAAY,KAAK,MAAM,EAAE,gBAAgB,CAAC;AA2C/E,SApCsB,MAAM,QAAQ,IACnC,YAAY,IAAI,OAAO,QAAQ;AAC9B,qBAAmB,IAAI,KAAK;EAC5B,MAAM,QAAQ,MAAM,IAAI;EAKxB,MAAM,YAJW,qBAAqB,IAAI,IAAI,KAAK,GAItB,GAAG,8BAA8B,GAAG;AAiBjE,UAfe,MAAM,GAAkB;;;OAGnC,IAAI,IAAI,IAAI,KAAK,CAAC;OAClB,IAAI,IAAI,IAAI,MAAM,CAAC;OACnB,UAAU;;;;;WAKN,IAAI,IAAI,MAAM,CAAC;;;;KAIrB,QAAQ,GAAG,EACC;GACb,CACF,EAIC,MAAM,CACN,UAAU,GAAG,MAAO,EAAE,aAAa,EAAE,aAAa,IAAI,EAAE,aAAa,EAAE,aAAa,KAAK,EAAG,CAC5F,MAAM,GAAG,GAAG,CAGA,KAAK,SAAS;EAC3B,IAAI,IAAI;EACR,YAAY,IAAI;EAChB,iBAAiB,IAAI;EACrB,OAAO,IAAI;EACX,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,WAAW,IAAI;EACf,UAAU,IAAI;EACd,EAAE"}
@@ -16,6 +16,19 @@ interface QueryRecorder {
16
16
  route: string;
17
17
  method: string;
18
18
  phase: string;
19
+ /**
20
+ * Set once the recorder has been emitted, so a flush is idempotent.
21
+ * Without this, a fallback flush and the stream-end flush could both
22
+ * fire and double-emit the events.
23
+ */
24
+ flushed?: boolean;
25
+ /**
26
+ * Set when the response body is wrapped for stream-end metrics. The
27
+ * recorder is then flushed when the body finishes streaming (so it
28
+ * captures queries issued by components during streaming) rather than
29
+ * when middleware returns (headers ready, body not yet streamed).
30
+ */
31
+ deferredFlush?: boolean;
19
32
  }
20
33
  declare function createRecorder(route: string, method: string, phase: string): QueryRecorder;
21
34
  declare function recordEvent(rec: QueryRecorder, sql: string, params: readonly unknown[], durationMs: number): void;
@@ -24,6 +37,12 @@ declare function recordEvent(rec: QueryRecorder, sql: string, params: readonly u
24
37
  * harness pipes the child's stdout, filters lines beginning with
25
38
  * QUERY_LOG_PREFIX, and writes them to its own file. Using stdout means
26
39
  * the sink works uniformly in Node and in workerd (which has no fs).
40
+ *
41
+ * Idempotent: the first call emits and marks the recorder flushed, later
42
+ * calls no-op. For streamed responses the flush is deferred to stream end
43
+ * (see wrapBodyForStreamMetrics) so it captures queries issued while the
44
+ * body is still rendering; bodyless responses fall back to a flush when
45
+ * middleware returns.
27
46
  */
28
47
  declare function flushRecorder(rec: QueryRecorder): void;
29
48
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.d.mts","names":[],"sources":["../../src/database/instrumentation.ts"],"mappings":";;;cAkBa,aAAA;AAAA,cACA,gBAAA;AAAA,UAEI,UAAA;EAChB,GAAA;EACA,MAAA;EACA,UAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;AAAA;AAAA,UAGgB,aAAA;EAChB,MAAA,EAAQ,UAAA;EACR,KAAA;EACA,MAAA;EACA,KAAA;AAAA;AAAA,iBAGe,cAAA,CAAe,KAAA,UAAe,MAAA,UAAgB,KAAA,WAAgB,aAAA;AAAA,iBAI9D,WAAA,CACf,GAAA,EAAK,aAAA,EACL,GAAA,UACA,MAAA,sBACA,UAAA;;;;;AARD;;iBA0BgB,aAAA,CAAc,GAAA,EAAK,aAAA;;;;;;;;iBAcnB,wBAAA,CAAA;;;;;;;;iBAgCA,eAAA,CAAA,GAAmB,MAAA;;;AA9CnC;;;;;AAcA;iBA4CgB,SAAA,CAAU,KAAA"}
1
+ {"version":3,"file":"instrumentation.d.mts","names":[],"sources":["../../src/database/instrumentation.ts"],"mappings":";;;cAkBa,aAAA;AAAA,cACA,gBAAA;AAAA,UAEI,UAAA;EAChB,GAAA;EACA,MAAA;EACA,UAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;AAAA;AAAA,UAGgB,aAAA;EAChB,MAAA,EAAQ,UAAA;EACR,KAAA;EACA,MAAA;EACA,KAAA;EAHA;;;;;EASA,OAAA;EAOA;;;AAGD;;;EAHC,aAAA;AAAA;AAAA,iBAGe,cAAA,CAAe,KAAA,UAAe,MAAA,UAAgB,KAAA,WAAgB,aAAA;AAAA,iBAI9D,WAAA,CACf,GAAA,EAAK,aAAA,EACL,GAAA,UACA,MAAA,sBACA,UAAA;;;;AAJD;;;;;;;;;iBA4BgB,aAAA,CAAc,GAAA,EAAK,aAAA;;AAAnC;;;;;AAeA;iBAAgB,wBAAA,CAAA;;;;AAgChB;;;;iBAAgB,eAAA,CAAA,GAAmB,MAAA;AAYnC;;;;;;;;AAAA,iBAAgB,SAAA,CAAU,KAAA"}
@@ -26,9 +26,16 @@ function recordEvent(rec, sql, params, durationMs) {
26
26
  * harness pipes the child's stdout, filters lines beginning with
27
27
  * QUERY_LOG_PREFIX, and writes them to its own file. Using stdout means
28
28
  * the sink works uniformly in Node and in workerd (which has no fs).
29
+ *
30
+ * Idempotent: the first call emits and marks the recorder flushed, later
31
+ * calls no-op. For streamed responses the flush is deferred to stream end
32
+ * (see wrapBodyForStreamMetrics) so it captures queries issued while the
33
+ * body is still rendering; bodyless responses fall back to a flush when
34
+ * middleware returns.
29
35
  */
30
36
  function flushRecorder(rec) {
31
- if (rec.events.length === 0) return;
37
+ if (rec.flushed) return;
38
+ rec.flushed = true;
32
39
  for (const e of rec.events) console.log(`${QUERY_LOG_PREFIX} ${JSON.stringify(e)}`);
33
40
  }
34
41
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.mjs","names":[],"sources":["../../src/database/instrumentation.ts"],"sourcesContent":["/**\n * Query instrumentation\n *\n * Dev/test-only: captures every Kysely query executed inside a request,\n * tagged with the route, method, and a caller-supplied phase (e.g. \"cold\"\n * or \"warm\"). Events are emitted as prefixed NDJSON on stdout so the\n * harness can capture them from both Node and workerd — workerd has no\n * filesystem access, but `console.log` is portable.\n *\n * The recorder lives on the request context (AsyncLocalStorage). The\n * Kysely `log` hook reads the recorder at query time and appends an\n * event. When no recorder is attached, the hook is a null check.\n */\n\nimport type { LogEvent, Logger } from \"kysely\";\n\nimport { getRequestContext } from \"../request-context.js\";\n\nexport const QUERY_LOG_ENV = \"EMDASH_QUERY_LOG\";\nexport const QUERY_LOG_PREFIX = \"[emdash-query-log]\";\n\nexport interface QueryEvent {\n\tsql: string;\n\tparams: readonly unknown[];\n\tdurationMs: number;\n\troute: string;\n\tmethod: string;\n\tphase: string;\n}\n\nexport interface QueryRecorder {\n\tevents: QueryEvent[];\n\troute: string;\n\tmethod: string;\n\tphase: string;\n}\n\nexport function createRecorder(route: string, method: string, phase: string): QueryRecorder {\n\treturn { events: [], route, method, phase };\n}\n\nexport function recordEvent(\n\trec: QueryRecorder,\n\tsql: string,\n\tparams: readonly unknown[],\n\tdurationMs: number,\n): void {\n\trec.events.push({\n\t\tsql,\n\t\tparams,\n\t\tdurationMs,\n\t\troute: rec.route,\n\t\tmethod: rec.method,\n\t\tphase: rec.phase,\n\t});\n}\n\n/**\n * Emit all events from a recorder as prefixed NDJSON on stdout. The\n * harness pipes the child's stdout, filters lines beginning with\n * QUERY_LOG_PREFIX, and writes them to its own file. Using stdout means\n * the sink works uniformly in Node and in workerd (which has no fs).\n */\nexport function flushRecorder(rec: QueryRecorder): void {\n\tif (rec.events.length === 0) return;\n\tfor (const e of rec.events) {\n\t\tconsole.log(`${QUERY_LOG_PREFIX} ${JSON.stringify(e)}`);\n\t}\n}\n\n/**\n * Whether query instrumentation is enabled. Read at Kysely construction\n * time and middleware entry — the env var is a process-lifetime flag, not\n * per-request. Gated via `process.env` so adapters that ship env through\n * to the worker (e.g. Miniflare via wrangler.jsonc `vars` or host env\n * pass-through) can enable it at runtime.\n */\nexport function isInstrumentationEnabled(): boolean {\n\treturn Boolean(\n\t\ttypeof process !== \"undefined\" && process.env && process.env[QUERY_LOG_ENV] === \"1\",\n\t);\n}\n\nfunction kyselyLog(event: LogEvent): void {\n\tif (event.level !== \"query\") return;\n\tconst ctx = getRequestContext();\n\tif (!ctx) return;\n\tconst dur = event.queryDurationMillis;\n\tif (ctx.metrics) {\n\t\tconst m = ctx.metrics;\n\t\tm.dbCount += 1;\n\t\tm.dbTotalMs += dur;\n\t\tconst finishedAt = performance.now() - m.start;\n\t\tconst startedAt = finishedAt - dur;\n\t\tif (m.dbFirstOffset === null) m.dbFirstOffset = startedAt;\n\t\tm.dbLastOffset = finishedAt;\n\t}\n\tif (ctx.queryRecorder) {\n\t\trecordEvent(ctx.queryRecorder, event.query.sql, event.query.parameters, dur);\n\t}\n}\n\n/**\n * Returns a Kysely `log` callback. Always returns a function so per-request\n * counters (db.count, db.total, db.first, db.last) and the optional NDJSON\n * recorder both get fed. The cost over the previous \"undefined when off\"\n * behaviour is one `performance.now()` pair per query inside Kysely, which\n * is in the noise compared to any real query.\n */\nexport function kyselyLogOption(): Logger {\n\treturn kyselyLog;\n}\n\n/**\n * Record physical database round trips for the current request.\n *\n * Called by backends that batch (the DO SQL driver coalesces same-turn SELECTs\n * into one RPC), so we can see round-trip count separately from logical query\n * count (`dbCount`, bumped by the Kysely log hook). No-op outside a request or\n * when metrics aren't attached (e.g. migrations on the singleton).\n */\nexport function recordRpc(count = 1): void {\n\tconst ctx = getRequestContext();\n\tif (ctx?.metrics) ctx.metrics.rpcCount += count;\n}\n"],"mappings":";;;AAkBA,MAAa,gBAAgB;AAC7B,MAAa,mBAAmB;AAkBhC,SAAgB,eAAe,OAAe,QAAgB,OAA8B;AAC3F,QAAO;EAAE,QAAQ,EAAE;EAAE;EAAO;EAAQ;EAAO;;AAG5C,SAAgB,YACf,KACA,KACA,QACA,YACO;AACP,KAAI,OAAO,KAAK;EACf;EACA;EACA;EACA,OAAO,IAAI;EACX,QAAQ,IAAI;EACZ,OAAO,IAAI;EACX,CAAC;;;;;;;;AASH,SAAgB,cAAc,KAA0B;AACvD,KAAI,IAAI,OAAO,WAAW,EAAG;AAC7B,MAAK,MAAM,KAAK,IAAI,OACnB,SAAQ,IAAI,GAAG,iBAAiB,GAAG,KAAK,UAAU,EAAE,GAAG;;;;;;;;;AAWzD,SAAgB,2BAAoC;AACnD,QAAO,QACN,OAAO,YAAY,eAAe,QAAQ,OAAO,QAAQ,IAAI,mBAAmB,IAChF;;AAGF,SAAS,UAAU,OAAuB;AACzC,KAAI,MAAM,UAAU,QAAS;CAC7B,MAAM,MAAM,mBAAmB;AAC/B,KAAI,CAAC,IAAK;CACV,MAAM,MAAM,MAAM;AAClB,KAAI,IAAI,SAAS;EAChB,MAAM,IAAI,IAAI;AACd,IAAE,WAAW;AACb,IAAE,aAAa;EACf,MAAM,aAAa,YAAY,KAAK,GAAG,EAAE;EACzC,MAAM,YAAY,aAAa;AAC/B,MAAI,EAAE,kBAAkB,KAAM,GAAE,gBAAgB;AAChD,IAAE,eAAe;;AAElB,KAAI,IAAI,cACP,aAAY,IAAI,eAAe,MAAM,MAAM,KAAK,MAAM,MAAM,YAAY,IAAI;;;;;;;;;AAW9E,SAAgB,kBAA0B;AACzC,QAAO;;;;;;;;;;AAWR,SAAgB,UAAU,QAAQ,GAAS;CAC1C,MAAM,MAAM,mBAAmB;AAC/B,KAAI,KAAK,QAAS,KAAI,QAAQ,YAAY"}
1
+ {"version":3,"file":"instrumentation.mjs","names":[],"sources":["../../src/database/instrumentation.ts"],"sourcesContent":["/**\n * Query instrumentation\n *\n * Dev/test-only: captures every Kysely query executed inside a request,\n * tagged with the route, method, and a caller-supplied phase (e.g. \"cold\"\n * or \"warm\"). Events are emitted as prefixed NDJSON on stdout so the\n * harness can capture them from both Node and workerd — workerd has no\n * filesystem access, but `console.log` is portable.\n *\n * The recorder lives on the request context (AsyncLocalStorage). The\n * Kysely `log` hook reads the recorder at query time and appends an\n * event. When no recorder is attached, the hook is a null check.\n */\n\nimport type { LogEvent, Logger } from \"kysely\";\n\nimport { getRequestContext } from \"../request-context.js\";\n\nexport const QUERY_LOG_ENV = \"EMDASH_QUERY_LOG\";\nexport const QUERY_LOG_PREFIX = \"[emdash-query-log]\";\n\nexport interface QueryEvent {\n\tsql: string;\n\tparams: readonly unknown[];\n\tdurationMs: number;\n\troute: string;\n\tmethod: string;\n\tphase: string;\n}\n\nexport interface QueryRecorder {\n\tevents: QueryEvent[];\n\troute: string;\n\tmethod: string;\n\tphase: string;\n\t/**\n\t * Set once the recorder has been emitted, so a flush is idempotent.\n\t * Without this, a fallback flush and the stream-end flush could both\n\t * fire and double-emit the events.\n\t */\n\tflushed?: boolean;\n\t/**\n\t * Set when the response body is wrapped for stream-end metrics. The\n\t * recorder is then flushed when the body finishes streaming (so it\n\t * captures queries issued by components during streaming) rather than\n\t * when middleware returns (headers ready, body not yet streamed).\n\t */\n\tdeferredFlush?: boolean;\n}\n\nexport function createRecorder(route: string, method: string, phase: string): QueryRecorder {\n\treturn { events: [], route, method, phase };\n}\n\nexport function recordEvent(\n\trec: QueryRecorder,\n\tsql: string,\n\tparams: readonly unknown[],\n\tdurationMs: number,\n): void {\n\trec.events.push({\n\t\tsql,\n\t\tparams,\n\t\tdurationMs,\n\t\troute: rec.route,\n\t\tmethod: rec.method,\n\t\tphase: rec.phase,\n\t});\n}\n\n/**\n * Emit all events from a recorder as prefixed NDJSON on stdout. The\n * harness pipes the child's stdout, filters lines beginning with\n * QUERY_LOG_PREFIX, and writes them to its own file. Using stdout means\n * the sink works uniformly in Node and in workerd (which has no fs).\n *\n * Idempotent: the first call emits and marks the recorder flushed, later\n * calls no-op. For streamed responses the flush is deferred to stream end\n * (see wrapBodyForStreamMetrics) so it captures queries issued while the\n * body is still rendering; bodyless responses fall back to a flush when\n * middleware returns.\n */\nexport function flushRecorder(rec: QueryRecorder): void {\n\tif (rec.flushed) return;\n\trec.flushed = true;\n\tfor (const e of rec.events) {\n\t\tconsole.log(`${QUERY_LOG_PREFIX} ${JSON.stringify(e)}`);\n\t}\n}\n\n/**\n * Whether query instrumentation is enabled. Read at Kysely construction\n * time and middleware entry — the env var is a process-lifetime flag, not\n * per-request. Gated via `process.env` so adapters that ship env through\n * to the worker (e.g. Miniflare via wrangler.jsonc `vars` or host env\n * pass-through) can enable it at runtime.\n */\nexport function isInstrumentationEnabled(): boolean {\n\treturn Boolean(\n\t\ttypeof process !== \"undefined\" && process.env && process.env[QUERY_LOG_ENV] === \"1\",\n\t);\n}\n\nfunction kyselyLog(event: LogEvent): void {\n\tif (event.level !== \"query\") return;\n\tconst ctx = getRequestContext();\n\tif (!ctx) return;\n\tconst dur = event.queryDurationMillis;\n\tif (ctx.metrics) {\n\t\tconst m = ctx.metrics;\n\t\tm.dbCount += 1;\n\t\tm.dbTotalMs += dur;\n\t\tconst finishedAt = performance.now() - m.start;\n\t\tconst startedAt = finishedAt - dur;\n\t\tif (m.dbFirstOffset === null) m.dbFirstOffset = startedAt;\n\t\tm.dbLastOffset = finishedAt;\n\t}\n\tif (ctx.queryRecorder) {\n\t\trecordEvent(ctx.queryRecorder, event.query.sql, event.query.parameters, dur);\n\t}\n}\n\n/**\n * Returns a Kysely `log` callback. Always returns a function so per-request\n * counters (db.count, db.total, db.first, db.last) and the optional NDJSON\n * recorder both get fed. The cost over the previous \"undefined when off\"\n * behaviour is one `performance.now()` pair per query inside Kysely, which\n * is in the noise compared to any real query.\n */\nexport function kyselyLogOption(): Logger {\n\treturn kyselyLog;\n}\n\n/**\n * Record physical database round trips for the current request.\n *\n * Called by backends that batch (the DO SQL driver coalesces same-turn SELECTs\n * into one RPC), so we can see round-trip count separately from logical query\n * count (`dbCount`, bumped by the Kysely log hook). No-op outside a request or\n * when metrics aren't attached (e.g. migrations on the singleton).\n */\nexport function recordR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,QAAQ,YAAY"}
@@ -1,4 +1,4 @@
1
- import "../types-Del0VMij.mjs";
2
- import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration, t as MigrationStatus } from "../runner-C8vcbvCe.mjs";
3
- import { a as SqliteConfig, c as sqlite, i as PostgresConfig, n as DatabaseDialectType, o as libsql, r as LibsqlConfig, s as postgres, t as DatabaseDescriptor } from "../adapters-BxSmgtbF.mjs";
1
+ import "../types-B-gIxFCE.mjs";
2
+ import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration, t as MigrationStatus } from "../runner-CEtq-6Sm.mjs";
3
+ import { a as SqliteConfig, c as sqlite, i as PostgresConfig, n as DatabaseDialectType, o as libsql, r as LibsqlConfig, s as postgres, t as DatabaseDescriptor } from "../adapters-DAAjOID4.mjs";
4
4
  export { type DatabaseDescriptor, type DatabaseDialectType, type LibsqlConfig, type MigrationStatus, type PostgresConfig, type SqliteConfig, getMigrationStatus, libsql, postgres, rollbackMigration, runMigrations, sqlite };
package/dist/db/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration } from "../runner--4wMWwKM.mjs";
1
+ import { i as runMigrations, n as getMigrationStatus, r as rollbackMigration } from "../runner-DYYnW530.mjs";
2
2
  import "../dialect-helpers-DRI5pyY3.mjs";
3
3
 
4
4
  //#region src/db/adapters.ts
@@ -1,4 +1,4 @@
1
- import { r as LibsqlConfig } from "../adapters-BxSmgtbF.mjs";
1
+ import { r as LibsqlConfig } from "../adapters-DAAjOID4.mjs";
2
2
  import { Dialect } from "kysely";
3
3
 
4
4
  //#region src/db/libsql.d.ts
@@ -1,4 +1,4 @@
1
- import { i as PostgresConfig } from "../adapters-BxSmgtbF.mjs";
1
+ import { i as PostgresConfig } from "../adapters-DAAjOID4.mjs";
2
2
  import { PostgresDialect } from "kysely";
3
3
 
4
4
  //#region src/db/postgres.d.ts
@@ -1,4 +1,4 @@
1
- import { a as SqliteConfig } from "../adapters-BxSmgtbF.mjs";
1
+ import { a as SqliteConfig } from "../adapters-DAAjOID4.mjs";
2
2
  import { Dialect } from "kysely";
3
3
 
4
4
  //#region src/db/sqlite.d.ts
@@ -50,4 +50,4 @@ function isMissingTableError(error) {
50
50
 
51
51
  //#endregion
52
52
  export { isMissingTableError as n, isMissingColumnError as t };
53
- //# sourceMappingURL=db-errors-BluWkwGI.mjs.map
53
+ //# sourceMappingURL=db-errors-UXB1CK42.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"db-errors-BluWkwGI.mjs","names":[],"sources":["../src/utils/db-errors.ts"],"sourcesContent":["/**\n * Shared detection helpers for database-layer error messages.\n *\n * Different SQL dialects phrase \"table or relation does not exist\" differently:\n *\n * - SQLite / D1: \"no such table: foo\"\n * - PostgreSQL: 'relation \"foo\" does not exist'\n * 'table \"foo\" does not exist'\n * - MySQL (future): \"Table 'db.foo' doesn't exist\"\n *\n * Runtime code paths that short-circuit on missing tables (pre-migration\n * probes, optional feature tables, etc.) should use these helpers rather\n * than hand-rolling string matches per call-site.\n */\n\n/**\n * Extract a lowercase error message from any unknown value, safely.\n */\nfunction messageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message.toLowerCase();\n\tif (typeof error === \"string\") return error.toLowerCase();\n\treturn \"\";\n}\n\n/**\n * Returns true when `error` is a \"column does not exist\" error.\n * Used to handle where filters that reference non-existent field names\n * gracefully (return empty results) instead of propagating a SQL error.\n */\nexport function isMissingColumnError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1: \"no such column: foo\"\n\tif (message.includes(\"no such column\")) return true;\n\n\t// PostgreSQL SQLSTATE 42703: 'column \"foo\" does not exist'\n\t// Exclude \"relation\" to avoid false positives on table names containing \"column\"\n\tif (\n\t\tmessage.includes(\"does not exist\") &&\n\t\tmessage.includes(\"column\") &&\n\t\t!message.includes(\"relation\")\n\t)\n\t\treturn true;\n\n\treturn false;\n}\n\n/**\n * Returns true when `error` is a \"table does not exist\" error across the\n * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime\n * probes to treat pre-migration databases as empty without logging a scary\n * warning, while still propagating unrelated errors (permissions, connection\n * loss, syntax issues) to callers.\n */\nexport function isMissingTableError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1\n\tif (message.includes(\"no such table\")) return true;\n\n\t// PostgreSQL (and some MySQL variants): \"relation ... does not exist\" /\n\t// \"table ... does not exist\" / \"doesn't exist\".\n\tif (message.includes(\"does not exist\") || message.includes(\"doesn't exist\")) {\n\t\treturn message.includes(\"relation\") || message.includes(\"table\");\n\t}\n\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,OAAwB;AAC1C,KAAI,iBAAiB,MAAO,QAAO,MAAM,QAAQ,aAAa;AAC9D,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,aAAa;AACzD,QAAO;;;;;;;AAQR,SAAgB,qBAAqB,OAAyB;CAC7D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,iBAAiB,CAAE,QAAO;AAI/C,KACC,QAAQ,SAAS,iBAAiB,IAClC,QAAQ,SAAS,SAAS,IAC1B,CAAC,QAAQ,SAAS,WAAW,CAE7B,QAAO;AAER,QAAO;;;;;;;;;AAUR,SAAgB,oBAAoB,OAAyB;CAC5D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,gBAAgB,CAAE,QAAO;AAI9C,KAAI,QAAQ,SAAS,iBAAiB,IAAI,QAAQ,SAAS,gBAAgB,CAC1E,QAAO,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,QAAQ;AAGjE,QAAO"}
1
+ {"version":3,"file":"db-errors-UXB1CK42.mjs","names":[],"sources":["../src/utils/db-errors.ts"],"sourcesContent":["/**\n * Shared detection helpers for database-layer error messages.\n *\n * Different SQL dialects phrase \"table or relation does not exist\" differently:\n *\n * - SQLite / D1: \"no such table: foo\"\n * - PostgreSQL: 'relation \"foo\" does not exist'\n * 'table \"foo\" does not exist'\n * - MySQL (future): \"Table 'db.foo' doesn't exist\"\n *\n * Runtime code paths that short-circuit on missing tables (pre-migration\n * probes, optional feature tables, etc.) should use these helpers rather\n * than hand-rolling string matches per call-site.\n */\n\n/**\n * Extract a lowercase error message from any unknown value, safely.\n */\nfunction messageOf(error: unknown): string {\n\tif (error instanceof Error) return error.message.toLowerCase();\n\tif (typeof error === \"string\") return error.toLowerCase();\n\treturn \"\";\n}\n\n/**\n * Returns true when `error` is a \"column does not exist\" error.\n * Used to handle where filters that reference non-existent field names\n * gracefully (return empty results) instead of propagating a SQL error.\n */\nexport function isMissingColumnError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1: \"no such column: foo\"\n\tif (message.includes(\"no such column\")) return true;\n\n\t// PostgreSQL SQLSTATE 42703: 'column \"foo\" does not exist'\n\t// Exclude \"relation\" to avoid false positives on table names containing \"column\"\n\tif (\n\t\tmessage.includes(\"does not exist\") &&\n\t\tmessage.includes(\"column\") &&\n\t\t!message.includes(\"relation\")\n\t)\n\t\treturn true;\n\n\treturn false;\n}\n\n/**\n * Returns true when `error` is a \"table does not exist\" error across the\n * dialects EmDash supports (D1/SQLite and PostgreSQL). Used by runtime\n * probes to treat pre-migration databases as empty without logging a scary\n * warning, while still propagating unrelated errors (permissions, connection\n * loss, syntax issues) to callers.\n */\nexport function isMissingTableError(error: unknown): boolean {\n\tconst message = messageOf(error);\n\tif (!message) return false;\n\n\t// SQLite / D1\n\tif (message.includes(\"no such table\")) return true;\n\n\t// PostgreSQL (and some MySQL variants): \"relation ... does not exist\" /\n\t// \"table ... does not exist\" / \"doesn't exist\".\n\tif (message.includes(\"does not exist\") || message.includes(\"doesn't exist\")) {\n\t\treturn message.includes(\"relation\") || message.includes(\"table\");\n\t}\n\n\treturn false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,OAAwB;AAC1C,KAAI,iBAAiB,MAAO,QAAO,MAAM,QAAQ,aAAa;AAC9D,KAAI,OAAO,UAAU,SAAU,QAAO,MAAM,aAAa;AACzD,QAAO;;;;;;;AAQR,SAAgB,qBAAqB,OAAyB;CAC7D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,iBAAiB,CAAE,QAAO;AAI/C,KACC,QAAQ,SAAS,iBAAiB,IAClC,QAAQ,SAAS,SAAS,IAC1B,CAAC,QAAQ,SAAS,WAAW,CAE7B,QAAO;AAER,QAAO;;;;;;;;;AAUR,SAAgB,oBAAoB,OAAyB;CAC5D,MAAM,UAAU,UAAU,MAAM;AAChC,KAAI,CAAC,QAAS,QAAO;AAGrB,KAAI,QAAQ,SAAS,gBAAgB,CAAE,QAAO;AAI9C,KAAI,QAAQ,SAAS,iBAAiB,IAAI,QAAQ,SAAS,gBAAgB,CAC1E,QAAO,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,QAAQ;AAGjE,QAAO"}
@@ -78,4 +78,4 @@ const defaultSeed = {
78
78
 
79
79
  //#endregion
80
80
  export { defaultSeed as t };
81
- //# sourceMappingURL=default-NHGuJzQ3.mjs.map
81
+ //# sourceMappingURL=default-CeRG-Ot4.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"default-NHGuJzQ3.mjs","names":[],"sources":["../src/seed/default.ts"],"sourcesContent":["/**\n * Default seed applied when no user seed file exists.\n *\n * Provides the baseline schema every EmDash site needs:\n * posts, pages, categories, and tags.\n */\n\nimport type { SeedFile } from \"./types.js\";\n\nexport const defaultSeed: SeedFile = {\n\tversion: \"1\",\n\tmeta: {\n\t\tname: \"Default\",\n\t\tdescription: \"Posts and pages with categories and tags\",\n\t},\n\tcollections: [\n\t\t{\n\t\t\tslug: \"posts\",\n\t\t\tlabel: \"Posts\",\n\t\t\tlabelSingular: \"Post\",\n\t\t\tsupports: [\"drafts\", \"revisions\", \"search\"],\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tslug: \"title\",\n\t\t\t\t\tlabel: \"Title\",\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"featured_image\",\n\t\t\t\t\tlabel: \"Featured Image\",\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"content\",\n\t\t\t\t\tlabel: \"Content\",\n\t\t\t\t\ttype: \"portableText\",\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"excerpt\",\n\t\t\t\t\tlabel: \"Excerpt\",\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tslug: \"pages\",\n\t\t\tlabel: \"Pages\",\n\t\t\tlabelSingular: \"Page\",\n\t\t\tsupports: [\"drafts\", \"revisions\", \"search\"],\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tslug: \"title\",\n\t\t\t\t\tlabel: \"Title\",\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"content\",\n\t\t\t\t\tlabel: \"Content\",\n\t\t\t\t\ttype: \"portableText\",\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n\ttaxonomies: [\n\t\t{\n\t\t\tname: \"category\",\n\t\t\tlabel: \"Categories\",\n\t\t\tlabelSingular: \"Category\",\n\t\t\thierarchical: true,\n\t\t\tcollections: [\"posts\"],\n\t\t},\n\t\t{\n\t\t\tname: \"tag\",\n\t\t\tlabel: \"Tags\",\n\t\t\tlabelSingular: \"Tag\",\n\t\t\thierarchical: false,\n\t\t\tcollections: [\"posts\"],\n\t\t},\n\t],\n};\n"],"mappings":";AASA,MAAa,cAAwB;CACpC,SAAS;CACT,MAAM;EACL,MAAM;EACN,aAAa;EACb;CACD,aAAa,CACZ;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,UAAU;GAAC;GAAU;GAAa;GAAS;EAC3C,QAAQ;GACP;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,YAAY;IACZ;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN,YAAY;IACZ;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN;GACD;EACD,EACD;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,UAAU;GAAC;GAAU;GAAa;GAAS;EAC3C,QAAQ,CACP;GACC,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,YAAY;GACZ,EACD;GACC,MAAM;GACN,OAAO;GACP,MAAM;GACN,YAAY;GACZ,CACD;EACD,CACD;CACD,YAAY,CACX;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,cAAc;EACd,aAAa,CAAC,QAAQ;EACtB,EACD;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,cAAc;EACd,aAAa,CAAC,QAAQ;EACtB,CACD;CACD"}
1
+ {"version":3,"file":"default-CeRG-Ot4.mjs","names":[],"sources":["../src/seed/default.ts"],"sourcesContent":["/**\n * Default seed applied when no user seed file exists.\n *\n * Provides the baseline schema every EmDash site needs:\n * posts, pages, categories, and tags.\n */\n\nimport type { SeedFile } from \"./types.js\";\n\nexport const defaultSeed: SeedFile = {\n\tversion: \"1\",\n\tmeta: {\n\t\tname: \"Default\",\n\t\tdescription: \"Posts and pages with categories and tags\",\n\t},\n\tcollections: [\n\t\t{\n\t\t\tslug: \"posts\",\n\t\t\tlabel: \"Posts\",\n\t\t\tlabelSingular: \"Post\",\n\t\t\tsupports: [\"drafts\", \"revisions\", \"search\"],\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tslug: \"title\",\n\t\t\t\t\tlabel: \"Title\",\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"featured_image\",\n\t\t\t\t\tlabel: \"Featured Image\",\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"content\",\n\t\t\t\t\tlabel: \"Content\",\n\t\t\t\t\ttype: \"portableText\",\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"excerpt\",\n\t\t\t\t\tlabel: \"Excerpt\",\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tslug: \"pages\",\n\t\t\tlabel: \"Pages\",\n\t\t\tlabelSingular: \"Page\",\n\t\t\tsupports: [\"drafts\", \"revisions\", \"search\"],\n\t\t\tfields: [\n\t\t\t\t{\n\t\t\t\t\tslug: \"title\",\n\t\t\t\t\tlabel: \"Title\",\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tslug: \"content\",\n\t\t\t\t\tlabel: \"Content\",\n\t\t\t\t\ttype: \"portableText\",\n\t\t\t\t\tsearchable: true,\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n\ttaxonomies: [\n\t\t{\n\t\t\tname: \"category\",\n\t\t\tlabel: \"Categories\",\n\t\t\tlabelSingular: \"Category\",\n\t\t\thierarchical: true,\n\t\t\tcollections: [\"posts\"],\n\t\t},\n\t\t{\n\t\t\tname: \"tag\",\n\t\t\tlabel: \"Tags\",\n\t\t\tlabelSingular: \"Tag\",\n\t\t\thierarchical: false,\n\t\t\tcollections: [\"posts\"],\n\t\t},\n\t],\n};\n"],"mappings":";AASA,MAAa,cAAwB;CACpC,SAAS;CACT,MAAM;EACL,MAAM;EACN,aAAa;EACb;CACD,aAAa,CACZ;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,UAAU;GAAC;GAAU;GAAa;GAAS;EAC3C,QAAQ;GACP;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN,UAAU;IACV,YAAY;IACZ;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN,YAAY;IACZ;GACD;IACC,MAAM;IACN,OAAO;IACP,MAAM;IACN;GACD;EACD,EACD;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,UAAU;GAAC;GAAU;GAAa;GAAS;EAC3C,QAAQ,CACP;GACC,MAAM;GACN,OAAO;GACP,MAAM;GACN,UAAU;GACV,YAAY;GACZ,EACD;GACC,MAAM;GACN,OAAO;GACP,MAAM;GACN,YAAY;GACZ,CACD;EACD,CACD;CACD,YAAY,CACX;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,cAAc;EACd,aAAa,CAAC,QAAQ;EACtB,EACD;EACC,MAAM;EACN,OAAO;EACP,eAAe;EACf,cAAc;EACd,aAAa,CAAC,QAAQ;EACtB,CACD;CACD"}
@@ -1,7 +1,7 @@
1
- import { t as withTransaction } from "./transaction-x2tJQ-A1.mjs";
2
- import { a as hashApiToken, n as VALID_SCOPES, r as generatePrefixedToken, t as TOKEN_PREFIXES } from "./api-tokens-C7ywRx7l.mjs";
3
- import { o as lookupOAuthClient } from "./oauth-clients-BC873NCV.mjs";
4
- import { t as lookupUserRoleAndStatus } from "./oauth-user-lookup-e4wOvDud.mjs";
1
+ import { t as withTransaction } from "./transaction-qfqpPVpu.mjs";
2
+ import { a as hashApiToken, n as VALID_SCOPES, r as generatePrefixedToken, t as TOKEN_PREFIXES } from "./api-tokens-B4BQybOp.mjs";
3
+ import { o as lookupOAuthClient } from "./oauth-clients-C9SYwEbZ.mjs";
4
+ import { t as lookupUserRoleAndStatus } from "./oauth-user-lookup-SHsWRlG9.mjs";
5
5
  import { clampScopes } from "@emdash-cms/auth";
6
6
  import { generateCodeVerifier } from "arctic";
7
7
 
@@ -464,4 +464,4 @@ async function handleTokenRevoke(db, input) {
464
464
 
465
465
  //#endregion
466
466
  export { handleTokenRevoke as a, handleTokenRefresh as i, handleDeviceCodeRequest as n, handleDeviceTokenExchange as r, handleDeviceAuthorize as t };
467
- //# sourceMappingURL=device-flow-BQApWgnW.mjs.map
467
+ //# sourceMappingURL=device-flow-DENDCQ9F.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"device-flow-BQApWgnW.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\tTOKEN_PREFIXES,\n\tVALID_SCOPES,\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\tconst validSet = new Set<string>(VALID_SCOPES);\n\treturn requested.filter((s) => validSet.has(s));\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;CAE3B,MAAM,WAAW,IAAI,IAAY,aAAa;AAC9C,QAAO,UAAU,QAAQ,MAAM,SAAS,IAAI,EAAE,CAAC;;;;;;;;AAahD,eAAsB,wBACrB,IACA,OAIA,iBACyC;AAC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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-DENDCQ9F.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\tTOKEN_PREFIXES,\n\tVALID_SCOPES,\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\tconst validSet = new Set<string>(VALID_SCOPES);\n\treturn requested.filter((s) => validSet.has(s));\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;CAE3B,MAAM,WAAW,IAAI,IAAY,aAAa;AAC9C,QAAO,UAAU,QAAQ,MAAM,SAAS,IAAI,EAAE,CAAC;;;;;;;;AAahD,eAAsB,wBACrB,IACA,OAIA,iBACyC;AACzC,KAAI;EAQH,MAAM,SAAS,gBADS,MAAM,QAAQ,MAAM,MAAM,MAAM,IAAI,CAAC,OAAO,QAAQ,GAAG,EAAE,CA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AC,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"}
@@ -47,4 +47,4 @@ async function devConsoleEmailDeliver(event, _ctx) {
47
47
 
48
48
  //#endregion
49
49
  export { getDevEmails as i, clearDevEmails as n, devConsoleEmailDeliver as r, DEV_CONSOLE_EMAIL_PLUGIN_ID as t };
50
- //# sourceMappingURL=email-console-BbU3RbWv.mjs.map
50
+ //# sourceMappingURL=email-console-DJP32ucW.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"email-console-BbU3RbWv.mjs","names":[],"sources":["../src/plugins/email-console.ts"],"sourcesContent":["/**\n * Dev Console Email Provider\n *\n * Built-in plugin that registers email:deliver as an exclusive hook.\n * Logs emails to console and stores them in memory (capped at 100).\n * Auto-activated when import.meta.env.DEV is true and no other provider is selected.\n *\n */\n\nimport type { EmailDeliverEvent, EmailMessage, PluginContext } from \"./types.js\";\n\n/** Plugin ID for the dev console email provider */\nexport const DEV_CONSOLE_EMAIL_PLUGIN_ID = \"emdash-console-email\";\n\n/** Maximum number of emails to keep in memory */\nconst MAX_STORED_EMAILS = 100;\n\n/**\n * Stored email record (in-memory only)\n */\nexport interface StoredEmail {\n\tmessage: EmailMessage;\n\tsource: string;\n\tsentAt: string;\n}\n\n/**\n * In-memory store for dev emails.\n * Uses globalThis so the same array is shared across Vite SSR module\n * instances (the runtime and the route handler may load separate copies\n * of this module, but globalThis is always the same object).\n */\nconst GLOBAL_KEY = Symbol.for(\"emdash:dev-emails\");\nconst g = globalThis as Record<symbol, unknown>;\nconst storedEmails: StoredEmail[] = (() => {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\tconst existing = g[GLOBAL_KEY] as StoredEmail[] | undefined;\n\tif (existing) return existing;\n\tconst fresh: StoredEmail[] = [];\n\tg[GLOBAL_KEY] = fresh;\n\treturn fresh;\n})();\n\n/**\n * Get all stored dev emails (most recent first).\n */\nexport function getDevEmails(): StoredEmail[] {\n\treturn storedEmails.toReversed();\n}\n\n/**\n * Clear all stored dev emails.\n */\nexport function clearDevEmails(): void {\n\tstoredEmails.length = 0;\n}\n\n/**\n * The email:deliver handler for the dev console provider.\n * Logs to console and stores in memory.\n */\nexport async function devConsoleEmailDeliver(\n\tevent: EmailDeliverEvent,\n\t_ctx: PluginContext,\n): Promise<void> {\n\tconst { message, source } = event;\n\n\tconsole.log(\n\t\t`\\n📧 [dev-email] Email sent\\n` +\n\t\t\t` From: ${source}\\n` +\n\t\t\t` To: ${message.to}\\n` +\n\t\t\t` Subject: ${message.subject}\\n` +\n\t\t\t` Text: ${message.text.slice(0, 200)}${message.text.length > 200 ? \"...\" : \"\"}\\n`,\n\t);\n\n\t// Store the email\n\tstoredEmails.push({\n\t\tmessage,\n\t\tsource,\n\t\tsentAt: new Date().toISOString(),\n\t});\n\n\t// Cap at MAX_STORED_EMAILS\n\twhile (storedEmails.length > MAX_STORED_EMAILS) {\n\t\tstoredEmails.shift();\n\t}\n}\n"],"mappings":";;AAYA,MAAa,8BAA8B;;AAG3C,MAAM,oBAAoB;;;;;;;AAiB1B,MAAM,aAAa,OAAO,IAAI,oBAAoB;AAClD,MAAM,IAAI;AACV,MAAM,sBAAqC;CAE1C,MAAM,WAAW,EAAE;AACnB,KAAI,SAAU,QAAO;CACrB,MAAM,QAAuB,EAAE;AAC/B,GAAE,cAAc;AAChB,QAAO;IACJ;;;;AAKJ,SAAgB,eAA8B;AAC7C,QAAO,aAAa,YAAY;;;;;AAMjC,SAAgB,iBAAuB;AACtC,cAAa,SAAS;;;;;;AAOvB,eAAsB,uBACrB,OACA,MACgB;CAChB,MAAM,EAAE,SAAS,WAAW;AAE5B,SAAQ,IACP,yCACa,OAAO,WACT,QAAQ,GAAG,gBACN,QAAQ,QAAQ,aACnB,QAAQ,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,KAAK,SAAS,MAAM,QAAQ,GAAG,IACjF;AAGD,cAAa,KAAK;EACjB;EACA;EACA,yBAAQ,IAAI,MAAM,EAAC,aAAa;EAChC,CAAC;AAGF,QAAO,aAAa,SAAS,kBAC5B,cAAa,OAAO"}
1
+ {"version":3,"file":"email-console-DJP32ucW.mjs","names":[],"sources":["../src/plugins/email-console.ts"],"sourcesContent":["/**\n * Dev Console Email Provider\n *\n * Built-in plugin that registers email:deliver as an exclusive hook.\n * Logs emails to console and stores them in memory (capped at 100).\n * Auto-activated when import.meta.env.DEV is true and no other provider is selected.\n *\n */\n\nimport type { EmailDeliverEvent, EmailMessage, PluginContext } from \"./types.js\";\n\n/** Plugin ID for the dev console email provider */\nexport const DEV_CONSOLE_EMAIL_PLUGIN_ID = \"emdash-console-email\";\n\n/** Maximum number of emails to keep in memory */\nconst MAX_STORED_EMAILS = 100;\n\n/**\n * Stored email record (in-memory only)\n */\nexport interface StoredEmail {\n\tmessage: EmailMessage;\n\tsource: string;\n\tsentAt: string;\n}\n\n/**\n * In-memory store for dev emails.\n * Uses globalThis so the same array is shared across Vite SSR module\n * instances (the runtime and the route handler may load separate copies\n * of this module, but globalThis is always the same object).\n */\nconst GLOBAL_KEY = Symbol.for(\"emdash:dev-emails\");\nconst g = globalThis as Record<symbol, unknown>;\nconst storedEmails: StoredEmail[] = (() => {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\tconst existing = g[GLOBAL_KEY] as StoredEmail[] | undefined;\n\tif (existing) return existing;\n\tconst fresh: StoredEmail[] = [];\n\tg[GLOBAL_KEY] = fresh;\n\treturn fresh;\n})();\n\n/**\n * Get all stored dev emails (most recent first).\n */\nexport function getDevEmails(): StoredEmail[] {\n\treturn storedEmails.toReversed();\n}\n\n/**\n * Clear all stored dev emails.\n */\nexport function clearDevEmails(): void {\n\tstoredEmails.length = 0;\n}\n\n/**\n * The email:deliver handler for the dev console provider.\n * Logs to console and stores in memory.\n */\nexport async function devConsoleEmailDeliver(\n\tevent: EmailDeliverEvent,\n\t_ctx: PluginContext,\n): Promise<void> {\n\tconst { message, source } = event;\n\n\tconsole.log(\n\t\t`\\n📧 [dev-email] Email sent\\n` +\n\t\t\t` From: ${source}\\n` +\n\t\t\t` To: ${message.to}\\n` +\n\t\t\t` Subject: ${message.subject}\\n` +\n\t\t\t` Text: ${message.text.slice(0, 200)}${message.text.length > 200 ? \"...\" : \"\"}\\n`,\n\t);\n\n\t// Store the email\n\tstoredEmails.push({\n\t\tmessage,\n\t\tsource,\n\t\tsentAt: new Date().toISOString(),\n\t});\n\n\t// Cap at MAX_STORED_EMAILS\n\twhile (storedEmails.length > MAX_STORED_EMAILS) {\n\t\tstoredEmails.shift();\n\t}\n}\n"],"mappings":";;AAYA,MAAa,8BAA8B;;AAG3C,MAAM,oBAAoB;;;;;;;AAiB1B,MAAM,aAAa,OAAO,IAAI,oBAAoB;AAClD,MAAM,IAAI;AACV,MAAM,sBAAqC;CAE1C,MAAM,WAAW,EAAE;AACnB,KAAI,SAAU,QAAO;CACrB,MAAM,QAAuB,EAAE;AAC/B,GAAE,cAAc;AAChB,QAAO;IACJ;;;;AAKJ,SAAgB,eAA8B;AAC7C,QAAO,aAAa,YAAY;;;;;AAMjC,SAAgB,iBAAuB;AACtC,cAAa,SAAS;;;;;;AAOvB,eAAsB,uBACrB,OACA,MACgB;CAChB,MAAM,EAAE,SAAS,WAAW;AAE5B,SAAQ,IACP,yCACa,OAAO,WACT,QAAQ,GAAG,gBACN,QAAQ,QAAQ,aACnB,QAAQ,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,KAAK,SAAS,MAAM,QAAQ,GAAG,IACjF;AAGD,cAAa,KAAK;EACjB;EACA;EACA,yBAAQ,IAAI,MAAM,EAAC,aAAa;EAChC,CAAC;AAGF,QAAO,aAAa,SAAS,kBAC5B,cAAa,OAAO"}
@@ -1,4 +1,4 @@
1
- import { n as InvalidCursorError } from "./types-BXSUSAjt.mjs";
1
+ import { n as InvalidCursorError } from "./types-DXOIbece.mjs";
2
2
 
3
3
  //#region src/api/errors.ts
4
4
  /**
@@ -448,4 +448,4 @@ function unwrapResult(result, successStatus = 200) {
448
448
 
449
449
  //#endregion
450
450
  export { unwrapResult as a, requireDb as i, apiSuccess as n, mapErrorStatus as o, handleError as r, apiError as t };
451
- //# sourceMappingURL=error-CNn_w7jf.mjs.map
451
+ //# sourceMappingURL=error-Bl6kZgtt.mjs.map