@sonicjs-cms/core 3.0.0-beta.3 → 3.0.0-beta.5

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 (47) hide show
  1. package/dist/{chunk-SO2T3OXR.js → chunk-7JRMNEDQ.js} +9 -9
  2. package/dist/{chunk-SO2T3OXR.js.map → chunk-7JRMNEDQ.js.map} +1 -1
  3. package/dist/{chunk-2JTWQZHG.cjs → chunk-B5ORC7QR.cjs} +2 -2
  4. package/dist/{chunk-2JTWQZHG.cjs.map → chunk-B5ORC7QR.cjs.map} +1 -1
  5. package/dist/{chunk-CHCBHIBM.cjs → chunk-BGUMJTUE.cjs} +10 -10
  6. package/dist/{chunk-CHCBHIBM.cjs.map → chunk-BGUMJTUE.cjs.map} +1 -1
  7. package/dist/{chunk-673S7EBY.cjs → chunk-BSM2NQYR.cjs} +2 -2
  8. package/dist/{chunk-673S7EBY.cjs.map → chunk-BSM2NQYR.cjs.map} +1 -1
  9. package/dist/{chunk-RJV6UXLZ.js → chunk-EEYFB6SU.js} +2 -2
  10. package/dist/{chunk-RJV6UXLZ.js.map → chunk-EEYFB6SU.js.map} +1 -1
  11. package/dist/{chunk-J5DCX3F6.cjs → chunk-EFXOZ4CD.cjs} +11 -11
  12. package/dist/{chunk-J5DCX3F6.cjs.map → chunk-EFXOZ4CD.cjs.map} +1 -1
  13. package/dist/{chunk-VQHAJUZZ.cjs → chunk-GHJJVBFM.cjs} +4 -4
  14. package/dist/{chunk-VQHAJUZZ.cjs.map → chunk-GHJJVBFM.cjs.map} +1 -1
  15. package/dist/{chunk-7LHUVREV.cjs → chunk-GJBLR3PW.cjs} +3 -3
  16. package/dist/{chunk-7LHUVREV.cjs.map → chunk-GJBLR3PW.cjs.map} +1 -1
  17. package/dist/{chunk-XFQHK64T.js → chunk-I547QD6V.js} +3 -3
  18. package/dist/{chunk-XFQHK64T.js.map → chunk-I547QD6V.js.map} +1 -1
  19. package/dist/{chunk-MHP7HYTT.js → chunk-IKEUELHZ.js} +2 -2
  20. package/dist/{chunk-MHP7HYTT.js.map → chunk-IKEUELHZ.js.map} +1 -1
  21. package/dist/{chunk-SL6XS6YT.js → chunk-JI4E5YFS.js} +4 -4
  22. package/dist/{chunk-SL6XS6YT.js.map → chunk-JI4E5YFS.js.map} +1 -1
  23. package/dist/{chunk-VZ3NHR5Z.js → chunk-TWATCPVJ.js} +4 -4
  24. package/dist/{chunk-VZ3NHR5Z.js.map → chunk-TWATCPVJ.js.map} +1 -1
  25. package/dist/{chunk-LO6MEPRW.cjs → chunk-VPDI7YAM.cjs} +200 -200
  26. package/dist/{chunk-LO6MEPRW.cjs.map → chunk-VPDI7YAM.cjs.map} +1 -1
  27. package/dist/{chunk-MP3Q2W76.js → chunk-ZWUXEIJY.js} +3 -3
  28. package/dist/{chunk-MP3Q2W76.js.map → chunk-ZWUXEIJY.js.map} +1 -1
  29. package/dist/index.cjs +252 -252
  30. package/dist/index.js +13 -13
  31. package/dist/middleware.cjs +32 -32
  32. package/dist/middleware.js +3 -3
  33. package/dist/migrations-JFOF3J4Z.js +4 -0
  34. package/dist/{migrations-DK2YFPLR.js.map → migrations-JFOF3J4Z.js.map} +1 -1
  35. package/dist/migrations-PIQH3IHN.cjs +13 -0
  36. package/dist/{migrations-YHNHTJOO.cjs.map → migrations-PIQH3IHN.cjs.map} +1 -1
  37. package/dist/plugins.cjs +40 -40
  38. package/dist/plugins.js +3 -3
  39. package/dist/routes.cjs +26 -26
  40. package/dist/routes.js +6 -6
  41. package/dist/services.cjs +14 -14
  42. package/dist/services.js +2 -2
  43. package/dist/utils.cjs +3 -3
  44. package/dist/utils.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/migrations-DK2YFPLR.js +0 -4
  47. package/dist/migrations-YHNHTJOO.cjs +0 -13
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/db/migrations-bundle.ts","../src/services/document-scalar-schema.ts","../src/services/migrations.ts"],"names":[],"mappings":";AAiBO,IAAM,iB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AAA;AAAA,MAAa;AAAA,KACxB;AAEA,IAAA,KAAA,MAAW,SAAS,cAAA,EAAgB;AAClC,MAAA,IAAI;AACF,QAAA,MAAM,KAAK,EAAA,CAAG,OAAA,CAAQ,wBAAwB,KAAK,CAAA,QAAA,CAAU,EAAE,KAAA,EAAM;AAAA,MACvE,SAAS,KAAA,EAAO;AACd,QAAA,MAAA,CAAO,IAAA,CAAK,CAAA,eAAA,EAAkB,KAAK,CAAA,CAAE,CAAA;AAAA,MACvC;AAAA,IACF;AAEA,IAAA,OAAO;AAAA,MACL,KAAA,EAAO,OAAO,MAAA,KAAW,CAAA;AAAA,MACzB;AAAA,KACF;AAAA,EACF;AACF","file":"chunk-MHP7HYTT.js","sourcesContent":["/**\n * AUTO-GENERATED FILE - DO NOT EDIT\n * Generated by: scripts/generate-migrations.ts\n * Generated at: 2026-06-18T22:53:44.759Z\n *\n * This file contains all migration SQL bundled for use in Cloudflare Workers\n * where filesystem access is not available at runtime.\n */\n\nexport interface BundledMigration {\n id: string\n name: string\n filename: string\n description: string\n sql: string\n}\n\nexport const bundledMigrations: BundledMigration[] = [\n {\n id: '0001',\n name: 'Core',\n filename: '0001_core.sql',\n description: 'Migration 0001: Core',\n sql: \"-- Migration 0001: Auth tables\\n-- auth_user, auth_session, auth_account, auth_verification + BA plugin tables + RBAC + auth support.\\n-- Only auth_* prefixed tables live here. All content lives in document_* tables (0002_documents.sql).\\n\\n-- ── auth_user ────────────────────────────────────────────────────────────────\\n-- BA user model + SonicJS domain columns as BA additionalFields.\\nCREATE TABLE IF NOT EXISTS auth_user (\\n id TEXT PRIMARY KEY,\\n name TEXT,\\n email TEXT NOT NULL UNIQUE,\\n email_verified INTEGER NOT NULL DEFAULT 0,\\n image TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL,\\n -- SonicJS additionalFields\\n first_name TEXT NOT NULL,\\n last_name TEXT NOT NULL,\\n role TEXT NOT NULL DEFAULT 'viewer',\\n -- Platform super-admin: bypasses the multi-tenant membership gate, uses global roles in every\\n -- tenant. Opt-in (default 0); intentionally NOT derived from the 'admin' role.\\n is_super_admin INTEGER NOT NULL DEFAULT 0,\\n avatar TEXT,\\n password_hash TEXT,\\n is_active INTEGER NOT NULL DEFAULT 1,\\n last_login_at INTEGER,\\n phone TEXT,\\n bio TEXT,\\n timezone TEXT DEFAULT 'UTC',\\n language TEXT DEFAULT 'en',\\n email_notifications INTEGER DEFAULT 1,\\n theme TEXT DEFAULT 'dark',\\n invitation_token TEXT,\\n invited_by TEXT,\\n invited_at INTEGER,\\n accepted_invitation_at INTEGER,\\n failed_login_count INTEGER NOT NULL DEFAULT 0,\\n locked_until INTEGER\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_auth_user_email ON auth_user(email);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_role ON auth_user(role);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_invitation_token ON auth_user(invitation_token);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_locked_until ON auth_user(locked_until) WHERE locked_until IS NOT NULL;\\n\\n-- ── auth_session ─────────────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_session (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n token TEXT NOT NULL UNIQUE,\\n expires_at INTEGER NOT NULL,\\n ip_address TEXT,\\n user_agent TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_user_id ON auth_session(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_token ON auth_session(token);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_expires_at ON auth_session(expires_at);\\n\\n-- ── auth_account ─────────────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_account (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n account_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n access_token TEXT,\\n refresh_token TEXT,\\n access_token_expires_at INTEGER,\\n refresh_token_expires_at INTEGER,\\n scope TEXT,\\n id_token TEXT,\\n password TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_account_user_id ON auth_account(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_account_provider ON auth_account(provider_id, account_id);\\n\\n-- ── auth_verification ────────────────────────────────────────────────────────\\n-- Covers email verification, password reset, magic-link tokens, OTP codes.\\nCREATE TABLE IF NOT EXISTS auth_verification (\\n id TEXT PRIMARY KEY,\\n identifier TEXT NOT NULL,\\n value TEXT NOT NULL,\\n expires_at INTEGER NOT NULL,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_verification_identifier ON auth_verification(identifier);\\n\\n-- ── BA plugin tables ──────────────────────────────────────────────────────────\\n\\nCREATE TABLE IF NOT EXISTS auth_two_factor (\\n id TEXT PRIMARY KEY,\\n secret TEXT NOT NULL,\\n backup_codes TEXT NOT NULL,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n verified INTEGER NOT NULL DEFAULT 1,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_two_factor_user_id ON auth_two_factor(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n slug TEXT NOT NULL UNIQUE,\\n logo TEXT,\\n metadata TEXT,\\n -- SonicJS tenant-resolution fields (BA organization additionalFields):\\n status TEXT NOT NULL DEFAULT 'active',\\n domain TEXT,\\n notes TEXT NOT NULL DEFAULT '',\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_domain ON auth_tenant(domain);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_member (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n role TEXT NOT NULL DEFAULT 'member',\\n email TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL,\\n UNIQUE(tenant_id, user_id)\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_member_tenant ON auth_tenant_member(tenant_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_member_user ON auth_tenant_member(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_invitation (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n email TEXT NOT NULL,\\n role TEXT NOT NULL DEFAULT 'member',\\n status TEXT NOT NULL DEFAULT 'pending',\\n expires_at INTEGER NOT NULL,\\n inviter_id TEXT REFERENCES auth_user(id) ON DELETE SET NULL,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_invitation_tenant ON auth_tenant_invitation(tenant_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_invitation_email ON auth_tenant_invitation(email);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_team (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\n\\n-- ── RBAC ─────────────────────────────────────────────────────────────────────\\n-- RBAC roles, verbs, and user-role assignments are document-backed (is_auth doc\\n-- types rbac_role / rbac_verb / rbac_user_roles — see services/rbac.ts). The\\n-- system roles/verbs/grants are seeded at bootstrap by RbacService.ensureSystemRbacSeed().\\n-- No auth_rbac_* tables.\\n\\n-- ── Auth support tables ───────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_password_history (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n password_hash TEXT NOT NULL,\\n created_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_password_history_user_id ON auth_password_history(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_api_tokens (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n token TEXT NOT NULL UNIQUE,\\n user_id TEXT NOT NULL REFERENCES auth_user(id),\\n permissions TEXT NOT NULL,\\n expires_at INTEGER,\\n last_used_at INTEGER,\\n created_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_api_tokens_user ON auth_api_tokens(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_api_tokens_token ON auth_api_tokens(token);\\n\\n-- User profiles moved to the document model: a `user_profile` document (is_auth type),\\n-- one per user, addressed by slug = userId. See services/document-types-seed.ts and\\n-- plugins/core-plugins/user-profiles/user-profile-document.ts. No auth_user_profiles table.\\n\"\n },\n {\n id: '0002',\n name: 'Documents',\n filename: '0002_documents.sql',\n description: 'Migration 0002: Documents',\n sql: \"-- Migration 0002: Document Schema (v3 greenfield)\\n-- Contains only the new document data model tables, generated columns, and indexes.\\n\\n-- Document type registry\\nCREATE TABLE IF NOT EXISTS document_types (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL UNIQUE,\\n display_name TEXT NOT NULL,\\n description TEXT,\\n schema TEXT NOT NULL DEFAULT '{}',\\n queryable_fields TEXT NOT NULL DEFAULT '[]',\\n settings TEXT NOT NULL DEFAULT '{}',\\n plugin_id TEXT,\\n source TEXT NOT NULL DEFAULT 'code' CHECK (source IN ('code', 'plugin', 'system')),\\n schema_version INTEGER NOT NULL DEFAULT 1,\\n is_system INTEGER NOT NULL DEFAULT 0,\\n is_active INTEGER NOT NULL DEFAULT 1,\\n is_auth INTEGER NOT NULL DEFAULT 0,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n updated_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_document_types_plugin ON document_types(plugin_id);\\nCREATE INDEX IF NOT EXISTS idx_document_types_active ON document_types(is_active);\\n\\n-- Documents: canonical document rows and historical versions.\\nCREATE TABLE IF NOT EXISTS documents (\\n id TEXT PRIMARY KEY,\\n root_id TEXT NOT NULL,\\n type_id TEXT NOT NULL REFERENCES document_types(id),\\n type_version INTEGER NOT NULL DEFAULT 1,\\n\\n version_of_id TEXT REFERENCES documents(id),\\n version_number INTEGER NOT NULL DEFAULT 1,\\n\\n is_current_draft INTEGER NOT NULL DEFAULT 1,\\n is_published INTEGER NOT NULL DEFAULT 0,\\n status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),\\n\\n parent_root_id TEXT NOT NULL DEFAULT '',\\n slug TEXT,\\n path TEXT,\\n title TEXT,\\n zone TEXT,\\n sort_order INTEGER NOT NULL DEFAULT 0,\\n visible INTEGER NOT NULL DEFAULT 1,\\n\\n published_at INTEGER,\\n scheduled_at INTEGER,\\n expires_at INTEGER,\\n deleted_at INTEGER,\\n\\n tenant_id TEXT NOT NULL DEFAULT 'default',\\n locale TEXT NOT NULL DEFAULT 'default',\\n translation_group_id TEXT NOT NULL DEFAULT '',\\n\\n data TEXT NOT NULL DEFAULT '{}',\\n metadata TEXT NOT NULL DEFAULT '{}',\\n\\n owner_id TEXT,\\n created_by TEXT,\\n updated_by TEXT,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n updated_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\n-- Queryable scalar fields (VIRTUAL generated columns) and their q_* filter indexes\\n-- are AUTO-GENERATED at runtime from each document type's queryableFields config —\\n-- see DocumentTypeRegistry.register() -> ensureScalarSchema() (document-scalar-schema.ts).\\n-- Do not hand-add q_* columns/indexes here; declare the field in the type instead.\\n\\n-- Revision chain\\nCREATE INDEX IF NOT EXISTS idx_documents_root ON documents(root_id, version_number DESC);\\n\\n-- List / lifecycle\\nCREATE INDEX IF NOT EXISTS idx_documents_published ON documents(tenant_id, type_id, locale, is_published)\\n WHERE is_published = 1 AND deleted_at IS NULL;\\nCREATE INDEX IF NOT EXISTS idx_documents_drafts ON documents(tenant_id, type_id, status, is_current_draft)\\n WHERE is_current_draft = 1;\\nCREATE INDEX IF NOT EXISTS idx_documents_parent ON documents(tenant_id, parent_root_id, sort_order, is_published);\\nCREATE INDEX IF NOT EXISTS idx_documents_path ON documents(tenant_id, path);\\nCREATE INDEX IF NOT EXISTS idx_documents_translation ON documents(translation_group_id, locale);\\nCREATE INDEX IF NOT EXISTS idx_documents_deleted ON documents(deleted_at);\\nCREATE INDEX IF NOT EXISTS idx_documents_scheduled ON documents(scheduled_at) WHERE scheduled_at IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS idx_documents_expires ON documents(expires_at) WHERE expires_at IS NOT NULL;\\n\\n-- Stable keyset/cursor pagination for published lists\\nCREATE INDEX IF NOT EXISTS idx_documents_published_cursor\\n ON documents(tenant_id, type_id, updated_at DESC, id DESC)\\n WHERE is_published = 1 AND deleted_at IS NULL;\\n\\n-- (q_* generated-column filter indexes are auto-created at runtime — see note above.)\\n\\n-- Partial unique indexes: the hard concurrency guarantees for draft/publish invariants.\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_current_draft\\n ON documents(root_id) WHERE is_current_draft = 1;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_published\\n ON documents(root_id) WHERE is_published = 1;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_unique_version\\n ON documents(root_id, version_number);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_unique_slug\\n ON documents(tenant_id, locale, type_id, parent_root_id, slug)\\n WHERE is_current_draft = 1 AND deleted_at IS NULL AND slug IS NOT NULL;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_translation_per_locale\\n ON documents(tenant_id, translation_group_id, locale)\\n WHERE is_current_draft = 1 AND translation_group_id <> '';\\n\\n-- Document references: typed document-to-document edges.\\nCREATE TABLE IF NOT EXISTS document_references (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n from_root_id TEXT NOT NULL,\\n from_document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\\n field_name TEXT NOT NULL,\\n ordinal INTEGER NOT NULL DEFAULT 0,\\n to_root_id TEXT NOT NULL,\\n ref_strength TEXT NOT NULL DEFAULT 'weak' CHECK (ref_strength IN ('strong', 'weak')),\\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_docref_to ON document_references(tenant_id, to_root_id);\\nCREATE INDEX IF NOT EXISTS idx_docref_from ON document_references(from_document_id);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_docref_unique\\n ON document_references(from_document_id, field_name, ordinal);\\n\\n-- Document facets: indexed rows for multi-valued scalar fields (e.g. tags arrays).\\nCREATE TABLE IF NOT EXISTS document_facets (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\\n root_id TEXT NOT NULL,\\n type_id TEXT NOT NULL,\\n field_name TEXT NOT NULL,\\n ordinal INTEGER NOT NULL DEFAULT 0,\\n value_text TEXT,\\n value_number REAL,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_facets_lookup ON document_facets(tenant_id, type_id, field_name, value_text);\\nCREATE INDEX IF NOT EXISTS idx_facets_doc ON document_facets(document_id);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_facets_unique\\n ON document_facets(document_id, field_name, ordinal);\\n\\n-- Document permissions: per-document ACL overrides.\\nCREATE TABLE IF NOT EXISTS document_permissions (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n root_id TEXT NOT NULL,\\n principal_type TEXT NOT NULL CHECK (principal_type IN ('user', 'role', 'group', 'public', 'token')),\\n principal_id TEXT NOT NULL,\\n permission TEXT NOT NULL CHECK (permission IN ('read', 'create', 'update', 'delete', 'publish', 'manage')),\\n effect TEXT NOT NULL DEFAULT 'allow' CHECK (effect IN ('allow', 'deny')),\\n inherited INTEGER NOT NULL DEFAULT 0,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n created_by TEXT\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_document_permissions_root ON document_permissions(tenant_id, root_id);\\nCREATE INDEX IF NOT EXISTS idx_document_permissions_principal\\n ON document_permissions(tenant_id, principal_type, principal_id, permission);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_document_permissions_unique\\n ON document_permissions(root_id, principal_type, principal_id, permission);\\n\"\n }\n]\n\n// Map for quick lookup by ID\nexport const migrationsByIdMap = new Map<string, BundledMigration>(\n bundledMigrations.map(m => [m.id, m])\n)\n\n// Get migration SQL by ID\nexport function getMigrationSQLById(id: string): string | null {\n return migrationsByIdMap.get(id)?.sql ?? null\n}\n\n// Get all migration info (without SQL for lighter payloads)\nexport function getMigrationList(): Array<Omit<BundledMigration, 'sql'>> {\n return bundledMigrations.map(({ sql, ...rest }) => rest)\n}\n","import { D1Database } from '@cloudflare/workers-types'\nimport type { QueryableField } from '../schemas/document'\n\n// Identifiers and JSON paths are interpolated into DDL (they cannot be bound), so\n// they are format-guarded here. Source is trusted code config, not user input —\n// this is defense-in-depth, mirroring document-repository.ts.\nconst SAFE_IDENTIFIER = /^[a-z_][a-z0-9_]*$/\n\n/** Map a queryable field's logical type to a SQLite column affinity. */\nfunction affinity(type?: QueryableField['type']): 'TEXT' | 'INTEGER' | 'REAL' {\n if (type === 'number') return 'REAL'\n if (type === 'integer' || type === 'boolean' || type === 'date') return 'INTEGER'\n return 'TEXT'\n}\n\nconst slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '')\n\n/**\n * Authoritative generated-column name for a scalar field. An explicit `column`\n * always wins (back-compat with every existing type definition); otherwise it is\n * derived deterministically from the type id + field name. The repository reads\n * the same `column`/derivation when building filter SQL, so the two never drift.\n */\nexport function resolveColumn(typeId: string, f: QueryableField): string {\n if (f.column) return f.column\n const name = `q_${slug(typeId)}_${slug(f.name)}`\n return name.length <= 60 ? name : `q_${slug(typeId).slice(0, 20)}_${slug(f.name).slice(0, 20)}`\n}\n\n/**\n * Idempotently ensure the `documents` table has a VIRTUAL generated column and a\n * filter/sort index for each of a type's scalar queryable fields. Safe to call on\n * every registration and every bootstrap: existing columns/indexes are skipped,\n * and a concurrent add surfaces as a swallowed \"duplicate column name\".\n *\n * Facet and reference fields need no DDL (generic document_facets /\n * document_references tables), so they are ignored here.\n *\n * Returns the columns it actually created (empty when all already existed).\n */\nexport async function ensureScalarSchema(\n db: D1Database,\n typeId: string,\n fields: QueryableField[],\n): Promise<string[]> {\n const scalars = fields.filter((f) => f.kind === 'scalar')\n if (scalars.length === 0) return []\n\n // pragma_table_info does NOT list VIRTUAL generated columns — use table_xinfo, which does.\n let existing = new Set<string>()\n try {\n const info = await db.prepare(\"SELECT name FROM pragma_table_xinfo('documents')\").all()\n existing = new Set((info?.results ?? []).map((r: any) => r.name))\n } catch {\n // table_xinfo unavailable — fall back to attempting every ALTER (duplicate errors swallowed).\n }\n\n const added: string[] = []\n for (const f of scalars) {\n const col = resolveColumn(typeId, f)\n if (!SAFE_IDENTIFIER.test(col)) {\n console.error(`[scalar-schema] unsafe column name '${col}' for ${typeId}.${f.name} — skipped`)\n continue\n }\n const path = f.path ?? `$.${f.name}`\n if (path.includes(\"'\")) {\n console.error(`[scalar-schema] unsafe json path for ${col} (${typeId}.${f.name}) — skipped`)\n continue\n }\n\n if (!existing.has(col)) {\n try {\n await db\n .prepare(`ALTER TABLE documents ADD COLUMN ${col} ${affinity(f.type)} AS (json_extract(data, '${path}')) VIRTUAL`)\n .run()\n added.push(col)\n console.log(`[scalar-schema] added documents.${col} for type '${typeId}'`)\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error)\n if (!msg.includes('duplicate column name')) {\n console.error(`[scalar-schema] failed to add documents.${col}:`, msg)\n continue\n }\n }\n }\n\n // One general index per column: the leading (tenant_id, type_id, col) prefix\n // serves every equality filter the repository builds; the trailing\n // (updated_at DESC, id DESC) matches the default keyset sort/cursor. Non-partial\n // so a single index covers both draft and published lists.\n try {\n await db\n .prepare(`CREATE INDEX IF NOT EXISTS idx_${col} ON documents(tenant_id, type_id, ${col}, updated_at DESC, id DESC)`)\n .run()\n } catch (error) {\n console.error(`[scalar-schema] failed to create idx_${col}:`, error instanceof Error ? error.message : String(error))\n }\n }\n return added\n}\n","import { D1Database } from '@cloudflare/workers-types'\nimport { bundledMigrations } from '../db/migrations-bundle'\nimport { ensureScalarSchema } from './document-scalar-schema'\nimport type { QueryableField } from '../schemas/document'\n\nexport interface Migration {\n id: string\n name: string\n filename: string\n description?: string\n applied: boolean\n appliedAt?: string\n size?: number\n}\n\nexport interface MigrationStatus {\n totalMigrations: number\n appliedMigrations: number\n pendingMigrations: number\n lastApplied?: string\n migrations: Migration[]\n}\n\nexport class MigrationService {\n constructor(private db: D1Database) {}\n\n /**\n * Cloudflare D1 owns migration bookkeeping through `d1_migrations`.\n * SonicJS intentionally does not create its own tracking table.\n */\n async initializeMigrationsTable(): Promise<void> {\n // Kept as a no-op for compatibility with older callers.\n }\n\n /**\n * Get all available migrations from the bundled migrations\n */\n async getAvailableMigrations(): Promise<Migration[]> {\n const migrations: Migration[] = []\n const appliedMigrations = await this.getD1AppliedMigrations()\n await this.ensureSchemaCompatibility()\n\n // Use bundled migrations as the source of truth\n for (const bundled of bundledMigrations) {\n const applied = appliedMigrations.has(bundled.id)\n const appliedData = appliedMigrations.get(bundled.id)\n\n migrations.push({\n id: bundled.id,\n name: bundled.name,\n filename: bundled.filename,\n description: bundled.description,\n applied,\n appliedAt: applied ? appliedData?.applied_at : undefined,\n size: bundled.sql.length\n })\n }\n\n return migrations\n }\n\n /**\n * Read Wrangler/D1's canonical migration table. If the table is absent, no\n * migrations have been applied by the supported migration runner yet.\n */\n private async getD1AppliedMigrations(): Promise<Map<string, any>> {\n try {\n const appliedResult = await this.db.prepare(\n 'SELECT name, applied_at FROM d1_migrations ORDER BY applied_at ASC'\n ).all()\n\n return new Map(\n (appliedResult.results ?? [])\n .map((row: any) => {\n const filename = String(row.name ?? '')\n const id = filename.match(/^(\\d+)/)?.[1]\n if (!id) return null\n return [id, {\n id,\n name: filename,\n filename,\n applied_at: row.applied_at\n }]\n })\n .filter((entry): entry is [string, any] => entry !== null)\n )\n } catch (error) {\n return new Map()\n }\n }\n\n /**\n * Run idempotent compatibility repairs that are safe outside migration state.\n */\n async ensureSchemaCompatibility(): Promise<void> {\n if (await this.checkTablesExist(['documents'])) {\n await this.ensureDocumentGeneratedColumns()\n }\n }\n\n /**\n * Ensure the `documents` table exposes every queryable VIRTUAL generated column + index (D45).\n * Data-driven repair: reconciles from each active type's `queryable_fields` rather than a hardcoded\n * list, so it stays in sync with whatever types are registered. Generation of these columns is owned\n * by DocumentTypeRegistry.register() (via ensureScalarSchema); this pass is a bootstrap safety net for\n * a DB that has document_types rows but lost columns (e.g. table rebuilt). Idempotent.\n */\n private async ensureDocumentGeneratedColumns(): Promise<void> {\n if (!(await this.checkTablesExist(['document_types']))) return\n const rows = await this.db\n .prepare('SELECT id, queryable_fields FROM document_types WHERE is_active = 1')\n .all<{ id: string; queryable_fields: string }>()\n for (const row of rows.results ?? []) {\n let fields: QueryableField[]\n try {\n fields = JSON.parse(row.queryable_fields)\n } catch {\n continue\n }\n await ensureScalarSchema(this.db, row.id, fields)\n }\n }\n\n /**\n * Check if specific tables exist in the database\n */\n private async checkTablesExist(tableNames: string[]): Promise<boolean> {\n try {\n for (const tableName of tableNames) {\n const result = await this.db.prepare(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`\n ).bind(tableName).first()\n\n if (!result) {\n return false\n }\n }\n return true\n } catch (error) {\n return false\n }\n }\n\n /**\n * Check if a specific column exists in a table\n */\n private async checkColumnExists(tableName: string, columnName: string): Promise<boolean> {\n try {\n const result = await this.db.prepare(\n `SELECT * FROM pragma_table_info(?) WHERE name = ?`\n ).bind(tableName, columnName).first()\n\n return !!result\n } catch (error) {\n return false\n }\n }\n\n /**\n * Get migration status summary\n */\n async getMigrationStatus(): Promise<MigrationStatus> {\n const migrations = await this.getAvailableMigrations()\n const appliedMigrations = migrations.filter(m => m.applied)\n const pendingMigrations = migrations.filter(m => !m.applied)\n\n const lastApplied = appliedMigrations.length > 0\n ? appliedMigrations[appliedMigrations.length - 1]?.appliedAt\n : undefined\n\n return {\n totalMigrations: migrations.length,\n appliedMigrations: appliedMigrations.length,\n pendingMigrations: pendingMigrations.length,\n lastApplied,\n migrations\n }\n }\n\n /**\n * D1 migration state is managed by Wrangler.\n */\n async markMigrationApplied(migrationId: string, name: string, filename: string): Promise<void> {\n void migrationId\n void name\n void filename\n }\n\n /**\n * D1 migration state is managed by Wrangler.\n */\n async removeMigrationApplied(migrationId: string): Promise<void> {\n void migrationId\n }\n\n /**\n * Check if a specific migration has been applied\n */\n async isMigrationApplied(migrationId: string): Promise<boolean> {\n const appliedMigrations = await this.getD1AppliedMigrations()\n return appliedMigrations.has(migrationId)\n }\n\n /**\n * Get the last applied migration\n */\n async getLastAppliedMigration(): Promise<Migration | null> {\n const migrations = await this.getAvailableMigrations()\n return migrations.filter(m => m.applied).at(-1) ?? null\n }\n\n /**\n * Run pending migrations\n */\n async runPendingMigrations(): Promise<{ success: boolean; message: string; applied: string[]; errors: string[] }> {\n return {\n success: false,\n message: 'Migrations are managed by Cloudflare D1. Run `wrangler d1 migrations apply DB --local` or `wrangler d1 migrations apply DB --remote`.',\n applied: [],\n errors: []\n }\n }\n\n /**\n * Validate database schema\n */\n async validateSchema(): Promise<{ valid: boolean; issues: string[] }> {\n const issues: string[] = []\n\n // Basic table existence checks\n const requiredTables = [\n 'users', 'documents', 'document_types'\n ]\n\n for (const table of requiredTables) {\n try {\n await this.db.prepare(`SELECT COUNT(*) FROM ${table} LIMIT 1`).first()\n } catch (error) {\n issues.push(`Missing table: ${table}`)\n }\n }\n\n return {\n valid: issues.length === 0,\n issues\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/db/migrations-bundle.ts","../src/services/document-scalar-schema.ts","../src/services/migrations.ts"],"names":[],"mappings":";AAiBO,IAAM,iBAAA,GAAwC;AAAA,EACnD;AAAA,IACE,EAAA,EAAI,MAAA;AAAA,IACJ,IAAA,EAAM,MAAA;AAAA,IACN,QAAA,EAAU,eAAA;AAAA,IACV,WAAA,EAAa,sBAAA;AAAA,IACb,GAAA,EAAK;AAAA,GACP;AAAA,EACA;AAAA,IACE,EAAA,EAAI,MAAA;AAAA,IACJ,IAAA,EAAM,WAAA;AAAA,IACN,QAAA,EAAU,oBAAA;AAAA,IACV,WAAA,EAAa,2BAAA;AAAA,IACb,GAAA,EAAK;AAAA;AAET,CAAA;AAGiC,IAAI,GAAA;AAAA,EACnC,kBAAkB,GAAA,CAAI,CAAA,CAAA,KAAK,CAAC,CAAA,CAAE,EAAA,EAAI,CAAC,CAAC;AACtC;;;AC/BA,IAAM,eAAA,GAAkB,oBAAA;AAGxB,SAAS,SAAS,IAAA,EAA4D;AAC5E,EAAA,IAAI,IAAA,KAAS,UAAU,OAAO,MAAA;AAC9B,EAAA,IAAI,SAAS,SAAA,IAAa,IAAA,KAAS,SAAA,IAAa,IAAA,KAAS,QAAQ,OAAO,SAAA;AACxE,EAAA,OAAO,MAAA;AACT;AAEA,IAAM,IAAA,GAAO,CAAC,CAAA,KAAc,CAAA,CAAE,WAAA,EAAY,CAAE,OAAA,CAAQ,aAAA,EAAe,GAAG,CAAA,CAAE,OAAA,CAAQ,UAAA,EAAY,EAAE,CAAA;AAQvF,SAAS,aAAA,CAAc,QAAgB,CAAA,EAA2B;AACvE,EAAA,IAAI,CA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EAKA,MAAM,oBAAA,GAA4G;AAChH,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,KAAA;AAAA,MACT,OAAA,EAAS,uIAAA;AAAA,MACT,SAAS,EAAC;AAAA,MACV,QAAQ;AAAC,KACX;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAA,GAAgE;AACpE,IAAA,MAAM,SAAmB,EAAC;AAG1B,IAAA,MAAM,cAAA,GAAiB;AAAA,MACrB,OAAA;AAAA,MAAS,WAAA;AAAA,MAAa;AAAA,KACxB;AAEA,IAAA,KAAA,MAAW,SAAS,cAAA,EAAgB;AAClC,MAAA,IAAI;AACF,QAAA,MAAM,KAAK,EAAA,CAAG,OAAA,CAAQ,wBAAwB,KAAK,CAAA,QAAA,CAAU,EAAE,KAAA,EAAM;AAAA,MACvE,SAAS,KAAA,EAAO;AACd,QAAA,MAAA,CAAO,IAAA,CAAK,CAAA,eAAA,EAAkB,KAAK,CAAA,CAAE,CAAA;AAAA,MACvC;AAAA,IACF;AAEA,IAAA,OAAO;AAAA,MACL,KAAA,EAAO,OAAO,MAAA,KAAW,CAAA;AAAA,MACzB;AAAA,KACF;AAAA,EACF;AACF","file":"chunk-IKEUELHZ.js","sourcesContent":["/**\n * AUTO-GENERATED FILE - DO NOT EDIT\n * Generated by: scripts/generate-migrations.ts\n * Generated at: 2026-06-18T23:55:36.354Z\n *\n * This file contains all migration SQL bundled for use in Cloudflare Workers\n * where filesystem access is not available at runtime.\n */\n\nexport interface BundledMigration {\n id: string\n name: string\n filename: string\n description: string\n sql: string\n}\n\nexport const bundledMigrations: BundledMigration[] = [\n {\n id: '0001',\n name: 'Core',\n filename: '0001_core.sql',\n description: 'Migration 0001: Core',\n sql: \"-- Migration 0001: Auth tables\\n-- auth_user, auth_session, auth_account, auth_verification + BA plugin tables + RBAC + auth support.\\n-- Only auth_* prefixed tables live here. All content lives in document_* tables (0002_documents.sql).\\n\\n-- ── auth_user ────────────────────────────────────────────────────────────────\\n-- BA user model + SonicJS domain columns as BA additionalFields.\\nCREATE TABLE IF NOT EXISTS auth_user (\\n id TEXT PRIMARY KEY,\\n name TEXT,\\n email TEXT NOT NULL UNIQUE,\\n email_verified INTEGER NOT NULL DEFAULT 0,\\n image TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL,\\n -- SonicJS additionalFields\\n first_name TEXT NOT NULL,\\n last_name TEXT NOT NULL,\\n role TEXT NOT NULL DEFAULT 'viewer',\\n -- Platform super-admin: bypasses the multi-tenant membership gate, uses global roles in every\\n -- tenant. Opt-in (default 0); intentionally NOT derived from the 'admin' role.\\n is_super_admin INTEGER NOT NULL DEFAULT 0,\\n avatar TEXT,\\n password_hash TEXT,\\n is_active INTEGER NOT NULL DEFAULT 1,\\n last_login_at INTEGER,\\n phone TEXT,\\n bio TEXT,\\n timezone TEXT DEFAULT 'UTC',\\n language TEXT DEFAULT 'en',\\n email_notifications INTEGER DEFAULT 1,\\n theme TEXT DEFAULT 'dark',\\n invitation_token TEXT,\\n invited_by TEXT,\\n invited_at INTEGER,\\n accepted_invitation_at INTEGER,\\n failed_login_count INTEGER NOT NULL DEFAULT 0,\\n locked_until INTEGER\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_auth_user_email ON auth_user(email);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_role ON auth_user(role);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_invitation_token ON auth_user(invitation_token);\\nCREATE INDEX IF NOT EXISTS idx_auth_user_locked_until ON auth_user(locked_until) WHERE locked_until IS NOT NULL;\\n\\n-- ── auth_session ─────────────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_session (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n token TEXT NOT NULL UNIQUE,\\n expires_at INTEGER NOT NULL,\\n ip_address TEXT,\\n user_agent TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_user_id ON auth_session(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_token ON auth_session(token);\\nCREATE INDEX IF NOT EXISTS idx_auth_session_expires_at ON auth_session(expires_at);\\n\\n-- ── auth_account ─────────────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_account (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n account_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n access_token TEXT,\\n refresh_token TEXT,\\n access_token_expires_at INTEGER,\\n refresh_token_expires_at INTEGER,\\n scope TEXT,\\n id_token TEXT,\\n password TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_account_user_id ON auth_account(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_account_provider ON auth_account(provider_id, account_id);\\n\\n-- ── auth_verification ────────────────────────────────────────────────────────\\n-- Covers email verification, password reset, magic-link tokens, OTP codes.\\nCREATE TABLE IF NOT EXISTS auth_verification (\\n id TEXT PRIMARY KEY,\\n identifier TEXT NOT NULL,\\n value TEXT NOT NULL,\\n expires_at INTEGER NOT NULL,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_verification_identifier ON auth_verification(identifier);\\n\\n-- ── BA plugin tables ──────────────────────────────────────────────────────────\\n\\nCREATE TABLE IF NOT EXISTS auth_two_factor (\\n id TEXT PRIMARY KEY,\\n secret TEXT NOT NULL,\\n backup_codes TEXT NOT NULL,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n verified INTEGER NOT NULL DEFAULT 1,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_two_factor_user_id ON auth_two_factor(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n slug TEXT NOT NULL UNIQUE,\\n logo TEXT,\\n metadata TEXT,\\n -- SonicJS tenant-resolution fields (BA organization additionalFields):\\n status TEXT NOT NULL DEFAULT 'active',\\n domain TEXT,\\n notes TEXT NOT NULL DEFAULT '',\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_domain ON auth_tenant(domain);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_member (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n role TEXT NOT NULL DEFAULT 'member',\\n email TEXT,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL,\\n UNIQUE(tenant_id, user_id)\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_member_tenant ON auth_tenant_member(tenant_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_member_user ON auth_tenant_member(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_invitation (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n email TEXT NOT NULL,\\n role TEXT NOT NULL DEFAULT 'member',\\n status TEXT NOT NULL DEFAULT 'pending',\\n expires_at INTEGER NOT NULL,\\n inviter_id TEXT REFERENCES auth_user(id) ON DELETE SET NULL,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_invitation_tenant ON auth_tenant_invitation(tenant_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_tenant_invitation_email ON auth_tenant_invitation(email);\\n\\nCREATE TABLE IF NOT EXISTS auth_tenant_team (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n tenant_id TEXT NOT NULL REFERENCES auth_tenant(id) ON DELETE CASCADE,\\n created_at INTEGER NOT NULL,\\n updated_at INTEGER NOT NULL\\n);\\n\\n-- ── RBAC ─────────────────────────────────────────────────────────────────────\\n-- RBAC roles, verbs, and user-role assignments are document-backed (is_auth doc\\n-- types rbac_role / rbac_verb / rbac_user_roles — see services/rbac.ts). The\\n-- system roles/verbs/grants are seeded at bootstrap by RbacService.ensureSystemRbacSeed().\\n-- No auth_rbac_* tables.\\n\\n-- ── Auth support tables ───────────────────────────────────────────────────────\\nCREATE TABLE IF NOT EXISTS auth_password_history (\\n id TEXT PRIMARY KEY,\\n user_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,\\n password_hash TEXT NOT NULL,\\n created_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_password_history_user_id ON auth_password_history(user_id);\\n\\nCREATE TABLE IF NOT EXISTS auth_api_tokens (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL,\\n token TEXT NOT NULL UNIQUE,\\n user_id TEXT NOT NULL REFERENCES auth_user(id),\\n permissions TEXT NOT NULL,\\n expires_at INTEGER,\\n last_used_at INTEGER,\\n created_at INTEGER NOT NULL\\n);\\nCREATE INDEX IF NOT EXISTS idx_auth_api_tokens_user ON auth_api_tokens(user_id);\\nCREATE INDEX IF NOT EXISTS idx_auth_api_tokens_token ON auth_api_tokens(token);\\n\\n-- User profiles moved to the document model: a `user_profile` document (is_auth type),\\n-- one per user, addressed by slug = userId. See services/document-types-seed.ts and\\n-- plugins/core-plugins/user-profiles/user-profile-document.ts. No auth_user_profiles table.\\n\"\n },\n {\n id: '0002',\n name: 'Documents',\n filename: '0002_documents.sql',\n description: 'Migration 0002: Documents',\n sql: \"-- Migration 0002: Document Schema (v3 greenfield)\\n-- Contains only the new document data model tables, generated columns, and indexes.\\n\\n-- Document type registry\\nCREATE TABLE IF NOT EXISTS document_types (\\n id TEXT PRIMARY KEY,\\n name TEXT NOT NULL UNIQUE,\\n display_name TEXT NOT NULL,\\n description TEXT,\\n schema TEXT NOT NULL DEFAULT '{}',\\n queryable_fields TEXT NOT NULL DEFAULT '[]',\\n settings TEXT NOT NULL DEFAULT '{}',\\n plugin_id TEXT,\\n source TEXT NOT NULL DEFAULT 'code' CHECK (source IN ('code', 'plugin', 'system')),\\n schema_version INTEGER NOT NULL DEFAULT 1,\\n is_system INTEGER NOT NULL DEFAULT 0,\\n is_active INTEGER NOT NULL DEFAULT 1,\\n is_auth INTEGER NOT NULL DEFAULT 0,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n updated_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_document_types_plugin ON document_types(plugin_id);\\nCREATE INDEX IF NOT EXISTS idx_document_types_active ON document_types(is_active);\\n\\n-- Documents: canonical document rows and historical versions.\\nCREATE TABLE IF NOT EXISTS documents (\\n id TEXT PRIMARY KEY,\\n root_id TEXT NOT NULL,\\n type_id TEXT NOT NULL REFERENCES document_types(id),\\n type_version INTEGER NOT NULL DEFAULT 1,\\n\\n version_of_id TEXT REFERENCES documents(id),\\n version_number INTEGER NOT NULL DEFAULT 1,\\n\\n is_current_draft INTEGER NOT NULL DEFAULT 1,\\n is_published INTEGER NOT NULL DEFAULT 0,\\n status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'archived')),\\n\\n parent_root_id TEXT NOT NULL DEFAULT '',\\n slug TEXT,\\n path TEXT,\\n title TEXT,\\n zone TEXT,\\n sort_order INTEGER NOT NULL DEFAULT 0,\\n visible INTEGER NOT NULL DEFAULT 1,\\n\\n published_at INTEGER,\\n scheduled_at INTEGER,\\n expires_at INTEGER,\\n deleted_at INTEGER,\\n\\n tenant_id TEXT NOT NULL DEFAULT 'default',\\n locale TEXT NOT NULL DEFAULT 'default',\\n translation_group_id TEXT NOT NULL DEFAULT '',\\n\\n data TEXT NOT NULL DEFAULT '{}',\\n metadata TEXT NOT NULL DEFAULT '{}',\\n\\n owner_id TEXT,\\n created_by TEXT,\\n updated_by TEXT,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n updated_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\n-- Queryable scalar fields (VIRTUAL generated columns) and their q_* filter indexes\\n-- are AUTO-GENERATED at runtime from each document type's queryableFields config —\\n-- see DocumentTypeRegistry.register() -> ensureScalarSchema() (document-scalar-schema.ts).\\n-- Do not hand-add q_* columns/indexes here; declare the field in the type instead.\\n\\n-- Revision chain\\nCREATE INDEX IF NOT EXISTS idx_documents_root ON documents(root_id, version_number DESC);\\n\\n-- List / lifecycle\\nCREATE INDEX IF NOT EXISTS idx_documents_published ON documents(tenant_id, type_id, locale, is_published)\\n WHERE is_published = 1 AND deleted_at IS NULL;\\nCREATE INDEX IF NOT EXISTS idx_documents_drafts ON documents(tenant_id, type_id, status, is_current_draft)\\n WHERE is_current_draft = 1;\\nCREATE INDEX IF NOT EXISTS idx_documents_parent ON documents(tenant_id, parent_root_id, sort_order, is_published);\\nCREATE INDEX IF NOT EXISTS idx_documents_path ON documents(tenant_id, path);\\nCREATE INDEX IF NOT EXISTS idx_documents_translation ON documents(translation_group_id, locale);\\nCREATE INDEX IF NOT EXISTS idx_documents_deleted ON documents(deleted_at);\\nCREATE INDEX IF NOT EXISTS idx_documents_scheduled ON documents(scheduled_at) WHERE scheduled_at IS NOT NULL;\\nCREATE INDEX IF NOT EXISTS idx_documents_expires ON documents(expires_at) WHERE expires_at IS NOT NULL;\\n\\n-- Stable keyset/cursor pagination for published lists\\nCREATE INDEX IF NOT EXISTS idx_documents_published_cursor\\n ON documents(tenant_id, type_id, updated_at DESC, id DESC)\\n WHERE is_published = 1 AND deleted_at IS NULL;\\n\\n-- (q_* generated-column filter indexes are auto-created at runtime — see note above.)\\n\\n-- Partial unique indexes: the hard concurrency guarantees for draft/publish invariants.\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_current_draft\\n ON documents(root_id) WHERE is_current_draft = 1;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_published\\n ON documents(root_id) WHERE is_published = 1;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_unique_version\\n ON documents(root_id, version_number);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_unique_slug\\n ON documents(tenant_id, locale, type_id, parent_root_id, slug)\\n WHERE is_current_draft = 1 AND deleted_at IS NULL AND slug IS NOT NULL;\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_documents_one_translation_per_locale\\n ON documents(tenant_id, translation_group_id, locale)\\n WHERE is_current_draft = 1 AND translation_group_id <> '';\\n\\n-- Document references: typed document-to-document edges.\\nCREATE TABLE IF NOT EXISTS document_references (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n from_root_id TEXT NOT NULL,\\n from_document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\\n field_name TEXT NOT NULL,\\n ordinal INTEGER NOT NULL DEFAULT 0,\\n to_root_id TEXT NOT NULL,\\n ref_strength TEXT NOT NULL DEFAULT 'weak' CHECK (ref_strength IN ('strong', 'weak')),\\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_docref_to ON document_references(tenant_id, to_root_id);\\nCREATE INDEX IF NOT EXISTS idx_docref_from ON document_references(from_document_id);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_docref_unique\\n ON document_references(from_document_id, field_name, ordinal);\\n\\n-- Document facets: indexed rows for multi-valued scalar fields (e.g. tags arrays).\\nCREATE TABLE IF NOT EXISTS document_facets (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n document_id TEXT NOT NULL REFERENCES documents(id) ON DELETE CASCADE,\\n root_id TEXT NOT NULL,\\n type_id TEXT NOT NULL,\\n field_name TEXT NOT NULL,\\n ordinal INTEGER NOT NULL DEFAULT 0,\\n value_text TEXT,\\n value_number REAL,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_facets_lookup ON document_facets(tenant_id, type_id, field_name, value_text);\\nCREATE INDEX IF NOT EXISTS idx_facets_doc ON document_facets(document_id);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_facets_unique\\n ON document_facets(document_id, field_name, ordinal);\\n\\n-- Document permissions: per-document ACL overrides.\\nCREATE TABLE IF NOT EXISTS document_permissions (\\n id TEXT PRIMARY KEY,\\n tenant_id TEXT NOT NULL,\\n root_id TEXT NOT NULL,\\n principal_type TEXT NOT NULL CHECK (principal_type IN ('user', 'role', 'group', 'public', 'token')),\\n principal_id TEXT NOT NULL,\\n permission TEXT NOT NULL CHECK (permission IN ('read', 'create', 'update', 'delete', 'publish', 'manage')),\\n effect TEXT NOT NULL DEFAULT 'allow' CHECK (effect IN ('allow', 'deny')),\\n inherited INTEGER NOT NULL DEFAULT 0,\\n created_at INTEGER NOT NULL DEFAULT (unixepoch()),\\n created_by TEXT\\n);\\n\\nCREATE INDEX IF NOT EXISTS idx_document_permissions_root ON document_permissions(tenant_id, root_id);\\nCREATE INDEX IF NOT EXISTS idx_document_permissions_principal\\n ON document_permissions(tenant_id, principal_type, principal_id, permission);\\nCREATE UNIQUE INDEX IF NOT EXISTS idx_document_permissions_unique\\n ON document_permissions(root_id, principal_type, principal_id, permission);\\n\"\n }\n]\n\n// Map for quick lookup by ID\nexport const migrationsByIdMap = new Map<string, BundledMigration>(\n bundledMigrations.map(m => [m.id, m])\n)\n\n// Get migration SQL by ID\nexport function getMigrationSQLById(id: string): string | null {\n return migrationsByIdMap.get(id)?.sql ?? null\n}\n\n// Get all migration info (without SQL for lighter payloads)\nexport function getMigrationList(): Array<Omit<BundledMigration, 'sql'>> {\n return bundledMigrations.map(({ sql, ...rest }) => rest)\n}\n","import { D1Database } from '@cloudflare/workers-types'\nimport type { QueryableField } from '../schemas/document'\n\n// Identifiers and JSON paths are interpolated into DDL (they cannot be bound), so\n// they are format-guarded here. Source is trusted code config, not user input —\n// this is defense-in-depth, mirroring document-repository.ts.\nconst SAFE_IDENTIFIER = /^[a-z_][a-z0-9_]*$/\n\n/** Map a queryable field's logical type to a SQLite column affinity. */\nfunction affinity(type?: QueryableField['type']): 'TEXT' | 'INTEGER' | 'REAL' {\n if (type === 'number') return 'REAL'\n if (type === 'integer' || type === 'boolean' || type === 'date') return 'INTEGER'\n return 'TEXT'\n}\n\nconst slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '')\n\n/**\n * Authoritative generated-column name for a scalar field. An explicit `column`\n * always wins (back-compat with every existing type definition); otherwise it is\n * derived deterministically from the type id + field name. The repository reads\n * the same `column`/derivation when building filter SQL, so the two never drift.\n */\nexport function resolveColumn(typeId: string, f: QueryableField): string {\n if (f.column) return f.column\n const name = `q_${slug(typeId)}_${slug(f.name)}`\n return name.length <= 60 ? name : `q_${slug(typeId).slice(0, 20)}_${slug(f.name).slice(0, 20)}`\n}\n\n/**\n * Idempotently ensure the `documents` table has a VIRTUAL generated column and a\n * filter/sort index for each of a type's scalar queryable fields. Safe to call on\n * every registration and every bootstrap: existing columns/indexes are skipped,\n * and a concurrent add surfaces as a swallowed \"duplicate column name\".\n *\n * Facet and reference fields need no DDL (generic document_facets /\n * document_references tables), so they are ignored here.\n *\n * Returns the columns it actually created (empty when all already existed).\n */\nexport async function ensureScalarSchema(\n db: D1Database,\n typeId: string,\n fields: QueryableField[],\n): Promise<string[]> {\n const scalars = fields.filter((f) => f.kind === 'scalar')\n if (scalars.length === 0) return []\n\n // pragma_table_info does NOT list VIRTUAL generated columns — use table_xinfo, which does.\n let existing = new Set<string>()\n try {\n const info = await db.prepare(\"SELECT name FROM pragma_table_xinfo('documents')\").all()\n existing = new Set((info?.results ?? []).map((r: any) => r.name))\n } catch {\n // table_xinfo unavailable — fall back to attempting every ALTER (duplicate errors swallowed).\n }\n\n const added: string[] = []\n for (const f of scalars) {\n const col = resolveColumn(typeId, f)\n if (!SAFE_IDENTIFIER.test(col)) {\n console.error(`[scalar-schema] unsafe column name '${col}' for ${typeId}.${f.name} — skipped`)\n continue\n }\n const path = f.path ?? `$.${f.name}`\n if (path.includes(\"'\")) {\n console.error(`[scalar-schema] unsafe json path for ${col} (${typeId}.${f.name}) — skipped`)\n continue\n }\n\n if (!existing.has(col)) {\n try {\n await db\n .prepare(`ALTER TABLE documents ADD COLUMN ${col} ${affinity(f.type)} AS (json_extract(data, '${path}')) VIRTUAL`)\n .run()\n added.push(col)\n console.log(`[scalar-schema] added documents.${col} for type '${typeId}'`)\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error)\n if (!msg.includes('duplicate column name')) {\n console.error(`[scalar-schema] failed to add documents.${col}:`, msg)\n continue\n }\n }\n }\n\n // One general index per column: the leading (tenant_id, type_id, col) prefix\n // serves every equality filter the repository builds; the trailing\n // (updated_at DESC, id DESC) matches the default keyset sort/cursor. Non-partial\n // so a single index covers both draft and published lists.\n try {\n await db\n .prepare(`CREATE INDEX IF NOT EXISTS idx_${col} ON documents(tenant_id, type_id, ${col}, updated_at DESC, id DESC)`)\n .run()\n } catch (error) {\n console.error(`[scalar-schema] failed to create idx_${col}:`, error instanceof Error ? error.message : String(error))\n }\n }\n return added\n}\n","import { D1Database } from '@cloudflare/workers-types'\nimport { bundledMigrations } from '../db/migrations-bundle'\nimport { ensureScalarSchema } from './document-scalar-schema'\nimport type { QueryableField } from '../schemas/document'\n\nexport interface Migration {\n id: string\n name: string\n filename: string\n description?: string\n applied: boolean\n appliedAt?: string\n size?: number\n}\n\nexport interface MigrationStatus {\n totalMigrations: number\n appliedMigrations: number\n pendingMigrations: number\n lastApplied?: string\n migrations: Migration[]\n}\n\nexport class MigrationService {\n constructor(private db: D1Database) {}\n\n /**\n * Cloudflare D1 owns migration bookkeeping through `d1_migrations`.\n * SonicJS intentionally does not create its own tracking table.\n */\n async initializeMigrationsTable(): Promise<void> {\n // Kept as a no-op for compatibility with older callers.\n }\n\n /**\n * Get all available migrations from the bundled migrations\n */\n async getAvailableMigrations(): Promise<Migration[]> {\n const migrations: Migration[] = []\n const appliedMigrations = await this.getD1AppliedMigrations()\n await this.ensureSchemaCompatibility()\n\n // Use bundled migrations as the source of truth\n for (const bundled of bundledMigrations) {\n const applied = appliedMigrations.has(bundled.id)\n const appliedData = appliedMigrations.get(bundled.id)\n\n migrations.push({\n id: bundled.id,\n name: bundled.name,\n filename: bundled.filename,\n description: bundled.description,\n applied,\n appliedAt: applied ? appliedData?.applied_at : undefined,\n size: bundled.sql.length\n })\n }\n\n return migrations\n }\n\n /**\n * Read Wrangler/D1's canonical migration table. If the table is absent, no\n * migrations have been applied by the supported migration runner yet.\n */\n private async getD1AppliedMigrations(): Promise<Map<string, any>> {\n try {\n const appliedResult = await this.db.prepare(\n 'SELECT name, applied_at FROM d1_migrations ORDER BY applied_at ASC'\n ).all()\n\n return new Map(\n (appliedResult.results ?? [])\n .map((row: any) => {\n const filename = String(row.name ?? '')\n const id = filename.match(/^(\\d+)/)?.[1]\n if (!id) return null\n return [id, {\n id,\n name: filename,\n filename,\n applied_at: row.applied_at\n }]\n })\n .filter((entry): entry is [string, any] => entry !== null)\n )\n } catch (error) {\n return new Map()\n }\n }\n\n /**\n * Run idempotent compatibility repairs that are safe outside migration state.\n */\n async ensureSchemaCompatibility(): Promise<void> {\n if (await this.checkTablesExist(['documents'])) {\n await this.ensureDocumentGeneratedColumns()\n }\n }\n\n /**\n * Ensure the `documents` table exposes every queryable VIRTUAL generated column + index (D45).\n * Data-driven repair: reconciles from each active type's `queryable_fields` rather than a hardcoded\n * list, so it stays in sync with whatever types are registered. Generation of these columns is owned\n * by DocumentTypeRegistry.register() (via ensureScalarSchema); this pass is a bootstrap safety net for\n * a DB that has document_types rows but lost columns (e.g. table rebuilt). Idempotent.\n */\n private async ensureDocumentGeneratedColumns(): Promise<void> {\n if (!(await this.checkTablesExist(['document_types']))) return\n const rows = await this.db\n .prepare('SELECT id, queryable_fields FROM document_types WHERE is_active = 1')\n .all<{ id: string; queryable_fields: string }>()\n for (const row of rows.results ?? []) {\n let fields: QueryableField[]\n try {\n fields = JSON.parse(row.queryable_fields)\n } catch {\n continue\n }\n await ensureScalarSchema(this.db, row.id, fields)\n }\n }\n\n /**\n * Check if specific tables exist in the database\n */\n private async checkTablesExist(tableNames: string[]): Promise<boolean> {\n try {\n for (const tableName of tableNames) {\n const result = await this.db.prepare(\n `SELECT name FROM sqlite_master WHERE type='table' AND name=?`\n ).bind(tableName).first()\n\n if (!result) {\n return false\n }\n }\n return true\n } catch (error) {\n return false\n }\n }\n\n /**\n * Check if a specific column exists in a table\n */\n private async checkColumnExists(tableName: string, columnName: string): Promise<boolean> {\n try {\n const result = await this.db.prepare(\n `SELECT * FROM pragma_table_info(?) WHERE name = ?`\n ).bind(tableName, columnName).first()\n\n return !!result\n } catch (error) {\n return false\n }\n }\n\n /**\n * Get migration status summary\n */\n async getMigrationStatus(): Promise<MigrationStatus> {\n const migrations = await this.getAvailableMigrations()\n const appliedMigrations = migrations.filter(m => m.applied)\n const pendingMigrations = migrations.filter(m => !m.applied)\n\n const lastApplied = appliedMigrations.length > 0\n ? appliedMigrations[appliedMigrations.length - 1]?.appliedAt\n : undefined\n\n return {\n totalMigrations: migrations.length,\n appliedMigrations: appliedMigrations.length,\n pendingMigrations: pendingMigrations.length,\n lastApplied,\n migrations\n }\n }\n\n /**\n * D1 migration state is managed by Wrangler.\n */\n async markMigrationApplied(migrationId: string, name: string, filename: string): Promise<void> {\n void migrationId\n void name\n void filename\n }\n\n /**\n * D1 migration state is managed by Wrangler.\n */\n async removeMigrationApplied(migrationId: string): Promise<void> {\n void migrationId\n }\n\n /**\n * Check if a specific migration has been applied\n */\n async isMigrationApplied(migrationId: string): Promise<boolean> {\n const appliedMigrations = await this.getD1AppliedMigrations()\n return appliedMigrations.has(migrationId)\n }\n\n /**\n * Get the last applied migration\n */\n async getLastAppliedMigration(): Promise<Migration | null> {\n const migrations = await this.getAvailableMigrations()\n return migrations.filter(m => m.applied).at(-1) ?? null\n }\n\n /**\n * Run pending migrations\n */\n async runPendingMigrations(): Promise<{ success: boolean; message: string; applied: string[]; errors: string[] }> {\n return {\n success: false,\n message: 'Migrations are managed by Cloudflare D1. Run `wrangler d1 migrations apply DB --local` or `wrangler d1 migrations apply DB --remote`.',\n applied: [],\n errors: []\n }\n }\n\n /**\n * Validate database schema\n */\n async validateSchema(): Promise<{ valid: boolean; issues: string[] }> {\n const issues: string[] = []\n\n // Basic table existence checks\n const requiredTables = [\n 'users', 'documents', 'document_types'\n ]\n\n for (const table of requiredTables) {\n try {\n await this.db.prepare(`SELECT COUNT(*) FROM ${table} LIMIT 1`).first()\n } catch (error) {\n issues.push(`Missing table: ${table}`)\n }\n }\n\n return {\n valid: issues.length === 0,\n issues\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { definePlugin, HOOK_CAPABILITY_MAP, SonicCapabilityError, setPluginDefinitions } from './chunk-MP3Q2W76.js';
1
+ import { definePlugin, HOOK_CAPABILITY_MAP, SonicCapabilityError, setPluginDefinitions } from './chunk-ZWUXEIJY.js';
2
2
  import { isKnownHookEvent } from './chunk-RNZFGN4R.js';
3
- import { getCoreVersion } from './chunk-XFQHK64T.js';
3
+ import { getCoreVersion } from './chunk-I547QD6V.js';
4
4
  import { HOOKS } from './chunk-QXOZI5Q2.js';
5
5
  import { __commonJS, __toESM } from './chunk-V4OQ3NZ2.js';
6
6
  import { z } from 'zod';
@@ -3801,5 +3801,5 @@ definePlugin({
3801
3801
  });
3802
3802
 
3803
3803
  export { HookSystemImpl, HookUtils, PluginDependencyCycleError, PluginManager, PluginRegisterMustBeSyncError, PluginRegistryImpl, PluginValidator, RegisterPluginsError, ScopedHookSystem, TurnstileService, collectCronSchedules, collectCrons, createPluginWirer, createScheduledHandler, createTurnstileMiddleware, dispatchCronTick, getPluginMenu, mountPlugin, registerPluginRoutes, registerPlugins, resetPluginMenu, resolvePluginMenuItems, setPluginMenu, topoSort, verifyTurnstile, wireRegisteredPlugins };
3804
- //# sourceMappingURL=chunk-SL6XS6YT.js.map
3805
- //# sourceMappingURL=chunk-SL6XS6YT.js.map
3804
+ //# sourceMappingURL=chunk-JI4E5YFS.js.map
3805
+ //# sourceMappingURL=chunk-JI4E5YFS.js.map