emdash 0.35.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (971) hide show
  1. package/dist/activation-K0kGBWuJ.mjs +382 -0
  2. package/dist/activation-K0kGBWuJ.mjs.map +1 -0
  3. package/dist/{adapters-Bb1vG41D.d.mts → adapters-BDQwg236.d.mts} +6 -4
  4. package/dist/{adapters-Bb1vG41D.d.mts.map → adapters-BDQwg236.d.mts.map} +1 -1
  5. package/dist/{allowed-origins-DW7sYyqg.mjs → allowed-origins-BGglilcs.mjs} +2 -2
  6. package/dist/{allowed-origins-DW7sYyqg.mjs.map → allowed-origins-BGglilcs.mjs.map} +1 -1
  7. package/dist/api/route-utils.d.mts +3 -3
  8. package/dist/api/route-utils.mjs +23 -21
  9. package/dist/api/route-utils.mjs.map +1 -1
  10. package/dist/api/schemas/index.d.mts +2 -2
  11. package/dist/api/schemas/index.mjs +5 -5
  12. package/dist/api-Dz6rgoa3.mjs +10040 -0
  13. package/dist/api-Dz6rgoa3.mjs.map +1 -0
  14. package/dist/{api-tokens-KO24G1Fd.mjs → api-tokens-BSsQACNe.mjs} +2 -2
  15. package/dist/{api-tokens-KO24G1Fd.mjs.map → api-tokens-BSsQACNe.mjs.map} +1 -1
  16. package/dist/{apply-kUDt80-G.mjs → apply-B4SIOxR1.mjs} +34 -35
  17. package/dist/{apply-kUDt80-G.mjs.map → apply-B4SIOxR1.mjs.map} +1 -1
  18. package/dist/astro/image-endpoint.mjs +2 -2
  19. package/dist/astro/image-endpoint.mjs.map +1 -1
  20. package/dist/astro/index.d.mts +12 -12
  21. package/dist/astro/index.d.mts.map +1 -1
  22. package/dist/astro/index.mjs +128 -44
  23. package/dist/astro/index.mjs.map +1 -1
  24. package/dist/astro/middleware/auth.d.mts +10 -10
  25. package/dist/astro/middleware/auth.d.mts.map +1 -1
  26. package/dist/astro/middleware/auth.mjs +10 -7
  27. package/dist/astro/middleware/auth.mjs.map +1 -1
  28. package/dist/astro/middleware/media-usage-write-fence.mjs +2 -2
  29. package/dist/astro/middleware/redirect.mjs +4 -4
  30. package/dist/astro/middleware/request-context.mjs +3 -3
  31. package/dist/astro/middleware/setup.mjs +1 -1
  32. package/dist/astro/middleware.d.mts +11 -12
  33. package/dist/astro/middleware.d.mts.map +1 -1
  34. package/dist/astro/middleware.mjs +237 -1412
  35. package/dist/astro/middleware.mjs.map +1 -1
  36. package/dist/astro/routes/api/admin/allowed-domains/_domain_.mjs +6 -6
  37. package/dist/astro/routes/api/admin/allowed-domains/index.mjs +6 -6
  38. package/dist/astro/routes/api/admin/api-tokens/_id_.mjs +3 -3
  39. package/dist/astro/routes/api/admin/api-tokens/index.d.mts.map +1 -1
  40. package/dist/astro/routes/api/admin/api-tokens/index.mjs +5 -5
  41. package/dist/astro/routes/api/admin/api-tokens/index.mjs.map +1 -1
  42. package/dist/astro/routes/api/admin/byline-fields/_slug_/usage.mjs +4 -4
  43. package/dist/astro/routes/api/admin/byline-fields/_slug_.mjs +9 -9
  44. package/dist/astro/routes/api/admin/byline-fields/index.mjs +9 -9
  45. package/dist/astro/routes/api/admin/byline-fields/reorder.mjs +9 -9
  46. package/dist/astro/routes/api/admin/bylines/_id_/index.mjs +16 -16
  47. package/dist/astro/routes/api/admin/bylines/_id_/translations.mjs +16 -16
  48. package/dist/astro/routes/api/admin/bylines/index.mjs +16 -16
  49. package/dist/astro/routes/api/admin/comments/_id_/status.mjs +13 -13
  50. package/dist/astro/routes/api/admin/comments/_id_.mjs +5 -5
  51. package/dist/astro/routes/api/admin/comments/bulk.mjs +10 -10
  52. package/dist/astro/routes/api/admin/comments/counts.mjs +5 -5
  53. package/dist/astro/routes/api/admin/comments/index.mjs +10 -10
  54. package/dist/astro/routes/api/admin/hooks/exclusive/_hookName_.mjs +4 -4
  55. package/dist/astro/routes/api/admin/hooks/exclusive/index.mjs +3 -3
  56. package/dist/astro/routes/api/admin/media-usage/activation.d.mts +9 -0
  57. package/dist/astro/routes/api/admin/media-usage/activation.d.mts.map +1 -0
  58. package/dist/astro/routes/api/admin/media-usage/activation.mjs +46 -0
  59. package/dist/astro/routes/api/admin/media-usage/activation.mjs.map +1 -0
  60. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs +14 -13
  61. package/dist/astro/routes/api/admin/media-usage/collection-deletions/index.mjs.map +1 -1
  62. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs +14 -13
  63. package/dist/astro/routes/api/admin/media-usage/collection-deletions/retry.mjs.map +1 -1
  64. package/dist/astro/routes/api/admin/media-usage/progress.d.mts +9 -0
  65. package/dist/astro/routes/api/admin/media-usage/progress.d.mts.map +1 -0
  66. package/dist/astro/routes/api/admin/media-usage/progress.mjs +44 -0
  67. package/dist/astro/routes/api/admin/media-usage/progress.mjs.map +1 -0
  68. package/dist/astro/routes/api/admin/media-usage/repair.mjs +16 -11
  69. package/dist/astro/routes/api/admin/media-usage/repair.mjs.map +1 -1
  70. package/dist/astro/routes/api/admin/media-usage/work/index.mjs +14 -13
  71. package/dist/astro/routes/api/admin/media-usage/work/index.mjs.map +1 -1
  72. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs +14 -13
  73. package/dist/astro/routes/api/admin/media-usage/work/retry.mjs.map +1 -1
  74. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs +4 -4
  75. package/dist/astro/routes/api/admin/oauth-clients/_id_.mjs.map +1 -1
  76. package/dist/astro/routes/api/admin/oauth-clients/index.mjs +4 -4
  77. package/dist/astro/routes/api/admin/oauth-clients/index.mjs.map +1 -1
  78. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +55 -49
  79. package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs.map +1 -1
  80. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +55 -49
  81. package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs.map +1 -1
  82. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +53 -47
  83. package/dist/astro/routes/api/admin/plugins/_id_/index.mjs.map +1 -1
  84. package/dist/astro/routes/api/admin/plugins/_id_/mcp.mjs +4 -4
  85. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs +53 -47
  86. package/dist/astro/routes/api/admin/plugins/_id_/settings.mjs.map +1 -1
  87. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +54 -48
  88. package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs.map +1 -1
  89. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +54 -48
  90. package/dist/astro/routes/api/admin/plugins/_id_/update.mjs.map +1 -1
  91. package/dist/astro/routes/api/admin/plugins/index.mjs +53 -47
  92. package/dist/astro/routes/api/admin/plugins/index.mjs.map +1 -1
  93. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/icon.mjs +2 -2
  94. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +53 -47
  95. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs.map +1 -1
  96. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +54 -48
  97. package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs.map +1 -1
  98. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +53 -47
  99. package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs.map +1 -1
  100. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +54 -48
  101. package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs.map +1 -1
  102. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.d.mts.map +1 -1
  103. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +60 -50
  104. package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs.map +1 -1
  105. package/dist/astro/routes/api/admin/plugins/registry/artifact.d.mts.map +1 -1
  106. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +179 -139
  107. package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs.map +1 -1
  108. package/dist/astro/routes/api/admin/plugins/registry/install.d.mts.map +1 -1
  109. package/dist/astro/routes/api/admin/plugins/registry/install.mjs +61 -51
  110. package/dist/astro/routes/api/admin/plugins/registry/install.mjs.map +1 -1
  111. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts +8 -0
  112. package/dist/astro/routes/api/admin/plugins/registry/verify.d.mts.map +1 -0
  113. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs +93 -0
  114. package/dist/astro/routes/api/admin/plugins/registry/verify.mjs.map +1 -0
  115. package/dist/astro/routes/api/admin/plugins/updates.mjs +53 -47
  116. package/dist/astro/routes/api/admin/plugins/updates.mjs.map +1 -1
  117. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +53 -47
  118. package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs.map +1 -1
  119. package/dist/astro/routes/api/admin/themes/marketplace/_id_/thumbnail.mjs +2 -2
  120. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +53 -47
  121. package/dist/astro/routes/api/admin/themes/marketplace/index.mjs.map +1 -1
  122. package/dist/astro/routes/api/admin/users/_id_/disable.mjs +2 -2
  123. package/dist/astro/routes/api/admin/users/_id_/enable.mjs +1 -1
  124. package/dist/astro/routes/api/admin/users/_id_/index.mjs +7 -7
  125. package/dist/astro/routes/api/admin/users/_id_/send-recovery.mjs +3 -3
  126. package/dist/astro/routes/api/admin/users/index.mjs +6 -6
  127. package/dist/astro/routes/api/auth/dev-bypass.mjs +3 -3
  128. package/dist/astro/routes/api/auth/invite/accept.mjs +1 -1
  129. package/dist/astro/routes/api/auth/invite/complete.mjs +11 -11
  130. package/dist/astro/routes/api/auth/invite/index.mjs +8 -8
  131. package/dist/astro/routes/api/auth/invite/register-options.mjs +10 -10
  132. package/dist/astro/routes/api/auth/logout.mjs +2 -2
  133. package/dist/astro/routes/api/auth/magic-link/send.mjs +10 -10
  134. package/dist/astro/routes/api/auth/magic-link/verify.mjs +2 -2
  135. package/dist/astro/routes/api/auth/me.d.mts.map +1 -1
  136. package/dist/astro/routes/api/auth/me.mjs +19 -9
  137. package/dist/astro/routes/api/auth/me.mjs.map +1 -1
  138. package/dist/astro/routes/api/auth/mode.mjs +2 -2
  139. package/dist/astro/routes/api/auth/oauth/_provider_/callback.mjs +4 -4
  140. package/dist/astro/routes/api/auth/oauth/_provider_.mjs +2 -2
  141. package/dist/astro/routes/api/auth/passkey/_id_.mjs +6 -6
  142. package/dist/astro/routes/api/auth/passkey/index.mjs +1 -1
  143. package/dist/astro/routes/api/auth/passkey/options.mjs +12 -12
  144. package/dist/astro/routes/api/auth/passkey/register/options.mjs +10 -10
  145. package/dist/astro/routes/api/auth/passkey/register/verify.mjs +11 -11
  146. package/dist/astro/routes/api/auth/passkey/verify.mjs +11 -11
  147. package/dist/astro/routes/api/auth/signup/complete.mjs +11 -11
  148. package/dist/astro/routes/api/auth/signup/request.mjs +10 -10
  149. package/dist/astro/routes/api/auth/signup/verify.mjs +1 -1
  150. package/dist/astro/routes/api/comments/_collection_/_contentId_/index.mjs +14 -14
  151. package/dist/astro/routes/api/comments/_collection_/_contentId_/reactions.mjs +13 -13
  152. package/dist/astro/routes/api/content/_collection_/_id_/compare.mjs +2 -2
  153. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.d.mts.map +1 -1
  154. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs +14 -5
  155. package/dist/astro/routes/api/content/_collection_/_id_/discard-draft.mjs.map +1 -1
  156. package/dist/astro/routes/api/content/_collection_/_id_/duplicate.mjs +3 -3
  157. package/dist/astro/routes/api/content/_collection_/_id_/permanent.mjs +2 -2
  158. package/dist/astro/routes/api/content/_collection_/_id_/preview-url.mjs +11 -11
  159. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs +13 -10
  160. package/dist/astro/routes/api/content/_collection_/_id_/publish.mjs.map +1 -1
  161. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs +17 -15
  162. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/children.mjs.map +1 -1
  163. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs +17 -15
  164. package/dist/astro/routes/api/content/_collection_/_id_/references/_relation_/parents.mjs.map +1 -1
  165. package/dist/astro/routes/api/content/_collection_/_id_/restore.mjs +3 -3
  166. package/dist/astro/routes/api/content/_collection_/_id_/revisions.mjs +2 -2
  167. package/dist/astro/routes/api/content/_collection_/_id_/schedule.mjs +8 -8
  168. package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +14 -14
  169. package/dist/astro/routes/api/content/_collection_/_id_/translations.mjs +2 -2
  170. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.d.mts.map +1 -1
  171. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs +14 -5
  172. package/dist/astro/routes/api/content/_collection_/_id_/unpublish.mjs.map +1 -1
  173. package/dist/astro/routes/api/content/_collection_/_id_.mjs +8 -8
  174. package/dist/astro/routes/api/content/_collection_/authors.mjs +2 -2
  175. package/dist/astro/routes/api/content/_collection_/index.mjs +8 -8
  176. package/dist/astro/routes/api/content/_collection_/trash.mjs +7 -7
  177. package/dist/astro/routes/api/dashboard.mjs +8 -8
  178. package/dist/astro/routes/api/dev/emails.mjs +2 -2
  179. package/dist/astro/routes/api/import/probe.d.mts +3 -3
  180. package/dist/astro/routes/api/import/probe.mjs +17 -17
  181. package/dist/astro/routes/api/import/wordpress/analyze.mjs +2 -2
  182. package/dist/astro/routes/api/import/wordpress/execute.d.mts +11 -11
  183. package/dist/astro/routes/api/import/wordpress/execute.mjs +13 -13
  184. package/dist/astro/routes/api/import/wordpress/media.d.mts +10 -10
  185. package/dist/astro/routes/api/import/wordpress/media.mjs +11 -11
  186. package/dist/astro/routes/api/import/wordpress/prepare.mjs +9 -9
  187. package/dist/astro/routes/api/import/wordpress/rewrite-urls.d.mts +11 -11
  188. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs +12 -10
  189. package/dist/astro/routes/api/import/wordpress/rewrite-urls.mjs.map +1 -1
  190. package/dist/astro/routes/api/import/wordpress-plugin/analyze.d.mts +1 -1
  191. package/dist/astro/routes/api/import/wordpress-plugin/analyze.mjs +17 -17
  192. package/dist/astro/routes/api/import/wordpress-plugin/execute.d.mts +11 -11
  193. package/dist/astro/routes/api/import/wordpress-plugin/execute.mjs +27 -27
  194. package/dist/astro/routes/api/manifest.mjs +4 -4
  195. package/dist/astro/routes/api/manifest.mjs.map +1 -1
  196. package/dist/astro/routes/api/mcp.mjs +188 -65
  197. package/dist/astro/routes/api/mcp.mjs.map +1 -1
  198. package/dist/astro/routes/api/media/_id_/confirm.mjs +11 -11
  199. package/dist/astro/routes/api/media/_id_/replace.d.mts +8 -0
  200. package/dist/astro/routes/api/media/_id_/replace.d.mts.map +1 -0
  201. package/dist/astro/routes/api/media/_id_/replace.mjs +91 -0
  202. package/dist/astro/routes/api/media/_id_/replace.mjs.map +1 -0
  203. package/dist/astro/routes/api/media/_id_/upload.mjs +6 -6
  204. package/dist/astro/routes/api/media/_id_/usage.mjs +18 -13
  205. package/dist/astro/routes/api/media/_id_/usage.mjs.map +1 -1
  206. package/dist/astro/routes/api/media/_id_.d.mts.map +1 -1
  207. package/dist/astro/routes/api/media/_id_.mjs +21 -13
  208. package/dist/astro/routes/api/media/_id_.mjs.map +1 -1
  209. package/dist/astro/routes/api/media/file/_...key_.d.mts.map +1 -1
  210. package/dist/astro/routes/api/media/file/_...key_.mjs +3 -2
  211. package/dist/astro/routes/api/media/file/_...key_.mjs.map +1 -1
  212. package/dist/astro/routes/api/media/folders/_id_.d.mts +10 -0
  213. package/dist/astro/routes/api/media/folders/_id_.d.mts.map +1 -0
  214. package/dist/astro/routes/api/media/folders/_id_.mjs +52 -0
  215. package/dist/astro/routes/api/media/folders/_id_.mjs.map +1 -0
  216. package/dist/astro/routes/api/media/folders/index.d.mts +9 -0
  217. package/dist/astro/routes/api/media/folders/index.d.mts.map +1 -0
  218. package/dist/astro/routes/api/media/folders/index.mjs +41 -0
  219. package/dist/astro/routes/api/media/folders/index.mjs.map +1 -0
  220. package/dist/astro/routes/api/media/providers/_providerId_/_itemId_.mjs +2 -2
  221. package/dist/astro/routes/api/media/providers/_providerId_/index.mjs +2 -2
  222. package/dist/astro/routes/api/media/providers/index.mjs +2 -2
  223. package/dist/astro/routes/api/media/upload-url.mjs +16 -14
  224. package/dist/astro/routes/api/media/upload-url.mjs.map +1 -1
  225. package/dist/astro/routes/api/media.d.mts.map +1 -1
  226. package/dist/astro/routes/api/media.mjs +59 -27
  227. package/dist/astro/routes/api/media.mjs.map +1 -1
  228. package/dist/astro/routes/api/menus/_name_/items/_id_.d.mts.map +1 -1
  229. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs +20 -13
  230. package/dist/astro/routes/api/menus/_name_/items/_id_.mjs.map +1 -1
  231. package/dist/astro/routes/api/menus/_name_/items.d.mts.map +1 -1
  232. package/dist/astro/routes/api/menus/_name_/items.mjs +15 -11
  233. package/dist/astro/routes/api/menus/_name_/items.mjs.map +1 -1
  234. package/dist/astro/routes/api/menus/_name_/reorder.d.mts.map +1 -1
  235. package/dist/astro/routes/api/menus/_name_/reorder.mjs +15 -11
  236. package/dist/astro/routes/api/menus/_name_/reorder.mjs.map +1 -1
  237. package/dist/astro/routes/api/menus/_name_/translations.d.mts.map +1 -1
  238. package/dist/astro/routes/api/menus/_name_/translations.mjs +16 -12
  239. package/dist/astro/routes/api/menus/_name_/translations.mjs.map +1 -1
  240. package/dist/astro/routes/api/menus/_name_.d.mts.map +1 -1
  241. package/dist/astro/routes/api/menus/_name_.mjs +21 -14
  242. package/dist/astro/routes/api/menus/_name_.mjs.map +1 -1
  243. package/dist/astro/routes/api/menus/index.d.mts.map +1 -1
  244. package/dist/astro/routes/api/menus/index.mjs +15 -11
  245. package/dist/astro/routes/api/menus/index.mjs.map +1 -1
  246. package/dist/astro/routes/api/oauth/authorize.mjs +6 -6
  247. package/dist/astro/routes/api/oauth/device/authorize.mjs +5 -5
  248. package/dist/astro/routes/api/oauth/device/code.mjs +8 -8
  249. package/dist/astro/routes/api/oauth/device/token.mjs +7 -7
  250. package/dist/astro/routes/api/oauth/register.mjs +2 -2
  251. package/dist/astro/routes/api/oauth/token/refresh.mjs +5 -5
  252. package/dist/astro/routes/api/oauth/token/revoke.mjs +5 -5
  253. package/dist/astro/routes/api/oauth/token.mjs +5 -5
  254. package/dist/astro/routes/api/openapi.json.mjs +253 -40
  255. package/dist/astro/routes/api/openapi.json.mjs.map +1 -1
  256. package/dist/astro/routes/api/plugins/_pluginId_/_...path_.mjs +4 -4
  257. package/dist/astro/routes/api/redirects/404s/index.mjs +10 -10
  258. package/dist/astro/routes/api/redirects/404s/summary.mjs +10 -10
  259. package/dist/astro/routes/api/redirects/_id_.mjs +11 -11
  260. package/dist/astro/routes/api/redirects/index.mjs +11 -11
  261. package/dist/astro/routes/api/relations/_id_/index.mjs +17 -15
  262. package/dist/astro/routes/api/relations/_id_/index.mjs.map +1 -1
  263. package/dist/astro/routes/api/relations/_id_/translations.mjs +12 -10
  264. package/dist/astro/routes/api/relations/_id_/translations.mjs.map +1 -1
  265. package/dist/astro/routes/api/relations/index.mjs +17 -15
  266. package/dist/astro/routes/api/relations/index.mjs.map +1 -1
  267. package/dist/astro/routes/api/revisions/_revisionId_/index.mjs +2 -2
  268. package/dist/astro/routes/api/revisions/_revisionId_/restore.mjs +3 -3
  269. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +53 -47
  270. package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs.map +1 -1
  271. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +53 -47
  272. package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs.map +1 -1
  273. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +53 -47
  274. package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs.map +1 -1
  275. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +53 -47
  276. package/dist/astro/routes/api/schema/collections/_slug_/index.mjs.map +1 -1
  277. package/dist/astro/routes/api/schema/collections/index.mjs +53 -47
  278. package/dist/astro/routes/api/schema/collections/index.mjs.map +1 -1
  279. package/dist/astro/routes/api/schema/collections/reorder.mjs +53 -47
  280. package/dist/astro/routes/api/schema/collections/reorder.mjs.map +1 -1
  281. package/dist/astro/routes/api/schema/index.mjs +10 -8
  282. package/dist/astro/routes/api/schema/index.mjs.map +1 -1
  283. package/dist/astro/routes/api/schema/orphans/_slug_.mjs +53 -47
  284. package/dist/astro/routes/api/schema/orphans/_slug_.mjs.map +1 -1
  285. package/dist/astro/routes/api/schema/orphans/index.mjs +53 -47
  286. package/dist/astro/routes/api/schema/orphans/index.mjs.map +1 -1
  287. package/dist/astro/routes/api/search/enable.mjs +10 -10
  288. package/dist/astro/routes/api/search/index.mjs +9 -9
  289. package/dist/astro/routes/api/search/rebuild.mjs +10 -10
  290. package/dist/astro/routes/api/search/stats.mjs +5 -5
  291. package/dist/astro/routes/api/search/suggest.mjs +9 -9
  292. package/dist/astro/routes/api/sections/_slug_.mjs +9 -9
  293. package/dist/astro/routes/api/sections/index.mjs +9 -9
  294. package/dist/astro/routes/api/settings/backups/archives/_name_.mjs +6 -6
  295. package/dist/astro/routes/api/settings/backups/archives/index.mjs +5 -5
  296. package/dist/astro/routes/api/settings/backups/export.mjs +6 -6
  297. package/dist/astro/routes/api/settings/backups/index.mjs +7 -7
  298. package/dist/astro/routes/api/settings/email.mjs +5 -5
  299. package/dist/astro/routes/api/settings/email.mjs.map +1 -1
  300. package/dist/astro/routes/api/settings.d.mts.map +1 -1
  301. package/dist/astro/routes/api/settings.mjs +20 -16
  302. package/dist/astro/routes/api/settings.mjs.map +1 -1
  303. package/dist/astro/routes/api/setup/admin-verify.mjs +12 -12
  304. package/dist/astro/routes/api/setup/admin.mjs +11 -11
  305. package/dist/astro/routes/api/setup/dev-bypass.d.mts.map +1 -1
  306. package/dist/astro/routes/api/setup/dev-bypass.mjs +35 -28
  307. package/dist/astro/routes/api/setup/dev-bypass.mjs.map +1 -1
  308. package/dist/astro/routes/api/setup/dev-reset.mjs +2 -2
  309. package/dist/astro/routes/api/setup/index.mjs +32 -30
  310. package/dist/astro/routes/api/setup/index.mjs.map +1 -1
  311. package/dist/astro/routes/api/setup/status.mjs +3 -3
  312. package/dist/astro/routes/api/snapshot.mjs +7 -7
  313. package/dist/astro/routes/api/taxonomies/_name_/reorder.d.mts.map +1 -1
  314. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs +20 -16
  315. package/dist/astro/routes/api/taxonomies/_name_/reorder.mjs.map +1 -1
  316. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.d.mts.map +1 -1
  317. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +21 -17
  318. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs.map +1 -1
  319. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.d.mts.map +1 -1
  320. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +25 -18
  321. package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs.map +1 -1
  322. package/dist/astro/routes/api/taxonomies/_name_/terms/index.d.mts.map +1 -1
  323. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +20 -16
  324. package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs.map +1 -1
  325. package/dist/astro/routes/api/taxonomies/_name_/translations.mjs +14 -14
  326. package/dist/astro/routes/api/taxonomies/_name_.d.mts.map +1 -1
  327. package/dist/astro/routes/api/taxonomies/_name_.mjs +26 -19
  328. package/dist/astro/routes/api/taxonomies/_name_.mjs.map +1 -1
  329. package/dist/astro/routes/api/taxonomies/index.d.mts.map +1 -1
  330. package/dist/astro/routes/api/taxonomies/index.mjs +20 -16
  331. package/dist/astro/routes/api/taxonomies/index.mjs.map +1 -1
  332. package/dist/astro/routes/api/themes/preview.mjs +5 -5
  333. package/dist/astro/routes/api/typegen.mjs +4 -4
  334. package/dist/astro/routes/api/well-known/auth.mjs +2 -2
  335. package/dist/astro/routes/api/well-known/oauth-authorization-server.mjs +2 -2
  336. package/dist/astro/routes/api/well-known/oauth-protected-resource.mjs +2 -2
  337. package/dist/astro/routes/api/widget-areas/_name_/reorder.d.mts.map +1 -1
  338. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs +10 -8
  339. package/dist/astro/routes/api/widget-areas/_name_/reorder.mjs.map +1 -1
  340. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.d.mts.map +1 -1
  341. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs +17 -13
  342. package/dist/astro/routes/api/widget-areas/_name_/widgets/_id_.mjs.map +1 -1
  343. package/dist/astro/routes/api/widget-areas/_name_/widgets.d.mts.map +1 -1
  344. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs +15 -12
  345. package/dist/astro/routes/api/widget-areas/_name_/widgets.mjs.map +1 -1
  346. package/dist/astro/routes/api/widget-areas/_name_.d.mts.map +1 -1
  347. package/dist/astro/routes/api/widget-areas/_name_.mjs +8 -6
  348. package/dist/astro/routes/api/widget-areas/_name_.mjs.map +1 -1
  349. package/dist/astro/routes/api/widget-areas/index.d.mts.map +1 -1
  350. package/dist/astro/routes/api/widget-areas/index.mjs +15 -12
  351. package/dist/astro/routes/api/widget-areas/index.mjs.map +1 -1
  352. package/dist/astro/routes/api/widget-components.mjs +2 -2
  353. package/dist/astro/routes/robots.txt.mjs +7 -7
  354. package/dist/astro/routes/sitemap-_collection_.xml.mjs +10 -10
  355. package/dist/astro/routes/sitemap.xml.mjs +8 -8
  356. package/dist/astro/types.d.mts +37 -17
  357. package/dist/astro/types.d.mts.map +1 -1
  358. package/dist/auth/providers/github.d.mts +1 -1
  359. package/dist/auth/providers/google.d.mts +1 -1
  360. package/dist/{authorize-DUElxgOQ.mjs → authorize-Bkf_UHhD.mjs} +2 -2
  361. package/dist/{authorize-DUElxgOQ.mjs.map → authorize-Bkf_UHhD.mjs.map} +1 -1
  362. package/dist/{backup-DWYpJlLj.mjs → backup-rwVAl9NI.mjs} +5 -5
  363. package/dist/{backup-DWYpJlLj.mjs.map → backup-rwVAl9NI.mjs.map} +1 -1
  364. package/dist/{bundle-vn56sLos.mjs → bundle-C8S2Zl6U.mjs} +4 -4
  365. package/dist/{bundle-vn56sLos.mjs.map → bundle-C8S2Zl6U.mjs.map} +1 -1
  366. package/dist/{byline-yjvWq4ip.mjs → byline-DuhF7NWl.mjs} +27 -14
  367. package/dist/byline-DuhF7NWl.mjs.map +1 -0
  368. package/dist/{byline-fields-txaLGoME.mjs → byline-fields-BovY4KYM.mjs} +2 -2
  369. package/dist/{byline-fields-txaLGoME.mjs.map → byline-fields-BovY4KYM.mjs.map} +1 -1
  370. package/dist/{byline-registry-DDun8sxh.mjs → byline-registry-Bpu9-MVs.mjs} +2 -2
  371. package/dist/{byline-registry-DDun8sxh.mjs.map → byline-registry-Bpu9-MVs.mjs.map} +1 -1
  372. package/dist/{bylines-DjXS5p0P.mjs → bylines-CJ5nd6Lw.mjs} +7 -7
  373. package/dist/{bylines-DjXS5p0P.mjs.map → bylines-CJ5nd6Lw.mjs.map} +1 -1
  374. package/dist/{bylines-Bu7pchQ4.mjs → bylines-RwBAeOF1.mjs} +3 -3
  375. package/dist/{bylines-Bu7pchQ4.mjs.map → bylines-RwBAeOF1.mjs.map} +1 -1
  376. package/dist/{cache-C46-3Irl.mjs → cache-BF5Kvn59.mjs} +4 -4
  377. package/dist/{cache-C46-3Irl.mjs.map → cache-BF5Kvn59.mjs.map} +1 -1
  378. package/dist/capture-triggers-CNW1q3HK.mjs +362 -0
  379. package/dist/capture-triggers-CNW1q3HK.mjs.map +1 -0
  380. package/dist/{challenge-store-SIL5DsF2.mjs → challenge-store-DQN_Yrck.mjs} +5 -3
  381. package/dist/challenge-store-DQN_Yrck.mjs.map +1 -0
  382. package/dist/chrome-tags-D8fiZG94.mjs +24 -0
  383. package/dist/chrome-tags-D8fiZG94.mjs.map +1 -0
  384. package/dist/{chunks-fiZ8G9RJ.mjs → chunks-C4szrD8o.mjs} +2 -2
  385. package/dist/{chunks-fiZ8G9RJ.mjs.map → chunks-C4szrD8o.mjs.map} +1 -1
  386. package/dist/cli/index.mjs +37 -53
  387. package/dist/cli/index.mjs.map +1 -1
  388. package/dist/client/cf-access.d.mts +1 -1
  389. package/dist/client/index.d.mts +74 -4
  390. package/dist/client/index.d.mts.map +1 -1
  391. package/dist/client/index.mjs +54 -2
  392. package/dist/client/index.mjs.map +1 -1
  393. package/dist/{collection-deletion-DQPvMD8R.mjs → collection-deletion-Bj07NHbj.mjs} +13 -356
  394. package/dist/collection-deletion-Bj07NHbj.mjs.map +1 -0
  395. package/dist/{comment-reaction-D-2J84UE.mjs → comment-reaction-BhrvSHml.mjs} +2 -2
  396. package/dist/{comment-reaction-D-2J84UE.mjs.map → comment-reaction-BhrvSHml.mjs.map} +1 -1
  397. package/dist/{comment-Dxlep6cE.mjs → comment-vxOzWbZN.mjs} +2 -2
  398. package/dist/{comment-Dxlep6cE.mjs.map → comment-vxOzWbZN.mjs.map} +1 -1
  399. package/dist/{comments-CTfZtLmM.mjs → comments-Ct4ensnf.mjs} +2 -2
  400. package/dist/{comments-CTfZtLmM.mjs.map → comments-Ct4ensnf.mjs.map} +1 -1
  401. package/dist/{components-CQy3lh9x.mjs → components-DJbo1z0S.mjs} +1 -1
  402. package/dist/{components-CQy3lh9x.mjs.map → components-DJbo1z0S.mjs.map} +1 -1
  403. package/dist/{config-COQzTe5Q.d.mts → config-B9eZ340f.d.mts} +1 -1
  404. package/dist/{config-COQzTe5Q.d.mts.map → config-B9eZ340f.d.mts.map} +1 -1
  405. package/dist/config-it29yDLA.mjs +1163 -0
  406. package/dist/config-it29yDLA.mjs.map +1 -0
  407. package/dist/{content-ZHCc1ngN.mjs → content-DjvM0T92.mjs} +86 -45
  408. package/dist/content-DjvM0T92.mjs.map +1 -0
  409. package/dist/{content-list-query-wJ2WN8Vp.d.mts → content-list-query-Btqd4uV2.d.mts} +1 -1
  410. package/dist/{content-list-query-wJ2WN8Vp.d.mts.map → content-list-query-Btqd4uV2.d.mts.map} +1 -1
  411. package/dist/{content-refresh-B_8SJzuU.mjs → content-refresh-Bwp-8yGy.mjs} +1139 -111
  412. package/dist/content-refresh-Bwp-8yGy.mjs.map +1 -0
  413. package/dist/{media-usage-BZCydfvu.mjs → content-repair-Czdp7jz5.mjs} +5 -196
  414. package/dist/content-repair-Czdp7jz5.mjs.map +1 -0
  415. package/dist/{context-ZldbZcle.mjs → context-CX6gxOLW.mjs} +55 -20
  416. package/dist/context-CX6gxOLW.mjs.map +1 -0
  417. package/dist/{cron-Y9aLtgrA.mjs → cron-C6o7VppJ.mjs} +1 -1
  418. package/dist/{cron-Y9aLtgrA.mjs.map → cron-C6o7VppJ.mjs.map} +1 -1
  419. package/dist/{dashboard-DvHbk_cv.mjs → dashboard-C2kTeeRI.mjs} +5 -5
  420. package/dist/{dashboard-DvHbk_cv.mjs.map → dashboard-C2kTeeRI.mjs.map} +1 -1
  421. package/dist/db/index.d.mts +3 -3
  422. package/dist/db/index.mjs +3 -3
  423. package/dist/db/index.mjs.map +1 -1
  424. package/dist/db/libsql-migrations.d.mts +1 -1
  425. package/dist/db/libsql-migrations.mjs +4 -4
  426. package/dist/db/libsql.d.mts +1 -1
  427. package/dist/db/postgres-migrations.d.mts +1 -1
  428. package/dist/db/postgres-migrations.mjs +4 -4
  429. package/dist/db/postgres.d.mts +1 -1
  430. package/dist/db/postgres.d.mts.map +1 -1
  431. package/dist/db/postgres.mjs +19 -3
  432. package/dist/db/postgres.mjs.map +1 -1
  433. package/dist/db/sqlite-migrations.d.mts +1 -1
  434. package/dist/db/sqlite-migrations.mjs +4 -4
  435. package/dist/db/sqlite.d.mts +1 -1
  436. package/dist/db/sqlite.mjs +3 -3
  437. package/dist/db/sqlite.mjs.map +1 -1
  438. package/dist/{default-DdDl3fxv.mjs → default-Clra32mw.mjs} +1 -1
  439. package/dist/{default-DdDl3fxv.mjs.map → default-Clra32mw.mjs.map} +1 -1
  440. package/dist/{deferred-tasks-SDWxrgzJ.d.mts → deferred-tasks-CvDETTJO.d.mts} +1 -1
  441. package/dist/{deferred-tasks-SDWxrgzJ.d.mts.map → deferred-tasks-CvDETTJO.d.mts.map} +1 -1
  442. package/dist/dev-typegen-DzOPfsNj.mjs +29 -0
  443. package/dist/dev-typegen-DzOPfsNj.mjs.map +1 -0
  444. package/dist/{device-flow-C0GdD_z8.mjs → device-flow-D2oCWvLJ.mjs} +5 -5
  445. package/dist/{device-flow-C0GdD_z8.mjs.map → device-flow-D2oCWvLJ.mjs.map} +1 -1
  446. package/dist/{direct-executor-CDXeJCSs.mjs → direct-executor-Bfa5_ToE.mjs} +3 -3
  447. package/dist/{direct-executor-CDXeJCSs.mjs.map → direct-executor-Bfa5_ToE.mjs.map} +1 -1
  448. package/dist/{dist-D_6CKR8z.mjs → dist-89xCrGqi.mjs} +1 -1
  449. package/dist/{dist-D_6CKR8z.mjs.map → dist-89xCrGqi.mjs.map} +1 -1
  450. package/dist/{email-console-BHNjIwiB.mjs → email-console-Dzb6uGYa.mjs} +1 -1
  451. package/dist/{email-console-BHNjIwiB.mjs.map → email-console-Dzb6uGYa.mjs.map} +1 -1
  452. package/dist/{enrich-_ySMEvEE.mjs → enrich-BX0IDp4z.mjs} +3 -3
  453. package/dist/{enrich-_ySMEvEE.mjs.map → enrich-BX0IDp4z.mjs.map} +1 -1
  454. package/dist/{error-DupyJZE2.mjs → error-DFrQjppn.mjs} +2 -2
  455. package/dist/{error-DupyJZE2.mjs.map → error-DFrQjppn.mjs.map} +1 -1
  456. package/dist/{errors-CLUPm7aD.mjs → errors-DsVoDUjJ.mjs} +24 -2
  457. package/dist/errors-DsVoDUjJ.mjs.map +1 -0
  458. package/dist/{escape-DUY2r2Zs.mjs → escape-HmHTC1Is.mjs} +1 -1
  459. package/dist/{escape-DUY2r2Zs.mjs.map → escape-HmHTC1Is.mjs.map} +1 -1
  460. package/dist/{field-defs-cache-BzwBlJrR.mjs → field-defs-cache-BM4SIRqH.mjs} +5 -5
  461. package/dist/{field-defs-cache-BzwBlJrR.mjs.map → field-defs-cache-BM4SIRqH.mjs.map} +1 -1
  462. package/dist/focal-point-BeWFo6Xx.mjs +23 -0
  463. package/dist/focal-point-BeWFo6Xx.mjs.map +1 -0
  464. package/dist/{fts-manager-DyZEohZC.mjs → fts-manager-Do1BlW2r.mjs} +3 -3
  465. package/dist/{fts-manager-DyZEohZC.mjs.map → fts-manager-Do1BlW2r.mjs.map} +1 -1
  466. package/dist/{hash-Cg0TXJPV.mjs → hash-3JJPlHF2.mjs} +1 -1
  467. package/dist/{hash-Cg0TXJPV.mjs.map → hash-3JJPlHF2.mjs.map} +1 -1
  468. package/dist/hook-result-DCh2WUpe.d.mts +31 -0
  469. package/dist/hook-result-DCh2WUpe.d.mts.map +1 -0
  470. package/dist/{hreflang-DwT2E0Sa.d.mts → hreflang-B6hbAuuO.d.mts} +2 -2
  471. package/dist/{hreflang-DwT2E0Sa.d.mts.map → hreflang-B6hbAuuO.d.mts.map} +1 -1
  472. package/dist/{hreflang-BBe83kKa.mjs → hreflang-DQbPZliA.mjs} +7 -7
  473. package/dist/{hreflang-BBe83kKa.mjs.map → hreflang-DQbPZliA.mjs.map} +1 -1
  474. package/dist/{identity-Ys6Dlc9C.mjs → identity-DksvEazf.mjs} +3 -3
  475. package/dist/{identity-Ys6Dlc9C.mjs.map → identity-DksvEazf.mjs.map} +1 -1
  476. package/dist/{import-DPkLmeXO.mjs → import-CJpaBBBT.mjs} +6 -6
  477. package/dist/{import-DPkLmeXO.mjs.map → import-CJpaBBBT.mjs.map} +1 -1
  478. package/dist/{index-BVBZj4-7.d.mts → index-BJNMCWmu.d.mts} +267 -82
  479. package/dist/index-BJNMCWmu.d.mts.map +1 -0
  480. package/dist/{index-C9KuQyO-.d.mts → index-Du8K7bWa.d.mts} +3 -3
  481. package/dist/{index-C9KuQyO-.d.mts.map → index-Du8K7bWa.d.mts.map} +1 -1
  482. package/dist/index.d.mts +22 -21
  483. package/dist/index.mjs +79 -73
  484. package/dist/{init-lock-6b309ZrF.mjs → init-lock-DJkX6Hto.mjs} +1 -1
  485. package/dist/{init-lock-6b309ZrF.mjs.map → init-lock-DJkX6Hto.mjs.map} +1 -1
  486. package/dist/{load-YJ2xl3ra.mjs → load-CawHjTOH.mjs} +2 -2
  487. package/dist/{load-YJ2xl3ra.mjs.map → load-CawHjTOH.mjs.map} +1 -1
  488. package/dist/{loader-CdG_Ci3H.mjs → loader-Z8vl7zTq.mjs} +48 -13
  489. package/dist/loader-Z8vl7zTq.mjs.map +1 -0
  490. package/dist/{manifest-builder-B252yQUf.mjs → manifest-builder-COtzuca2.mjs} +2 -2
  491. package/dist/{manifest-builder-B252yQUf.mjs.map → manifest-builder-COtzuca2.mjs.map} +1 -1
  492. package/dist/{manifest-schema-BXbUAHod.mjs → manifest-schema-BNWwR8Vd.mjs} +5 -5
  493. package/dist/manifest-schema-BNWwR8Vd.mjs.map +1 -0
  494. package/dist/media/image-endpoint.d.mts +4 -2
  495. package/dist/media/image-endpoint.d.mts.map +1 -1
  496. package/dist/media/image-endpoint.mjs +6 -4
  497. package/dist/media/image-endpoint.mjs.map +1 -1
  498. package/dist/media/index.d.mts +1 -1
  499. package/dist/media/index.mjs +13 -3
  500. package/dist/media/index.mjs.map +1 -1
  501. package/dist/media/local-runtime.d.mts +14 -12
  502. package/dist/media/local-runtime.d.mts.map +1 -1
  503. package/dist/media/local-runtime.mjs +12 -6
  504. package/dist/media/local-runtime.mjs.map +1 -1
  505. package/dist/{media-CzhAn2--.mjs → media-BBm8Wg3f.mjs} +69 -12
  506. package/dist/media-BBm8Wg3f.mjs.map +1 -0
  507. package/dist/{media-BWWWb8kg.mjs → media-BHjus86Y.mjs} +133 -9
  508. package/dist/media-BHjus86Y.mjs.map +1 -0
  509. package/dist/{media-allowlist-D6x-Us02.mjs → media-allowlist-CoTBWoDp.mjs} +3 -2
  510. package/dist/media-allowlist-CoTBWoDp.mjs.map +1 -0
  511. package/dist/media-folders-BGkATs8n.mjs +210 -0
  512. package/dist/media-folders-BGkATs8n.mjs.map +1 -0
  513. package/dist/{media-upload-CHBVn6m-.mjs → media-upload-BCidR-EY.mjs} +9 -9
  514. package/dist/{media-upload-CHBVn6m-.mjs.map → media-upload-BCidR-EY.mjs.map} +1 -1
  515. package/dist/{media-url-BvoX88FA.mjs → media-url-DHoPr0hq.mjs} +1 -1
  516. package/dist/{media-url-BvoX88FA.mjs.map → media-url-DHoPr0hq.mjs.map} +1 -1
  517. package/dist/media-usage-CdY5jhSR.mjs +1833 -0
  518. package/dist/media-usage-CdY5jhSR.mjs.map +1 -0
  519. package/dist/media-usage-activation-BgeMtK5C.mjs +78 -0
  520. package/dist/media-usage-activation-BgeMtK5C.mjs.map +1 -0
  521. package/dist/{media-usage-work-CLo_6tct.mjs → media-usage-work-CnGCdHxx.mjs} +4 -4
  522. package/dist/{media-usage-work-CLo_6tct.mjs.map → media-usage-work-CnGCdHxx.mjs.map} +1 -1
  523. package/dist/{media-usage-work-DrCbqBcl.mjs → media-usage-work-D6D9sMCA.mjs} +221 -59
  524. package/dist/media-usage-work-D6D9sMCA.mjs.map +1 -0
  525. package/dist/{media-usage-write-fence-aHEgN1zB.mjs → media-usage-write-fence-hjeD4u7s.mjs} +2 -2
  526. package/dist/{media-usage-write-fence-aHEgN1zB.mjs.map → media-usage-write-fence-hjeD4u7s.mjs.map} +1 -1
  527. package/dist/{menus-DSo5QeW0.mjs → menus-6qSwTNxG.mjs} +375 -107
  528. package/dist/menus-6qSwTNxG.mjs.map +1 -0
  529. package/dist/{menus-TCNSd2vp.mjs → menus-uvPLXMZf.mjs} +4 -4
  530. package/dist/{menus-TCNSd2vp.mjs.map → menus-uvPLXMZf.mjs.map} +1 -1
  531. package/dist/migrations/index.d.mts +1 -1
  532. package/dist/migrations/index.mjs +3 -3
  533. package/dist/{mime-DfIVjNkr.mjs → mime-CUIG6x84.mjs} +1 -1
  534. package/dist/mime-CUIG6x84.mjs.map +1 -0
  535. package/dist/{mode-BDoH_WcF.mjs → mode-DN_WneRx.mjs} +1 -1
  536. package/dist/{mode-BDoH_WcF.mjs.map → mode-DN_WneRx.mjs.map} +1 -1
  537. package/dist/node-sqlite-compat-BuJXIeMz.mjs +46 -0
  538. package/dist/node-sqlite-compat-BuJXIeMz.mjs.map +1 -0
  539. package/dist/{normalize-Bc-s_r-a.mjs → normalize-C2xNjTSG.mjs} +36 -5
  540. package/dist/normalize-C2xNjTSG.mjs.map +1 -0
  541. package/dist/{oauth-authorization-iOikmrJd.mjs → oauth-authorization-Dj6Kwc21.mjs} +5 -5
  542. package/dist/{oauth-authorization-iOikmrJd.mjs.map → oauth-authorization-Dj6Kwc21.mjs.map} +1 -1
  543. package/dist/{oauth-clients-CvI0nHMJ.mjs → oauth-clients-FD7I0J8m.mjs} +1 -1
  544. package/dist/{oauth-clients-CvI0nHMJ.mjs.map → oauth-clients-FD7I0J8m.mjs.map} +1 -1
  545. package/dist/{oauth-state-store-Ba8KZlwW.mjs → oauth-state-store-DkmDOmHs.mjs} +1 -1
  546. package/dist/{oauth-state-store-Ba8KZlwW.mjs.map → oauth-state-store-DkmDOmHs.mjs.map} +1 -1
  547. package/dist/{oauth-user-lookup-C5SQwGYC.mjs → oauth-user-lookup-CvIwGpYd.mjs} +1 -1
  548. package/dist/{oauth-user-lookup-C5SQwGYC.mjs.map → oauth-user-lookup-CvIwGpYd.mjs.map} +1 -1
  549. package/dist/object-cache/memory.d.mts +1 -1
  550. package/dist/{object-cache-71tPfV4A.mjs → object-cache-DVKnyOfy.mjs} +19 -3
  551. package/dist/object-cache-DVKnyOfy.mjs.map +1 -0
  552. package/dist/{options-CBXIHUoT.mjs → options-BHPeIbBd.mjs} +1 -1
  553. package/dist/{options-CBXIHUoT.mjs.map → options-BHPeIbBd.mjs.map} +1 -1
  554. package/dist/{options--hhz-jZ1.d.mts → options-CYb4y7hM.d.mts} +24 -11
  555. package/dist/options-CYb4y7hM.d.mts.map +1 -0
  556. package/dist/page/index.d.mts +2 -2
  557. package/dist/{parse-DFbuc-Fh.mjs → parse-Ckpg-Qfp.mjs} +2 -2
  558. package/dist/{parse-DFbuc-Fh.mjs.map → parse-Ckpg-Qfp.mjs.map} +1 -1
  559. package/dist/{passkey-config-DFAmUyuE.mjs → passkey-config-O_lj3y0k.mjs} +1 -1
  560. package/dist/{passkey-config-DFAmUyuE.mjs.map → passkey-config-O_lj3y0k.mjs.map} +1 -1
  561. package/dist/{patterns-CiyXeDgr.mjs → patterns-D9iDO3j8.mjs} +1 -1
  562. package/dist/{patterns-CiyXeDgr.mjs.map → patterns-D9iDO3j8.mjs.map} +1 -1
  563. package/dist/{placeholder-Dp0K3RkD.d.mts → placeholder-4X9BrRrp.d.mts} +7 -1
  564. package/dist/placeholder-4X9BrRrp.d.mts.map +1 -0
  565. package/dist/plugin-types.d.mts +8 -3
  566. package/dist/plugin-types.d.mts.map +1 -1
  567. package/dist/plugin-utils.d.mts +10 -10
  568. package/dist/plugins/adapt-sandbox-entry.d.mts +10 -10
  569. package/dist/plugins/adapt-sandbox-entry.mjs +2 -2
  570. package/dist/{policy-TluUIxuu.mjs → policy-Dhtwntrt.mjs} +2 -2
  571. package/dist/{policy-TluUIxuu.mjs.map → policy-Dhtwntrt.mjs.map} +1 -1
  572. package/dist/{portable-text-imBW5cHK.mjs → portable-text-U85hOafW.mjs} +1 -1
  573. package/dist/{portable-text-imBW5cHK.mjs.map → portable-text-U85hOafW.mjs.map} +1 -1
  574. package/dist/{preview-PW-nOnq4.mjs → preview-B_vJLvf8.mjs} +2 -2
  575. package/dist/{preview-PW-nOnq4.mjs.map → preview-B_vJLvf8.mjs.map} +1 -1
  576. package/dist/{protocol-DjsJHTlK.d.mts → protocol-JdD2YhY9.d.mts} +2 -2
  577. package/dist/{protocol-DjsJHTlK.d.mts.map → protocol-JdD2YhY9.d.mts.map} +1 -1
  578. package/dist/{public-url-CWoFhQT8.mjs → public-url-CarhZJgf.mjs} +1 -1
  579. package/dist/{public-url-CWoFhQT8.mjs.map → public-url-CarhZJgf.mjs.map} +1 -1
  580. package/dist/{query-zTVAR1Sl.mjs → query-BZKZcG5b.mjs} +15 -15
  581. package/dist/{query-zTVAR1Sl.mjs.map → query-BZKZcG5b.mjs.map} +1 -1
  582. package/dist/{query-BWs7O5Il.mjs → query-BndaFxxp.mjs} +5 -5
  583. package/dist/{query-BWs7O5Il.mjs.map → query-BndaFxxp.mjs.map} +1 -1
  584. package/dist/{rate-limit-Bx4g9m3p.mjs → rate-limit-BZmATC6W.mjs} +2 -2
  585. package/dist/{rate-limit-Bx4g9m3p.mjs.map → rate-limit-BZmATC6W.mjs.map} +1 -1
  586. package/dist/{redirect-COsS6SWJ.mjs → redirect-CZkbozu9.mjs} +2 -2
  587. package/dist/{redirect-COsS6SWJ.mjs.map → redirect-CZkbozu9.mjs.map} +1 -1
  588. package/dist/{redirect-BgAOGHDq.mjs → redirect-CzqnLxK-.mjs} +1 -1
  589. package/dist/{redirect-BgAOGHDq.mjs.map → redirect-CzqnLxK-.mjs.map} +1 -1
  590. package/dist/{redirects-DTDHWH31.mjs → redirects-BLNOWQTn.mjs} +64 -29
  591. package/dist/redirects-BLNOWQTn.mjs.map +1 -0
  592. package/dist/{redirects-DyChwDkG.mjs → redirects-CqzNM0KM.mjs} +5 -5
  593. package/dist/{redirects-DyChwDkG.mjs.map → redirects-CqzNM0KM.mjs.map} +1 -1
  594. package/dist/{registry-Cqa2I749.mjs → registry-AZAsRsor.mjs} +30 -126
  595. package/dist/registry-AZAsRsor.mjs.map +1 -0
  596. package/dist/{relation-BnHB0T4J.mjs → relation-04DfKRTO.mjs} +2 -2
  597. package/dist/{relation-BnHB0T4J.mjs.map → relation-04DfKRTO.mjs.map} +1 -1
  598. package/dist/{relations-BBApI4e2.mjs → relations-C4htk5sb.mjs} +7 -7
  599. package/dist/relations-C4htk5sb.mjs.map +1 -0
  600. package/dist/{relations-D5sM5fW0.mjs → relations-CcFwDJdJ.mjs} +4 -4
  601. package/dist/{relations-D5sM5fW0.mjs.map → relations-CcFwDJdJ.mjs.map} +1 -1
  602. package/dist/{relations-BHo5A8Zf.d.mts → relations-DnRK4YIT.d.mts} +347 -54
  603. package/dist/relations-DnRK4YIT.d.mts.map +1 -0
  604. package/dist/{request-cache-BSUptuJR.mjs → request-cache-DH9zdCOD.mjs} +1 -1
  605. package/dist/{request-cache-BSUptuJR.mjs.map → request-cache-DH9zdCOD.mjs.map} +1 -1
  606. package/dist/request-context.d.mts +1 -1
  607. package/dist/{request-meta-DgZJh3zG.mjs → request-meta-DYxLlnmz.mjs} +2 -2
  608. package/dist/{request-meta-DgZJh3zG.mjs.map → request-meta-DYxLlnmz.mjs.map} +1 -1
  609. package/dist/{resolve-DOhVEvty.mjs → resolve-prZ3mP7l.mjs} +1 -1
  610. package/dist/{resolve-DOhVEvty.mjs.map → resolve-prZ3mP7l.mjs.map} +1 -1
  611. package/dist/{runner-C1T11CfC.mjs → runner-BLIDKpmA.mjs} +471 -290
  612. package/dist/runner-BLIDKpmA.mjs.map +1 -0
  613. package/dist/{runner-BYHZn3Jy.d.mts → runner-YKfIMnaF.d.mts} +3 -2
  614. package/dist/runner-YKfIMnaF.d.mts.map +1 -0
  615. package/dist/runtime.d.mts +11 -11
  616. package/dist/runtime.mjs +1 -1
  617. package/dist/{schema-DZ5YVVZj.mjs → schema-CGnBeLiW.mjs} +3 -3
  618. package/dist/{schema-DZ5YVVZj.mjs.map → schema-CGnBeLiW.mjs.map} +1 -1
  619. package/dist/{schema-2AOsSn2v.mjs → schema-DYr-Vd-L.mjs} +36 -6
  620. package/dist/{schema-2AOsSn2v.mjs.map → schema-DYr-Vd-L.mjs.map} +1 -1
  621. package/dist/{scopes-8ClPF2bC.mjs → scopes-BhWvBavj.mjs} +3 -3
  622. package/dist/{scopes-8ClPF2bC.mjs.map → scopes-BhWvBavj.mjs.map} +1 -1
  623. package/dist/{search-u1QYdOCG.mjs → search-C-qDk4kx.mjs} +4 -4
  624. package/dist/{search-u1QYdOCG.mjs.map → search-C-qDk4kx.mjs.map} +1 -1
  625. package/dist/{secrets-BEgsAQEU.mjs → secrets-rEtHt-6z.mjs} +3 -3
  626. package/dist/{secrets-BEgsAQEU.mjs.map → secrets-rEtHt-6z.mjs.map} +1 -1
  627. package/dist/{sections-DmHviGyM.mjs → sections-B_nYvlwn.mjs} +2 -2
  628. package/dist/{sections-DmHviGyM.mjs.map → sections-B_nYvlwn.mjs.map} +1 -1
  629. package/dist/seed/index.d.mts +2 -2
  630. package/dist/seed/index.mjs +25 -23
  631. package/dist/seo/index.d.mts +3 -3
  632. package/dist/seo/index.mjs +17 -15
  633. package/dist/seo/index.mjs.map +1 -1
  634. package/dist/{seo-Dq4G-RrO.mjs → seo-926NRIgt.mjs} +3 -3
  635. package/dist/{seo-Dq4G-RrO.mjs.map → seo-926NRIgt.mjs.map} +1 -1
  636. package/dist/{seo-AFpVvTqr.mjs → seo-CVWkdv6x.mjs} +1 -1
  637. package/dist/{seo-AFpVvTqr.mjs.map → seo-CVWkdv6x.mjs.map} +1 -1
  638. package/dist/{service-BpArayPr.mjs → service-CJl3ZAYs.mjs} +3 -3
  639. package/dist/{service-BpArayPr.mjs.map → service-CJl3ZAYs.mjs.map} +1 -1
  640. package/dist/{session-user-BEorKVT-.mjs → session-user-BlMgqCHS.mjs} +1 -1
  641. package/dist/{session-user-BEorKVT-.mjs.map → session-user-BlMgqCHS.mjs.map} +1 -1
  642. package/dist/{settings-xRdoUZr0.mjs → settings--wobrkkC.mjs} +21 -8
  643. package/dist/settings--wobrkkC.mjs.map +1 -0
  644. package/dist/{settings-DE9xtzqd.mjs → settings-Cwm6o2jY.mjs} +3 -3
  645. package/dist/{settings-DE9xtzqd.mjs.map → settings-Cwm6o2jY.mjs.map} +1 -1
  646. package/dist/{setup-complete-BnT8pq_C.mjs → setup-complete-DQbClIN2.mjs} +2 -2
  647. package/dist/{setup-complete-BnT8pq_C.mjs.map → setup-complete-DQbClIN2.mjs.map} +1 -1
  648. package/dist/{setup-nonce-CBitf_oQ.mjs → setup-nonce-DZCFS2sn.mjs} +1 -1
  649. package/dist/{setup-nonce-CBitf_oQ.mjs.map → setup-nonce-DZCFS2sn.mjs.map} +1 -1
  650. package/dist/{single-flight-cache-B0eLKS6K.mjs → single-flight-cache-BPuGPdcN.mjs} +2 -2
  651. package/dist/{single-flight-cache-B0eLKS6K.mjs.map → single-flight-cache-BPuGPdcN.mjs.map} +1 -1
  652. package/dist/{site-url-DjpIXMXJ.mjs → site-url-BrxA_E9H.mjs} +3 -3
  653. package/dist/{site-url-DjpIXMXJ.mjs.map → site-url-BrxA_E9H.mjs.map} +1 -1
  654. package/dist/{snapshot-BBlGkb2q.mjs → snapshot--OCDTqdb.mjs} +1 -1
  655. package/dist/{snapshot-BBlGkb2q.mjs.map → snapshot--OCDTqdb.mjs.map} +1 -1
  656. package/dist/{ssrf-Cpvg_n3A.mjs → ssrf-5sIM5jzl.mjs} +23 -6
  657. package/dist/{ssrf-Cpvg_n3A.mjs.map → ssrf-5sIM5jzl.mjs.map} +1 -1
  658. package/dist/{state-DYwPue40.mjs → state-BpFVsJZB.mjs} +12 -4
  659. package/dist/state-BpFVsJZB.mjs.map +1 -0
  660. package/dist/{status-CWVYpbD8.mjs → status-B777-dXz.mjs} +1 -1
  661. package/dist/{status-CWVYpbD8.mjs.map → status-B777-dXz.mjs.map} +1 -1
  662. package/dist/storage/local.d.mts +2 -1
  663. package/dist/storage/local.d.mts.map +1 -1
  664. package/dist/storage/local.mjs +1 -1
  665. package/dist/storage/local.mjs.map +1 -1
  666. package/dist/storage/s3.d.mts +2 -1
  667. package/dist/storage/s3.d.mts.map +1 -1
  668. package/dist/storage/s3.mjs +3 -2
  669. package/dist/storage/s3.mjs.map +1 -1
  670. package/dist/{target-DixqqV5i.mjs → target-BmR0iTwz.mjs} +1 -1
  671. package/dist/{target-DixqqV5i.mjs.map → target-BmR0iTwz.mjs.map} +1 -1
  672. package/dist/{taxonomies-OHUIiIpI.mjs → taxonomies-DkAkMupr.mjs} +17 -14
  673. package/dist/taxonomies-DkAkMupr.mjs.map +1 -0
  674. package/dist/{taxonomies-BlrncHi9.mjs → taxonomies-Wfy_Lg12.mjs} +43 -17
  675. package/dist/taxonomies-Wfy_Lg12.mjs.map +1 -0
  676. package/dist/{taxonomy-BqCZ1TdU.mjs → taxonomy-tJepplLL.mjs} +5 -5
  677. package/dist/{taxonomy-BqCZ1TdU.mjs.map → taxonomy-tJepplLL.mjs.map} +1 -1
  678. package/dist/{tokens-C39klX8R.mjs → tokens-BCO1oruF.mjs} +1 -1
  679. package/dist/{tokens-C39klX8R.mjs.map → tokens-BCO1oruF.mjs.map} +1 -1
  680. package/dist/{transaction-NQj4VJ7Z.mjs → transaction-0KOpOyMu.mjs} +2 -1
  681. package/dist/{transaction-NQj4VJ7Z.mjs.map → transaction-0KOpOyMu.mjs.map} +1 -1
  682. package/dist/{transport-DBJwa-Si.mjs → transport-Dr3qtwXC.mjs} +4 -3
  683. package/dist/{transport-DBJwa-Si.mjs.map → transport-Dr3qtwXC.mjs.map} +1 -1
  684. package/dist/{transport-RQE36APG.d.mts → transport-xh6YKW2G.d.mts} +1 -1
  685. package/dist/{transport-RQE36APG.d.mts.map → transport-xh6YKW2G.d.mts.map} +1 -1
  686. package/dist/{trusted-proxy-CEVekpby.mjs → trusted-proxy-BR5F1Otp.mjs} +1 -1
  687. package/dist/{trusted-proxy-CEVekpby.mjs.map → trusted-proxy-BR5F1Otp.mjs.map} +1 -1
  688. package/dist/{types-BW1syrlw.mjs → types-3qNFPlci.mjs} +1 -1
  689. package/dist/{types-BW1syrlw.mjs.map → types-3qNFPlci.mjs.map} +1 -1
  690. package/dist/types-75KIqzL9.mjs.map +1 -1
  691. package/dist/{types-DrJrVCT1.d.mts → types-B6GrPic4.d.mts} +9 -3
  692. package/dist/{types-DrJrVCT1.d.mts.map → types-B6GrPic4.d.mts.map} +1 -1
  693. package/dist/{types-DN64_zzZ.d.mts → types-BuHW4xDE.d.mts} +11 -10
  694. package/dist/types-BuHW4xDE.d.mts.map +1 -0
  695. package/dist/{types-DWRhk9xZ.d.mts → types-C00oyCZp.d.mts} +1 -1
  696. package/dist/{types-DWRhk9xZ.d.mts.map → types-C00oyCZp.d.mts.map} +1 -1
  697. package/dist/{types-BntycPTF.d.mts → types-CDtkNSFQ.d.mts} +1 -1
  698. package/dist/{types-BntycPTF.d.mts.map → types-CDtkNSFQ.d.mts.map} +1 -1
  699. package/dist/{types-Dfk8KI5R.d.mts → types-CPeXo1wF.d.mts} +1 -1
  700. package/dist/{types-Dfk8KI5R.d.mts.map → types-CPeXo1wF.d.mts.map} +1 -1
  701. package/dist/types-CQPWhPxE.mjs.map +1 -1
  702. package/dist/{types-BcqdcT-r.d.mts → types-CXFkwEGC.d.mts} +3 -2
  703. package/dist/types-CXFkwEGC.d.mts.map +1 -0
  704. package/dist/{types-CtzytVXn.mjs → types-DM3vioBY.mjs} +1 -1
  705. package/dist/{types-CtzytVXn.mjs.map → types-DM3vioBY.mjs.map} +1 -1
  706. package/dist/{types-CXnOzDe1.d.mts → types-DczELMop.d.mts} +1 -1
  707. package/dist/{types-CXnOzDe1.d.mts.map → types-DczELMop.d.mts.map} +1 -1
  708. package/dist/types-DfuTR6dL.mjs +3 -0
  709. package/dist/{types-DQIDRKF2.d.mts → types-FV23hEoW.d.mts} +10 -1
  710. package/dist/types-FV23hEoW.d.mts.map +1 -0
  711. package/dist/{types-C2pMvO62.d.mts → types-xDMtUFnO.d.mts} +2 -1
  712. package/dist/types-xDMtUFnO.d.mts.map +1 -0
  713. package/dist/{upload-attempts-D4FS8LT6.mjs → upload-attempts-BsqoQ1fn.mjs} +1 -1
  714. package/dist/{upload-attempts-D4FS8LT6.mjs.map → upload-attempts-BsqoQ1fn.mjs.map} +1 -1
  715. package/dist/{url-pattern-BHS0V5Ng.mjs → url-pattern-D4c2czpJ.mjs} +1 -1
  716. package/dist/{url-pattern-BHS0V5Ng.mjs.map → url-pattern-D4c2czpJ.mjs.map} +1 -1
  717. package/dist/{user-DJZfUJVE.mjs → user-BTZ40aq6.mjs} +2 -2
  718. package/dist/{user-DJZfUJVE.mjs.map → user-BTZ40aq6.mjs.map} +1 -1
  719. package/dist/{utils-D4vD_Y98.mjs → utils-BKvNjjhY.mjs} +1 -1
  720. package/dist/{utils-D4vD_Y98.mjs.map → utils-BKvNjjhY.mjs.map} +1 -1
  721. package/dist/{validate-BMLBvxOC.mjs → validate-DE_LRwo9.mjs} +2 -2
  722. package/dist/{validate-BMLBvxOC.mjs.map → validate-DE_LRwo9.mjs.map} +1 -1
  723. package/dist/{validate-CTqt5nuE.d.mts → validate-DUP27OYD.d.mts} +5 -5
  724. package/dist/{validate-CTqt5nuE.d.mts.map → validate-DUP27OYD.d.mts.map} +1 -1
  725. package/dist/{validation-npvENUCB.mjs → validation-BMImFJ11.mjs} +10 -8
  726. package/dist/{validation-npvENUCB.mjs.map → validation-BMImFJ11.mjs.map} +1 -1
  727. package/dist/version-Bii3suaO.mjs +7 -0
  728. package/dist/{version-DB_fqCSI.mjs.map → version-Bii3suaO.mjs.map} +1 -1
  729. package/dist/{widgets-BD3ho7Rq.mjs → widgets-D3gJ10xU.mjs} +18 -5
  730. package/dist/widgets-D3gJ10xU.mjs.map +1 -0
  731. package/dist/{wxr-taxonomies-Ca68766D.d.mts → wxr-taxonomies-B2Og_6rU.d.mts} +1 -1
  732. package/dist/{wxr-taxonomies-Ca68766D.d.mts.map → wxr-taxonomies-B2Og_6rU.d.mts.map} +1 -1
  733. package/dist/{wxr-taxonomies-B1R3vBoD.mjs → wxr-taxonomies-Cxngsjwo.mjs} +4 -4
  734. package/dist/{wxr-taxonomies-B1R3vBoD.mjs.map → wxr-taxonomies-Cxngsjwo.mjs.map} +1 -1
  735. package/dist/{zod-generator-LC-on_Vb.mjs → zod-generator-BuYSQJB7.mjs} +32 -22
  736. package/dist/zod-generator-BuYSQJB7.mjs.map +1 -0
  737. package/package.json +20 -9
  738. package/src/api/errors.ts +22 -0
  739. package/src/api/handlers/content.ts +49 -11
  740. package/src/api/handlers/index.ts +18 -0
  741. package/src/api/handlers/manifest.ts +161 -12
  742. package/src/api/handlers/media-allowlist.ts +1 -0
  743. package/src/api/handlers/media-folders.ts +130 -0
  744. package/src/api/handlers/media-usage-activation.ts +102 -0
  745. package/src/api/handlers/media-usage.ts +108 -0
  746. package/src/api/handlers/media.ts +92 -2
  747. package/src/api/handlers/registry.ts +483 -561
  748. package/src/api/handlers/taxonomies.ts +16 -9
  749. package/src/api/openapi/document.ts +277 -7
  750. package/src/api/parse.ts +1 -1
  751. package/src/api/schemas/auth.ts +4 -4
  752. package/src/api/schemas/bylines.ts +3 -3
  753. package/src/api/schemas/comments.ts +1 -1
  754. package/src/api/schemas/common.ts +3 -2
  755. package/src/api/schemas/content.ts +78 -22
  756. package/src/api/schemas/media-usage.ts +77 -0
  757. package/src/api/schemas/media.ts +121 -0
  758. package/src/api/schemas/redirects.ts +6 -1
  759. package/src/api/schemas/schema.ts +4 -0
  760. package/src/api/schemas/setup.ts +1 -1
  761. package/src/api/schemas/taxonomies.ts +2 -2
  762. package/src/api/schemas/users.ts +1 -1
  763. package/src/api/types.ts +23 -10
  764. package/src/astro/dev-typegen.ts +35 -0
  765. package/src/astro/image-endpoint.ts +2 -2
  766. package/src/astro/integration/dev-typegen.ts +91 -0
  767. package/src/astro/integration/index.ts +9 -44
  768. package/src/astro/integration/routes.ts +23 -0
  769. package/src/astro/integration/vite-config.ts +23 -9
  770. package/src/astro/middleware/auth.ts +4 -0
  771. package/src/astro/middleware.ts +5 -7
  772. package/src/astro/routes/api/admin/api-tokens/index.ts +4 -1
  773. package/src/astro/routes/api/admin/media-usage/activation.ts +42 -0
  774. package/src/astro/routes/api/admin/media-usage/progress.ts +37 -0
  775. package/src/astro/routes/api/admin/oauth-clients/[id].ts +1 -1
  776. package/src/astro/routes/api/admin/oauth-clients/index.ts +1 -1
  777. package/src/astro/routes/api/admin/plugins/registry/[id]/update.ts +4 -0
  778. package/src/astro/routes/api/admin/plugins/registry/artifact.ts +247 -101
  779. package/src/astro/routes/api/admin/plugins/registry/install.ts +4 -0
  780. package/src/astro/routes/api/admin/plugins/registry/verify.ts +60 -0
  781. package/src/astro/routes/api/auth/me.ts +14 -2
  782. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +8 -2
  783. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +2 -1
  784. package/src/astro/routes/api/content/[collection]/[id]/unpublish.ts +6 -2
  785. package/src/astro/routes/api/manifest.ts +1 -1
  786. package/src/astro/routes/api/media/[id]/replace.ts +114 -0
  787. package/src/astro/routes/api/media/[id].ts +3 -0
  788. package/src/astro/routes/api/media/file/[...key].ts +4 -1
  789. package/src/astro/routes/api/media/folders/[id].ts +55 -0
  790. package/src/astro/routes/api/media/folders/index.ts +37 -0
  791. package/src/astro/routes/api/media/upload-url.ts +8 -4
  792. package/src/astro/routes/api/media.ts +66 -10
  793. package/src/astro/routes/api/menus/[name]/items/[id].ts +7 -2
  794. package/src/astro/routes/api/menus/[name]/items.ts +4 -1
  795. package/src/astro/routes/api/menus/[name]/reorder.ts +4 -1
  796. package/src/astro/routes/api/menus/[name]/translations.ts +4 -1
  797. package/src/astro/routes/api/menus/[name].ts +7 -2
  798. package/src/astro/routes/api/menus/index.ts +4 -1
  799. package/src/astro/routes/api/settings/email.ts +1 -1
  800. package/src/astro/routes/api/settings.ts +4 -1
  801. package/src/astro/routes/api/setup/dev-bypass.ts +12 -0
  802. package/src/astro/routes/api/taxonomies/[name]/reorder.ts +4 -1
  803. package/src/astro/routes/api/taxonomies/[name]/terms/[slug]/translations.ts +4 -1
  804. package/src/astro/routes/api/taxonomies/[name]/terms/[slug].ts +7 -2
  805. package/src/astro/routes/api/taxonomies/[name]/terms/index.ts +4 -1
  806. package/src/astro/routes/api/taxonomies/[name].ts +7 -2
  807. package/src/astro/routes/api/taxonomies/index.ts +4 -1
  808. package/src/astro/routes/api/widget-areas/[name]/reorder.ts +3 -1
  809. package/src/astro/routes/api/widget-areas/[name]/widgets/[id].ts +5 -2
  810. package/src/astro/routes/api/widget-areas/[name]/widgets.ts +3 -1
  811. package/src/astro/routes/api/widget-areas/[name].ts +3 -1
  812. package/src/astro/routes/api/widget-areas/index.ts +3 -1
  813. package/src/astro/types.ts +34 -6
  814. package/src/auth/challenge-store.ts +3 -1
  815. package/src/aws-sdk.d.ts +1 -0
  816. package/src/cache/chrome-tags.ts +24 -0
  817. package/src/client/index.ts +140 -2
  818. package/src/client/transport.ts +6 -2
  819. package/src/components/EmDashImage.astro +156 -51
  820. package/src/components/EmDashMedia.astro +2 -1
  821. package/src/components/Gallery.astro +7 -0
  822. package/src/components/InlinePortableTextEditor.tsx +136 -2
  823. package/src/components/LiveSearch.astro +23 -0
  824. package/src/components/inline-code-block.tsx +180 -49
  825. package/src/components/widgets/Archives.astro +2 -37
  826. package/src/content/converters/gallery.ts +2 -0
  827. package/src/content/converters/index.ts +2 -0
  828. package/src/content/converters/mark-safety.ts +1 -0
  829. package/src/content/converters/portable-text-identity.ts +139 -0
  830. package/src/content/converters/portable-text-to-prosemirror.ts +202 -69
  831. package/src/content/converters/prosemirror-to-portable-text.ts +96 -25
  832. package/src/content/converters/types.ts +3 -0
  833. package/src/database/connection.ts +2 -31
  834. package/src/database/index.ts +1 -1
  835. package/src/database/json-recordset.ts +16 -0
  836. package/src/database/migrations/017_authorization_codes.ts +14 -4
  837. package/src/database/migrations/019_i18n.ts +1 -1
  838. package/src/database/migrations/071_restore_content_bylines_table.ts +43 -0
  839. package/src/database/migrations/072_media_folders.ts +72 -0
  840. package/src/database/migrations/073_media_focal_point.ts +57 -0
  841. package/src/database/migrations/074_content_deleted_scheduled_index.ts +55 -0
  842. package/src/database/migrations/runner.ts +11 -3
  843. package/src/database/repositories/byline.ts +32 -16
  844. package/src/database/repositories/content.ts +119 -51
  845. package/src/database/repositories/media-folders.ts +115 -0
  846. package/src/database/repositories/media-usage-work.ts +395 -111
  847. package/src/database/repositories/media-usage.ts +1104 -47
  848. package/src/database/repositories/media.ts +156 -29
  849. package/src/database/repositories/plugin-storage.ts +74 -9
  850. package/src/database/repositories/types.ts +8 -7
  851. package/src/database/transaction.ts +1 -0
  852. package/src/database/types.ts +13 -0
  853. package/src/db/adapters.ts +10 -3
  854. package/src/db/node-sqlite-compat.ts +78 -0
  855. package/src/db/postgres.ts +23 -0
  856. package/src/db/sqlite.ts +3 -3
  857. package/src/emdash-runtime.ts +186 -251
  858. package/src/fields/boolean.ts +1 -1
  859. package/src/fields/datetime.ts +1 -1
  860. package/src/fields/file.ts +1 -1
  861. package/src/fields/image.ts +7 -1
  862. package/src/fields/integer.ts +1 -1
  863. package/src/fields/json.ts +1 -1
  864. package/src/fields/multiselect.ts +1 -1
  865. package/src/fields/number.ts +1 -1
  866. package/src/fields/portable-text.ts +1 -1
  867. package/src/fields/richtext.ts +1 -1
  868. package/src/fields/select.ts +1 -1
  869. package/src/fields/slug.ts +1 -1
  870. package/src/fields/text.ts +1 -1
  871. package/src/fields/textarea.ts +1 -1
  872. package/src/fields/types.ts +8 -4
  873. package/src/index.ts +30 -3
  874. package/src/loader.ts +63 -10
  875. package/src/mcp/server.ts +228 -24
  876. package/src/media/focal-point.ts +37 -0
  877. package/src/media/image-endpoint.ts +5 -2
  878. package/src/media/local-runtime.ts +8 -0
  879. package/src/media/mime.ts +1 -0
  880. package/src/media/normalize.ts +25 -4
  881. package/src/media/types.ts +10 -0
  882. package/src/media/usage/activation.ts +162 -35
  883. package/src/media/usage/capture-triggers.ts +19 -3
  884. package/src/media/usage/cleanup.ts +9 -8
  885. package/src/media/usage/collection-deletion-processor.ts +7 -3
  886. package/src/media/usage/collection-deletion.ts +10 -0
  887. package/src/media/usage/content-refresh.ts +258 -39
  888. package/src/media/usage/content-snapshots.ts +128 -31
  889. package/src/media/usage/extractor.ts +32 -13
  890. package/src/media/usage/maintenance-engine.ts +166 -0
  891. package/src/media/usage/reconciliation-processor.ts +106 -29
  892. package/src/media/usage/reconciliation.ts +90 -7
  893. package/src/media/usage/work-processor.ts +342 -101
  894. package/src/menus/index.ts +16 -0
  895. package/src/object-cache/index.ts +44 -2
  896. package/src/plugin-types.ts +18 -1
  897. package/src/plugins/hooks.ts +4 -1
  898. package/src/plugins/index.ts +7 -0
  899. package/src/plugins/manager.ts +2 -1
  900. package/src/plugins/manifest-schema.ts +1 -1
  901. package/src/plugins/routes.ts +3 -1
  902. package/src/plugins/sandbox/hook-result.ts +52 -0
  903. package/src/plugins/sandbox/index.ts +10 -0
  904. package/src/plugins/save-rejection.ts +20 -0
  905. package/src/plugins/scheduler/node.ts +1 -13
  906. package/src/plugins/scheduler/types.ts +0 -2
  907. package/src/plugins/state.ts +13 -3
  908. package/src/plugins/types.ts +6 -0
  909. package/src/registry/artifact-checksum.ts +15 -0
  910. package/src/registry/artifact-fetch.ts +530 -0
  911. package/src/registry/artifact-verification.ts +85 -0
  912. package/src/registry/authoritative-records.ts +180 -0
  913. package/src/registry/config.ts +24 -6
  914. package/src/registry/record-labels.ts +28 -0
  915. package/src/registry/types.ts +12 -15
  916. package/src/schema/registry.ts +26 -3
  917. package/src/schema/types.ts +1 -0
  918. package/src/schema/zod-generator.ts +28 -17
  919. package/src/security/ssrf.ts +26 -4
  920. package/src/seed/apply.ts +4 -4
  921. package/src/settings/index.ts +16 -0
  922. package/src/storage/local.ts +1 -0
  923. package/src/storage/s3.ts +2 -0
  924. package/src/storage/types.ts +2 -0
  925. package/src/taxonomies/index.ts +40 -20
  926. package/src/ui.ts +2 -0
  927. package/src/widgets/archives.ts +67 -0
  928. package/src/widgets/index.ts +16 -0
  929. package/dist/api-BeBglVxU.mjs +0 -4695
  930. package/dist/api-BeBglVxU.mjs.map +0 -1
  931. package/dist/byline-yjvWq4ip.mjs.map +0 -1
  932. package/dist/challenge-store-SIL5DsF2.mjs.map +0 -1
  933. package/dist/collection-deletion-DQPvMD8R.mjs.map +0 -1
  934. package/dist/content-ZHCc1ngN.mjs.map +0 -1
  935. package/dist/content-refresh-B_8SJzuU.mjs.map +0 -1
  936. package/dist/context-ZldbZcle.mjs.map +0 -1
  937. package/dist/errors-CLUPm7aD.mjs.map +0 -1
  938. package/dist/index-BVBZj4-7.d.mts.map +0 -1
  939. package/dist/loader-CdG_Ci3H.mjs.map +0 -1
  940. package/dist/manifest-schema-BXbUAHod.mjs.map +0 -1
  941. package/dist/media-BWWWb8kg.mjs.map +0 -1
  942. package/dist/media-CzhAn2--.mjs.map +0 -1
  943. package/dist/media-allowlist-D6x-Us02.mjs.map +0 -1
  944. package/dist/media-usage-BZCydfvu.mjs.map +0 -1
  945. package/dist/media-usage-work-DrCbqBcl.mjs.map +0 -1
  946. package/dist/menus-DSo5QeW0.mjs.map +0 -1
  947. package/dist/mime-DfIVjNkr.mjs.map +0 -1
  948. package/dist/normalize-Bc-s_r-a.mjs.map +0 -1
  949. package/dist/object-cache-71tPfV4A.mjs.map +0 -1
  950. package/dist/options--hhz-jZ1.d.mts.map +0 -1
  951. package/dist/placeholder-Dp0K3RkD.d.mts.map +0 -1
  952. package/dist/redirects-DTDHWH31.mjs.map +0 -1
  953. package/dist/registry-Cqa2I749.mjs.map +0 -1
  954. package/dist/relations-BBApI4e2.mjs.map +0 -1
  955. package/dist/relations-BHo5A8Zf.d.mts.map +0 -1
  956. package/dist/runner-BYHZn3Jy.d.mts.map +0 -1
  957. package/dist/runner-C1T11CfC.mjs.map +0 -1
  958. package/dist/settings-xRdoUZr0.mjs.map +0 -1
  959. package/dist/state-DYwPue40.mjs.map +0 -1
  960. package/dist/taxonomies-BlrncHi9.mjs.map +0 -1
  961. package/dist/taxonomies-OHUIiIpI.mjs.map +0 -1
  962. package/dist/types-BcqdcT-r.d.mts.map +0 -1
  963. package/dist/types-C2pMvO62.d.mts.map +0 -1
  964. package/dist/types-CP1CflWf.mjs +0 -3
  965. package/dist/types-DN64_zzZ.d.mts.map +0 -1
  966. package/dist/types-DQIDRKF2.d.mts.map +0 -1
  967. package/dist/version-DB_fqCSI.mjs +0 -7
  968. package/dist/widgets-BD3ho7Rq.mjs.map +0 -1
  969. package/dist/zod-generator-LC-on_Vb.mjs.map +0 -1
  970. /package/dist/{api-tokens-rIXC6LdE.mjs → api-tokens-BfYts-sq.mjs} +0 -0
  971. /package/dist/{ssrf-DpXgKsna.mjs → ssrf-Dg3cIT-b.mjs} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"device-flow-C0GdD_z8.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\ts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oCWvLJ.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,MA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,KAAK,UAAU,OAAO;GAC9B,aAAa,IAAI;GACjB,YAAY;GACZ,oBAAoB;GACpB,CAAC,CACD,SAAS;AAEX,SAAO;GACN,SAAS;GACT,MAAM;IACL,cAAc,YAAY;IAC1B,eAAe,MAAM;IACrB,YAAY;IACZ,YAAY;IACZ,OAAO,OAAO,KAAK,IAAI;IACvB;GACD;SACM;AACP,SAAO;GACN,SAAS;GACT,OAAO;IACN,MAAM;IACN,SAAS;IACT;GACD;;;;;;;;;;;AAYH,eAAsB,kBACrB,IACA,OAG2C;AAC3C,KAAI;EACH,MAAM,OAAO,aAAa,MAAM,MAAM;EAGtC,MAAM,MAAM,MAAM,GAChB,WAAW,uBAAuB,CAClC,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,6 +1,6 @@
