emdash 0.7.0 → 0.9.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 (354) hide show
  1. package/dist/{adapters-Di31kZ28.d.mts → adapters-DoNJiveC.d.mts} +1 -1
  2. package/dist/{adapters-Di31kZ28.d.mts.map → adapters-DoNJiveC.d.mts.map} +1 -1
  3. package/dist/{apply-5uslYdUu.mjs → apply-BzltprvY.mjs} +90 -139
  4. package/dist/apply-BzltprvY.mjs.map +1 -0
  5. package/dist/astro/index.d.mts +6 -6
  6. package/dist/astro/index.d.mts.map +1 -1
  7. package/dist/astro/index.mjs +194 -17
  8. package/dist/astro/index.mjs.map +1 -1
  9. package/dist/astro/middleware/auth.d.mts +6 -7
  10. package/dist/astro/middleware/auth.d.mts.map +1 -1
  11. package/dist/astro/middleware/auth.mjs +34 -57
  12. package/dist/astro/middleware/auth.mjs.map +1 -1
  13. package/dist/astro/middleware/redirect.d.mts.map +1 -1
  14. package/dist/astro/middleware/redirect.mjs +17 -12
  15. package/dist/astro/middleware/redirect.mjs.map +1 -1
  16. package/dist/astro/middleware/request-context.d.mts.map +1 -1
  17. package/dist/astro/middleware/request-context.mjs +9 -6
  18. package/dist/astro/middleware/request-context.mjs.map +1 -1
  19. package/dist/astro/middleware/setup.mjs +1 -1
  20. package/dist/astro/middleware.d.mts.map +1 -1
  21. package/dist/astro/middleware.mjs +301 -165
  22. package/dist/astro/middleware.mjs.map +1 -1
  23. package/dist/astro/types.d.mts +34 -10
  24. package/dist/astro/types.d.mts.map +1 -1
  25. package/dist/{base64-MBPo9ozB.mjs → base64-BRICGH2l.mjs} +1 -1
  26. package/dist/{base64-MBPo9ozB.mjs.map → base64-BRICGH2l.mjs.map} +1 -1
  27. package/dist/{byline-C4OVd8b3.mjs → byline-BSaNL1w7.mjs} +5 -5
  28. package/dist/byline-BSaNL1w7.mjs.map +1 -0
  29. package/dist/bylines-CvJ3PYz2.mjs +113 -0
  30. package/dist/bylines-CvJ3PYz2.mjs.map +1 -0
  31. package/dist/cache-C6N_hhN7.mjs +65 -0
  32. package/dist/cache-C6N_hhN7.mjs.map +1 -0
  33. package/dist/{chunks-HGz06Soa.mjs → chunks-NBQVDOci.mjs} +8 -2
  34. package/dist/{chunks-HGz06Soa.mjs.map → chunks-NBQVDOci.mjs.map} +1 -1
  35. package/dist/cli/index.mjs +229 -31
  36. package/dist/cli/index.mjs.map +1 -1
  37. package/dist/client/cf-access.d.mts +1 -1
  38. package/dist/client/index.d.mts +1 -1
  39. package/dist/client/index.mjs +3 -3
  40. package/dist/client/index.mjs.map +1 -1
  41. package/dist/{config-BXwuX8Bx.mjs → config-BI0V3ICQ.mjs} +1 -1
  42. package/dist/{config-BXwuX8Bx.mjs.map → config-BI0V3ICQ.mjs.map} +1 -1
  43. package/dist/{content-D7J5y73J.mjs → content-8lOYF0pr.mjs} +43 -28
  44. package/dist/content-8lOYF0pr.mjs.map +1 -0
  45. package/dist/db/index.d.mts +3 -3
  46. package/dist/db/index.mjs +2 -2
  47. package/dist/db/libsql.d.mts +1 -1
  48. package/dist/db/libsql.d.mts.map +1 -1
  49. package/dist/db/libsql.mjs +7 -2
  50. package/dist/db/libsql.mjs.map +1 -1
  51. package/dist/db/postgres.d.mts +1 -1
  52. package/dist/db/sqlite.d.mts +1 -1
  53. package/dist/db/sqlite.d.mts.map +1 -1
  54. package/dist/db/sqlite.mjs +8 -3
  55. package/dist/db/sqlite.mjs.map +1 -1
  56. package/dist/{db-errors-D0UT85nC.mjs → db-errors-WRezodiz.mjs} +1 -1
  57. package/dist/{db-errors-D0UT85nC.mjs.map → db-errors-WRezodiz.mjs.map} +1 -1
  58. package/dist/{default-CME5YdZ3.mjs → default-D8ksjWhO.mjs} +1 -1
  59. package/dist/{default-CME5YdZ3.mjs.map → default-D8ksjWhO.mjs.map} +1 -1
  60. package/dist/{dialect-helpers-DhTzaUxP.mjs → dialect-helpers-BKCvISIQ.mjs} +19 -2
  61. package/dist/dialect-helpers-BKCvISIQ.mjs.map +1 -0
  62. package/dist/{error-CiYn9yDu.mjs → error-D_-tqP-I.mjs} +1 -1
  63. package/dist/error-D_-tqP-I.mjs.map +1 -0
  64. package/dist/{index-De6_Xv3v.d.mts → index-BFRaVcD6.d.mts} +243 -40
  65. package/dist/index-BFRaVcD6.d.mts.map +1 -0
  66. package/dist/index.d.mts +11 -11
  67. package/dist/index.mjs +29 -25
  68. package/dist/{load-CBcmDIot.mjs → load-DDqMMvZL.mjs} +2 -2
  69. package/dist/{load-CBcmDIot.mjs.map → load-DDqMMvZL.mjs.map} +1 -1
  70. package/dist/{loader-DeiBJEMe.mjs → loader-CKLbBnhK.mjs} +32 -10
  71. package/dist/loader-CKLbBnhK.mjs.map +1 -0
  72. package/dist/{manifest-schema-V30qsMft.mjs → manifest-schema-DqWNC3lM.mjs} +45 -3
  73. package/dist/manifest-schema-DqWNC3lM.mjs.map +1 -0
  74. package/dist/media/index.d.mts +1 -1
  75. package/dist/media/index.mjs +1 -1
  76. package/dist/media/local-runtime.d.mts +7 -7
  77. package/dist/media/local-runtime.mjs +3 -3
  78. package/dist/{media-DqHVh136.mjs → media-BW32b4gi.mjs} +4 -7
  79. package/dist/media-BW32b4gi.mjs.map +1 -0
  80. package/dist/{mode-CpNnGkPz.mjs → mode-ier8jbBk.mjs} +1 -1
  81. package/dist/mode-ier8jbBk.mjs.map +1 -0
  82. package/dist/options-BVp3UsTS.mjs +117 -0
  83. package/dist/options-BVp3UsTS.mjs.map +1 -0
  84. package/dist/page/index.d.mts +2 -2
  85. package/dist/{placeholder-tzpqGWII.d.mts → placeholder-BE4o_2dc.d.mts} +1 -1
  86. package/dist/{placeholder-tzpqGWII.d.mts.map → placeholder-BE4o_2dc.d.mts.map} +1 -1
  87. package/dist/{placeholder-C-fk5hYI.mjs → placeholder-CIJejMlK.mjs} +1 -1
  88. package/dist/placeholder-CIJejMlK.mjs.map +1 -0
  89. package/dist/plugins/adapt-sandbox-entry.d.mts +5 -5
  90. package/dist/plugins/adapt-sandbox-entry.d.mts.map +1 -1
  91. package/dist/plugins/adapt-sandbox-entry.mjs +6 -5
  92. package/dist/plugins/adapt-sandbox-entry.mjs.map +1 -1
  93. package/dist/public-url-DByxYjUw.mjs +51 -0
  94. package/dist/public-url-DByxYjUw.mjs.map +1 -0
  95. package/dist/{query-g4Ug-9j9.mjs → query-Cg9ZKRQ0.mjs} +114 -16
  96. package/dist/query-Cg9ZKRQ0.mjs.map +1 -0
  97. package/dist/{redirect-CN0Rt9Ob.mjs → redirect-BhUBKRc1.mjs} +13 -8
  98. package/dist/redirect-BhUBKRc1.mjs.map +1 -0
  99. package/dist/{registry-Ci3WxVAr.mjs → registry-Dw70ChxB.mjs} +69 -11
  100. package/dist/registry-Dw70ChxB.mjs.map +1 -0
  101. package/dist/{request-cache-DiR961CV.mjs → request-cache-B-bmkipQ.mjs} +1 -1
  102. package/dist/request-cache-B-bmkipQ.mjs.map +1 -0
  103. package/dist/runner-Bnoj7vjK.d.mts +44 -0
  104. package/dist/runner-Bnoj7vjK.d.mts.map +1 -0
  105. package/dist/{runner-tQ7BJ4T7.mjs → runner-C7ADox5q.mjs} +185 -55
  106. package/dist/{runner-tQ7BJ4T7.mjs.map → runner-C7ADox5q.mjs.map} +1 -1
  107. package/dist/runtime.d.mts +6 -6
  108. package/dist/runtime.mjs +4 -4
  109. package/dist/{search-B0effn3j.mjs → search-dOGEccMa.mjs} +341 -152
  110. package/dist/search-dOGEccMa.mjs.map +1 -0
  111. package/dist/secrets-CW3reAnU.mjs +314 -0
  112. package/dist/secrets-CW3reAnU.mjs.map +1 -0
  113. package/dist/seed/index.d.mts +2 -2
  114. package/dist/seed/index.mjs +15 -14
  115. package/dist/seo/index.d.mts +1 -1
  116. package/dist/storage/local.d.mts +1 -1
  117. package/dist/storage/local.mjs +1 -1
  118. package/dist/storage/s3.d.mts +1 -1
  119. package/dist/storage/s3.d.mts.map +1 -1
  120. package/dist/storage/s3.mjs +4 -4
  121. package/dist/storage/s3.mjs.map +1 -1
  122. package/dist/{taxonomies-K2z0Uhnj.mjs → taxonomies-ZlRtD6AG.mjs} +14 -7
  123. package/dist/taxonomies-ZlRtD6AG.mjs.map +1 -0
  124. package/dist/{tokens-BFPFx3CA.mjs → tokens-D7zMmWi2.mjs} +2 -2
  125. package/dist/{tokens-BFPFx3CA.mjs.map → tokens-D7zMmWi2.mjs.map} +1 -1
  126. package/dist/{transport-BykRfpyy.mjs → transport-BeMCmin1.mjs} +6 -5
  127. package/dist/{transport-BykRfpyy.mjs.map → transport-BeMCmin1.mjs.map} +1 -1
  128. package/dist/{transport-H4Iwx7tC.d.mts → transport-DNEfeMaU.d.mts} +1 -1
  129. package/dist/{transport-H4Iwx7tC.d.mts.map → transport-DNEfeMaU.d.mts.map} +1 -1
  130. package/dist/types-4fVtCIm0.mjs +68 -0
  131. package/dist/types-4fVtCIm0.mjs.map +1 -0
  132. package/dist/{types-CnZYHyLW.d.mts → types-BSyXeCFW.d.mts} +24 -2
  133. package/dist/{types-CnZYHyLW.d.mts.map → types-BSyXeCFW.d.mts.map} +1 -1
  134. package/dist/{types-DgrIP0tF.d.mts → types-BuBIptGk.d.mts} +80 -106
  135. package/dist/types-BuBIptGk.d.mts.map +1 -0
  136. package/dist/{types-BH2L167P.mjs → types-CDbKp7ND.mjs} +1 -1
  137. package/dist/{types-BH2L167P.mjs.map → types-CDbKp7ND.mjs.map} +1 -1
  138. package/dist/{types-DDS4MxsT.mjs → types-CIOg5AR8.mjs} +1 -1
  139. package/dist/{types-DDS4MxsT.mjs.map → types-CIOg5AR8.mjs.map} +1 -1
  140. package/dist/{types-6CUZRrZP.d.mts → types-CJsYGpco.d.mts} +24 -2
  141. package/dist/{types-6CUZRrZP.d.mts.map → types-CJsYGpco.d.mts.map} +1 -1
  142. package/dist/types-CRxNbK-Z.mjs +68 -0
  143. package/dist/types-CRxNbK-Z.mjs.map +1 -0
  144. package/dist/{types-C2v0c34j.d.mts → types-CrtWgIvl.d.mts} +1 -1
  145. package/dist/{types-C2v0c34j.d.mts.map → types-CrtWgIvl.d.mts.map} +1 -1
  146. package/dist/{types-CFWjXmus.d.mts → types-M78DQ1lx.d.mts} +1 -1
  147. package/dist/{types-CFWjXmus.d.mts.map → types-M78DQ1lx.d.mts.map} +1 -1
  148. package/dist/{validate-CqsNItbt.mjs → validate-Baqf0slj.mjs} +3 -3
  149. package/dist/{validate-CqsNItbt.mjs.map → validate-Baqf0slj.mjs.map} +1 -1
  150. package/dist/{validate-kM8Pjuf7.d.mts → validate-BfQh_C_y.d.mts} +4 -4
  151. package/dist/{validate-kM8Pjuf7.d.mts.map → validate-BfQh_C_y.d.mts.map} +1 -1
  152. package/dist/validation-BfEI7tNe.mjs +144 -0
  153. package/dist/validation-BfEI7tNe.mjs.map +1 -0
  154. package/dist/version-DoxrVdYf.mjs +7 -0
  155. package/dist/{version-BnTKdfam.mjs.map → version-DoxrVdYf.mjs.map} +1 -1
  156. package/dist/zod-generator-CC0xNe_K.mjs +132 -0
  157. package/dist/zod-generator-CC0xNe_K.mjs.map +1 -0
  158. package/locals.d.ts +1 -6
  159. package/package.json +21 -7
  160. package/src/api/auth-storage.ts +37 -0
  161. package/src/api/error.ts +6 -0
  162. package/src/api/errors.ts +8 -0
  163. package/src/api/handlers/comments.ts +19 -4
  164. package/src/api/handlers/content.ts +151 -4
  165. package/src/api/handlers/device-flow.ts +5 -0
  166. package/src/api/handlers/index.ts +2 -0
  167. package/src/api/handlers/marketplace.ts +11 -4
  168. package/src/api/handlers/media.ts +8 -1
  169. package/src/api/handlers/menus.ts +160 -21
  170. package/src/api/handlers/oauth-authorization.ts +72 -33
  171. package/src/api/handlers/redirects.ts +16 -3
  172. package/src/api/handlers/revision.ts +23 -14
  173. package/src/api/handlers/sections.ts +8 -1
  174. package/src/api/handlers/taxonomies.ts +131 -22
  175. package/src/api/handlers/validation.ts +212 -0
  176. package/src/api/openapi/document.ts +4 -1
  177. package/src/api/public-url.ts +54 -5
  178. package/src/api/route-utils.ts +14 -0
  179. package/src/api/schemas/comments.ts +2 -2
  180. package/src/api/schemas/common.ts +1 -1
  181. package/src/api/schemas/content.ts +17 -0
  182. package/src/api/schemas/sections.ts +3 -3
  183. package/src/api/schemas/setup.ts +8 -0
  184. package/src/api/schemas/users.ts +1 -1
  185. package/src/api/schemas/widgets.ts +12 -10
  186. package/src/api/setup-complete.ts +40 -0
  187. package/src/api/types.ts +5 -1
  188. package/src/astro/integration/index.ts +30 -2
  189. package/src/astro/integration/routes.ts +28 -0
  190. package/src/astro/integration/runtime.ts +49 -1
  191. package/src/astro/integration/virtual-modules.ts +73 -2
  192. package/src/astro/integration/vite-config.ts +49 -13
  193. package/src/astro/middleware/auth.ts +34 -6
  194. package/src/astro/middleware/redirect.ts +29 -16
  195. package/src/astro/middleware/request-context.ts +15 -5
  196. package/src/astro/middleware.ts +41 -10
  197. package/src/astro/routes/PluginRegistry.tsx +10 -1
  198. package/src/astro/routes/api/auth/invite/complete.ts +6 -1
  199. package/src/astro/routes/api/auth/mode.ts +57 -0
  200. package/src/astro/routes/api/auth/oauth/[provider]/callback.ts +23 -3
  201. package/src/astro/routes/api/auth/oauth/[provider].ts +10 -4
  202. package/src/astro/routes/api/auth/passkey/register/verify.ts +6 -1
  203. package/src/astro/routes/api/auth/passkey/verify.ts +6 -1
  204. package/src/astro/routes/api/auth/signup/complete.ts +6 -1
  205. package/src/astro/routes/api/comments/[collection]/[contentId]/index.ts +2 -2
  206. package/src/astro/routes/api/content/[collection]/[id]/discard-draft.ts +4 -2
  207. package/src/astro/routes/api/content/[collection]/[id]/preview-url.ts +34 -12
  208. package/src/astro/routes/api/content/[collection]/[id]/publish.ts +32 -2
  209. package/src/astro/routes/api/content/[collection]/[id]/restore.ts +4 -2
  210. package/src/astro/routes/api/content/[collection]/[id]/revisions.ts +3 -2
  211. package/src/astro/routes/api/content/[collection]/[id]/terms/[taxonomy].ts +8 -4
  212. package/src/astro/routes/api/content/[collection]/[id]/translations.ts +1 -1
  213. package/src/astro/routes/api/content/[collection]/[id].ts +12 -0
  214. package/src/astro/routes/api/content/[collection]/index.ts +1 -9
  215. package/src/astro/routes/api/import/wordpress/execute.ts +3 -1
  216. package/src/astro/routes/api/import/wordpress/media.ts +2 -7
  217. package/src/astro/routes/api/import/wordpress/prepare.ts +9 -0
  218. package/src/astro/routes/api/import/wordpress-plugin/execute.ts +3 -1
  219. package/src/astro/routes/api/manifest.ts +62 -45
  220. package/src/astro/routes/api/media/[id]/confirm.ts +10 -1
  221. package/src/astro/routes/api/media/providers/[providerId]/index.ts +12 -3
  222. package/src/astro/routes/api/openapi.json.ts +27 -10
  223. package/src/astro/routes/api/redirects/404s/index.ts +10 -4
  224. package/src/astro/routes/api/redirects/404s/summary.ts +4 -2
  225. package/src/astro/routes/api/redirects/[id].ts +10 -4
  226. package/src/astro/routes/api/redirects/index.ts +7 -3
  227. package/src/astro/routes/api/revisions/[revisionId]/index.ts +1 -1
  228. package/src/astro/routes/api/schema/collections/[slug]/fields/[fieldSlug].ts +0 -2
  229. package/src/astro/routes/api/schema/collections/[slug]/fields/index.ts +0 -1
  230. package/src/astro/routes/api/schema/collections/[slug]/fields/reorder.ts +0 -1
  231. package/src/astro/routes/api/schema/collections/[slug]/index.ts +2 -2
  232. package/src/astro/routes/api/schema/collections/index.ts +1 -1
  233. package/src/astro/routes/api/search/index.ts +10 -2
  234. package/src/astro/routes/api/sections/[slug].ts +10 -4
  235. package/src/astro/routes/api/sections/index.ts +7 -3
  236. package/src/astro/routes/api/settings/email.ts +4 -9
  237. package/src/astro/routes/api/setup/admin-verify.ts +6 -1
  238. package/src/astro/routes/api/setup/admin.ts +8 -2
  239. package/src/astro/routes/api/setup/index.ts +2 -2
  240. package/src/astro/routes/api/setup/status.ts +3 -1
  241. package/src/astro/routes/api/snapshot.ts +44 -18
  242. package/src/astro/routes/api/taxonomies/index.ts +0 -1
  243. package/src/astro/routes/api/themes/preview.ts +11 -5
  244. package/src/astro/routes/api/widget-areas/[name]/widgets/[id].ts +4 -1
  245. package/src/astro/routes/api/widget-areas/[name]/widgets.ts +4 -1
  246. package/src/astro/routes/api/widget-areas/[name].ts +4 -1
  247. package/src/astro/routes/api/widget-areas/index.ts +4 -1
  248. package/src/astro/types.ts +32 -3
  249. package/src/auth/allowed-origins.ts +168 -0
  250. package/src/auth/mode.ts +15 -3
  251. package/src/auth/passkey-config.ts +35 -13
  252. package/src/auth/providers/github-admin.tsx +29 -0
  253. package/src/auth/providers/github.ts +31 -0
  254. package/src/auth/providers/google-admin.tsx +44 -0
  255. package/src/auth/providers/google.ts +31 -0
  256. package/src/auth/types.ts +114 -4
  257. package/src/bylines/index.ts +37 -88
  258. package/src/cli/commands/auth.ts +28 -6
  259. package/src/cli/commands/bundle-utils.ts +11 -2
  260. package/src/cli/commands/bundle.ts +31 -9
  261. package/src/cli/commands/content.ts +13 -0
  262. package/src/cli/commands/login.ts +8 -1
  263. package/src/cli/commands/publish.ts +24 -0
  264. package/src/cli/commands/secrets.ts +183 -0
  265. package/src/cli/credentials.ts +1 -1
  266. package/src/cli/index.ts +5 -1
  267. package/src/client/index.ts +4 -4
  268. package/src/client/transport.ts +17 -7
  269. package/src/components/Break.astro +2 -2
  270. package/src/components/EmDashHead.astro +18 -13
  271. package/src/components/EmDashImage.astro +7 -6
  272. package/src/components/Embed.astro +1 -1
  273. package/src/components/Gallery.astro +6 -4
  274. package/src/components/Image.astro +9 -4
  275. package/src/components/InlinePortableTextEditor.tsx +106 -19
  276. package/src/components/LiveSearch.astro +5 -14
  277. package/src/config/secrets.ts +528 -0
  278. package/src/database/dialect-helpers.ts +50 -0
  279. package/src/database/migrations/034_published_at_index.ts +1 -1
  280. package/src/database/migrations/035_bounded_404_log.ts +56 -39
  281. package/src/database/migrations/runner.ts +156 -23
  282. package/src/database/repositories/audit.ts +6 -8
  283. package/src/database/repositories/byline.ts +6 -8
  284. package/src/database/repositories/comment.ts +12 -16
  285. package/src/database/repositories/content.ts +76 -52
  286. package/src/database/repositories/index.ts +1 -1
  287. package/src/database/repositories/media.ts +10 -13
  288. package/src/database/repositories/plugin-storage.ts +4 -6
  289. package/src/database/repositories/redirect.ts +26 -19
  290. package/src/database/repositories/taxonomy.ts +40 -3
  291. package/src/database/repositories/types.ts +57 -8
  292. package/src/database/repositories/user.ts +6 -8
  293. package/src/db/libsql.ts +1 -3
  294. package/src/db/sqlite.ts +2 -5
  295. package/src/emdash-runtime.ts +388 -247
  296. package/src/index.ts +14 -1
  297. package/src/loader.ts +30 -6
  298. package/src/mcp/server.ts +781 -141
  299. package/src/media/normalize.ts +1 -1
  300. package/src/media/url.ts +78 -0
  301. package/src/page/site-identity.ts +58 -0
  302. package/src/plugins/adapt-sandbox-entry.ts +22 -10
  303. package/src/plugins/context.ts +13 -10
  304. package/src/plugins/define-plugin.ts +40 -12
  305. package/src/plugins/email-console.ts +10 -3
  306. package/src/plugins/hooks.ts +34 -19
  307. package/src/plugins/index.ts +9 -0
  308. package/src/plugins/manifest-schema.ts +49 -2
  309. package/src/plugins/types.ts +174 -13
  310. package/src/preview/urls.ts +23 -3
  311. package/src/query.ts +149 -6
  312. package/src/redirects/cache.ts +38 -18
  313. package/src/request-cache.ts +3 -0
  314. package/src/schema/registry.ts +97 -5
  315. package/src/schema/zod-generator.ts +27 -5
  316. package/src/search/fts-manager.ts +0 -2
  317. package/src/search/query.ts +111 -26
  318. package/src/search/types.ts +8 -1
  319. package/src/sections/index.ts +7 -9
  320. package/src/seed/apply.ts +2 -0
  321. package/src/settings/index.ts +80 -6
  322. package/src/settings/types.ts +23 -1
  323. package/src/storage/s3.ts +12 -6
  324. package/src/taxonomies/index.ts +11 -1
  325. package/src/virtual-modules.d.ts +21 -1
  326. package/src/widgets/index.ts +1 -1
  327. package/dist/apply-5uslYdUu.mjs.map +0 -1
  328. package/dist/byline-C4OVd8b3.mjs.map +0 -1
  329. package/dist/bylines-hPTW79hw.mjs +0 -157
  330. package/dist/bylines-hPTW79hw.mjs.map +0 -1
  331. package/dist/cache-BkKBuIvS.mjs +0 -56
  332. package/dist/cache-BkKBuIvS.mjs.map +0 -1
  333. package/dist/chunk-ClPoSABd.mjs +0 -21
  334. package/dist/content-D7J5y73J.mjs.map +0 -1
  335. package/dist/dialect-helpers-DhTzaUxP.mjs.map +0 -1
  336. package/dist/error-CiYn9yDu.mjs.map +0 -1
  337. package/dist/index-De6_Xv3v.d.mts.map +0 -1
  338. package/dist/loader-DeiBJEMe.mjs.map +0 -1
  339. package/dist/manifest-schema-V30qsMft.mjs.map +0 -1
  340. package/dist/media-DqHVh136.mjs.map +0 -1
  341. package/dist/mode-CpNnGkPz.mjs.map +0 -1
  342. package/dist/placeholder-C-fk5hYI.mjs.map +0 -1
  343. package/dist/query-g4Ug-9j9.mjs.map +0 -1
  344. package/dist/redirect-CN0Rt9Ob.mjs.map +0 -1
  345. package/dist/registry-Ci3WxVAr.mjs.map +0 -1
  346. package/dist/request-cache-DiR961CV.mjs.map +0 -1
  347. package/dist/runner-BR2xKwhn.d.mts +0 -34
  348. package/dist/runner-BR2xKwhn.d.mts.map +0 -1
  349. package/dist/search-B0effn3j.mjs.map +0 -1
  350. package/dist/taxonomies-K2z0Uhnj.mjs.map +0 -1
  351. package/dist/types-CMMN0pNg.mjs +0 -31
  352. package/dist/types-CMMN0pNg.mjs.map +0 -1
  353. package/dist/types-DgrIP0tF.d.mts.map +0 -1
  354. package/dist/version-BnTKdfam.mjs +0 -7
