emdash 0.0.1 → 0.0.3

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 (36) hide show
  1. package/dist/astro/index.mjs +41 -38
  2. package/dist/astro/index.mjs.map +1 -1
  3. package/dist/astro/middleware.d.mts.map +1 -1
  4. package/dist/astro/middleware.mjs +18 -1
  5. package/dist/astro/middleware.mjs.map +1 -1
  6. package/dist/cli/index.mjs +1 -1
  7. package/dist/cli/index.mjs.map +1 -1
  8. package/dist/db/index.mjs +1 -1
  9. package/dist/index.mjs +1 -1
  10. package/dist/{runner-B-u2F2b6.mjs → runner-C0hCbYnD.mjs} +15 -15
  11. package/dist/runner-C0hCbYnD.mjs.map +1 -0
  12. package/dist/storage/local.d.mts.map +1 -1
  13. package/dist/storage/local.mjs.map +1 -1
  14. package/dist/storage/s3.d.mts.map +1 -1
  15. package/dist/storage/s3.mjs.map +1 -1
  16. package/package.json +5 -5
  17. package/src/api/handlers/device-flow.ts +1 -4
  18. package/src/api/handlers/oauth-clients.ts +1 -5
  19. package/src/astro/integration/index.ts +1 -1
  20. package/src/astro/integration/vite-config.ts +8 -1
  21. package/src/astro/middleware.ts +35 -0
  22. package/src/astro/routes/api/admin/comments/[id]/status.ts +1 -5
  23. package/src/astro/routes/api/auth/passkey/register/verify.ts +1 -3
  24. package/src/astro/routes/api/content/[collection]/[id]/schedule.ts +1 -5
  25. package/src/astro/routes/api/import/wordpress/analyze.ts +1 -1
  26. package/src/astro/routes/api/import/wordpress/media.ts +1 -1
  27. package/src/astro/routes/api/revisions/[revisionId]/restore.ts +1 -5
  28. package/src/astro/routes/api/widget-areas/[name]/reorder.ts +1 -5
  29. package/src/cli/commands/publish.ts +1 -3
  30. package/src/cli/commands/seed.ts +1 -3
  31. package/src/database/migrations/001_initial.ts +39 -5
  32. package/src/database/migrations/032_rate_limits.ts +1 -4
  33. package/src/mcp/server.ts +2 -2
  34. package/src/storage/local.ts +1 -5
  35. package/src/storage/s3.ts +2 -10
  36. package/dist/runner-B-u2F2b6.mjs.map +0 -1
package/dist/db/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import "../dialect-helpers-B9uSp2GJ.mjs";
2
- import { n as rollbackMigration, r as runMigrations, t as getMigrationStatus } from "../runner-B-u2F2b6.mjs";
2
+ import { n as rollbackMigration, r as runMigrations, t as getMigrationStatus } from "../runner-C0hCbYnD.mjs";
3
3
 
4
4
  //#region src/db/adapters.ts
