emdash 0.37.0 → 0.38.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 (811) hide show
  1. package/dist/{activation-K0kGBWuJ.mjs → activation-DyNTe_Tl.mjs} +3 -3
  2. package/dist/{activation-K0kGBWuJ.mjs.map → activation-DyNTe_Tl.mjs.map} +1 -1
  3. package/dist/{adapters-BDQwg236.d.mts → adapters-DCEgOBXi.d.mts} +1 -1
  4. package/dist/{adapters-BDQwg236.d.mts.map → adapters-DCEgOBXi.d.mts.map} +1 -1
  5. package/dist/{allowed-origins-BGglilcs.mjs → allowed-origins-GFUVavRj.mjs} +2 -2
  6. package/dist/{allowed-origins-BGglilcs.mjs.map → allowed-origins-GFUVavRj.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -3
  8. package/dist/api/route-utils.mjs +23 -22
  9. package/dist/api/route-utils.mjs.map +1 -1
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +5 -5
  12. package/dist/{api-Dz6rgoa3.mjs → api-BvxJmnFY.mjs} +141 -87
  13. package/dist/api-BvxJmnFY.mjs.map +1 -0
  14. package/dist/{api-tokens-BSsQACNe.mjs → api-tokens-xpGqMHrC.mjs} +2 -2
  15. package/dist/{api-tokens-BSsQACNe.mjs.map → api-tokens-xpGqMHrC.mjs.map} +1 -1
  16. package/dist/{apply-B4SIOxR1.mjs → apply-DLmM3R7f.mjs} +25 -21
  17. package/dist/apply-DLmM3R7f.mjs.map +1 -0
  18. package/dist/{config-it29yDLA.mjs → artifact-fetch-P2JXVwOq.mjs} +8 -199
  19. package/dist/artifact-fetch-P2JXVwOq.mjs.map +1 -0
  20. package/dist/astro/index.d.mts +12 -12
  21. package/dist/astro/index.d.mts.map +1 -1
  22. package/dist/astro/index.mjs +37 -11
  23. package/dist/astro/index.mjs.map +1 -1
  24. package/dist/astro/middleware/auth.d.mts +10 -10
  25. package/dist/astro/middleware/auth.mjs +6 -6
  26. package/dist/astro/middleware/media-usage-write-fence.mjs +3 -3
  27. package/dist/astro/middleware/redirect.mjs +7 -5
  28. package/dist/astro/middleware/redirect.mjs.map +1 -1
  29. package/dist/astro/middleware/request-context.mjs +3 -3
  30. package/dist/astro/middleware/setup.mjs +1 -1
  31. package/dist/astro/middleware.d.mts +10 -10
  32. package/dist/astro/middleware.d.mts.map +1 -1
  33. package/dist/astro/middleware.mjs +154 -125
  34. package/dist/astro/middleware.mjs.map +1 -1
  35. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  36. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  37. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +3 -3
  38. package/dist/astro/routes/api/admin/api-tokens/index.mjs +4 -4
  39. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
  40. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +9 -9
  41. package/dist/astro/routes/api/admin/byline-fields/index.mjs +9 -9
  42. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +9 -9
  43. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +16 -16
  44. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +16 -16
  45. package/dist/astro/routes/api/admin/bylines/index.mjs +16 -16
  46. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +11 -11
  47. package/dist/astro/routes/api/admin/comments/_id_.mjs +3 -3
  48. package/dist/astro/routes/api/admin/comments/bulk.mjs +8 -8
  49. package/dist/astro/routes/api/admin/comments/counts.mjs +3 -3
  50. package/dist/astro/routes/api/admin/comments/index.mjs +8 -8
  51. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  52. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  53. package/dist/astro/routes/api/admin/media-usage/activation.mjs +13 -13
  54. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +15 -15
  55. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +15 -15
  56. package/dist/astro/routes/api/admin/media-usage/progress.mjs +13 -13
  57. package/dist/astro/routes/api/admin/media-usage/repair.mjs +16 -16
  58. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +15 -15
  59. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +15 -15
  60. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +3 -3
  61. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +3 -3
  62. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +56 -53
  63. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  64. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +56 -53
  65. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  66. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +54 -51
  67. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  68. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  69. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +54 -51
  70. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  71. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +55 -52
  72. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  73. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +55 -52
  74. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  75. package/dist/astro/routes/api/admin/plugins/index.mjs +54 -51
  76. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  77. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
  78. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +54 -51
  79. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  80. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +55 -52
  81. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +54 -51
  83. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +55 -52
  85. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  86. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +56 -53
  87. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  88. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +5 -4
  89. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  90. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +56 -53
  91. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  92. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +55 -52
  93. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -1
  94. package/dist/astro/routes/api/admin/plugins/updates.mjs +54 -51
  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 +54 -51
  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 +2 -2
  99. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +54 -51
  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 +1 -1
  102. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
  103. package/dist/astro/routes/api/admin/users/_id_/index.mjs +6 -6
  104. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
  105. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  106. package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
  107. package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
  108. package/dist/astro/routes/api/auth/invite/complete.mjs +11 -11
  109. package/dist/astro/routes/api/auth/invite/index.mjs +8 -8
  110. package/dist/astro/routes/api/auth/invite/register-options.mjs +10 -10
  111. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  112. package/dist/astro/routes/api/auth/magic-link/send.mjs +10 -10
  113. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  114. package/dist/astro/routes/api/auth/me.mjs +7 -7
  115. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  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 +6 -6
  119. package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
  120. package/dist/astro/routes/api/auth/passkey/options.mjs +12 -12
  121. package/dist/astro/routes/api/auth/passkey/register/options.mjs +10 -10
  122. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +11 -11
  123. package/dist/astro/routes/api/auth/passkey/verify.mjs +11 -11
  124. package/dist/astro/routes/api/auth/signup/complete.mjs +11 -11
  125. package/dist/astro/routes/api/auth/signup/request.mjs +10 -10
  126. package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
  127. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +12 -12
  128. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +11 -11
  129. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
  130. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.d.mts.map +1 -1
  131. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +13 -8
  132. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs.map +1 -1
  133. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  134. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts +10 -0
  135. package/dist/astro/routes/api/content/_collection_/_id_/lock.d.mts.map +1 -0
  136. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs +66 -0
  137. package/dist/astro/routes/api/content/_collection_/_id_/lock.mjs.map +1 -0
  138. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
  139. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +11 -11
  140. package/dist/astro/routes/api/content/_collection_/_id_/publish.d.mts.map +1 -1
  141. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +14 -9
  142. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs.map +1 -1
  143. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +19 -17
  144. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  145. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +19 -17
  146. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  147. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  148. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
  149. package/dist/astro/routes/api/content/_collection_/_id_/schedule.d.mts.map +1 -1
  150. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +15 -8
  151. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs.map +1 -1
  152. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +15 -14
  153. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs.map +1 -1
  154. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
  155. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.d.mts.map +1 -1
  156. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +13 -8
  157. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs.map +1 -1
  158. package/dist/astro/routes/api/content/_collection_/_id_.d.mts.map +1 -1
  159. package/dist/astro/routes/api/content/_collection_/_id_.mjs +23 -11
  160. package/dist/astro/routes/api/content/_collection_/_id_.mjs.map +1 -1
  161. package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
  162. package/dist/astro/routes/api/content/_collection_/index.mjs +14 -9
  163. package/dist/astro/routes/api/content/_collection_/index.mjs.map +1 -1
  164. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  165. package/dist/astro/routes/api/dashboard.mjs +6 -6
  166. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  167. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  168. package/dist/astro/routes/api/import/probe.mjs +16 -16
  169. package/dist/astro/routes/api/import/wordpress/analyze.mjs +3 -3
  170. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  171. package/dist/astro/routes/api/import/wordpress/execute.mjs +14 -13
  172. package/dist/astro/routes/api/import/wordpress/execute.mjs.map +1 -1
  173. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  174. package/dist/astro/routes/api/import/wordpress/media.mjs +11 -11
  175. package/dist/astro/routes/api/import/wordpress/prepare.mjs +10 -10
  176. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  177. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +13 -13
  178. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  179. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +16 -16
  180. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  181. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +27 -26
  182. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs.map +1 -1
  183. package/dist/astro/routes/api/manifest.mjs +4 -4
  184. package/dist/astro/routes/api/mcp.mjs +71 -55
  185. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  186. package/dist/astro/routes/api/media/_id_/confirm.mjs +10 -10
  187. package/dist/astro/routes/api/media/_id_/replace.mjs +8 -8
  188. package/dist/astro/routes/api/media/_id_/upload.mjs +5 -5
  189. package/dist/astro/routes/api/media/_id_/usage.mjs +18 -18
  190. package/dist/astro/routes/api/media/_id_.mjs +17 -17
  191. package/dist/astro/routes/api/media/file/_...key_.mjs +1 -1
  192. package/dist/astro/routes/api/media/folders/_id_.mjs +8 -8
  193. package/dist/astro/routes/api/media/folders/index.mjs +8 -8
  194. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
  195. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
  196. package/dist/astro/routes/api/media/providers/index.mjs +2 -2
  197. package/dist/astro/routes/api/media/upload-url.mjs +9 -9
  198. package/dist/astro/routes/api/media.mjs +21 -21
  199. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +9 -9
  200. package/dist/astro/routes/api/menus/_name_/items.mjs +9 -9
  201. package/dist/astro/routes/api/menus/_name_/reorder.mjs +9 -9
  202. package/dist/astro/routes/api/menus/_name_/translations.mjs +9 -9
  203. package/dist/astro/routes/api/menus/_name_.mjs +9 -9
  204. package/dist/astro/routes/api/menus/index.mjs +9 -9
  205. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  206. package/dist/astro/routes/api/oauth/device/authorize.mjs +5 -5
  207. package/dist/astro/routes/api/oauth/device/code.mjs +8 -8
  208. package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
  209. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  210. package/dist/astro/routes/api/oauth/token/refresh.mjs +5 -5
  211. package/dist/astro/routes/api/oauth/token/revoke.mjs +5 -5
  212. package/dist/astro/routes/api/oauth/token.mjs +5 -5
  213. package/dist/astro/routes/api/openapi.json.mjs +84 -18
  214. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  215. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
  216. package/dist/astro/routes/api/redirects/404s/index.mjs +12 -11
  217. package/dist/astro/routes/api/redirects/404s/index.mjs.map +1 -1
  218. package/dist/astro/routes/api/redirects/404s/summary.mjs +12 -11
  219. package/dist/astro/routes/api/redirects/404s/summary.mjs.map +1 -1
  220. package/dist/astro/routes/api/redirects/_id_.mjs +13 -12
  221. package/dist/astro/routes/api/redirects/_id_.mjs.map +1 -1
  222. package/dist/astro/routes/api/redirects/index.mjs +13 -12
  223. package/dist/astro/routes/api/redirects/index.mjs.map +1 -1
  224. package/dist/astro/routes/api/relations/_id_/index.mjs +19 -17
  225. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  226. package/dist/astro/routes/api/relations/_id_/translations.mjs +14 -12
  227. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  228. package/dist/astro/routes/api/relations/index.mjs +19 -17
  229. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  230. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
  231. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  232. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +54 -51
  233. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  234. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +54 -51
  235. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  236. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +54 -51
  237. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  238. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +54 -51
  239. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  240. package/dist/astro/routes/api/schema/collections/index.mjs +54 -51
  241. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  242. package/dist/astro/routes/api/schema/collections/reorder.mjs +54 -51
  243. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  244. package/dist/astro/routes/api/schema/index.mjs +13 -11
  245. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  246. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +54 -51
  247. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  248. package/dist/astro/routes/api/schema/orphans/index.mjs +54 -51
  249. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  250. package/dist/astro/routes/api/search/enable.mjs +12 -11
  251. package/dist/astro/routes/api/search/enable.mjs.map +1 -1
  252. package/dist/astro/routes/api/search/index.mjs +11 -10
  253. package/dist/astro/routes/api/search/index.mjs.map +1 -1
  254. package/dist/astro/routes/api/search/rebuild.mjs +12 -11
  255. package/dist/astro/routes/api/search/rebuild.mjs.map +1 -1
  256. package/dist/astro/routes/api/search/stats.mjs +7 -6
  257. package/dist/astro/routes/api/search/stats.mjs.map +1 -1
  258. package/dist/astro/routes/api/search/suggest.mjs +11 -10
  259. package/dist/astro/routes/api/search/suggest.mjs.map +1 -1
  260. package/dist/astro/routes/api/sections/_slug_.mjs +11 -10
  261. package/dist/astro/routes/api/sections/_slug_.mjs.map +1 -1
  262. package/dist/astro/routes/api/sections/index.mjs +11 -10
  263. package/dist/astro/routes/api/sections/index.mjs.map +1 -1
  264. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +7 -6
  265. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs.map +1 -1
  266. package/dist/astro/routes/api/settings/backups/archives/index.mjs +6 -5
  267. package/dist/astro/routes/api/settings/backups/archives/index.mjs.map +1 -1
  268. package/dist/astro/routes/api/settings/backups/export.mjs +7 -6
  269. package/dist/astro/routes/api/settings/backups/export.mjs.map +1 -1
  270. package/dist/astro/routes/api/settings/backups/index.mjs +8 -7
  271. package/dist/astro/routes/api/settings/backups/index.mjs.map +1 -1
  272. package/dist/astro/routes/api/settings/email.mjs +4 -4
  273. package/dist/astro/routes/api/settings.mjs +14 -14
  274. package/dist/astro/routes/api/setup/admin-verify.mjs +12 -12
  275. package/dist/astro/routes/api/setup/admin.mjs +11 -11
  276. package/dist/astro/routes/api/setup/dev-bypass.mjs +33 -31
  277. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  278. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  279. package/dist/astro/routes/api/setup/index.mjs +33 -31
  280. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  281. package/dist/astro/routes/api/setup/status.mjs +3 -3
  282. package/dist/astro/routes/api/snapshot.mjs +8 -7
  283. package/dist/astro/routes/api/snapshot.mjs.map +1 -1
  284. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +16 -15
  285. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -1
  286. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +16 -15
  287. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  288. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +16 -15
  289. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  290. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +16 -15
  291. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  292. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +15 -14
  293. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs.map +1 -1
  294. package/dist/astro/routes/api/taxonomies/_name_.mjs +16 -15
  295. package/dist/astro/routes/api/taxonomies/_name_.mjs.map +1 -1
  296. package/dist/astro/routes/api/taxonomies/index.mjs +16 -15
  297. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  298. package/dist/astro/routes/api/themes/preview.mjs +5 -5
  299. package/dist/astro/routes/api/typegen.mjs +4 -4
  300. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  301. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  302. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  303. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +8 -8
  304. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +12 -12
  305. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +12 -12
  306. package/dist/astro/routes/api/widget-areas/_name_.mjs +7 -7
  307. package/dist/astro/routes/api/widget-areas/index.mjs +12 -12
  308. package/dist/astro/routes/api/widget-components.mjs +2 -2
  309. package/dist/astro/routes/robots.txt.mjs +6 -6
  310. package/dist/astro/routes/sitemap-_collection_.xml.mjs +11 -10
  311. package/dist/astro/routes/sitemap-_collection_.xml.mjs.map +1 -1
  312. package/dist/astro/routes/sitemap.xml.mjs +7 -7
  313. package/dist/astro/types.d.mts +32 -17
  314. package/dist/astro/types.d.mts.map +1 -1
  315. package/dist/auth/providers/github.d.mts +1 -1
  316. package/dist/auth/providers/google.d.mts +1 -1
  317. package/dist/{authorize-Bkf_UHhD.mjs → authorize-C2QHlWSS.mjs} +2 -2
  318. package/dist/{authorize-Bkf_UHhD.mjs.map → authorize-C2QHlWSS.mjs.map} +1 -1
  319. package/dist/{backup-rwVAl9NI.mjs → backup-oS8ft5Cm.mjs} +5 -5
  320. package/dist/{backup-rwVAl9NI.mjs.map → backup-oS8ft5Cm.mjs.map} +1 -1
  321. package/dist/{bundle-C8S2Zl6U.mjs → bundle-CL0JjIPx.mjs} +4 -4
  322. package/dist/{bundle-C8S2Zl6U.mjs.map → bundle-CL0JjIPx.mjs.map} +1 -1
  323. package/dist/{byline-DuhF7NWl.mjs → byline-Vdi85CsZ.mjs} +6 -6
  324. package/dist/{byline-DuhF7NWl.mjs.map → byline-Vdi85CsZ.mjs.map} +1 -1
  325. package/dist/{byline-fields-BovY4KYM.mjs → byline-fields-DPVRFMz2.mjs} +2 -2
  326. package/dist/{byline-fields-BovY4KYM.mjs.map → byline-fields-DPVRFMz2.mjs.map} +1 -1
  327. package/dist/{byline-registry-Bpu9-MVs.mjs → byline-registry-BxDGIO0I.mjs} +2 -2
  328. package/dist/{byline-registry-Bpu9-MVs.mjs.map → byline-registry-BxDGIO0I.mjs.map} +1 -1
  329. package/dist/{bylines-CJ5nd6Lw.mjs → bylines-BX8QhcTk.mjs} +7 -7
  330. package/dist/{bylines-CJ5nd6Lw.mjs.map → bylines-BX8QhcTk.mjs.map} +1 -1
  331. package/dist/{bylines-RwBAeOF1.mjs → bylines-w-E1IEQd.mjs} +3 -3
  332. package/dist/{bylines-RwBAeOF1.mjs.map → bylines-w-E1IEQd.mjs.map} +1 -1
  333. package/dist/{cache-BF5Kvn59.mjs → cache--7HKu5Xm.mjs} +4 -4
  334. package/dist/{cache-BF5Kvn59.mjs.map → cache--7HKu5Xm.mjs.map} +1 -1
  335. package/dist/{capture-triggers-CNW1q3HK.mjs → capture-triggers-CeAsC76Z.mjs} +2 -2
  336. package/dist/{capture-triggers-CNW1q3HK.mjs.map → capture-triggers-CeAsC76Z.mjs.map} +1 -1
  337. package/dist/{challenge-store-DQN_Yrck.mjs → challenge-store-BIOak-tp.mjs} +1 -1
  338. package/dist/{challenge-store-DQN_Yrck.mjs.map → challenge-store-BIOak-tp.mjs.map} +1 -1
  339. package/dist/{chrome-tags-D8fiZG94.mjs → chrome-tags-DzDQBCjX.mjs} +1 -1
  340. package/dist/{chrome-tags-D8fiZG94.mjs.map → chrome-tags-DzDQBCjX.mjs.map} +1 -1
  341. package/dist/{chunks-C4szrD8o.mjs → chunks-VG_tyqnP.mjs} +2 -2
  342. package/dist/{chunks-C4szrD8o.mjs.map → chunks-VG_tyqnP.mjs.map} +1 -1
  343. package/dist/cli/index.mjs +66 -38
  344. package/dist/cli/index.mjs.map +1 -1
  345. package/dist/client/cf-access.d.mts +1 -1
  346. package/dist/client/index.d.mts +17 -7
  347. package/dist/client/index.d.mts.map +1 -1
  348. package/dist/client/index.mjs +17 -12
  349. package/dist/client/index.mjs.map +1 -1
  350. package/dist/{collection-deletion-Bj07NHbj.mjs → collection-deletion-BCwaWTDw.mjs} +4 -4
  351. package/dist/{collection-deletion-Bj07NHbj.mjs.map → collection-deletion-BCwaWTDw.mjs.map} +1 -1
  352. package/dist/collection-slugs-cache-7lTmNzeA.mjs +85 -0
  353. package/dist/collection-slugs-cache-7lTmNzeA.mjs.map +1 -0
  354. package/dist/{comment-reaction-BhrvSHml.mjs → comment-reaction-CDyvPQRj.mjs} +2 -2
  355. package/dist/{comment-reaction-BhrvSHml.mjs.map → comment-reaction-CDyvPQRj.mjs.map} +1 -1
  356. package/dist/{comments-Ct4ensnf.mjs → comments-VzmVLyaC.mjs} +1 -1
  357. package/dist/{comments-Ct4ensnf.mjs.map → comments-VzmVLyaC.mjs.map} +1 -1
  358. package/dist/{components-DJbo1z0S.mjs → components-CL6Wkdk-.mjs} +1 -1
  359. package/dist/{components-DJbo1z0S.mjs.map → components-CL6Wkdk-.mjs.map} +1 -1
  360. package/dist/config--eWjQJE5.mjs +217 -0
  361. package/dist/config--eWjQJE5.mjs.map +1 -0
  362. package/dist/{index-BJNMCWmu.d.mts → config-CGAhyOjP.d.mts} +138 -47
  363. package/dist/config-CGAhyOjP.d.mts.map +1 -0
  364. package/dist/{config-B9eZ340f.d.mts → config-ChFzshGd.d.mts} +1 -1
  365. package/dist/{config-B9eZ340f.d.mts.map → config-ChFzshGd.d.mts.map} +1 -1
  366. package/dist/{content-DjvM0T92.mjs → content-CNfMWuhY.mjs} +121 -5
  367. package/dist/content-CNfMWuhY.mjs.map +1 -0
  368. package/dist/{content-list-query-Btqd4uV2.d.mts → content-list-query-B8d4UQp9.d.mts} +1 -1
  369. package/dist/{content-list-query-Btqd4uV2.d.mts.map → content-list-query-B8d4UQp9.d.mts.map} +1 -1
  370. package/dist/{content-refresh-Bwp-8yGy.mjs → content-refresh-GTMyi2Xy.mjs} +8 -8
  371. package/dist/{content-refresh-Bwp-8yGy.mjs.map → content-refresh-GTMyi2Xy.mjs.map} +1 -1
  372. package/dist/{content-repair-Czdp7jz5.mjs → content-repair-CIMt5C0U.mjs} +4 -4
  373. package/dist/{content-repair-Czdp7jz5.mjs.map → content-repair-CIMt5C0U.mjs.map} +1 -1
  374. package/dist/{context-CX6gxOLW.mjs → context-C9PB8vGd.mjs} +265 -25
  375. package/dist/context-C9PB8vGd.mjs.map +1 -0
  376. package/dist/{cron-C6o7VppJ.mjs → cron-DHAy9oyq.mjs} +1 -1
  377. package/dist/{cron-C6o7VppJ.mjs.map → cron-DHAy9oyq.mjs.map} +1 -1
  378. package/dist/{dashboard-C2kTeeRI.mjs → dashboard-BNSvAN8A.mjs} +4 -4
  379. package/dist/{dashboard-C2kTeeRI.mjs.map → dashboard-BNSvAN8A.mjs.map} +1 -1
  380. package/dist/db/index.d.mts +3 -3
  381. package/dist/db/index.mjs +2 -2
  382. package/dist/db/libsql-migrations.d.mts +1 -1
  383. package/dist/db/libsql-migrations.mjs +5 -5
  384. package/dist/db/libsql.d.mts +1 -1
  385. package/dist/db/postgres-migrations.d.mts +1 -1
  386. package/dist/db/postgres-migrations.mjs +5 -5
  387. package/dist/db/postgres.d.mts +1 -1
  388. package/dist/db/sqlite-migrations.d.mts +1 -1
  389. package/dist/db/sqlite-migrations.mjs +5 -5
  390. package/dist/db/sqlite.d.mts +1 -1
  391. package/dist/db/sqlite.mjs +1 -1
  392. package/dist/{default-Clra32mw.mjs → default-ByZ0JqZo.mjs} +1 -1
  393. package/dist/{default-Clra32mw.mjs.map → default-ByZ0JqZo.mjs.map} +1 -1
  394. package/dist/{deferred-tasks-CvDETTJO.d.mts → deferred-tasks-Cu4NSJpa.d.mts} +1 -1
  395. package/dist/{deferred-tasks-CvDETTJO.d.mts.map → deferred-tasks-Cu4NSJpa.d.mts.map} +1 -1
  396. package/dist/{dev-typegen-DzOPfsNj.mjs → dev-typegen-DHT7lcMU.mjs} +1 -1
  397. package/dist/{dev-typegen-DzOPfsNj.mjs.map → dev-typegen-DHT7lcMU.mjs.map} +1 -1
  398. package/dist/{device-flow-D2oCWvLJ.mjs → device-flow-Cf6bhCCT.mjs} +4 -4
  399. package/dist/{device-flow-D2oCWvLJ.mjs.map → device-flow-Cf6bhCCT.mjs.map} +1 -1
  400. package/dist/{dialect-helpers-BSbfaO3F.mjs → dialect-helpers-BcQvkHgn.mjs} +83 -2
  401. package/dist/dialect-helpers-BcQvkHgn.mjs.map +1 -0
  402. package/dist/{direct-executor-Bfa5_ToE.mjs → direct-executor-yAyUGSqB.mjs} +3 -3
  403. package/dist/{direct-executor-Bfa5_ToE.mjs.map → direct-executor-yAyUGSqB.mjs.map} +1 -1
  404. package/dist/{dist-89xCrGqi.mjs → dist-BAsh8dbf.mjs} +1 -1
  405. package/dist/{dist-89xCrGqi.mjs.map → dist-BAsh8dbf.mjs.map} +1 -1
  406. package/dist/{email-console-Dzb6uGYa.mjs → email-console-DNup1Fku.mjs} +1 -1
  407. package/dist/{email-console-Dzb6uGYa.mjs.map → email-console-DNup1Fku.mjs.map} +1 -1
  408. package/dist/{enrich-BX0IDp4z.mjs → enrich-t2Xvjdqa.mjs} +3 -3
  409. package/dist/{enrich-BX0IDp4z.mjs.map → enrich-t2Xvjdqa.mjs.map} +1 -1
  410. package/dist/entry-lock-BEr8gDkG.mjs +163 -0
  411. package/dist/entry-lock-BEr8gDkG.mjs.map +1 -0
  412. package/dist/{relations-DnRK4YIT.d.mts → entry-lock-CGAtrwAR.d.mts} +92 -37
  413. package/dist/entry-lock-CGAtrwAR.d.mts.map +1 -0
  414. package/dist/{redirects-BLNOWQTn.mjs → entry-lock-DIYHAaSw.mjs} +57 -14
  415. package/dist/entry-lock-DIYHAaSw.mjs.map +1 -0
  416. package/dist/entry-locks-BEcX7ET0.mjs +167 -0
  417. package/dist/entry-locks-BEcX7ET0.mjs.map +1 -0
  418. package/dist/{error-DFrQjppn.mjs → error-BDcFyoRt.mjs} +2 -2
  419. package/dist/{error-DFrQjppn.mjs.map → error-BDcFyoRt.mjs.map} +1 -1
  420. package/dist/{errors-DsVoDUjJ.mjs → errors-DvMdNrgf.mjs} +8 -1
  421. package/dist/errors-DvMdNrgf.mjs.map +1 -0
  422. package/dist/{escape-HmHTC1Is.mjs → escape-B3asJC6W.mjs} +1 -1
  423. package/dist/{escape-HmHTC1Is.mjs.map → escape-B3asJC6W.mjs.map} +1 -1
  424. package/dist/{field-defs-cache-BM4SIRqH.mjs → field-defs-cache-Cf5FHK0M.mjs} +5 -5
  425. package/dist/{field-defs-cache-BM4SIRqH.mjs.map → field-defs-cache-Cf5FHK0M.mjs.map} +1 -1
  426. package/dist/{fts-manager-Do1BlW2r.mjs → fts-manager-iddym8cd.mjs} +4 -4
  427. package/dist/{fts-manager-Do1BlW2r.mjs.map → fts-manager-iddym8cd.mjs.map} +1 -1
  428. package/dist/{hash-3JJPlHF2.mjs → hash-BRweX6jz.mjs} +1 -1
  429. package/dist/{hash-3JJPlHF2.mjs.map → hash-BRweX6jz.mjs.map} +1 -1
  430. package/dist/{hook-result-DCh2WUpe.d.mts → hook-result-BrshYHLx.d.mts} +1 -1
  431. package/dist/{hook-result-DCh2WUpe.d.mts.map → hook-result-BrshYHLx.d.mts.map} +1 -1
  432. package/dist/{hreflang-B6hbAuuO.d.mts → hreflang-CQpu5bMy.d.mts} +2 -2
  433. package/dist/{hreflang-B6hbAuuO.d.mts.map → hreflang-CQpu5bMy.d.mts.map} +1 -1
  434. package/dist/{hreflang-DQbPZliA.mjs → hreflang-DshnweTC.mjs} +9 -8
  435. package/dist/{hreflang-DQbPZliA.mjs.map → hreflang-DshnweTC.mjs.map} +1 -1
  436. package/dist/{identity-DksvEazf.mjs → identity-CjGKDq8J.mjs} +3 -3
  437. package/dist/{identity-DksvEazf.mjs.map → identity-CjGKDq8J.mjs.map} +1 -1
  438. package/dist/{import-CJpaBBBT.mjs → import-D96g2otw.mjs} +5 -5
  439. package/dist/{import-CJpaBBBT.mjs.map → import-D96g2otw.mjs.map} +1 -1
  440. package/dist/{index-Du8K7bWa.d.mts → index-1ECYpfiF.d.mts} +3 -3
  441. package/dist/{index-Du8K7bWa.d.mts.map → index-1ECYpfiF.d.mts.map} +1 -1
  442. package/dist/index.d.mts +22 -22
  443. package/dist/index.mjs +81 -78
  444. package/dist/{init-lock-DJkX6Hto.mjs → init-lock-CFNBe_iH.mjs} +1 -1
  445. package/dist/{init-lock-DJkX6Hto.mjs.map → init-lock-CFNBe_iH.mjs.map} +1 -1
  446. package/dist/{load-CawHjTOH.mjs → load-DPtY9cZo.mjs} +2 -2
  447. package/dist/{load-CawHjTOH.mjs.map → load-DPtY9cZo.mjs.map} +1 -1
  448. package/dist/{loader-Z8vl7zTq.mjs → loader-WJi6GFRn.mjs} +46 -8
  449. package/dist/loader-WJi6GFRn.mjs.map +1 -0
  450. package/dist/{manifest-builder-COtzuca2.mjs → manifest-builder-BfNlGQIA.mjs} +2 -2
  451. package/dist/{manifest-builder-COtzuca2.mjs.map → manifest-builder-BfNlGQIA.mjs.map} +1 -1
  452. package/dist/{manifest-schema-BNWwR8Vd.mjs → manifest-schema-CILooI5J.mjs} +1 -1
  453. package/dist/{manifest-schema-BNWwR8Vd.mjs.map → manifest-schema-CILooI5J.mjs.map} +1 -1
  454. package/dist/media/image-endpoint.mjs +1 -1
  455. package/dist/media/index.d.mts +1 -1
  456. package/dist/media/index.mjs +3 -3
  457. package/dist/media/local-runtime.d.mts +12 -12
  458. package/dist/media/local-runtime.mjs +5 -5
  459. package/dist/{media-BHjus86Y.mjs → media-C1EIZKh1.mjs} +1 -1
  460. package/dist/{media-BHjus86Y.mjs.map → media-C1EIZKh1.mjs.map} +1 -1
  461. package/dist/{media-allowlist-CoTBWoDp.mjs → media-allowlist-elXJgb_K.mjs} +2 -2
  462. package/dist/{media-allowlist-CoTBWoDp.mjs.map → media-allowlist-elXJgb_K.mjs.map} +1 -1
  463. package/dist/{media-folders-BGkATs8n.mjs → media-folders-DASfX_DH.mjs} +1 -1
  464. package/dist/{media-folders-BGkATs8n.mjs.map → media-folders-DASfX_DH.mjs.map} +1 -1
  465. package/dist/{media-upload-BCidR-EY.mjs → media-upload-C7_AQJ5v.mjs} +8 -8
  466. package/dist/{media-upload-BCidR-EY.mjs.map → media-upload-C7_AQJ5v.mjs.map} +1 -1
  467. package/dist/{media-url-DHoPr0hq.mjs → media-url-8dVl1loq.mjs} +19 -2
  468. package/dist/media-url-8dVl1loq.mjs.map +1 -0
  469. package/dist/{media-usage-CdY5jhSR.mjs → media-usage-C1EswMTq.mjs} +9 -9
  470. package/dist/{media-usage-CdY5jhSR.mjs.map → media-usage-C1EswMTq.mjs.map} +1 -1
  471. package/dist/{media-usage-activation-BgeMtK5C.mjs → media-usage-activation-CrHNltlL.mjs} +3 -3
  472. package/dist/{media-usage-activation-BgeMtK5C.mjs.map → media-usage-activation-CrHNltlL.mjs.map} +1 -1
  473. package/dist/{media-usage-work-D6D9sMCA.mjs → media-usage-work-C5B1zT1c.mjs} +2 -2
  474. package/dist/{media-usage-work-D6D9sMCA.mjs.map → media-usage-work-C5B1zT1c.mjs.map} +1 -1
  475. package/dist/{media-usage-work-CnGCdHxx.mjs → media-usage-work-IkQx_Yz6.mjs} +4 -4
  476. package/dist/{media-usage-work-CnGCdHxx.mjs.map → media-usage-work-IkQx_Yz6.mjs.map} +1 -1
  477. package/dist/{media-usage-write-fence-hjeD4u7s.mjs → media-usage-write-fence-B9anjOSg.mjs} +3 -3
  478. package/dist/{media-usage-write-fence-hjeD4u7s.mjs.map → media-usage-write-fence-B9anjOSg.mjs.map} +1 -1
  479. package/dist/{menus-6qSwTNxG.mjs → menus-D8mC4eaN.mjs} +115 -136
  480. package/dist/menus-D8mC4eaN.mjs.map +1 -0
  481. package/dist/{menus-uvPLXMZf.mjs → menus-UdwjHZJC.mjs} +11 -3
  482. package/dist/{menus-uvPLXMZf.mjs.map → menus-UdwjHZJC.mjs.map} +1 -1
  483. package/dist/migrations/index.d.mts +1 -1
  484. package/dist/migrations/index.mjs +4 -4
  485. package/dist/{mime-CUIG6x84.mjs → mime-DYpsOAny.mjs} +1 -1
  486. package/dist/{mime-CUIG6x84.mjs.map → mime-DYpsOAny.mjs.map} +1 -1
  487. package/dist/{mode-DN_WneRx.mjs → mode-Dm4BHhRH.mjs} +1 -1
  488. package/dist/{mode-DN_WneRx.mjs.map → mode-Dm4BHhRH.mjs.map} +1 -1
  489. package/dist/{node-sqlite-compat-BuJXIeMz.mjs → node-sqlite-compat-2sezm-Zd.mjs} +1 -1
  490. package/dist/{node-sqlite-compat-BuJXIeMz.mjs.map → node-sqlite-compat-2sezm-Zd.mjs.map} +1 -1
  491. package/dist/{normalize-C2xNjTSG.mjs → normalize-4nkKGsuW.mjs} +1 -1
  492. package/dist/{normalize-C2xNjTSG.mjs.map → normalize-4nkKGsuW.mjs.map} +1 -1
  493. package/dist/{oauth-authorization-Dj6Kwc21.mjs → oauth-authorization-BxE_lURD.mjs} +4 -4
  494. package/dist/{oauth-authorization-Dj6Kwc21.mjs.map → oauth-authorization-BxE_lURD.mjs.map} +1 -1
  495. package/dist/{oauth-clients-FD7I0J8m.mjs → oauth-clients-DJIdOdq0.mjs} +1 -1
  496. package/dist/{oauth-clients-FD7I0J8m.mjs.map → oauth-clients-DJIdOdq0.mjs.map} +1 -1
  497. package/dist/{oauth-state-store-DkmDOmHs.mjs → oauth-state-store-CsdxP57n.mjs} +1 -1
  498. package/dist/{oauth-state-store-DkmDOmHs.mjs.map → oauth-state-store-CsdxP57n.mjs.map} +1 -1
  499. package/dist/{oauth-user-lookup-CvIwGpYd.mjs → oauth-user-lookup-HzzW-dkF.mjs} +1 -1
  500. package/dist/{oauth-user-lookup-CvIwGpYd.mjs.map → oauth-user-lookup-HzzW-dkF.mjs.map} +1 -1
  501. package/dist/object-cache/memory.d.mts +1 -1
  502. package/dist/{options-BHPeIbBd.mjs → options-D1FBiAv1.mjs} +60 -5
  503. package/dist/options-D1FBiAv1.mjs.map +1 -0
  504. package/dist/{options-CYb4y7hM.d.mts → options-D8Y0VHc7.d.mts} +9 -3
  505. package/dist/options-D8Y0VHc7.d.mts.map +1 -0
  506. package/dist/page/index.d.mts +2 -2
  507. package/dist/page/index.d.mts.map +1 -1
  508. package/dist/page/index.mjs +12 -0
  509. package/dist/page/index.mjs.map +1 -1
  510. package/dist/{parse-Ckpg-Qfp.mjs → parse-WRg5C3NX.mjs} +2 -2
  511. package/dist/{parse-Ckpg-Qfp.mjs.map → parse-WRg5C3NX.mjs.map} +1 -1
  512. package/dist/{passkey-config-O_lj3y0k.mjs → passkey-config-qIdO-wF6.mjs} +1 -1
  513. package/dist/{passkey-config-O_lj3y0k.mjs.map → passkey-config-qIdO-wF6.mjs.map} +1 -1
  514. package/dist/{patterns-D9iDO3j8.mjs → patterns-DC8CLptu.mjs} +1 -1
  515. package/dist/{patterns-D9iDO3j8.mjs.map → patterns-DC8CLptu.mjs.map} +1 -1
  516. package/dist/{placeholder-4X9BrRrp.d.mts → placeholder-COrvARyD.d.mts} +1 -1
  517. package/dist/{placeholder-4X9BrRrp.d.mts.map → placeholder-COrvARyD.d.mts.map} +1 -1
  518. package/dist/plugin-types.d.mts +3 -3
  519. package/dist/plugin-types.d.mts.map +1 -1
  520. package/dist/plugin-utils.d.mts +10 -10
  521. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  522. package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
  523. package/dist/{policy-Dhtwntrt.mjs → policy-XCfb-IE9.mjs} +2 -2
  524. package/dist/{policy-Dhtwntrt.mjs.map → policy-XCfb-IE9.mjs.map} +1 -1
  525. package/dist/{portable-text-U85hOafW.mjs → portable-text-BS3d5n-0.mjs} +1 -1
  526. package/dist/{portable-text-U85hOafW.mjs.map → portable-text-BS3d5n-0.mjs.map} +1 -1
  527. package/dist/{preview-B_vJLvf8.mjs → preview-BxwsGgGp.mjs} +2 -2
  528. package/dist/{preview-B_vJLvf8.mjs.map → preview-BxwsGgGp.mjs.map} +1 -1
  529. package/dist/{protocol-JdD2YhY9.d.mts → protocol-CLn58-nw.d.mts} +2 -2
  530. package/dist/{protocol-JdD2YhY9.d.mts.map → protocol-CLn58-nw.d.mts.map} +1 -1
  531. package/dist/{public-url-CarhZJgf.mjs → public-url-FWWAvnre.mjs} +1 -1
  532. package/dist/{public-url-CarhZJgf.mjs.map → public-url-FWWAvnre.mjs.map} +1 -1
  533. package/dist/{query-BZKZcG5b.mjs → query-DygOte9M.mjs} +25 -16
  534. package/dist/query-DygOte9M.mjs.map +1 -0
  535. package/dist/{query-BndaFxxp.mjs → query-gtXT03Wc.mjs} +4 -4
  536. package/dist/{query-BndaFxxp.mjs.map → query-gtXT03Wc.mjs.map} +1 -1
  537. package/dist/{rate-limit-BZmATC6W.mjs → rate-limit-CQUPm0dh.mjs} +2 -2
  538. package/dist/{rate-limit-BZmATC6W.mjs.map → rate-limit-CQUPm0dh.mjs.map} +1 -1
  539. package/dist/{redirect-CzqnLxK-.mjs → redirect-D1cWafi6.mjs} +1 -1
  540. package/dist/{redirect-CzqnLxK-.mjs.map → redirect-D1cWafi6.mjs.map} +1 -1
  541. package/dist/{redirect-CZkbozu9.mjs → redirect-DId44BS1.mjs} +19 -6
  542. package/dist/redirect-DId44BS1.mjs.map +1 -0
  543. package/dist/{redirects-CqzNM0KM.mjs → redirects-DN-ZE33W.mjs} +5 -5
  544. package/dist/{redirects-CqzNM0KM.mjs.map → redirects-DN-ZE33W.mjs.map} +1 -1
  545. package/dist/{registry-AZAsRsor.mjs → registry-DTqaqxed.mjs} +26 -10
  546. package/dist/registry-DTqaqxed.mjs.map +1 -0
  547. package/dist/{relation-04DfKRTO.mjs → relation-DxgCHOBw.mjs} +2 -2
  548. package/dist/{relation-04DfKRTO.mjs.map → relation-DxgCHOBw.mjs.map} +1 -1
  549. package/dist/{relations-CcFwDJdJ.mjs → relations-KKDSLUwS.mjs} +4 -4
  550. package/dist/{relations-CcFwDJdJ.mjs.map → relations-KKDSLUwS.mjs.map} +1 -1
  551. package/dist/{relations-C4htk5sb.mjs → relations-rOmbndUJ.mjs} +3 -3
  552. package/dist/{relations-C4htk5sb.mjs.map → relations-rOmbndUJ.mjs.map} +1 -1
  553. package/dist/{request-cache-DH9zdCOD.mjs → request-cache-DAZZmesc.mjs} +1 -1
  554. package/dist/{request-cache-DH9zdCOD.mjs.map → request-cache-DAZZmesc.mjs.map} +1 -1
  555. package/dist/request-context.d.mts +1 -1
  556. package/dist/{request-meta-DYxLlnmz.mjs → request-meta-BgjUQLQ-.mjs} +2 -2
  557. package/dist/{request-meta-DYxLlnmz.mjs.map → request-meta-BgjUQLQ-.mjs.map} +1 -1
  558. package/dist/{resolve-prZ3mP7l.mjs → resolve-Cy0aWSRj.mjs} +37 -4
  559. package/dist/resolve-Cy0aWSRj.mjs.map +1 -0
  560. package/dist/{runner-YKfIMnaF.d.mts → runner-CfwysRM0.d.mts} +2 -2
  561. package/dist/{runner-YKfIMnaF.d.mts.map → runner-CfwysRM0.d.mts.map} +1 -1
  562. package/dist/{runner-BLIDKpmA.mjs → runner-nEzvnogG.mjs} +419 -295
  563. package/dist/runner-nEzvnogG.mjs.map +1 -0
  564. package/dist/runtime.d.mts +11 -11
  565. package/dist/runtime.mjs +3 -2
  566. package/dist/runtime.mjs.map +1 -1
  567. package/dist/{schema-CGnBeLiW.mjs → schema-CRu38Pr5.mjs} +3 -3
  568. package/dist/{schema-CGnBeLiW.mjs.map → schema-CRu38Pr5.mjs.map} +1 -1
  569. package/dist/{schema-DYr-Vd-L.mjs → schema-DifxndJx.mjs} +4 -4
  570. package/dist/{schema-DYr-Vd-L.mjs.map → schema-DifxndJx.mjs.map} +1 -1
  571. package/dist/{scopes-BhWvBavj.mjs → scopes-D5A1OZbq.mjs} +3 -3
  572. package/dist/{scopes-BhWvBavj.mjs.map → scopes-D5A1OZbq.mjs.map} +1 -1
  573. package/dist/{search-C-qDk4kx.mjs → search-DEPFSBFq.mjs} +4 -4
  574. package/dist/{search-C-qDk4kx.mjs.map → search-DEPFSBFq.mjs.map} +1 -1
  575. package/dist/{secrets-rEtHt-6z.mjs → secrets-CdfzLdoO.mjs} +3 -3
  576. package/dist/{secrets-rEtHt-6z.mjs.map → secrets-CdfzLdoO.mjs.map} +1 -1
  577. package/dist/{sections-B_nYvlwn.mjs → sections-3X52kmIR.mjs} +2 -2
  578. package/dist/{sections-B_nYvlwn.mjs.map → sections-3X52kmIR.mjs.map} +1 -1
  579. package/dist/seed/index.d.mts +2 -2
  580. package/dist/seed/index.mjs +26 -24
  581. package/dist/seo/index.d.mts +3 -3
  582. package/dist/seo/index.d.mts.map +1 -1
  583. package/dist/seo/index.mjs +18 -19
  584. package/dist/seo/index.mjs.map +1 -1
  585. package/dist/{seo-926NRIgt.mjs → seo-Bw68KxRc.mjs} +2 -2
  586. package/dist/{seo-926NRIgt.mjs.map → seo-Bw68KxRc.mjs.map} +1 -1
  587. package/dist/{seo-CVWkdv6x.mjs → seo-C4AmbsMU.mjs} +3 -2
  588. package/dist/seo-C4AmbsMU.mjs.map +1 -0
  589. package/dist/{service-CJl3ZAYs.mjs → service-J_-Vgo7R.mjs} +2 -2
  590. package/dist/{service-CJl3ZAYs.mjs.map → service-J_-Vgo7R.mjs.map} +1 -1
  591. package/dist/{session-user-BlMgqCHS.mjs → session-user-CbnMMwk6.mjs} +1 -1
  592. package/dist/{session-user-BlMgqCHS.mjs.map → session-user-CbnMMwk6.mjs.map} +1 -1
  593. package/dist/{settings-Cwm6o2jY.mjs → settings-AnEFYICn.mjs} +3 -3
  594. package/dist/{settings-Cwm6o2jY.mjs.map → settings-AnEFYICn.mjs.map} +1 -1
  595. package/dist/{settings--wobrkkC.mjs → settings-DcMjREe5.mjs} +6 -6
  596. package/dist/{settings--wobrkkC.mjs.map → settings-DcMjREe5.mjs.map} +1 -1
  597. package/dist/{setup-complete-DQbClIN2.mjs → setup-complete-BClXXTvr.mjs} +2 -2
  598. package/dist/{setup-complete-DQbClIN2.mjs.map → setup-complete-BClXXTvr.mjs.map} +1 -1
  599. package/dist/{setup-nonce-DZCFS2sn.mjs → setup-nonce-BheRa4RG.mjs} +1 -1
  600. package/dist/{setup-nonce-DZCFS2sn.mjs.map → setup-nonce-BheRa4RG.mjs.map} +1 -1
  601. package/dist/{single-flight-cache-BPuGPdcN.mjs → single-flight-cache-jaswDzmQ.mjs} +2 -2
  602. package/dist/{single-flight-cache-BPuGPdcN.mjs.map → single-flight-cache-jaswDzmQ.mjs.map} +1 -1
  603. package/dist/{site-url-BrxA_E9H.mjs → site-url-Bqf-ea3N.mjs} +3 -3
  604. package/dist/{site-url-BrxA_E9H.mjs.map → site-url-Bqf-ea3N.mjs.map} +1 -1
  605. package/dist/{snapshot--OCDTqdb.mjs → snapshot-C4CtXntb.mjs} +51 -35
  606. package/dist/snapshot-C4CtXntb.mjs.map +1 -0
  607. package/dist/{ssrf-5sIM5jzl.mjs → ssrf-gl4gFNhw.mjs} +148 -91
  608. package/dist/ssrf-gl4gFNhw.mjs.map +1 -0
  609. package/dist/{state-BpFVsJZB.mjs → state-1F6IOhdQ.mjs} +1 -1
  610. package/dist/{state-BpFVsJZB.mjs.map → state-1F6IOhdQ.mjs.map} +1 -1
  611. package/dist/{status-B777-dXz.mjs → status-Cenfk_r5.mjs} +1 -1
  612. package/dist/{status-B777-dXz.mjs.map → status-Cenfk_r5.mjs.map} +1 -1
  613. package/dist/storage/local.d.mts +1 -1
  614. package/dist/storage/local.mjs +1 -1
  615. package/dist/storage/s3.d.mts +1 -1
  616. package/dist/storage/s3.mjs +1 -1
  617. package/dist/{target-BmR0iTwz.mjs → target-CRzeTs8G.mjs} +1 -1
  618. package/dist/{target-BmR0iTwz.mjs.map → target-CRzeTs8G.mjs.map} +1 -1
  619. package/dist/{taxonomies-DkAkMupr.mjs → taxonomies-BOdxuZpV.mjs} +11 -4
  620. package/dist/taxonomies-BOdxuZpV.mjs.map +1 -0
  621. package/dist/{taxonomies-Wfy_Lg12.mjs → taxonomies-NcFDq5Gg.mjs} +23 -14
  622. package/dist/taxonomies-NcFDq5Gg.mjs.map +1 -0
  623. package/dist/{taxonomy-tJepplLL.mjs → taxonomy-DP1vny4K.mjs} +11 -3
  624. package/dist/{taxonomy-tJepplLL.mjs.map → taxonomy-DP1vny4K.mjs.map} +1 -1
  625. package/dist/{tokens-BCO1oruF.mjs → tokens-CDk8ox9p.mjs} +1 -1
  626. package/dist/{tokens-BCO1oruF.mjs.map → tokens-CDk8ox9p.mjs.map} +1 -1
  627. package/dist/{transport-xh6YKW2G.d.mts → transport-BVn4tVb9.d.mts} +1 -1
  628. package/dist/{transport-xh6YKW2G.d.mts.map → transport-BVn4tVb9.d.mts.map} +1 -1
  629. package/dist/{transport-Dr3qtwXC.mjs → transport-DP0JI-8i.mjs} +1 -1
  630. package/dist/{transport-Dr3qtwXC.mjs.map → transport-DP0JI-8i.mjs.map} +1 -1
  631. package/dist/{trusted-proxy-BR5F1Otp.mjs → trusted-proxy-BTM6UxqD.mjs} +1 -1
  632. package/dist/{trusted-proxy-BR5F1Otp.mjs.map → trusted-proxy-BTM6UxqD.mjs.map} +1 -1
  633. package/dist/{types-CXFkwEGC.d.mts → types-2n848aVW.d.mts} +1 -1
  634. package/dist/{types-CXFkwEGC.d.mts.map → types-2n848aVW.d.mts.map} +1 -1
  635. package/dist/{types-75KIqzL9.mjs → types-BMXnRIrX.mjs} +4 -2
  636. package/dist/types-BMXnRIrX.mjs.map +1 -0
  637. package/dist/{types-B6GrPic4.d.mts → types-BouXpOsa.d.mts} +115 -4
  638. package/dist/types-BouXpOsa.d.mts.map +1 -0
  639. package/dist/{types-3qNFPlci.mjs → types-ByG2coLw.mjs} +1 -1
  640. package/dist/{types-3qNFPlci.mjs.map → types-ByG2coLw.mjs.map} +1 -1
  641. package/dist/types-CQPWhPxE.mjs.map +1 -1
  642. package/dist/{types-CDtkNSFQ.d.mts → types-DEfNJ__A.d.mts} +1 -1
  643. package/dist/{types-CDtkNSFQ.d.mts.map → types-DEfNJ__A.d.mts.map} +1 -1
  644. package/dist/{types-xDMtUFnO.d.mts → types-DKcKSbtB.d.mts} +23 -7
  645. package/dist/types-DKcKSbtB.d.mts.map +1 -0
  646. package/dist/{types-C00oyCZp.d.mts → types-DRYs7uTL.d.mts} +1 -1
  647. package/dist/{types-C00oyCZp.d.mts.map → types-DRYs7uTL.d.mts.map} +1 -1
  648. package/dist/{types-DczELMop.d.mts → types-DaEg7KX2.d.mts} +1 -1
  649. package/dist/{types-DczELMop.d.mts.map → types-DaEg7KX2.d.mts.map} +1 -1
  650. package/dist/{types-BuHW4xDE.d.mts → types-LU8utpP_.d.mts} +6 -3
  651. package/dist/types-LU8utpP_.d.mts.map +1 -0
  652. package/dist/{types-CPeXo1wF.d.mts → types-VpYfPUxN.d.mts} +1 -1
  653. package/dist/{types-CPeXo1wF.d.mts.map → types-VpYfPUxN.d.mts.map} +1 -1
  654. package/dist/{types-DM3vioBY.mjs → types-c9GP7Dj5.mjs} +1 -1
  655. package/dist/{types-DM3vioBY.mjs.map → types-c9GP7Dj5.mjs.map} +1 -1
  656. package/dist/{types-FV23hEoW.d.mts → types-tJWDK__M.d.mts} +14 -1
  657. package/dist/types-tJWDK__M.d.mts.map +1 -0
  658. package/dist/{upload-attempts-BsqoQ1fn.mjs → upload-attempts-C6S2y-lp.mjs} +1 -1
  659. package/dist/{upload-attempts-BsqoQ1fn.mjs.map → upload-attempts-C6S2y-lp.mjs.map} +1 -1
  660. package/dist/{url-pattern-D4c2czpJ.mjs → url-pattern-UYtxVTuj.mjs} +1 -1
  661. package/dist/{url-pattern-D4c2czpJ.mjs.map → url-pattern-UYtxVTuj.mjs.map} +1 -1
  662. package/dist/{user-BTZ40aq6.mjs → user-DIsIXogT.mjs} +2 -2
  663. package/dist/{user-BTZ40aq6.mjs.map → user-DIsIXogT.mjs.map} +1 -1
  664. package/dist/{utils-BKvNjjhY.mjs → utils-BicP5Qbg.mjs} +2 -2
  665. package/dist/{utils-BKvNjjhY.mjs.map → utils-BicP5Qbg.mjs.map} +1 -1
  666. package/dist/{validate-DE_LRwo9.mjs → validate-D8VPn4Hv.mjs} +8 -3
  667. package/dist/validate-D8VPn4Hv.mjs.map +1 -0
  668. package/dist/{validate-DUP27OYD.d.mts → validate-Df6Dvwbw.d.mts} +12 -7
  669. package/dist/validate-Df6Dvwbw.d.mts.map +1 -0
  670. package/dist/{validation-BMImFJ11.mjs → validation-CzMJn9Ku.mjs} +13 -11
  671. package/dist/{validation-BMImFJ11.mjs.map → validation-CzMJn9Ku.mjs.map} +1 -1
  672. package/dist/version-CK67_SXX.mjs +7 -0
  673. package/dist/{version-Bii3suaO.mjs.map → version-CK67_SXX.mjs.map} +1 -1
  674. package/dist/{widgets-D3gJ10xU.mjs → widgets-RFVAxQl3.mjs} +5 -5
  675. package/dist/{widgets-D3gJ10xU.mjs.map → widgets-RFVAxQl3.mjs.map} +1 -1
  676. package/dist/{wxr-taxonomies-B2Og_6rU.d.mts → wxr-taxonomies-BX4yQL9s.d.mts} +1 -1
  677. package/dist/{wxr-taxonomies-B2Og_6rU.d.mts.map → wxr-taxonomies-BX4yQL9s.d.mts.map} +1 -1
  678. package/dist/{wxr-taxonomies-Cxngsjwo.mjs → wxr-taxonomies-Csdp7yde.mjs} +4 -4
  679. package/dist/{wxr-taxonomies-Cxngsjwo.mjs.map → wxr-taxonomies-Csdp7yde.mjs.map} +1 -1
  680. package/dist/{zod-generator-BuYSQJB7.mjs → zod-generator-CNRGdnBY.mjs} +3 -3
  681. package/dist/{zod-generator-BuYSQJB7.mjs.map → zod-generator-CNRGdnBY.mjs.map} +1 -1
  682. package/package.json +12 -10
  683. package/src/api/errors.ts +7 -0
  684. package/src/api/handlers/content.ts +66 -79
  685. package/src/api/handlers/entry-lock.ts +206 -0
  686. package/src/api/handlers/manifest.ts +1 -0
  687. package/src/api/handlers/marketplace.ts +28 -20
  688. package/src/api/handlers/menus.ts +9 -0
  689. package/src/api/handlers/registry.ts +13 -8
  690. package/src/api/handlers/revision.ts +2 -1
  691. package/src/api/handlers/seo.ts +10 -1
  692. package/src/api/handlers/snapshot.ts +84 -72
  693. package/src/api/handlers/taxonomies.ts +9 -0
  694. package/src/api/openapi/document.ts +111 -6
  695. package/src/api/schemas/content.ts +8 -0
  696. package/src/api/schemas/entry-lock.ts +48 -0
  697. package/src/api/schemas/index.ts +1 -0
  698. package/src/api/schemas/schema.ts +10 -1
  699. package/src/api/types.ts +2 -0
  700. package/src/astro/integration/index.ts +9 -6
  701. package/src/astro/integration/routes.ts +5 -0
  702. package/src/astro/integration/runtime.ts +13 -5
  703. package/src/astro/integration/vite-config.ts +30 -0
  704. package/src/astro/middleware.ts +16 -0
  705. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +10 -0
  706. package/src/astro/routes/api/content/[collection]/[id]/lock.ts +133 -0
  707. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +11 -1
  708. package/src/astro/routes/api/content/[collection]/[id]/schedule.ts +20 -0
  709. package/src/astro/routes/api/content/[collection]/[id]/unpublish.ts +10 -0
  710. package/src/astro/routes/api/content/[collection]/[id].ts +27 -2
  711. package/src/astro/routes/api/content/[collection]/index.ts +3 -0
  712. package/src/astro/routes/sitemap-[collection].xml.ts +4 -0
  713. package/src/astro/types.ts +13 -3
  714. package/src/cli/commands/content.ts +31 -5
  715. package/src/cli/commands/export-seed.ts +2 -0
  716. package/src/client/index.ts +34 -7
  717. package/src/components/EmDashBodyEnd.astro +4 -1
  718. package/src/components/EmDashBodyStart.astro +4 -1
  719. package/src/components/EmDashHead.astro +35 -16
  720. package/src/components/Gallery.astro +18 -4
  721. package/src/components/InlineEditor.astro +3 -1
  722. package/src/components/InlinePortableTextEditor.tsx +106 -11
  723. package/src/components/PortableText.astro +4 -0
  724. package/src/components/Table.astro +147 -62
  725. package/src/config/errors.ts +13 -0
  726. package/src/content/converters/portable-text-to-prosemirror.ts +26 -2
  727. package/src/content/converters/prosemirror-to-portable-text.ts +35 -6
  728. package/src/content/converters/types.ts +10 -0
  729. package/src/database/dialect-helpers.ts +125 -0
  730. package/src/database/migrations/075_entry_edit_locks.ts +44 -0
  731. package/src/database/migrations/076_collection_nav_group.ts +22 -0
  732. package/src/database/migrations/077_plugin_storage_revisions.ts +89 -0
  733. package/src/database/migrations/runner.ts +6 -0
  734. package/src/database/repositories/content.ts +170 -1
  735. package/src/database/repositories/entry-locks.ts +257 -0
  736. package/src/database/repositories/options.ts +69 -5
  737. package/src/database/repositories/plugin-storage.ts +159 -0
  738. package/src/database/repositories/redirect.ts +17 -6
  739. package/src/database/repositories/taxonomy.ts +8 -0
  740. package/src/database/repositories/types.ts +3 -0
  741. package/src/database/types.ts +15 -1
  742. package/src/emdash-runtime.ts +117 -50
  743. package/src/i18n/resolve.ts +44 -4
  744. package/src/index.ts +14 -0
  745. package/src/loader.ts +35 -4
  746. package/src/mcp/server.ts +23 -5
  747. package/src/media/responsive.ts +23 -0
  748. package/src/media/usage/content-refresh.ts +2 -1
  749. package/src/menus/index.ts +17 -21
  750. package/src/page/seo-contributions.ts +78 -1
  751. package/src/page/seo-panel.ts +47 -0
  752. package/src/plugin-types.ts +9 -0
  753. package/src/plugins/conditional-storage.ts +30 -0
  754. package/src/plugins/context.ts +49 -17
  755. package/src/plugins/hooks.ts +7 -1
  756. package/src/plugins/index.ts +9 -0
  757. package/src/plugins/manager.ts +5 -2
  758. package/src/plugins/sandbox/types.ts +16 -2
  759. package/src/plugins/storage-query.ts +45 -0
  760. package/src/plugins/storage-update.ts +96 -0
  761. package/src/plugins/types.ts +114 -0
  762. package/src/query.ts +29 -3
  763. package/src/registry/config.ts +130 -27
  764. package/src/registry/types.ts +5 -6
  765. package/src/schema/collection-slugs-cache.ts +157 -0
  766. package/src/schema/registry.ts +19 -0
  767. package/src/schema/types.ts +25 -6
  768. package/src/security/ssrf.ts +167 -141
  769. package/src/seed/apply.ts +4 -0
  770. package/src/seed/types.ts +7 -2
  771. package/src/seed/validate.ts +18 -1
  772. package/src/seo/hreflang.ts +1 -0
  773. package/src/seo/index.ts +5 -10
  774. package/src/seo/media-url.ts +26 -0
  775. package/src/taxonomies/term-counts.ts +22 -5
  776. package/dist/api-Dz6rgoa3.mjs.map +0 -1
  777. package/dist/apply-B4SIOxR1.mjs.map +0 -1
  778. package/dist/config-it29yDLA.mjs.map +0 -1
  779. package/dist/content-DjvM0T92.mjs.map +0 -1
  780. package/dist/context-CX6gxOLW.mjs.map +0 -1
  781. package/dist/dialect-helpers-BSbfaO3F.mjs.map +0 -1
  782. package/dist/errors-DsVoDUjJ.mjs.map +0 -1
  783. package/dist/index-BJNMCWmu.d.mts.map +0 -1
  784. package/dist/loader-Z8vl7zTq.mjs.map +0 -1
  785. package/dist/media-url-DHoPr0hq.mjs.map +0 -1
  786. package/dist/menus-6qSwTNxG.mjs.map +0 -1
  787. package/dist/options-BHPeIbBd.mjs.map +0 -1
  788. package/dist/options-CYb4y7hM.d.mts.map +0 -1
  789. package/dist/query-BZKZcG5b.mjs.map +0 -1
  790. package/dist/redirect-CZkbozu9.mjs.map +0 -1
  791. package/dist/redirects-BLNOWQTn.mjs.map +0 -1
  792. package/dist/registry-AZAsRsor.mjs.map +0 -1
  793. package/dist/relations-DnRK4YIT.d.mts.map +0 -1
  794. package/dist/resolve-prZ3mP7l.mjs.map +0 -1
  795. package/dist/runner-BLIDKpmA.mjs.map +0 -1
  796. package/dist/seo-CVWkdv6x.mjs.map +0 -1
  797. package/dist/snapshot--OCDTqdb.mjs.map +0 -1
  798. package/dist/ssrf-5sIM5jzl.mjs.map +0 -1
  799. package/dist/taxonomies-DkAkMupr.mjs.map +0 -1
  800. package/dist/taxonomies-Wfy_Lg12.mjs.map +0 -1
  801. package/dist/types-75KIqzL9.mjs.map +0 -1
  802. package/dist/types-B6GrPic4.d.mts.map +0 -1
  803. package/dist/types-BuHW4xDE.d.mts.map +0 -1
  804. package/dist/types-FV23hEoW.d.mts.map +0 -1
  805. package/dist/types-xDMtUFnO.d.mts.map +0 -1
  806. package/dist/validate-DE_LRwo9.mjs.map +0 -1
  807. package/dist/validate-DUP27OYD.d.mts.map +0 -1
  808. package/dist/version-Bii3suaO.mjs +0 -7
  809. /package/dist/{api-tokens-BfYts-sq.mjs → api-tokens-B_lfpmH3.mjs} +0 -0
  810. /package/dist/{ssrf-Dg3cIT-b.mjs → ssrf-TQhaljuI.mjs} +0 -0
  811. /package/dist/{types-DfuTR6dL.mjs → types-A2cN6a4a.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"dev-typegen-DzOPfsNj.mjs","names":[],"sources":["../src/astro/dev-typegen.ts"],"sourcesContent":["/**\n * Dev-only hook for regenerating `emdash-env.d.ts` when the schema changes.\n *\n * The Astro integration registers an environment-specific refresh function\n * (filesystem + local HTTP in Node dev, no-op everywhere else). Schema\n * mutation code just triggers the hook, so runtime modules stay free of\n * Node-only I/O.\n */\n\nconst REFRESH_FN_KEY = \"__emdashDevTypegenRefresh\";\n\nexport interface DevTypegenRefreshFn {\n\t(db: unknown): void | Promise<void>;\n}\n\nexport function setDevTypegenRefresh(fn: DevTypegenRefreshFn): void {\n\tif (typeof globalThis !== \"undefined\") {\n\t\tReflect.set(globalThis, REFRESH_FN_KEY, fn);\n\t}\n}\n\nexport function refreshDevTypes(db: unknown): void {\n\tif (typeof import.meta.env === \"undefined\" || !import.meta.env.DEV) return;\n\n\tconst fn = Reflect.get(globalThis, REFRESH_FN_KEY);\n\tif (typeof fn !== \"function\") return;\n\n\ttry {\n\t\tPromise.resolve(fn(db)).catch((error: unknown) => {\n\t\t\tconsole.error(\"[emdash] dev typegen refresh failed:\", error);\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"[emdash] dev typegen refresh failed:\", error);\n\t}\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,iBAAiB;AAMvB,SAAgB,qBAAqB,IAA+B;AACnE,KAAI,OAAO,eAAe,YACzB,SAAQ,IAAI,YAAY,gBAAgB,GAAG;;AAI7C,SAAgB,gBAAgB,IAAmB;AAClD,KAAI,OAAO,OAAO,KAAK,QAAQ,eAAe,CAAC,OAAO,KAAK,IAAI,IAAK;CAEpE,MAAM,KAAK,QAAQ,IAAI,YAAY,eAAe;AAClD,KAAI,OAAO,OAAO,WAAY;AAE9B,KAAI;AACH,UAAQ,QAAQ,GAAG,GAAG,CAAC,CAAC,OAAO,UAAmB;AACjD,WAAQ,MAAM,wCAAwC,MAAM;IAC3D;UACM,OAAO;AACf,UAAQ,MAAM,wCAAwC,MAAM"}
1
+ {"version":3,"file":"dev-typegen-DHT7lcMU.mjs","names":[],"sources":["../src/astro/dev-typegen.ts"],"sourcesContent":["/**\n * Dev-only hook for regenerating `emdash-env.d.ts` when the schema changes.\n *\n * The Astro integration registers an environment-specific refresh function\n * (filesystem + local HTTP in Node dev, no-op everywhere else). Schema\n * mutation code just triggers the hook, so runtime modules stay free of\n * Node-only I/O.\n */\n\nconst REFRESH_FN_KEY = \"__emdashDevTypegenRefresh\";\n\nexport interface DevTypegenRefreshFn {\n\t(db: unknown): void | Promise<void>;\n}\n\nexport function setDevTypegenRefresh(fn: DevTypegenRefreshFn): void {\n\tif (typeof globalThis !== \"undefined\") {\n\t\tReflect.set(globalThis, REFRESH_FN_KEY, fn);\n\t}\n}\n\nexport function refreshDevTypes(db: unknown): void {\n\tif (typeof import.meta.env === \"undefined\" || !import.meta.env.DEV) return;\n\n\tconst fn = Reflect.get(globalThis, REFRESH_FN_KEY);\n\tif (typeof fn !== \"function\") return;\n\n\ttry {\n\t\tPromise.resolve(fn(db)).catch((error: unknown) => {\n\t\t\tconsole.error(\"[emdash] dev typegen refresh failed:\", error);\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(\"[emdash] dev typegen refresh failed:\", error);\n\t}\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,iBAAiB;AAMvB,SAAgB,qBAAqB,IAA+B;AACnE,KAAI,OAAO,eAAe,YACzB,SAAQ,IAAI,YAAY,gBAAgB,GAAG;;AAI7C,SAAgB,gBAAgB,IAAmB;AAClD,KAAI,OAAO,OAAO,KAAK,QAAQ,eAAe,CAAC,OAAO,KAAK,IAAI,IAAK;CAEpE,MAAM,KAAK,QAAQ,IAAI,YAAY,eAAe;AAClD,KAAI,OAAO,OAAO,WAAY;AAE9B,KAAI;AACH,UAAQ,QAAQ,GAAG,GAAG,CAAC,CAAC,OAAO,UAAmB;AACjD,WAAQ,MAAM,wCAAwC,MAAM;IAC3D;UACM,OAAO;AACf,UAAQ,MAAM,wCAAwC,MAAM"}
@@ -1,7 +1,7 @@
1
1
  import { t as withTransaction } from "./transaction-0KOpOyMu.mjs";
2
- import { a as hashApiToken, o as isValidScope, r as generatePrefixedToken, t as TOKEN_PREFIXES } from "./api-tokens-BfYts-sq.mjs";
3
- import { o as lookupOAuthClient } from "./oauth-clients-FD7I0J8m.mjs";
4
- import { t as lookupUserRoleAndStatus } from "./oauth-user-lookup-CvIwGpYd.mjs";
2
+ import { a as hashApiToken, o as isValidScope, r as generatePrefixedToken, t as TOKEN_PREFIXES } from "./api-tokens-B_lfpmH3.mjs";
3
+ import { o as lookupOAuthClient } from "./oauth-clients-DJIdOdq0.mjs";
4
+ import { t as lookupUserRoleAndStatus } from "./oauth-user-lookup-HzzW-dkF.mjs";
5
5
  import { clampScopes } from "@emdash-cms/auth";
6
6
  import { generateCodeVerifier } from "arctic";
7
7
 
@@ -463,4 +463,4 @@ async function handleTokenRevoke(db, input) {
463
463
 
464
464
  //#endregion
465
465
  export { handleTokenRevoke as a, handleTokenRefresh as i, handleDeviceCodeRequest as n, handleDeviceTokenExchange as r, handleDeviceAuthorize as t };
466
- //# sourceMappingURL=device-flow-D2oCWvLJ.mjs.map
466
+ //# sourceMappingURL=device-flow-Cf6bhCCT.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"device-flow-D2oCWvLJ.mjs","names":[],"sources":["../src/api/handlers/device-flow.ts"],"sourcesContent":["/**\n * OAuth Device Flow handlers (RFC 8628).\n *\n * EmDash acts as an OAuth 2.0 authorization server. The CLI requests\n * a device code, displays a URL + user code, and polls for a token.\n * The user opens a browser, logs in, enters the code, and the CLI gets\n * an access + refresh token pair.\n *\n * Uses arctic for code generation and @emdash-cms/auth for token utilities.\n */\n\nimport { clampScopes } from \"@emdash-cms/auth\";\nimport type { RoleLevel } from \"@emdash-cms/auth\";\nimport { generateCodeVerifier } from \"arctic\";\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tgeneratePrefixedToken,\n\thashApiToken,\n\tisValidScope,\n\tTOKEN_PREFIXES,\n} from \"../../auth/api-tokens.js\";\nimport { withTransaction } from \"../../database/transaction.js\";\nimport type { Database } from \"../../database/types.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { lookupOAuthClient } from \"./oauth-clients.js\";\nimport { lookupUserRoleAndStatus } from \"./oauth-user-lookup.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Device codes expire after 15 minutes */\nconst DEVICE_CODE_TTL_SECONDS = 15 * 60;\n\n/** Default polling interval in seconds */\nconst DEFAULT_INTERVAL = 5;\n\n/** RFC 8628 §3.5: interval increase on slow_down */\nconst SLOW_DOWN_INCREMENT = 5;\n\n/** Maximum slow_down interval cap (seconds) */\nconst MAX_SLOW_DOWN_INTERVAL = 60;\n\n/** Access token TTL: 1 hour */\nconst ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\n/** Refresh token TTL: 90 days */\nconst REFRESH_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n/** Default scopes for CLI login */\nconst DEFAULT_SCOPES = [\n\t\"content:read\",\n\t\"content:write\",\n\t\"media:read\",\n\t\"media:write\",\n\t\"schema:read\",\n] as const;\n\n/** Pattern to normalize user codes (strip hyphens) */\nconst HYPHEN_PATTERN = /-/g;\n\n/** Characters for user codes (uppercase, no ambiguous chars like 0/O, 1/I) */\nconst USER_CODE_CHARS = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface DeviceCodeResponse {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval: number;\n}\n\nexport interface TokenResponse {\n\taccess_token: string;\n\trefresh_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n}\n\n// RFC 8628 error codes\nexport type DeviceFlowError =\n\t| \"authorization_pending\"\n\t| \"slow_down\"\n\t| \"expired_token\"\n\t| \"access_denied\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Generate a short human-readable user code (XXXX-XXXX) */\nfunction generateUserCode(): string {\n\tconst bytes = new Uint8Array(8);\n\tcrypto.getRandomValues(bytes);\n\tconst chars = Array.from(bytes, (b) => USER_CODE_CHARS[b % USER_CODE_CHARS.length]).join(\"\");\n\treturn `${chars.slice(0, 4)}-${chars.slice(4, 8)}`;\n}\n\n/** Get an ISO datetime string offset from now */\nfunction expiresAt(seconds: number): string {\n\treturn new Date(Date.now() + seconds * 1000).toISOString();\n}\n\n/** Validate and normalize scopes. Returns validated scope list. */\nfunction normalizeScopes(requested?: string[]): string[] {\n\tif (!requested || requested.length === 0) {\n\t\treturn [...DEFAULT_SCOPES];\n\t}\n\treturn requested.filter(isValidScope);\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\n/**\n * POST /oauth/device/code\n *\n * Issue a device code + user code. The CLI displays the user code\n * and tells the user to open the verification URI.\n */\nexport async function handleDeviceCodeRequest(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tclient_id?: string;\n\t\tscope?: string;\n\t},\n\tverificationUri: string,\n): Promise<ApiResult<DeviceCodeResponse>> {\n\ttry {\n\t\t// Note: client_id is accepted but not validated against _emdash_oauth_clients\n\t\t// because the CLI uses a well-known built-in client ID (\"emdash-cli\") that\n\t\t// isn't stored in the DB. Full client_id validation + scope clamping for the\n\t\t// device flow is tracked as a follow-up.\n\n\t\t// Parse and validate scopes\n\t\tconst requestedScopes = input.scope ? input.scope.split(\" \").filter(Boolean) : [];\n\t\tconst scopes = normalizeScopes(requestedScopes);\n\n\t\tif (scopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_SCOPE\", message: \"No valid scopes requested\" },\n\t\t\t};\n\t\t}\n\n\t\tconst deviceCode = generateCodeVerifier();\n\t\tconst userCode = generateUserCode();\n\t\tconst expires = expiresAt(DEVICE_CODE_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_device_codes\")\n\t\t\t.values({\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tstatus: \"pending\",\n\t\t\t\texpires_at: expires,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tverification_uri: verificationUri,\n\t\t\t\texpires_in: DEVICE_CODE_TTL_SECONDS,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DEVICE_CODE_ERROR\",\n\t\t\t\tmessage: \"Failed to create device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/token\n *\n * CLI polls this endpoint with the device_code. Returns:\n * - 200 with tokens if authorized\n * - 400 with error \"authorization_pending\" while waiting\n * - 400 with error \"slow_down\" if polling too fast\n * - 400 with error \"expired_token\" if the code expired\n * - 400 with error \"access_denied\" if the user denied\n */\nexport async function handleDeviceTokenExchange(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tdevice_code: string;\n\t\tgrant_type: string;\n\t},\n): Promise<\n\tApiResult<TokenResponse> & { deviceFlowError?: DeviceFlowError; deviceFlowInterval?: number }\n> {\n\ttry {\n\t\t// Validate grant_type\n\t\tif (input.grant_type !== \"urn:ietf:params:oauth:grant-type:device_code\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\t// Look up the device code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code\" },\n\t\t\t};\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < now) {\n\t\t\t// Clean up expired code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"expired_token\",\n\t\t\t\terror: { code: \"expired_token\", message: \"The device code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check status\n\t\tif (row.status === \"denied\") {\n\t\t\t// Clean up denied code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"access_denied\",\n\t\t\t\terror: { code: \"access_denied\", message: \"The user denied the request\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status === \"pending\") {\n\t\t\t// RFC 8628 §3.5: slow_down enforcement during polling phase.\n\t\t\t// Only applies while waiting for authorization — once authorized,\n\t\t\t// the final exchange proceeds without throttling.\n\t\t\tif (row.last_polled_at) {\n\t\t\t\tconst lastPolled = new Date(row.last_polled_at);\n\t\t\t\tconst elapsedSeconds = (now.getTime() - lastPolled.getTime()) / 1000;\n\n\t\t\t\tif (elapsedSeconds < row.interval) {\n\t\t\t\t\t// Too fast — increase interval by 5s per RFC 8628 §3.5, capped at 60s\n\t\t\t\t\tconst newInterval = Math.min(row.interval + SLOW_DOWN_INCREMENT, MAX_SLOW_DOWN_INTERVAL);\n\t\t\t\t\tawait db\n\t\t\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tinterval: newInterval,\n\t\t\t\t\t\t\tlast_polled_at: now.toISOString(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t\t\t.execute();\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdeviceFlowError: \"slow_down\",\n\t\t\t\t\t\tdeviceFlowInterval: newInterval,\n\t\t\t\t\t\terror: { code: \"slow_down\", message: \"Polling too fast\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update last_polled_at for future slow_down checks\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ last_polled_at: now.toISOString() })\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"authorization_pending\",\n\t\t\t\terror: { code: \"authorization_pending\", message: \"Authorization pending\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status !== \"authorized\" || !row.user_id) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code state\" },\n\t\t\t};\n\t\t}\n\n\t\t// Generate tokens before consuming the device code so that if\n\t\t// generation fails, the code is still available for retry.\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\t\tconst refreshToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_REFRESH);\n\t\tconst refreshExpires = expiresAt(REFRESH_TOKEN_TTL_SECONDS);\n\n\t\t// Atomically consume the device code and create tokens in a single\n\t\t// transaction. DELETE...RETURNING prevents TOCTOU: two concurrent\n\t\t// requests race on the DELETE, only one gets a row back. Wrapping\n\t\t// in a transaction ensures the code isn't consumed if token storage fails.\n\t\tconst result = await withTransaction(db, async (trx) => {\n\t\t\tconst consumed = await trx\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.where(\"status\", \"=\", \"authorized\")\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (!consumed) return null;\n\n\t\t\tif (!consumed.user_id) return null;\n\n\t\t\tconst scopes = JSON.parse(consumed.scopes) as string[];\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\t\ttoken_type: \"access\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: accessExpires,\n\t\t\t\t\trefresh_token_hash: refreshToken.hash,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: refreshToken.hash,\n\t\t\t\t\ttoken_type: \"refresh\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: refreshExpires,\n\t\t\t\t\trefresh_token_hash: null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\treturn { scopes };\n\t\t});\n\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Device code already consumed\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: refreshToken.raw,\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: result.scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_EXCHANGE_ERROR\",\n\t\t\t\tmessage: \"Failed to exchange device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/authorize\n *\n * The user submits the user_code after logging in via the browser.\n * This authorizes the device code, allowing the CLI to exchange it for tokens.\n *\n * Scopes are clamped to the user's role at this point. The stored scopes\n * are replaced with the intersection of requested scopes and the scopes\n * the user's role permits. This prevents scope escalation.\n */\nexport async function handleDeviceAuthorize(\n\tdb: Kysely<Database>,\n\tuserId: string,\n\tuserRole: RoleLevel,\n\tinput: {\n\t\tuser_code: string;\n\t\taction?: \"approve\" | \"deny\";\n\t},\n): Promise<ApiResult<{ authorized: boolean }>> {\n\ttry {\n\t\t// Normalize user code (strip hyphens, uppercase)\n\t\tconst normalizedCode = input.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase();\n\n\t\t// Look up the device code by user_code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.execute();\n\n\t\t// Find the matching code (strip hyphens for comparison)\n\t\tconst match = row.find(\n\t\t\t(r) => r.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase() === normalizedCode,\n\t\t);\n\n\t\tif (!match) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CODE\", message: \"Invalid or expired code\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(match.expires_at) < new Date()) {\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"EXPIRED_CODE\", message: \"This code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\tconst action = input.action ?? \"approve\";\n\n\t\tif (action === \"deny\") {\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ status: \"denied\" })\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn { success: true, data: { authorized: false } };\n\t\t}\n\n\t\t// Clamp requested scopes to those the user's role permits.\n\t\t// effective_scopes = requested_scopes ∩ scopesForRole(user.role)\n\t\tconst requestedScopes = JSON.parse(match.scopes) as string[];\n\t\tconst effectiveScopes = clampScopes(requestedScopes, userRole);\n\n\t\tif (effectiveScopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INSUFFICIENT_ROLE\",\n\t\t\t\t\tmessage: \"Your role does not permit any of the requested scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Approve: set user_id, status, and clamped scopes\n\t\tawait db\n\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t.set({\n\t\t\t\tstatus: \"authorized\",\n\t\t\t\tuser_id: userId,\n\t\t\t\tscopes: JSON.stringify(effectiveScopes),\n\t\t\t})\n\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t.execute();\n\n\t\treturn { success: true, data: { authorized: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"AUTHORIZE_ERROR\",\n\t\t\t\tmessage: \"Failed to authorize device\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/refresh\n *\n * Exchange a refresh token for a new access token.\n * The refresh token itself is not rotated (per spec: optional rotation).\n */\nexport async function handleTokenRefresh(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\trefresh_token: string;\n\t\tgrant_type: string;\n\t},\n): Promise<ApiResult<TokenResponse>> {\n\ttry {\n\t\tif (input.grant_type !== \"refresh_token\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\tif (!input.refresh_token.startsWith(TOKEN_PREFIXES.OAUTH_REFRESH)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token format\" },\n\t\t\t};\n\t\t}\n\n\t\tconst refreshHash = hashApiToken(input.refresh_token);\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.selectAll()\n\t\t\t.where(\"token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"refresh\")\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < new Date()) {\n\t\t\t// Clean up expired refresh token and its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Refresh token expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// SEC-42: Revalidate user role before issuing new access token.\n\t\t// SEC-43: Reject refresh if user is disabled or deleted.\n\t\tconst userInfo = await lookupUserRoleAndStatus(db, row.user_id);\n\t\tif (!userInfo) {\n\t\t\t// User no longer exists — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User not found\" },\n\t\t\t};\n\t\t}\n\n\t\tif (userInfo.disabled) {\n\t\t\t// User is disabled — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User account is disabled\" },\n\t\t\t};\n\t\t}\n\n\t\t// Revalidate stored scopes against the user's current role.\n\t\t// A demoted user's refresh token may carry stale elevated scopes.\n\t\tconst storedScopes = JSON.parse(row.scopes) as string[];\n\t\tlet scopes = clampScopes(storedScopes, userInfo.role);\n\n\t\t// SEC-41: Intersect with the client's registered scopes (if any).\n\t\t// Same check as the approval path — a client registered with limited\n\t\t// scopes should never receive elevated scopes on refresh, even if the\n\t\t// user's role would allow them.\n\t\tif (row.client_id) {\n\t\t\tconst client = await lookupOAuthClient(db, row.client_id);\n\t\t\tif (client?.scopes?.length) {\n\t\t\t\tscopes = scopes.filter((s: string) => client.scopes!.includes(s));\n\t\t\t}\n\t\t}\n\n\t\tif (scopes.length === 0) {\n\t\t\t// User's role no longer supports any of the token's scopes — revoke\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INVALID_GRANT\",\n\t\t\t\t\tmessage: \"User role no longer supports any of the token's scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Delete old access tokens for this refresh token\n\t\tawait db\n\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"access\")\n\t\t\t.execute();\n\n\t\t// Generate new access token\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t.values({\n\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\ttoken_type: \"access\",\n\t\t\t\tuser_id: row.user_id,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tclient_type: row.client_type,\n\t\t\t\texpires_at: accessExpires,\n\t\t\t\trefresh_token_hash: refreshHash,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: input.refresh_token, // Return same refresh token\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REFRESH_ERROR\",\n\t\t\t\tmessage: \"Failed to refresh token\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/revoke\n *\n * Revoke an access or refresh token. If a refresh token is revoked,\n * also revoke all associated access tokens.\n *\n * Per RFC 7009, this endpoint always returns 200 (even for invalid tokens).\n */\nexport async function handleTokenRevoke(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\ttoken: string;\n\t},\n): Promise<ApiResult<{ revoked: boolean }>> {\n\ttry {\n\t\tconst hash = hashApiToken(input.token);\n\n\t\t// Look up the token\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.select([\"token_hash\", \"token_type\", \"refresh_token_hash\"])\n\t\t\t.where(\"token_hash\", \"=\", hash)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\t// Per RFC 7009: always 200, even for invalid tokens\n\t\t\treturn { success: true, data: { revoked: true } };\n\t\t}\n\n\t\tif (row.token_type === \"refresh\") {\n\t\t\t// Revoke refresh token and all its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"refresh_token_hash\", \"=\", hash).execute();\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t} else {\n\t\t\t// Revoke just the access token\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t}\n\n\t\treturn { success: true, data: { revoked: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REVOKE_ERROR\",\n\t\t\t\tmessage: \"Failed to revoke token\",\n\t\t\t},\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAM,0BAA0B;;AAGhC,MAAM,mBAAmB;;AAGzB,MAAM,sBAAsB;;AAG5B,MAAM,yBAAyB;;AAG/B,MAAM,2BAA2B;;AAGjC,MAAM,4BAA4B,OAAU,KAAK;;AAGjD,MAAM,iBAAiB;CACtB;CACA;CACA;CACA;CACA;CACA;;AAGD,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAkCxB,SAAS,mBAA2B;CACnC,MAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAO,gBAAgB,MAAM;CAC7B,MAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM,gBAAgB,IAAI,IAAwB,CAAC,KAAK,GAAG;AAC5F,QAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,MAAM,G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ClC,OAAO;GAAC;GAAc;GAAc;GAAqB,CAAC,CAC1D,MAAM,cAAc,KAAK,KAAK,CAC9B,kBAAkB;AAEpB,MAAI,CAAC,IAEJ,QAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;AAGlD,MAAI,IAAI,eAAe,WAAW;AAEjC,SAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,sBAAsB,KAAK,KAAK,CAAC,SAAS;AAC5F,SAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;QAGpF,OAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;AAGrF,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD"}
1
+ {"version":3,"file":"device-flow-Cf6bhCCT.mjs","names":[],"sources":["../src/api/handlers/device-flow.ts"],"sourcesContent":["/**\n * OAuth Device Flow handlers (RFC 8628).\n *\n * EmDash acts as an OAuth 2.0 authorization server. The CLI requests\n * a device code, displays a URL + user code, and polls for a token.\n * The user opens a browser, logs in, enters the code, and the CLI gets\n * an access + refresh token pair.\n *\n * Uses arctic for code generation and @emdash-cms/auth for token utilities.\n */\n\nimport { clampScopes } from \"@emdash-cms/auth\";\nimport type { RoleLevel } from \"@emdash-cms/auth\";\nimport { generateCodeVerifier } from \"arctic\";\nimport type { Kysely } from \"kysely\";\n\nimport {\n\tgeneratePrefixedToken,\n\thashApiToken,\n\tisValidScope,\n\tTOKEN_PREFIXES,\n} from \"../../auth/api-tokens.js\";\nimport { withTransaction } from \"../../database/transaction.js\";\nimport type { Database } from \"../../database/types.js\";\nimport type { ApiResult } from \"../types.js\";\nimport { lookupOAuthClient } from \"./oauth-clients.js\";\nimport { lookupUserRoleAndStatus } from \"./oauth-user-lookup.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Device codes expire after 15 minutes */\nconst DEVICE_CODE_TTL_SECONDS = 15 * 60;\n\n/** Default polling interval in seconds */\nconst DEFAULT_INTERVAL = 5;\n\n/** RFC 8628 §3.5: interval increase on slow_down */\nconst SLOW_DOWN_INCREMENT = 5;\n\n/** Maximum slow_down interval cap (seconds) */\nconst MAX_SLOW_DOWN_INTERVAL = 60;\n\n/** Access token TTL: 1 hour */\nconst ACCESS_TOKEN_TTL_SECONDS = 60 * 60;\n\n/** Refresh token TTL: 90 days */\nconst REFRESH_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n/** Default scopes for CLI login */\nconst DEFAULT_SCOPES = [\n\t\"content:read\",\n\t\"content:write\",\n\t\"media:read\",\n\t\"media:write\",\n\t\"schema:read\",\n] as const;\n\n/** Pattern to normalize user codes (strip hyphens) */\nconst HYPHEN_PATTERN = /-/g;\n\n/** Characters for user codes (uppercase, no ambiguous chars like 0/O, 1/I) */\nconst USER_CODE_CHARS = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface DeviceCodeResponse {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval: number;\n}\n\nexport interface TokenResponse {\n\taccess_token: string;\n\trefresh_token: string;\n\ttoken_type: \"Bearer\";\n\texpires_in: number;\n\tscope: string;\n}\n\n// RFC 8628 error codes\nexport type DeviceFlowError =\n\t| \"authorization_pending\"\n\t| \"slow_down\"\n\t| \"expired_token\"\n\t| \"access_denied\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Generate a short human-readable user code (XXXX-XXXX) */\nfunction generateUserCode(): string {\n\tconst bytes = new Uint8Array(8);\n\tcrypto.getRandomValues(bytes);\n\tconst chars = Array.from(bytes, (b) => USER_CODE_CHARS[b % USER_CODE_CHARS.length]).join(\"\");\n\treturn `${chars.slice(0, 4)}-${chars.slice(4, 8)}`;\n}\n\n/** Get an ISO datetime string offset from now */\nfunction expiresAt(seconds: number): string {\n\treturn new Date(Date.now() + seconds * 1000).toISOString();\n}\n\n/** Validate and normalize scopes. Returns validated scope list. */\nfunction normalizeScopes(requested?: string[]): string[] {\n\tif (!requested || requested.length === 0) {\n\t\treturn [...DEFAULT_SCOPES];\n\t}\n\treturn requested.filter(isValidScope);\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\n/**\n * POST /oauth/device/code\n *\n * Issue a device code + user code. The CLI displays the user code\n * and tells the user to open the verification URI.\n */\nexport async function handleDeviceCodeRequest(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tclient_id?: string;\n\t\tscope?: string;\n\t},\n\tverificationUri: string,\n): Promise<ApiResult<DeviceCodeResponse>> {\n\ttry {\n\t\t// Note: client_id is accepted but not validated against _emdash_oauth_clients\n\t\t// because the CLI uses a well-known built-in client ID (\"emdash-cli\") that\n\t\t// isn't stored in the DB. Full client_id validation + scope clamping for the\n\t\t// device flow is tracked as a follow-up.\n\n\t\t// Parse and validate scopes\n\t\tconst requestedScopes = input.scope ? input.scope.split(\" \").filter(Boolean) : [];\n\t\tconst scopes = normalizeScopes(requestedScopes);\n\n\t\tif (scopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_SCOPE\", message: \"No valid scopes requested\" },\n\t\t\t};\n\t\t}\n\n\t\tconst deviceCode = generateCodeVerifier();\n\t\tconst userCode = generateUserCode();\n\t\tconst expires = expiresAt(DEVICE_CODE_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_device_codes\")\n\t\t\t.values({\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tstatus: \"pending\",\n\t\t\t\texpires_at: expires,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\tdevice_code: deviceCode,\n\t\t\t\tuser_code: userCode,\n\t\t\t\tverification_uri: verificationUri,\n\t\t\t\texpires_in: DEVICE_CODE_TTL_SECONDS,\n\t\t\t\tinterval: DEFAULT_INTERVAL,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"DEVICE_CODE_ERROR\",\n\t\t\t\tmessage: \"Failed to create device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/token\n *\n * CLI polls this endpoint with the device_code. Returns:\n * - 200 with tokens if authorized\n * - 400 with error \"authorization_pending\" while waiting\n * - 400 with error \"slow_down\" if polling too fast\n * - 400 with error \"expired_token\" if the code expired\n * - 400 with error \"access_denied\" if the user denied\n */\nexport async function handleDeviceTokenExchange(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\tdevice_code: string;\n\t\tgrant_type: string;\n\t},\n): Promise<\n\tApiResult<TokenResponse> & { deviceFlowError?: DeviceFlowError; deviceFlowInterval?: number }\n> {\n\ttry {\n\t\t// Validate grant_type\n\t\tif (input.grant_type !== \"urn:ietf:params:oauth:grant-type:device_code\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\t// Look up the device code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code\" },\n\t\t\t};\n\t\t}\n\n\t\tconst now = new Date();\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < now) {\n\t\t\t// Clean up expired code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"expired_token\",\n\t\t\t\terror: { code: \"expired_token\", message: \"The device code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check status\n\t\tif (row.status === \"denied\") {\n\t\t\t// Clean up denied code\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"access_denied\",\n\t\t\t\terror: { code: \"access_denied\", message: \"The user denied the request\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status === \"pending\") {\n\t\t\t// RFC 8628 §3.5: slow_down enforcement during polling phase.\n\t\t\t// Only applies while waiting for authorization — once authorized,\n\t\t\t// the final exchange proceeds without throttling.\n\t\t\tif (row.last_polled_at) {\n\t\t\t\tconst lastPolled = new Date(row.last_polled_at);\n\t\t\t\tconst elapsedSeconds = (now.getTime() - lastPolled.getTime()) / 1000;\n\n\t\t\t\tif (elapsedSeconds < row.interval) {\n\t\t\t\t\t// Too fast — increase interval by 5s per RFC 8628 §3.5, capped at 60s\n\t\t\t\t\tconst newInterval = Math.min(row.interval + SLOW_DOWN_INCREMENT, MAX_SLOW_DOWN_INTERVAL);\n\t\t\t\t\tawait db\n\t\t\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tinterval: newInterval,\n\t\t\t\t\t\t\tlast_polled_at: now.toISOString(),\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t\t\t.execute();\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\tdeviceFlowError: \"slow_down\",\n\t\t\t\t\t\tdeviceFlowInterval: newInterval,\n\t\t\t\t\t\terror: { code: \"slow_down\", message: \"Polling too fast\" },\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update last_polled_at for future slow_down checks\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ last_polled_at: now.toISOString() })\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tdeviceFlowError: \"authorization_pending\",\n\t\t\t\terror: { code: \"authorization_pending\", message: \"Authorization pending\" },\n\t\t\t};\n\t\t}\n\n\t\tif (row.status !== \"authorized\" || !row.user_id) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid device code state\" },\n\t\t\t};\n\t\t}\n\n\t\t// Generate tokens before consuming the device code so that if\n\t\t// generation fails, the code is still available for retry.\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\t\tconst refreshToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_REFRESH);\n\t\tconst refreshExpires = expiresAt(REFRESH_TOKEN_TTL_SECONDS);\n\n\t\t// Atomically consume the device code and create tokens in a single\n\t\t// transaction. DELETE...RETURNING prevents TOCTOU: two concurrent\n\t\t// requests race on the DELETE, only one gets a row back. Wrapping\n\t\t// in a transaction ensures the code isn't consumed if token storage fails.\n\t\tconst result = await withTransaction(db, async (trx) => {\n\t\t\tconst consumed = await trx\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", input.device_code)\n\t\t\t\t.where(\"status\", \"=\", \"authorized\")\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (!consumed) return null;\n\n\t\t\tif (!consumed.user_id) return null;\n\n\t\t\tconst scopes = JSON.parse(consumed.scopes) as string[];\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\t\ttoken_type: \"access\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: accessExpires,\n\t\t\t\t\trefresh_token_hash: refreshToken.hash,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\tawait trx\n\t\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t\t.values({\n\t\t\t\t\ttoken_hash: refreshToken.hash,\n\t\t\t\t\ttoken_type: \"refresh\",\n\t\t\t\t\tuser_id: consumed.user_id,\n\t\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\t\tclient_type: \"cli\",\n\t\t\t\t\texpires_at: refreshExpires,\n\t\t\t\t\trefresh_token_hash: null,\n\t\t\t\t})\n\t\t\t\t.execute();\n\n\t\t\treturn { scopes };\n\t\t});\n\n\t\tif (!result) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Device code already consumed\" },\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: refreshToken.raw,\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: result.scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_EXCHANGE_ERROR\",\n\t\t\t\tmessage: \"Failed to exchange device code\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/device/authorize\n *\n * The user submits the user_code after logging in via the browser.\n * This authorizes the device code, allowing the CLI to exchange it for tokens.\n *\n * Scopes are clamped to the user's role at this point. The stored scopes\n * are replaced with the intersection of requested scopes and the scopes\n * the user's role permits. This prevents scope escalation.\n */\nexport async function handleDeviceAuthorize(\n\tdb: Kysely<Database>,\n\tuserId: string,\n\tuserRole: RoleLevel,\n\tinput: {\n\t\tuser_code: string;\n\t\taction?: \"approve\" | \"deny\";\n\t},\n): Promise<ApiResult<{ authorized: boolean }>> {\n\ttry {\n\t\t// Normalize user code (strip hyphens, uppercase)\n\t\tconst normalizedCode = input.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase();\n\n\t\t// Look up the device code by user_code\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_device_codes\")\n\t\t\t.selectAll()\n\t\t\t.where(\"status\", \"=\", \"pending\")\n\t\t\t.execute();\n\n\t\t// Find the matching code (strip hyphens for comparison)\n\t\tconst match = row.find(\n\t\t\t(r) => r.user_code.replace(HYPHEN_PATTERN, \"\").toUpperCase() === normalizedCode,\n\t\t);\n\n\t\tif (!match) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_CODE\", message: \"Invalid or expired code\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(match.expires_at) < new Date()) {\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_device_codes\")\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"EXPIRED_CODE\", message: \"This code has expired\" },\n\t\t\t};\n\t\t}\n\n\t\tconst action = input.action ?? \"approve\";\n\n\t\tif (action === \"deny\") {\n\t\t\tawait db\n\t\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t\t.set({ status: \"denied\" })\n\t\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t\t.execute();\n\n\t\t\treturn { success: true, data: { authorized: false } };\n\t\t}\n\n\t\t// Clamp requested scopes to those the user's role permits.\n\t\t// effective_scopes = requested_scopes ∩ scopesForRole(user.role)\n\t\tconst requestedScopes = JSON.parse(match.scopes) as string[];\n\t\tconst effectiveScopes = clampScopes(requestedScopes, userRole);\n\n\t\tif (effectiveScopes.length === 0) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INSUFFICIENT_ROLE\",\n\t\t\t\t\tmessage: \"Your role does not permit any of the requested scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Approve: set user_id, status, and clamped scopes\n\t\tawait db\n\t\t\t.updateTable(\"_emdash_device_codes\")\n\t\t\t.set({\n\t\t\t\tstatus: \"authorized\",\n\t\t\t\tuser_id: userId,\n\t\t\t\tscopes: JSON.stringify(effectiveScopes),\n\t\t\t})\n\t\t\t.where(\"device_code\", \"=\", match.device_code)\n\t\t\t.execute();\n\n\t\treturn { success: true, data: { authorized: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"AUTHORIZE_ERROR\",\n\t\t\t\tmessage: \"Failed to authorize device\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/refresh\n *\n * Exchange a refresh token for a new access token.\n * The refresh token itself is not rotated (per spec: optional rotation).\n */\nexport async function handleTokenRefresh(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\trefresh_token: string;\n\t\tgrant_type: string;\n\t},\n): Promise<ApiResult<TokenResponse>> {\n\ttry {\n\t\tif (input.grant_type !== \"refresh_token\") {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"UNSUPPORTED_GRANT_TYPE\", message: \"Invalid grant_type\" },\n\t\t\t};\n\t\t}\n\n\t\tif (!input.refresh_token.startsWith(TOKEN_PREFIXES.OAUTH_REFRESH)) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token format\" },\n\t\t\t};\n\t\t}\n\n\t\tconst refreshHash = hashApiToken(input.refresh_token);\n\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.selectAll()\n\t\t\t.where(\"token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"refresh\")\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Invalid refresh token\" },\n\t\t\t};\n\t\t}\n\n\t\t// Check expiry\n\t\tif (new Date(row.expires_at) < new Date()) {\n\t\t\t// Clean up expired refresh token and its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"Refresh token expired\" },\n\t\t\t};\n\t\t}\n\n\t\t// SEC-42: Revalidate user role before issuing new access token.\n\t\t// SEC-43: Reject refresh if user is disabled or deleted.\n\t\tconst userInfo = await lookupUserRoleAndStatus(db, row.user_id);\n\t\tif (!userInfo) {\n\t\t\t// User no longer exists — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User not found\" },\n\t\t\t};\n\t\t}\n\n\t\tif (userInfo.disabled) {\n\t\t\t// User is disabled — revoke all their tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"user_id\", \"=\", row.user_id).execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: { code: \"INVALID_GRANT\", message: \"User account is disabled\" },\n\t\t\t};\n\t\t}\n\n\t\t// Revalidate stored scopes against the user's current role.\n\t\t// A demoted user's refresh token may carry stale elevated scopes.\n\t\tconst storedScopes = JSON.parse(row.scopes) as string[];\n\t\tlet scopes = clampScopes(storedScopes, userInfo.role);\n\n\t\t// SEC-41: Intersect with the client's registered scopes (if any).\n\t\t// Same check as the approval path — a client registered with limited\n\t\t// scopes should never receive elevated scopes on refresh, even if the\n\t\t// user's role would allow them.\n\t\tif (row.client_id) {\n\t\t\tconst client = await lookupOAuthClient(db, row.client_id);\n\t\t\tif (client?.scopes?.length) {\n\t\t\t\tscopes = scopes.filter((s: string) => client.scopes!.includes(s));\n\t\t\t}\n\t\t}\n\n\t\tif (scopes.length === 0) {\n\t\t\t// User's role no longer supports any of the token's scopes — revoke\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", refreshHash).execute();\n\t\t\tawait db\n\t\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t\t.execute();\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"INVALID_GRANT\",\n\t\t\t\t\tmessage: \"User role no longer supports any of the token's scopes\",\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Delete old access tokens for this refresh token\n\t\tawait db\n\t\t\t.deleteFrom(\"_emdash_oauth_tokens\")\n\t\t\t.where(\"refresh_token_hash\", \"=\", refreshHash)\n\t\t\t.where(\"token_type\", \"=\", \"access\")\n\t\t\t.execute();\n\n\t\t// Generate new access token\n\t\tconst accessToken = generatePrefixedToken(TOKEN_PREFIXES.OAUTH_ACCESS);\n\t\tconst accessExpires = expiresAt(ACCESS_TOKEN_TTL_SECONDS);\n\n\t\tawait db\n\t\t\t.insertInto(\"_emdash_oauth_tokens\")\n\t\t\t.values({\n\t\t\t\ttoken_hash: accessToken.hash,\n\t\t\t\ttoken_type: \"access\",\n\t\t\t\tuser_id: row.user_id,\n\t\t\t\tscopes: JSON.stringify(scopes),\n\t\t\t\tclient_type: row.client_type,\n\t\t\t\texpires_at: accessExpires,\n\t\t\t\trefresh_token_hash: refreshHash,\n\t\t\t})\n\t\t\t.execute();\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: {\n\t\t\t\taccess_token: accessToken.raw,\n\t\t\t\trefresh_token: input.refresh_token, // Return same refresh token\n\t\t\t\ttoken_type: \"Bearer\",\n\t\t\t\texpires_in: ACCESS_TOKEN_TTL_SECONDS,\n\t\t\t\tscope: scopes.join(\" \"),\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REFRESH_ERROR\",\n\t\t\t\tmessage: \"Failed to refresh token\",\n\t\t\t},\n\t\t};\n\t}\n}\n\n/**\n * POST /oauth/token/revoke\n *\n * Revoke an access or refresh token. If a refresh token is revoked,\n * also revoke all associated access tokens.\n *\n * Per RFC 7009, this endpoint always returns 200 (even for invalid tokens).\n */\nexport async function handleTokenRevoke(\n\tdb: Kysely<Database>,\n\tinput: {\n\t\ttoken: string;\n\t},\n): Promise<ApiResult<{ revoked: boolean }>> {\n\ttry {\n\t\tconst hash = hashApiToken(input.token);\n\n\t\t// Look up the token\n\t\tconst row = await db\n\t\t\t.selectFrom(\"_emdash_oauth_tokens\")\n\t\t\t.select([\"token_hash\", \"token_type\", \"refresh_token_hash\"])\n\t\t\t.where(\"token_hash\", \"=\", hash)\n\t\t\t.executeTakeFirst();\n\n\t\tif (!row) {\n\t\t\t// Per RFC 7009: always 200, even for invalid tokens\n\t\t\treturn { success: true, data: { revoked: true } };\n\t\t}\n\n\t\tif (row.token_type === \"refresh\") {\n\t\t\t// Revoke refresh token and all its access tokens\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"refresh_token_hash\", \"=\", hash).execute();\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t} else {\n\t\t\t// Revoke just the access token\n\t\t\tawait db.deleteFrom(\"_emdash_oauth_tokens\").where(\"token_hash\", \"=\", hash).execute();\n\t\t}\n\n\t\treturn { success: true, data: { revoked: true } };\n\t} catch {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tcode: \"TOKEN_REVOKE_ERROR\",\n\t\t\t\tmessage: \"Failed to revoke token\",\n\t\t\t},\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAM,0BAA0B;;AAGhC,MAAM,mBAAmB;;AAGzB,MAAM,sBAAsB;;AAG5B,MAAM,yBAAyB;;AAG/B,MAAM,2BAA2B;;AAGjC,MAAM,4BAA4B,OAAU,KAAK;;AAGjD,MAAM,iBAAiB;CACtB;CACA;CACA;CACA;CACA;CACA;;AAGD,MAAM,iBAAiB;;AAGvB,MAAM,kBAAkB;;AAkCxB,SAAS,mBAA2B;CACnC,MAAM,QAAQ,IAAI,WAAW,EAAE;AAC/B,QAAO,gBAAgB,MAAM;CAC7B,MAAM,QAAQ,MAAM,KAAK,QAAQ,MAAM,gBAAgB,IAAI,IAAwB,CAAC,KAAK,GAAG;AAC5F,QAAO,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,MAAM,MAAM,GAAG,EAAE;;;AAIjD,SAAS,UAAU,SAAyB;AAC3C,QAAO,IAAI,KAAK,KAAK,KAAK,GAAG,UAAU,IAAK,CAAC,aAAa;;;AAI3D,SAAS,gBAAgB,WAAgC;AACxD,KAAI,CAAC,aAAa,UAAU,WAAW,EACtC,QAAO,CAAC,GAAG,eAAe;AAE3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AM,GAAG,WAAW,uBAAuB,CAAC,MAAM,sBAAsB,KAAK,KAAK,CAAC,SAAS;AAC5F,SAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;QAGpF,OAAM,GAAG,WAAW,uBAAuB,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,SAAS;AAGrF,SAAO;GAAE,SAAS;GAAM,MAAM,EAAE,SAAS,MAAM;GAAE;SAC1C;AACP,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD"}
@@ -104,13 +104,34 @@ async function listTablesLike(db, pattern) {
104
104
  if (isPostgres(db)) return (await sql`
105
105
  SELECT table_name FROM information_schema.tables
106
106
  WHERE table_schema = current_schema() AND table_name LIKE ${pattern}
107
+ ORDER BY table_name
107
108
  `.execute(db)).rows.map((r) => r.table_name);
108
109
  return (await sql`
109
110
  SELECT name FROM sqlite_master
110
111
  WHERE type = 'table' AND name LIKE ${pattern}
112
+ ORDER BY name
111
113
  `.execute(db)).rows.map((r) => r.name);
112
114
  }
113
115
  /**
116
+ * List a table's columns in declaration order.
117
+ */
118
+ async function listTableColumns(db, tableName) {
119
+ if (isPostgres(db)) return (await sql`
120
+ SELECT column_name, data_type
121
+ FROM information_schema.columns
122
+ WHERE table_schema = current_schema() AND table_name = ${tableName}
123
+ ORDER BY ordinal_position
124
+ `.execute(db)).rows.map((column) => ({
125
+ name: column.column_name,
126
+ type: column.data_type
127
+ }));
128
+ return (await sql`
129
+ SELECT name, type
130
+ FROM pragma_table_info(${tableName})
131
+ ORDER BY cid
132
+ `.execute(db)).rows;
133
+ }
134
+ /**
114
135
  * Column type for binary data.
115
136
  *
116
137
  * sqlite: blob
@@ -178,6 +199,66 @@ function pluginDataExtractExpr(db, field, options) {
178
199
  return `CASE WHEN json_type(data, '$.${field}') IN ('integer', 'real') THEN ${extract} END`;
179
200
  }
180
201
  /**
202
+ * Build the new value of the `_plugin_storage.data` (text-JSON) column for a
203
+ * guarded `updateIf`, composing wholesale `set` fields and integer `delta`
204
+ * fields into a SINGLE dialect-correct expression.
205
+ *
206
+ * Both branches go through `json_set` / `jsonb_set` so the write never rewrites
207
+ * the whole column from JS (which would require a read-then-write and break the
208
+ * single-statement atomicity that makes no-oversell hold):
209
+ *
210
+ * - **set** field → the value is stored via `json(?)` (SQLite) / `?::jsonb`
211
+ * (Postgres) with `JSON.stringify(value)`, uniformly handling scalars,
212
+ * objects, arrays, and `null` (stored as JSON `null`, never SQL `NULL` — a
213
+ * SQL `NULL` in `jsonb_set` would null the entire `data` column and hit the
214
+ * `NOT NULL` constraint).
215
+ * - **delta** field → `COALESCE(<numeric extract>, 0) + n`, where the extract
216
+ * is the type-guarded numeric form from {@link pluginDataExtractExpr} so a
217
+ * missing or null stored value coalesces to `0` on both dialects. The update
218
+ * guard rejects invalid counters and unsafe results. Integer arithmetic stays
219
+ * integer (Postgres `to_jsonb(numeric)` and SQLite integer `+` both round-trip
220
+ * without a spurious `.0`).
221
+ *
222
+ * Field names are validated (`validateJsonFieldName` / `pluginDataExtractExpr`)
223
+ * before interpolation, so the JSON path is a safe identifier and values are
224
+ * bound parameters — no injection surface.
225
+ *
226
+ * SQLite: json_set(json_set(data, '$.f1', json(?)), '$.f2', COALESCE(json_extract(...), 0) + ?)
227
+ * Postgres: (jsonb_set(jsonb_set(data::jsonb, '{f1}', ?::jsonb), '{f2}', to_jsonb(COALESCE(..., 0) + ?)))::text
228
+ */
229
+ function pluginDataWriteExpr(db, setEntries, deltaEntries) {
230
+ const pg = isPostgres(db);
231
+ let expr = pg ? sql`data::jsonb` : sql`data`;
232
+ for (const [field, value] of setEntries) {
233
+ validateJsonFieldName(field, "plugin storage set field name");
234
+ const json = JSON.stringify(value ?? null);
235
+ if (pg) expr = sql`jsonb_set(${expr}, ${sql.lit(`{${field}}`)}, ${json}::jsonb)`;
236
+ else expr = sql`json_set(${expr}, ${sql.lit(`$.${field}`)}, json(${json}))`;
237
+ }
238
+ for (const [field, n] of deltaEntries) {
239
+ const numericExtract = pluginDataExtractExpr(db, field, { numeric: true });
240
+ if (pg) expr = sql`jsonb_set(${expr}, ${sql.lit(`{${field}}`)}, to_jsonb(COALESCE(${sql.raw(numericExtract)}, 0) + ${n}))`;
241
+ else expr = sql`json_set(${expr}, ${sql.lit(`$.${field}`)}, cast(COALESCE(${sql.raw(numericExtract)}, 0) as integer) + cast(${n} as integer))`;
242
+ }
243
+ if (pg) return sql`(${expr})::text`;
244
+ return sql`${expr}`;
245
+ }
246
+ function pluginDataUpdateGuard(db, deltaEntries) {
247
+ const pg = isPostgres(db);
248
+ const conditions = [pg ? sql`jsonb_typeof(data::jsonb) = 'object'` : sql`json_type(data) = 'object'`];
249
+ for (const [field, amount] of deltaEntries) {
250
+ const numeric = sql.raw(pluginDataExtractExpr(db, field, { numeric: true }));
251
+ const type = pg ? sql`jsonb_typeof(data::jsonb -> ${sql.lit(field)})` : sql`json_type(data, ${sql.lit(`$.${field}`)})`;
252
+ const base = sql`coalesce(${numeric}, 0)`;
253
+ const integral = pg ? sql`${base} = trunc(${base})` : sql`${base} = cast(${base} as integer)`;
254
+ const lower = Math.max(Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER - amount);
255
+ const upper = Math.min(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - amount);
256
+ conditions.push(sql`((${type} is null or ${type} = 'null' or ${numeric} is not null)
257
+ and ${integral} and ${base} >= ${lower} and ${base} <= ${upper})`);
258
+ }
259
+ return sql`(${sql.join(conditions, sql` and `)})`;
260
+ }
261
+ /**
181
262
  * SQL expression for ordering plugin-storage rows by a `data` field.
182
263
  *
183
264
  * `ORDER BY` has no bound operand to infer numeric-vs-text from, so extracting
@@ -198,5 +279,5 @@ function pluginDataOrderExpr(db, field) {
198
279
  }
199
280
 
200
281
  //#endregion
201
- export { currentTimestamp as a, isSqlite as c, pluginDataExtractExpr as d, pluginDataOrderExpr as f, compoundSelectLimit as i, jsonExtractExpr as l, buildStatusCondition as n, currentTimestampValue as o, tableExists as p, columnExists as r, isPostgres as s, binaryType as t, listTablesLike as u };
202
- //# sourceMappingURL=dialect-helpers-BSbfaO3F.mjs.map
282
+ export { currentTimestamp as a, isSqlite as c, listTablesLike as d, pluginDataExtractExpr as f, tableExists as g, pluginDataWriteExpr as h, compoundSelectLimit as i, jsonExtractExpr as l, pluginDataUpdateGuard as m, buildStatusCondition as n, currentTimestampValue as o, pluginDataOrderExpr as p, columnExists as r, isPostgres as s, binaryType as t, listTableColumns as u };
283
+ //# sourceMappingURL=dialect-helpers-BcQvkHgn.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dialect-helpers-BcQvkHgn.mjs","names":[],"sources":["../src/database/dialect-helpers.ts"],"sourcesContent":["/**\n * Dialect-specific SQL helpers\n *\n * Every function takes a Kysely `db` instance and detects the dialect from\n * the adapter class. No module-level state, no globals, no heuristics —\n * the adapter is the source of truth.\n *\n * This is NOT an ORM abstraction — just targeted helpers for the ~15 places\n * that use raw dialect-specific SQL. Most Kysely schema builder code already\n * works cross-dialect.\n */\n\nimport type { ColumnDataType, Kysely, RawBuilder } from \"kysely\";\nimport { PostgresAdapter, sql } from \"kysely\";\n\nimport type { DatabaseDialectType } from \"../db/adapters.js\";\nimport type { Database } from \"./types.js\";\nimport { validateIdentifier, validateJsonFieldName } from \"./validate.js\";\n\nexport type { DatabaseDialectType };\n\n/**\n * Detect dialect type from a Kysely instance via the adapter class.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function detectDialect(db: Kysely<any>): DatabaseDialectType {\n\tif (db.getExecutor().adapter instanceof PostgresAdapter) return \"postgres\";\n\treturn \"sqlite\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function isSqlite(db: Kysely<any>): boolean {\n\treturn detectDialect(db) === \"sqlite\";\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function isPostgres(db: Kysely<any>): boolean {\n\treturn detectDialect(db) === \"postgres\";\n}\n\n/**\n * Declared by an adapter whose backend caps the number of terms in a compound\n * SELECT (`UNION ALL`, `INTERSECT`, `EXCEPT`). SQLite's own\n * SQLITE_LIMIT_COMPOUND_SELECT default is 500 — high enough that no query\n * EmDash builds approaches it — but Cloudflare D1 sets it to 5 and rejects\n * anything larger with \"too many terms in compound SELECT\".\n */\nexport interface CompoundSelectLimitedAdapter {\n\t/** Maximum terms per compound SELECT. Must be a positive integer. */\n\treadonly compoundSelectLimit: number;\n}\n\n/**\n * The backend's compound-SELECT ceiling, or null when it has none worth\n * splitting statements for. Only the adapter knows: the limit is a property of\n * the SQLite build behind the dialect, not of the SQL flavour, so two \"sqlite\"\n * dialects can answer differently.\n *\n * A declared ceiling must be a positive integer — callers batch by it, and\n * every other value silently misbehaves rather than failing: 0 and negatives\n * never advance the batch cursor, fractions overlap batches and double-count,\n * NaN yields an empty batch. A malformed declaration throws here, where the\n * message can name the adapter.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function compoundSelectLimit(db: Kysely<any>): number | null {\n\tconst adapter: object = db.getExecutor().adapter;\n\tif (!(\"compoundSelectLimit\" in adapter)) return null;\n\n\tconst limit: unknown = adapter.compoundSelectLimit;\n\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1) {\n\t\tthrow new Error(\n\t\t\t`${adapter.constructor.name} declares compoundSelectLimit ${String(limit)}; it must be a positive integer.`,\n\t\t);\n\t}\n\treturn limit;\n}\n\n/**\n * Default timestamp expression for column defaults.\n * Wrapped in parens for use in CREATE TABLE ... DEFAULT (...).\n *\n * sqlite: (datetime('now'))\n * postgres: CURRENT_TIMESTAMP\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function currentTimestamp(db: Kysely<any>): RawBuilder<string> {\n\tif (isPostgres(db)) {\n\t\treturn sql`CURRENT_TIMESTAMP`;\n\t}\n\treturn sql`(datetime('now'))`;\n}\n\n/**\n * Timestamp expression for use in WHERE clauses and SET expressions.\n * No wrapping parens.\n *\n * sqlite: datetime('now')\n * postgres: CURRENT_TIMESTAMP\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function currentTimestampValue(db: Kysely<any>): RawBuilder<string> {\n\tif (isPostgres(db)) {\n\t\treturn sql`CURRENT_TIMESTAMP`;\n\t}\n\treturn sql`datetime('now')`;\n}\n\n/**\n * Build WHERE clause for status filtering on a content table.\n * Scheduled content becomes public only after the publication sweep commits\n * the row with a literal `published` status.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function buildStatusCondition(\n\t_db: Kysely<any>,\n\tstatus: string,\n\ttablePrefix?: string,\n): ReturnType<typeof sql> {\n\tconst statusField = tablePrefix ? `${tablePrefix}.status` : \"status\";\n\treturn sql`${sql.ref(statusField)} = ${status}`;\n}\n\n/**\n * Check if a table exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function tableExists(db: Kysely<any>, tableName: string): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\t// Scope to the active schema (matches indexExists/columnExists below).\n\t\t// Hardcoding 'public' breaks non-public-schema Postgres deployments.\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.tables\n\t\t\t\tWHERE table_schema = current_schema() AND table_name = ${tableName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table' AND name = ${tableName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * Check if an index exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function indexExists(db: Kysely<any>, indexName: string): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM pg_indexes\n\t\t\t\tWHERE schemaname = current_schema() AND indexname = ${indexName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'index' AND name = ${indexName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * Check if a column exists in the database.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function columnExists(\n\tdb: Kysely<any>,\n\ttableName: string,\n\tcolumnName: string,\n): Promise<boolean> {\n\tif (isPostgres(db)) {\n\t\tconst result = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\t\tWHERE table_schema = current_schema()\n\t\t\t\t\tAND table_name = ${tableName}\n\t\t\t\t\tAND column_name = ${columnName}\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\treturn result.rows[0]?.exists === true;\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM pragma_table_info(${tableName})\n\t\tWHERE name = ${columnName}\n\t`.execute(db);\n\treturn result.rows.length > 0;\n}\n\n/**\n * List tables matching a LIKE pattern.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function listTablesLike(db: Kysely<any>, pattern: string): Promise<string[]> {\n\tif (isPostgres(db)) {\n\t\t// Scope to the connection's active schema rather than hardcoding\n\t\t// 'public'. A Postgres deployment using a non-public schema (per-tenant\n\t\t// or shared-cluster setups), or per-test schemas, otherwise sees tables\n\t\t// from the wrong schema — or none at all. Mirrors migration 038.\n\t\tconst result = await sql<{ table_name: string }>`\n\t\t\tSELECT table_name FROM information_schema.tables\n\t\t\tWHERE table_schema = current_schema() AND table_name LIKE ${pattern}\n\t\t\tORDER BY table_name\n\t\t`.execute(db);\n\t\treturn result.rows.map((r) => r.table_name);\n\t}\n\n\tconst result = await sql<{ name: string }>`\n\t\tSELECT name FROM sqlite_master\n\t\tWHERE type = 'table' AND name LIKE ${pattern}\n\t\tORDER BY name\n\t`.execute(db);\n\treturn result.rows.map((r) => r.name);\n}\n\nexport interface TableColumnInfo {\n\tname: string;\n\ttype: string;\n}\n\n/**\n * List a table's columns in declaration order.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport async function listTableColumns(\n\tdb: Kysely<any>,\n\ttableName: string,\n): Promise<TableColumnInfo[]> {\n\tif (isPostgres(db)) {\n\t\tconst result = await sql<{\n\t\t\tcolumn_name: string;\n\t\t\tdata_type: string;\n\t\t}>`\n\t\t\tSELECT column_name, data_type\n\t\t\tFROM information_schema.columns\n\t\t\tWHERE table_schema = current_schema() AND table_name = ${tableName}\n\t\t\tORDER BY ordinal_position\n\t\t`.execute(db);\n\t\treturn result.rows.map((column) => ({\n\t\t\tname: column.column_name,\n\t\t\ttype: column.data_type,\n\t\t}));\n\t}\n\n\tconst result = await sql<{ name: string; type: string }>`\n\t\tSELECT name, type\n\t\tFROM pragma_table_info(${tableName})\n\t\tORDER BY cid\n\t`.execute(db);\n\treturn result.rows;\n}\n\n/**\n * Column type for binary data.\n *\n * sqlite: blob\n * postgres: bytea\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function binaryType(db: Kysely<any>): ColumnDataType {\n\tif (isPostgres(db)) {\n\t\treturn \"bytea\";\n\t}\n\treturn \"blob\";\n}\n\n/**\n * SQL expression for extracting a field from a JSON column stored as text.\n *\n * sqlite: json_extract(column, '$.path')\n * postgres: (column)::jsonb->>'path'\n *\n * The Postgres cast is required because JSON columns (e.g.\n * `_plugin_storage.data`) are `text`, and `text ->> unknown` is not an\n * operator. The cast is immutable, so the same expression works in\n * expression indexes — queries and indexes must build it through this\n * helper so the planner can match them.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function jsonExtractExpr(db: Kysely<any>, column: string, path: string): string {\n\tvalidateIdentifier(column, \"JSON column name\");\n\tvalidateJsonFieldName(path, \"JSON path\");\n\tif (isPostgres(db)) {\n\t\treturn `(${column})::jsonb->>'${path}'`;\n\t}\n\treturn `json_extract(${column}, '$.${path}')`;\n}\n\n/**\n * SQL expression for extracting a queryable field from the plugin-storage\n * `data` column.\n *\n * `_plugin_storage.data` is `text`, so Postgres extraction goes through the\n * `(data)::jsonb->>'field'` cast (#1898) — otherwise `text ->> unknown` is not\n * an operator. But the extracted value is still `text`, so a numeric comparison\n * (`stock >= 10`) compares lexically (`'9' >= '10'` is TRUE) and silently\n * over-counts / oversells; pass `{ numeric: true }` for a numeric comparison.\n *\n * The numeric form is a **type-guarded** cast, not a bare `::numeric`. A bare\n * cast throws `invalid input syntax for type numeric` the moment a single\n * scanned row stores a non-number in that field (documents are schemaless),\n * aborting the whole query — and it would diverge from SQLite, which silently\n * coerces. Guarding with `jsonb_typeof`/`json_type` makes the comparison total\n * and parity-correct on both dialects: a non-number stored value yields `NULL`\n * (no match) instead of an error.\n *\n * The field name is validated before interpolation, so the casts wrap only a\n * safe identifier and add no injection surface.\n *\n * sqlite text: json_extract(data, '$.field')\n * sqlite numeric: CASE WHEN json_type(data, '$.field') IN ('integer', 'real')\n * THEN json_extract(data, '$.field') END\n * postgres text: (data)::jsonb->>'field'\n * postgres numeric: CASE WHEN jsonb_typeof((data)::jsonb->'field') = 'number'\n * THEN ((data)::jsonb->>'field')::numeric END\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function pluginDataExtractExpr(\n\tdb: Kysely<any>,\n\tfield: string,\n\toptions?: { numeric?: boolean },\n): string {\n\tvalidateJsonFieldName(field, \"plugin storage field name\");\n\tif (isPostgres(db)) {\n\t\tconst text = `(data)::jsonb->>'${field}'`;\n\t\tif (!options?.numeric) return text;\n\t\treturn `CASE WHEN jsonb_typeof((data)::jsonb->'${field}') = 'number' THEN (${text})::numeric END`;\n\t}\n\tconst extract = `json_extract(data, '$.${field}')`;\n\tif (!options?.numeric) return extract;\n\treturn `CASE WHEN json_type(data, '$.${field}') IN ('integer', 'real') THEN ${extract} END`;\n}\n\n/**\n * Build the new value of the `_plugin_storage.data` (text-JSON) column for a\n * guarded `updateIf`, composing wholesale `set` fields and integer `delta`\n * fields into a SINGLE dialect-correct expression.\n *\n * Both branches go through `json_set` / `jsonb_set` so the write never rewrites\n * the whole column from JS (which would require a read-then-write and break the\n * single-statement atomicity that makes no-oversell hold):\n *\n * - **set** field → the value is stored via `json(?)` (SQLite) / `?::jsonb`\n * (Postgres) with `JSON.stringify(value)`, uniformly handling scalars,\n * objects, arrays, and `null` (stored as JSON `null`, never SQL `NULL` — a\n * SQL `NULL` in `jsonb_set` would null the entire `data` column and hit the\n * `NOT NULL` constraint).\n * - **delta** field → `COALESCE(<numeric extract>, 0) + n`, where the extract\n * is the type-guarded numeric form from {@link pluginDataExtractExpr} so a\n * missing or null stored value coalesces to `0` on both dialects. The update\n * guard rejects invalid counters and unsafe results. Integer arithmetic stays\n * integer (Postgres `to_jsonb(numeric)` and SQLite integer `+` both round-trip\n * without a spurious `.0`).\n *\n * Field names are validated (`validateJsonFieldName` / `pluginDataExtractExpr`)\n * before interpolation, so the JSON path is a safe identifier and values are\n * bound parameters — no injection surface.\n *\n * SQLite: json_set(json_set(data, '$.f1', json(?)), '$.f2', COALESCE(json_extract(...), 0) + ?)\n * Postgres: (jsonb_set(jsonb_set(data::jsonb, '{f1}', ?::jsonb), '{f2}', to_jsonb(COALESCE(..., 0) + ?)))::text\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function pluginDataWriteExpr(\n\tdb: Kysely<any>,\n\tsetEntries: Array<[string, unknown]>,\n\tdeltaEntries: Array<[string, number]>,\n): RawBuilder<string> {\n\tconst pg = isPostgres(db);\n\tlet expr: RawBuilder<unknown> = pg ? sql`data::jsonb` : sql`data`;\n\n\tfor (const [field, value] of setEntries) {\n\t\tvalidateJsonFieldName(field, \"plugin storage set field name\");\n\t\tconst json = JSON.stringify(value ?? null);\n\t\tif (pg) {\n\t\t\texpr = sql`jsonb_set(${expr}, ${sql.lit(`{${field}}`)}, ${json}::jsonb)`;\n\t\t} else {\n\t\t\texpr = sql`json_set(${expr}, ${sql.lit(`$.${field}`)}, json(${json}))`;\n\t\t}\n\t}\n\n\tfor (const [field, n] of deltaEntries) {\n\t\tconst numericExtract = pluginDataExtractExpr(db, field, { numeric: true });\n\t\tif (pg) {\n\t\t\texpr = sql`jsonb_set(${expr}, ${sql.lit(`{${field}}`)}, to_jsonb(COALESCE(${sql.raw(numericExtract)}, 0) + ${n}))`;\n\t\t} else {\n\t\t\texpr = sql`json_set(${expr}, ${sql.lit(`$.${field}`)}, cast(COALESCE(${sql.raw(numericExtract)}, 0) as integer) + cast(${n} as integer))`;\n\t\t}\n\t}\n\n\tif (pg) {\n\t\treturn sql<string>`(${expr})::text`;\n\t}\n\treturn sql<string>`${expr}`;\n}\n\nexport function pluginDataUpdateGuard(\n\tdb: Kysely<Database>,\n\tdeltaEntries: Array<[string, number]>,\n): RawBuilder<boolean> {\n\tconst pg = isPostgres(db);\n\tconst conditions: RawBuilder<boolean>[] = [\n\t\tpg ? sql`jsonb_typeof(data::jsonb) = 'object'` : sql`json_type(data) = 'object'`,\n\t];\n\tfor (const [field, amount] of deltaEntries) {\n\t\tconst numeric = sql.raw(pluginDataExtractExpr(db, field, { numeric: true }));\n\t\tconst type = pg\n\t\t\t? sql`jsonb_typeof(data::jsonb -> ${sql.lit(field)})`\n\t\t\t: sql`json_type(data, ${sql.lit(`$.${field}`)})`;\n\t\tconst base = sql`coalesce(${numeric}, 0)`;\n\t\tconst integral = pg ? sql`${base} = trunc(${base})` : sql`${base} = cast(${base} as integer)`;\n\t\tconst lower = Math.max(Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER - amount);\n\t\tconst upper = Math.min(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER - amount);\n\t\tconditions.push(sql`((${type} is null or ${type} = 'null' or ${numeric} is not null)\n\t\t\tand ${integral} and ${base} >= ${lower} and ${base} <= ${upper})`);\n\t}\n\treturn sql`(${sql.join(conditions, sql` and `)})`;\n}\n\n/**\n * SQL expression for ordering plugin-storage rows by a `data` field.\n *\n * `ORDER BY` has no bound operand to infer numeric-vs-text from, so extracting\n * as text (`->>'field'`) would sort a numeric field lexically on Postgres\n * (`[10, 100, 9]`) while SQLite's `json_extract` sorts it numerically — a\n * cross-dialect divergence. Ordering over the jsonb-native value (`->'field'`,\n * single arrow) fixes this: jsonb btree ordering is numeric among numbers,\n * lexical among strings, and total across heterogeneous values (never throws).\n * SQLite's `json_extract` already orders numerically, so it is unchanged.\n *\n * sqlite: json_extract(data, '$.field')\n * postgres: (data)::jsonb->'field'\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any Kysely instance\nexport function pluginDataOrderExpr(db: Kysely<any>, field: string): string {\n\tvalidateJsonFieldName(field, \"plugin storage order field name\");\n\tif (isPostgres(db)) {\n\t\treturn `(data)::jsonb->'${field}'`;\n\t}\n\treturn `json_extract(data, '$.${field}')`;\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,cAAc,IAAsC;AACnE,KAAI,GAAG,aAAa,CAAC,mBAAmB,gBAAiB,QAAO;AAChE,QAAO;;AAIR,SAAgB,SAAS,IAA0B;AAClD,QAAO,cAAc,GAAG,KAAK;;AAI9B,SAAgB,WAAW,IAA0B;AACpD,QAAO,cAAc,GAAG,KAAK;;;;;;;;;;;;;;AA4B9B,SAAgB,oBAAoB,IAAgC;CACnE,MAAM,UAAkB,GAAG,aAAa,CAAC;AACzC,KAAI,EAAE,yBAAyB,SAAU,QAAO;CAEhD,MAAM,QAAiB,QAAQ;AAC/B,KAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,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AAK,MAAM,MAAM,GAAG;;AAEpE,QAAO,GAAG,IAAI,IAAI,KAAK,YAAY,GAAG,QAAQ,CAAC;;;;;;;;;;;;;;;;AAkBhD,SAAgB,oBAAoB,IAAiB,OAAuB;AAC3E,uBAAsB,OAAO,kCAAkC;AAC/D,KAAI,WAAW,GAAG,CACjB,QAAO,mBAAmB,MAAM;AAEjC,QAAO,yBAAyB,MAAM"}
@@ -1,6 +1,6 @@
1
- import { i as getExactMigrationStatus, s as runMigrations } from "./runner-BLIDKpmA.mjs";
1
+ import { i as getExactMigrationStatus, s as runMigrations } from "./runner-nEzvnogG.mjs";
2
2
  import { r as getI18nConfig, s as setI18nConfig } from "./config-C3EBstHi.mjs";
3
- import { r as getCoreMigrationIdentity } from "./identity-DksvEazf.mjs";
3
+ import { r as getCoreMigrationIdentity } from "./identity-CjGKDq8J.mjs";
4
4
  import { Kysely } from "kysely";
5
5
 
6
6
  //#region src/migrations/direct-executor.ts
@@ -82,4 +82,4 @@ function createDirectMigrationExecutor(options) {
82
82
 
83
83
  //#endregion
84
84
  export { createDirectMigrationExecutor as t };
85
- //# sourceMappingURL=direct-executor-Bfa5_ToE.mjs.map
85
+ //# sourceMappingURL=direct-executor-yAyUGSqB.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"direct-executor-Bfa5_ToE.mjs","names":[],"sources":["../src/migrations/direct-executor.ts"],"sourcesContent":["import { type Dialect, Kysely } from \"kysely\";\n\nimport {\n\tgetExactMigrationStatus,\n\trunMigrations,\n\ttype ExactMigrationStatus,\n} from \"../database/migrations/runner.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getI18nConfig, setI18nConfig } from \"../i18n/config.js\";\nimport { getCoreMigrationIdentity } from \"./identity.js\";\nimport type {\n\tMigrationExecutor,\n\tMigrationReport,\n\tMigrationRequest,\n\tMigrationTarget,\n} from \"./protocol.js\";\n\nexport interface DirectMigrationExecutorOptions {\n\ttarget: MigrationTarget;\n\tcreateDialect: () => Dialect | Promise<Dialect>;\n}\n\nfunction createReport(\n\ttarget: MigrationTarget,\n\tstatus: ExactMigrationStatus,\n\texecuted: readonly string[],\n): MigrationReport {\n\treturn {\n\t\ttarget,\n\t\tknownApplied: [...status.knownApplied],\n\t\tpending: [...status.pending],\n\t\tunknownApplied: [...status.unknownApplied],\n\t\texecuted: [...executed],\n\t};\n}\n\nasync function verifyRequest(request: MigrationRequest): Promise<void> {\n\tconst identity = await getCoreMigrationIdentity();\n\tif (\n\t\trequest.artifact.emdashVersion !== identity.emdashVersion ||\n\t\trequest.artifact.migrationSetFingerprint !== identity.fingerprint\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Migration artifact does not match the loaded EmDash version and migration registry.\",\n\t\t);\n\t}\n}\n\nasync function executeRequest(\n\tdb: Kysely<Database>,\n\ttarget: MigrationTarget,\n\trequest: MigrationRequest,\n): Promise<MigrationReport> {\n\tconst initialStatus = await getExactMigrationStatus(db);\n\tif (request.action === \"check\") {\n\t\treturn createReport(target, initialStatus, []);\n\t}\n\n\tif (initialStatus.unknownApplied.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Cannot apply migrations with unknown applied migrations: ${initialStatus.unknownApplied.join(\", \")}`,\n\t\t);\n\t}\n\tif (initialStatus.pending.length === 0) {\n\t\treturn createReport(target, initialStatus, []);\n\t}\n\n\tconst result = await runMigrations(db);\n\tconst finalStatus = await getExactMigrationStatus(db);\n\treturn createReport(target, finalStatus, result.applied);\n}\n\nexport function createDirectMigrationExecutor(\n\toptions: DirectMigrationExecutorOptions,\n): MigrationExecutor {\n\tconst target = Object.freeze({ ...options.target });\n\tlet used = false;\n\tlet disposed = false;\n\tlet activeDb: Kysely<Database> | undefined;\n\tlet closePromise: Promise<void> | undefined;\n\n\tconst closeActiveDb = (): Promise<void> => {\n\t\tif (!activeDb) return Promise.resolve();\n\t\tclosePromise ??= activeDb.destroy();\n\t\treturn closePromise;\n\t};\n\n\treturn {\n\t\ttarget,\n\t\tasync execute(request) {\n\t\t\tif (disposed) {\n\t\t\t\tthrow new Error(\"Migration executor has been disposed.\");\n\t\t\t}\n\t\t\tif (used) {\n\t\t\t\tthrow new Error(\"Migration executors are single-use.\");\n\t\t\t}\n\t\t\tused = true;\n\n\t\t\tif (request.action !== \"check\" && request.action !== \"apply\") {\n\t\t\t\tthrow new Error(\"Unsupported migration action.\");\n\t\t\t}\n\t\t\tawait verifyRequest(request);\n\n\t\t\tconst dialect = await options.createDialect();\n\t\t\tconst db = new Kysely<Database>({ dialect });\n\t\t\tactiveDb = db;\n\t\t\tif (disposed) {\n\t\t\t\tawait closeActiveDb();\n\t\t\t\tthrow new Error(\"Migration executor has been disposed.\");\n\t\t\t}\n\t\t\tconst previousI18n = getI18nConfig();\n\t\t\tlet executionFailed = false;\n\t\t\tlet executionError: unknown;\n\t\t\tlet report: MigrationReport | undefined;\n\t\t\tsetI18nConfig(request.i18n);\n\n\t\t\ttry {\n\t\t\t\treport = await executeRequest(db, target, request);\n\t\t\t} catch (error) {\n\t\t\t\texecutionFailed = true;\n\t\t\t\texecutionError = error;\n\t\t\t} finally {\n\t\t\t\tsetI18nConfig(previousI18n);\n\t\t\t\ttry {\n\t\t\t\t\tawait closeActiveDb();\n\t\t\t\t} catch {\n\t\t\t\t\tconsole.error(\"[migrations] Database close failed.\");\n\t\t\t\t\tclosePromise = Promise.resolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (executionFailed) throw executionError;\n\t\t\tif (!report) throw new Error(\"Migration execution did not produce a report.\");\n\t\t\treturn report;\n\t\t},\n\t\tdispose() {\n\t\t\tdisposed = true;\n\t\t\treturn closeActiveDb();\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;AAsBA,SAAS,aACR,QACA,QACA,UACkB;AAClB,QAAO;EACN;EACA,cAAc,CAAC,GAAG,OAAO,aAAa;EACtC,SAAS,CAAC,GAAG,OAAO,QAAQ;EAC5B,gBAAgB,CAAC,GAAG,OAAO,eAAe;EAC1C,UAAU,CAAC,GAAG,SAAS;EACvB;;AAGF,eA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AM,eAAe,eAAe;GACpC,IAAI,kBAAkB;GACtB,IAAI;GACJ,IAAI;AACJ,iBAAc,QAAQ,KAAK;AAE3B,OAAI;AACH,aAAS,MAAM,eAAe,IAAI,QAAQ,QAAQ;YAC1C,OAAO;AACf,sBAAkB;AAClB,qBAAiB;aACR;AACT,kBAAc,aAAa;AAC3B,QAAI;AACH,WAAM,eAAe;YACd;AACP,aAAQ,MAAM,sCAAsC;AACpD,oBAAe,QAAQ,SAAS;;;AAIlC,OAAI,gBAAiB,OAAM;AAC3B,OAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,gDAAgD;AAC7E,UAAO;;EAER,UAAU;AACT,cAAW;AACX,UAAO,eAAe;;EAEvB"}
1
+ {"version":3,"file":"direct-executor-yAyUGSqB.mjs","names":[],"sources":["../src/migrations/direct-executor.ts"],"sourcesContent":["import { type Dialect, Kysely } from \"kysely\";\n\nimport {\n\tgetExactMigrationStatus,\n\trunMigrations,\n\ttype ExactMigrationStatus,\n} from \"../database/migrations/runner.js\";\nimport type { Database } from \"../database/types.js\";\nimport { getI18nConfig, setI18nConfig } from \"../i18n/config.js\";\nimport { getCoreMigrationIdentity } from \"./identity.js\";\nimport type {\n\tMigrationExecutor,\n\tMigrationReport,\n\tMigrationRequest,\n\tMigrationTarget,\n} from \"./protocol.js\";\n\nexport interface DirectMigrationExecutorOptions {\n\ttarget: MigrationTarget;\n\tcreateDialect: () => Dialect | Promise<Dialect>;\n}\n\nfunction createReport(\n\ttarget: MigrationTarget,\n\tstatus: ExactMigrationStatus,\n\texecuted: readonly string[],\n): MigrationReport {\n\treturn {\n\t\ttarget,\n\t\tknownApplied: [...status.knownApplied],\n\t\tpending: [...status.pending],\n\t\tunknownApplied: [...status.unknownApplied],\n\t\texecuted: [...executed],\n\t};\n}\n\nasync function verifyRequest(request: MigrationRequest): Promise<void> {\n\tconst identity = await getCoreMigrationIdentity();\n\tif (\n\t\trequest.artifact.emdashVersion !== identity.emdashVersion ||\n\t\trequest.artifact.migrationSetFingerprint !== identity.fingerprint\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Migration artifact does not match the loaded EmDash version and migration registry.\",\n\t\t);\n\t}\n}\n\nasync function executeRequest(\n\tdb: Kysely<Database>,\n\ttarget: MigrationTarget,\n\trequest: MigrationRequest,\n): Promise<MigrationReport> {\n\tconst initialStatus = await getExactMigrationStatus(db);\n\tif (request.action === \"check\") {\n\t\treturn createReport(target, initialStatus, []);\n\t}\n\n\tif (initialStatus.unknownApplied.length > 0) {\n\t\tthrow new Error(\n\t\t\t`Cannot apply migrations with unknown applied migrations: ${initialStatus.unknownApplied.join(\", \")}`,\n\t\t);\n\t}\n\tif (initialStatus.pending.length === 0) {\n\t\treturn createReport(target, initialStatus, []);\n\t}\n\n\tconst result = await runMigrations(db);\n\tconst finalStatus = await getExactMigrationStatus(db);\n\treturn createReport(target, finalStatus, result.applied);\n}\n\nexport function createDirectMigrationExecutor(\n\toptions: DirectMigrationExecutorOptions,\n): MigrationExecutor {\n\tconst target = Object.freeze({ ...options.target });\n\tlet used = false;\n\tlet disposed = false;\n\tlet activeDb: Kysely<Database> | undefined;\n\tlet closePromise: Promise<void> | undefined;\n\n\tconst closeActiveDb = (): Promise<void> => {\n\t\tif (!activeDb) return Promise.resolve();\n\t\tclosePromise ??= activeDb.destroy();\n\t\treturn closePromise;\n\t};\n\n\treturn {\n\t\ttarget,\n\t\tasync execute(request) {\n\t\t\tif (disposed) {\n\t\t\t\tthrow new Error(\"Migration executor has been disposed.\");\n\t\t\t}\n\t\t\tif (used) {\n\t\t\t\tthrow new Error(\"Migration executors are single-use.\");\n\t\t\t}\n\t\t\tused = true;\n\n\t\t\tif (request.action !== \"check\" && request.action !== \"apply\") {\n\t\t\t\tthrow new Error(\"Unsupported migration action.\");\n\t\t\t}\n\t\t\tawait verifyRequest(request);\n\n\t\t\tconst dialect = await options.createDialect();\n\t\t\tconst db = new Kysely<Database>({ dialect });\n\t\t\tactiveDb = db;\n\t\t\tif (disposed) {\n\t\t\t\tawait closeActiveDb();\n\t\t\t\tthrow new Error(\"Migration executor has been disposed.\");\n\t\t\t}\n\t\t\tconst previousI18n = getI18nConfig();\n\t\t\tlet executionFailed = false;\n\t\t\tlet executionError: unknown;\n\t\t\tlet report: MigrationReport | undefined;\n\t\t\tsetI18nConfig(request.i18n);\n\n\t\t\ttry {\n\t\t\t\treport = await executeRequest(db, target, request);\n\t\t\t} catch (error) {\n\t\t\t\texecutionFailed = true;\n\t\t\t\texecutionError = error;\n\t\t\t} finally {\n\t\t\t\tsetI18nConfig(previousI18n);\n\t\t\t\ttry {\n\t\t\t\t\tawait closeActiveDb();\n\t\t\t\t} catch {\n\t\t\t\t\tconsole.error(\"[migrations] Database close failed.\");\n\t\t\t\t\tclosePromise = Promise.resolve();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (executionFailed) throw executionError;\n\t\t\tif (!report) throw new Error(\"Migration execution did not produce a report.\");\n\t\t\treturn report;\n\t\t},\n\t\tdispose() {\n\t\t\tdisposed = true;\n\t\t\treturn closeActiveDb();\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;AAsBA,SAAS,aACR,QACA,QACA,UACkB;AAClB,QAAO;EACN;EACA,cAAc,CAAC,GAAG,OAAO,aAAa;EACtC,SAAS,CAAC,GAAG,OAAO,QAAQ;EAC5B,gBAAgB,CAAC,GAAG,OAAO,eAAe;EAC1C,UAAU,CAAC,GAAG,SAAS;EACvB;;AAGF,eAAe,cAAc,SAA0C;CACtE,MAAM,WAAW,MAAM,0BAA0B;AACjD,KACC,QAAQ,SAAS,kBAAkB,SAAS,iBAC5C,QAAQ,SAAS,4BAA4B,SAAS,YAEtD,OAAM,IAAI,MACT,sFACA;;AAIH,eAAe,eACd,IACA,QACA,SAC2B;CAC3B,MAAM,gBAAgB,MAAM,wBAAwB,GAAG;AACvD,KAAI,QAAQ,WAAW,QACtB,QAAO,aAAa,QAAQ,eAAe,EAAE,CAAC;AAG/C,KAAI,cAAc,eAAe,SAAS,EACzC,OAA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AC,OAAQ,OAAM,IAAI,MAAM,gDAAgD;AAC7E,UAAO;;EAER,UAAU;AACT,cAAW;AACX,UAAO,eAAe;;EAEvB"}
@@ -807,4 +807,4 @@ function imageSize(input) {
807
807
 
808
808
  //#endregion
809
809
  export { imageSize as t };
810
- //# sourceMappingURL=dist-89xCrGqi.mjs.map
810
+ //# sourceMappingURL=dist-BAsh8dbf.mjs.map