@@ -0,0 +1,314 @@
1
+ import { i as encodeBase64url, n as decodeBase64url } from "./base64-BRICGH2l.mjs";
2
+ import { t as OptionsRepository } from "./options-BVp3UsTS.mjs";
3
+ import { sha256 } from "@oslojs/crypto/sha2";
4
+ import { encodeHexLowerCase } from "@oslojs/encoding";
5
+
6
+ //#region src/config/secrets.ts
7
+ /**
8
+ * Centralized secrets module
9
+ *
10
+ * Single source of truth for site-level cryptographic secrets:
11
+ *
12
+ * - `EMDASH_ENCRYPTION_KEY` — primary key for encrypting plugin secrets at
13
+ * rest. Multi-key (comma-separated) for rotation forward-compat. v1 ships
14
+ * single-key. Format: `emdash_enc_v1_<43 base64url chars>` representing
15
+ * 32 random bytes. **Operator-provided; never stored in the database.**
16
+ * Losing the key means losing every secret encrypted with it. Validated
17
+ * at runtime startup via `validateEncryptionKeyAtStartup` — request-time
18
+ * resolution does not depend on it, so a malformed key can't 500 the
19
+ * preview/comment hot paths for unrelated visitors.
20
+ * - `EMDASH_IP_SALT` (optional) / DB-stored `emdash:ip_salt` — site-specific
21
+ * salt for hashing commenter IPs. Generated and persisted on first need
22
+ * if no env override is set. Replaces the previous hardcoded
23
+ * `"emdash-ip-salt"` constant which was correlatable across installs.
24
+ * - `EMDASH_PREVIEW_SECRET` (optional) / DB-stored `emdash:preview_secret` —
25
+ * HMAC secret for signing preview URLs. Generated and persisted on first
26
+ * need if no env override is set. Replaces the previous empty-string
27
+ * fallback which silently disabled preview-token verification.
28
+ *
29
+ * The `EMDASH_AUTH_SECRET` env var is consulted only as a legacy fallback
30
+ * source for the IP salt — that's the only path the prior code actually
31
+ * read it from. New deployments don't need to set it.
32
+ *
33
+ * Modeled on `resolveS3Config` in `../storage/s3.ts`.
34
+ */
35
+ /** v1 encryption key prefix. Bumping requires a separate KDF version. */
36
+ const ENCRYPTION_KEY_PREFIX = "emdash_enc_v1_";
37
+ /** 32 random bytes encoded as unpadded base64url = 43 chars. */
38
+ const ENCRYPTION_KEY_BODY_LENGTH = 43;
39
+ /**
40
+ * Built from the prefix constant via interpolation. The prefix has no regex
41
+ * metacharacters today (`emdash_enc_v1_`), but escaping is cheap defense
42
+ * against anyone changing the prefix in a future bump without remembering.
43
+ */
44
+ const ENCRYPTION_KEY_PATTERN = new RegExp(`^${ENCRYPTION_KEY_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[A-Za-z0-9_-]{${ENCRYPTION_KEY_BODY_LENGTH}}$`);
45
+ /** Options-table key for the persisted commenter-IP salt. */
46
+ const IP_SALT_OPTION_KEY = "emdash:ip_salt";
47
+ /** Options-table key for the persisted preview HMAC secret. */
48
+ const PREVIEW_SECRET_OPTION_KEY = "emdash:preview_secret";
49
+ /** Length in bytes of generated values. 32 bytes = 256 bits. */
50
+ const GENERATED_SECRET_BYTES = 32;
51
+ /**
52
+ * Class of validation failures raised by this module.
53
+ *
54
+ * Errors here are operator-facing config problems (malformed key, etc.).
55
+ * They are thrown rather than soft-skipped so misconfiguration fails loudly
56
+ * at startup instead of silently degrading at request time.
57
+ */
58
+ var EmDashSecretsError = class extends Error {
59
+ name = "EmDashSecretsError";
60
+ code;
61
+ constructor(message, code) {
62
+ super(message);
63
+ this.code = code;
64
+ }
65
+ };
66
+ /**
67
+ * Parse the `EMDASH_ENCRYPTION_KEY` env var.
68
+ *
69
+ * Accepts a single key or a comma-separated list. The first entry is the
70
+ * primary (used for new writes); all entries are tried for decryption,
71
+ * matched by `kid`. Whitespace around commas is tolerated. Empty entries
72
+ * (e.g. trailing comma) are ignored.
73
+ *
74
+ * Returns `null` for an unset/empty input. Throws `EmDashSecretsError` on
75
+ * any malformed entry — silent skipping would mask deployment mistakes.
76
+ */
77
+ async function parseEncryptionKeys(raw) {
78
+ if (!raw) return null;
79
+ const entries = raw.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
80
+ if (entries.length === 0) return null;
81
+ const parsed = [];
82
+ const seenKids = /* @__PURE__ */ new Set();
83
+ for (const entry of entries) {
84
+ if (!ENCRYPTION_KEY_PATTERN.test(entry)) throw new EmDashSecretsError(`EMDASH_ENCRYPTION_KEY entry is malformed (expected "${ENCRYPTION_KEY_PREFIX}" followed by ${ENCRYPTION_KEY_BODY_LENGTH} base64url chars). Generate one with \`emdash secrets generate\`.`, "INVALID_ENCRYPTION_KEY");
85
+ const body = entry.slice(14);
86
+ const key = decodeBase64urlStrict(body);
87
+ if (!key) throw new EmDashSecretsError("EMDASH_ENCRYPTION_KEY body is not valid base64url", "INVALID_ENCRYPTION_KEY");
88
+ if (key.length !== GENERATED_SECRET_BYTES) throw new EmDashSecretsError(`EMDASH_ENCRYPTION_KEY must decode to ${GENERATED_SECRET_BYTES} bytes, got ${key.length}`, "INVALID_ENCRYPTION_KEY");
89
+ if (encodeBase64url(key) !== body) throw new EmDashSecretsError("EMDASH_ENCRYPTION_KEY body is not canonical base64url. Generate one with `emdash secrets generate`.", "INVALID_ENCRYPTION_KEY");
90
+ const kid = fingerprintKeyBytes(key);
91
+ if (seenKids.has(kid)) continue;
92
+ seenKids.add(kid);
93
+ parsed.push({
94
+ kid,
95
+ key,
96
+ raw: entry
97
+ });
98
+ }
99
+ return parsed;
100
+ }
101
+ /**
102
+ * Compute the kid for a raw key string (the env-var form including the
103
+ * `emdash_enc_v1_` prefix). Public so the CLI's `fingerprint` subcommand
104
+ * and admin endpoints can show kids without exposing raw keys.
105
+ *
106
+ * The kid is derived from the decoded key **bytes**, not the raw string,
107
+ * so admin endpoints / future rotation flows can match envelope kids
108
+ * against bytes regardless of how the env var was originally spelled.
109
+ *
110
+ * Validates the same shape as `parseEncryptionKeys` — including canonical
111
+ * base64url — so the CLI can't print a kid for a key the runtime would
112
+ * later refuse to load.
113
+ *
114
+ * Throws `EmDashSecretsError` for malformed or non-canonical input.
115
+ */
116
+ async function fingerprintKey(raw) {
117
+ if (!ENCRYPTION_KEY_PATTERN.test(raw)) throw new EmDashSecretsError(`Key must match "${ENCRYPTION_KEY_PREFIX}" followed by ${ENCRYPTION_KEY_BODY_LENGTH} base64url chars`, "INVALID_ENCRYPTION_KEY");
118
+ const body = raw.slice(14);
119
+ const bytes = decodeBase64urlStrict(body);
120
+ if (!bytes || bytes.length !== GENERATED_SECRET_BYTES || encodeBase64url(bytes) !== body) throw new EmDashSecretsError(`Key body must decode to ${GENERATED_SECRET_BYTES} canonical base64url bytes`, "INVALID_ENCRYPTION_KEY");
121
+ return fingerprintKeyBytes(bytes);
122
+ }
123
+ /**
124
+ * Internal: kid derivation from raw key bytes. The single source of truth
125
+ * for what makes two keys "the same key" — used by both `parseEncryptionKeys`
126
+ * and `fingerprintKey`.
127
+ */
128
+ function fingerprintKeyBytes(key) {
129
+ return encodeHexLowerCase(sha256(key)).slice(0, 8);
130
+ }
131
+ /**
132
+ * Generate a fresh `EMDASH_ENCRYPTION_KEY` value. Used by the CLI's
133
+ * `secrets generate` subcommand and by `create-emdash` scaffolding.
134
+ */
135
+ function generateEncryptionKey() {
136
+ const bytes = new Uint8Array(GENERATED_SECRET_BYTES);
137
+ crypto.getRandomValues(bytes);
138
+ return `${ENCRYPTION_KEY_PREFIX}${encodeBase64url(bytes)}`;
139
+ }
140
+ /**
141
+ * Resolve site secrets. Reads env vars; for IP salt and preview secret,
142
+ * falls back to a DB-stored value, generating one atomically on first need.
143
+ *
144
+ * Idempotent. Concurrent callers race on the atomic `setIfAbsent`; whichever
145
+ * wins, all callers converge on the same stored value.
146
+ *
147
+ * Note: `EMDASH_ENCRYPTION_KEY` is **not** consumed here. It's validated
148
+ * separately at runtime startup (see `validateEncryptionKeyAtStartup`) so a
149
+ * malformed key can't take down preview-token verification or comment
150
+ * submission for unrelated visitors. Future plugin-secret encryption code
151
+ * will read it via its own dedicated helper.
152
+ */
153
+ async function resolveSecrets(options) {
154
+ const env = options.env ?? readDefaultEnv();
155
+ const repo = options._repo ?? new OptionsRepository(options.db);
156
+ const previewEnvOverride = pickFirstNonEmpty(env.EMDASH_PREVIEW_SECRET, env.PREVIEW_SECRET);
157
+ const ipSaltEnvOverride = pickFirstNonEmpty(env.EMDASH_IP_SALT, env.EMDASH_AUTH_SECRET, env.AUTH_SECRET);
158
+ const [previewSecret, ipSalt] = await Promise.all([previewEnvOverride !== null ? Promise.resolve({
159
+ value: previewEnvOverride,
160
+ source: "env"
161
+ }) : ensureGeneratedOption(repo, PREVIEW_SECRET_OPTION_KEY), ipSaltEnvOverride !== null ? Promise.resolve({
162
+ value: ipSaltEnvOverride,
163
+ source: "env"
164
+ }) : ensureGeneratedOption(repo, IP_SALT_OPTION_KEY)]);
165
+ return {
166
+ previewSecret: previewSecret.value,
167
+ previewSecretSource: previewSecret.source,
168
+ ipSalt: ipSalt.value,
169
+ ipSaltSource: ipSalt.source
170
+ };
171
+ }
172
+ /**
173
+ * Validate `EMDASH_ENCRYPTION_KEY` once at runtime startup. Logs an
174
+ * operator-facing error if the value is malformed but does **not** throw —
175
+ * the key is currently inert (no consumers), and the follow-up PR that
176
+ * actually uses it will throw at point of use. This way, deployment
177
+ * mistakes surface immediately in startup logs without wedging unrelated
178
+ * request paths in the meantime.
179
+ *
180
+ * Returns `true` if the key is unset or valid, `false` if it was malformed.
181
+ */
182
+ async function validateEncryptionKeyAtStartup(env) {
183
+ const resolved = env ?? readDefaultEnv();
184
+ try {
185
+ await parseEncryptionKeys(resolved.EMDASH_ENCRYPTION_KEY);
186
+ return true;
187
+ } catch (error) {
188
+ if (error instanceof EmDashSecretsError) {
189
+ console.error(`[emdash] EMDASH_ENCRYPTION_KEY is invalid: ${error.message} Plugin-secret encryption will fail once it ships. Generate a fresh key with \`emdash secrets generate\`.`);
190
+ return false;
191
+ }
192
+ throw error;
193
+ }
194
+ }
195
+ /**
196
+ * Per-DB cache of resolved secrets, keyed by Kysely instance identity.
197
+ *
198
+ * The resolved values are stable for the lifetime of the deployment (env
199
+ * vars don't change without a restart, and DB-stored values are written
200
+ * once via `setIfAbsent`). Caching avoids one options-table read per
201
+ * request on the hot paths (preview verification, comment hashing).
202
+ *
203
+ * Lives on `globalThis` so module-duplication during SSR bundling can't
204
+ * fragment the cache. See `request-context.ts` for the same pattern.
205
+ */
206
+ const SECRETS_CACHE_KEY = Symbol.for("@emdash-cms/core/secrets-cache@1");
207
+ function getSecretsCache() {
208
+ const holder = globalThis;
209
+ let entry = holder[SECRETS_CACHE_KEY];
210
+ if (!entry) {
211
+ entry = { cache: /* @__PURE__ */ new WeakMap() };
212
+ holder[SECRETS_CACHE_KEY] = entry;
213
+ }
214
+ return entry.cache;
215
+ }
216
+ /**
217
+ * Memoized wrapper around `resolveSecrets`. Use this from request-time hot
218
+ * paths (preview verification, comment IP hashing) so they don't reread
219
+ * env / re-query options on every request.
220
+ *
221
+ * The cache is keyed by `Kysely` instance, so playground / per-DO / per-test
222
+ * databases each get their own resolution.
223
+ */
224
+ function resolveSecretsCached(db) {
225
+ const cache = getSecretsCache();
226
+ const cached = cache.get(db);
227
+ if (cached) return cached;
228
+ const promise = resolveSecrets({ db }).catch((error) => {
229
+ cache.delete(db);
230
+ throw error;
231
+ });
232
+ cache.set(db, promise);
233
+ return promise;
234
+ }
235
+ /**
236
+ * Read or generate-and-persist a random base64url secret stored in the
237
+ * options table.
238
+ *
239
+ * Concurrency: `setIfAbsent` is an atomic INSERT...ON CONFLICT DO NOTHING.
240
+ * On race, the loser re-reads to converge on the winner's value.
241
+ */
242
+ async function ensureGeneratedOption(repo, optionKey) {
243
+ const existing = await repo.get(optionKey);
244
+ if (typeof existing === "string" && existing.length > 0) return {
245
+ value: existing,
246
+ source: "db"
247
+ };
248
+ const generated = generateRandomSecret();
249
+ if (await repo.setIfAbsent(optionKey, generated)) return {
250
+ value: generated,
251
+ source: "db"
252
+ };
253
+ const winner = await repo.get(optionKey);
254
+ if (typeof winner !== "string" || winner.length === 0) throw new EmDashSecretsError(`Failed to persist generated secret for "${optionKey}"`, "SECRET_PERSIST_FAILED");
255
+ return {
256
+ value: winner,
257
+ source: "db"
258
+ };
259
+ }
260
+ /** Generate 32 random bytes encoded as unpadded base64url. */
261
+ function generateRandomSecret() {
262
+ const bytes = new Uint8Array(GENERATED_SECRET_BYTES);
263
+ crypto.getRandomValues(bytes);
264
+ return encodeBase64url(bytes);
265
+ }
266
+ /** Return the first non-empty string from `values`, or `null` if all are empty. */
267
+ function pickFirstNonEmpty(...values) {
268
+ for (const value of values) if (typeof value === "string" && value.length > 0) return value;
269
+ return null;
270
+ }
271
+ const BASE64URL_CHARSET_PATTERN = /^[A-Za-z0-9_-]+$/;
272
+ /**
273
+ * Validate base64url shape and decode. Returns `null` on malformed input
274
+ * (rather than throwing) so the caller can produce a config-specific error.
275
+ */
276
+ function decodeBase64urlStrict(input) {
277
+ if (!BASE64URL_CHARSET_PATTERN.test(input)) return null;
278
+ try {
279
+ return decodeBase64url(input);
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ /**
285
+ * Default env reader.
286
+ *
287
+ * Note: this is the **only** code path in core that reads both
288
+ * `import.meta.env` and `process.env`. Route handlers should not — they
289
+ * always run inside the Astro/Vite bundle where `import.meta.env` is
290
+ * the correct source. This resolver is shared with the CLI surface (via
291
+ * `cli/commands/secrets.ts`) which runs outside the bundle, so we
292
+ * deliberately consult both. `import.meta.env` wins so build-time
293
+ * substitutions are honored when present.
294
+ *
295
+ * The convention documented in AGENTS.md ("import.meta.env.EMDASH_X ||
296
+ * import.meta.env.X") is the route-handler convention; this is the
297
+ * shared-with-CLI exception.
298
+ */
299
+ function readDefaultEnv() {
300
+ const meta = import.meta.env ?? {};
301
+ const proc = typeof process !== "undefined" && process.env ? process.env : {};
302
+ return {
303
+ EMDASH_ENCRYPTION_KEY: meta.EMDASH_ENCRYPTION_KEY ?? proc.EMDASH_ENCRYPTION_KEY,
304
+ EMDASH_PREVIEW_SECRET: meta.EMDASH_PREVIEW_SECRET ?? proc.EMDASH_PREVIEW_SECRET,
305
+ PREVIEW_SECRET: meta.PREVIEW_SECRET ?? proc.PREVIEW_SECRET,
306
+ EMDASH_IP_SALT: meta.EMDASH_IP_SALT ?? proc.EMDASH_IP_SALT,
307
+ EMDASH_AUTH_SECRET: meta.EMDASH_AUTH_SECRET ?? proc.EMDASH_AUTH_SECRET,
308
+ AUTH_SECRET: meta.AUTH_SECRET ?? proc.AUTH_SECRET
309
+ };
310
+ }
311
+
312
+ //#endregion
313
+ export { validateEncryptionKeyAtStartup as a, resolveSecretsCached as i, fingerprintKey as n, generateEncryptionKey as r, EmDashSecretsError as t };
314
+ //# sourceMappingURL=secrets-CW3reAnU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secrets-CW3reAnU.mjs","names":[],"sources":["../src/config/secrets.ts"],"sourcesContent":["/**\n * Centralized secrets module\n *\n * Single source of truth for site-level cryptographic secrets:\n *\n * - `EMDASH_ENCRYPTION_KEY` — primary key for encrypting plugin secrets at\n * rest. Multi-key (comma-separated) for rotation forward-compat. v1 ships\n * single-key. Format: `emdash_enc_v1_<43 base64url chars>` representing\n * 32 random bytes. **Operator-provided; never stored in the database.**\n * Losing the key means losing every secret encrypted with it. Validated\n * at runtime startup via `validateEncryptionKeyAtStartup` — request-time\n * resolution does not depend on it, so a malformed key can't 500 the\n * preview/comment hot paths for unrelated visitors.\n * - `EMDASH_IP_SALT` (optional) / DB-stored `emdash:ip_salt` — site-specific\n * salt for hashing commenter IPs. Generated and persisted on first need\n * if no env override is set. Replaces the previous hardcoded\n * `\"emdash-ip-salt\"` constant which was correlatable across installs.\n * - `EMDASH_PREVIEW_SECRET` (optional) / DB-stored `emdash:preview_secret` —\n * HMAC secret for signing preview URLs. Generated and persisted on first\n * need if no env override is set. Replaces the previous empty-string\n * fallback which silently disabled preview-token verification.\n *\n * The `EMDASH_AUTH_SECRET` env var is consulted only as a legacy fallback\n * source for the IP salt — that's the only path the prior code actually\n * read it from. New deployments don't need to set it.\n *\n * Modeled on `resolveS3Config` in `../storage/s3.ts`.\n */\n\nimport { sha256 } from \"@oslojs/crypto/sha2\";\nimport { encodeHexLowerCase } from \"@oslojs/encoding\";\nimport type { Kysely } from \"kysely\";\n\nimport { OptionsRepository } from \"../database/repositories/options.js\";\nimport type { Database } from \"../database/types.js\";\nimport { decodeBase64url, encodeBase64url } from \"../utils/base64.js\";\n\n/** v1 encryption key prefix. Bumping requires a separate KDF version. */\nexport const ENCRYPTION_KEY_PREFIX = \"emdash_enc_v1_\";\n\n/** 32 random bytes encoded as unpadded base64url = 43 chars. */\nconst ENCRYPTION_KEY_BODY_LENGTH = 43;\n\nconst REGEX_META_PATTERN = /[.*+?^${}()|[\\]\\\\]/g;\n\n/**\n * Built from the prefix constant via interpolation. The prefix has no regex\n * metacharacters today (`emdash_enc_v1_`), but escaping is cheap defense\n * against anyone changing the prefix in a future bump without remembering.\n */\nconst ENCRYPTION_KEY_PATTERN = new RegExp(\n\t`^${ENCRYPTION_KEY_PREFIX.replace(REGEX_META_PATTERN, \"\\\\$&\")}[A-Za-z0-9_-]{${ENCRYPTION_KEY_BODY_LENGTH}}$`,\n);\n\n/** Options-table key for the persisted commenter-IP salt. */\nexport const IP_SALT_OPTION_KEY = \"emdash:ip_salt\";\n\n/** Options-table key for the persisted preview HMAC secret. */\nexport const PREVIEW_SECRET_OPTION_KEY = \"emdash:preview_secret\";\n\n/** Length in bytes of generated values. 32 bytes = 256 bits. */\nconst GENERATED_SECRET_BYTES = 32;\n\n/**\n * A parsed encryption key with its kid (key id) fingerprint.\n *\n * `kid` is the first 8 chars of the SHA-256 hash of the decoded key bytes\n * (lowercase hex), used to tag envelopes so the decryptor can pick the right\n * key during rotation.\n */\nexport interface ParsedEncryptionKey {\n\t/** 8-char lowercase hex fingerprint derived from the decoded key bytes. */\n\tkid: string;\n\t/** The 32 raw key bytes, ready for `crypto.subtle.importKey`. */\n\tkey: Uint8Array;\n\t/** The original env-var-formatted string (kept for re-emit; never log). */\n\traw: string;\n}\n\n/** Resolved site secrets. */\nexport interface ResolvedSecrets {\n\t/** HMAC secret for preview URLs. Always non-empty after resolution. */\n\tpreviewSecret: string;\n\t/**\n\t * Source of `previewSecret`. Useful for diagnostics; never expose the\n\t * value itself, only the source.\n\t */\n\tpreviewSecretSource: \"env\" | \"db\";\n\t/** Salt for hashing commenter IPs. Always non-empty after resolution. */\n\tipSalt: string;\n\t/** Source of `ipSalt`. */\n\tipSaltSource: \"env\" | \"db\";\n}\n\n/** Inputs for `resolveSecrets`. */\nexport interface ResolveSecretsOptions {\n\t/**\n\t * The Kysely DB used to persist (and read back) generated salt/preview\n\t * secret values. Required — these values must be stable across requests\n\t * within a deployment.\n\t */\n\tdb: Kysely<Database>;\n\t/**\n\t * Optional explicit env override map. When omitted, falls back to\n\t * `import.meta.env` via the global accessor below. Tests pass an\n\t * explicit map to avoid leaking process state.\n\t */\n\tenv?: SecretsEnv;\n\t/**\n\t * @internal Test seam: inject a custom OptionsRepository to exercise\n\t * the lost-race re-read branch. Production callers never set this.\n\t */\n\t_repo?: OptionsRepository;\n}\n\n/** Environment-variable shape consulted by the resolver. */\nexport interface SecretsEnv {\n\t/**\n\t * Read by `validateEncryptionKeyAtStartup` and (in a follow-up PR) by the\n\t * plugin-secret encryption layer. **Not** consulted by `resolveSecrets`,\n\t * so a malformed value can't 500 the preview/comment hot paths.\n\t */\n\tEMDASH_ENCRYPTION_KEY?: string;\n\tEMDASH_PREVIEW_SECRET?: string;\n\t/** Legacy alias; new docs point at EMDASH_PREVIEW_SECRET. */\n\tPREVIEW_SECRET?: string;\n\tEMDASH_IP_SALT?: string;\n\t/**\n\t * Legacy fallback. Prior code derived the IP salt from\n\t * `EMDASH_AUTH_SECRET || AUTH_SECRET || \"emdash-ip-salt\"`. We preserve\n\t * the env-var fallback (so existing installs keep their stable salt)\n\t * but no longer read it from `import.meta.env` in route handlers.\n\t */\n\tEMDASH_AUTH_SECRET?: string;\n\t/** Legacy alias. */\n\tAUTH_SECRET?: string;\n}\n\n/**\n * Class of validation failures raised by this module.\n *\n * Errors here are operator-facing config problems (malformed key, etc.).\n * They are thrown rather than soft-skipped so misconfiguration fails loudly\n * at startup instead of silently degrading at request time.\n */\nexport class EmDashSecretsError extends Error {\n\toverride readonly name = \"EmDashSecretsError\";\n\treadonly code: string;\n\n\tconstructor(message: string, code: string) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Encryption key parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Parse the `EMDASH_ENCRYPTION_KEY` env var.\n *\n * Accepts a single key or a comma-separated list. The first entry is the\n * primary (used for new writes); all entries are tried for decryption,\n * matched by `kid`. Whitespace around commas is tolerated. Empty entries\n * (e.g. trailing comma) are ignored.\n *\n * Returns `null` for an unset/empty input. Throws `EmDashSecretsError` on\n * any malformed entry — silent skipping would mask deployment mistakes.\n */\nexport async function parseEncryptionKeys(\n\traw: string | undefined,\n): Promise<ParsedEncryptionKey[] | null> {\n\tif (!raw) return null;\n\n\tconst entries = raw\n\t\t.split(\",\")\n\t\t.map((entry) => entry.trim())\n\t\t.filter((entry) => entry.length > 0);\n\n\tif (entries.length === 0) return null;\n\n\tconst parsed: ParsedEncryptionKey[] = [];\n\tconst seenKids = new Set<string>();\n\n\tfor (const entry of entries) {\n\t\tif (!ENCRYPTION_KEY_PATTERN.test(entry)) {\n\t\t\tthrow new EmDashSecretsError(\n\t\t\t\t`EMDASH_ENCRYPTION_KEY entry is malformed (expected \"${ENCRYPTION_KEY_PREFIX}\" followed by ${ENCRYPTION_KEY_BODY_LENGTH} base64url chars). Generate one with \\`emdash secrets generate\\`.`,\n\t\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t\t);\n\t\t}\n\n\t\tconst body = entry.slice(ENCRYPTION_KEY_PREFIX.length);\n\t\tconst key = decodeBase64urlStrict(body);\n\t\tif (!key) {\n\t\t\tthrow new EmDashSecretsError(\n\t\t\t\t\"EMDASH_ENCRYPTION_KEY body is not valid base64url\",\n\t\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t\t);\n\t\t}\n\t\tif (key.length !== GENERATED_SECRET_BYTES) {\n\t\t\tthrow new EmDashSecretsError(\n\t\t\t\t`EMDASH_ENCRYPTION_KEY must decode to ${GENERATED_SECRET_BYTES} bytes, got ${key.length}`,\n\t\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t\t);\n\t\t}\n\n\t\t// Reject non-canonical base64url. 43 chars decode to 32 bytes but\n\t\t// the last char only carries 2 information bits — multiple raw\n\t\t// strings can decode to the same bytes. Forcing canonical form\n\t\t// guarantees `kid` (derived from bytes) is stable per key\n\t\t// material, regardless of how the operator pasted it.\n\t\tconst canonical = encodeBase64url(key);\n\t\tif (canonical !== body) {\n\t\t\tthrow new EmDashSecretsError(\n\t\t\t\t\"EMDASH_ENCRYPTION_KEY body is not canonical base64url. Generate one with `emdash secrets generate`.\",\n\t\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t\t);\n\t\t}\n\n\t\tconst kid = fingerprintKeyBytes(key);\n\t\tif (seenKids.has(kid)) {\n\t\t\t// Duplicate keys are user error (paste mistake during rotation).\n\t\t\t// We dedupe rather than throw — the rotation flow is forgiving.\n\t\t\tcontinue;\n\t\t}\n\t\tseenKids.add(kid);\n\t\tparsed.push({ kid, key, raw: entry });\n\t}\n\n\t// `parsed` always has at least one entry here: `entries` was non-empty\n\t// after filtering, the loop runs at least once, the first iteration\n\t// always passes the empty-`seenKids` check.\n\treturn parsed;\n}\n\n/**\n * Compute the kid for a raw key string (the env-var form including the\n * `emdash_enc_v1_` prefix). Public so the CLI's `fingerprint` subcommand\n * and admin endpoints can show kids without exposing raw keys.\n *\n * The kid is derived from the decoded key **bytes**, not the raw string,\n * so admin endpoints / future rotation flows can match envelope kids\n * against bytes regardless of how the env var was originally spelled.\n *\n * Validates the same shape as `parseEncryptionKeys` — including canonical\n * base64url — so the CLI can't print a kid for a key the runtime would\n * later refuse to load.\n *\n * Throws `EmDashSecretsError` for malformed or non-canonical input.\n */\nexport async function fingerprintKey(raw: string): Promise<string> {\n\tif (!ENCRYPTION_KEY_PATTERN.test(raw)) {\n\t\tthrow new EmDashSecretsError(\n\t\t\t`Key must match \"${ENCRYPTION_KEY_PREFIX}\" followed by ${ENCRYPTION_KEY_BODY_LENGTH} base64url chars`,\n\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t);\n\t}\n\tconst body = raw.slice(ENCRYPTION_KEY_PREFIX.length);\n\tconst bytes = decodeBase64urlStrict(body);\n\tif (!bytes || bytes.length !== GENERATED_SECRET_BYTES || encodeBase64url(bytes) !== body) {\n\t\tthrow new EmDashSecretsError(\n\t\t\t`Key body must decode to ${GENERATED_SECRET_BYTES} canonical base64url bytes`,\n\t\t\t\"INVALID_ENCRYPTION_KEY\",\n\t\t);\n\t}\n\treturn fingerprintKeyBytes(bytes);\n}\n\n/**\n * Internal: kid derivation from raw key bytes. The single source of truth\n * for what makes two keys \"the same key\" — used by both `parseEncryptionKeys`\n * and `fingerprintKey`.\n */\nfunction fingerprintKeyBytes(key: Uint8Array): string {\n\treturn encodeHexLowerCase(sha256(key)).slice(0, 8);\n}\n\n/**\n * Generate a fresh `EMDASH_ENCRYPTION_KEY` value. Used by the CLI's\n * `secrets generate` subcommand and by `create-emdash` scaffolding.\n */\nexport function generateEncryptionKey(): string {\n\tconst bytes = new Uint8Array(GENERATED_SECRET_BYTES);\n\tcrypto.getRandomValues(bytes);\n\treturn `${ENCRYPTION_KEY_PREFIX}${encodeBase64url(bytes)}`;\n}\n\n// ---------------------------------------------------------------------------\n// Site-secret resolution (DB-backed with env override)\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve site secrets. Reads env vars; for IP salt and preview secret,\n * falls back to a DB-stored value, generating one atomically on first need.\n *\n * Idempotent. Concurrent callers race on the atomic `setIfAbsent`; whichever\n * wins, all callers converge on the same stored value.\n *\n * Note: `EMDASH_ENCRYPTION_KEY` is **not** consumed here. It's validated\n * separately at runtime startup (see `validateEncryptionKeyAtStartup`) so a\n * malformed key can't take down preview-token verification or comment\n * submission for unrelated visitors. Future plugin-secret encryption code\n * will read it via its own dedicated helper.\n */\nexport async function resolveSecrets(options: ResolveSecretsOptions): Promise<ResolvedSecrets> {\n\tconst env = options.env ?? readDefaultEnv();\n\tconst repo = options._repo ?? new OptionsRepository(options.db);\n\n\tconst previewEnvOverride = pickFirstNonEmpty(env.EMDASH_PREVIEW_SECRET, env.PREVIEW_SECRET);\n\tconst ipSaltEnvOverride = pickFirstNonEmpty(\n\t\tenv.EMDASH_IP_SALT,\n\t\tenv.EMDASH_AUTH_SECRET,\n\t\tenv.AUTH_SECRET,\n\t);\n\n\tconst [previewSecret, ipSalt] = await Promise.all([\n\t\tpreviewEnvOverride !== null\n\t\t\t? Promise.resolve({ value: previewEnvOverride, source: \"env\" as const })\n\t\t\t: ensureGeneratedOption(repo, PREVIEW_SECRET_OPTION_KEY),\n\t\tipSaltEnvOverride !== null\n\t\t\t? Promise.resolve({ value: ipSaltEnvOverride, source: \"env\" as const })\n\t\t\t: ensureGeneratedOption(repo, IP_SALT_OPTION_KEY),\n\t]);\n\n\treturn {\n\t\tpreviewSecret: previewSecret.value,\n\t\tpreviewSecretSource: previewSecret.source,\n\t\tipSalt: ipSalt.value,\n\t\tipSaltSource: ipSalt.source,\n\t};\n}\n\n/**\n * Validate `EMDASH_ENCRYPTION_KEY` once at runtime startup. Logs an\n * operator-facing error if the value is malformed but does **not** throw —\n * the key is currently inert (no consumers), and the follow-up PR that\n * actually uses it will throw at point of use. This way, deployment\n * mistakes surface immediately in startup logs without wedging unrelated\n * request paths in the meantime.\n *\n * Returns `true` if the key is unset or valid, `false` if it was malformed.\n */\nexport async function validateEncryptionKeyAtStartup(env?: SecretsEnv): Promise<boolean> {\n\tconst resolved = env ?? readDefaultEnv();\n\ttry {\n\t\tawait parseEncryptionKeys(resolved.EMDASH_ENCRYPTION_KEY);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error instanceof EmDashSecretsError) {\n\t\t\tconsole.error(\n\t\t\t\t`[emdash] EMDASH_ENCRYPTION_KEY is invalid: ${error.message} ` +\n\t\t\t\t\t\"Plugin-secret encryption will fail once it ships. \" +\n\t\t\t\t\t\"Generate a fresh key with `emdash secrets generate`.\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Per-DB cache of resolved secrets, keyed by Kysely instance identity.\n *\n * The resolved values are stable for the lifetime of the deployment (env\n * vars don't change without a restart, and DB-stored values are written\n * once via `setIfAbsent`). Caching avoids one options-table read per\n * request on the hot paths (preview verification, comment hashing).\n *\n * Lives on `globalThis` so module-duplication during SSR bundling can't\n * fragment the cache. See `request-context.ts` for the same pattern.\n */\n// Versioned to prevent cache fragmentation if `ResolvedSecrets`'s shape\n// ever changes. Bump the suffix on incompatible changes so a co-resident\n// older build doesn't read a newer-shape value.\nconst SECRETS_CACHE_KEY = Symbol.for(\"@emdash-cms/core/secrets-cache@1\");\n\ninterface SecretsCacheHolder {\n\tcache: WeakMap<Kysely<Database>, Promise<ResolvedSecrets>>;\n}\n\nfunction getSecretsCache(): WeakMap<Kysely<Database>, Promise<ResolvedSecrets>> {\n\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- globalThis singleton pattern\n\tconst holder = globalThis as Record<symbol, SecretsCacheHolder | undefined>;\n\tlet entry = holder[SECRETS_CACHE_KEY];\n\tif (!entry) {\n\t\tentry = { cache: new WeakMap() };\n\t\tholder[SECRETS_CACHE_KEY] = entry;\n\t}\n\treturn entry.cache;\n}\n\n/**\n * Memoized wrapper around `resolveSecrets`. Use this from request-time hot\n * paths (preview verification, comment IP hashing) so they don't reread\n * env / re-query options on every request.\n *\n * The cache is keyed by `Kysely` instance, so playground / per-DO / per-test\n * databases each get their own resolution.\n */\nexport function resolveSecretsCached(db: Kysely<Database>): Promise<ResolvedSecrets> {\n\tconst cache = getSecretsCache();\n\tconst cached = cache.get(db);\n\tif (cached) return cached;\n\tconst promise = resolveSecrets({ db }).catch((error) => {\n\t\t// Don't poison the cache on transient failure; next caller retries.\n\t\tcache.delete(db);\n\t\tthrow error;\n\t});\n\tcache.set(db, promise);\n\treturn promise;\n}\n\n/**\n * Test-only helper: clear the secrets cache. Tests that mutate env between\n * cases need this so a stale resolution doesn't leak across cases.\n *\n * @internal\n */\nexport function _clearSecretsCacheForTesting(): void {\n\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- globalThis singleton pattern\n\tconst holder = globalThis as Record<symbol, SecretsCacheHolder | undefined>;\n\tholder[SECRETS_CACHE_KEY] = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\n/**\n * Read or generate-and-persist a random base64url secret stored in the\n * options table.\n *\n * Concurrency: `setIfAbsent` is an atomic INSERT...ON CONFLICT DO NOTHING.\n * On race, the loser re-reads to converge on the winner's value.\n */\nasync function ensureGeneratedOption(\n\trepo: OptionsRepository,\n\toptionKey: string,\n): Promise<{ value: string; source: \"db\" }> {\n\tconst existing = await repo.get<string>(optionKey);\n\tif (typeof existing === \"string\" && existing.length > 0) {\n\t\treturn { value: existing, source: \"db\" };\n\t}\n\n\tconst generated = generateRandomSecret();\n\tconst inserted = await repo.setIfAbsent(optionKey, generated);\n\tif (inserted) {\n\t\treturn { value: generated, source: \"db\" };\n\t}\n\n\t// Lost the race — another process inserted first. Re-read to pick up\n\t// the winner. If the row is somehow still missing or empty, treat that\n\t// as a real error rather than looping.\n\tconst winner = await repo.get<string>(optionKey);\n\tif (typeof winner !== \"string\" || winner.length === 0) {\n\t\tthrow new EmDashSecretsError(\n\t\t\t`Failed to persist generated secret for \"${optionKey}\"`,\n\t\t\t\"SECRET_PERSIST_FAILED\",\n\t\t);\n\t}\n\treturn { value: winner, source: \"db\" };\n}\n\n/** Generate 32 random bytes encoded as unpadded base64url. */\nfunction generateRandomSecret(): string {\n\tconst bytes = new Uint8Array(GENERATED_SECRET_BYTES);\n\tcrypto.getRandomValues(bytes);\n\treturn encodeBase64url(bytes);\n}\n\n/** Return the first non-empty string from `values`, or `null` if all are empty. */\nfunction pickFirstNonEmpty(...values: (string | undefined)[]): string | null {\n\tfor (const value of values) {\n\t\tif (typeof value === \"string\" && value.length > 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn null;\n}\n\nconst BASE64URL_CHARSET_PATTERN = /^[A-Za-z0-9_-]+$/;\n\n/**\n * Validate base64url shape and decode. Returns `null` on malformed input\n * (rather than throwing) so the caller can produce a config-specific error.\n */\nfunction decodeBase64urlStrict(input: string): Uint8Array | null {\n\t// `decodeBase64url` accepts padded input too; the env-var format is\n\t// strictly unpadded base64url, so we do a charset check first.\n\tif (!BASE64URL_CHARSET_PATTERN.test(input)) return null;\n\ttry {\n\t\treturn decodeBase64url(input);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Default env reader.\n *\n * Note: this is the **only** code path in core that reads both\n * `import.meta.env` and `process.env`. Route handlers should not — they\n * always run inside the Astro/Vite bundle where `import.meta.env` is\n * the correct source. This resolver is shared with the CLI surface (via\n * `cli/commands/secrets.ts`) which runs outside the bundle, so we\n * deliberately consult both. `import.meta.env` wins so build-time\n * substitutions are honored when present.\n *\n * The convention documented in AGENTS.md (\"import.meta.env.EMDASH_X ||\n * import.meta.env.X\") is the route-handler convention; this is the\n * shared-with-CLI exception.\n */\nfunction readDefaultEnv(): SecretsEnv {\n\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- import.meta.env is loose by design\n\tconst meta = (import.meta.env ?? {}) as Record<string, string | undefined>;\n\tconst proc = typeof process !== \"undefined\" && process.env ? process.env : {};\n\n\treturn {\n\t\tEMDASH_ENCRYPTION_KEY: meta.EMDASH_ENCRYPTION_KEY ?? proc.EMDASH_ENCRYPTION_KEY,\n\t\tEMDASH_PREVIEW_SECRET: meta.EMDASH_PREVIEW_SECRET ?? proc.EMDASH_PREVIEW_SECRET,\n\t\tPREVIEW_SECRET: meta.PREVIEW_SECRET ?? proc.PREVIEW_SECRET,\n\t\tEMDASH_IP_SALT: meta.EMDASH_IP_SALT ?? proc.EMDASH_IP_SALT,\n\t\tEMDASH_AUTH_SECRET: meta.EMDASH_AUTH_SECRET ?? proc.EMDASH_AUTH_SECRET,\n\t\tAUTH_SECRET: meta.AUTH_SECRET ?? proc.AUTH_SECRET,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,wBAAwB;;AAGrC,MAAM,6BAA6B;;;;;;AASnC,MAAM,yBAAyB,IAAI,OAClC,IAAI,sBAAsB,QARA,uBAQ4B,OAAO,CAAC,gBAAgB,2BAA2B,IACzG;;AAGD,MAAa,qBAAqB;;AAGlC,MAAa,4BAA4B;;AAGzC,MAAM,yBAAyB;;;;;;;;AAoF/B,IAAa,qBAAb,cAAwC,MAAM;CAC7C,AAAkB,O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AAGhE,KAAI,CAAC,0BAA0B,KAAK,MAAM,CAAE,QAAO;AACnD,KAAI;AACH,SAAO,gBAAgB,MAAM;SACtB;AACP,SAAO;;;;;;;;;;;;;;;;;;AAmBT,SAAS,iBAA6B;CAErC,MAAM,OAAQ,OAAO,KAAK,OAAO,EAAE;CACnC,MAAM,OAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE;AAE7E,QAAO;EACN,uBAAuB,KAAK,yBAAyB,KAAK;EAC1D,uBAAuB,KAAK,yBAAyB,KAAK;EAC1D,gBAAgB,KAAK,kBAAkB,KAAK;EAC5C,gBAAgB,KAAK,kBAAkB,KAAK;EAC5C,oBAAoB,KAAK,sBAAsB,KAAK;EACpD,aAAa,KAAK,eAAe,KAAK;EACtC"}
@@ -1,3 +1,3 @@
1
- import "../types-C2v0c34j.mjs";
2
- import { _ as SeedTaxonomyTerm, a as applySeed, b as ValidationResult, c as SeedCollection, d as SeedFile, f as SeedMenu, g as SeedTaxonomy, h as SeedSection, i as defaultSeed, l as SeedContentEntry, m as SeedRedirect, n as loadSeed, o as SeedApplyOptions, p as SeedMenuItem, r as loadUserSeed, s as SeedApplyResult, t as validateSeed, u as SeedField, v as SeedWidget, y as SeedWidgetArea } from "../validate-kM8Pjuf7.mjs";
1
+ import "../types-CrtWgIvl.mjs";
2
+ import { _ as SeedTaxonomyTerm, a as applySeed, b as ValidationResult, c as SeedCollection, d as SeedFile, f as SeedMenu, g as SeedTaxonomy, h as SeedSection, i as defaultSeed, l as SeedContentEntry, m as SeedRedirect, n as loadSeed, o as SeedApplyOptions, p as SeedMenuItem, r as loadUserSeed, s as SeedApplyResult, t as validateSeed, u as SeedField, v as SeedWidget, y as SeedWidgetArea } from "../validate-BfQh_C_y.mjs";
3
3
  export { type SeedApplyOptions, type SeedApplyResult, type SeedCollection, type SeedContentEntry, type SeedField, type SeedFile, type SeedMenu, type SeedMenuItem, type SeedRedirect, type SeedSection, type SeedTaxonomy, type SeedTaxonomyTerm, type SeedWidget, type SeedWidgetArea, type ValidationResult, applySeed, defaultSeed, loadSeed, loadUserSeed, validateSeed };
@@ -1,16 +1,17 @@
1
- import "../dialect-helpers-DhTzaUxP.mjs";
2
- import "../content-D7J5y73J.mjs";
3
- import "../base64-MBPo9ozB.mjs";
4
- import "../types-CMMN0pNg.mjs";
5
- import "../media-DqHVh136.mjs";
6
- import { t as applySeed } from "../apply-5uslYdUu.mjs";
7
- import "../redirect-CN0Rt9Ob.mjs";
8
- import "../byline-C4OVd8b3.mjs";
9
- import "../registry-Ci3WxVAr.mjs";
10
- import "../loader-DeiBJEMe.mjs";
11
- import "../request-cache-DiR961CV.mjs";
12
- import { t as validateSeed } from "../validate-CqsNItbt.mjs";
13
- import { t as defaultSeed } from "../default-CME5YdZ3.mjs";
14
- import { n as loadUserSeed, t as loadSeed } from "../load-CBcmDIot.mjs";
1
+ import "../dialect-helpers-BKCvISIQ.mjs";
2
+ import "../content-8lOYF0pr.mjs";
3
+ import "../base64-BRICGH2l.mjs";
4
+ import "../types-CRxNbK-Z.mjs";
5
+ import "../media-BW32b4gi.mjs";
6
+ import { t as applySeed } from "../apply-BzltprvY.mjs";
7
+ import "../options-BVp3UsTS.mjs";
8
+ import "../redirect-BhUBKRc1.mjs";
9
+ import "../byline-BSaNL1w7.mjs";
10
+ import "../registry-Dw70ChxB.mjs";
11
+ import "../loader-CKLbBnhK.mjs";
12
+ import "../request-cache-B-bmkipQ.mjs";
13
+ import { t as validateSeed } from "../validate-Baqf0slj.mjs";
14
+ import { t as defaultSeed } from "../default-D8ksjWhO.mjs";
15
+ import { n as loadUserSeed, t as loadSeed } from "../load-DDqMMvZL.mjs";
15
16
 
16
17
  export { applySeed, defaultSeed, loadSeed, loadUserSeed, validateSeed };
@@ -1,4 +1,4 @@
1
- import { i as ContentSeo } from "../types-6CUZRrZP.mjs";
1
+ import { i as ContentSeo } from "../types-CJsYGpco.mjs";
2
2
 
3
3
  //#region src/seo/index.d.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-CFWjXmus.mjs";
1
+ import { a as ListOptions, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, s as LocalStorageConfig, u as SignedUploadUrl } from "../types-M78DQ1lx.mjs";
2
2
 
3
3
  //#region src/storage/local.d.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { t as EmDashStorageError } from "../types-BH2L167P.mjs";
1
+ import { t as EmDashStorageError } from "../types-CDbKp7ND.mjs";
2
2
  import mime from "mime/lite";
3
3
  import * as path from "node:path";
4
4
  import { createReadStream, existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-CFWjXmus.mjs";
1
+ import { a as ListOptions, c as S3StorageConfig, d as Storage, l as SignedUploadOptions, n as DownloadResult, o as ListResult, p as UploadResult, u as SignedUploadUrl } from "../types-M78DQ1lx.mjs";
2
2
 
3
3
  //#region src/storage/s3.d.ts
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"s3.d.mts","names":[],"sources":["../../src/storage/s3.ts"],"mappings":";;;;;;;;AA0HA;iBA3DgB,eAAA,CAAgB,OAAA,EAAS,MAAA,oBAA0B,eAAA;;;;cA2DtD,SAAA,YAAqB,OAAA;EAAA,QACzB,MAAA;EAAA,QACA,MAAA;EAAA,QACA,SAAA;EAAA,QACA,QAAA;cAEI,MAAA,EAAQ,eAAA;EAqBd,MAAA,CAAO,OAAA;IACZ,GAAA;IACA,IAAA,EAAM,MAAA,GAAS,UAAA,GAAa,cAAA,CAAe,UAAA;IAC3C,WAAA;EAAA,IACG,OAAA,CAAQ,YAAA;EAoCN,QAAA,CAAS,GAAA,WAAc,OAAA,CAAQ,cAAA;EAgC/B,MAAA,CAAO,GAAA,WAAc,OAAA;EAgBrB,MAAA,CAAO,GAAA,WAAc,OAAA;EAiBrB,IAAA,CAAK,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,UAAA;EA4BzC,kBAAA,CAAmB,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,eAAA;EAiChE,YAAA,CAAa,GAAA;AAAA;;;;;;iBAcE,aAAA,CAAc,MAAA,EAAQ,MAAA,oBAA0B,OAAA"}
1
+ {"version":3,"file":"s3.d.mts","names":[],"sources":["../../src/storage/s3.ts"],"mappings":";;;;;;;;AA2HA;iBA3DgB,eAAA,CAAgB,OAAA,EAAS,MAAA,oBAA0B,eAAA;;;;cA2DtD,SAAA,YAAqB,OAAA;EAAA,QACzB,MAAA;EAAA,QACA,MAAA;EAAA,QACA,SAAA;EAAA,QACA,QAAA;cAEI,MAAA,EAAQ,eAAA;EA0Bd,MAAA,CAAO,OAAA;IACZ,GAAA;IACA,IAAA,EAAM,MAAA,GAAS,UAAA,GAAa,cAAA,CAAe,UAAA;IAC3C,WAAA;EAAA,IACG,OAAA,CAAQ,YAAA;EAoCN,QAAA,CAAS,GAAA,WAAc,OAAA,CAAQ,cAAA;EAgC/B,MAAA,CAAO,GAAA,WAAc,OAAA;EAgBrB,MAAA,CAAO,GAAA,WAAc,OAAA;EAiBrB,IAAA,CAAK,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,UAAA;EA4BzC,kBAAA,CAAmB,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,eAAA;EAiChE,YAAA,CAAa,GAAA;AAAA;;;;;;iBAcE,aAAA,CAAc,MAAA,EAAQ,MAAA,oBAA0B,OAAA"}
@@ -1,4 +1,4 @@
1
- import { t as EmDashStorageError } from "../types-BH2L167P.mjs";
1
+ import { t as EmDashStorageError } from "../types-CDbKp7ND.mjs";
2
2
  import { z } from "zod";
3
3
  import { DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
4
4
  import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
@@ -98,11 +98,11 @@ var S3Storage = class {
98
98
  this.client = new S3Client({
99
99
  endpoint: config.endpoint,
100
100
  region: config.region || "auto",
101
+ forcePathStyle: true,
101
102
  ...config.accessKeyId && config.secretAccessKey ? { credentials: {
102
103
  accessKeyId: config.accessKeyId,
103
104
  secretAccessKey: config.secretAccessKey
104
- } } : {},
105
- forcePathStyle: true
105
+ } } : {}
106
106
  });
107
107
  }
108
108
  async upload(options) {
@@ -219,7 +219,7 @@ var S3Storage = class {
219
219
  }
220
220
  getPublicUrl(key) {
221
221
  if (this.publicUrl) return `${this.publicUrl.replace(TRAILING_SLASH_PATTERN, "")}/${key}`;
222
- return `${this.endpoint.replace(TRAILING_SLASH_PATTERN, "")}/${this.bucket}/${key}`;
222
+ return `/_emdash/api/media/file/${key}`;
223
223
  }
224
224
  };
225
225
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"s3.mjs","names":[],"sources":["../../src/storage/s3.ts"],"sourcesContent":["/**\n * S3-Compatible Storage Implementation\n *\n * Uses the AWS SDK v3 for S3 operations.\n * Works with AWS S3, Cloudflare R2, Minio, and other S3-compatible services.\n */\n\nimport {\n\tS3Client,\n\tPutObjectCommand,\n\tGetObjectCommand,\n\tDeleteObjectCommand,\n\tHeadObjectCommand,\n\tListObjectsV2Command,\n\ttype ListObjectsV2Response,\n} from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { z } from \"zod\";\n\nimport type {\n\tStorage,\n\tS3StorageConfig,\n\tUploadResult,\n\tDownloadResult,\n\tListResult,\n\tListOptions,\n\tSignedUploadUrl,\n\tSignedUploadOptions,\n} from \"./types.js\";\nimport { EmDashStorageError } from \"./types.js\";\n\nconst ENV_KEYS = {\n\tendpoint: \"S3_ENDPOINT\",\n\tbucket: \"S3_BUCKET\",\n\taccessKeyId: \"S3_ACCESS_KEY_ID\",\n\tsecretAccessKey: \"S3_SECRET_ACCESS_KEY\",\n\tregion: \"S3_REGION\",\n\tpublicUrl: \"S3_PUBLIC_URL\",\n} as const satisfies Record<keyof S3StorageConfig, string>;\n\nfunction fail(msg: string): never {\n\tthrow new EmDashStorageError(msg, \"MISSING_S3_CONFIG\");\n}\n\nconst s3ConfigSchema = z.object({\n\tendpoint: z.url({ protocol: /^https?$/, error: \"is not a valid http/https URL\" }).optional(),\n\tbucket: z.string().optional(),\n\taccessKeyId: z.string().optional(),\n\tsecretAccessKey: z.string().optional(),\n\tregion: z.string().optional(),\n\tpublicUrl: z.string().optional(),\n});\n\nfunction isConfigKey(key: unknown): key is keyof S3StorageConfig {\n\treturn typeof key === \"string\" && key in ENV_KEYS;\n}\n\n/**\n * Build the merged config: for each field, use the explicit value if present,\n * otherwise fall back to the corresponding S3_* env var. Validate once on the\n * final merged result so a malformed env var never breaks the build when the\n * caller provides that field explicitly.\n */\nexport function resolveS3Config(partial: Record<string, unknown>): S3StorageConfig {\n\tconst raw: Record<string, unknown> = {};\n\tfor (const [field, envKey] of Object.entries(ENV_KEYS)) {\n\t\tconst explicit = partial[field];\n\t\tif (explicit !== undefined && explicit !== \"\") {\n\t\t\traw[field] = explicit;\n\t\t\tcontinue;\n\t\t}\n\t\tconst envVal = typeof process !== \"undefined\" && process.env ? process.env[envKey] : undefined;\n\t\tif (envVal !== undefined && envVal !== \"\") {\n\t\t\traw[field] = envVal;\n\t\t}\n\t}\n\n\tconst result = s3ConfigSchema.safeParse(raw);\n\tif (!result.success) {\n\t\tconst issue = result.error.issues[0];\n\t\tconst pathKey = issue?.path[0];\n\t\tif (!issue || !isConfigKey(pathKey)) fail(\"S3 config validation failed\");\n\t\tconst fromExplicit = partial[pathKey] !== undefined && partial[pathKey] !== \"\";\n\t\tconst label = fromExplicit ? `s3({ ${pathKey} })` : ENV_KEYS[pathKey];\n\t\tfail(`${label} ${issue.message}`);\n\t}\n\tconst merged = result.data;\n\n\tconst endpoint = merged.endpoint;\n\tconst bucket = merged.bucket;\n\tif (!endpoint || !bucket) {\n\t\tconst missing: string[] = [];\n\t\tif (!endpoint) missing.push(`endpoint: set ${ENV_KEYS.endpoint} or pass endpoint to s3({...})`);\n\t\tif (!bucket) missing.push(`bucket: set ${ENV_KEYS.bucket} or pass bucket to s3({...})`);\n\t\tfail(`missing required S3 config: ${missing.join(\"; \")}`);\n\t}\n\tconst accessKeyId = merged.accessKeyId;\n\tconst secretAccessKey = merged.secretAccessKey;\n\tif (accessKeyId && !secretAccessKey) {\n\t\tfail(\n\t\t\t`S3 credentials incomplete: accessKeyId is set but secretAccessKey is missing (set ${ENV_KEYS.secretAccessKey} or pass secretAccessKey to s3({...}))`,\n\t\t);\n\t}\n\tif (secretAccessKey && !accessKeyId) {\n\t\tfail(\n\t\t\t`S3 credentials incomplete: secretAccessKey is set but accessKeyId is missing (set ${ENV_KEYS.accessKeyId} or pass accessKeyId to s3({...}))`,\n\t\t);\n\t}\n\n\treturn { ...merged, endpoint, bucket };\n}\n\nconst TRAILING_SLASH_PATTERN = /\\/$/;\n\n/** Type guard for AWS SDK errors (have a `name` property) */\nfunction hasErrorName(error: unknown): error is Error & { name: string } {\n\treturn error instanceof Error && typeof error.name === \"string\";\n}\n\n/**\n * S3-compatible storage implementation\n */\nexport class S3Storage implements Storage {\n\tprivate client: S3Client;\n\tprivate bucket: string;\n\tprivate publicUrl?: string;\n\tprivate endpoint: string;\n\n\tconstructor(config: S3StorageConfig) {\n\t\tthis.bucket = config.bucket;\n\t\tthis.publicUrl = config.publicUrl;\n\t\tthis.endpoint = config.endpoint;\n\n\t\tthis.client = new S3Client({\n\t\t\tendpoint: config.endpoint,\n\t\t\tregion: config.region || \"auto\",\n\t\t\t...(config.accessKeyId && config.secretAccessKey\n\t\t\t\t? {\n\t\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t\taccessKeyId: config.accessKeyId,\n\t\t\t\t\t\t\tsecretAccessKey: config.secretAccessKey,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// Required for R2 and some S3-compatible services\n\t\t\tforcePathStyle: true,\n\t\t} as ConstructorParameters<typeof S3Client>[0]);\n\t}\n\n\tasync upload(options: {\n\t\tkey: string;\n\t\tbody: Buffer | Uint8Array | ReadableStream<Uint8Array>;\n\t\tcontentType: string;\n\t}): Promise<UploadResult> {\n\t\ttry {\n\t\t\t// Convert ReadableStream to Buffer if needed\n\t\t\tlet body: Buffer | Uint8Array;\n\t\t\tif (options.body instanceof ReadableStream) {\n\t\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\t\tconst reader = options.body.getReader();\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tchunks.push(value);\n\t\t\t\t}\n\t\t\t\tbody = Buffer.concat(chunks);\n\t\t\t} else {\n\t\t\t\tbody = options.body;\n\t\t\t}\n\n\t\t\tawait this.client.send(\n\t\t\t\tnew PutObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: options.key,\n\t\t\t\t\tBody: body,\n\t\t\t\t\tContentType: options.contentType,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tkey: options.key,\n\t\t\t\turl: this.getPublicUrl(options.key),\n\t\t\t\tsize: body.length,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(`Failed to upload file: ${options.key}`, \"UPLOAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync download(key: string): Promise<DownloadResult> {\n\t\ttry {\n\t\t\tconst response = await this.client.send(\n\t\t\t\tnew GetObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tif (!response.Body) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\");\n\t\t\t}\n\n\t\t\t// Convert SDK stream to web ReadableStream\n\t\t\tconst body = response.Body.transformToWebStream();\n\n\t\t\treturn {\n\t\t\t\tbody,\n\t\t\t\tcontentType: response.ContentType || \"application/octet-stream\",\n\t\t\t\tsize: response.ContentLength || 0,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof EmDashStorageError ||\n\t\t\t\t(hasErrorName(error) && error.name === \"NoSuchKey\")\n\t\t\t) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\", error);\n\t\t\t}\n\t\t\tthrow new EmDashStorageError(`Failed to download file: ${key}`, \"DOWNLOAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.client.send(\n\t\t\t\tnew DeleteObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// S3 delete is idempotent, so we ignore \"not found\" errors\n\t\t\tif (!hasErrorName(error) || error.name !== \"NoSuchKey\") {\n\t\t\t\tthrow new EmDashStorageError(`Failed to delete file: ${key}`, \"DELETE_FAILED\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync exists(key: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait this.client.send(\n\t\t\t\tnew HeadObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (hasErrorName(error) && error.name === \"NotFound\") {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow new EmDashStorageError(`Failed to check file existence: ${key}`, \"HEAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync list(options: ListOptions = {}): Promise<ListResult> {\n\t\ttry {\n\t\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- S3 client.send returns generic output; narrowing to ListObjectsV2Response\n\t\t\tconst response = (await this.client.send(\n\t\t\t\tnew ListObjectsV2Command({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tPrefix: options.prefix,\n\t\t\t\t\tMaxKeys: options.limit,\n\t\t\t\t\tContinuationToken: options.cursor,\n\t\t\t\t}),\n\t\t\t)) as ListObjectsV2Response;\n\n\t\t\treturn {\n\t\t\t\tfiles: (response.Contents || []).map(\n\t\t\t\t\t(item: { Key?: string; Size?: number; LastModified?: Date; ETag?: string }) => ({\n\t\t\t\t\t\tkey: item.Key!,\n\t\t\t\t\t\tsize: item.Size || 0,\n\t\t\t\t\t\tlastModified: item.LastModified || new Date(),\n\t\t\t\t\t\tetag: item.ETag,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tnextCursor: response.NextContinuationToken,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(\"Failed to list files\", \"LIST_FAILED\", error);\n\t\t}\n\t}\n\n\tasync getSignedUploadUrl(options: SignedUploadOptions): Promise<SignedUploadUrl> {\n\t\ttry {\n\t\t\tconst expiresIn = options.expiresIn || 3600; // 1 hour default\n\n\t\t\tconst command = new PutObjectCommand({\n\t\t\t\tBucket: this.bucket,\n\t\t\t\tKey: options.key,\n\t\t\t\tContentType: options.contentType,\n\t\t\t\tContentLength: options.size,\n\t\t\t});\n\n\t\t\tconst url = await getSignedUrl(this.client, command, { expiresIn });\n\n\t\t\tconst expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();\n\n\t\t\treturn {\n\t\t\t\turl,\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": options.contentType,\n\t\t\t\t\t...(options.size ? { \"Content-Length\": String(options.size) } : {}),\n\t\t\t\t},\n\t\t\t\texpiresAt,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(\n\t\t\t\t`Failed to generate signed URL for: ${options.key}`,\n\t\t\t\t\"SIGNED_URL_FAILED\",\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\t}\n\n\tgetPublicUrl(key: string): string {\n\t\tif (this.publicUrl) {\n\t\t\treturn `${this.publicUrl.replace(TRAILING_SLASH_PATTERN, \"\")}/${key}`;\n\t\t}\n\t\t// Default to endpoint + bucket + key\n\t\treturn `${this.endpoint.replace(TRAILING_SLASH_PATTERN, \"\")}/${this.bucket}/${key}`;\n\t}\n}\n\n/**\n * Create S3 storage adapter\n * This is the factory function called at runtime.\n * Config fields are merged with S3_* env vars; env vars fill in any missing fields.\n */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\treturn new S3Storage(resolveS3Config(config));\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,WAAW;CAChB,UAAU;CACV,QAAQ;CACR,aAAa;CACb,iBAAiB;CACjB,QAAQ;CACR,WAAW;CACX;AAED,SAAS,KAAK,KAAoB;AACjC,OAAM,IAAI,mBAAmB,KAAK,oBAAoB;;AAGvD,MAAM,iBAAiB,EAAE,OAAO;CAC/B,UAAU,EAAE,IAAI;EAAE,UAAU;EAAY,OAAO;EAAiC,CAAC,CAAC,UAAU;CAC5F,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,aAAa,EAAE,QAAQ,CAAC,UAAU;CAClC,iBAAiB,EAAE,QAAQ,CAAC,UAAU;CACtC,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,WAAW,EAAE,QAAQ,CAAC,UAAU;CAChC,CAAC;AAEF,SAAS,YAAY,KAA4C;AAChE,QAAO,OAAO,QAAQ,YAAY,OAAO;;;;;;;;AAS1C,SAAgB,gBAAgB,SAAmD;CAClF,MAAM,MAA+B,EAAE;AACvC,MAAK,MAAM,CAAC,OAAO,WAAW,OAAO,QAAQ,SAAS,EAAE;EACvD,MAAM,WAAW,QAAQ;AACzB,MAAI,aAAa,UAAa,aAAa,IAAI;AAC9C,OAAI,SAAS;AACb;;EAED,MAAM,SAAS,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,IAAI,UAAU;AACrF,MAAI,WAAW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MAAM,YAAY,IAAI,KAAK,KAAK,KAAK,GAAG,YAAY,IAAK,CAAC,aAAa;AAEvE,UAAO;IACN;IACA,QAAQ;IACR,SAAS;KACR,gBAAgB,QAAQ;KACxB,GAAI,QAAQ,OAAO,EAAE,kBAAkB,OAAO,QAAQ,KAAK,EAAE,GAAG,EAAE;KAClE;IACD;IACA;WACO,OAAO;AACf,SAAM,IAAI,mBACT,sCAAsC,QAAQ,OAC9C,qBACA,MACA;;;CAIH,aAAa,KAAqB;AACjC,MAAI,KAAK,UACR,QAAO,GAAG,KAAK,UAAU,QAAQ,wBAAwB,GAAG,CAAC,GAAG;AAGjE,SAAO,GAAG,KAAK,SAAS,QAAQ,wBAAwB,GAAG,CAAC,GAAG,KAAK,OAAO,GAAG;;;;;;;;AAShF,SAAgB,cAAc,QAA0C;AACvE,QAAO,IAAI,UAAU,gBAAgB,OAAO,CAAC"}
1
+ {"version":3,"file":"s3.mjs","names":[],"sources":["../../src/storage/s3.ts"],"sourcesContent":["/**\n * S3-Compatible Storage Implementation\n *\n * Uses the AWS SDK v3 for S3 operations.\n * Works with AWS S3, Cloudflare R2, Minio, and other S3-compatible services.\n */\n\nimport {\n\tS3Client,\n\ttype S3ClientConfig,\n\tPutObjectCommand,\n\tGetObjectCommand,\n\tDeleteObjectCommand,\n\tHeadObjectCommand,\n\tListObjectsV2Command,\n\ttype ListObjectsV2Response,\n} from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { z } from \"zod\";\n\nimport type {\n\tStorage,\n\tS3StorageConfig,\n\tUploadResult,\n\tDownloadResult,\n\tListResult,\n\tListOptions,\n\tSignedUploadUrl,\n\tSignedUploadOptions,\n} from \"./types.js\";\nimport { EmDashStorageError } from \"./types.js\";\n\nconst ENV_KEYS = {\n\tendpoint: \"S3_ENDPOINT\",\n\tbucket: \"S3_BUCKET\",\n\taccessKeyId: \"S3_ACCESS_KEY_ID\",\n\tsecretAccessKey: \"S3_SECRET_ACCESS_KEY\",\n\tregion: \"S3_REGION\",\n\tpublicUrl: \"S3_PUBLIC_URL\",\n} as const satisfies Record<keyof S3StorageConfig, string>;\n\nfunction fail(msg: string): never {\n\tthrow new EmDashStorageError(msg, \"MISSING_S3_CONFIG\");\n}\n\nconst s3ConfigSchema = z.object({\n\tendpoint: z.url({ protocol: /^https?$/, error: \"is not a valid http/https URL\" }).optional(),\n\tbucket: z.string().optional(),\n\taccessKeyId: z.string().optional(),\n\tsecretAccessKey: z.string().optional(),\n\tregion: z.string().optional(),\n\tpublicUrl: z.string().optional(),\n});\n\nfunction isConfigKey(key: unknown): key is keyof S3StorageConfig {\n\treturn typeof key === \"string\" && key in ENV_KEYS;\n}\n\n/**\n * Build the merged config: for each field, use the explicit value if present,\n * otherwise fall back to the corresponding S3_* env var. Validate once on the\n * final merged result so a malformed env var never breaks the build when the\n * caller provides that field explicitly.\n */\nexport function resolveS3Config(partial: Record<string, unknown>): S3StorageConfig {\n\tconst raw: Record<string, unknown> = {};\n\tfor (const [field, envKey] of Object.entries(ENV_KEYS)) {\n\t\tconst explicit = partial[field];\n\t\tif (explicit !== undefined && explicit !== \"\") {\n\t\t\traw[field] = explicit;\n\t\t\tcontinue;\n\t\t}\n\t\tconst envVal = typeof process !== \"undefined\" && process.env ? process.env[envKey] : undefined;\n\t\tif (envVal !== undefined && envVal !== \"\") {\n\t\t\traw[field] = envVal;\n\t\t}\n\t}\n\n\tconst result = s3ConfigSchema.safeParse(raw);\n\tif (!result.success) {\n\t\tconst issue = result.error.issues[0];\n\t\tconst pathKey = issue?.path[0];\n\t\tif (!issue || !isConfigKey(pathKey)) fail(\"S3 config validation failed\");\n\t\tconst fromExplicit = partial[pathKey] !== undefined && partial[pathKey] !== \"\";\n\t\tconst label = fromExplicit ? `s3({ ${pathKey} })` : ENV_KEYS[pathKey];\n\t\tfail(`${label} ${issue.message}`);\n\t}\n\tconst merged = result.data;\n\n\tconst endpoint = merged.endpoint;\n\tconst bucket = merged.bucket;\n\tif (!endpoint || !bucket) {\n\t\tconst missing: string[] = [];\n\t\tif (!endpoint) missing.push(`endpoint: set ${ENV_KEYS.endpoint} or pass endpoint to s3({...})`);\n\t\tif (!bucket) missing.push(`bucket: set ${ENV_KEYS.bucket} or pass bucket to s3({...})`);\n\t\tfail(`missing required S3 config: ${missing.join(\"; \")}`);\n\t}\n\tconst accessKeyId = merged.accessKeyId;\n\tconst secretAccessKey = merged.secretAccessKey;\n\tif (accessKeyId && !secretAccessKey) {\n\t\tfail(\n\t\t\t`S3 credentials incomplete: accessKeyId is set but secretAccessKey is missing (set ${ENV_KEYS.secretAccessKey} or pass secretAccessKey to s3({...}))`,\n\t\t);\n\t}\n\tif (secretAccessKey && !accessKeyId) {\n\t\tfail(\n\t\t\t`S3 credentials incomplete: secretAccessKey is set but accessKeyId is missing (set ${ENV_KEYS.accessKeyId} or pass accessKeyId to s3({...}))`,\n\t\t);\n\t}\n\n\treturn { ...merged, endpoint, bucket };\n}\n\nconst TRAILING_SLASH_PATTERN = /\\/$/;\n\n/** Type guard for AWS SDK errors (have a `name` property) */\nfunction hasErrorName(error: unknown): error is Error & { name: string } {\n\treturn error instanceof Error && typeof error.name === \"string\";\n}\n\n/**\n * S3-compatible storage implementation\n */\nexport class S3Storage implements Storage {\n\tprivate client: S3Client;\n\tprivate bucket: string;\n\tprivate publicUrl?: string;\n\tprivate endpoint: string;\n\n\tconstructor(config: S3StorageConfig) {\n\t\tthis.bucket = config.bucket;\n\t\tthis.publicUrl = config.publicUrl;\n\t\tthis.endpoint = config.endpoint;\n\n\t\t// S3ClientConfig types `credentials` as required, but the SDK accepts\n\t\t// omitted credentials at runtime (falls back to the provider chain).\n\t\t/* eslint-disable typescript-eslint(no-unsafe-type-assertion) -- upstream @aws-sdk/client-s3 overstates required fields */\n\t\tconst clientConfig = {\n\t\t\tendpoint: config.endpoint,\n\t\t\tregion: config.region || \"auto\",\n\t\t\t// Required for R2 and some S3-compatible services\n\t\t\tforcePathStyle: true,\n\t\t\t...(config.accessKeyId && config.secretAccessKey\n\t\t\t\t? {\n\t\t\t\t\t\tcredentials: {\n\t\t\t\t\t\t\taccessKeyId: config.accessKeyId,\n\t\t\t\t\t\t\tsecretAccessKey: config.secretAccessKey,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t} as S3ClientConfig;\n\t\t/* eslint-enable typescript-eslint(no-unsafe-type-assertion) */\n\t\tthis.client = new S3Client(clientConfig);\n\t}\n\n\tasync upload(options: {\n\t\tkey: string;\n\t\tbody: Buffer | Uint8Array | ReadableStream<Uint8Array>;\n\t\tcontentType: string;\n\t}): Promise<UploadResult> {\n\t\ttry {\n\t\t\t// Convert ReadableStream to Buffer if needed\n\t\t\tlet body: Buffer | Uint8Array;\n\t\t\tif (options.body instanceof ReadableStream) {\n\t\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\t\tconst reader = options.body.getReader();\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tchunks.push(value);\n\t\t\t\t}\n\t\t\t\tbody = Buffer.concat(chunks);\n\t\t\t} else {\n\t\t\t\tbody = options.body;\n\t\t\t}\n\n\t\t\tawait this.client.send(\n\t\t\t\tnew PutObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: options.key,\n\t\t\t\t\tBody: body,\n\t\t\t\t\tContentType: options.contentType,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tkey: options.key,\n\t\t\t\turl: this.getPublicUrl(options.key),\n\t\t\t\tsize: body.length,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(`Failed to upload file: ${options.key}`, \"UPLOAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync download(key: string): Promise<DownloadResult> {\n\t\ttry {\n\t\t\tconst response = await this.client.send(\n\t\t\t\tnew GetObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\n\t\t\tif (!response.Body) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\");\n\t\t\t}\n\n\t\t\t// Convert SDK stream to web ReadableStream\n\t\t\tconst body = response.Body.transformToWebStream();\n\n\t\t\treturn {\n\t\t\t\tbody,\n\t\t\t\tcontentType: response.ContentType || \"application/octet-stream\",\n\t\t\t\tsize: response.ContentLength || 0,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof EmDashStorageError ||\n\t\t\t\t(hasErrorName(error) && error.name === \"NoSuchKey\")\n\t\t\t) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\", error);\n\t\t\t}\n\t\t\tthrow new EmDashStorageError(`Failed to download file: ${key}`, \"DOWNLOAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync delete(key: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.client.send(\n\t\t\t\tnew DeleteObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// S3 delete is idempotent, so we ignore \"not found\" errors\n\t\t\tif (!hasErrorName(error) || error.name !== \"NoSuchKey\") {\n\t\t\t\tthrow new EmDashStorageError(`Failed to delete file: ${key}`, \"DELETE_FAILED\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync exists(key: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait this.client.send(\n\t\t\t\tnew HeadObjectCommand({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tKey: key,\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (hasErrorName(error) && error.name === \"NotFound\") {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow new EmDashStorageError(`Failed to check file existence: ${key}`, \"HEAD_FAILED\", error);\n\t\t}\n\t}\n\n\tasync list(options: ListOptions = {}): Promise<ListResult> {\n\t\ttry {\n\t\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- S3 client.send returns generic output; narrowing to ListObjectsV2Response\n\t\t\tconst response = (await this.client.send(\n\t\t\t\tnew ListObjectsV2Command({\n\t\t\t\t\tBucket: this.bucket,\n\t\t\t\t\tPrefix: options.prefix,\n\t\t\t\t\tMaxKeys: options.limit,\n\t\t\t\t\tContinuationToken: options.cursor,\n\t\t\t\t}),\n\t\t\t)) as ListObjectsV2Response;\n\n\t\t\treturn {\n\t\t\t\tfiles: (response.Contents || []).map(\n\t\t\t\t\t(item: { Key?: string; Size?: number; LastModified?: Date; ETag?: string }) => ({\n\t\t\t\t\t\tkey: item.Key!,\n\t\t\t\t\t\tsize: item.Size || 0,\n\t\t\t\t\t\tlastModified: item.LastModified || new Date(),\n\t\t\t\t\t\tetag: item.ETag,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\tnextCursor: response.NextContinuationToken,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(\"Failed to list files\", \"LIST_FAILED\", error);\n\t\t}\n\t}\n\n\tasync getSignedUploadUrl(options: SignedUploadOptions): Promise<SignedUploadUrl> {\n\t\ttry {\n\t\t\tconst expiresIn = options.expiresIn || 3600; // 1 hour default\n\n\t\t\tconst command = new PutObjectCommand({\n\t\t\t\tBucket: this.bucket,\n\t\t\t\tKey: options.key,\n\t\t\t\tContentType: options.contentType,\n\t\t\t\tContentLength: options.size,\n\t\t\t});\n\n\t\t\tconst url = await getSignedUrl(this.client, command, { expiresIn });\n\n\t\t\tconst expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();\n\n\t\t\treturn {\n\t\t\t\turl,\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": options.contentType,\n\t\t\t\t\t...(options.size ? { \"Content-Length\": String(options.size) } : {}),\n\t\t\t\t},\n\t\t\t\texpiresAt,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(\n\t\t\t\t`Failed to generate signed URL for: ${options.key}`,\n\t\t\t\t\"SIGNED_URL_FAILED\",\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\t}\n\n\tgetPublicUrl(key: string): string {\n\t\tif (this.publicUrl) {\n\t\t\treturn `${this.publicUrl.replace(TRAILING_SLASH_PATTERN, \"\")}/${key}`;\n\t\t}\n\t\t// No public URL configured; defer to the /_emdash/api/media/file route.\n\t\treturn `/_emdash/api/media/file/${key}`;\n\t}\n}\n\n/**\n * Create S3 storage adapter\n * This is the factory function called at runtime.\n * Config fields are merged with S3_* env vars; env vars fill in any missing fields.\n */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\treturn new S3Storage(resolveS3Config(config));\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAM,WAAW;CAChB,UAAU;CACV,QAAQ;CACR,aAAa;CACb,iBAAiB;CACjB,QAAQ;CACR,WAAW;CACX;AAED,SAAS,KAAK,KAAoB;AACjC,OAAM,IAAI,mBAAmB,KAAK,oBAAoB;;AAGvD,MAAM,iBAAiB,EAAE,OAAO;CAC/B,UAAU,EAAE,IAAI;EAAE,UAAU;EAAY,OAAO;EAAiC,CAAC,CAAC,UAAU;CAC5F,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,aAAa,EAAE,QAAQ,CAAC,UAAU;CAClC,iBAAiB,EAAE,QAAQ,CAAC,UAAU;CACtC,QAAQ,EAAE,QAAQ,CAAC,UAAU;CAC7B,WAAW,EAAE,QAAQ,CAAC,UAAU;CAChC,CAAC;AAEF,SAAS,YAAY,KAA4C;AAChE,QAAO,OAAO,QAAQ,YAAY,OAAO;;;;;;;;AAS1C,SAAgB,gBAAgB,SAAmD;CAClF,MAAM,MAA+B,EAAE;AACvC,MAAK,MAAM,CAAC,OAAO,WAAW,OAAO,QAAQ,SAAS,EAAE;EACvD,MAAM,WAAW,QAAQ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AAK;IACb,KAAK,QAAQ;IACb,aAAa,QAAQ;IACrB,eAAe,QAAQ;IACvB,CAAC;GAEF,MAAM,MAAM,MAAM,aAAa,KAAK,QAAQ,SAAS,EAAE,WAAW,CAAC;GAEnE,MAAM,YAAY,IAAI,KAAK,KAAK,KAAK,GAAG,YAAY,IAAK,CAAC,aAAa;AAEvE,UAAO;IACN;IACA,QAAQ;IACR,SAAS;KACR,gBAAgB,QAAQ;KACxB,GAAI,QAAQ,OAAO,EAAE,kBAAkB,OAAO,QAAQ,KAAK,EAAE,GAAG,EAAE;KAClE;IACD;IACA;WACO,OAAO;AACf,SAAM,IAAI,mBACT,sCAAsC,QAAQ,OAC9C,qBACA,MACA;;;CAIH,aAAa,KAAqB;AACjC,MAAI,KAAK,UACR,QAAO,GAAG,KAAK,UAAU,QAAQ,wBAAwB,GAAG,CAAC,GAAG;AAGjE,SAAO,2BAA2B;;;;;;;;AASpC,SAAgB,cAAc,QAA0C;AACvE,QAAO,IAAI,UAAU,gBAAgB,OAAO,CAAC"}
@@ -1,8 +1,8 @@
1
- import { t as __exportAll } from "./chunk-ClPoSABd.mjs";
2
- import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-HGz06Soa.mjs";
3
- import { t as isMissingTableError } from "./db-errors-D0UT85nC.mjs";
4
- import { n as getDb } from "./loader-DeiBJEMe.mjs";
5
- import { n as requestCached, r as setRequestCacheEntry } from "./request-cache-DiR961CV.mjs";
1
+ import { i as __exportAll } from "./runner-C7ADox5q.mjs";
2
+ import { n as chunks, t as SQL_BATCH_SIZE } from "./chunks-NBQVDOci.mjs";
3
+ import { t as isMissingTableError } from "./db-errors-WRezodiz.mjs";
4
+ import { r as getDb } from "./loader-CKLbBnhK.mjs";
5
+ import { n as requestCached, r as setRequestCacheEntry, t as peekRequestCache } from "./request-cache-B-bmkipQ.mjs";
6
6
 
7
7
  //#region src/taxonomies/index.ts
8
8
  /**
@@ -48,8 +48,15 @@ async function getTaxonomyDefs() {
48
48
  }
49
49
  /**
50
50
  * Get a single taxonomy definition by name
51
+ *
52
+ * If `getTaxonomyDefs()` has already loaded the full list in this request
53
+ * (which happens during entry-term hydration on every page that renders a
54
+ * collection), find the matching def in memory rather than running a
55
+ * second `WHERE name=?` query against `_emdash_taxonomy_defs`.
51
56
  */
52
57
  async function getTaxonomyDef(name) {
58
+ const allDefs = peekRequestCache("taxonomy-defs:all");
59
+ if (allDefs) return (await allDefs).find((d) => d.name === name) ?? null;
53
60
  return requestCached(`taxonomy-def:${name}`, async () => {
54
61
  const row = await (await getDb()).selectFrom("_emdash_taxonomy_defs").selectAll().where("name", "=", name).executeTakeFirst();
55
62
  if (!row) return null;
@@ -278,7 +285,7 @@ function primeEntryTermsCache(collection, entryId, byTaxonomy, applicableTaxonom
278
285
  * Get entries by term (wraps getEmDashCollection)
279
286
  */
280
287
  async function getEntriesByTerm(collection, taxonomyName, termSlug) {
281
- const { getEmDashCollection } = await import("./query-g4Ug-9j9.mjs").then((n) => n.o);
288
+ const { getEmDashCollection } = await import("./query-Cg9ZKRQ0.mjs").then((n) => n.o);
282
289
  const { entries } = await getEmDashCollection(collection, { where: { [taxonomyName]: termSlug } });
283
290
  return entries;
284
291
  }
@@ -305,4 +312,4 @@ function buildTree(flatTerms, counts) {
305
312
 
306
313
  //#endregion
307
314
  export { getTaxonomyDefs as a, getTermsForEntries as c, getTaxonomyDef as i, invalidateTermCache as l, getEntriesByTerm as n, getTaxonomyTerms as o, getEntryTerms as r, getTerm as s, getAllTermsForEntries as t, taxonomies_exports as u };
308
- //# sourceMappingURL=taxonomies-K2z0Uhnj.mjs.map
315
+ //# sourceMappingURL=taxonomies-ZlRtD6AG.mjs.map