1
- import { i as getExactMigrationStatus, s as runMigrations } from "./runner-C1T11CfC.mjs";
1
+ import { i as getExactMigrationStatus, s as runMigrations } from "./runner-BLIDKpmA.mjs";
2
2
  import { r as getI18nConfig, s as setI18nConfig } from "./config-C3EBstHi.mjs";
3
- import { r as getCoreMigrationIdentity } from "./identity-Ys6Dlc9C.mjs";
3
+ import { r as getCoreMigrationIdentity } from "./identity-DksvEazf.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-CDXeJCSs.mjs.map
85
+ //# sourceMappingURL=direct-executor-Bfa5_ToE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"direct-executor-CDXeJCSs.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,OAAM,IAAI,MACT,4DAA4D,cAAc,eAAe,KAAK,KAAK,GACnG;AAEF,KAAI,cAAc,QAAQ,WAAW,EACpC,QAAO,aAAa,QAAQ,eAAe,EAAE,CAAC;CAG/C,MAAM,SAAS,MA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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,OAAM,IAAI,MACT,4DAA4D,cAAc,eAAe,KAAK,KAAK,GACnG;AAEF,KAAI,cAAc,QAAQ,WAAW,EACpC,QAAO,aAAa,QAAQ,eAAe,EAAE,CAAC;CAG/C,MAAM,SAAS,MAAM,cAAc,GAAG;AAEtC,QAAO,aAAa,QADA,MAAM,wBAAwB,GAAG,EACZ,OAAO,QAAQ;;AAGzD,SAAgB,8BACf,SACoB;CACpB,MAAM,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,QAAQ,CAAC;CACnD,IAAI,OAAO;CACX,IAAI,WAAW;CACf,IAAI;CACJ,IAAI;CAEJ,MAAM,sBAAqC;AAC1C,MAAI,CAAC,SAAU,QAAO,QAAQ,SAAS;AACvC,mBAAiB,SAAS,SAAS;AACnC,SAAO;;AAGR,QAAO;EACN;EACA,MAAM,QAAQ,SAAS;AACtB,OAAI,SACH,OAAM,IAAI,MAAM,wCAAwC;AAEzD,OAAI,KACH,OAAM,IAAI,MAAM,sCAAsC;AAEvD,UAAO;AAEP,OAAI,QAAQ,WAAW,WAAW,QAAQ,WAAW,QACpD,OAAM,IAAI,MAAM,gCAAgC;AAEjD,SAAM,cAAc,QAAQ;GAG5B,MAAM,KAAK,IAAI,OAAiB,EAAE,SADlB,MAAM,QAAQ,eAAe,EACF,CAAC;AAC5C,cAAW;AACX,OAAI,UAAU;AACb,UAAM,eAAe;AACrB,UAAM,IAAI,MAAM,wCAAwC;;GAEzD,MAAM,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"}
@@ -807,4 +807,4 @@ function imageSize(input) {
807
807
 
808
808
  //#endregion
809
809
  export { imageSize as t };
810
- //# sourceMappingURL=dist-D_6CKR8z.mjs.map
810
+ //# sourceMappingURL=dist-89xCrGqi.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dist-D_6CKR8z.mjs","names":[],"sources":["../../../node_modules/.pnpm/image-size@2.0.2_patch_hash=77c12533e3a635c4066c55da8952f4912e8210416539dc1249550fa639271595/node_modules/image-size/dist/index.mjs"],"sourcesContent":["// lib/types/utils.ts\nvar decoder = new TextDecoder();\nvar toUTF8String = (input, start = 0, end = input.length) => decoder.decode(input.slice(start, end));\nvar toHexString = (input, start = 0, end = input.length) => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), \"\");\nvar getView = (input, offset) => new DataView(input.buffer, input.byteOffset + offset);\nvar readInt16LE = (input, offset = 0) => getView(input, offset).getInt16(0, true);\nvar readUInt16BE = (input, offset = 0) => getView(input, offset).getUint16(0, false);\nvar readUInt16LE = (input, offset = 0) => getView(input, offset).getUint16(0, true);\nvar readUInt24LE = (input, offset = 0) => {\n const view = getView(input, offset);\n return view.getUint16(0, true) + (view.getUint8(2) << 16);\n};\nvar readInt32LE = (input, offset = 0) => getView(input, offset).getInt32(0, true);\nvar readUInt32BE = (input, offset = 0) => getView(input, offset).getUint32(0, false);\nvar readUInt32LE = (input, offset = 0) => getView(input, offset).getUint32(0, true);\nvar readUInt64 = (input, offset, isBigEndian) => getView(input, offset).getBigUint64(0, !isBigEndian);\nvar methods = {\n readUInt16BE,\n readUInt16LE,\n readUInt32BE,\n readUInt32LE\n};\nfunction readUInt(input, bits, offset = 0, isBigEndian = false) {\n const endian = isBigEndian ? \"BE\" : \"LE\";\n const methodName = `readUInt${bits}${endian}`;\n return methods[methodName](input, offset);\n}\nfunction readBox(input, offset) {\n if (input.length - offset < 4) return;\n const boxSize = readUInt32BE(input, offset);\n if (input.length - offset < boxSize) return;\n return {\n name: toUTF8String(input, 4 + offset, 8 + offset),\n offset,\n size: boxSize\n };\n}\nfunction findBox(input, boxName, currentOffset) {\n while (currentOffset < input.length) {\n const box = readBox(input, currentOffset);\n if (!box) break;\n if (box.name === boxName) return box;\n currentOffset += box.size > 0 ? box.size : 8;\n }\n}\n\n// lib/types/bmp.ts\nvar BMP = {\n validate: (input) => toUTF8String(input, 0, 2) === \"BM\",\n calculate: (input) => ({\n height: Math.abs(readInt32LE(input, 22)),\n width: readUInt32LE(input, 18)\n })\n};\n\n// lib/types/ico.ts\nvar TYPE_ICON = 1;\nvar SIZE_HEADER = 2 + 2 + 2;\nvar SIZE_IMAGE_ENTRY = 1 + 1 + 1 + 1 + 2 + 2 + 4 + 4;\nfunction getSizeFromOffset(input, offset) {\n const value = input[offset];\n return value === 0 ? 256 : value;\n}\nfunction getImageSize(input, imageIndex) {\n const offset = SIZE_HEADER + imageIndex * SIZE_IMAGE_ENTRY;\n return {\n height: getSizeFromOffset(input, offset + 1),\n width: getSizeFromOffset(input, offset)\n };\n}\nvar ICO = {\n validate(input) {\n const reserved = readUInt16LE(input, 0);\n const imageCount = readUInt16LE(input, 4);\n if (reserved !== 0 || imageCount === 0) return false;\n const imageType = readUInt16LE(input, 2);\n return imageType === TYPE_ICON;\n },\n calculate(input) {\n const nbImages = readUInt16LE(input, 4);\n const imageSize2 = getImageSize(input, 0);\n if (nbImages === 1) return imageSize2;\n const images = [];\n for (let imageIndex = 0; imageIndex < nbImages; imageIndex += 1) {\n images.push(getImageSize(input, imageIndex));\n }\n return {\n width: imageSize2.width,\n height: imageSize2.height,\n images\n };\n }\n};\n\n// lib/types/cur.ts\nvar TYPE_CURSOR = 2;\nvar CUR = {\n validate(input) {\n const reserved = readUInt16LE(input, 0);\n const imageCount = readUInt16LE(input, 4);\n if (reserved !== 0 || imageCount === 0) return false;\n const imageType = readUInt16LE(input, 2);\n return imageType === TYPE_CURSOR;\n },\n calculate: (input) => ICO.calculate(input)\n};\n\n// lib/types/dds.ts\nvar DDS = {\n validate: (input) => readUInt32LE(input, 0) === 542327876,\n calculate: (input) => ({\n height: readUInt32LE(input, 12),\n width: readUInt32LE(input, 16)\n })\n};\n\n// lib/types/gif.ts\nvar gifRegexp = /^GIF8[79]a/;\nvar GIF = {\n validate: (input) => gifRegexp.test(toUTF8String(input, 0, 6)),\n calculate: (input) => ({\n height: readUInt16LE(input, 8),\n width: readUInt16LE(input, 6)\n })\n};\n\n// lib/types/heif.ts\nvar brandMap = {\n avif: \"avif\",\n mif1: \"heif\",\n msf1: \"heif\",\n // heif-sequence\n heic: \"heic\",\n heix: \"heic\",\n hevc: \"heic\",\n // heic-sequence\n hevx: \"heic\"\n // heic-sequence\n};\nvar HEIF = {\n validate(input) {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"ftyp\") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand in brandMap;\n },\n calculate(input) {\n const metaBox = findBox(input, \"meta\", 0);\n const iprpBox = metaBox && findBox(input, \"iprp\", metaBox.offset + 12);\n const ipcoBox = iprpBox && findBox(input, \"ipco\", iprpBox.offset + 8);\n if (!ipcoBox) {\n throw new TypeError(\"Invalid HEIF, no ipco box found\");\n }\n const type = toUTF8String(input, 8, 12);\n const images = [];\n let currentOffset = ipcoBox.offset + 8;\n while (currentOffset < ipcoBox.offset + ipcoBox.size) {\n const ispeBox = findBox(input, \"ispe\", currentOffset);\n if (!ispeBox) break;\n const rawWidth = readUInt32BE(input, ispeBox.offset + 12);\n const rawHeight = readUInt32BE(input, ispeBox.offset + 16);\n const clapBox = findBox(input, \"clap\", currentOffset);\n let width = rawWidth;\n let height = rawHeight;\n if (clapBox && clapBox.offset < ipcoBox.offset + ipcoBox.size) {\n const cropRight = readUInt32BE(input, clapBox.offset + 12);\n width = rawWidth - cropRight;\n }\n images.push({ height, width });\n currentOffset = ispeBox.offset + (ispeBox.size > 0 ? ispeBox.size : 8);\n }\n if (images.length === 0) {\n throw new TypeError(\"Invalid HEIF, no sizes found\");\n }\n return {\n width: images[0].width,\n height: images[0].height,\n type,\n ...images.length > 1 ? { images } : {}\n };\n }\n};\n\n// lib/types/icns.ts\nvar SIZE_HEADER2 = 4 + 4;\nvar FILE_LENGTH_OFFSET = 4;\nvar ENTRY_LENGTH_OFFSET = 4;\nvar ICON_TYPE_SIZE = {\n ICON: 32,\n \"ICN#\": 32,\n // m => 16 x 16\n \"icm#\": 16,\n icm4: 16,\n icm8: 16,\n // s => 16 x 16\n \"ics#\": 16,\n ics4: 16,\n ics8: 16,\n is32: 16,\n s8mk: 16,\n icp4: 16,\n // l => 32 x 32\n icl4: 32,\n icl8: 32,\n il32: 32,\n l8mk: 32,\n icp5: 32,\n ic11: 32,\n // h => 48 x 48\n ich4: 48,\n ich8: 48,\n ih32: 48,\n h8mk: 48,\n // . => 64 x 64\n icp6: 64,\n ic12: 32,\n // t => 128 x 128\n it32: 128,\n t8mk: 128,\n ic07: 128,\n // . => 256 x 256\n ic08: 256,\n ic13: 256,\n // . => 512 x 512\n ic09: 512,\n ic14: 512,\n // . => 1024 x 1024\n ic10: 1024\n};\nfunction readImageHeader(input, imageOffset) {\n const imageLengthOffset = imageOffset + ENTRY_LENGTH_OFFSET;\n return [\n toUTF8String(input, imageOffset, imageLengthOffset),\n readUInt32BE(input, imageLengthOffset)\n ];\n}\nfunction getImageSize2(type) {\n const size = ICON_TYPE_SIZE[type];\n return { width: size, height: size, type };\n}\nvar ICNS = {\n validate: (input) => toUTF8String(input, 0, 4) === \"icns\",\n calculate(input) {\n const inputLength = input.length;\n const fileLength = readUInt32BE(input, FILE_LENGTH_OFFSET);\n let imageOffset = SIZE_HEADER2;\n const images = [];\n while (imageOffset < fileLength && imageOffset < inputLength) {\n const imageHeader = readImageHeader(input, imageOffset);\n const imageSize2 = getImageSize2(imageHeader[0]);\n images.push(imageSize2);\n imageOffset += imageHeader[1] > 0 ? imageHeader[1] : 8;\n }\n if (images.length === 0) {\n throw new TypeError(\"Invalid ICNS, no sizes found\");\n }\n return {\n width: images[0].width,\n height: images[0].height,\n ...images.length > 1 ? { images } : {}\n };\n }\n};\n\n// lib/types/j2c.ts\nvar J2C = {\n // TODO: this doesn't seem right. SIZ marker doesn't have to be right after the SOC\n validate: (input) => readUInt32BE(input, 0) === 4283432785,\n calculate: (input) => ({\n height: readUInt32BE(input, 12),\n width: readUInt32BE(input, 8)\n })\n};\n\n// lib/types/jp2.ts\nvar JP2 = {\n validate(input) {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"jP \") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand === \"jp2 \";\n },\n calculate(input) {\n const jp2hBox = findBox(input, \"jp2h\", 0);\n const ihdrBox = jp2hBox && findBox(input, \"ihdr\", jp2hBox.offset + 8);\n if (ihdrBox) {\n return {\n height: readUInt32BE(input, ihdrBox.offset + 8),\n width: readUInt32BE(input, ihdrBox.offset + 12)\n };\n }\n throw new TypeError(\"Unsupported JPEG 2000 format\");\n }\n};\n\n// lib/types/jpg.ts\nvar EXIF_MARKER = \"45786966\";\nvar APP1_DATA_SIZE_BYTES = 2;\nvar EXIF_HEADER_BYTES = 6;\nvar TIFF_BYTE_ALIGN_BYTES = 2;\nvar BIG_ENDIAN_BYTE_ALIGN = \"4d4d\";\nvar LITTLE_ENDIAN_BYTE_ALIGN = \"4949\";\nvar IDF_ENTRY_BYTES = 12;\nvar NUM_DIRECTORY_ENTRIES_BYTES = 2;\nfunction isEXIF(input) {\n return toHexString(input, 2, 6) === EXIF_MARKER;\n}\nfunction extractSize(input, index) {\n return {\n height: readUInt16BE(input, index),\n width: readUInt16BE(input, index + 2)\n };\n}\nfunction extractOrientation(exifBlock, isBigEndian) {\n const idfOffset = 8;\n const offset = EXIF_HEADER_BYTES + idfOffset;\n const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian);\n for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) {\n const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES;\n const end = start + IDF_ENTRY_BYTES;\n if (start > exifBlock.length) {\n return;\n }\n const block = exifBlock.slice(start, end);\n const tagNumber = readUInt(block, 16, 0, isBigEndian);\n if (tagNumber === 274) {\n const dataFormat = readUInt(block, 16, 2, isBigEndian);\n if (dataFormat !== 3) {\n return;\n }\n const numberOfComponents = readUInt(block, 32, 4, isBigEndian);\n if (numberOfComponents !== 1) {\n return;\n }\n return readUInt(block, 16, 8, isBigEndian);\n }\n }\n}\nfunction validateExifBlock(input, index) {\n const exifBlock = input.slice(APP1_DATA_SIZE_BYTES, index);\n const byteAlign = toHexString(\n exifBlock,\n EXIF_HEADER_BYTES,\n EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES\n );\n const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN;\n const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN;\n if (isBigEndian || isLittleEndian) {\n return extractOrientation(exifBlock, isBigEndian);\n }\n}\nfunction validateInput(input, index) {\n if (index > input.length) {\n throw new TypeError(\"Corrupt JPG, exceeded buffer limits\");\n }\n}\nvar JPG = {\n validate: (input) => toHexString(input, 0, 2) === \"ffd8\",\n calculate(_input) {\n let input = _input.slice(4);\n let orientation;\n let next;\n while (input.length) {\n const i = readUInt16BE(input, 0);\n validateInput(input, i);\n if (input[i] !== 255) {\n input = input.slice(1);\n continue;\n }\n if (isEXIF(input)) {\n orientation = validateExifBlock(input, i);\n }\n next = input[i + 1];\n if (next === 192 || next === 193 || next === 194) {\n const size = extractSize(input, i + 5);\n if (!orientation) {\n return size;\n }\n return {\n height: size.height,\n orientation,\n width: size.width\n };\n }\n input = input.slice(i + 2);\n }\n throw new TypeError(\"Invalid JPG, no size found\");\n }\n};\n\n// lib/utils/bit-reader.ts\nvar BitReader = class {\n constructor(input, endianness) {\n this.input = input;\n this.endianness = endianness;\n // Skip the first 16 bits (2 bytes) of signature\n this.byteOffset = 2;\n this.bitOffset = 0;\n }\n /** Reads a specified number of bits, and move the offset */\n getBits(length = 1) {\n let result = 0;\n let bitsRead = 0;\n while (bitsRead < length) {\n if (this.byteOffset >= this.input.length) {\n throw new Error(\"Reached end of input\");\n }\n const currentByte = this.input[this.byteOffset];\n const bitsLeft = 8 - this.bitOffset;\n const bitsToRead = Math.min(length - bitsRead, bitsLeft);\n if (this.endianness === \"little-endian\") {\n const mask = (1 << bitsToRead) - 1;\n const bits = currentByte >> this.bitOffset & mask;\n result |= bits << bitsRead;\n } else {\n const mask = (1 << bitsToRead) - 1 << 8 - this.bitOffset - bitsToRead;\n const bits = (currentByte & mask) >> 8 - this.bitOffset - bitsToRead;\n result = result << bitsToRead | bits;\n }\n bitsRead += bitsToRead;\n this.bitOffset += bitsToRead;\n if (this.bitOffset === 8) {\n this.byteOffset++;\n this.bitOffset = 0;\n }\n }\n return result;\n }\n};\n\n// lib/types/jxl-stream.ts\nfunction calculateImageDimension(reader, isSmallImage) {\n if (isSmallImage) {\n return 8 * (1 + reader.getBits(5));\n }\n const sizeClass = reader.getBits(2);\n const extraBits = [9, 13, 18, 30][sizeClass];\n return 1 + reader.getBits(extraBits);\n}\nfunction calculateImageWidth(reader, isSmallImage, widthMode, height) {\n if (isSmallImage && widthMode === 0) {\n return 8 * (1 + reader.getBits(5));\n }\n if (widthMode === 0) {\n return calculateImageDimension(reader, false);\n }\n const aspectRatios = [1, 1.2, 4 / 3, 1.5, 16 / 9, 5 / 4, 2];\n return Math.floor(height * aspectRatios[widthMode - 1]);\n}\nvar JXLStream = {\n validate: (input) => {\n return toHexString(input, 0, 2) === \"ff0a\";\n },\n calculate(input) {\n const reader = new BitReader(input, \"little-endian\");\n const isSmallImage = reader.getBits(1) === 1;\n const height = calculateImageDimension(reader, isSmallImage);\n const widthMode = reader.getBits(3);\n const width = calculateImageWidth(reader, isSmallImage, widthMode, height);\n return { width, height };\n }\n};\n\n// lib/types/jxl.ts\nfunction extractCodestream(input) {\n const jxlcBox = findBox(input, \"jxlc\", 0);\n if (jxlcBox) {\n return input.slice(jxlcBox.offset + 8, jxlcBox.offset + jxlcBox.size);\n }\n const partialStreams = extractPartialStreams(input);\n if (partialStreams.length > 0) {\n return concatenateCodestreams(partialStreams);\n }\n return void 0;\n}\nfunction extractPartialStreams(input) {\n const partialStreams = [];\n let offset = 0;\n while (offset < input.length) {\n const jxlpBox = findBox(input, \"jxlp\", offset);\n if (!jxlpBox) break;\n partialStreams.push(\n input.slice(jxlpBox.offset + 12, jxlpBox.offset + jxlpBox.size)\n );\n offset = jxlpBox.offset + (jxlpBox.size > 0 ? jxlpBox.size : 8);\n }\n return partialStreams;\n}\nfunction concatenateCodestreams(partialCodestreams) {\n const totalLength = partialCodestreams.reduce(\n (acc, curr) => acc + curr.length,\n 0\n );\n const codestream = new Uint8Array(totalLength);\n let position = 0;\n for (const partial of partialCodestreams) {\n codestream.set(partial, position);\n position += partial.length;\n }\n return codestream;\n}\nvar JXL = {\n validate: (input) => {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"JXL \") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand === \"jxl \";\n },\n calculate(input) {\n const codestream = extractCodestream(input);\n if (codestream) return JXLStream.calculate(codestream);\n throw new Error(\"No codestream found in JXL container\");\n }\n};\n\n// lib/types/ktx.ts\nvar KTX = {\n validate: (input) => {\n const signature = toUTF8String(input, 1, 7);\n return [\"KTX 11\", \"KTX 20\"].includes(signature);\n },\n calculate: (input) => {\n const type = input[5] === 49 ? \"ktx\" : \"ktx2\";\n const offset = type === \"ktx\" ? 36 : 20;\n return {\n height: readUInt32LE(input, offset + 4),\n width: readUInt32LE(input, offset),\n type\n };\n }\n};\n\n// lib/types/png.ts\nvar pngSignature = \"PNG\\r\\n\u001a\\n\";\nvar pngImageHeaderChunkName = \"IHDR\";\nvar pngFriedChunkName = \"CgBI\";\nvar PNG = {\n validate(input) {\n if (pngSignature === toUTF8String(input, 1, 8)) {\n let chunkName = toUTF8String(input, 12, 16);\n if (chunkName === pngFriedChunkName) {\n chunkName = toUTF8String(input, 28, 32);\n }\n if (chunkName !== pngImageHeaderChunkName) {\n throw new TypeError(\"Invalid PNG\");\n }\n return true;\n }\n return false;\n },\n calculate(input) {\n if (toUTF8String(input, 12, 16) === pngFriedChunkName) {\n return {\n height: readUInt32BE(input, 36),\n width: readUInt32BE(input, 32)\n };\n }\n return {\n height: readUInt32BE(input, 20),\n width: readUInt32BE(input, 16)\n };\n }\n};\n\n// lib/types/pnm.ts\nvar PNMTypes = {\n P1: \"pbm/ascii\",\n P2: \"pgm/ascii\",\n P3: \"ppm/ascii\",\n P4: \"pbm\",\n P5: \"pgm\",\n P6: \"ppm\",\n P7: \"pam\",\n PF: \"pfm\"\n};\nvar handlers = {\n default: (lines) => {\n let dimensions = [];\n while (lines.length > 0) {\n const line = lines.shift();\n if (line[0] === \"#\") {\n continue;\n }\n dimensions = line.split(\" \");\n break;\n }\n if (dimensions.length === 2) {\n return {\n height: Number.parseInt(dimensions[1], 10),\n width: Number.parseInt(dimensions[0], 10)\n };\n }\n throw new TypeError(\"Invalid PNM\");\n },\n pam: (lines) => {\n const size = {};\n while (lines.length > 0) {\n const line = lines.shift();\n if (line.length > 16 || line.charCodeAt(0) > 128) {\n continue;\n }\n const [key, value] = line.split(\" \");\n if (key && value) {\n size[key.toLowerCase()] = Number.parseInt(value, 10);\n }\n if (size.height && size.width) {\n break;\n }\n }\n if (size.height && size.width) {\n return {\n height: size.height,\n width: size.width\n };\n }\n throw new TypeError(\"Invalid PAM\");\n }\n};\nvar PNM = {\n validate: (input) => toUTF8String(input, 0, 2) in PNMTypes,\n calculate(input) {\n const signature = toUTF8String(input, 0, 2);\n const type = PNMTypes[signature];\n const lines = toUTF8String(input, 3).split(/[\\r\\n]+/);\n const handler = handlers[type] || handlers.default;\n return handler(lines);\n }\n};\n\n// lib/types/psd.ts\nvar PSD = {\n validate: (input) => toUTF8String(input, 0, 4) === \"8BPS\",\n calculate: (input) => ({\n height: readUInt32BE(input, 14),\n width: readUInt32BE(input, 18)\n })\n};\n\n// lib/types/svg.ts\nvar svgReg = /<svg\\s([^>\"']|\"[^\"]*\"|'[^']*')*>/;\nvar extractorRegExps = {\n height: /\\sheight=(['\"])([^%]+?)\\1/,\n root: svgReg,\n viewbox: /\\sviewBox=(['\"])(.+?)\\1/i,\n width: /\\swidth=(['\"])([^%]+?)\\1/\n};\nvar INCH_CM = 2.54;\nvar units = {\n in: 96,\n cm: 96 / INCH_CM,\n em: 16,\n ex: 8,\n m: 96 / INCH_CM * 100,\n mm: 96 / INCH_CM / 10,\n pc: 96 / 72 / 12,\n pt: 96 / 72,\n px: 1\n};\nvar unitsReg = new RegExp(\n `^([0-9.]+(?:e\\\\d+)?)(${Object.keys(units).join(\"|\")})?$`\n);\nfunction parseLength(len) {\n const m = unitsReg.exec(len);\n if (!m) {\n return void 0;\n }\n return Math.round(Number(m[1]) * (units[m[2]] || 1));\n}\nfunction parseViewbox(viewbox) {\n const bounds = viewbox.split(\" \");\n return {\n height: parseLength(bounds[3]),\n width: parseLength(bounds[2])\n };\n}\nfunction parseAttributes(root) {\n const width = root.match(extractorRegExps.width);\n const height = root.match(extractorRegExps.height);\n const viewbox = root.match(extractorRegExps.viewbox);\n return {\n height: height && parseLength(height[2]),\n viewbox: viewbox && parseViewbox(viewbox[2]),\n width: width && parseLength(width[2])\n };\n}\nfunction calculateByDimensions(attrs) {\n return {\n height: attrs.height,\n width: attrs.width\n };\n}\nfunction calculateByViewbox(attrs, viewbox) {\n const ratio = viewbox.width / viewbox.height;\n if (attrs.width) {\n return {\n height: Math.floor(attrs.width / ratio),\n width: attrs.width\n };\n }\n if (attrs.height) {\n return {\n height: attrs.height,\n width: Math.floor(attrs.height * ratio)\n };\n }\n return {\n height: viewbox.height,\n width: viewbox.width\n };\n}\nvar SVG = {\n // Scan only the first kilo-byte to speed up the check on larger files\n validate: (input) => svgReg.test(toUTF8String(input, 0, 1e3)),\n calculate(input) {\n const root = toUTF8String(input).match(extractorRegExps.root);\n if (root) {\n const attrs = parseAttributes(root[0]);\n if (attrs.width && attrs.height) {\n return calculateByDimensions(attrs);\n }\n if (attrs.viewbox) {\n return calculateByViewbox(attrs, attrs.viewbox);\n }\n }\n throw new TypeError(\"Invalid SVG\");\n }\n};\n\n// lib/types/tga.ts\nvar TGA = {\n validate(input) {\n return readUInt16LE(input, 0) === 0 && readUInt16LE(input, 4) === 0;\n },\n calculate(input) {\n return {\n height: readUInt16LE(input, 14),\n width: readUInt16LE(input, 12)\n };\n }\n};\n\n// lib/types/tiff.ts\nvar CONSTANTS = {\n TAG: {\n WIDTH: 256,\n HEIGHT: 257,\n COMPRESSION: 259\n },\n TYPE: {\n SHORT: 3,\n LONG: 4,\n LONG8: 16\n },\n ENTRY_SIZE: {\n STANDARD: 12,\n BIG: 20\n },\n COUNT_SIZE: {\n STANDARD: 2,\n BIG: 8\n }\n};\nfunction readIFD(input, { isBigEndian, isBigTiff }) {\n const ifdOffset = isBigTiff ? Number(readUInt64(input, 8, isBigEndian)) : readUInt(input, 32, 4, isBigEndian);\n const entryCountSize = isBigTiff ? CONSTANTS.COUNT_SIZE.BIG : CONSTANTS.COUNT_SIZE.STANDARD;\n return input.slice(ifdOffset + entryCountSize);\n}\nfunction readTagValue(input, type, offset, isBigEndian) {\n switch (type) {\n case CONSTANTS.TYPE.SHORT:\n return readUInt(input, 16, offset, isBigEndian);\n case CONSTANTS.TYPE.LONG:\n return readUInt(input, 32, offset, isBigEndian);\n case CONSTANTS.TYPE.LONG8: {\n const value = Number(readUInt64(input, offset, isBigEndian));\n if (value > Number.MAX_SAFE_INTEGER) {\n throw new TypeError(\"Value too large\");\n }\n return value;\n }\n default:\n return 0;\n }\n}\nfunction nextTag(input, isBigTiff) {\n const entrySize = isBigTiff ? CONSTANTS.ENTRY_SIZE.BIG : CONSTANTS.ENTRY_SIZE.STANDARD;\n if (input.length > entrySize) {\n return input.slice(entrySize);\n }\n}\nfunction extractTags(input, { isBigEndian, isBigTiff }) {\n const tags = {};\n let temp = input;\n while (temp?.length) {\n const code = readUInt(temp, 16, 0, isBigEndian);\n const type = readUInt(temp, 16, 2, isBigEndian);\n const length = isBigTiff ? Number(readUInt64(temp, 4, isBigEndian)) : readUInt(temp, 32, 4, isBigEndian);\n if (code === 0) break;\n if (length === 1 && (type === CONSTANTS.TYPE.SHORT || type === CONSTANTS.TYPE.LONG || isBigTiff && type === CONSTANTS.TYPE.LONG8)) {\n const valueOffset = isBigTiff ? 12 : 8;\n tags[code] = readTagValue(temp, type, valueOffset, isBigEndian);\n }\n temp = nextTag(temp, isBigTiff);\n }\n return tags;\n}\nfunction determineFormat(input) {\n const signature = toUTF8String(input, 0, 2);\n const version = readUInt(input, 16, 2, signature === \"MM\");\n return {\n isBigEndian: signature === \"MM\",\n isBigTiff: version === 43\n };\n}\nfunction validateBigTIFFHeader(input, isBigEndian) {\n const byteSize = readUInt(input, 16, 4, isBigEndian);\n const reserved = readUInt(input, 16, 6, isBigEndian);\n if (byteSize !== 8 || reserved !== 0) {\n throw new TypeError(\"Invalid BigTIFF header\");\n }\n}\nvar signatures = /* @__PURE__ */ new Set([\n \"49492a00\",\n // Little Endian\n \"4d4d002a\",\n // Big Endian\n \"49492b00\",\n // BigTIFF Little Endian\n \"4d4d002b\"\n // BigTIFF Big Endian\n]);\nvar TIFF = {\n validate: (input) => {\n const signature = toHexString(input, 0, 4);\n return signatures.has(signature);\n },\n calculate(input) {\n const format = determineFormat(input);\n if (format.isBigTiff) {\n validateBigTIFFHeader(input, format.isBigEndian);\n }\n const ifdBuffer = readIFD(input, format);\n const tags = extractTags(ifdBuffer, format);\n const info = {\n height: tags[CONSTANTS.TAG.HEIGHT],\n width: tags[CONSTANTS.TAG.WIDTH],\n type: format.isBigTiff ? \"bigtiff\" : \"tiff\"\n };\n if (tags[CONSTANTS.TAG.COMPRESSION]) {\n info.compression = tags[CONSTANTS.TAG.COMPRESSION];\n }\n if (!info.width || !info.height) {\n throw new TypeError(\"Invalid Tiff. Missing tags\");\n }\n return info;\n }\n};\n\n// lib/types/webp.ts\nfunction calculateExtended(input) {\n return {\n height: 1 + readUInt24LE(input, 7),\n width: 1 + readUInt24LE(input, 4)\n };\n}\nfunction calculateLossless(input) {\n return {\n height: 1 + ((input[4] & 15) << 10 | input[3] << 2 | (input[2] & 192) >> 6),\n width: 1 + ((input[2] & 63) << 8 | input[1])\n };\n}\nfunction calculateLossy(input) {\n return {\n height: readInt16LE(input, 8) & 16383,\n width: readInt16LE(input, 6) & 16383\n };\n}\nvar WEBP = {\n validate(input) {\n const riffHeader = \"RIFF\" === toUTF8String(input, 0, 4);\n const webpHeader = \"WEBP\" === toUTF8String(input, 8, 12);\n const vp8Header = \"VP8\" === toUTF8String(input, 12, 15);\n return riffHeader && webpHeader && vp8Header;\n },\n calculate(_input) {\n const chunkHeader = toUTF8String(_input, 12, 16);\n const input = _input.slice(20, 30);\n if (chunkHeader === \"VP8X\") {\n const extendedHeader = input[0];\n const validStart = (extendedHeader & 192) === 0;\n const validEnd = (extendedHeader & 1) === 0;\n if (validStart && validEnd) {\n return calculateExtended(input);\n }\n throw new TypeError(\"Invalid WebP\");\n }\n if (chunkHeader === \"VP8 \" && input[0] !== 47) {\n return calculateLossy(input);\n }\n const signature = toHexString(input, 3, 6);\n if (chunkHeader === \"VP8L\" && signature !== \"9d012a\") {\n return calculateLossless(input);\n }\n throw new TypeError(\"Invalid WebP\");\n }\n};\n\n// lib/types/index.ts\nvar typeHandlers = /* @__PURE__ */ new Map([\n [\"bmp\", BMP],\n [\"cur\", CUR],\n [\"dds\", DDS],\n [\"gif\", GIF],\n [\"heif\", HEIF],\n [\"icns\", ICNS],\n [\"ico\", ICO],\n [\"j2c\", J2C],\n [\"jp2\", JP2],\n [\"jpg\", JPG],\n [\"jxl\", JXL],\n [\"jxl-stream\", JXLStream],\n [\"ktx\", KTX],\n [\"png\", PNG],\n [\"pnm\", PNM],\n [\"psd\", PSD],\n [\"svg\", SVG],\n [\"tga\", TGA],\n [\"tiff\", TIFF],\n [\"webp\", WEBP]\n]);\nvar types = Array.from(typeHandlers.keys());\n\n// lib/detector.ts\nvar firstBytes = /* @__PURE__ */ new Map([\n [0, \"heif\"],\n [56, \"psd\"],\n [66, \"bmp\"],\n [68, \"dds\"],\n [71, \"gif\"],\n [73, \"tiff\"],\n [77, \"tiff\"],\n [82, \"webp\"],\n [105, \"icns\"],\n [137, \"png\"],\n [255, \"jpg\"]\n]);\nfunction detector(input) {\n const byte = input[0];\n const type = firstBytes.get(byte);\n if (type && typeHandlers.get(type).validate(input)) {\n return type;\n }\n return types.find((type2) => typeHandlers.get(type2).validate(input));\n}\n\n// lib/lookup.ts\nvar globalOptions = {\n disabledTypes: []\n};\nfunction imageSize(input) {\n const type = detector(input);\n if (typeof type !== \"undefined\") {\n if (globalOptions.disabledTypes.indexOf(type) > -1) {\n throw new TypeError(`disabled file type: ${type}`);\n }\n const size = typeHandlers.get(type).calculate(input);\n if (size !== void 0) {\n size.type = size.type ?? type;\n if (size.images && size.images.length > 1) {\n const largestImage = size.images.reduce((largest, current) => {\n return current.width * current.height > largest.width * largest.height ? current : largest;\n }, size.images[0]);\n size.width = largestImage.width;\n size.height = largestImage.height;\n }\n return size;\n }\n }\n throw new TypeError(`unsupported file type: ${type}`);\n}\nvar disableTypes = (types2) => {\n globalOptions.disabledTypes = types2;\n};\n\nexport { imageSize as default, disableTypes, imageSize, types };\n"],"x_google_ignoreList":[0],"mappings":";AACA,IAAI,UAAU,IAAI,aAAa;AAC/B,IAAI,gBAAgB,OAAO,QAAQ,GAAG,MAAM,MAAM,WAAW,QAAQ,OAAO,MAAM,MAAM,OAAO,IAAI,CAAC;AACpG,IAAI,eAAe,OAAO,QAAQ,GAAG,MAAM,MAAM,WAAW,MAAM,MAAM,OAAO,IAAI,CAAC,QAAQ,MAAM,MAAM,OAAO,IAAI,EAAE,SAAS,GAAG,GAAG,MAAM,GAAG,EAAE,GAAG;AAClJ,IAAI,WAAW,OAAO,WAAW,IAAI,SAAS,MAAM,QAAQ,MAAM,aAAa,OAAO;AACtF,IAAI,eAAe,OAAO,SAAS,MAAM,QAAQ,OAAO,OAAO,CAAC,SAAS,GAAG,KAAK;AACjF,IAAI,gBAAgB,OAAO,SAAS,MAAM,QAAQ,OAAO,OAAO,CAAC,UAAU,GAAG,MAAM;AACpF,IAAI,gBAAgB,OAAO,SAAS,MAAM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YAAO,QAAQ,QAAQ,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,SAAS,UAAU;OAClF,KAAK,OAAO,GAAG;AAClB,SAAK,QAAQ,aAAa;AAC1B,SAAK,SAAS,aAAa;;AAE7B,UAAO;;;AAGX,OAAM,IAAI,UAAU,0BAA0B,OAAO"}
1
+ {"version":3,"file":"dist-89xCrGqi.mjs","names":[],"sources":["../../../node_modules/.pnpm/image-size@2.0.2_patch_hash=77c12533e3a635c4066c55da8952f4912e8210416539dc1249550fa639271595/node_modules/image-size/dist/index.mjs"],"sourcesContent":["// lib/types/utils.ts\nvar decoder = new TextDecoder();\nvar toUTF8String = (input, start = 0, end = input.length) => decoder.decode(input.slice(start, end));\nvar toHexString = (input, start = 0, end = input.length) => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), \"\");\nvar getView = (input, offset) => new DataView(input.buffer, input.byteOffset + offset);\nvar readInt16LE = (input, offset = 0) => getView(input, offset).getInt16(0, true);\nvar readUInt16BE = (input, offset = 0) => getView(input, offset).getUint16(0, false);\nvar readUInt16LE = (input, offset = 0) => getView(input, offset).getUint16(0, true);\nvar readUInt24LE = (input, offset = 0) => {\n const view = getView(input, offset);\n return view.getUint16(0, true) + (view.getUint8(2) << 16);\n};\nvar readInt32LE = (input, offset = 0) => getView(input, offset).getInt32(0, true);\nvar readUInt32BE = (input, offset = 0) => getView(input, offset).getUint32(0, false);\nvar readUInt32LE = (input, offset = 0) => getView(input, offset).getUint32(0, true);\nvar readUInt64 = (input, offset, isBigEndian) => getView(input, offset).getBigUint64(0, !isBigEndian);\nvar methods = {\n readUInt16BE,\n readUInt16LE,\n readUInt32BE,\n readUInt32LE\n};\nfunction readUInt(input, bits, offset = 0, isBigEndian = false) {\n const endian = isBigEndian ? \"BE\" : \"LE\";\n const methodName = `readUInt${bits}${endian}`;\n return methods[methodName](input, offset);\n}\nfunction readBox(input, offset) {\n if (input.length - offset < 4) return;\n const boxSize = readUInt32BE(input, offset);\n if (input.length - offset < boxSize) return;\n return {\n name: toUTF8String(input, 4 + offset, 8 + offset),\n offset,\n size: boxSize\n };\n}\nfunction findBox(input, boxName, currentOffset) {\n while (currentOffset < input.length) {\n const box = readBox(input, currentOffset);\n if (!box) break;\n if (box.name === boxName) return box;\n currentOffset += box.size > 0 ? box.size : 8;\n }\n}\n\n// lib/types/bmp.ts\nvar BMP = {\n validate: (input) => toUTF8String(input, 0, 2) === \"BM\",\n calculate: (input) => ({\n height: Math.abs(readInt32LE(input, 22)),\n width: readUInt32LE(input, 18)\n })\n};\n\n// lib/types/ico.ts\nvar TYPE_ICON = 1;\nvar SIZE_HEADER = 2 + 2 + 2;\nvar SIZE_IMAGE_ENTRY = 1 + 1 + 1 + 1 + 2 + 2 + 4 + 4;\nfunction getSizeFromOffset(input, offset) {\n const value = input[offset];\n return value === 0 ? 256 : value;\n}\nfunction getImageSize(input, imageIndex) {\n const offset = SIZE_HEADER + imageIndex * SIZE_IMAGE_ENTRY;\n return {\n height: getSizeFromOffset(input, offset + 1),\n width: getSizeFromOffset(input, offset)\n };\n}\nvar ICO = {\n validate(input) {\n const reserved = readUInt16LE(input, 0);\n const imageCount = readUInt16LE(input, 4);\n if (reserved !== 0 || imageCount === 0) return false;\n const imageType = readUInt16LE(input, 2);\n return imageType === TYPE_ICON;\n },\n calculate(input) {\n const nbImages = readUInt16LE(input, 4);\n const imageSize2 = getImageSize(input, 0);\n if (nbImages === 1) return imageSize2;\n const images = [];\n for (let imageIndex = 0; imageIndex < nbImages; imageIndex += 1) {\n images.push(getImageSize(input, imageIndex));\n }\n return {\n width: imageSize2.width,\n height: imageSize2.height,\n images\n };\n }\n};\n\n// lib/types/cur.ts\nvar TYPE_CURSOR = 2;\nvar CUR = {\n validate(input) {\n const reserved = readUInt16LE(input, 0);\n const imageCount = readUInt16LE(input, 4);\n if (reserved !== 0 || imageCount === 0) return false;\n const imageType = readUInt16LE(input, 2);\n return imageType === TYPE_CURSOR;\n },\n calculate: (input) => ICO.calculate(input)\n};\n\n// lib/types/dds.ts\nvar DDS = {\n validate: (input) => readUInt32LE(input, 0) === 542327876,\n calculate: (input) => ({\n height: readUInt32LE(input, 12),\n width: readUInt32LE(input, 16)\n })\n};\n\n// lib/types/gif.ts\nvar gifRegexp = /^GIF8[79]a/;\nvar GIF = {\n validate: (input) => gifRegexp.test(toUTF8String(input, 0, 6)),\n calculate: (input) => ({\n height: readUInt16LE(input, 8),\n width: readUInt16LE(input, 6)\n })\n};\n\n// lib/types/heif.ts\nvar brandMap = {\n avif: \"avif\",\n mif1: \"heif\",\n msf1: \"heif\",\n // heif-sequence\n heic: \"heic\",\n heix: \"heic\",\n hevc: \"heic\",\n // heic-sequence\n hevx: \"heic\"\n // heic-sequence\n};\nvar HEIF = {\n validate(input) {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"ftyp\") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand in brandMap;\n },\n calculate(input) {\n const metaBox = findBox(input, \"meta\", 0);\n const iprpBox = metaBox && findBox(input, \"iprp\", metaBox.offset + 12);\n const ipcoBox = iprpBox && findBox(input, \"ipco\", iprpBox.offset + 8);\n if (!ipcoBox) {\n throw new TypeError(\"Invalid HEIF, no ipco box found\");\n }\n const type = toUTF8String(input, 8, 12);\n const images = [];\n let currentOffset = ipcoBox.offset + 8;\n while (currentOffset < ipcoBox.offset + ipcoBox.size) {\n const ispeBox = findBox(input, \"ispe\", currentOffset);\n if (!ispeBox) break;\n const rawWidth = readUInt32BE(input, ispeBox.offset + 12);\n const rawHeight = readUInt32BE(input, ispeBox.offset + 16);\n const clapBox = findBox(input, \"clap\", currentOffset);\n let width = rawWidth;\n let height = rawHeight;\n if (clapBox && clapBox.offset < ipcoBox.offset + ipcoBox.size) {\n const cropRight = readUInt32BE(input, clapBox.offset + 12);\n width = rawWidth - cropRight;\n }\n images.push({ height, width });\n currentOffset = ispeBox.offset + (ispeBox.size > 0 ? ispeBox.size : 8);\n }\n if (images.length === 0) {\n throw new TypeError(\"Invalid HEIF, no sizes found\");\n }\n return {\n width: images[0].width,\n height: images[0].height,\n type,\n ...images.length > 1 ? { images } : {}\n };\n }\n};\n\n// lib/types/icns.ts\nvar SIZE_HEADER2 = 4 + 4;\nvar FILE_LENGTH_OFFSET = 4;\nvar ENTRY_LENGTH_OFFSET = 4;\nvar ICON_TYPE_SIZE = {\n ICON: 32,\n \"ICN#\": 32,\n // m => 16 x 16\n \"icm#\": 16,\n icm4: 16,\n icm8: 16,\n // s => 16 x 16\n \"ics#\": 16,\n ics4: 16,\n ics8: 16,\n is32: 16,\n s8mk: 16,\n icp4: 16,\n // l => 32 x 32\n icl4: 32,\n icl8: 32,\n il32: 32,\n l8mk: 32,\n icp5: 32,\n ic11: 32,\n // h => 48 x 48\n ich4: 48,\n ich8: 48,\n ih32: 48,\n h8mk: 48,\n // . => 64 x 64\n icp6: 64,\n ic12: 32,\n // t => 128 x 128\n it32: 128,\n t8mk: 128,\n ic07: 128,\n // . => 256 x 256\n ic08: 256,\n ic13: 256,\n // . => 512 x 512\n ic09: 512,\n ic14: 512,\n // . => 1024 x 1024\n ic10: 1024\n};\nfunction readImageHeader(input, imageOffset) {\n const imageLengthOffset = imageOffset + ENTRY_LENGTH_OFFSET;\n return [\n toUTF8String(input, imageOffset, imageLengthOffset),\n readUInt32BE(input, imageLengthOffset)\n ];\n}\nfunction getImageSize2(type) {\n const size = ICON_TYPE_SIZE[type];\n return { width: size, height: size, type };\n}\nvar ICNS = {\n validate: (input) => toUTF8String(input, 0, 4) === \"icns\",\n calculate(input) {\n const inputLength = input.length;\n const fileLength = readUInt32BE(input, FILE_LENGTH_OFFSET);\n let imageOffset = SIZE_HEADER2;\n const images = [];\n while (imageOffset < fileLength && imageOffset < inputLength) {\n const imageHeader = readImageHeader(input, imageOffset);\n const imageSize2 = getImageSize2(imageHeader[0]);\n images.push(imageSize2);\n imageOffset += imageHeader[1] > 0 ? imageHeader[1] : 8;\n }\n if (images.length === 0) {\n throw new TypeError(\"Invalid ICNS, no sizes found\");\n }\n return {\n width: images[0].width,\n height: images[0].height,\n ...images.length > 1 ? { images } : {}\n };\n }\n};\n\n// lib/types/j2c.ts\nvar J2C = {\n // TODO: this doesn't seem right. SIZ marker doesn't have to be right after the SOC\n validate: (input) => readUInt32BE(input, 0) === 4283432785,\n calculate: (input) => ({\n height: readUInt32BE(input, 12),\n width: readUInt32BE(input, 8)\n })\n};\n\n// lib/types/jp2.ts\nvar JP2 = {\n validate(input) {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"jP \") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand === \"jp2 \";\n },\n calculate(input) {\n const jp2hBox = findBox(input, \"jp2h\", 0);\n const ihdrBox = jp2hBox && findBox(input, \"ihdr\", jp2hBox.offset + 8);\n if (ihdrBox) {\n return {\n height: readUInt32BE(input, ihdrBox.offset + 8),\n width: readUInt32BE(input, ihdrBox.offset + 12)\n };\n }\n throw new TypeError(\"Unsupported JPEG 2000 format\");\n }\n};\n\n// lib/types/jpg.ts\nvar EXIF_MARKER = \"45786966\";\nvar APP1_DATA_SIZE_BYTES = 2;\nvar EXIF_HEADER_BYTES = 6;\nvar TIFF_BYTE_ALIGN_BYTES = 2;\nvar BIG_ENDIAN_BYTE_ALIGN = \"4d4d\";\nvar LITTLE_ENDIAN_BYTE_ALIGN = \"4949\";\nvar IDF_ENTRY_BYTES = 12;\nvar NUM_DIRECTORY_ENTRIES_BYTES = 2;\nfunction isEXIF(input) {\n return toHexString(input, 2, 6) === EXIF_MARKER;\n}\nfunction extractSize(input, index) {\n return {\n height: readUInt16BE(input, index),\n width: readUInt16BE(input, index + 2)\n };\n}\nfunction extractOrientation(exifBlock, isBigEndian) {\n const idfOffset = 8;\n const offset = EXIF_HEADER_BYTES + idfOffset;\n const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian);\n for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) {\n const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES;\n const end = start + IDF_ENTRY_BYTES;\n if (start > exifBlock.length) {\n return;\n }\n const block = exifBlock.slice(start, end);\n const tagNumber = readUInt(block, 16, 0, isBigEndian);\n if (tagNumber === 274) {\n const dataFormat = readUInt(block, 16, 2, isBigEndian);\n if (dataFormat !== 3) {\n return;\n }\n const numberOfComponents = readUInt(block, 32, 4, isBigEndian);\n if (numberOfComponents !== 1) {\n return;\n }\n return readUInt(block, 16, 8, isBigEndian);\n }\n }\n}\nfunction validateExifBlock(input, index) {\n const exifBlock = input.slice(APP1_DATA_SIZE_BYTES, index);\n const byteAlign = toHexString(\n exifBlock,\n EXIF_HEADER_BYTES,\n EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES\n );\n const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN;\n const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN;\n if (isBigEndian || isLittleEndian) {\n return extractOrientation(exifBlock, isBigEndian);\n }\n}\nfunction validateInput(input, index) {\n if (index > input.length) {\n throw new TypeError(\"Corrupt JPG, exceeded buffer limits\");\n }\n}\nvar JPG = {\n validate: (input) => toHexString(input, 0, 2) === \"ffd8\",\n calculate(_input) {\n let input = _input.slice(4);\n let orientation;\n let next;\n while (input.length) {\n const i = readUInt16BE(input, 0);\n validateInput(input, i);\n if (input[i] !== 255) {\n input = input.slice(1);\n continue;\n }\n if (isEXIF(input)) {\n orientation = validateExifBlock(input, i);\n }\n next = input[i + 1];\n if (next === 192 || next === 193 || next === 194) {\n const size = extractSize(input, i + 5);\n if (!orientation) {\n return size;\n }\n return {\n height: size.height,\n orientation,\n width: size.width\n };\n }\n input = input.slice(i + 2);\n }\n throw new TypeError(\"Invalid JPG, no size found\");\n }\n};\n\n// lib/utils/bit-reader.ts\nvar BitReader = class {\n constructor(input, endianness) {\n this.input = input;\n this.endianness = endianness;\n // Skip the first 16 bits (2 bytes) of signature\n this.byteOffset = 2;\n this.bitOffset = 0;\n }\n /** Reads a specified number of bits, and move the offset */\n getBits(length = 1) {\n let result = 0;\n let bitsRead = 0;\n while (bitsRead < length) {\n if (this.byteOffset >= this.input.length) {\n throw new Error(\"Reached end of input\");\n }\n const currentByte = this.input[this.byteOffset];\n const bitsLeft = 8 - this.bitOffset;\n const bitsToRead = Math.min(length - bitsRead, bitsLeft);\n if (this.endianness === \"little-endian\") {\n const mask = (1 << bitsToRead) - 1;\n const bits = currentByte >> this.bitOffset & mask;\n result |= bits << bitsRead;\n } else {\n const mask = (1 << bitsToRead) - 1 << 8 - this.bitOffset - bitsToRead;\n const bits = (currentByte & mask) >> 8 - this.bitOffset - bitsToRead;\n result = result << bitsToRead | bits;\n }\n bitsRead += bitsToRead;\n this.bitOffset += bitsToRead;\n if (this.bitOffset === 8) {\n this.byteOffset++;\n this.bitOffset = 0;\n }\n }\n return result;\n }\n};\n\n// lib/types/jxl-stream.ts\nfunction calculateImageDimension(reader, isSmallImage) {\n if (isSmallImage) {\n return 8 * (1 + reader.getBits(5));\n }\n const sizeClass = reader.getBits(2);\n const extraBits = [9, 13, 18, 30][sizeClass];\n return 1 + reader.getBits(extraBits);\n}\nfunction calculateImageWidth(reader, isSmallImage, widthMode, height) {\n if (isSmallImage && widthMode === 0) {\n return 8 * (1 + reader.getBits(5));\n }\n if (widthMode === 0) {\n return calculateImageDimension(reader, false);\n }\n const aspectRatios = [1, 1.2, 4 / 3, 1.5, 16 / 9, 5 / 4, 2];\n return Math.floor(height * aspectRatios[widthMode - 1]);\n}\nvar JXLStream = {\n validate: (input) => {\n return toHexString(input, 0, 2) === \"ff0a\";\n },\n calculate(input) {\n const reader = new BitReader(input, \"little-endian\");\n const isSmallImage = reader.getBits(1) === 1;\n const height = calculateImageDimension(reader, isSmallImage);\n const widthMode = reader.getBits(3);\n const width = calculateImageWidth(reader, isSmallImage, widthMode, height);\n return { width, height };\n }\n};\n\n// lib/types/jxl.ts\nfunction extractCodestream(input) {\n const jxlcBox = findBox(input, \"jxlc\", 0);\n if (jxlcBox) {\n return input.slice(jxlcBox.offset + 8, jxlcBox.offset + jxlcBox.size);\n }\n const partialStreams = extractPartialStreams(input);\n if (partialStreams.length > 0) {\n return concatenateCodestreams(partialStreams);\n }\n return void 0;\n}\nfunction extractPartialStreams(input) {\n const partialStreams = [];\n let offset = 0;\n while (offset < input.length) {\n const jxlpBox = findBox(input, \"jxlp\", offset);\n if (!jxlpBox) break;\n partialStreams.push(\n input.slice(jxlpBox.offset + 12, jxlpBox.offset + jxlpBox.size)\n );\n offset = jxlpBox.offset + (jxlpBox.size > 0 ? jxlpBox.size : 8);\n }\n return partialStreams;\n}\nfunction concatenateCodestreams(partialCodestreams) {\n const totalLength = partialCodestreams.reduce(\n (acc, curr) => acc + curr.length,\n 0\n );\n const codestream = new Uint8Array(totalLength);\n let position = 0;\n for (const partial of partialCodestreams) {\n codestream.set(partial, position);\n position += partial.length;\n }\n return codestream;\n}\nvar JXL = {\n validate: (input) => {\n const boxType = toUTF8String(input, 4, 8);\n if (boxType !== \"JXL \") return false;\n const ftypBox = findBox(input, \"ftyp\", 0);\n if (!ftypBox) return false;\n const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12);\n return brand === \"jxl \";\n },\n calculate(input) {\n const codestream = extractCodestream(input);\n if (codestream) return JXLStream.calculate(codestream);\n throw new Error(\"No codestream found in JXL container\");\n }\n};\n\n// lib/types/ktx.ts\nvar KTX = {\n validate: (input) => {\n const signature = toUTF8String(input, 1, 7);\n return [\"KTX 11\", \"KTX 20\"].includes(signature);\n },\n calculate: (input) => {\n const type = input[5] === 49 ? \"ktx\" : \"ktx2\";\n const offset = type === \"ktx\" ? 36 : 20;\n return {\n height: readUInt32LE(input, offset + 4),\n width: readUInt32LE(input, offset),\n type\n };\n }\n};\n\n// lib/types/png.ts\nvar pngSignature = \"PNG\\r\\n\u001a\\n\";\nvar pngImageHeaderChunkName = \"IHDR\";\nvar pngFriedChunkName = \"CgBI\";\nvar PNG = {\n validate(input) {\n if (pngSignature === toUTF8String(input, 1, 8)) {\n let chunkName = toUTF8String(input, 12, 16);\n if (chunkName === pngFriedChunkName) {\n chunkName = toUTF8String(input, 28, 32);\n }\n if (chunkName !== pngImageHeaderChunkName) {\n throw new TypeError(\"Invalid PNG\");\n }\n return true;\n }\n return false;\n },\n calculate(input) {\n if (toUTF8String(input, 12, 16) === pngFriedChunkName) {\n return {\n height: readUInt32BE(input, 36),\n width: readUInt32BE(input, 32)\n };\n }\n return {\n height: readUInt32BE(input, 20),\n width: readUInt32BE(input, 16)\n };\n }\n};\n\n// lib/types/pnm.ts\nvar PNMTypes = {\n P1: \"pbm/ascii\",\n P2: \"pgm/ascii\",\n P3: \"ppm/ascii\",\n P4: \"pbm\",\n P5: \"pgm\",\n P6: \"ppm\",\n P7: \"pam\",\n PF: \"pfm\"\n};\nvar handlers = {\n default: (lines) => {\n let dimensions = [];\n while (lines.length > 0) {\n const line = lines.shift();\n if (line[0] === \"#\") {\n continue;\n }\n dimensions = line.split(\" \");\n break;\n }\n if (dimensions.length === 2) {\n return {\n height: Number.parseInt(dimensions[1], 10),\n width: Number.parseInt(dimensions[0], 10)\n };\n }\n throw new TypeError(\"Invalid PNM\");\n },\n pam: (lines) => {\n const size = {};\n while (lines.length > 0) {\n const line = lines.shift();\n if (line.length > 16 || line.charCodeAt(0) > 128) {\n continue;\n }\n const [key, value] = line.split(\" \");\n if (key && value) {\n size[key.toLowerCase()] = Number.parseInt(value, 10);\n }\n if (size.height && size.width) {\n break;\n }\n }\n if (size.height && size.width) {\n return {\n height: size.height,\n width: size.width\n };\n }\n throw new TypeError(\"Invalid PAM\");\n }\n};\nvar PNM = {\n validate: (input) => toUTF8String(input, 0, 2) in PNMTypes,\n calculate(input) {\n const signature = toUTF8String(input, 0, 2);\n const type = PNMTypes[signature];\n const lines = toUTF8String(input, 3).split(/[\\r\\n]+/);\n const handler = handlers[type] || handlers.default;\n return handler(lines);\n }\n};\n\n// lib/types/psd.ts\nvar PSD = {\n validate: (input) => toUTF8String(input, 0, 4) === \"8BPS\",\n calculate: (input) => ({\n height: readUInt32BE(input, 14),\n width: readUInt32BE(input, 18)\n })\n};\n\n// lib/types/svg.ts\nvar svgReg = /<svg\\s([^>\"']|\"[^\"]*\"|'[^']*')*>/;\nvar extractorRegExps = {\n height: /\\sheight=(['\"])([^%]+?)\\1/,\n root: svgReg,\n viewbox: /\\sviewBox=(['\"])(.+?)\\1/i,\n width: /\\swidth=(['\"])([^%]+?)\\1/\n};\nvar INCH_CM = 2.54;\nvar units = {\n in: 96,\n cm: 96 / INCH_CM,\n em: 16,\n ex: 8,\n m: 96 / INCH_CM * 100,\n mm: 96 / INCH_CM / 10,\n pc: 96 / 72 / 12,\n pt: 96 / 72,\n px: 1\n};\nvar unitsReg = new RegExp(\n `^([0-9.]+(?:e\\\\d+)?)(${Object.keys(units).join(\"|\")})?$`\n);\nfunction parseLength(len) {\n const m = unitsReg.exec(len);\n if (!m) {\n return void 0;\n }\n return Math.round(Number(m[1]) * (units[m[2]] || 1));\n}\nfunction parseViewbox(viewbox) {\n const bounds = viewbox.split(\" \");\n return {\n height: parseLength(bounds[3]),\n width: parseLength(bounds[2])\n };\n}\nfunction parseAttributes(root) {\n const width = root.match(extractorRegExps.width);\n const height = root.match(extractorRegExps.height);\n const viewbox = root.match(extractorRegExps.viewbox);\n return {\n height: height && parseLength(height[2]),\n viewbox: viewbox && parseViewbox(viewbox[2]),\n width: width && parseLength(width[2])\n };\n}\nfunction calculateByDimensions(attrs) {\n return {\n height: attrs.height,\n width: attrs.width\n };\n}\nfunction calculateByViewbox(attrs, viewbox) {\n const ratio = viewbox.width / viewbox.height;\n if (attrs.width) {\n return {\n height: Math.floor(attrs.width / ratio),\n width: attrs.width\n };\n }\n if (attrs.height) {\n return {\n height: attrs.height,\n width: Math.floor(attrs.height * ratio)\n };\n }\n return {\n height: viewbox.height,\n width: viewbox.width\n };\n}\nvar SVG = {\n // Scan only the first kilo-byte to speed up the check on larger files\n validate: (input) => svgReg.test(toUTF8String(input, 0, 1e3)),\n calculate(input) {\n const root = toUTF8String(input).match(extractorRegExps.root);\n if (root) {\n const attrs = parseAttributes(root[0]);\n if (attrs.width && attrs.height) {\n return calculateByDimensions(attrs);\n }\n if (attrs.viewbox) {\n return calculateByViewbox(attrs, attrs.viewbox);\n }\n }\n throw new TypeError(\"Invalid SVG\");\n }\n};\n\n// lib/types/tga.ts\nvar TGA = {\n validate(input) {\n return readUInt16LE(input, 0) === 0 && readUInt16LE(input, 4) === 0;\n },\n calculate(input) {\n return {\n height: readUInt16LE(input, 14),\n width: readUInt16LE(input, 12)\n };\n }\n};\n\n// lib/types/tiff.ts\nvar CONSTANTS = {\n TAG: {\n WIDTH: 256,\n HEIGHT: 257,\n COMPRESSION: 259\n },\n TYPE: {\n SHORT: 3,\n LONG: 4,\n LONG8: 16\n },\n ENTRY_SIZE: {\n STANDARD: 12,\n BIG: 20\n },\n COUNT_SIZE: {\n STANDARD: 2,\n BIG: 8\n }\n};\nfunction readIFD(input, { isBigEndian, isBigTiff }) {\n const ifdOffset = isBigTiff ? Number(readUInt64(input, 8, isBigEndian)) : readUInt(input, 32, 4, isBigEndian);\n const entryCountSize = isBigTiff ? CONSTANTS.COUNT_SIZE.BIG : CONSTANTS.COUNT_SIZE.STANDARD;\n return input.slice(ifdOffset + entryCountSize);\n}\nfunction readTagValue(input, type, offset, isBigEndian) {\n switch (type) {\n case CONSTANTS.TYPE.SHORT:\n return readUInt(input, 16, offset, isBigEndian);\n case CONSTANTS.TYPE.LONG:\n return readUInt(input, 32, offset, isBigEndian);\n case CONSTANTS.TYPE.LONG8: {\n const value = Number(readUInt64(input, offset, isBigEndian));\n if (value > Number.MAX_SAFE_INTEGER) {\n throw new TypeError(\"Value too large\");\n }\n return value;\n }\n default:\n return 0;\n }\n}\nfunction nextTag(input, isBigTiff) {\n const entrySize = isBigTiff ? CONSTANTS.ENTRY_SIZE.BIG : CONSTANTS.ENTRY_SIZE.STANDARD;\n if (input.length > entrySize) {\n return input.slice(entrySize);\n }\n}\nfunction extractTags(input, { isBigEndian, isBigTiff }) {\n const tags = {};\n let temp = input;\n while (temp?.length) {\n const code = readUInt(temp, 16, 0, isBigEndian);\n const type = readUInt(temp, 16, 2, isBigEndian);\n const length = isBigTiff ? Number(readUInt64(temp, 4, isBigEndian)) : readUInt(temp, 32, 4, isBigEndian);\n if (code === 0) break;\n if (length === 1 && (type === CONSTANTS.TYPE.SHORT || type === CONSTANTS.TYPE.LONG || isBigTiff && type === CONSTANTS.TYPE.LONG8)) {\n const valueOffset = isBigTiff ? 12 : 8;\n tags[code] = readTagValue(temp, type, valueOffset, isBigEndian);\n }\n temp = nextTag(temp, isBigTiff);\n }\n return tags;\n}\nfunction determineFormat(input) {\n const signature = toUTF8String(input, 0, 2);\n const version = readUInt(input, 16, 2, signature === \"MM\");\n return {\n isBigEndian: signature === \"MM\",\n isBigTiff: version === 43\n };\n}\nfunction validateBigTIFFHeader(input, isBigEndian) {\n const byteSize = readUInt(input, 16, 4, isBigEndian);\n const reserved = readUInt(input, 16, 6, isBigEndian);\n if (byteSize !== 8 || reserved !== 0) {\n throw new TypeError(\"Invalid BigTIFF header\");\n }\n}\nvar signatures = /* @__PURE__ */ new Set([\n \"49492a00\",\n // Little Endian\n \"4d4d002a\",\n // Big Endian\n \"49492b00\",\n // BigTIFF Little Endian\n \"4d4d002b\"\n // BigTIFF Big Endian\n]);\nvar TIFF = {\n validate: (input) => {\n const signature = toHexString(input, 0, 4);\n return signatures.has(signature);\n },\n calculate(input) {\n const format = determineFormat(input);\n if (format.isBigTiff) {\n validateBigTIFFHeader(input, format.isBigEndian);\n }\n const ifdBuffer = readIFD(input, format);\n const tags = extractTags(ifdBuffer, format);\n const info = {\n height: tags[CONSTANTS.TAG.HEIGHT],\n width: tags[CONSTANTS.TAG.WIDTH],\n type: format.isBigTiff ? \"bigtiff\" : \"tiff\"\n };\n if (tags[CONSTANTS.TAG.COMPRESSION]) {\n info.compression = tags[CONSTANTS.TAG.COMPRESSION];\n }\n if (!info.width || !info.height) {\n throw new TypeError(\"Invalid Tiff. Missing tags\");\n }\n return info;\n }\n};\n\n// lib/types/webp.ts\nfunction calculateExtended(input) {\n return {\n height: 1 + readUInt24LE(input, 7),\n width: 1 + readUInt24LE(input, 4)\n };\n}\nfunction calculateLossless(input) {\n return {\n height: 1 + ((input[4] & 15) << 10 | input[3] << 2 | (input[2] & 192) >> 6),\n width: 1 + ((input[2] & 63) << 8 | input[1])\n };\n}\nfunction calculateLossy(input) {\n return {\n height: readInt16LE(input, 8) & 16383,\n width: readInt16LE(input, 6) & 16383\n };\n}\nvar WEBP = {\n validate(input) {\n const riffHeader = \"RIFF\" === toUTF8String(input, 0, 4);\n const webpHeader = \"WEBP\" === toUTF8String(input, 8, 12);\n const vp8Header = \"VP8\" === toUTF8String(input, 12, 15);\n return riffHeader && webpHeader && vp8Header;\n },\n calculate(_input) {\n const chunkHeader = toUTF8String(_input, 12, 16);\n const input = _input.slice(20, 30);\n if (chunkHeader === \"VP8X\") {\n const extendedHeader = input[0];\n const validStart = (extendedHeader & 192) === 0;\n const validEnd = (extendedHeader & 1) === 0;\n if (validStart && validEnd) {\n return calculateExtended(input);\n }\n throw new TypeError(\"Invalid WebP\");\n }\n if (chunkHeader === \"VP8 \" && input[0] !== 47) {\n return calculateLossy(input);\n }\n const signature = toHexString(input, 3, 6);\n if (chunkHeader === \"VP8L\" && signature !== \"9d012a\") {\n return calculateLossless(input);\n }\n throw new TypeError(\"Invalid WebP\");\n }\n};\n\n// lib/types/index.ts\nvar typeHandlers = /* @__PURE__ */ new Map([\n [\"bmp\", BMP],\n [\"cur\", CUR],\n [\"dds\", DDS],\n [\"gif\", GIF],\n [\"heif\", HEIF],\n [\"icns\", ICNS],\n [\"ico\", ICO],\n [\"j2c\", J2C],\n [\"jp2\", JP2],\n [\"jpg\", JPG],\n [\"jxl\", JXL],\n [\"jxl-stream\", JXLStream],\n [\"ktx\", KTX],\n [\"png\", PNG],\n [\"pnm\", PNM],\n [\"psd\", PSD],\n [\"svg\", SVG],\n [\"tga\", TGA],\n [\"tiff\", TIFF],\n [\"webp\", WEBP]\n]);\nvar types = Array.from(typeHandlers.keys());\n\n// lib/detector.ts\nvar firstBytes = /* @__PURE__ */ new Map([\n [0, \"heif\"],\n [56, \"psd\"],\n [66, \"bmp\"],\n [68, \"dds\"],\n [71, \"gif\"],\n [73, \"tiff\"],\n [77, \"tiff\"],\n [82, \"webp\"],\n [105, \"icns\"],\n [137, \"png\"],\n [255, \"jpg\"]\n]);\nfunction detector(input) {\n const byte = input[0];\n const type = firstBytes.get(byte);\n if (type && typeHandlers.get(type).validate(input)) {\n return type;\n }\n return types.find((type2) => typeHandlers.get(type2).validate(input));\n}\n\n// lib/lookup.ts\nvar globalOptions = {\n disabledTypes: []\n};\nfunction imageSize(input) {\n const type = detector(input);\n if (typeof type !== \"undefined\") {\n if (globalOptions.disabledTypes.indexOf(type) > -1) {\n throw new TypeError(`disabled file type: ${type}`);\n }\n const size = typeHandlers.get(type).calculate(input);\n if (size !== void 0) {\n size.type = size.type ?? type;\n if (size.images && size.images.length > 1) {\n const largestImage = size.images.reduce((largest, current) => {\n return current.width * current.height > largest.width * largest.height ? current : largest;\n }, size.images[0]);\n size.width = largestImage.width;\n size.height = largestImage.height;\n }\n return size;\n }\n }\n throw new TypeError(`unsupported file type: ${type}`);\n}\nvar disableTypes = (types2) => {\n globalOptions.disabledTypes = types2;\n};\n\nexport { imageSize as default, disableTypes, imageSize, types };\n"],"x_google_ignoreList":[0],"mappings":";AACA,IAAI,UAAU,IAAI,aAAa;AAC/B,IAAI,gBAAgB,OAAO,QAAQ,GAAG,MAAM,MAAM,WAAW,QAAQ,OAAO,MAAM,MAAM,OAAO,IAAI,CAAC;AACpG,IAAI,e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I,gBAAgB,EAClB,eAAe,EAAE,EAClB;AACD,SAAS,UAAU,OAAO;CACxB,MAAM,OAAO,SAAS,MAAM;AAC5B,KAAI,OAAO,SAAS,aAAa;AAC/B,MAAI,cAAc,cAAc,QAAQ,KAAK,GAAG,GAC9C,OAAM,IAAI,UAAU,uBAAuB,OAAO;EAEpD,MAAM,OAAO,aAAa,IAAI,KAAK,CAAC,UAAU,MAAM;AACpD,MAAI,SAAS,KAAK,GAAG;AACnB,QAAK,OAAO,KAAK,QAAQ;AACzB,OAAI,KAAK,UAAU,KAAK,OAAO,SAAS,GAAG;IACzC,MAAM,eAAe,KAAK,OAAO,QAAQ,SAAS,YAAY;AAC5D,YAAO,QAAQ,QAAQ,QAAQ,SAAS,QAAQ,QAAQ,QAAQ,SAAS,UAAU;OAClF,KAAK,OAAO,GAAG;AAClB,SAAK,QAAQ,aAAa;AAC1B,SAAK,SAAS,aAAa;;AAE7B,UAAO;;;AAGX,OAAM,IAAI,UAAU,0BAA0B,OAAO"}
@@ -47,4 +47,4 @@ async function devConsoleEmailDeliver(event, _ctx) {
47
47
 
48
48
  //#endregion
49
49
  export { getDevEmails as i, clearDevEmails as n, devConsoleEmailDeliver as r, DEV_CONSOLE_EMAIL_PLUGIN_ID as t };
50
- //# sourceMappingURL=email-console-BHNjIwiB.mjs.map
50
+ //# sourceMappingURL=email-console-Dzb6uGYa.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"email-console-BHNjIwiB.mjs","names":[],"sources":["../src/plugins/email-console.ts"],"sourcesContent":["/**\n * Dev Console Email Provider\n *\n * Built-in plugin that registers email:deliver as an exclusive hook.\n * Logs emails to console and stores them in memory (capped at 100).\n * Auto-activated when import.meta.env.DEV is true and no other provider is selected.\n *\n */\n\nimport type { EmailDeliverEvent, EmailMessage, PluginContext } from \"./types.js\";\n\n/** Plugin ID for the dev console email provider */\nexport const DEV_CONSOLE_EMAIL_PLUGIN_ID = \"emdash-console-email\";\n\n/** Maximum number of emails to keep in memory */\nconst MAX_STORED_EMAILS = 100;\n\n/**\n * Stored email record (in-memory only)\n */\nexport interface StoredEmail {\n\tmessage: EmailMessage;\n\tsource: string;\n\tsentAt: string;\n}\n\n/**\n * In-memory store for dev emails.\n * Uses globalThis so the same array is shared across Vite SSR module\n * instances (the runtime and the route handler may load separate copies\n * of this module, but globalThis is always the same object).\n */\nconst GLOBAL_KEY = Symbol.for(\"emdash:dev-emails\");\nconst g = globalThis as Record<symbol, unknown>;\nconst storedEmails: StoredEmail[] = (() => {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\tconst existing = g[GLOBAL_KEY] as StoredEmail[] | undefined;\n\tif (existing) return existing;\n\tconst fresh: StoredEmail[] = [];\n\tg[GLOBAL_KEY] = fresh;\n\treturn fresh;\n})();\n\n/**\n * Get all stored dev emails (most recent first).\n */\nexport function getDevEmails(): StoredEmail[] {\n\treturn storedEmails.toReversed();\n}\n\n/**\n * Clear all stored dev emails.\n */\nexport function clearDevEmails(): void {\n\tstoredEmails.length = 0;\n}\n\n/**\n * The email:deliver handler for the dev console provider.\n * Logs to console and stores in memory.\n */\nexport async function devConsoleEmailDeliver(\n\tevent: EmailDeliverEvent,\n\t_ctx: PluginContext,\n): Promise<void> {\n\tconst { message, source } = event;\n\n\tconsole.log(\n\t\t`\\n📧 [dev-email] Email sent\\n` +\n\t\t\t` From: ${source}\\n` +\n\t\t\t` To: ${message.to}\\n` +\n\t\t\t` Subject: ${message.subject}\\n` +\n\t\t\t` Text: ${message.text.slice(0, 200)}${message.text.length > 200 ? \"...\" : \"\"}\\n`,\n\t);\n\n\t// Store the email\n\tstoredEmails.push({\n\t\tmessage,\n\t\tsource,\n\t\tsentAt: new Date().toISOString(),\n\t});\n\n\t// Cap at MAX_STORED_EMAILS\n\twhile (storedEmails.length > MAX_STORED_EMAILS) {\n\t\tstoredEmails.shift();\n\t}\n}\n"],"mappings":";;AAYA,MAAa,8BAA8B;;AAG3C,MAAM,oBAAoB;;;;;;;AAiB1B,MAAM,aAAa,OAAO,IAAI,oBAAoB;AAClD,MAAM,IAAI;AACV,MAAM,sBAAqC;CAE1C,MAAM,WAAW,EAAE;AACnB,KAAI,SAAU,QAAO;CACrB,MAAM,QAAuB,EAAE;AAC/B,GAAE,cAAc;AAChB,QAAO;IACJ;;;;AAKJ,SAAgB,eAA8B;AAC7C,QAAO,aAAa,YAAY;;;;;AAMjC,SAAgB,iBAAuB;AACtC,cAAa,SAAS;;;;;;AAOvB,eAAsB,uBACrB,OACA,MACgB;CAChB,MAAM,EAAE,SAAS,WAAW;AAE5B,SAAQ,IACP,yCACa,OAAO,WACT,QAAQ,GAAG,gBACN,QAAQ,QAAQ,aACnB,QAAQ,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,KAAK,SAAS,MAAM,QAAQ,GAAG,IACjF;AAGD,cAAa,KAAK;EACjB;EACA;EACA,yBAAQ,IAAI,MAAM,EAAC,aAAa;EAChC,CAAC;AAGF,QAAO,aAAa,SAAS,kBAC5B,cAAa,OAAO"}
1
+ {"version":3,"file":"email-console-Dzb6uGYa.mjs","names":[],"sources":["../src/plugins/email-console.ts"],"sourcesContent":["/**\n * Dev Console Email Provider\n *\n * Built-in plugin that registers email:deliver as an exclusive hook.\n * Logs emails to console and stores them in memory (capped at 100).\n * Auto-activated when import.meta.env.DEV is true and no other provider is selected.\n *\n */\n\nimport type { EmailDeliverEvent, EmailMessage, PluginContext } from \"./types.js\";\n\n/** Plugin ID for the dev console email provider */\nexport const DEV_CONSOLE_EMAIL_PLUGIN_ID = \"emdash-console-email\";\n\n/** Maximum number of emails to keep in memory */\nconst MAX_STORED_EMAILS = 100;\n\n/**\n * Stored email record (in-memory only)\n */\nexport interface StoredEmail {\n\tmessage: EmailMessage;\n\tsource: string;\n\tsentAt: string;\n}\n\n/**\n * In-memory store for dev emails.\n * Uses globalThis so the same array is shared across Vite SSR module\n * instances (the runtime and the route handler may load separate copies\n * of this module, but globalThis is always the same object).\n */\nconst GLOBAL_KEY = Symbol.for(\"emdash:dev-emails\");\nconst g = globalThis as Record<symbol, unknown>;\nconst storedEmails: StoredEmail[] = (() => {\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-context.ts)\n\tconst existing = g[GLOBAL_KEY] as StoredEmail[] | undefined;\n\tif (existing) return existing;\n\tconst fresh: StoredEmail[] = [];\n\tg[GLOBAL_KEY] = fresh;\n\treturn fresh;\n})();\n\n/**\n * Get all stored dev emails (most recent first).\n */\nexport function getDevEmails(): StoredEmail[] {\n\treturn storedEmails.toReversed();\n}\n\n/**\n * Clear all stored dev emails.\n */\nexport function clearDevEmails(): void {\n\tstoredEmails.length = 0;\n}\n\n/**\n * The email:deliver handler for the dev console provider.\n * Logs to console and stores in memory.\n */\nexport async function devConsoleEmailDeliver(\n\tevent: EmailDeliverEvent,\n\t_ctx: PluginContext,\n): Promise<void> {\n\tconst { message, source } = event;\n\n\tconsole.log(\n\t\t`\\n📧 [dev-email] Email sent\\n` +\n\t\t\t` From: ${source}\\n` +\n\t\t\t` To: ${message.to}\\n` +\n\t\t\t` Subject: ${message.subject}\\n` +\n\t\t\t` Text: ${message.text.slice(0, 200)}${message.text.length > 200 ? \"...\" : \"\"}\\n`,\n\t);\n\n\t// Store the email\n\tstoredEmails.push({\n\t\tmessage,\n\t\tsource,\n\t\tsentAt: new Date().toISOString(),\n\t});\n\n\t// Cap at MAX_STORED_EMAILS\n\twhile (storedEmails.length > MAX_STORED_EMAILS) {\n\t\tstoredEmails.shift();\n\t}\n}\n"],"mappings":";;AAYA,MAAa,8BAA8B;;AAG3C,MAAM,oBAAoB;;;;;;;AAiB1B,MAAM,aAAa,OAAO,IAAI,oBAAoB;AAClD,MAAM,IAAI;AACV,MAAM,sBAAqC;CAE1C,MAAM,WAAW,EAAE;AACnB,KAAI,SAAU,QAAO;CACrB,MAAM,QAAuB,EAAE;AAC/B,GAAE,cAAc;AAChB,QAAO;IACJ;;;;AAKJ,SAAgB,eAA8B;AAC7C,QAAO,aAAa,YAAY;;;;;AAMjC,SAAgB,iBAAuB;AACtC,cAAa,SAAS;;;;;;AAOvB,eAAsB,uBACrB,OACA,MACgB;CAChB,MAAM,EAAE,SAAS,WAAW;AAE5B,SAAQ,IACP,yCACa,OAAO,WACT,QAAQ,GAAG,gBACN,QAAQ,QAAQ,aACnB,QAAQ,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,KAAK,SAAS,MAAM,QAAQ,GAAG,IACjF;AAGD,cAAa,KAAK;EACjB;EACA;EACA,yBAAQ,IAAI,MAAM,EAAC,aAAa;EAChC,CAAC;AAGF,QAAO,aAAa,SAAS,kBAC5B,cAAa,OAAO"}
@@ -1,5 +1,5 @@
1
- import { t as imageSize } from "./dist-D_6CKR8z.mjs";
2
- import { n as normalizeMime } from "./mime-DfIVjNkr.mjs";
1
+ import { t as imageSize } from "./dist-89xCrGqi.mjs";
2
+ import { n as normalizeMime } from "./mime-CUIG6x84.mjs";
3
3
  import { encode } from "blurhash";
4
4
 
5
5
  //#region src/media/placeholder.ts
@@ -191,4 +191,4 @@ async function enrichImageMetadata(bytes, contentType, opts) {
191
191
 
192
192
  //#endregion
193
193
  export { generatePlaceholder as n, enrichImageMetadata as t };
194
- //# sourceMappingURL=enrich-_ySMEvEE.mjs.map
194
+ //# sourceMappingURL=enrich-BX0IDp4z.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"enrich-_ySMEvEE.mjs","names":[],"sources":["../src/media/placeholder.ts","../src/media/enrich.ts"],"sourcesContent":["/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nimport { normalizeMime } from \"./mime.js\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n * Returns null when the header cannot be parsed.\n *\n * Shared by every caller that needs pixel dimensions so the header is parsed\n * once per buffer, not re-read inside generatePlaceholder.\n */\nexport function readDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. When present they are\n * trusted verbatim (the caller has typically already read them via\n * readDimensions); otherwise dimensions are read from this buffer's header.\n * Generation is skipped (returns null) when no dimensions are available at\n * all, or when the decoded size (width * height * 4) exceeds\n * MAX_DECODED_BYTES — both guards avoid OOM from unbounded decodes on\n * memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[normalizeMime(mimeType)];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Trust caller-supplied dimensions when present (the caller has usually\n\t\t// already read them via readDimensions); otherwise read them from this\n\t\t// buffer. The header is parsed at most once per call.\n\t\tconst dims = dimensions ?? readDimensions(buffer);\n\n\t\t// Safety net: the decoders allocate the full RGBA buffer with no internal\n\t\t// cap, so refuse to decode unless we can bound the output size. When we\n\t\t// have no parseable header AND no known dimensions, the decoded size is\n\t\t// unbounded — a crafted/truncated PNG whose header image-size can't read\n\t\t// could still be decodable by upng-js, so we must bail to avoid OOM on\n\t\t// memory-constrained runtimes. LQIP is progressive enhancement; missing\n\t\t// it is preferable to crashing the request.\n\t\tif (!dims) return null;\n\t\tif (dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n","/**\n * Image Metadata Enrichment\n *\n * Single seam that derives image dimensions and LQIP placeholders (blurhash,\n * dominant color) from raw image bytes. Every server-side media-creation path\n * routes through this so records are populated consistently. Pure-JS and\n * Workers-safe (image-size reads headers only; generatePlaceholder guards\n * decode size).\n */\n\nimport { normalizeMime } from \"./mime.js\";\nimport { generatePlaceholder, readDimensions } from \"./placeholder.js\";\n\nexport interface EnrichedImageMetadata {\n\twidth?: number;\n\theight?: number;\n\tblurhash?: string;\n\tdominantColor?: string;\n}\n\n/**\n * Derive dimensions + LQIP placeholders from image bytes.\n *\n * - Non-image content types return `{}`.\n * - `knownDimensions` (e.g. browser `naturalWidth/Height`) win over `image-size`\n * for the *stored record* because the browser applies EXIF orientation;\n * `image-size` reports raw header dimensions, which are swapped for\n * 90°/270°-rotated JPEGs. They are NOT used for the decode OOM guard — see below.\n * - The placeholder OOM guard uses only header dimensions read from the bytes\n * actually decoded. Caller-supplied `knownDimensions` are untrusted for the\n * guard: a client could claim a tiny size for a huge image to bypass the cap.\n * - `placeholder` lets a caller decode a smaller thumbnail for the blurhash to\n * avoid OOM on large originals; dimensions still come from `bytes`.\n * - Placeholders are jpeg/png only (the generator's supported formats); other\n * image types still get dimensions.\n */\nexport async function enrichImageMetadata(\n\tbytes: Uint8Array,\n\tcontentType: string,\n\topts?: {\n\t\tknownDimensions?: { width: number; height: number };\n\t\tplaceholder?: { bytes: Uint8Array; contentType: string };\n\t},\n): Promise<EnrichedImageMetadata> {\n\tconst normalizedContentType = normalizeMime(contentType);\n\tif (!normalizedContentType.startsWith(\"image/\")) return {};\n\n\t// Header dimensions are read once from the actual bytes. They feed the\n\t// placeholder OOM guard, which must never trust caller-supplied dimensions:\n\t// `knownDimensions` is decoupled from the buffer, so a client could claim a\n\t// tiny size for a huge image and slip past the decoded-size cap, making the\n\t// decoder allocate an unbounded RGBA buffer and OOM the runtime. Only dims\n\t// read from the buffer that actually gets decoded can bound the decode.\n\tconst headerDims = readDimensions(bytes) ?? undefined;\n\n\t// Dimensions published on the record prefer the caller's knownDimensions\n\t// (e.g. browser naturalWidth/Height, which apply EXIF orientation) over the\n\t// raw header dims, which are swapped for 90°/270°-rotated JPEGs.\n\tconst recordDims = opts?.knownDimensions ?? headerDims;\n\n\t// When a smaller thumbnail override is supplied, decode that for the blurhash\n\t// and let generatePlaceholder read the thumbnail's own header for the OOM\n\t// guard (the override buffer is what actually gets decoded). On the common\n\t// no-override path pass the header dims already read from this same buffer.\n\tconst override = opts?.placeholder;\n\tconst placeholder = await generatePlaceholder(\n\t\toverride ? override.bytes : bytes,\n\t\toverride ? normalizeMime(override.contentType) : normalizedContentType,\n\t\toverride ? undefined : headerDims,\n\t);\n\n\treturn {\n\t\twidth: recordDims?.width,\n\t\theight: recordDims?.height,\n\t\tblurhash: placeholder?.blurhash,\n\t\tdominantColor: placeholder?.dominantColor,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,kBAAkD;CACvD,cAAc;CACd,aAAa;CACb,aAAa;CACb;;AAGD,MAAM,mBAAmB;;AAGzB,MAAM,oBAAoB,KAAK,OAAO;;;;AAWtC,eAAe,WAAW,QAA2C;CACpE,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,OAAO,QAAQ,EAAE,WAAW,MAAM,CAAC;AAClD,QAAO;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,MAAM,OAAO;EAAM;;;;;;AAOzE,eAAe,UAAU,QAA2C;CAEnE,MAAM,QAAQ,MAAM,OAAO,YAAY;CACvC,MAAM,MAAM,KAAK,OAAO,OAAO,OAAO;CAEtC,MAAM,SAAwB,KAAK,QAAQ,IAAI;CAC/C,MAAM,OAAO,IAAI,WAAW,OAAO,GAAG;AACtC,QAAO;EAAE,OAAO,IAAI;EAAO,QAAQ,IAAI;EAAQ,MAAM;EAAM;;;;;;AAO5D,SAAS,qBAAqB,MAAkB,OAAe,QAAwB;CACtF,IAAI,IA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","names":[],"sources":["../src/media/placeholder.ts","../src/media/enrich.ts"],"sourcesContent":["/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nimport { normalizeMime } from \"./mime.js\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n * Returns null when the header cannot be parsed.\n *\n * Shared by every caller that needs pixel dimensions so the header is parsed\n * once per buffer, not re-read inside generatePlaceholder.\n */\nexport function readDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. When present they are\n * trusted verbatim (the caller has typically already read them via\n * readDimensions); otherwise dimensions are read from this buffer's header.\n * Generation is skipped (returns null) when no dimensions are available at\n * all, or when the decoded size (width * height * 4) exceeds\n * MAX_DECODED_BYTES — both guards avoid OOM from unbounded decodes on\n * memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[normalizeMime(mimeType)];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Trust caller-supplied dimensions when present (the caller has usually\n\t\t// already read them via readDimensions); otherwise read them from this\n\t\t// buffer. The header is parsed at most once per call.\n\t\tconst dims = dimensions ?? readDimensions(buffer);\n\n\t\t// Safety net: the decoders allocate the full RGBA buffer with no internal\n\t\t// cap, so refuse to decode unless we can bound the output size. When we\n\t\t// have no parseable header AND no known dimensions, the decoded size is\n\t\t// unbounded — a crafted/truncated PNG whose header image-size can't read\n\t\t// could still be decodable by upng-js, so we must bail to avoid OOM on\n\t\t// memory-constrained runtimes. LQIP is progressive enhancement; missing\n\t\t// it is preferable to crashing the request.\n\t\tif (!dims) return null;\n\t\tif (dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n","/**\n * Image Metadata Enrichment\n *\n * Single seam that derives image dimensions and LQIP placeholders (blurhash,\n * dominant color) from raw image bytes. Every server-side media-creation path\n * routes through this so records are populated consistently. Pure-JS and\n * Workers-safe (image-size reads headers only; generatePlaceholder guards\n * decode size).\n */\n\nimport { normalizeMime } from \"./mime.js\";\nimport { generatePlaceholder, readDimensions } from \"./placeholder.js\";\n\nexport interface EnrichedImageMetadata {\n\twidth?: number;\n\theight?: number;\n\tblurhash?: string;\n\tdominantColor?: string;\n}\n\n/**\n * Derive dimensions + LQIP placeholders from image bytes.\n *\n * - Non-image content types return `{}`.\n * - `knownDimensions` (e.g. browser `naturalWidth/Height`) win over `image-size`\n * for the *stored record* because the browser applies EXIF orientation;\n * `image-size` reports raw header dimensions, which are swapped for\n * 90°/270°-rotated JPEGs. They are NOT used for the decode OOM guard — see below.\n * - The placeholder OOM guard uses only header dimensions read from the bytes\n * actually decoded. Caller-supplied `knownDimensions` are untrusted for the\n * guard: a client could claim a tiny size for a huge image to bypass the cap.\n * - `placeholder` lets a caller decode a smaller thumbnail for the blurhash to\n * avoid OOM on large originals; dimensions still come from `bytes`.\n * - Placeholders are jpeg/png only (the generator's supported formats); other\n * image types still get dimensions.\n */\nexport async function enrichImageMetadata(\n\tbytes: Uint8Array,\n\tcontentType: string,\n\topts?: {\n\t\tknownDimensions?: { width: number; height: number };\n\t\tplaceholder?: { bytes: Uint8Array; contentType: string };\n\t},\n): Promise<EnrichedImageMetadata> {\n\tconst normalizedContentType = normalizeMime(contentType);\n\tif (!normalizedContentType.startsWith(\"image/\")) return {};\n\n\t// Header dimensions are read once from the actual bytes. They feed the\n\t// placeholder OOM guard, which must never trust caller-supplied dimensions:\n\t// `knownDimensions` is decoupled from the buffer, so a client could claim a\n\t// tiny size for a huge image and slip past the decoded-size cap, making the\n\t// decoder allocate an unbounded RGBA buffer and OOM the runtime. Only dims\n\t// read from the buffer that actually gets decoded can bound the decode.\n\tconst headerDims = readDimensions(bytes) ?? undefined;\n\n\t// Dimensions published on the record prefer the caller's knownDimensions\n\t// (e.g. browser naturalWidth/Height, which apply EXIF orientation) over the\n\t// raw header dims, which are swapped for 90°/270°-rotated JPEGs.\n\tconst recordDims = opts?.knownDimensions ?? headerDims;\n\n\t// When a smaller thumbnail override is supplied, decode that for the blurhash\n\t// and let generatePlaceholder read the thumbnail's own header for the OOM\n\t// guard (the override buffer is what actually gets decoded). On the common\n\t// no-override path pass the header dims already read from this same buffer.\n\tconst override = opts?.placeholder;\n\tconst placeholder = await generatePlaceholder(\n\t\toverride ? override.bytes : bytes,\n\t\toverride ? normalizeMime(override.contentType) : normalizedContentType,\n\t\toverride ? undefined : headerDims,\n\t);\n\n\treturn {\n\t\twidth: recordDims?.width,\n\t\theight: recordDims?.height,\n\t\tblurhash: placeholder?.blurhash,\n\t\tdominantColor: placeholder?.dominantColor,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,kBAAkD;CACvD,cAAc;CACd,aAAa;CACb,aAAa;CACb;;AAGD,MAAM,mBAAmB;;AAGzB,MAAM,oBAAoB,KAAK,OAAO;;;;AAWtC,eAAe,WAAW,QAA2C;CACpE,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,OAAO,QAAQ,EAAE,WAAW,MAAM,CAAC;AAClD,QAAO;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;EAAQ,MAAM,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CAQ1D,MAAM,aAAa,eAAe,MAAM,IAAI;CAK5C,MAAM,aAAa,MAAM,mBAAmB;CAM5C,MAAM,WAAW,MAAM;CACvB,MAAM,cAAc,MAAM,oBACzB,WAAW,SAAS,QAAQ,OAC5B,WAAW,cAAc,SAAS,YAAY,GAAG,uBACjD,WAAW,SAAY,WACvB;AAED,QAAO;EACN,OAAO,YAAY;EACnB,QAAQ,YAAY;EACpB,UAAU,aAAa;EACvB,eAAe,aAAa;EAC5B"}
@@ -1,5 +1,5 @@
1
1
  import { i as InvalidCursorError } from "./types-CQPWhPxE.mjs";
2
- import { n as mapErrorStatus } from "./errors-CLUPm7aD.mjs";
2
+ import { n as mapErrorStatus } from "./errors-DsVoDUjJ.mjs";
3
3
 
4
4
  //#region src/api/error.ts
5
5
  /**
@@ -87,4 +87,4 @@ function unwrapResult(result, successStatus = 200) {
87
87
 
88
88
  //#endregion
89
89
  export { unwrapResult as a, requireDb as i, apiSuccess as n, handleError as r, apiError as t };
90
- //# sourceMappingURL=error-DupyJZE2.mjs.map
90
+ //# sourceMappingURL=error-DFrQjppn.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-DupyJZE2.mjs","names":[],"sources":["../src/api/error.ts"],"sourcesContent":["/**\n * Standardized API error responses.\n *\n * All API routes should use these utilities instead of inline\n * `new Response(JSON.stringify({ error: ... }), ...)` patterns.\n */\n\nimport { InvalidCursorError } from \"../database/repositories/types.js\";\nimport { mapErrorStatus } from \"./errors.js\";\nimport type { ApiResult } from \"./types.js\";\n\n// Re-export everything from errors.ts so existing `import { mapErrorStatus } from \"./error.js\"` still works\nexport * from \"./errors.js\";\n\n/**\n * Standard cache headers for all API responses.\n *\n * Cache-Control: private, no-store -- prevents CDN/proxy caching of authenticated data.\n * no-store already tells caches not to store the response, so Vary is unnecessary.\n */\nconst API_CACHE_HEADERS: HeadersInit = {\n\t\"Cache-Control\": \"private, no-store\",\n};\n\n/**\n * Create a standardized error response.\n *\n * Always returns `{ success: false, error: { code, message } }` with correct\n * Content-Type. Use this for all error responses in API routes.\n */\nexport function apiError(\n\tcode: string,\n\tmessage: string,\n\tstatus: number,\n\tdetails?: Record<string, unknown>,\n): Response {\n\tconst error: { code: string; message: string; details?: Record<string, unknown> } = {\n\t\tcode,\n\t\tmessage,\n\t};\n\tif (details !== undefined) error.details = details;\n\treturn Response.json({ success: false, error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ success: true, data: T }` with correct status code.\n * Use this for all success responses in API routes.\n */\nexport function apiSuccess<T>(data: T, status = 200): Response {\n\treturn Response.json({ success: true, data }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Handle an unknown error in a catch block.\n *\n * - Logs the full error server-side\n * - Returns a generic message to the client (never leaks error.message)\n * - Use `fallbackMessage` for the public-facing message\n * - Use `fallbackCode` for the error code\n */\nexport function handleError(\n\terror: unknown,\n\tfallbackMessage: string,\n\tfallbackCode: string,\n): Response {\n\t// Bubble malformed-cursor errors as a structured 400 instead of a\n\t// generic 500.\n\tif (error instanceof InvalidCursorError) {\n\t\treturn apiError(\"INVALID_CURSOR\", error.message, 400);\n\t}\n\tconsole.error(`[${fallbackCode}]`, error);\n\treturn apiError(fallbackCode, fallbackMessage, 500);\n}\n\n/**\n * Standard initialization check.\n *\n * Returns an error response if EmDash is not initialized, or null if OK.\n * Usage: `const err = requireInit(emdash); if (err) return err;`\n */\nexport function requireInit(emdash: unknown): Response | null {\n\tif (!emdash || typeof emdash !== \"object\") {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Standard database check.\n *\n * Returns an error response if the database is not available, or null if OK.\n * Usage: `const err = requireDb(emdash?.db); if (err) return err;`\n */\nexport function requireDb(db: unknown): Response | null {\n\tif (!db) {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Convert an ApiResult into an HTTP Response.\n *\n * Collapses the handler-to-response boilerplate:\n * - Success: returns `apiSuccess(result.data, successStatus)`\n * - Error: returns `apiError(code, message, mapErrorStatus(code))`\n */\nexport function unwrapResult<T>(result: ApiResult<T>, successStatus = 200): Response {\n\tif (!result.success) {\n\t\treturn apiError(\n\t\t\tresult.error.code,\n\t\t\tresult.error.message,\n\t\t\tmapErrorStatus(result.error.code),\n\t\t\tresult.error.details,\n\t\t);\n\t}\n\treturn apiSuccess(result.data, successStatus);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,oBAAiC,EACtC,iBAAiB,qBACjB;;;;;;;AAQD,SAAgB,SACf,MACA,SACA,QACA,SACW;CACX,MAAM,QAA8E;EACnF;EACA;EACA;AACD,KAAI,YAAY,OAAW,OAAM,UAAU;AAC3C,QAAO,SAAS,KAAK;EAAE,SAAS;EAAO;EAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxF,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK;EAAE,SAAS;EAAM;EAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWtF,SAAgB,YACf,OACA,iBACA,cACW;AAGX,KAAI,iBAAiB,mBACpB,QAAO,SAAS,kBAAkB,MAAM,SAAS,IAAI;AAEtD,SAAQ,MAAM,IAAI,aAAa,IAAI,MAAM;AACzC,QAAO,SAAS,cAAc,iBAAiB,IAAI;;;;;;;;AAsBpD,SAAgB,UAAU,IAA8B;AACvD,KAAI,CAAC,GACJ,QAAO,SAAS,kBAAkB,6BAA6B,IAAI;AAEpE,QAAO;;;;;;;;;AAUR,SAAgB,aAAgB,QAAsB,gBAAgB,KAAe;AACpF,KAAI,CAAC,OAAO,QACX,QAAO,SACN,OAAO,MAAM,MACb,OAAO,MAAM,SACb,eAAe,OAAO,MAAM,KAAK,EACjC,OAAO,MAAM,QACb;AAEF,QAAO,WAAW,OAAO,MAAM,cAAc"}
1
+ {"version":3,"file":"error-DFrQjppn.mjs","names":[],"sources":["../src/api/error.ts"],"sourcesContent":["/**\n * Standardized API error responses.\n *\n * All API routes should use these utilities instead of inline\n * `new Response(JSON.stringify({ error: ... }), ...)` patterns.\n */\n\nimport { InvalidCursorError } from \"../database/repositories/types.js\";\nimport { mapErrorStatus } from \"./errors.js\";\nimport type { ApiResult } from \"./types.js\";\n\n// Re-export everything from errors.ts so existing `import { mapErrorStatus } from \"./error.js\"` still works\nexport * from \"./errors.js\";\n\n/**\n * Standard cache headers for all API responses.\n *\n * Cache-Control: private, no-store -- prevents CDN/proxy caching of authenticated data.\n * no-store already tells caches not to store the response, so Vary is unnecessary.\n */\nconst API_CACHE_HEADERS: HeadersInit = {\n\t\"Cache-Control\": \"private, no-store\",\n};\n\n/**\n * Create a standardized error response.\n *\n * Always returns `{ success: false, error: { code, message } }` with correct\n * Content-Type. Use this for all error responses in API routes.\n */\nexport function apiError(\n\tcode: string,\n\tmessage: string,\n\tstatus: number,\n\tdetails?: Record<string, unknown>,\n): Response {\n\tconst error: { code: string; message: string; details?: Record<string, unknown> } = {\n\t\tcode,\n\t\tmessage,\n\t};\n\tif (details !== undefined) error.details = details;\n\treturn Response.json({ success: false, error }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Create a standardized success response.\n *\n * Always returns `{ success: true, data: T }` with correct status code.\n * Use this for all success responses in API routes.\n */\nexport function apiSuccess<T>(data: T, status = 200): Response {\n\treturn Response.json({ success: true, data }, { status, headers: API_CACHE_HEADERS });\n}\n\n/**\n * Handle an unknown error in a catch block.\n *\n * - Logs the full error server-side\n * - Returns a generic message to the client (never leaks error.message)\n * - Use `fallbackMessage` for the public-facing message\n * - Use `fallbackCode` for the error code\n */\nexport function handleError(\n\terror: unknown,\n\tfallbackMessage: string,\n\tfallbackCode: string,\n): Response {\n\t// Bubble malformed-cursor errors as a structured 400 instead of a\n\t// generic 500.\n\tif (error instanceof InvalidCursorError) {\n\t\treturn apiError(\"INVALID_CURSOR\", error.message, 400);\n\t}\n\tconsole.error(`[${fallbackCode}]`, error);\n\treturn apiError(fallbackCode, fallbackMessage, 500);\n}\n\n/**\n * Standard initialization check.\n *\n * Returns an error response if EmDash is not initialized, or null if OK.\n * Usage: `const err = requireInit(emdash); if (err) return err;`\n */\nexport function requireInit(emdash: unknown): Response | null {\n\tif (!emdash || typeof emdash !== \"object\") {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Standard database check.\n *\n * Returns an error response if the database is not available, or null if OK.\n * Usage: `const err = requireDb(emdash?.db); if (err) return err;`\n */\nexport function requireDb(db: unknown): Response | null {\n\tif (!db) {\n\t\treturn apiError(\"NOT_CONFIGURED\", \"EmDash is not initialized\", 500);\n\t}\n\treturn null;\n}\n\n/**\n * Convert an ApiResult into an HTTP Response.\n *\n * Collapses the handler-to-response boilerplate:\n * - Success: returns `apiSuccess(result.data, successStatus)`\n * - Error: returns `apiError(code, message, mapErrorStatus(code))`\n */\nexport function unwrapResult<T>(result: ApiResult<T>, successStatus = 200): Response {\n\tif (!result.success) {\n\t\treturn apiError(\n\t\t\tresult.error.code,\n\t\t\tresult.error.message,\n\t\t\tmapErrorStatus(result.error.code),\n\t\t\tresult.error.details,\n\t\t);\n\t}\n\treturn apiSuccess(result.data, successStatus);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,oBAAiC,EACtC,iBAAiB,qBACjB;;;;;;;AAQD,SAAgB,SACf,MACA,SACA,QACA,SACW;CACX,MAAM,QAA8E;EACnF;EACA;EACA;AACD,KAAI,YAAY,OAAW,OAAM,UAAU;AAC3C,QAAO,SAAS,KAAK;EAAE,SAAS;EAAO;EAAO,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;AASxF,SAAgB,WAAc,MAAS,SAAS,KAAe;AAC9D,QAAO,SAAS,KAAK;EAAE,SAAS;EAAM;EAAM,EAAE;EAAE;EAAQ,SAAS;EAAmB,CAAC;;;;;;;;;;AAWtF,SAAgB,YACf,OACA,iBACA,cACW;AAGX,KAAI,iBAAiB,mBACpB,QAAO,SAAS,kBAAkB,MAAM,SAAS,IAAI;AAEtD,SAAQ,MAAM,IAAI,aAAa,IAAI,MAAM;AACzC,QAAO,SAAS,cAAc,iBAAiB,IAAI;;;;;;;;AAsBpD,SAAgB,UAAU,IAA8B;AACvD,KAAI,CAAC,GACJ,QAAO,SAAS,kBAAkB,6BAA6B,IAAI;AAEpE,QAAO;;;;;;;;;AAUR,SAAgB,aAAgB,QAAsB,gBAAgB,KAAe;AACpF,KAAI,CAAC,OAAO,QACX,QAAO,SACN,OAAO,MAAM,MACb,OAAO,MAAM,SACb,eAAe,OAAO,MAAM,KAAK,EACjC,OAAO,MAAM,QACb;AAEF,QAAO,WAAW,OAAO,MAAM,cAAc"}