5
5
  /**
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as EmDashDatabaseError } from "./connection-B4zVnQIa.mjs";
2
2
  import "./dialect-helpers-B9uSp2GJ.mjs";
3
- import { t as getMigrationStatus } from "./runner-B-u2F2b6.mjs";
3
+ import { t as getMigrationStatus } from "./runner-C0hCbYnD.mjs";
4
4
  import { $ as definePlugin, A as getFileSources, At as handleContentGetIncludingTrashed, B as PluginManager, Bt as handleContentUpdate, C as isPreviewRequest, Ct as handleContentCountScheduled, D as wxrSource, Dt as handleContentDiscardDraft, E as wordpressRestSource, Et as handleContentDelete, F as importReusableBlocksAsSections, Ft as handleContentRestore, H as PluginRouteError, Ht as portableText, I as isStandardPluginDefinition, It as handleContentSchedule, J as createHookPipeline, L as NoopSandboxRunner, Lt as handleContentTranslations, M as getUrlSources, Mt as handleContentListTrashed, N as probeUrl, Nt as handleContentPermanentDelete, O as clearSources, Ot as handleContentDuplicate, P as registerSource, Pt as handleContentPublish, R as SandboxNotAvailableError, Rt as handleContentUnpublish, S as getPreviewToken, St as handleContentCompare, T as getPreviewUrl, Tt as handleContentCreate, Ut as reference, V as createPluginManager, Wt as image, _ as getTermsForEntries, _t as handleRevisionList, a as search, at as prosemirrorToPortableText, b as getCommentCount, bt as computeContentHash, c as getWidgetArea, ct as getSections, d as getEntriesByTerm, dt as handleMediaCreate, et as parseWxr, f as getEntryTerms, ft as handleMediaDelete, g as getTerm, gt as handleRevisionGet, h as getTaxonomyTerms, ht as handleMediaUpdate, i as getSuggestions, it as portableTextToProsemirror, j as getSource, jt as handleContentList, k as getAllSources, kt as handleContentGet, l as getWidgetAreas, m as getTaxonomyDefs, mt as handleMediaList, n as extractSearchableFields, nt as isSafeHref, o as searchCollection, p as getTaxonomyDef, pt as handleMediaGet, q as HookPipeline, r as getSearchStats, rt as sanitizeHref, s as searchWithDb, st as getSection, t as extractPlainText, tt as parseWxrString, u as getWidgetComponents, ut as getCollectionInfo, v as getMenu, vt as handleRevisionRestore, w as buildPreviewUrl, wt as handleContentCountTrashed, x as getComments, xt as hashString, y as getMenus, yt as generateManifest, z as createNoopSandboxRunner, zt as handleContentUnschedule } from "./search-DG603UrT.mjs";
5
5
  import { t as ContentRepository } from "./content-D6C2WsZC.mjs";
6
6
  import "./base64-MBPo9ozB.mjs";
@@ -16,24 +16,24 @@ var _001_initial_exports = /* @__PURE__ */ __exportAll({
16
16
  * This migration only creates system tables.
17
17
  */
18
18
  async function up$30(db) {
19
- await db.schema.createTable("revisions").addColumn("id", "text", (col) => col.primaryKey()).addColumn("collection", "text", (col) => col.notNull()).addColumn("entry_id", "text", (col) => col.notNull()).addColumn("data", "text", (col) => col.notNull()).addColumn("author_id", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).execute();
20
- await db.schema.createIndex("idx_revisions_entry").on("revisions").columns(["collection", "entry_id"]).execute();
21
- await db.schema.createTable("taxonomies").addColumn("id", "text", (col) => col.primaryKey()).addColumn("name", "text", (col) => col.notNull()).addColumn("slug", "text", (col) => col.notNull()).addColumn("label", "text", (col) => col.notNull()).addColumn("parent_id", "text").addColumn("data", "text").addUniqueConstraint("taxonomies_name_slug_unique", ["name", "slug"]).addForeignKeyConstraint("taxonomies_parent_fk", ["parent_id"], "taxonomies", ["id"], (cb) => cb.onDelete("set null")).execute();
22
- await db.schema.createIndex("idx_taxonomies_name").on("taxonomies").column("name").execute();
23
- await db.schema.createTable("content_taxonomies").addColumn("collection", "text", (col) => col.notNull()).addColumn("entry_id", "text", (col) => col.notNull()).addColumn("taxonomy_id", "text", (col) => col.notNull()).addPrimaryKeyConstraint("content_taxonomies_pk", [
19
+ await db.schema.createTable("revisions").ifNotExists().addColumn("id", "text", (col) => col.primaryKey()).addColumn("collection", "text", (col) => col.notNull()).addColumn("entry_id", "text", (col) => col.notNull()).addColumn("data", "text", (col) => col.notNull()).addColumn("author_id", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).execute();
20
+ await db.schema.createIndex("idx_revisions_entry").ifNotExists().on("revisions").columns(["collection", "entry_id"]).execute();
21
+ await db.schema.createTable("taxonomies").ifNotExists().addColumn("id", "text", (col) => col.primaryKey()).addColumn("name", "text", (col) => col.notNull()).addColumn("slug", "text", (col) => col.notNull()).addColumn("label", "text", (col) => col.notNull()).addColumn("parent_id", "text").addColumn("data", "text").addUniqueConstraint("taxonomies_name_slug_unique", ["name", "slug"]).addForeignKeyConstraint("taxonomies_parent_fk", ["parent_id"], "taxonomies", ["id"], (cb) => cb.onDelete("set null")).execute();
22
+ await db.schema.createIndex("idx_taxonomies_name").ifNotExists().on("taxonomies").column("name").execute();
23
+ await db.schema.createTable("content_taxonomies").ifNotExists().addColumn("collection", "text", (col) => col.notNull()).addColumn("entry_id", "text", (col) => col.notNull()).addColumn("taxonomy_id", "text", (col) => col.notNull()).addPrimaryKeyConstraint("content_taxonomies_pk", [
24
24
  "collection",
25
25
  "entry_id",
26
26
  "taxonomy_id"
27
27
  ]).addForeignKeyConstraint("content_taxonomies_taxonomy_fk", ["taxonomy_id"], "taxonomies", ["id"], (cb) => cb.onDelete("cascade")).execute();
28
- await db.schema.createTable("media").addColumn("id", "text", (col) => col.primaryKey()).addColumn("filename", "text", (col) => col.notNull()).addColumn("mime_type", "text", (col) => col.notNull()).addColumn("size", "integer").addColumn("width", "integer").addColumn("height", "integer").addColumn("alt", "text").addColumn("caption", "text").addColumn("storage_key", "text", (col) => col.notNull()).addColumn("content_hash", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).addColumn("author_id", "text").execute();
29
- await db.schema.createIndex("idx_media_content_hash").on("media").column("content_hash").execute();
30
- await db.schema.createTable("users").addColumn("id", "text", (col) => col.primaryKey()).addColumn("email", "text", (col) => col.notNull().unique()).addColumn("password_hash", "text", (col) => col.notNull()).addColumn("name", "text").addColumn("role", "text", (col) => col.defaultTo("subscriber")).addColumn("avatar_id", "text").addColumn("data", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).execute();
31
- await db.schema.createIndex("idx_users_email").on("users").column("email").execute();
32
- await db.schema.createTable("options").addColumn("name", "text", (col) => col.primaryKey()).addColumn("value", "text", (col) => col.notNull()).execute();
33
- await db.schema.createTable("audit_logs").addColumn("id", "text", (col) => col.primaryKey()).addColumn("timestamp", "text", (col) => col.defaultTo(currentTimestamp(db))).addColumn("actor_id", "text").addColumn("actor_ip", "text").addColumn("action", "text", (col) => col.notNull()).addColumn("resource_type", "text").addColumn("resource_id", "text").addColumn("details", "text").addColumn("status", "text").execute();
34
- await db.schema.createIndex("idx_audit_actor").on("audit_logs").column("actor_id").execute();
35
- await db.schema.createIndex("idx_audit_action").on("audit_logs").column("action").execute();
36
- await db.schema.createIndex("idx_audit_timestamp").on("audit_logs").column("timestamp").execute();
28
+ await db.schema.createTable("media").ifNotExists().addColumn("id", "text", (col) => col.primaryKey()).addColumn("filename", "text", (col) => col.notNull()).addColumn("mime_type", "text", (col) => col.notNull()).addColumn("size", "integer").addColumn("width", "integer").addColumn("height", "integer").addColumn("alt", "text").addColumn("caption", "text").addColumn("storage_key", "text", (col) => col.notNull()).addColumn("content_hash", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).addColumn("author_id", "text").execute();
29
+ await db.schema.createIndex("idx_media_content_hash").ifNotExists().on("media").column("content_hash").execute();
30
+ await db.schema.createTable("users").ifNotExists().addColumn("id", "text", (col) => col.primaryKey()).addColumn("email", "text", (col) => col.notNull().unique()).addColumn("password_hash", "text", (col) => col.notNull()).addColumn("name", "text").addColumn("role", "text", (col) => col.defaultTo("subscriber")).addColumn("avatar_id", "text").addColumn("data", "text").addColumn("created_at", "text", (col) => col.defaultTo(currentTimestamp(db))).execute();
31
+ await db.schema.createIndex("idx_users_email").ifNotExists().on("users").column("email").execute();
32
+ await db.schema.createTable("options").ifNotExists().addColumn("name", "text", (col) => col.primaryKey()).addColumn("value", "text", (col) => col.notNull()).execute();
33
+ await db.schema.createTable("audit_logs").ifNotExists().addColumn("id", "text", (col) => col.primaryKey()).addColumn("timestamp", "text", (col) => col.defaultTo(currentTimestamp(db))).addColumn("actor_id", "text").addColumn("actor_ip", "text").addColumn("action", "text", (col) => col.notNull()).addColumn("resource_type", "text").addColumn("resource_id", "text").addColumn("details", "text").addColumn("status", "text").execute();
34
+ await db.schema.createIndex("idx_audit_actor").ifNotExists().on("audit_logs").column("actor_id").execute();
35
+ await db.schema.createIndex("idx_audit_action").ifNotExists().on("audit_logs").column("action").execute();
36
+ await db.schema.createIndex("idx_audit_timestamp").ifNotExists().on("audit_logs").column("timestamp").execute();
37
37
  }
38
38
  async function down$30(db) {
39
39
  await db.schema.dropTable("audit_logs").execute();
@@ -1409,4 +1409,4 @@ async function rollbackMigration(db) {
1409
1409
 
1410
1410
  //#endregion
1411
1411
  export { rollbackMigration as n, runMigrations as r, getMigrationStatus as t };
1412
- //# sourceMappingURL=runner-B-u2F2b6.mjs.map
1412
+ //# sourceMappingURL=runner-C0hCbYnD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-C0hCbYnD.mjs","names":["up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","up","down","m001","m002","m003","m004","m005","m006","m007","m008","m009","m011","m012","m013","m014","m015","m016","m017","m018","m019","m020","m021","m022","m023","m024","m025","m026","m027","m028","m029","m030","m031","m032"],"sources":["../src/database/migrations/001_initial.ts","../src/database/migrations/002_media_status.ts","../src/database/migrations/003_schema_registry.ts","../src/database/migrations/004_plugins.ts","../src/database/migrations/005_menus.ts","../src/database/migrations/006_taxonomy_defs.ts","../src/database/migrations/007_widgets.ts","../src/database/migrations/008_auth.ts","../src/database/migrations/009_user_disabled.ts","../src/database/migrations/011_sections.ts","../src/database/migrations/012_search.ts","../src/database/migrations/013_scheduled_publishing.ts","../src/database/migrations/014_draft_revisions.ts","../src/database/migrations/015_indexes.ts","../src/database/migrations/016_api_tokens.ts","../src/database/migrations/017_authorization_codes.ts","../src/database/migrations/018_seo.ts","../src/database/migrations/019_i18n.ts","../src/database/migrations/020_collection_url_pattern.ts","../src/database/migrations/021_remove_section_categories.ts","../src/database/migrations/022_marketplace_plugin_state.ts","../src/database/migrations/023_plugin_metadata.ts","../src/database/migrations/024_media_placeholders.ts","../src/database/migrations/025_oauth_clients.ts","../src/database/migrations/026_cron_tasks.ts","../src/database/migrations/027_comments.ts","../src/database/migrations/028_drop_author_url.ts","../src/database/migrations/029_redirects.ts","../src/database/migrations/030_widen_scheduled_index.ts","../src/database/migrations/031_bylines.ts","../src/database/migrations/032_rate_limits.ts","../src/database/migrations/runner.ts"],"sourcesContent":["import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Initial schema migration\n *\n * Note: Content tables (ec_posts, ec_pages, etc.) are created dynamically\n * by the SchemaRegistry when collections are added via the admin UI.\n * This migration only creates system tables.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Revisions - stores snapshots of content entries\n\t// References entries in ec_* tables by collection + entry_id\n\tawait db.schema\n\t\t.createTable(\"revisions\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull()) // e.g., 'posts'\n\t\t.addColumn(\"entry_id\", \"text\", (col) => col.notNull()) // ID in the ec_* table\n\t\t.addColumn(\"data\", \"text\", (col) => col.notNull()) // JSON snapshot of all fields\n\t\t.addColumn(\"author_id\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_revisions_entry\")\n\t\t.ifNotExists()\n\t\t.on(\"revisions\")\n\t\t.columns([\"collection\", \"entry_id\"])\n\t\t.execute();\n\n\t// Taxonomies\n\tawait db.schema\n\t\t.createTable(\"taxonomies\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"parent_id\", \"text\")\n\t\t.addColumn(\"data\", \"text\")\n\t\t.addUniqueConstraint(\"taxonomies_name_slug_unique\", [\"name\", \"slug\"])\n\t\t.addForeignKeyConstraint(\"taxonomies_parent_fk\", [\"parent_id\"], \"taxonomies\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"set null\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_taxonomies_name\")\n\t\t.ifNotExists()\n\t\t.on(\"taxonomies\")\n\t\t.column(\"name\")\n\t\t.execute();\n\n\t// Content-Taxonomy junction - references entries in ec_* tables\n\tawait db.schema\n\t\t.createTable(\"content_taxonomies\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull()) // e.g., 'posts'\n\t\t.addColumn(\"entry_id\", \"text\", (col) => col.notNull()) // ID in the ec_* table\n\t\t.addColumn(\"taxonomy_id\", \"text\", (col) => col.notNull())\n\t\t.addPrimaryKeyConstraint(\"content_taxonomies_pk\", [\"collection\", \"entry_id\", \"taxonomy_id\"])\n\t\t.addForeignKeyConstraint(\n\t\t\t\"content_taxonomies_taxonomy_fk\",\n\t\t\t[\"taxonomy_id\"],\n\t\t\t\"taxonomies\",\n\t\t\t[\"id\"],\n\t\t\t(cb) => cb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\t// Media\n\tawait db.schema\n\t\t.createTable(\"media\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"filename\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"mime_type\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"size\", \"integer\")\n\t\t.addColumn(\"width\", \"integer\")\n\t\t.addColumn(\"height\", \"integer\")\n\t\t.addColumn(\"alt\", \"text\")\n\t\t.addColumn(\"caption\", \"text\")\n\t\t.addColumn(\"storage_key\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"content_hash\", \"text\") // xxHash64 for deduplication\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"author_id\", \"text\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_media_content_hash\")\n\t\t.ifNotExists()\n\t\t.on(\"media\")\n\t\t.column(\"content_hash\")\n\t\t.execute();\n\n\t// Users\n\tawait db.schema\n\t\t.createTable(\"users\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"email\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"password_hash\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"name\", \"text\")\n\t\t.addColumn(\"role\", \"text\", (col) => col.defaultTo(\"subscriber\"))\n\t\t.addColumn(\"avatar_id\", \"text\")\n\t\t.addColumn(\"data\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_users_email\")\n\t\t.ifNotExists()\n\t\t.on(\"users\")\n\t\t.column(\"email\")\n\t\t.execute();\n\n\t// Options (key-value store)\n\tawait db.schema\n\t\t.createTable(\"options\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"name\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"value\", \"text\", (col) => col.notNull())\n\t\t.execute();\n\n\t// Audit logs (security events)\n\tawait db.schema\n\t\t.createTable(\"audit_logs\")\n\t\t.ifNotExists()\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"timestamp\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"actor_id\", \"text\")\n\t\t.addColumn(\"actor_ip\", \"text\")\n\t\t.addColumn(\"action\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"resource_type\", \"text\")\n\t\t.addColumn(\"resource_id\", \"text\")\n\t\t.addColumn(\"details\", \"text\")\n\t\t.addColumn(\"status\", \"text\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_audit_actor\")\n\t\t.ifNotExists()\n\t\t.on(\"audit_logs\")\n\t\t.column(\"actor_id\")\n\t\t.execute();\n\tawait db.schema\n\t\t.createIndex(\"idx_audit_action\")\n\t\t.ifNotExists()\n\t\t.on(\"audit_logs\")\n\t\t.column(\"action\")\n\t\t.execute();\n\tawait db.schema\n\t\t.createIndex(\"idx_audit_timestamp\")\n\t\t.ifNotExists()\n\t\t.on(\"audit_logs\")\n\t\t.column(\"timestamp\")\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"audit_logs\").execute();\n\tawait db.schema.dropTable(\"options\").execute();\n\tawait db.schema.dropTable(\"users\").execute();\n\tawait db.schema.dropTable(\"media\").execute();\n\tawait db.schema.dropTable(\"content_taxonomies\").execute();\n\tawait db.schema.dropTable(\"taxonomies\").execute();\n\tawait db.schema.dropTable(\"revisions\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\n/**\n * Add status column to media table for tracking upload state.\n * Status values: 'pending' | 'ready' | 'failed'\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema\n\t\t.alterTable(\"media\")\n\t\t.addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"ready\"))\n\t\t.execute();\n\n\tawait db.schema.createIndex(\"idx_media_status\").on(\"media\").column(\"status\").execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropIndex(\"idx_media_status\").execute();\n\n\t// Note: SQLite doesn't support DROP COLUMN directly\n\t// For a proper down migration in SQLite, you'd need to:\n\t// 1. Create a new table without the column\n\t// 2. Copy data over\n\t// 3. Drop old table\n\t// 4. Rename new table\n\t// For simplicity, we'll leave this as a no-op since down migrations are rarely used\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Schema Registry Tables\n *\n * Creates the schema registry tables that store collection and field definitions.\n * This enables dynamic schema management where D1 is the source of truth.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Collection definitions (like WordPress post types, but stored in DB)\n\tawait db.schema\n\t\t.createTable(\"_emdash_collections\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"label_singular\", \"text\")\n\t\t.addColumn(\"description\", \"text\")\n\t\t.addColumn(\"icon\", \"text\")\n\t\t.addColumn(\"supports\", \"text\") // JSON array: [\"revisions\", \"drafts\", \"preview\"]\n\t\t.addColumn(\"source\", \"text\") // 'template:blog', 'import:wordpress', 'manual'\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Field definitions for each collection\n\tawait db.schema\n\t\t.createTable(\"_emdash_fields\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"collection_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"type\", \"text\", (col) => col.notNull()) // 'string', 'number', 'boolean', 'portableText', etc.\n\t\t.addColumn(\"column_type\", \"text\", (col) => col.notNull()) // 'TEXT', 'REAL', 'INTEGER', 'JSON'\n\t\t.addColumn(\"required\", \"integer\", (col) => col.defaultTo(0)) // boolean as 0/1\n\t\t.addColumn(\"unique\", \"integer\", (col) => col.defaultTo(0)) // boolean as 0/1\n\t\t.addColumn(\"default_value\", \"text\") // JSON-encoded default\n\t\t.addColumn(\"validation\", \"text\") // JSON: { min: 0, max: 100, pattern: \"^[a-z]+$\" }\n\t\t.addColumn(\"widget\", \"text\") // UI widget hint: 'textarea', 'richtext', 'select'\n\t\t.addColumn(\"options\", \"text\") // JSON: widget-specific config\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\n\t\t\t\"fields_collection_fk\",\n\t\t\t[\"collection_id\"],\n\t\t\t\"_emdash_collections\",\n\t\t\t[\"id\"],\n\t\t\t(cb) => cb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\t// Unique constraint on collection + field slug\n\tawait db.schema\n\t\t.createIndex(\"idx_fields_collection_slug\")\n\t\t.on(\"_emdash_fields\")\n\t\t.columns([\"collection_id\", \"slug\"])\n\t\t.unique()\n\t\t.execute();\n\n\t// Index for faster field lookups\n\tawait db.schema\n\t\t.createIndex(\"idx_fields_collection\")\n\t\t.on(\"_emdash_fields\")\n\t\t.column(\"collection_id\")\n\t\t.execute();\n\n\t// Index for sorting\n\tawait db.schema\n\t\t.createIndex(\"idx_fields_sort\")\n\t\t.on(\"_emdash_fields\")\n\t\t.columns([\"collection_id\", \"sort_order\"])\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_fields\").execute();\n\tawait db.schema.dropTable(\"_emdash_collections\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Plugin System Tables\n *\n * Creates the plugin storage table and plugin state tracking.\n * Plugin storage uses a document store with declared indexes.\n *\n * @see PLUGIN-SYSTEM.md § Plugin Storage\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Core storage table for plugin documents\n\tawait db.schema\n\t\t.createTable(\"_plugin_storage\")\n\t\t.addColumn(\"plugin_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"data\", \"text\", (col) => col.notNull()) // JSON\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addPrimaryKeyConstraint(\"pk_plugin_storage\", [\"plugin_id\", \"collection\", \"id\"])\n\t\t.execute();\n\n\t// Base index for listing\n\tawait db.schema\n\t\t.createIndex(\"idx_plugin_storage_list\")\n\t\t.on(\"_plugin_storage\")\n\t\t.columns([\"plugin_id\", \"collection\", \"created_at\"])\n\t\t.execute();\n\n\t// Plugin state tracking for lifecycle hooks\n\tawait db.schema\n\t\t.createTable(\"_plugin_state\")\n\t\t.addColumn(\"plugin_id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"version\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"installed\")) // installed, active, inactive\n\t\t.addColumn(\"installed_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"activated_at\", \"text\")\n\t\t.addColumn(\"deactivated_at\", \"text\")\n\t\t.addColumn(\"data\", \"text\") // JSON for plugin-specific state\n\t\t.execute();\n\n\t// Index tracking for dynamic expression indexes on plugin storage\n\t// This tracks which indexes have been created so we can manage them\n\tawait db.schema\n\t\t.createTable(\"_plugin_indexes\")\n\t\t.addColumn(\"plugin_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"index_name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"fields\", \"text\", (col) => col.notNull()) // JSON array of field paths\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addPrimaryKeyConstraint(\"pk_plugin_indexes\", [\"plugin_id\", \"collection\", \"index_name\"])\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_plugin_indexes\").execute();\n\tawait db.schema.dropTable(\"_plugin_state\").execute();\n\tawait db.schema.dropTable(\"_plugin_storage\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Navigation Menus migration\n *\n * Creates tables for admin-editable navigation menus.\n * Menu items can reference content entries, taxonomy terms, or custom URLs.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Menu definitions\n\tawait db.schema\n\t\t.createTable(\"_emdash_menus\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Menu items (ordered, hierarchical)\n\tawait db.schema\n\t\t.createTable(\"_emdash_menu_items\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"menu_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"parent_id\", \"text\")\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"type\", \"text\", (col) => col.notNull()) // 'page', 'post', 'custom', 'taxonomy', 'collection'\n\t\t.addColumn(\"reference_collection\", \"text\")\n\t\t.addColumn(\"reference_id\", \"text\")\n\t\t.addColumn(\"custom_url\", \"text\")\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"title_attr\", \"text\")\n\t\t.addColumn(\"target\", \"text\")\n\t\t.addColumn(\"css_classes\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"menu_items_menu_fk\", [\"menu_id\"], \"_emdash_menus\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.addForeignKeyConstraint(\n\t\t\t\"menu_items_parent_fk\",\n\t\t\t[\"parent_id\"],\n\t\t\t\"_emdash_menu_items\",\n\t\t\t[\"id\"],\n\t\t\t(cb) => cb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\t// Index for efficient menu item queries\n\tawait db.schema\n\t\t.createIndex(\"idx_menu_items_menu\")\n\t\t.on(\"_emdash_menu_items\")\n\t\t.columns([\"menu_id\", \"sort_order\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_menu_items_parent\")\n\t\t.on(\"_emdash_menu_items\")\n\t\t.column(\"parent_id\")\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_menu_items\").execute();\n\tawait db.schema.dropTable(\"_emdash_menus\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Taxonomy definitions migration\n *\n * Adds _emdash_taxonomy_defs table to store taxonomy definitions (category, tag, custom)\n * and seeds default category and tag taxonomies.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Taxonomy definitions (what taxonomies exist)\n\tawait db.schema\n\t\t.createTable(\"_emdash_taxonomy_defs\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull().unique()) // 'category', 'tag'\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull()) // 'Categories'\n\t\t.addColumn(\"label_singular\", \"text\") // 'Category'\n\t\t.addColumn(\"hierarchical\", \"integer\", (col) => col.defaultTo(0)) // 0 or 1\n\t\t.addColumn(\"collections\", \"text\") // JSON array: [\"posts\"]\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Seed default taxonomies\n\tawait db\n\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely migration runs against unknown schema\n\t\t.insertInto(\"_emdash_taxonomy_defs\" as never)\n\t\t.values([\n\t\t\t{\n\t\t\t\tid: \"taxdef_category\",\n\t\t\t\tname: \"category\",\n\t\t\t\tlabel: \"Categories\",\n\t\t\t\tlabel_singular: \"Category\",\n\t\t\t\thierarchical: 1,\n\t\t\t\tcollections: JSON.stringify([\"posts\"]),\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"taxdef_tag\",\n\t\t\t\tname: \"tag\",\n\t\t\t\tlabel: \"Tags\",\n\t\t\t\tlabel_singular: \"Tag\",\n\t\t\t\thierarchical: 0,\n\t\t\t\tcollections: JSON.stringify([\"posts\"]),\n\t\t\t},\n\t\t])\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_taxonomy_defs\").execute();\n}\n","import { type Kysely, sql } from \"kysely\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Widget areas table\n\tawait db.schema\n\t\t.createTable(\"_emdash_widget_areas\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"description\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.execute();\n\n\t// Widgets table\n\tawait db.schema\n\t\t.createTable(\"_emdash_widgets\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"area_id\", \"text\", (col) =>\n\t\t\tcol.notNull().references(\"_emdash_widget_areas.id\").onDelete(\"cascade\"),\n\t\t)\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"type\", \"text\", (col) => col.notNull()) // 'content', 'menu', 'component'\n\t\t.addColumn(\"title\", \"text\")\n\t\t.addColumn(\"content\", \"text\") // JSON: Portable Text for content type\n\t\t.addColumn(\"menu_name\", \"text\") // For menu type\n\t\t.addColumn(\"component_id\", \"text\") // For component type: 'core:recent-posts'\n\t\t.addColumn(\"component_props\", \"text\") // JSON: props for component\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.execute();\n\n\t// Index for efficient lookups by area and order\n\tawait db.schema\n\t\t.createIndex(\"idx_widgets_area\")\n\t\t.on(\"_emdash_widgets\")\n\t\t.columns([\"area_id\", \"sort_order\"])\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_widgets\").execute();\n\tawait db.schema.dropTable(\"_emdash_widget_areas\").execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { binaryType, currentTimestamp, currentTimestampValue } from \"../dialect-helpers.js\";\n\n/**\n * Auth migration - passkey-first authentication\n *\n * Changes:\n * - Removes password_hash from users (no passwords)\n * - Adds role as integer (RBAC levels)\n * - Adds email_verified, avatar_url, updated_at to users\n * - Creates credentials table (passkeys)\n * - Creates auth_tokens table (magic links, invites)\n * - Creates oauth_accounts table (external provider links)\n * - Creates allowed_domains table (self-signup)\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// SQLite doesn't support DROP COLUMN directly, so we need to recreate the table\n\t// Create new users table with updated schema\n\tawait db.schema\n\t\t.createTable(\"users_new\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"email\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"name\", \"text\")\n\t\t.addColumn(\"avatar_url\", \"text\")\n\t\t.addColumn(\"role\", \"integer\", (col) => col.notNull().defaultTo(10)) // SUBSCRIBER\n\t\t.addColumn(\"email_verified\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"data\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Migrate existing data (map old role strings to new integer levels)\n\tawait sql`\n\t\tINSERT INTO users_new (id, email, name, role, data, created_at, updated_at)\n\t\tSELECT\n\t\t\tid,\n\t\t\temail,\n\t\t\tname,\n\t\t\tCASE role\n\t\t\t\tWHEN 'admin' THEN 50\n\t\t\t\tWHEN 'editor' THEN 40\n\t\t\t\tWHEN 'author' THEN 30\n\t\t\t\tWHEN 'contributor' THEN 20\n\t\t\t\tELSE 10\n\t\t\tEND,\n\t\t\tdata,\n\t\t\tcreated_at,\n\t\t\t${currentTimestampValue(db)}\n\t\tFROM users\n\t`.execute(db);\n\n\t// Drop old table and rename new one\n\tawait db.schema.dropTable(\"users\").execute();\n\tawait sql`ALTER TABLE users_new RENAME TO users`.execute(db);\n\n\t// Recreate index\n\tawait db.schema.createIndex(\"idx_users_email\").on(\"users\").column(\"email\").execute();\n\n\t// Passkey credentials\n\tawait db.schema\n\t\t.createTable(\"credentials\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey()) // Base64url credential ID\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"public_key\", binaryType(db), (col) => col.notNull()) // COSE public key\n\t\t.addColumn(\"counter\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"device_type\", \"text\", (col) => col.notNull()) // 'singleDevice' | 'multiDevice'\n\t\t.addColumn(\"backed_up\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"transports\", \"text\") // JSON array\n\t\t.addColumn(\"name\", \"text\") // User-friendly name\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"last_used_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"credentials_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema.createIndex(\"idx_credentials_user\").on(\"credentials\").column(\"user_id\").execute();\n\n\t// Auth tokens (magic links, email verification, invites, recovery)\n\tawait db.schema\n\t\t.createTable(\"auth_tokens\")\n\t\t.addColumn(\"hash\", \"text\", (col) => col.primaryKey()) // SHA-256 hash of token\n\t\t.addColumn(\"user_id\", \"text\")\n\t\t.addColumn(\"email\", \"text\") // For pre-user tokens\n\t\t.addColumn(\"type\", \"text\", (col) => col.notNull()) // 'magic_link' | 'email_verify' | 'invite' | 'recovery'\n\t\t.addColumn(\"role\", \"integer\") // For invites\n\t\t.addColumn(\"invited_by\", \"text\")\n\t\t.addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"auth_tokens_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.addForeignKeyConstraint(\"auth_tokens_invited_by_fk\", [\"invited_by\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"set null\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema.createIndex(\"idx_auth_tokens_email\").on(\"auth_tokens\").column(\"email\").execute();\n\n\t// OAuth accounts (external provider links)\n\tawait db.schema\n\t\t.createTable(\"oauth_accounts\")\n\t\t.addColumn(\"provider\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"provider_account_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addPrimaryKeyConstraint(\"oauth_accounts_pk\", [\"provider\", \"provider_account_id\"])\n\t\t.addForeignKeyConstraint(\"oauth_accounts_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_oauth_accounts_user\")\n\t\t.on(\"oauth_accounts\")\n\t\t.column(\"user_id\")\n\t\t.execute();\n\n\t// Allowed domains for self-signup\n\tawait db.schema\n\t\t.createTable(\"allowed_domains\")\n\t\t.addColumn(\"domain\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"default_role\", \"integer\", (col) => col.notNull().defaultTo(20)) // CONTRIBUTOR\n\t\t.addColumn(\"enabled\", \"integer\", (col) => col.notNull().defaultTo(1))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// WebAuthn challenges (ephemeral, with TTL)\n\tawait db.schema\n\t\t.createTable(\"auth_challenges\")\n\t\t.addColumn(\"challenge\", \"text\", (col) => col.primaryKey()) // Base64url challenge\n\t\t.addColumn(\"type\", \"text\", (col) => col.notNull()) // 'registration' | 'authentication'\n\t\t.addColumn(\"user_id\", \"text\") // For registration, the user being registered\n\t\t.addColumn(\"data\", \"text\") // JSON for additional context\n\t\t.addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Index for efficient cleanup of expired challenges\n\tawait db.schema\n\t\t.createIndex(\"idx_auth_challenges_expires\")\n\t\t.on(\"auth_challenges\")\n\t\t.column(\"expires_at\")\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// Drop new tables\n\tawait db.schema.dropTable(\"auth_challenges\").execute();\n\tawait db.schema.dropTable(\"allowed_domains\").execute();\n\tawait db.schema.dropTable(\"oauth_accounts\").execute();\n\tawait db.schema.dropTable(\"auth_tokens\").execute();\n\tawait db.schema.dropTable(\"credentials\").execute();\n\n\t// Recreate old users table with password_hash\n\tawait db.schema\n\t\t.createTable(\"users_old\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"email\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"password_hash\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"name\", \"text\")\n\t\t.addColumn(\"role\", \"text\", (col) => col.defaultTo(\"subscriber\"))\n\t\t.addColumn(\"avatar_id\", \"text\")\n\t\t.addColumn(\"data\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Migrate data back (users will have empty password_hash)\n\tawait sql`\n\t\tINSERT INTO users_old (id, email, password_hash, name, role, data, created_at)\n\t\tSELECT\n\t\t\tid,\n\t\t\temail,\n\t\t\t'', -- No way to restore password\n\t\t\tname,\n\t\t\tCASE role\n\t\t\t\tWHEN 50 THEN 'admin'\n\t\t\t\tWHEN 40 THEN 'editor'\n\t\t\t\tWHEN 30 THEN 'author'\n\t\t\t\tWHEN 20 THEN 'contributor'\n\t\t\t\tELSE 'subscriber'\n\t\t\tEND,\n\t\t\tdata,\n\t\t\tcreated_at\n\t\tFROM users\n\t`.execute(db);\n\n\tawait db.schema.dropTable(\"users\").execute();\n\tawait sql`ALTER TABLE users_old RENAME TO users`.execute(db);\n\n\tawait db.schema.createIndex(\"idx_users_email\").on(\"users\").column(\"email\").execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\n/**\n * User disabled column - for soft-disabling users\n *\n * Changes:\n * - Adds disabled column to users table (INTEGER, default 0)\n * - Disabled users cannot log in\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// SQLite supports ADD COLUMN\n\tawait sql`ALTER TABLE users ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0`.execute(db);\n\n\t// Create index for querying active users\n\tawait db.schema.createIndex(\"idx_users_disabled\").on(\"users\").column(\"disabled\").execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// SQLite doesn't support DROP COLUMN directly, but we can drop the index\n\t// For full rollback, table would need to be recreated\n\tawait db.schema.dropIndex(\"idx_users_disabled\").execute();\n\n\t// SQLite 3.35.0+ supports DROP COLUMN, but for compatibility:\n\t// We'll leave the column but document that it's deprecated\n\t// In production, you'd recreate the table without the column\n}\n","import { type Kysely, sql } from \"kysely\";\n\n/**\n * Migration: Add sections tables and performance indexes\n *\n * Sections are reusable content blocks that can be inserted into any Portable Text field.\n * They provide a library of pre-built page sections (heroes, CTAs, testimonials, etc.)\n * that content authors can browse and insert with a single click.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Section categories table\n\tawait db.schema\n\t\t.createTable(\"_emdash_section_categories\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.execute();\n\n\t// Sections table\n\tawait db.schema\n\t\t.createTable(\"_emdash_sections\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"title\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"description\", \"text\")\n\t\t// Categorization\n\t\t.addColumn(\"category_id\", \"text\", (col) =>\n\t\t\tcol.references(\"_emdash_section_categories.id\").onDelete(\"set null\"),\n\t\t)\n\t\t.addColumn(\"keywords\", \"text\") // JSON array for search\n\t\t// Content (Portable Text array)\n\t\t.addColumn(\"content\", \"text\", (col) => col.notNull()) // JSON\n\t\t// Preview image (optional)\n\t\t.addColumn(\"preview_media_id\", \"text\")\n\t\t// Source tracking\n\t\t.addColumn(\"source\", \"text\", (col) => col.notNull().defaultTo(\"user\")) // 'theme', 'user', 'import'\n\t\t.addColumn(\"theme_id\", \"text\") // Which theme provided it (if source='theme')\n\t\t// Metadata\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.execute();\n\n\t// Index for efficient category lookups\n\tawait db.schema\n\t\t.createIndex(\"idx_sections_category\")\n\t\t.on(\"_emdash_sections\")\n\t\t.columns([\"category_id\"])\n\t\t.execute();\n\n\t// Index for filtering by source\n\tawait db.schema\n\t\t.createIndex(\"idx_sections_source\")\n\t\t.on(\"_emdash_sections\")\n\t\t.columns([\"source\"])\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropIndex(\"idx_content_taxonomies_term\").execute();\n\tawait db.schema.dropIndex(\"idx_media_mime_type\").execute();\n\tawait db.schema.dropTable(\"_emdash_sections\").execute();\n\tawait db.schema.dropTable(\"_emdash_section_categories\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\n/**\n * Migration: Search Support\n *\n * Adds search configuration to collections and searchable flag to fields.\n * FTS5 tables are created dynamically when search is enabled for a collection.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Add search_config to collections (JSON: { enabled, weights })\n\tawait db.schema.alterTable(\"_emdash_collections\").addColumn(\"search_config\", \"text\").execute();\n\n\t// Add searchable flag to fields\n\tawait db.schema\n\t\t.alterTable(\"_emdash_fields\")\n\t\t.addColumn(\"searchable\", \"integer\", (col) => col.defaultTo(0))\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// SQLite doesn't support DROP COLUMN in older versions, but modern SQLite does\n\t// These columns are safe to drop\n\tawait db.schema.alterTable(\"_emdash_fields\").dropColumn(\"searchable\").execute();\n\tawait db.schema.alterTable(\"_emdash_collections\").dropColumn(\"search_config\").execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { listTablesLike } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Add scheduled publishing support\n *\n * Adds scheduled_at column to all ec_* content tables.\n * When scheduled_at is set and status is 'scheduled', the content\n * will be auto-published when the scheduled time is reached.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Get all ec_* content tables\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\t// Add scheduled_at column to each content table\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(table.name)} \n\t\t\tADD COLUMN scheduled_at TEXT\n\t\t`.execute(db);\n\n\t\t// Create index for efficient scheduled content queries\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${table.name}_scheduled`)} \n\t\t\tON ${sql.ref(table.name)} (scheduled_at)\n\t\t\tWHERE scheduled_at IS NOT NULL AND status = 'scheduled'\n\t\t`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// Get all ec_* content tables\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\t// Drop scheduled_at column from each content table\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\t\t// Drop index first\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${table.name}_scheduled`)}\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(table.name)} \n\t\t\tDROP COLUMN scheduled_at\n\t\t`.execute(db);\n\t}\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Get all content tables\n\tconst tables = await db\n\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely migration runs against unknown schema\n\t\t.selectFrom(\"_emdash_collections\" as never)\n\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely migration runs against unknown schema\n\t\t.select(\"slug\" as never)\n\t\t.execute();\n\n\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely execute returns unknown[]; narrowing to known shape\n\tfor (const row of tables as Array<{ slug: string }>) {\n\t\tconst tableName = `ec_${row.slug}`;\n\n\t\t// Add live_revision_id column\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tADD COLUMN live_revision_id TEXT REFERENCES revisions(id)\n\t\t`.execute(db);\n\n\t\t// Add draft_revision_id column\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tADD COLUMN draft_revision_id TEXT REFERENCES revisions(id)\n\t\t`.execute(db);\n\n\t\t// Create indexes for the new columns\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${row.slug}_live_revision`)}\n\t\t\tON ${sql.ref(tableName)} (live_revision_id)\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${row.slug}_draft_revision`)}\n\t\t\tON ${sql.ref(tableName)} (draft_revision_id)\n\t\t`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tconst tables = await db\n\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely migration runs against unknown schema\n\t\t.selectFrom(\"_emdash_collections\" as never)\n\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely migration runs against unknown schema\n\t\t.select(\"slug\" as never)\n\t\t.execute();\n\n\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Kysely execute returns unknown[]; narrowing to known shape\n\tfor (const row of tables as Array<{ slug: string }>) {\n\t\tconst tableName = `ec_${row.slug}`;\n\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${row.slug}_draft_revision`)}\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${row.slug}_live_revision`)}\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tDROP COLUMN draft_revision_id\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tDROP COLUMN live_revision_id\n\t\t`.execute(db);\n\t}\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { listTablesLike } from \"../dialect-helpers.js\";\n\n/**\n * Add performance indexes for common query patterns.\n *\n * Covers:\n * 1. Media table: mime_type, filename, created_at\n * 2. content_taxonomies: reverse lookup by taxonomy_id\n * 3. taxonomies: parent_id FK\n * 4. audit_logs: compound (resource_type, resource_id)\n * 5. Retroactive author_id + updated_at on existing ec_* content tables\n * (new tables get these from createContentTable() in registry.ts)\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// ── Media indexes ────────────────────────────────────────────────\n\tawait db.schema.createIndex(\"idx_media_mime_type\").on(\"media\").column(\"mime_type\").execute();\n\tawait db.schema.createIndex(\"idx_media_filename\").on(\"media\").column(\"filename\").execute();\n\tawait db.schema.createIndex(\"idx_media_created_at\").on(\"media\").column(\"created_at\").execute();\n\n\t// ── Taxonomy indexes ─────────────────────────────────────────────\n\t// Reverse lookup: find entries with a specific term\n\tawait db.schema\n\t\t.createIndex(\"idx_content_taxonomies_term\")\n\t\t.on(\"content_taxonomies\")\n\t\t.column(\"taxonomy_id\")\n\t\t.execute();\n\n\t// Hierarchical queries filter on parent_id FK\n\tawait db.schema\n\t\t.createIndex(\"idx_taxonomies_parent\")\n\t\t.on(\"taxonomies\")\n\t\t.column(\"parent_id\")\n\t\t.execute();\n\n\t// ── Audit log indexes ────────────────────────────────────────────\n\t// findByResource() compound query\n\tawait db.schema\n\t\t.createIndex(\"idx_audit_resource\")\n\t\t.on(\"audit_logs\")\n\t\t.columns([\"resource_type\", \"resource_id\"])\n\t\t.execute();\n\n\t// ── Retroactive content table indexes ────────────────────────────\n\t// Add author_id and updated_at indexes to all existing ec_* tables.\n\t// New tables created after this migration get these from createContentTable().\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${table.name}_author`)} \n\t\t\tON ${sql.ref(table.name)} (author_id)\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${table.name}_updated`)} \n\t\t\tON ${sql.ref(table.name)} (updated_at)\n\t\t`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// Drop retroactive content table indexes\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${table.name}_updated`)}`.execute(db);\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${table.name}_author`)}`.execute(db);\n\t}\n\n\t// Drop system table indexes\n\tawait db.schema.dropIndex(\"idx_audit_resource\").execute();\n\tawait db.schema.dropIndex(\"idx_taxonomies_parent\").execute();\n\tawait db.schema.dropIndex(\"idx_content_taxonomies_term\").execute();\n\tawait db.schema.dropIndex(\"idx_media_created_at\").execute();\n\tawait db.schema.dropIndex(\"idx_media_filename\").execute();\n\tawait db.schema.dropIndex(\"idx_media_mime_type\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * API token tables for programmatic access.\n *\n * Three tables:\n * 1. _emdash_api_tokens — Personal Access Tokens (ec_pat_...)\n * 2. _emdash_oauth_tokens — OAuth access/refresh tokens (ec_oat_/ec_ort_...)\n * 3. _emdash_device_codes — OAuth Device Flow state (RFC 8628)\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// ── Personal Access Tokens ───────────────────────────────────────\n\tawait db.schema\n\t\t.createTable(\"_emdash_api_tokens\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"token_hash\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"prefix\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"scopes\", \"text\", (col) => col.notNull()) // JSON array\n\t\t.addColumn(\"expires_at\", \"text\") // null = no expiry\n\t\t.addColumn(\"last_used_at\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"api_tokens_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_api_tokens_token_hash\")\n\t\t.on(\"_emdash_api_tokens\")\n\t\t.column(\"token_hash\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_api_tokens_user_id\")\n\t\t.on(\"_emdash_api_tokens\")\n\t\t.column(\"user_id\")\n\t\t.execute();\n\n\t// ── OAuth Tokens ─────────────────────────────────────────────────\n\tawait db.schema\n\t\t.createTable(\"_emdash_oauth_tokens\")\n\t\t.addColumn(\"token_hash\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"token_type\", \"text\", (col) => col.notNull()) // 'access' | 'refresh'\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"scopes\", \"text\", (col) => col.notNull()) // JSON array\n\t\t.addColumn(\"client_type\", \"text\", (col) => col.notNull().defaultTo(\"cli\"))\n\t\t.addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"refresh_token_hash\", \"text\") // links access → refresh\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"oauth_tokens_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_oauth_tokens_user_id\")\n\t\t.on(\"_emdash_oauth_tokens\")\n\t\t.column(\"user_id\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_oauth_tokens_expires\")\n\t\t.on(\"_emdash_oauth_tokens\")\n\t\t.column(\"expires_at\")\n\t\t.execute();\n\n\t// ── Device Codes (OAuth Device Flow, RFC 8628) ───────────────────\n\tawait db.schema\n\t\t.createTable(\"_emdash_device_codes\")\n\t\t.addColumn(\"device_code\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"user_code\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"scopes\", \"text\", (col) => col.notNull()) // JSON array\n\t\t.addColumn(\"user_id\", \"text\") // set when user authorizes\n\t\t.addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"pending\"))\n\t\t.addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"interval\", \"integer\", (col) => col.notNull().defaultTo(5))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_device_codes\").execute();\n\tawait db.schema.dropTable(\"_emdash_oauth_tokens\").execute();\n\tawait db.schema.dropTable(\"_emdash_api_tokens\").execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Authorization codes for OAuth 2.1 Authorization Code + PKCE flow.\n *\n * Used by MCP clients (Claude Desktop, VS Code, etc.) to authenticate\n * via the standard OAuth authorization code grant.\n *\n * Also adds client_id tracking to oauth_tokens for per-client revocation.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema\n\t\t.createTable(\"_emdash_authorization_codes\")\n\t\t.addColumn(\"code_hash\", \"text\", (col) => col.primaryKey()) // SHA-256 hash of authorization code\n\t\t.addColumn(\"client_id\", \"text\", (col) => col.notNull()) // CIMD URL or opaque string\n\t\t.addColumn(\"redirect_uri\", \"text\", (col) => col.notNull()) // Must match exactly on exchange\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"scopes\", \"text\", (col) => col.notNull()) // JSON array\n\t\t.addColumn(\"code_challenge\", \"text\", (col) => col.notNull()) // S256 challenge\n\t\t.addColumn(\"code_challenge_method\", \"text\", (col) => col.notNull().defaultTo(\"S256\"))\n\t\t.addColumn(\"resource\", \"text\") // RFC 8707 resource indicator\n\t\t.addColumn(\"expires_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addForeignKeyConstraint(\"auth_codes_user_fk\", [\"user_id\"], \"users\", [\"id\"], (cb) =>\n\t\t\tcb.onDelete(\"cascade\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_auth_codes_expires\")\n\t\t.on(\"_emdash_authorization_codes\")\n\t\t.column(\"expires_at\")\n\t\t.execute();\n\n\t// Track which client obtained a token (for per-client revocation)\n\tawait sql`ALTER TABLE _emdash_oauth_tokens ADD COLUMN client_id TEXT`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_authorization_codes\").execute();\n\t// SQLite doesn't support DROP COLUMN, but this is only for dev rollback\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Migration: SEO support\n *\n * Creates:\n * - `_emdash_seo` table: per-content SEO metadata (separate from content tables)\n * - `has_seo` column on `_emdash_collections`: opt-in flag per collection\n *\n * SEO is not a universal concern — only collections representing web pages\n * need it. The `has_seo` flag controls whether the admin shows SEO fields\n * and whether the collection's content appears in sitemaps.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Create the SEO table\n\tawait db.schema\n\t\t.createTable(\"_emdash_seo\")\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"content_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"seo_title\", \"text\")\n\t\t.addColumn(\"seo_description\", \"text\")\n\t\t.addColumn(\"seo_image\", \"text\")\n\t\t.addColumn(\"seo_canonical\", \"text\")\n\t\t.addColumn(\"seo_no_index\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.notNull().defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.notNull().defaultTo(currentTimestamp(db)))\n\t\t.addPrimaryKeyConstraint(\"_emdash_seo_pk\", [\"collection\", \"content_id\"])\n\t\t.execute();\n\n\t// Index for batch lookups by collection (PK covers point lookups).\n\t// Sitemap queries join on (collection, content_id) which the PK covers,\n\t// and filter seo_no_index. This index supports getMany() batch queries.\n\tawait sql`\n\t\tCREATE INDEX idx_emdash_seo_collection\n\t\tON _emdash_seo (collection)\n\t`.execute(db);\n\n\t// Add has_seo flag to collections\n\tawait sql`\n\t\tALTER TABLE _emdash_collections\n\t\tADD COLUMN has_seo INTEGER NOT NULL DEFAULT 0\n\t`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait sql`DROP TABLE IF EXISTS _emdash_seo`.execute(db);\n\n\t// SQLite doesn't support DROP COLUMN before 3.35.0, but D1 does\n\tawait sql`\n\t\tALTER TABLE _emdash_collections\n\t\tDROP COLUMN has_seo\n\t`.execute(db);\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { isSqlite, listTablesLike } from \"../dialect-helpers.js\";\nimport { validateIdentifier } from \"../validate.js\";\n\n/**\n * Migration: i18n support (row-per-locale model)\n *\n * Each piece of content can exist in multiple locales. Translations of the\n * same content share a `translation_group` ULID while each row carries its\n * own `locale` code. Slugs are unique per-locale, not globally.\n *\n * Changes:\n * 1. For every ec_* content table:\n * - Rebuild the table to replace inline `slug TEXT UNIQUE` with\n * `slug TEXT` + a compound `UNIQUE(slug, locale)` constraint.\n * - Add `locale TEXT NOT NULL DEFAULT 'en'`\n * - Add `translation_group TEXT`\n * - Backfill `translation_group = id` for existing rows\n * - Recreate all standard indexes plus new locale/translation_group indexes\n *\n * 2. Add `translatable` column to `_emdash_fields`\n *\n * The table-rebuild approach is required because SQLite cannot drop an inline\n * UNIQUE constraint via ALTER TABLE. We use PRAGMA table_info to discover all\n * columns (including dynamic user-defined fields) and rebuild dynamically.\n */\n\n// Column info returned by PRAGMA table_info\ninterface ColumnInfo {\n\tcid: number;\n\tname: string;\n\ttype: string;\n\tnotnull: number;\n\tdflt_value: string | null;\n\tpk: number;\n}\n\n// Index info returned by PRAGMA index_list\ninterface IndexInfo {\n\tseq: number;\n\tname: string;\n\tunique: number;\n\torigin: string;\n\tpartial: number;\n}\n\n// Index column info returned by PRAGMA index_info\ninterface IndexColumnInfo {\n\tseqno: number;\n\tcid: number;\n\tname: string;\n}\n\n/**\n * Quote an identifier for use in raw SQL. Escapes embedded double-quotes\n * per SQL standard (double them). The name should first pass\n * validateIdentifier() or validateTableName() for defense-in-depth.\n */\nconst DOUBLE_QUOTE_RE = /\"/g;\nfunction quoteIdent(name: string): string {\n\treturn `\"${name.replace(DOUBLE_QUOTE_RE, '\"\"')}\"`;\n}\n\n/** Suffix added to tmp tables during i18n migration rebuild. */\nconst I18N_TMP_SUFFIX = /_i18n_tmp$/;\n\n/** Table names from sqlite_master are ec_{slug} — validate the pattern. */\nconst TABLE_NAME_PATTERN = /^ec_[a-z][a-z0-9_]*$/;\nfunction validateTableName(name: string): void {\n\tif (!TABLE_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`Invalid content table name: \"${name}\"`);\n\t}\n}\n\n/** SQLite column types produced by EmDash's schema registry. */\nconst ALLOWED_COLUMN_TYPES = new Set([\"TEXT\", \"INTEGER\", \"REAL\", \"BLOB\", \"JSON\", \"NUMERIC\", \"\"]);\nfunction validateColumnType(type: string, colName: string): void {\n\tif (!ALLOWED_COLUMN_TYPES.has(type.toUpperCase())) {\n\t\tthrow new Error(`Unexpected column type \"${type}\" for column \"${colName}\"`);\n\t}\n}\n\n/**\n * Validate that a default value expression from PRAGMA table_info is safe\n * to interpolate into DDL. Allows: string literals, numeric literals,\n * NULL, and known function calls like datetime('now').\n *\n * Note: PRAGMA table_info strips the outer parens from expression defaults,\n * so `DEFAULT (datetime('now'))` is reported as `datetime('now')`.\n * We accept both forms and re-wrap in parens via normalizeDdlDefault().\n */\nconst SAFE_DEFAULT_PATTERN =\n\t/^(?:'[^']*'|NULL|-?\\d+(?:\\.\\d+)?|\\(?datetime\\('now'\\)\\)?|\\(?json\\('[^']*'\\)\\)?|0|1)$/i;\nfunction validateDefaultValue(value: string, colName: string): void {\n\tif (!SAFE_DEFAULT_PATTERN.test(value)) {\n\t\tthrow new Error(`Unexpected default value \"${value}\" for column \"${colName}\"`);\n\t}\n}\n\n/**\n * Normalize a PRAGMA table_info default value for use in DDL.\n * Function-call defaults (e.g. `datetime('now')`) must be wrapped in parens\n * to form valid expression defaults: `DEFAULT (datetime('now'))`.\n * PRAGMA strips the outer parens, so we re-add them here.\n */\nconst FUNCTION_DEFAULT_PATTERN = /^(?:datetime|json)\\(/i;\nfunction normalizeDdlDefault(value: string): string {\n\t// Already wrapped in parens — return as-is\n\tif (value.startsWith(\"(\")) return value;\n\tif (FUNCTION_DEFAULT_PATTERN.test(value)) return `(${value})`;\n\treturn value;\n}\n\n/**\n * Validate that a CREATE INDEX statement from sqlite_master is safe to replay.\n * Must start with CREATE [UNIQUE] INDEX and not contain suspicious patterns.\n */\nconst CREATE_INDEX_PATTERN = /^CREATE\\s+(UNIQUE\\s+)?INDEX\\s+/i;\nfunction validateCreateIndexSql(sqlStr: string, idxName: string): void {\n\tif (!CREATE_INDEX_PATTERN.test(sqlStr)) {\n\t\tthrow new Error(`Unexpected index SQL for \"${idxName}\": does not match CREATE INDEX pattern`);\n\t}\n\t// Reject semicolons which could allow statement injection\n\tif (sqlStr.includes(\";\")) {\n\t\tthrow new Error(`Unexpected index SQL for \"${idxName}\": contains semicolon`);\n\t}\n}\n\n/**\n * PostgreSQL path: ALTER TABLE supports ADD COLUMN and DROP CONSTRAINT directly.\n * No table rebuild needed.\n */\nasync function upPostgres(db: Kysely<unknown>): Promise<void> {\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const t of tableNames) {\n\t\tvalidateTableName(t);\n\n\t\t// Check if already migrated (idempotency)\n\t\tconst hasLocale = await sql<{ exists: boolean }>`\n\t\t\tSELECT EXISTS(\n\t\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\t\tWHERE table_schema = 'public' AND table_name = ${t} AND column_name = 'locale'\n\t\t\t) as exists\n\t\t`.execute(db);\n\t\tif (hasLocale.rows[0]?.exists === true) continue;\n\n\t\t// Add i18n columns\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} ADD COLUMN locale TEXT NOT NULL DEFAULT 'en'`.execute(db);\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} ADD COLUMN translation_group TEXT`.execute(db);\n\n\t\t// Drop existing unique constraint on slug (Postgres auto-names these)\n\t\t// Find the constraint name first\n\t\tconst constraints = await sql<{ conname: string }>`\n\t\t\tSELECT conname FROM pg_constraint\n\t\t\tWHERE conrelid = ${t}::regclass\n\t\t\tAND contype = 'u'\n\t\t\tAND array_length(conkey, 1) = 1\n\t\t\tAND conkey[1] = (\n\t\t\t\tSELECT attnum FROM pg_attribute\n\t\t\t\tWHERE attrelid = ${t}::regclass AND attname = 'slug'\n\t\t\t)\n\t\t`.execute(db);\n\n\t\tfor (const c of constraints.rows) {\n\t\t\tawait sql`ALTER TABLE ${sql.ref(t)} DROP CONSTRAINT ${sql.ref(c.conname)}`.execute(db);\n\t\t}\n\n\t\t// Add compound unique constraint\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(t)}\n\t\t\tADD CONSTRAINT ${sql.ref(`${t}_slug_locale_unique`)} UNIQUE (slug, locale)\n\t\t`.execute(db);\n\n\t\t// Backfill translation_group\n\t\tawait sql`UPDATE ${sql.ref(t)} SET translation_group = id`.execute(db);\n\n\t\t// Create indexes\n\t\tawait sql`CREATE INDEX ${sql.ref(`idx_${t}_locale`)} ON ${sql.ref(t)} (locale)`.execute(db);\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${t}_translation_group`)}\n\t\t\tON ${sql.ref(t)} (translation_group)\n\t\t`.execute(db);\n\t}\n\n\t// Add translatable flag to fields table\n\tconst hasTranslatable = await sql<{ exists: boolean }>`\n\t\tSELECT EXISTS(\n\t\t\tSELECT 1 FROM information_schema.columns\n\t\t\tWHERE table_schema = 'public' AND table_name = '_emdash_fields' AND column_name = 'translatable'\n\t\t) as exists\n\t`.execute(db);\n\tif (hasTranslatable.rows[0]?.exists !== true) {\n\t\tawait sql`\n\t\t\tALTER TABLE _emdash_fields\n\t\t\tADD COLUMN translatable INTEGER NOT NULL DEFAULT 1\n\t\t`.execute(db);\n\t}\n}\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tif (!isSqlite(db)) {\n\t\treturn upPostgres(db);\n\t}\n\n\t// Clean up orphaned tmp tables from a previous partial run.\n\t// On D1 (no transactions), a crash mid-migration can leave these behind.\n\tconst orphanedTmps = await listTablesLike(db, \"ec_%_i18n_tmp\");\n\tfor (const tmpName of orphanedTmps) {\n\t\tvalidateTableName(tmpName.replace(I18N_TMP_SUFFIX, \"\"));\n\t\tawait sql`DROP TABLE IF EXISTS ${sql.ref(tmpName)}`.execute(db);\n\t}\n\n\t// Discover all ec_* content tables\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\tconst tables = { rows: tableNames.map((name) => ({ name })) };\n\n\tfor (const table of tables.rows) {\n\t\tconst t = table.name;\n\t\tvalidateTableName(t);\n\t\tconst tmp = `${t}_i18n_tmp`;\n\n\t\t// Note: no transaction wrapper — D1 doesn't support transactions,\n\t\t// and SQLite/better-sqlite3 is single-writer so crash-safety is\n\t\t// handled by the journal mode. The tmp table approach is already\n\t\t// crash-recoverable (orphaned tmp tables are harmless).\n\t\t{\n\t\t\tconst trx = db;\n\t\t\t// ── 1. Read existing column definitions ──────────────────────\n\t\t\tconst colResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.ref(t)})\n\t\t\t`.execute(trx);\n\t\t\tconst columns = colResult.rows;\n\n\t\t\t// ── Idempotency: skip tables already migrated ───────────────\n\t\t\t// On D1, the migrator can't use transactions, so a partially-\n\t\t\t// applied migration may not be recorded. If the table already\n\t\t\t// has a `locale` column, it was already rebuilt — skip it.\n\t\t\tif (columns.some((col) => col.name === \"locale\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// ── 2. Read existing indexes (to recreate after rebuild) ─────\n\t\t\tconst idxResult = await sql<IndexInfo>`\n\t\t\t\tPRAGMA index_list(${sql.ref(t)})\n\t\t\t`.execute(trx);\n\n\t\t\t// Collect non-autoindex, non-primary-key indexes for recreation\n\t\t\tconst indexDefs: { name: string; unique: boolean; columns: string[]; partial: number }[] = [];\n\t\t\tfor (const idx of idxResult.rows) {\n\t\t\t\t// Skip autoindexes (created by inline UNIQUE) — we're removing them\n\t\t\t\tif (idx.origin === \"pk\" || idx.name.startsWith(\"sqlite_autoindex_\")) continue;\n\n\t\t\t\tconst idxColResult = await sql<IndexColumnInfo>`\n\t\t\t\t\tPRAGMA index_info(${sql.ref(idx.name)})\n\t\t\t\t`.execute(trx);\n\n\t\t\t\tindexDefs.push({\n\t\t\t\t\tname: idx.name,\n\t\t\t\t\tunique: idx.unique === 1,\n\t\t\t\t\tcolumns: idxColResult.rows.map((c) => c.name),\n\t\t\t\t\tpartial: idx.partial,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// For partial indexes we need the original CREATE statement\n\t\t\tconst partialSqls = new Map<string, string>();\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\tif (idx.partial) {\n\t\t\t\t\tconst createResult = await sql<{ sql: string }>`\n\t\t\t\t\t\tSELECT sql FROM sqlite_master \n\t\t\t\t\t\tWHERE type = 'index' AND name = ${idx.name}\n\t\t\t\t\t`.execute(trx);\n\t\t\t\t\tif (createResult.rows[0]?.sql) {\n\t\t\t\t\t\tpartialSqls.set(idx.name, createResult.rows[0].sql);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── 3. Build column defs for the new table ──────────────────\n\t\t\t// Validate all column names from PRAGMA before using them in raw SQL.\n\t\t\t// These originate from our own schema, but defense-in-depth matters.\n\t\t\tfor (const col of columns) {\n\t\t\t\tvalidateIdentifier(col.name, \"column name\");\n\t\t\t}\n\n\t\t\t// Replace slug's inline UNIQUE with a table-level UNIQUE(slug, locale)\n\t\t\tconst colDefs: string[] = [];\n\t\t\tconst colNames: string[] = [];\n\n\t\t\tfor (const col of columns) {\n\t\t\t\tvalidateColumnType(col.type || \"TEXT\", col.name);\n\t\t\t\tcolNames.push(quoteIdent(col.name));\n\t\t\t\tlet def = `${quoteIdent(col.name)} ${col.type || \"TEXT\"}`;\n\n\t\t\t\tif (col.pk) {\n\t\t\t\t\tdef += \" PRIMARY KEY\";\n\t\t\t\t} else if (col.name === \"slug\") {\n\t\t\t\t\t// Intentionally omit UNIQUE — compound unique below\n\t\t\t\t} else {\n\t\t\t\t\tif (col.notnull) def += \" NOT NULL\";\n\t\t\t\t}\n\n\t\t\t\tif (col.dflt_value !== null) {\n\t\t\t\t\tvalidateDefaultValue(col.dflt_value, col.name);\n\t\t\t\t\tdef += ` DEFAULT ${normalizeDdlDefault(col.dflt_value)}`;\n\t\t\t\t}\n\n\t\t\t\tcolDefs.push(def);\n\t\t\t}\n\n\t\t\t// Append new i18n columns\n\t\t\tcolDefs.push(\"\\\"locale\\\" TEXT NOT NULL DEFAULT 'en'\");\n\t\t\tcolDefs.push('\"translation_group\" TEXT');\n\n\t\t\t// Compound unique: same slug + locale must be unique\n\t\t\tcolDefs.push('UNIQUE(\"slug\", \"locale\")');\n\n\t\t\tconst createColsSql = colDefs.join(\",\\n\\t\\t\\t\\t\");\n\t\t\tconst selectColsSql = colNames.join(\", \");\n\n\t\t\t// ── 4. Rebuild the table ────────────────────────────────────\n\t\t\t// Drop all existing indexes first (they reference the old table)\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(idx.name)}`.execute(trx);\n\t\t\t}\n\n\t\t\t// Create new table with updated schema\n\t\t\tawait sql\n\t\t\t\t.raw(`CREATE TABLE ${quoteIdent(tmp)} (\\n\\t\\t\\t\\t${createColsSql}\\n\\t\\t\\t)`)\n\t\t\t\t.execute(trx);\n\n\t\t\t// Copy existing data, backfilling locale='en' and translation_group=id\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`INSERT INTO ${quoteIdent(tmp)} (${selectColsSql}, \"locale\", \"translation_group\")\\n\\t\\t\\t SELECT ${selectColsSql}, 'en', \"id\" FROM ${quoteIdent(t)}`,\n\t\t\t\t)\n\t\t\t\t.execute(trx);\n\n\t\t\t// Swap tables\n\t\t\tawait sql`DROP TABLE ${sql.ref(t)}`.execute(trx);\n\t\t\tawait sql.raw(`ALTER TABLE ${quoteIdent(tmp)} RENAME TO ${quoteIdent(t)}`).execute(trx);\n\n\t\t\t// ── 5. Recreate all original indexes ────────────────────────\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\t// Skip the old slug-only index — replaced by slug_locale below\n\t\t\t\tif (idx.name === `idx_${t}_slug`) continue;\n\n\t\t\t\tif (idx.partial && partialSqls.has(idx.name)) {\n\t\t\t\t\t// Partial indexes — validate the SQL before replaying\n\t\t\t\t\tconst idxSql = partialSqls.get(idx.name)!;\n\t\t\t\t\tvalidateCreateIndexSql(idxSql, idx.name);\n\t\t\t\t\tawait sql.raw(idxSql).execute(trx);\n\t\t\t\t} else {\n\t\t\t\t\t// Validate index column names before interpolation\n\t\t\t\t\tfor (const c of idx.columns) {\n\t\t\t\t\t\tvalidateIdentifier(c, \"index column name\");\n\t\t\t\t\t}\n\t\t\t\t\tconst cols = idx.columns.map((c) => quoteIdent(c)).join(\", \");\n\t\t\t\t\tconst unique = idx.unique ? \"UNIQUE \" : \"\";\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(`CREATE ${unique}INDEX ${quoteIdent(idx.name)} ON ${quoteIdent(t)} (${cols})`)\n\t\t\t\t\t\t.execute(trx);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── 6. Create new i18n indexes ──────────────────────────────\n\t\t\t// slug_locale unique is handled by the table constraint above,\n\t\t\t// but we still want a regular slug index for non-locale-aware queries\n\t\t\tawait sql`\n\t\t\t\tCREATE INDEX ${sql.ref(`idx_${t}_slug`)} \n\t\t\t\tON ${sql.ref(t)} (slug)\n\t\t\t`.execute(trx);\n\n\t\t\tawait sql`\n\t\t\t\tCREATE INDEX ${sql.ref(`idx_${t}_locale`)} \n\t\t\t\tON ${sql.ref(t)} (locale)\n\t\t\t`.execute(trx);\n\n\t\t\tawait sql`\n\t\t\t\tCREATE INDEX ${sql.ref(`idx_${t}_translation_group`)} \n\t\t\t\tON ${sql.ref(t)} (translation_group)\n\t\t\t`.execute(trx);\n\t\t}\n\t}\n\n\t// ── 7. Add translatable flag to fields table ────────────────────\n\t// Guard against duplicate column — on D1 the migration may have\n\t// partially applied without being recorded (no transaction support).\n\tconst fieldCols = await sql<ColumnInfo>`\n\t\tPRAGMA table_info(_emdash_fields)\n\t`.execute(db);\n\tif (!fieldCols.rows.some((col) => col.name === \"translatable\")) {\n\t\tawait sql`\n\t\t\tALTER TABLE _emdash_fields \n\t\t\tADD COLUMN translatable INTEGER NOT NULL DEFAULT 1\n\t\t`.execute(db);\n\t}\n}\n\n/**\n * PostgreSQL down path: straightforward ALTER TABLE operations.\n */\nasync function downPostgres(db: Kysely<unknown>): Promise<void> {\n\tawait sql`ALTER TABLE _emdash_fields DROP COLUMN translatable`.execute(db);\n\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\tfor (const t of tableNames) {\n\t\tvalidateTableName(t);\n\n\t\t// Drop i18n indexes\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${t}_locale`)}`.execute(db);\n\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(`idx_${t}_translation_group`)}`.execute(db);\n\n\t\t// Drop compound unique constraint\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} DROP CONSTRAINT IF EXISTS ${sql.ref(`${t}_slug_locale_unique`)}`.execute(\n\t\t\tdb,\n\t\t);\n\n\t\t// Restore simple unique constraint on slug\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} ADD CONSTRAINT ${sql.ref(`${t}_slug_unique`)} UNIQUE (slug)`.execute(\n\t\t\tdb,\n\t\t);\n\n\t\t// Drop i18n columns\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} DROP COLUMN locale`.execute(db);\n\t\tawait sql`ALTER TABLE ${sql.ref(t)} DROP COLUMN translation_group`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tif (!isSqlite(db)) {\n\t\treturn downPostgres(db);\n\t}\n\n\t// Remove translatable column from fields table\n\tawait sql`\n\t\tALTER TABLE _emdash_fields\n\t\tDROP COLUMN translatable\n\t`.execute(db);\n\n\t// Discover all ec_* content tables\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const tableName of tableNames) {\n\t\tconst t = tableName;\n\t\tvalidateTableName(t);\n\t\tconst tmp = `${t}_i18n_tmp`;\n\n\t\t// No transaction — see comment in up() above.\n\t\t{\n\t\t\tconst trx = db;\n\t\t\t// ── 1. Read current column definitions ──────────────────────\n\t\t\tconst colResult = await sql<ColumnInfo>`\n\t\t\t\tPRAGMA table_info(${sql.ref(t)})\n\t\t\t`.execute(trx);\n\t\t\tconst columns = colResult.rows;\n\n\t\t\t// ── 2. Read current indexes ─────────────────────────────────\n\t\t\tconst idxResult = await sql<IndexInfo>`\n\t\t\t\tPRAGMA index_list(${sql.ref(t)})\n\t\t\t`.execute(trx);\n\n\t\t\tconst indexDefs: { name: string; unique: boolean; columns: string[]; partial: number }[] = [];\n\t\t\tfor (const idx of idxResult.rows) {\n\t\t\t\tif (idx.origin === \"pk\" || idx.name.startsWith(\"sqlite_autoindex_\")) continue;\n\n\t\t\t\tconst idxColResult = await sql<IndexColumnInfo>`\n\t\t\t\t\tPRAGMA index_info(${sql.ref(idx.name)})\n\t\t\t\t`.execute(trx);\n\n\t\t\t\tindexDefs.push({\n\t\t\t\t\tname: idx.name,\n\t\t\t\t\tunique: idx.unique === 1,\n\t\t\t\t\tcolumns: idxColResult.rows.map((c) => c.name),\n\t\t\t\t\tpartial: idx.partial,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Save partial index SQL\n\t\t\tconst partialSqls = new Map<string, string>();\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\tif (idx.partial) {\n\t\t\t\t\tconst createResult = await sql<{ sql: string }>`\n\t\t\t\t\t\tSELECT sql FROM sqlite_master \n\t\t\t\t\t\tWHERE type = 'index' AND name = ${idx.name}\n\t\t\t\t\t`.execute(trx);\n\t\t\t\t\tif (createResult.rows[0]?.sql) {\n\t\t\t\t\t\tpartialSqls.set(idx.name, createResult.rows[0].sql);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ── 3. Build column defs WITHOUT locale/translation_group ───\n\t\t\t// Validate all column names\n\t\t\tfor (const col of columns) {\n\t\t\t\tif (col.name === \"locale\" || col.name === \"translation_group\") continue;\n\t\t\t\tvalidateIdentifier(col.name, \"column name\");\n\t\t\t}\n\n\t\t\t// Restore slug's inline UNIQUE\n\t\t\tconst colDefs: string[] = [];\n\t\t\tconst colNames: string[] = [];\n\n\t\t\tfor (const col of columns) {\n\t\t\t\t// Skip i18n columns\n\t\t\t\tif (col.name === \"locale\" || col.name === \"translation_group\") continue;\n\n\t\t\t\tvalidateColumnType(col.type || \"TEXT\", col.name);\n\t\t\t\tcolNames.push(quoteIdent(col.name));\n\t\t\t\tlet def = `${quoteIdent(col.name)} ${col.type || \"TEXT\"}`;\n\n\t\t\t\tif (col.pk) {\n\t\t\t\t\tdef += \" PRIMARY KEY\";\n\t\t\t\t} else if (col.name === \"slug\") {\n\t\t\t\t\t// Restore inline UNIQUE\n\t\t\t\t\tdef += \" UNIQUE\";\n\t\t\t\t} else {\n\t\t\t\t\tif (col.notnull) def += \" NOT NULL\";\n\t\t\t\t}\n\n\t\t\t\tif (col.dflt_value !== null) {\n\t\t\t\t\tvalidateDefaultValue(col.dflt_value, col.name);\n\t\t\t\t\tdef += ` DEFAULT ${normalizeDdlDefault(col.dflt_value)}`;\n\t\t\t\t}\n\n\t\t\t\tcolDefs.push(def);\n\t\t\t}\n\n\t\t\tconst createColsSql = colDefs.join(\",\\n\\t\\t\\t\\t\");\n\t\t\tconst selectColsSql = colNames.join(\", \");\n\n\t\t\t// ── 4. Rebuild the table ────────────────────────────────────\n\t\t\t// Drop all existing indexes first\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\tawait sql`DROP INDEX IF EXISTS ${sql.ref(idx.name)}`.execute(trx);\n\t\t\t}\n\n\t\t\t// Create table with original schema (slug UNIQUE, no i18n columns)\n\t\t\tawait sql\n\t\t\t\t.raw(`CREATE TABLE ${quoteIdent(tmp)} (\\n\\t\\t\\t\\t${createColsSql}\\n\\t\\t\\t)`)\n\t\t\t\t.execute(trx);\n\n\t\t\t// Copy data — keep only one row per content item.\n\t\t\t// Prefer locale='en' rows. For items without an 'en' row, pick the\n\t\t\t// row with the smallest locale code (deterministic, unlike bare GROUP BY).\n\t\t\t// Handle NULL translation_group by treating each such row as its own group.\n\t\t\t// INSERT OR IGNORE skips any duplicate slugs from the fallback pass.\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`INSERT OR IGNORE INTO ${quoteIdent(tmp)} (${selectColsSql})\n\t\t\t SELECT ${selectColsSql} FROM ${quoteIdent(t)}\n\t\t\t WHERE \"locale\" = 'en'`,\n\t\t\t\t)\n\t\t\t\t.execute(trx);\n\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`INSERT OR IGNORE INTO ${quoteIdent(tmp)} (${selectColsSql})\n\t\t\t SELECT ${selectColsSql} FROM ${quoteIdent(t)}\n\t\t\t WHERE \"id\" NOT IN (SELECT \"id\" FROM ${quoteIdent(tmp)})\n\t\t\t AND \"id\" IN (\n\t\t\t\tSELECT \"id\" FROM ${quoteIdent(t)} AS t2\n\t\t\t\tWHERE t2.\"translation_group\" IS NOT NULL\n\t\t\t\tAND t2.\"locale\" = (\n\t\t\t\t\tSELECT MIN(t3.\"locale\") FROM ${quoteIdent(t)} AS t3\n\t\t\t\t\tWHERE t3.\"translation_group\" = t2.\"translation_group\"\n\t\t\t\t)\n\t\t\t )`,\n\t\t\t\t)\n\t\t\t\t.execute(trx);\n\n\t\t\t// Pick up any rows with NULL translation_group that weren't already copied\n\t\t\tawait sql\n\t\t\t\t.raw(\n\t\t\t\t\t`INSERT OR IGNORE INTO ${quoteIdent(tmp)} (${selectColsSql})\n\t\t\t SELECT ${selectColsSql} FROM ${quoteIdent(t)}\n\t\t\t WHERE \"id\" NOT IN (SELECT \"id\" FROM ${quoteIdent(tmp)})\n\t\t\t AND \"translation_group\" IS NULL`,\n\t\t\t\t)\n\t\t\t\t.execute(trx);\n\n\t\t\t// Swap tables\n\t\t\tawait sql`DROP TABLE ${sql.ref(t)}`.execute(trx);\n\t\t\tawait sql.raw(`ALTER TABLE ${quoteIdent(tmp)} RENAME TO ${quoteIdent(t)}`).execute(trx);\n\n\t\t\t// ── 5. Recreate indexes ─────────────────────────────────────\n\t\t\tfor (const idx of indexDefs) {\n\t\t\t\t// Skip i18n-specific indexes — they don't exist in the old schema\n\t\t\t\tif (idx.name === `idx_${t}_locale`) continue;\n\t\t\t\tif (idx.name === `idx_${t}_translation_group`) continue;\n\n\t\t\t\tif (idx.partial && partialSqls.has(idx.name)) {\n\t\t\t\t\t// Partial indexes — validate the SQL before replaying\n\t\t\t\t\tconst idxSql = partialSqls.get(idx.name)!;\n\t\t\t\t\tvalidateCreateIndexSql(idxSql, idx.name);\n\t\t\t\t\tawait sql.raw(idxSql).execute(trx);\n\t\t\t\t} else {\n\t\t\t\t\t// Filter out i18n columns from any index that might reference them\n\t\t\t\t\tconst cols = idx.columns.filter((c) => c !== \"locale\" && c !== \"translation_group\");\n\t\t\t\t\tif (cols.length === 0) continue;\n\n\t\t\t\t\t// Validate column names\n\t\t\t\t\tfor (const c of cols) {\n\t\t\t\t\t\tvalidateIdentifier(c, \"index column name\");\n\t\t\t\t\t}\n\t\t\t\t\tconst colsSql = cols.map((c) => quoteIdent(c)).join(\", \");\n\t\t\t\t\tconst unique = idx.unique ? \"UNIQUE \" : \"\";\n\t\t\t\t\tawait sql\n\t\t\t\t\t\t.raw(`CREATE ${unique}INDEX ${quoteIdent(idx.name)} ON ${quoteIdent(t)} (${colsSql})`)\n\t\t\t\t\t\t.execute(trx);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\n/**\n * Migration: URL pattern for collections\n *\n * Adds `url_pattern` column to `_emdash_collections` so each collection\n * can declare its own URL structure (e.g. \"/{slug}\" for pages, \"/blog/{slug}\"\n * for posts). Used for menu URL resolution, sitemaps, and path-based lookups.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE _emdash_collections\n\t\tADD COLUMN url_pattern TEXT\n\t`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE _emdash_collections\n\t\tDROP COLUMN url_pattern\n\t`.execute(db);\n}\n","import { type Kysely, sql } from \"kysely\";\n\n/**\n * Migration: Remove section categories\n *\n * Section categories had a complete backend but no UI to create or manage them.\n * Rather than building the missing UI for a feature with very little need at this stage,\n * we're removing the feature entirely.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Drop index before column — SQLite requires this order\n\tawait db.schema.dropIndex(\"idx_sections_category\").ifExists().execute();\n\n\tawait db.schema.alterTable(\"_emdash_sections\").dropColumn(\"category_id\").execute();\n\n\tawait db.schema.dropTable(\"_emdash_section_categories\").execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\t// Recreate section categories table\n\tawait db.schema\n\t\t.createTable(\"_emdash_section_categories\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"label\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))\n\t\t.execute();\n\n\t// Re-add category_id column to sections\n\tawait db.schema\n\t\t.alterTable(\"_emdash_sections\")\n\t\t.addColumn(\"category_id\", \"text\", (col) =>\n\t\t\tcol.references(\"_emdash_section_categories.id\").onDelete(\"set null\"),\n\t\t)\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_sections_category\")\n\t\t.on(\"_emdash_sections\")\n\t\t.columns([\"category_id\"])\n\t\t.execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\n/**\n * Migration: Add marketplace fields to _plugin_state\n *\n * Adds `source` and `marketplace_version` columns to track\n * whether a plugin was installed from config or marketplace,\n * and which marketplace version is installed.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// source: 'config' (declared in astro.config) or 'marketplace' (installed from registry)\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tADD COLUMN source TEXT NOT NULL DEFAULT 'config'\n\t`.execute(db);\n\n\t// marketplace_version: tracks installed version for update checking\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tADD COLUMN marketplace_version TEXT\n\t`.execute(db);\n\n\t// Index for efficient marketplace plugin queries on cold start\n\tawait sql`\n\t\tCREATE INDEX idx_plugin_state_source\n\t\tON _plugin_state (source)\n\t\tWHERE source = 'marketplace'\n\t`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tDROP INDEX IF EXISTS idx_plugin_state_source\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tDROP COLUMN marketplace_version\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tDROP COLUMN source\n\t`.execute(db);\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\n/**\n * Migration: Add display metadata to _plugin_state\n *\n * Stores display_name and description for marketplace plugins\n * so the admin UI can show meaningful info without re-fetching\n * from the marketplace on every page load.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tADD COLUMN display_name TEXT\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tADD COLUMN description TEXT\n\t`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tDROP COLUMN description\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE _plugin_state\n\t\tDROP COLUMN display_name\n\t`.execute(db);\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\n/**\n * Migration: Add placeholder columns to media table\n *\n * Stores blurhash and dominant_color for LQIP (Low Quality Image Placeholder)\n * support. Generated at upload time from image pixel data.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE media\n\t\tADD COLUMN blurhash TEXT\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE media\n\t\tADD COLUMN dominant_color TEXT\n\t`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait sql`\n\t\tALTER TABLE media\n\t\tDROP COLUMN dominant_color\n\t`.execute(db);\n\n\tawait sql`\n\t\tALTER TABLE media\n\t\tDROP COLUMN blurhash\n\t`.execute(db);\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Create OAuth clients table\n *\n * Implements the oauth_clients registry so that the authorization endpoint\n * can validate client_id and enforce a per-client redirect URI allowlist.\n *\n * Each client has a set of pre-registered redirect URIs (JSON array).\n * The authorize endpoint rejects any redirect_uri not in the client's list.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema\n\t\t.createTable(\"_emdash_oauth_clients\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey()) // Client ID (e.g. URL or opaque string)\n\t\t.addColumn(\"name\", \"text\", (col) => col.notNull()) // Human-readable name\n\t\t.addColumn(\"redirect_uris\", \"text\", (col) => col.notNull()) // JSON array of allowed redirect URIs\n\t\t.addColumn(\"scopes\", \"text\") // JSON array of allowed scopes (null = all)\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_oauth_clients\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Create cron tasks table for plugin scheduled tasks.\n *\n * Each plugin can register cron tasks (recurring or one-shot) which are\n * stored here and executed by the platform-specific scheduler.\n *\n * The `next_run_at` + `status` + `enabled` index drives the \"find overdue\n * tasks\" query used by CronExecutor.tick().\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema\n\t\t.createTable(\"_emdash_cron_tasks\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"plugin_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"task_name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"schedule\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"is_oneshot\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"data\", \"text\") // JSON\n\t\t.addColumn(\"next_run_at\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"last_run_at\", \"text\")\n\t\t.addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"idle\"))\n\t\t.addColumn(\"locked_at\", \"text\")\n\t\t.addColumn(\"enabled\", \"integer\", (col) => col.notNull().defaultTo(1))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addUniqueConstraint(\"uq_cron_tasks_plugin_task\", [\"plugin_id\", \"task_name\"])\n\t\t.execute();\n\n\t// Equality columns first (enabled, status), then range column (next_run_at)\n\t// for optimal B-tree index usage in the tick query.\n\tawait db.schema\n\t\t.createIndex(\"idx_cron_tasks_due\")\n\t\t.on(\"_emdash_cron_tasks\")\n\t\t.columns([\"enabled\", \"status\", \"next_run_at\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_cron_tasks_plugin\")\n\t\t.on(\"_emdash_cron_tasks\")\n\t\t.column(\"plugin_id\")\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_cron_tasks\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Create the comments table\n\tawait db.schema\n\t\t.createTable(\"_emdash_comments\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"collection\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"content_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"parent_id\", \"text\", (col) =>\n\t\t\tcol.references(\"_emdash_comments.id\").onDelete(\"cascade\"),\n\t\t)\n\t\t.addColumn(\"author_name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"author_email\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"author_url\", \"text\")\n\t\t.addColumn(\"author_user_id\", \"text\", (col) => col.references(\"users.id\").onDelete(\"set null\"))\n\t\t.addColumn(\"body\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(\"pending\"))\n\t\t.addColumn(\"ip_hash\", \"text\")\n\t\t.addColumn(\"user_agent\", \"text\")\n\t\t.addColumn(\"moderation_metadata\", \"text\") // JSON\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Indexes\n\tawait db.schema\n\t\t.createIndex(\"idx_comments_content\")\n\t\t.on(\"_emdash_comments\")\n\t\t.columns([\"collection\", \"content_id\", \"status\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_comments_parent\")\n\t\t.on(\"_emdash_comments\")\n\t\t.column(\"parent_id\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_comments_status\")\n\t\t.on(\"_emdash_comments\")\n\t\t.columns([\"status\", \"created_at\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_comments_author_email\")\n\t\t.on(\"_emdash_comments\")\n\t\t.column(\"author_email\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_comments_author_user\")\n\t\t.on(\"_emdash_comments\")\n\t\t.column(\"author_user_id\")\n\t\t.execute();\n\n\t// Add collection-level comment settings columns\n\tawait db.schema\n\t\t.alterTable(\"_emdash_collections\")\n\t\t.addColumn(\"comments_enabled\", \"integer\", (col) => col.defaultTo(0))\n\t\t.execute();\n\n\tawait db.schema\n\t\t.alterTable(\"_emdash_collections\")\n\t\t.addColumn(\"comments_moderation\", \"text\", (col) => col.defaultTo(\"first_time\"))\n\t\t.execute();\n\n\tawait db.schema\n\t\t.alterTable(\"_emdash_collections\")\n\t\t.addColumn(\"comments_closed_after_days\", \"integer\", (col) => col.defaultTo(90))\n\t\t.execute();\n\n\tawait db.schema\n\t\t.alterTable(\"_emdash_collections\")\n\t\t.addColumn(\"comments_auto_approve_users\", \"integer\", (col) => col.defaultTo(1))\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_comments\").execute();\n\n\t// Note: SQLite doesn't support DROP COLUMN before 3.35.0.\n\t// For down migrations on the collection settings columns, the table\n\t// would need to be rebuilt. Skipping for simplicity in v0.\n}\n","import { sql, type Kysely } from \"kysely\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait sql`ALTER TABLE _emdash_comments DROP COLUMN author_url`.execute(db);\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.alterTable(\"_emdash_comments\").addColumn(\"author_url\", \"text\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\nimport { currentTimestamp } from \"../dialect-helpers.js\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// Redirect rules table\n\tawait db.schema\n\t\t.createTable(\"_emdash_redirects\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"source\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"destination\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"type\", \"integer\", (col) => col.notNull().defaultTo(301))\n\t\t.addColumn(\"is_pattern\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"enabled\", \"integer\", (col) => col.notNull().defaultTo(1))\n\t\t.addColumn(\"hits\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"last_hit_at\", \"text\")\n\t\t.addColumn(\"group_name\", \"text\")\n\t\t.addColumn(\"auto\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\t// Unique source for exact (non-pattern) rules\n\t// SQLite doesn't support partial indexes with WHERE on all versions,\n\t// so we use a regular index and enforce uniqueness in the application layer\n\tawait db.schema\n\t\t.createIndex(\"idx_redirects_source\")\n\t\t.on(\"_emdash_redirects\")\n\t\t.column(\"source\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_redirects_enabled\")\n\t\t.on(\"_emdash_redirects\")\n\t\t.column(\"enabled\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_redirects_group\")\n\t\t.on(\"_emdash_redirects\")\n\t\t.column(\"group_name\")\n\t\t.execute();\n\n\t// 404 log table\n\tawait db.schema\n\t\t.createTable(\"_emdash_404_log\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"path\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"referrer\", \"text\")\n\t\t.addColumn(\"user_agent\", \"text\")\n\t\t.addColumn(\"ip\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\tawait db.schema.createIndex(\"idx_404_log_path\").on(\"_emdash_404_log\").column(\"path\").execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_404_log_created\")\n\t\t.on(\"_emdash_404_log\")\n\t\t.column(\"created_at\")\n\t\t.execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_404_log\").execute();\n\tawait db.schema.dropTable(\"_emdash_redirects\").execute();\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { listTablesLike } from \"../dialect-helpers.js\";\n\n/**\n * Migration: Widen scheduled publishing index\n *\n * The original partial index (013) only covered status='scheduled'.\n * Published posts can now have scheduled draft changes, so widen the\n * index to cover all rows where scheduled_at IS NOT NULL.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${table.name}_scheduled`)}\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${table.name}_scheduled`)}\n\t\t\tON ${sql.ref(table.name)} (scheduled_at)\n\t\t\tWHERE scheduled_at IS NOT NULL\n\t\t`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\n\tfor (const tableName of tableNames) {\n\t\tconst table = { name: tableName };\n\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${table.name}_scheduled`)}\n\t\t`.execute(db);\n\n\t\t// Restore the original narrower index\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${table.name}_scheduled`)}\n\t\t\tON ${sql.ref(table.name)} (scheduled_at)\n\t\t\tWHERE scheduled_at IS NOT NULL AND status = 'scheduled'\n\t\t`.execute(db);\n\t}\n}\n","import type { Kysely } from \"kysely\";\nimport { sql } from \"kysely\";\n\nimport { currentTimestamp, listTablesLike } from \"../dialect-helpers.js\";\n\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema\n\t\t.createTable(\"_emdash_bylines\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"slug\", \"text\", (col) => col.notNull().unique())\n\t\t.addColumn(\"display_name\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"bio\", \"text\")\n\t\t.addColumn(\"avatar_media_id\", \"text\", (col) => col.references(\"media.id\").onDelete(\"set null\"))\n\t\t.addColumn(\"website_url\", \"text\")\n\t\t.addColumn(\"user_id\", \"text\", (col) => col.references(\"users.id\").onDelete(\"set null\"))\n\t\t.addColumn(\"is_guest\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addColumn(\"updated_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.execute();\n\n\tawait sql`\n\t\tCREATE UNIQUE INDEX ${sql.ref(\"idx_bylines_user_id_unique\")}\n\t\tON ${sql.ref(\"_emdash_bylines\")} (user_id)\n\t\tWHERE user_id IS NOT NULL\n\t`.execute(db);\n\n\tawait db.schema.createIndex(\"idx_bylines_slug\").on(\"_emdash_bylines\").column(\"slug\").execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_bylines_display_name\")\n\t\t.on(\"_emdash_bylines\")\n\t\t.column(\"display_name\")\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createTable(\"_emdash_content_bylines\")\n\t\t.addColumn(\"id\", \"text\", (col) => col.primaryKey())\n\t\t.addColumn(\"collection_slug\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"content_id\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"byline_id\", \"text\", (col) =>\n\t\t\tcol.notNull().references(\"_emdash_bylines.id\").onDelete(\"cascade\"),\n\t\t)\n\t\t.addColumn(\"sort_order\", \"integer\", (col) => col.notNull().defaultTo(0))\n\t\t.addColumn(\"role_label\", \"text\")\n\t\t.addColumn(\"created_at\", \"text\", (col) => col.defaultTo(currentTimestamp(db)))\n\t\t.addUniqueConstraint(\"content_bylines_unique\", [\"collection_slug\", \"content_id\", \"byline_id\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_content_bylines_content\")\n\t\t.on(\"_emdash_content_bylines\")\n\t\t.columns([\"collection_slug\", \"content_id\", \"sort_order\"])\n\t\t.execute();\n\n\tawait db.schema\n\t\t.createIndex(\"idx_content_bylines_byline\")\n\t\t.on(\"_emdash_content_bylines\")\n\t\t.column(\"byline_id\")\n\t\t.execute();\n\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\tfor (const tableName of tableNames) {\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tADD COLUMN primary_byline_id TEXT\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tCREATE INDEX ${sql.ref(`idx_${tableName}_primary_byline`)}\n\t\t\tON ${sql.ref(tableName)} (primary_byline_id)\n\t\t`.execute(db);\n\t}\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tconst tableNames = await listTablesLike(db, \"ec_%\");\n\tfor (const tableName of tableNames) {\n\t\tawait sql`\n\t\t\tDROP INDEX IF EXISTS ${sql.ref(`idx_${tableName}_primary_byline`)}\n\t\t`.execute(db);\n\n\t\tawait sql`\n\t\t\tALTER TABLE ${sql.ref(tableName)}\n\t\t\tDROP COLUMN primary_byline_id\n\t\t`.execute(db);\n\t}\n\n\tawait db.schema.dropTable(\"_emdash_content_bylines\").execute();\n\tawait db.schema.dropTable(\"_emdash_bylines\").execute();\n}\n","import type { Kysely } from \"kysely\";\n\n/**\n * Migration: Rate limits table + device code polling tracking.\n *\n * 1. Create _emdash_rate_limits for database-backed rate limiting\n * of unauthenticated endpoints (device code, magic link, passkey).\n *\n * 2. Add last_polled_at column to _emdash_device_codes for\n * RFC 8628 slow_down enforcement.\n */\nexport async function up(db: Kysely<unknown>): Promise<void> {\n\t// ── Rate limits table ────────────────────────────────────────────\n\tawait db.schema\n\t\t.createTable(\"_emdash_rate_limits\")\n\t\t.addColumn(\"key\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"window\", \"text\", (col) => col.notNull())\n\t\t.addColumn(\"count\", \"integer\", (col) => col.notNull().defaultTo(1))\n\t\t.addPrimaryKeyConstraint(\"pk_rate_limits\", [\"key\", \"window\"])\n\t\t.execute();\n\n\t// Index on window for efficient cleanup of expired entries\n\tawait db.schema\n\t\t.createIndex(\"idx_rate_limits_window\")\n\t\t.on(\"_emdash_rate_limits\")\n\t\t.column(\"window\")\n\t\t.execute();\n\n\t// ── Device code polling tracking ─────────────────────────────────\n\tawait db.schema.alterTable(\"_emdash_device_codes\").addColumn(\"last_polled_at\", \"text\").execute();\n}\n\nexport async function down(db: Kysely<unknown>): Promise<void> {\n\tawait db.schema.dropTable(\"_emdash_rate_limits\").execute();\n\n\t// SQLite doesn't support DROP COLUMN before 3.35.0, but since this is\n\t// dev-only (v0, no migrations in production), we accept the limitation.\n\tawait db.schema.alterTable(\"_emdash_device_codes\").dropColumn(\"last_polled_at\").execute();\n}\n","import { type Kysely, type Migration, type MigrationProvider, Migrator } from \"kysely\";\n\nimport type { Database } from \"../types.js\";\n// Import migrations statically for bundling\nimport * as m001 from \"./001_initial.js\";\nimport * as m002 from \"./002_media_status.js\";\nimport * as m003 from \"./003_schema_registry.js\";\nimport * as m004 from \"./004_plugins.js\";\nimport * as m005 from \"./005_menus.js\";\nimport * as m006 from \"./006_taxonomy_defs.js\";\nimport * as m007 from \"./007_widgets.js\";\nimport * as m008 from \"./008_auth.js\";\nimport * as m009 from \"./009_user_disabled.js\";\nimport * as m011 from \"./011_sections.js\";\nimport * as m012 from \"./012_search.js\";\nimport * as m013 from \"./013_scheduled_publishing.js\";\nimport * as m014 from \"./014_draft_revisions.js\";\nimport * as m015 from \"./015_indexes.js\";\nimport * as m016 from \"./016_api_tokens.js\";\nimport * as m017 from \"./017_authorization_codes.js\";\nimport * as m018 from \"./018_seo.js\";\nimport * as m019 from \"./019_i18n.js\";\nimport * as m020 from \"./020_collection_url_pattern.js\";\nimport * as m021 from \"./021_remove_section_categories.js\";\nimport * as m022 from \"./022_marketplace_plugin_state.js\";\nimport * as m023 from \"./023_plugin_metadata.js\";\nimport * as m024 from \"./024_media_placeholders.js\";\nimport * as m025 from \"./025_oauth_clients.js\";\nimport * as m026 from \"./026_cron_tasks.js\";\nimport * as m027 from \"./027_comments.js\";\nimport * as m028 from \"./028_drop_author_url.js\";\nimport * as m029 from \"./029_redirects.js\";\nimport * as m030 from \"./030_widen_scheduled_index.js\";\nimport * as m031 from \"./031_bylines.js\";\nimport * as m032 from \"./032_rate_limits.js\";\n\n/**\n * Migration provider that uses statically imported migrations.\n * This approach works well with bundlers and avoids filesystem access.\n */\nclass StaticMigrationProvider implements MigrationProvider {\n\tasync getMigrations(): Promise<Record<string, Migration>> {\n\t\treturn {\n\t\t\t\"001_initial\": m001,\n\t\t\t\"002_media_status\": m002,\n\t\t\t\"003_schema_registry\": m003,\n\t\t\t\"004_plugins\": m004,\n\t\t\t\"005_menus\": m005,\n\t\t\t\"006_taxonomy_defs\": m006,\n\t\t\t\"007_widgets\": m007,\n\t\t\t\"008_auth\": m008,\n\t\t\t\"009_user_disabled\": m009,\n\t\t\t\"011_sections\": m011,\n\t\t\t\"012_search\": m012,\n\t\t\t\"013_scheduled_publishing\": m013,\n\t\t\t\"014_draft_revisions\": m014,\n\t\t\t\"015_indexes\": m015,\n\t\t\t\"016_api_tokens\": m016,\n\t\t\t\"017_authorization_codes\": m017,\n\t\t\t\"018_seo\": m018,\n\t\t\t\"019_i18n\": m019,\n\t\t\t\"020_collection_url_pattern\": m020,\n\t\t\t\"021_remove_section_categories\": m021,\n\t\t\t\"022_marketplace_plugin_state\": m022,\n\t\t\t\"023_plugin_metadata\": m023,\n\t\t\t\"024_media_placeholders\": m024,\n\t\t\t\"025_oauth_clients\": m025,\n\t\t\t\"026_cron_tasks\": m026,\n\t\t\t\"027_comments\": m027,\n\t\t\t\"028_drop_author_url\": m028,\n\t\t\t\"029_redirects\": m029,\n\t\t\t\"030_widen_scheduled_index\": m030,\n\t\t\t\"031_bylines\": m031,\n\t\t\t\"032_rate_limits\": m032,\n\t\t};\n\t}\n}\n\nexport interface MigrationStatus {\n\tapplied: string[];\n\tpending: string[];\n}\n\n/** Custom migration table name */\nconst MIGRATION_TABLE = \"_emdash_migrations\";\nconst MIGRATION_LOCK_TABLE = \"_emdash_migrations_lock\";\n\n/**\n * Get migration status\n */\nexport async function getMigrationStatus(db: Kysely<Database>): Promise<MigrationStatus> {\n\tconst migrator = new Migrator({\n\t\tdb,\n\t\tprovider: new StaticMigrationProvider(),\n\t\tmigrationTableName: MIGRATION_TABLE,\n\t\tmigrationLockTableName: MIGRATION_LOCK_TABLE,\n\t});\n\n\tconst migrations = await migrator.getMigrations();\n\n\tconst applied: string[] = [];\n\tconst pending: string[] = [];\n\n\tfor (const migration of migrations) {\n\t\tif (migration.executedAt) {\n\t\t\tapplied.push(migration.name);\n\t\t} else {\n\t\t\tpending.push(migration.name);\n\t\t}\n\t}\n\n\treturn { applied, pending };\n}\n\n/**\n * Run all pending migrations\n */\nexport async function runMigrations(db: Kysely<Database>): Promise<{ applied: string[] }> {\n\tconst migrator = new Migrator({\n\t\tdb,\n\t\tprovider: new StaticMigrationProvider(),\n\t\tmigrationTableName: MIGRATION_TABLE,\n\t\tmigrationLockTableName: MIGRATION_LOCK_TABLE,\n\t});\n\n\tconst { error, results } = await migrator.migrateToLatest();\n\n\tconst applied = results?.filter((r) => r.status === \"Success\").map((r) => r.migrationName) ?? [];\n\n\tif (error) {\n\t\t// Kysely sometimes wraps errors with an empty message. Check cause and\n\t\t// failed migration results for the real error.\n\t\tlet msg = error instanceof Error ? error.message : JSON.stringify(error);\n\t\tif (!msg && error instanceof Error && error.cause) {\n\t\t\tmsg = error.cause instanceof Error ? error.cause.message : JSON.stringify(error.cause);\n\t\t}\n\t\tconst failedMigration = results?.find((r) => r.status === \"Error\");\n\t\tif (failedMigration) {\n\t\t\tmsg = `${msg || \"unknown error\"} (migration: ${failedMigration.migrationName})`;\n\t\t}\n\t\tthrow new Error(`Migration failed: ${msg}`);\n\t}\n\n\treturn { applied };\n}\n\n/**\n * Rollback the last migration\n */\nexport async function rollbackMigration(\n\tdb: Kysely<Database>,\n): Promise<{ rolledBack: string | null }> {\n\tconst migrator = new Migrator({\n\t\tdb,\n\t\tprovider: new StaticMigrationProvider(),\n\t\tmigrationTableName: MIGRATION_TABLE,\n\t\tmigrationLockTableName: MIGRATION_LOCK_TABLE,\n\t});\n\n\tconst { error, results } = await migrator.migrateDown();\n\n\tconst rolledBack = results?.[0]?.status === \"Success\" ? results[0].migrationName : null;\n\n\tif (error) {\n\t\tconst msg = error instanceof Error ? error.message : JSON.stringify(error);\n\t\tthrow new Error(`Rollback failed: ${msg}`);\n\t}\n\n\treturn { rolledBack };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAWA,eAAsBA,MAAG,IAAoC;AAG5D,OAAM,GAAG,OACP,YAAY,YAAY,CACxB,aAAa,CACb,UAAU,MAAM,SAAS,QAAQ,IAAI,YAAY,CAAC,CAClD,UAAU,cAAc,SAAS,QAAQ,IAAI,SAAS,CAAC,CACvD,UAAU,YAAY,SAAS,QAAQ,IAAI,SAAS,CAAC,CACrD,UAAU,QAAQ,SAAS,QAAQ,IAAI,SAAS,CAAC,CACjD,UAAU,aAAa,OAAO,CAC9B,UAAU,cAAc,SAAS,QAAQ,IAAI,UAAU,iBAAiB,GAAG,CAAC,CAAC,CAC7E,SAAS;AAEX,OAAM,GAAG,OACP,YAAY,sBAAsB,CACl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;EAsDzC,kBAAA,CAAmB,QAAA,EAAU,mBAAA,GAAsB,OAAA,CAAQ,eAAA;EASjE,YAAA,CAAa,GAAA;AAAA;;;;;iBAgBE,aAAA,CAAc,MAAA,EAAQ,MAAA,oBAA0B,OAAA"}
1
+ {"version":3,"file":"local.d.mts","names":[],"sources":["../../src/storage/local.ts"],"mappings":";;;;;;cAuCa,YAAA,YAAwB,OAAA;EA+BP;EAAA,QA7BrB,SAAA;EAAA,QACA,OAAA;cAEI,MAAA,EAAQ,kBAAA;EAiES;;;;;;;EAAA,QArDrB,WAAA;EAYF,MAAA,CAAO,OAAA;IACZ,GAAA;IACA,IAAA,EAAM,MAAA,GAAS,UAAA,GAAa,cAAA,CAAe,UAAA;IAC3C,WAAA;EAAA,IACG,OAAA,CAAQ,YAAA;EAqCN,QAAA,CAAS,GAAA,WAAc,OAAA,CAAQ,cAAA;EAkC/B,MAAA,CAAO,GAAA,WAAc,OAAA;EAYrB,MAAA,CAAO,GAAA,WAAc,OAAA;EAUrB,IAAA,CAAK,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,UAAA;EAsDzC,kBAAA,CAAmB,QAAA,EAAU,mBAAA,GAAsB,OAAA,CAAQ,eAAA;EASjE,YAAA,CAAa,GAAA;AAAA;;;;;iBAgBE,aAAA,CAAc,MAAA,EAAQ,MAAA,oBAA0B,OAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"local.mjs","names":[],"sources":["../../src/storage/local.ts"],"sourcesContent":["/**\n * Local Filesystem Storage Implementation\n *\n * For development and testing. Stores files in a local directory.\n */\n\nimport { createReadStream, existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { Readable } from \"node:stream\";\n\nimport mime from \"mime/lite\";\n\n/** Type guard for Node.js ErrnoException */\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nimport type {\n\tStorage,\n\tLocalStorageConfig,\n\tUploadResult,\n\tDownloadResult,\n\tListResult,\n\tListOptions,\n\tSignedUploadUrl,\n\tSignedUploadOptions,\n} from \"./types.js\";\nimport { EmDashStorageError } from \"./types.js\";\n\n/** Pattern to remove leading slashes */\nconst LEADING_SLASH_PATTERN = /^\\//;\n\n/** Pattern to remove trailing slashes */\nconst TRAILING_SLASH_PATTERN = /\\/$/;\n\n/**\n * Local filesystem storage implementation\n */\nexport class LocalStorage implements Storage {\n\t/** Resolved absolute base directory for all stored files */\n\tprivate directory: string;\n\tprivate baseUrl: string;\n\n\tconstructor(config: LocalStorageConfig) {\n\t\tthis.directory = path.resolve(config.directory);\n\t\tthis.baseUrl = config.baseUrl.replace(TRAILING_SLASH_PATTERN, \"\");\n\t}\n\n\t/**\n\t * Resolve a storage key to an absolute file path, ensuring it stays\n\t * within the configured storage directory. Uses path.resolve() for\n\t * canonical resolution rather than regex stripping.\n\t *\n\t * @throws EmDashStorageError if the resolved path escapes the base directory\n\t */\n\tprivate getFilePath(key: string): string {\n\t\tconst normalizedKey = key.replace(LEADING_SLASH_PATTERN, \"\");\n\t\tconst resolved = path.resolve(this.directory, normalizedKey);\n\n\t\t// Verify the resolved path is within the base directory\n\t\tif (!resolved.startsWith(this.directory + path.sep) && resolved !== this.directory) {\n\t\t\tthrow new EmDashStorageError(\"Invalid file path\", \"INVALID_PATH\");\n\t\t}\n\n\t\treturn resolved;\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\tconst filePath = this.getFilePath(options.key);\n\t\t\tconst dir = path.dirname(filePath);\n\n\t\t\t// Ensure directory exists\n\t\t\tawait fs.mkdir(dir, { recursive: true });\n\n\t\t\t// Convert body to buffer\n\t\t\tlet buffer: Buffer;\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\tbuffer = Buffer.concat(chunks);\n\t\t\t} else if (options.body instanceof Uint8Array) {\n\t\t\t\tbuffer = Buffer.from(options.body);\n\t\t\t} else {\n\t\t\t\tbuffer = options.body;\n\t\t\t}\n\n\t\t\tawait fs.writeFile(filePath, buffer);\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: buffer.length,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new EmDashStorageError(\n\t\t\t\t`Failed to upload file: ${options.key}`,\n\t\t\t\t\"UPLOAD_FAILED\",\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync download(key: string): Promise<DownloadResult> {\n\t\ttry {\n\t\t\tconst filePath = this.getFilePath(key);\n\n\t\t\tif (!existsSync(filePath)) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\");\n\t\t\t}\n\n\t\t\tconst stat = await fs.stat(filePath);\n\t\t\tconst nodeStream = createReadStream(filePath);\n\n\t\t\t// Convert Node.js stream to web ReadableStream\n\t\t\t// Readable.toWeb returns ReadableStream (which is ReadableStream<unknown>),\n\t\t\t// but Node ReadStreams produce Buffer/Uint8Array chunks\n\t\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Readable.toWeb returns ReadableStream<unknown>; Node ReadStreams produce Uint8Array chunks\n\t\t\tconst webStream: ReadableStream<Uint8Array> = Readable.toWeb(\n\t\t\t\tnodeStream,\n\t\t\t) as ReadableStream<Uint8Array>;\n\n\t\t\t// Infer content type from extension\n\t\t\tconst ext = path.extname(key).toLowerCase();\n\t\t\tconst contentType = getContentType(ext);\n\n\t\t\treturn {\n\t\t\t\tbody: webStream,\n\t\t\t\tcontentType,\n\t\t\t\tsize: stat.size,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof EmDashStorageError) throw error;\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\tconst filePath = this.getFilePath(key);\n\t\t\tawait fs.unlink(filePath);\n\t\t} catch (error) {\n\t\t\t// Ignore \"file not found\" errors (idempotent delete)\n\t\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\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\tconst filePath = this.getFilePath(key);\n\t\t\tawait fs.access(filePath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync list(options: ListOptions = {}): Promise<ListResult> {\n\t\ttry {\n\t\t\tconst prefix = options.prefix || \"\";\n\t\t\tconst searchDir = path.resolve(this.directory, path.dirname(prefix));\n\n\t\t\t// Validate the search directory stays within the base directory\n\t\t\tif (!searchDir.startsWith(this.directory + path.sep) && searchDir !== this.directory) {\n\t\t\t\tthrow new EmDashStorageError(\"Invalid list prefix\", \"INVALID_PATH\");\n\t\t\t}\n\n\t\t\tconst prefixBase = path.basename(prefix);\n\n\t\t\t// Ensure directory exists\n\t\t\ttry {\n\t\t\t\tawait fs.access(searchDir);\n\t\t\t} catch {\n\t\t\t\treturn { files: [] };\n\t\t\t}\n\n\t\t\tconst entries = await fs.readdir(searchDir, { withFileTypes: true });\n\t\t\tconst files: ListResult[\"files\"] = [];\n\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isFile() && entry.name.startsWith(prefixBase)) {\n\t\t\t\t\tconst key = path.join(path.dirname(prefix), entry.name);\n\t\t\t\t\tconst filePath = path.join(searchDir, entry.name);\n\t\t\t\t\tconst stat = await fs.stat(filePath);\n\n\t\t\t\t\tfiles.push({\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tsize: stat.size,\n\t\t\t\t\t\tlastModified: stat.mtime,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sort by last modified (newest first)\n\t\t\tfiles.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());\n\n\t\t\t// Apply limit and cursor (simple implementation)\n\t\t\tconst startIndex = options.cursor ? parseInt(options.cursor, 10) : 0;\n\t\t\tconst limit = options.limit || 1000;\n\t\t\tconst paginatedFiles = files.slice(startIndex, startIndex + limit);\n\t\t\tconst hasMore = startIndex + limit < files.length;\n\n\t\t\treturn {\n\t\t\t\tfiles: paginatedFiles,\n\t\t\t\tnextCursor: hasMore ? String(startIndex + limit) : undefined,\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\t// Local storage doesn't support signed URLs\n\t\tthrow new EmDashStorageError(\n\t\t\t\"Local storage does not support signed upload URLs. \" +\n\t\t\t\t\"Upload files directly through the API.\",\n\t\t\t\"NOT_SUPPORTED\",\n\t\t);\n\t}\n\n\tgetPublicUrl(key: string): string {\n\t\treturn `${this.baseUrl}/${key}`;\n\t}\n}\n\n/**\n * Get content type from file extension\n */\nfunction getContentType(ext: string): string {\n\treturn mime.getType(ext) ?? \"application/octet-stream\";\n}\n\n/**\n * Create local storage adapter\n * This is the factory function called at runtime\n */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\tconst directory = typeof config.directory === \"string\" ? config.directory : \"\";\n\tconst baseUrl = typeof config.baseUrl === \"string\" ? config.baseUrl : \"\";\n\treturn new LocalStorage({ directory, baseUrl });\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,YAAY,OAAgD;AACpE,QAAO,iBAAiB,SAAS,UAAU;;;AAg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EAAE;AAErC,QAAK,MAAM,SAAS,QACnB,KAAI,MAAM,QAAQ,IAAI,MAAM,KAAK,WAAW,WAAW,EAAE;IACxD,MAAM,MAAM,KAAK,KAAK,KAAK,QAAQ,OAAO,EAAE,MAAM,KAAK;IACvD,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,KAAK;IACjD,MAAM,OAAO,MAAM,GAAG,KAAK,SAAS;AAEpC,UAAM,KAAK;KACV;KACA,MAAM,KAAK;KACX,cAAc,KAAK;KACnB,CAAC;;AAKJ,SAAM,MAAM,GAAG,MAAM,EAAE,aAAa,SAAS,GAAG,EAAE,aAAa,SAAS,CAAC;GAGzE,MAAM,aAAa,QAAQ,SAAS,SAAS,QAAQ,QAAQ,GAAG,GAAG;GACnE,MAAM,QAAQ,QAAQ,SAAS;AAI/B,UAAO;IACN,OAJsB,MAAM,MAAM,YAAY,aAAa,MAAM;IAKjE,YAJe,aAAa,QAAQ,MAAM,SAIpB,OAAO,aAAa,MAAM,GAAG;IACnD;WACO,OAAO;AACf,SAAM,IAAI,mBAAmB,wBAAwB,eAAe,MAAM;;;CAI5E,MAAM,mBAAmB,UAAyD;AAEjF,QAAM,IAAI,mBACT,6FAEA,gBACA;;CAGF,aAAa,KAAqB;AACjC,SAAO,GAAG,KAAK,QAAQ,GAAG;;;;;;AAO5B,SAAS,eAAe,KAAqB;AAC5C,QAAO,KAAK,QAAQ,IAAI,IAAI;;;;;;AAO7B,SAAgB,cAAc,QAA0C;AAGvE,QAAO,IAAI,aAAa;EAAE,WAFR,OAAO,OAAO,cAAc,WAAW,OAAO,YAAY;EAEvC,SADrB,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;EACxB,CAAC"}
1
+ {"version":3,"file":"local.mjs","names":[],"sources":["../../src/storage/local.ts"],"sourcesContent":["/**\n * Local Filesystem Storage Implementation\n *\n * For development and testing. Stores files in a local directory.\n */\n\nimport { createReadStream, existsSync } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { Readable } from \"node:stream\";\n\nimport mime from \"mime/lite\";\n\n/** Type guard for Node.js ErrnoException */\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n\treturn error instanceof Error && \"code\" in error;\n}\n\nimport type {\n\tStorage,\n\tLocalStorageConfig,\n\tUploadResult,\n\tDownloadResult,\n\tListResult,\n\tListOptions,\n\tSignedUploadUrl,\n\tSignedUploadOptions,\n} from \"./types.js\";\nimport { EmDashStorageError } from \"./types.js\";\n\n/** Pattern to remove leading slashes */\nconst LEADING_SLASH_PATTERN = /^\\//;\n\n/** Pattern to remove trailing slashes */\nconst TRAILING_SLASH_PATTERN = /\\/$/;\n\n/**\n * Local filesystem storage implementation\n */\nexport class LocalStorage implements Storage {\n\t/** Resolved absolute base directory for all stored files */\n\tprivate directory: string;\n\tprivate baseUrl: string;\n\n\tconstructor(config: LocalStorageConfig) {\n\t\tthis.directory = path.resolve(config.directory);\n\t\tthis.baseUrl = config.baseUrl.replace(TRAILING_SLASH_PATTERN, \"\");\n\t}\n\n\t/**\n\t * Resolve a storage key to an absolute file path, ensuring it stays\n\t * within the configured storage directory. Uses path.resolve() for\n\t * canonical resolution rather than regex stripping.\n\t *\n\t * @throws EmDashStorageError if the resolved path escapes the base directory\n\t */\n\tprivate getFilePath(key: string): string {\n\t\tconst normalizedKey = key.replace(LEADING_SLASH_PATTERN, \"\");\n\t\tconst resolved = path.resolve(this.directory, normalizedKey);\n\n\t\t// Verify the resolved path is within the base directory\n\t\tif (!resolved.startsWith(this.directory + path.sep) && resolved !== this.directory) {\n\t\t\tthrow new EmDashStorageError(\"Invalid file path\", \"INVALID_PATH\");\n\t\t}\n\n\t\treturn resolved;\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\tconst filePath = this.getFilePath(options.key);\n\t\t\tconst dir = path.dirname(filePath);\n\n\t\t\t// Ensure directory exists\n\t\t\tawait fs.mkdir(dir, { recursive: true });\n\n\t\t\t// Convert body to buffer\n\t\t\tlet buffer: Buffer;\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\tbuffer = Buffer.concat(chunks);\n\t\t\t} else if (options.body instanceof Uint8Array) {\n\t\t\t\tbuffer = Buffer.from(options.body);\n\t\t\t} else {\n\t\t\t\tbuffer = options.body;\n\t\t\t}\n\n\t\t\tawait fs.writeFile(filePath, buffer);\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: buffer.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 filePath = this.getFilePath(key);\n\n\t\t\tif (!existsSync(filePath)) {\n\t\t\t\tthrow new EmDashStorageError(`File not found: ${key}`, \"NOT_FOUND\");\n\t\t\t}\n\n\t\t\tconst stat = await fs.stat(filePath);\n\t\t\tconst nodeStream = createReadStream(filePath);\n\n\t\t\t// Convert Node.js stream to web ReadableStream\n\t\t\t// Readable.toWeb returns ReadableStream (which is ReadableStream<unknown>),\n\t\t\t// but Node ReadStreams produce Buffer/Uint8Array chunks\n\t\t\t// eslint-disable-next-line typescript-eslint(no-unsafe-type-assertion) -- Readable.toWeb returns ReadableStream<unknown>; Node ReadStreams produce Uint8Array chunks\n\t\t\tconst webStream: ReadableStream<Uint8Array> = Readable.toWeb(\n\t\t\t\tnodeStream,\n\t\t\t) as ReadableStream<Uint8Array>;\n\n\t\t\t// Infer content type from extension\n\t\t\tconst ext = path.extname(key).toLowerCase();\n\t\t\tconst contentType = getContentType(ext);\n\n\t\t\treturn {\n\t\t\t\tbody: webStream,\n\t\t\t\tcontentType,\n\t\t\t\tsize: stat.size,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof EmDashStorageError) throw error;\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\tconst filePath = this.getFilePath(key);\n\t\t\tawait fs.unlink(filePath);\n\t\t} catch (error) {\n\t\t\t// Ignore \"file not found\" errors (idempotent delete)\n\t\t\tif (!isNodeError(error) || error.code !== \"ENOENT\") {\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\tconst filePath = this.getFilePath(key);\n\t\t\tawait fs.access(filePath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync list(options: ListOptions = {}): Promise<ListResult> {\n\t\ttry {\n\t\t\tconst prefix = options.prefix || \"\";\n\t\t\tconst searchDir = path.resolve(this.directory, path.dirname(prefix));\n\n\t\t\t// Validate the search directory stays within the base directory\n\t\t\tif (!searchDir.startsWith(this.directory + path.sep) && searchDir !== this.directory) {\n\t\t\t\tthrow new EmDashStorageError(\"Invalid list prefix\", \"INVALID_PATH\");\n\t\t\t}\n\n\t\t\tconst prefixBase = path.basename(prefix);\n\n\t\t\t// Ensure directory exists\n\t\t\ttry {\n\t\t\t\tawait fs.access(searchDir);\n\t\t\t} catch {\n\t\t\t\treturn { files: [] };\n\t\t\t}\n\n\t\t\tconst entries = await fs.readdir(searchDir, { withFileTypes: true });\n\t\t\tconst files: ListResult[\"files\"] = [];\n\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.isFile() && entry.name.startsWith(prefixBase)) {\n\t\t\t\t\tconst key = path.join(path.dirname(prefix), entry.name);\n\t\t\t\t\tconst filePath = path.join(searchDir, entry.name);\n\t\t\t\t\tconst stat = await fs.stat(filePath);\n\n\t\t\t\t\tfiles.push({\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tsize: stat.size,\n\t\t\t\t\t\tlastModified: stat.mtime,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Sort by last modified (newest first)\n\t\t\tfiles.sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());\n\n\t\t\t// Apply limit and cursor (simple implementation)\n\t\t\tconst startIndex = options.cursor ? parseInt(options.cursor, 10) : 0;\n\t\t\tconst limit = options.limit || 1000;\n\t\t\tconst paginatedFiles = files.slice(startIndex, startIndex + limit);\n\t\t\tconst hasMore = startIndex + limit < files.length;\n\n\t\t\treturn {\n\t\t\t\tfiles: paginatedFiles,\n\t\t\t\tnextCursor: hasMore ? String(startIndex + limit) : undefined,\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\t// Local storage doesn't support signed URLs\n\t\tthrow new EmDashStorageError(\n\t\t\t\"Local storage does not support signed upload URLs. \" +\n\t\t\t\t\"Upload files directly through the API.\",\n\t\t\t\"NOT_SUPPORTED\",\n\t\t);\n\t}\n\n\tgetPublicUrl(key: string): string {\n\t\treturn `${this.baseUrl}/${key}`;\n\t}\n}\n\n/**\n * Get content type from file extension\n */\nfunction getContentType(ext: string): string {\n\treturn mime.getType(ext) ?? \"application/octet-stream\";\n}\n\n/**\n * Create local storage adapter\n * This is the factory function called at runtime\n */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\tconst directory = typeof config.directory === \"string\" ? config.directory : \"\";\n\tconst baseUrl = typeof config.baseUrl === \"string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A,CAAQ,eAAA;EAiChE,YAAA,CAAa,GAAA;AAAA;;;;;iBAaE,aAAA,CAAc,MAAA,EAAQ,MAAA,oBAA0B,OAAA"}
@@ -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\";\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 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\tcredentials: {\n\t\t\t\taccessKeyId: config.accessKeyId,\n\t\t\t\tsecretAccessKey: config.secretAccessKey,\n\t\t\t},\n\t\t\t// Required for R2 and some S3-compatible services\n\t\t\tforcePathStyle: true,\n\t\t});\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(\n\t\t\t\t`Failed to upload file: ${options.key}`,\n\t\t\t\t\"UPLOAD_FAILED\",\n\t\t\t\terror,\n\t\t\t);\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(\n\t\t\t\t`Failed to check file existence: ${key}`,\n\t\t\t\t\"HEAD_FAILED\",\n\t\t\t\terror,\n\t\t\t);\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 */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\tconst { endpoint, bucket, accessKeyId, secretAccessKey, region, publicUrl } = config;\n\tif (\n\t\ttypeof endpoint !== \"string\" ||\n\t\ttypeof bucket !== \"string\" ||\n\t\ttypeof accessKeyId !== \"string\" ||\n\t\ttypeof secretAccessKey !== \"string\"\n\t) {\n\t\tthrow new Error(\n\t\t\t\"S3Storage requires 'endpoint', 'bucket', 'accessKeyId', and 'secretAccessKey' string config values\",\n\t\t);\n\t}\n\treturn new S3Storage({\n\t\tendpoint,\n\t\tbucket,\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tregion: typeof region === \"string\" ? region : undefined,\n\t\tpublicUrl: typeof publicUrl === \"string\" ? publicUrl : undefined,\n\t});\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,yBAAyB;;AAG/B,SAAS,aAAa,OAAmD;AACxE,QAAO,iBAAiB,SAAS,OAAO,MAAM,SAAS;;;;;AAMxD,IAAa,YAAb,MAA0C;CACzC,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAyB;AACpC,OAAK,SAAS,OAAO;AACrB,OAAK,YAAY,OAAO;AACxB,OAAK,WAAW,OAAO;AAEvB,OAAK,SAAS,IAAI,SAAS;GAC1B,UAAU,OAAO;GACjB,QAAQ,OAAO,UAAU;GACzB,aAAa;IACZ,aAAa,OAAO;IACpB,iBAAiB,OAAO;IACxB;GAED,gBAAgB;GAChB,CAAC;;CAGH,MAAM,OAAO,SAIa;AACzB,MAAI;GAEH,IAAI;AACJ,OAAI,QAAQ,gBAAgB,gBAAgB;IAC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AI,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;;;;;;;AAQhF,SAAgB,cAAc,QAA0C;CACvE,MAAM,EAAE,UAAU,QAAQ,aAAa,iBAAiB,QAAQ,cAAc;AAC9E,KACC,OAAO,aAAa,YACpB,OAAO,WAAW,YAClB,OAAO,gBAAgB,YACvB,OAAO,oBAAoB,SAE3B,OAAM,IAAI,MACT,qGACA;AAEF,QAAO,IAAI,UAAU;EACpB;EACA;EACA;EACA;EACA,QAAQ,OAAO,WAAW,WAAW,SAAS;EAC9C,WAAW,OAAO,cAAc,WAAW,YAAY;EACvD,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\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\";\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 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\tcredentials: {\n\t\t\t\taccessKeyId: config.accessKeyId,\n\t\t\t\tsecretAccessKey: config.secretAccessKey,\n\t\t\t},\n\t\t\t// Required for R2 and some S3-compatible services\n\t\t\tforcePathStyle: true,\n\t\t});\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 */\nexport function createStorage(config: Record<string, unknown>): Storage {\n\tconst { endpoint, bucket, accessKeyId, secretAccessKey, region, publicUrl } = config;\n\tif (\n\t\ttypeof endpoint !== \"string\" ||\n\t\ttypeof bucket !== \"string\" ||\n\t\ttypeof accessKeyId !== \"string\" ||\n\t\ttypeof secretAccessKey !== \"string\"\n\t) {\n\t\tthrow new Error(\n\t\t\t\"S3Storage requires 'endpoint', 'bucket', 'accessKeyId', and 'secretAccessKey' string config values\",\n\t\t);\n\t}\n\treturn new S3Storage({\n\t\tendpoint,\n\t\tbucket,\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tregion: typeof region === \"string\" ? region : undefined,\n\t\tpublicUrl: typeof publicUrl === \"string\" ? publicUrl : undefined,\n\t});\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,yBAAyB;;AAG/B,SAAS,aAAa,OAAmD;AACxE,QAAO,iBAAiB,SAAS,OAAO,MAAM,SAAS;;;;;AAMxD,IAAa,YAAb,MAA0C;CACzC,AAAQ;CACR,AAAQ;CACR,AA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