@elytracms/studio 0.0.47 → 0.0.48

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 (72) hide show
  1. package/convex/auth.ts +61 -12
  2. package/convex/authority.ts +40 -2
  3. package/convex/functions.ts +9 -0
  4. package/convex/invites.ts +75 -0
  5. package/convex/members.ts +44 -18
  6. package/convex/schema.ts +37 -0
  7. package/convex/users.ts +89 -2
  8. package/dist/components/account/account-settings.d.ts +13 -0
  9. package/dist/components/account/account-settings.js +54 -0
  10. package/dist/components/account/account-settings.js.map +1 -0
  11. package/dist/components/account/credential-panel.d.ts +14 -0
  12. package/dist/components/account/credential-panel.js +52 -0
  13. package/dist/components/account/credential-panel.js.map +1 -0
  14. package/dist/components/account/self-account-schema.d.ts +19 -0
  15. package/dist/components/account/self-account-schema.js +52 -0
  16. package/dist/components/account/self-account-schema.js.map +1 -0
  17. package/dist/components/account/self-account-view-source.d.ts +35 -0
  18. package/dist/components/account/self-account-view-source.js +110 -0
  19. package/dist/components/account/self-account-view-source.js.map +1 -0
  20. package/dist/components/auth-context.d.ts +5 -1
  21. package/dist/components/auth-context.js +9 -0
  22. package/dist/components/auth-context.js.map +1 -1
  23. package/dist/components/current-user-menu.js +11 -2
  24. package/dist/components/current-user-menu.js.map +1 -1
  25. package/dist/components/deployment-setup-gate.d.ts +31 -0
  26. package/dist/components/deployment-setup-gate.js +92 -0
  27. package/dist/components/deployment-setup-gate.js.map +1 -0
  28. package/dist/components/project-session.d.ts +1 -1
  29. package/dist/components/project-session.js.map +1 -1
  30. package/dist/components/use-hydration-phase.js +1 -1
  31. package/dist/components/use-hydration-phase.js.map +1 -1
  32. package/dist/components/users/invite-user-bar.d.ts +3 -0
  33. package/dist/components/users/invite-user-bar.js +91 -0
  34. package/dist/components/users/invite-user-bar.js.map +1 -0
  35. package/dist/components/users/users-module.js +13 -2
  36. package/dist/components/users/users-module.js.map +1 -1
  37. package/dist/lib/auth/auth-adapter.d.ts +50 -2
  38. package/dist/lib/auth/auth-adapter.js.map +1 -1
  39. package/dist/lib/auth/convex-auth-adapter.d.ts +28 -1
  40. package/dist/lib/auth/convex-auth-adapter.js +113 -1
  41. package/dist/lib/auth/convex-auth-adapter.js.map +1 -1
  42. package/dist/lib/auth/dev-auto-login-adapter.d.ts +3 -1
  43. package/dist/lib/auth/dev-auto-login-adapter.js +6 -0
  44. package/dist/lib/auth/dev-auto-login-adapter.js.map +1 -1
  45. package/dist/lib/auth/index.d.ts +2 -2
  46. package/dist/lib/auth/index.js +1 -1
  47. package/dist/lib/auth/index.js.map +1 -1
  48. package/dist/lib/auth/local-auth-adapter.d.ts +3 -1
  49. package/dist/lib/auth/local-auth-adapter.js +16 -0
  50. package/dist/lib/auth/local-auth-adapter.js.map +1 -1
  51. package/dist/lib/i18n/messages.en.js +45 -0
  52. package/dist/lib/i18n/messages.en.js.map +1 -1
  53. package/dist/lib/operations/studio-operations.js +1 -1
  54. package/dist/lib/operations/studio-operations.js.map +1 -1
  55. package/dist/lib/persistence/backend-mode.d.ts +1 -1
  56. package/dist/lib/persistence/backend-mode.js +1 -1
  57. package/dist/lib/persistence/backend-mode.js.map +1 -1
  58. package/dist/lib/persistence/convex-adapter.d.ts +2 -1
  59. package/dist/lib/persistence/convex-adapter.js +69 -1
  60. package/dist/lib/persistence/convex-adapter.js.map +1 -1
  61. package/dist/lib/persistence/deployment-readiness.d.ts +36 -0
  62. package/dist/lib/persistence/deployment-readiness.js +26 -0
  63. package/dist/lib/persistence/deployment-readiness.js.map +1 -0
  64. package/dist/lib/persistence/index.d.ts +3 -1
  65. package/dist/lib/persistence/index.js +4 -1
  66. package/dist/lib/persistence/index.js.map +1 -1
  67. package/dist/lib/workspace/switcher-source.js +1 -1
  68. package/dist/lib/workspace/switcher-source.js.map +1 -1
  69. package/dist/lib/workspace/workspace-source.d.ts +1 -1
  70. package/dist/lib/workspace/workspace-source.js +1 -1
  71. package/dist/lib/workspace/workspace-source.js.map +1 -1
  72. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"studio-operations.js","sourceRoot":"","sources":["../../../src/lib/operations/studio-operations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAA;AAC9E,OAAO,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAgD7B;;;;GAIG;AACH,SAAS,4BAA4B;IACnC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC,EAAE,CAAA;AACpD,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,sBAAsB,CACpC,OAA2B,EAC3B,UAAyC,EAAE;IAE3C,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK;QAC9B,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,uBAAuB,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC/E,CAAC,CAAC,EAAE,CAAA;IACN,MAAM,UAAU,GAAG,gBAAgB,CAAC,EAAE,OAAO,EAAE,GAAG,UAAU,EAAE,CAAC,CAAA;IAC/D,mFAAmF;IACnF,gFAAgF;IAChF,gFAAgF;IAChF,kFAAkF;IAClF,+EAA+E;IAC/E,0EAA0E;IAC1E,MAAM,UAAU,GAAG,OAAO,CAAC,uBAAuB;QAChD,CAAC,CAAC,4BAA4B,EAAE;QAChC,CAAC,CAAC,oBAAoB,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACpD,MAAM,UAAU,GAAG,gBAAgB,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,GAAG,UAAU,EAAE,CAAC,CAAA;IAC1F,4EAA4E;IAC5E,wEAAwE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,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAuB;IACtD,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,EAAE;QAAE,OAAM,CAAC,8CAA8C;IACzF,YAAY,GAAG,KAAK,CAAA;IACpB,cAAc,CAAC,KAAK,EAAE,CAAA;AACxB,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,2BAA2B,CAAC,IAA6B;IACvE,IAAI,IAAI,EAAE,CAAC;QACT,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;QAC1D,OAAM;IACR,CAAC;IACD,cAAc,CAAC,KAAK,EAAE,CAAA;IACtB,aAAa,CAAC,KAAK,EAAE,CAAA;IACrB,YAAY,GAAG,IAAI,CAAA;AACrB,CAAC","sourcesContent":["import type { PersistenceAdapter } from '@elytracms/core/persistence'\nimport { activeDeploymentKey, selectPersistenceAdapter } from '../persistence'\nimport { attachConfiguredRevalidationWebhooks } from '../webhooks'\nimport {\n attachReferenceIndex,\n createChangesets,\n createOperations,\n createRoleAuthorization,\n} from './operations-package'\nimport type {\n ChangesetOperations,\n OperationsClient,\n Principal,\n ReferenceIndexAttachment,\n} from './operations-package'\n\n/**\n * The studio's single operations bootstrap (EC-141, vision AD-7).\n *\n * One `OperationsClient` + one `ChangesetOperations` instance, built over the\n * selected persistence adapter, shared by every store and surface in the app.\n * The UI never talks to a repository for writes — every mutation is a typed\n * operation command (validate → authorize → mutate → event), so the studio\n * dogfoods the same seam plugins, AI changesets, and the CLI use.\n *\n * The EC-155 reference index is attached to the shared event bus here, so any\n * document/graph/publishing command issued anywhere in the studio keeps the\n * index maintained.\n */\nexport interface StudioOperations {\n readonly operations: OperationsClient\n readonly changesets: ChangesetOperations\n /**\n * The raw adapter, exposed for *transport and read paths only*: blob byte\n * upload/download (`adapter.blobs`) and existing read stores. Studio code\n * must not call repository write methods on it — writes go through\n * `operations`.\n */\n readonly adapter: PersistenceAdapter\n /** EC-155 maintained-on-write index attachment (flushable in tests). */\n readonly references: ReferenceIndexAttachment\n}\n\nexport interface CreateStudioOperationsOptions {\n /**\n * The signed-in principal (EC-150). When present, the EC-150 role hook\n * (`createRoleAuthorization` over `adapter.members`) becomes the\n * authorization chokepoint for every command and query — viewers get\n * structured denials on mutations, editors on administration. Without an\n * actor the client runs pass-through (seeds, fixtures, tests that exercise\n * domain logic rather than permissions); the route guard keeps\n * unauthenticated users away from every operation surface.\n */\n actor?: Principal\n}\n\n/**\n * A no-op {@link ReferenceIndexAttachment} for self-maintaining adapters (EC-277):\n * nothing is subscribed, so `detach` and `flush` are trivially satisfied (the index\n * is kept current in the adapter's write path, not by a queued subscriber).\n */\nfunction noopReferenceIndexAttachment(): ReferenceIndexAttachment {\n return { detach: () => {}, flush: async () => {} }\n}\n\n/** Build a studio operations bundle over an adapter (exported for tests). */\nexport function createStudioOperations(\n adapter: PersistenceAdapter,\n options: CreateStudioOperationsOptions = {},\n): StudioOperations {\n const authorized = options.actor\n ? { actor: options.actor, authorize: createRoleAuthorization(adapter.members) }\n : {}\n const operations = createOperations({ adapter, ...authorized })\n // EC-277: when the adapter maintains the index in its own write path (AD-6 \"at the\n // source\" — the Convex provider does this server-side, so a raw `convex run` is\n // caught too), the client-side subscriber would only double the work. Attach it\n // ONLY for providers that don't self-maintain. Where it does run, extraction is a\n // schema-free, manifest-free walk over self-describing content, so it needs no\n // registry (compositions self-typed their relation/asset props on write).\n const references = adapter.maintainsReferenceIndex\n ? noopReferenceIndexAttachment()\n : attachReferenceIndex(operations.events, adapter)\n const changesets = createChangesets({ adapter, events: operations.events, ...authorized })\n // EC-146 instant publish: when a host revalidate endpoint is configured via\n // env, every successful publish-shaped command (document upsert/delete/\n // setState, graph publish/unpublish) fires a signed revalidation webhook.\n // No env (dev/tests) → no-op.\n attachConfiguredRevalidationWebhooks(operations.events)\n return { operations, changesets, adapter, references }\n}\n\n// One adapter + one operations bundle per backend (EC-179): keyed by the active\n// deployment so switching to a project on another Convex deployment selects (or\n// lazily builds) that backend's client, rather than reusing the first one.\nconst adaptersByKey = new Map<string, Promise<PersistenceAdapter>>()\nconst instancesByKey = new Map<string, Promise<StudioOperations>>()\nlet currentActor: Principal | null = null\n\n/**\n * The active backend key, tolerant of an unconfigured env: the real app never\n * reaches `getStudioOperations` while misconfigured (the `BackendGate` renders a\n * boot error first), but tests inject a bundle directly via the seam below — so\n * a missing backend resolves to one stable key rather than throwing.\n */\nfunction deploymentKey(): string {\n try {\n return activeDeploymentKey()\n } catch {\n return '__unconfigured__'\n }\n}\n\nfunction getAdapter(key: string): Promise<PersistenceAdapter> {\n let adapter = adaptersByKey.get(key)\n if (!adapter) {\n adapter = selectPersistenceAdapter()\n adaptersByKey.set(key, adapter)\n }\n return adapter\n}\n\n/**\n * The shared studio operations client for the active backend (lazily\n * bootstrapped, cached per deployment). In-memory mode this owns the one seeded\n * adapter the whole session mutates; against Convex it owns one client per\n * deployment — the active project (EC-179) selects which.\n */\nexport function getStudioOperations(): Promise<StudioOperations> {\n const key = deploymentKey()\n let instance = instancesByKey.get(key)\n if (!instance) {\n const actor = currentActor\n instance = getAdapter(key).then((adapter) =>\n createStudioOperations(adapter, actor ? { actor } : {}),\n )\n instancesByKey.set(key, instance)\n }\n return instance\n}\n\n/**\n * Bind (or clear) the session principal (EC-150). Called by the auth context\n * on sign-in/sign-out. Rebuilds the operations clients over the *same* adapters\n * — the persisted state (and, in-memory, the whole session's edits) survives;\n * only the authorization identity changes. All cached backends are rebuilt so a\n * later switch picks up the new actor too.\n */\nexport function setStudioSession(actor: Principal | null): void {\n if (currentActor?.id === actor?.id) return // same user (or both null) — keep the clients\n currentActor = actor\n instancesByKey.clear()\n}\n\n/** Test seam: replace (or clear) the singleton for the active backend. */\nexport function setStudioOperationsForTests(next: StudioOperations | null): void {\n if (next) {\n instancesByKey.set(deploymentKey(), Promise.resolve(next))\n return\n }\n instancesByKey.clear()\n adaptersByKey.clear()\n currentActor = null\n}\n"]}
1
+ {"version":3,"file":"studio-operations.js","sourceRoot":"","sources":["../../../src/lib/operations/studio-operations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAA;AAC9E,OAAO,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAA;AAClE,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAgD7B;;;;GAIG;AACH,SAAS,4BAA4B;IACnC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC,EAAE,CAAA;AACpD,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,sBAAsB,CACpC,OAA2B,EAC3B,UAAyC,EAAE;IAE3C,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK;QAC9B,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,uBAAuB,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QAC/E,CAAC,CAAC,EAAE,CAAA;IACN,MAAM,UAAU,GAAG,gBAAgB,CAAC,EAAE,OAAO,EAAE,GAAG,UAAU,EAAE,CAAC,CAAA;IAC/D,mFAAmF;IACnF,gFAAgF;IAChF,gFAAgF;IAChF,kFAAkF;IAClF,+EAA+E;IAC/E,0EAA0E;IAC1E,MAAM,UAAU,GAAG,OAAO,CAAC,uBAAuB;QAChD,CAAC,CAAC,4BAA4B,EAAE;QAChC,CAAC,CAAC,oBAAoB,CAAC,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IACpD,MAAM,UAAU,GAAG,gBAAgB,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,CA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EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CACxD,CAAA;QACD,cAAc,CAAC,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAA;IACnC,CAAC;IACD,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAuB;IACtD,IAAI,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,EAAE;QAAE,OAAM,CAAC,8CAA8C;IACzF,YAAY,GAAG,KAAK,CAAA;IACpB,cAAc,CAAC,KAAK,EAAE,CAAA;AACxB,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,2BAA2B,CAAC,IAA6B;IACvE,IAAI,IAAI,EAAE,CAAC;QACT,cAAc,CAAC,GAAG,CAAC,aAAa,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;QAC1D,OAAM;IACR,CAAC;IACD,cAAc,CAAC,KAAK,EAAE,CAAA;IACtB,aAAa,CAAC,KAAK,EAAE,CAAA;IACrB,YAAY,GAAG,IAAI,CAAA;AACrB,CAAC","sourcesContent":["import type { PersistenceAdapter } from '@elytracms/core/persistence'\nimport { activeDeploymentKey, selectPersistenceAdapter } from '../persistence'\nimport { attachConfiguredRevalidationWebhooks } from '../webhooks'\nimport {\n attachReferenceIndex,\n createChangesets,\n createOperations,\n createRoleAuthorization,\n} from './operations-package'\nimport type {\n ChangesetOperations,\n OperationsClient,\n Principal,\n ReferenceIndexAttachment,\n} from './operations-package'\n\n/**\n * The studio's single operations bootstrap (EC-141, vision AD-7).\n *\n * One `OperationsClient` + one `ChangesetOperations` instance, built over the\n * selected persistence adapter, shared by every store and surface in the app.\n * The UI never talks to a repository for writes — every mutation is a typed\n * operation command (validate → authorize → mutate → event), so the studio\n * dogfoods the same seam plugins, AI changesets, and the CLI use.\n *\n * The EC-155 reference index is attached to the shared event bus here, so any\n * document/graph/publishing command issued anywhere in the studio keeps the\n * index maintained.\n */\nexport interface StudioOperations {\n readonly operations: OperationsClient\n readonly changesets: ChangesetOperations\n /**\n * The raw adapter, exposed for *transport and read paths only*: blob byte\n * upload/download (`adapter.blobs`) and existing read stores. Studio code\n * must not call repository write methods on it — writes go through\n * `operations`.\n */\n readonly adapter: PersistenceAdapter\n /** EC-155 maintained-on-write index attachment (flushable in tests). */\n readonly references: ReferenceIndexAttachment\n}\n\nexport interface CreateStudioOperationsOptions {\n /**\n * The signed-in principal (EC-150). When present, the EC-150 role hook\n * (`createRoleAuthorization` over `adapter.members`) becomes the\n * authorization chokepoint for every command and query — viewers get\n * structured denials on mutations, editors on administration. Without an\n * actor the client runs pass-through (seeds, fixtures, tests that exercise\n * domain logic rather than permissions); the route guard keeps\n * unauthenticated users away from every operation surface.\n */\n actor?: Principal\n}\n\n/**\n * A no-op {@link ReferenceIndexAttachment} for self-maintaining adapters (EC-277):\n * nothing is subscribed, so `detach` and `flush` are trivially satisfied (the index\n * is kept current in the adapter's write path, not by a queued subscriber).\n */\nfunction noopReferenceIndexAttachment(): ReferenceIndexAttachment {\n return { detach: () => {}, flush: async () => {} }\n}\n\n/** Build a studio operations bundle over an adapter (exported for tests). */\nexport function createStudioOperations(\n adapter: PersistenceAdapter,\n options: CreateStudioOperationsOptions = {},\n): StudioOperations {\n const authorized = options.actor\n ? { actor: options.actor, authorize: createRoleAuthorization(adapter.members) }\n : {}\n const operations = createOperations({ adapter, ...authorized })\n // EC-277: when the adapter maintains the index in its own write path (AD-6 \"at the\n // source\" — the Convex provider does this server-side, so a raw `convex run` is\n // caught too), the client-side subscriber would only double the work. Attach it\n // ONLY for providers that don't self-maintain. Where it does run, extraction is a\n // schema-free, manifest-free walk over self-describing content, so it needs no\n // registry (compositions self-typed their relation/asset props on write).\n const references = adapter.maintainsReferenceIndex\n ? noopReferenceIndexAttachment()\n : attachReferenceIndex(operations.events, adapter)\n const changesets = createChangesets({ adapter, events: operations.events, ...authorized })\n // EC-146 instant publish: when a host revalidate endpoint is configured via\n // env, every successful publish-shaped command (document upsert/delete/\n // setState, graph publish/unpublish) fires a signed revalidation webhook.\n // No env (dev/tests) → no-op.\n attachConfiguredRevalidationWebhooks(operations.events)\n return { operations, changesets, adapter, references }\n}\n\n// One adapter + one operations bundle per backend (EC-179): keyed by the active\n// deployment so switching to a project on another Convex deployment selects (or\n// lazily builds) that backend's client, rather than reusing the first one.\nconst adaptersByKey = new Map<string, Promise<PersistenceAdapter>>()\nconst instancesByKey = new Map<string, Promise<StudioOperations>>()\nlet currentActor: Principal | null = null\n\n/**\n * The active backend key, tolerant of an unconfigured env: the real app never\n * reaches `getStudioOperations` while misconfigured (the `DeploymentSetupGate` renders a\n * boot error first), but tests inject a bundle directly via the seam below — so\n * a missing backend resolves to one stable key rather than throwing.\n */\nfunction deploymentKey(): string {\n try {\n return activeDeploymentKey()\n } catch {\n return '__unconfigured__'\n }\n}\n\nfunction getAdapter(key: string): Promise<PersistenceAdapter> {\n let adapter = adaptersByKey.get(key)\n if (!adapter) {\n adapter = selectPersistenceAdapter()\n adaptersByKey.set(key, adapter)\n }\n return adapter\n}\n\n/**\n * The shared studio operations client for the active backend (lazily\n * bootstrapped, cached per deployment). In-memory mode this owns the one seeded\n * adapter the whole session mutates; against Convex it owns one client per\n * deployment — the active project (EC-179) selects which.\n */\nexport function getStudioOperations(): Promise<StudioOperations> {\n const key = deploymentKey()\n let instance = instancesByKey.get(key)\n if (!instance) {\n const actor = currentActor\n instance = getAdapter(key).then((adapter) =>\n createStudioOperations(adapter, actor ? { actor } : {}),\n )\n instancesByKey.set(key, instance)\n }\n return instance\n}\n\n/**\n * Bind (or clear) the session principal (EC-150). Called by the auth context\n * on sign-in/sign-out. Rebuilds the operations clients over the *same* adapters\n * — the persisted state (and, in-memory, the whole session's edits) survives;\n * only the authorization identity changes. All cached backends are rebuilt so a\n * later switch picks up the new actor too.\n */\nexport function setStudioSession(actor: Principal | null): void {\n if (currentActor?.id === actor?.id) return // same user (or both null) — keep the clients\n currentActor = actor\n instancesByKey.clear()\n}\n\n/** Test seam: replace (or clear) the singleton for the active backend. */\nexport function setStudioOperationsForTests(next: StudioOperations | null): void {\n if (next) {\n instancesByKey.set(deploymentKey(), Promise.resolve(next))\n return\n }\n instancesByKey.clear()\n adaptersByKey.clear()\n currentActor = null\n}\n"]}
@@ -8,7 +8,7 @@
8
8
  * local + ephemeral). The flag wins over a configured URL — explicit beats
9
9
  * implicit — so a checked-out `.env.local` can be flipped without deleting it.
10
10
  * - Neither → **misconfigured**: the studio renders a deterministic boot-error
11
- * screen (see `BackendGate`) telling the developer exactly what to set.
11
+ * screen (see `DeploymentSetupGate`) telling the developer exactly what to set.
12
12
  * Likewise, a Convex backend that is unreachable at runtime is a visible
13
13
  * error state — the studio never silently swaps in in-memory storage.
14
14
  */
@@ -8,7 +8,7 @@
8
8
  * local + ephemeral). The flag wins over a configured URL — explicit beats
9
9
  * implicit — so a checked-out `.env.local` can be flipped without deleting it.
10
10
  * - Neither → **misconfigured**: the studio renders a deterministic boot-error
11
- * screen (see `BackendGate`) telling the developer exactly what to set.
11
+ * screen (see `DeploymentSetupGate`) telling the developer exactly what to set.
12
12
  * Likewise, a Convex backend that is unreachable at runtime is a visible
13
13
  * error state — the studio never silently swaps in in-memory storage.
14
14
  */
@@ -1 +1 @@
1
- {"version":3,"file":"backend-mode.js","sourceRoot":"","sources":["../../../src/lib/persistence/backend-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,CAAC,MAAM,YAAY,GAAG,kBAAkB,CAAA;AAC9C,MAAM,CAAC,MAAM,eAAe,GAAG,YAAY,CAAA;AAC3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,iBAAiB,CAAA;AAYnD,SAAS,OAAO;IACd,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,EAAE,CAAA;IACjD,OAAQ,MAAM,CAAC,IAA4B,CAAC,GAAG,IAAI,EAAE,CAAA;AACvD,CAAC;AAED,SAAS,OAA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AAK,EAAE,QAAQ,EAAE,CAAA;AAC5B,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,oBAAoB;IAClC,OAAO,mBAAmB,EAAE,KAAK,IAAI,CAAA;AACvC,CAAC","sourcesContent":["/**\n * Studio backend mode resolution (EC-153). Convex is the **default and primary**\n * persistence backend; the deterministic in-memory adapter is demoted to an\n * explicit, labeled **playground** mode and is never an automatic fallback:\n *\n * - `VITE_CONVEX_URL` set → Convex mode (the production/dev default).\n * - `VITE_ELYTRA_MODE=playground` → playground mode (seeded in-memory adapter,\n * local + ephemeral). The flag wins over a configured URL — explicit beats\n * implicit — so a checked-out `.env.local` can be flipped without deleting it.\n * - Neither → **misconfigured**: the studio renders a deterministic boot-error\n * screen (see `BackendGate`) telling the developer exactly what to set.\n * Likewise, a Convex backend that is unreachable at runtime is a visible\n * error state — the studio never silently swaps in in-memory storage.\n */\n\nexport const MODE_ENV_VAR = 'VITE_ELYTRA_MODE'\nexport const PLAYGROUND_MODE = 'playground'\nexport const CONVEX_URL_ENV_VAR = 'VITE_CONVEX_URL'\n\nexport type StudioBackendMode = 'convex' | 'playground'\n\nexport type StudioBackendConfig =\n | { kind: 'convex'; url: string }\n | { kind: 'playground' }\n | { kind: 'misconfigured'; reason: 'missing-convex-url' | 'unknown-mode'; detail: string }\n\n/** The studio's env surface: Vite client env first, Node/SSR env second. */\nexport type EnvRecord = Record<string, string | undefined>\n\nfunction viteEnv(): EnvRecord {\n if (typeof import.meta === 'undefined') return {}\n return (import.meta as { env?: EnvRecord }).env ?? {}\n}\n\nfunction nodeEnv(): EnvRecord {\n return typeof process !== 'undefined' ? (process.env ?? {}) : {}\n}\n\nfunction readEnv(env: EnvRecord, key: string): string | undefined {\n const value = env[key]\n return value && value.trim() !== '' ? value.trim() : undefined\n}\n\nlet envOverride: EnvRecord | null = null\n\n/**\n * Test seam: pin the env the selectors see. `vi.stubEnv` cannot reach the\n * `import.meta.env` snapshot Vitest hands this module, so suites that exercise\n * `selectPersistenceAdapter`/`selectAuthAdapter` against specific configurations\n * use this instead — keeping results independent of any developer `.env.local`.\n */\nexport function setStudioEnvOverrideForTests(env: EnvRecord | null): void {\n envOverride = env\n}\n\n/** Resolve the configured studio env (Vite client env wins over process.env). */\nexport function studioEnv(): EnvRecord {\n return envOverride ?? { ...nodeEnv(), ...viteEnv() }\n}\n\n/**\n * Pure mode decision — testable with a plain env record. The app calls it with\n * {@link studioEnv}; `CONVEX_URL` (Node-side alias) is honored for SSR/tools.\n */\nexport function resolveBackendConfig(env: EnvRecord = studioEnv()): StudioBackendConfig {\n const mode = readEnv(env, MODE_ENV_VAR)\n if (mode === PLAYGROUND_MODE) return { kind: 'playground' }\n if (mode !== undefined) {\n return {\n kind: 'misconfigured',\n reason: 'unknown-mode',\n detail: `${MODE_ENV_VAR}=\"${mode}\" is not a known mode. The only supported value is \"${PLAYGROUND_MODE}\"; unset it to run against Convex.`,\n }\n }\n const url = readEnv(env, CONVEX_URL_ENV_VAR) ?? readEnv(env, 'CONVEX_URL')\n if (url) return { kind: 'convex', url }\n return {\n kind: 'misconfigured',\n reason: 'missing-convex-url',\n detail: `No persistence backend is configured. Set ${CONVEX_URL_ENV_VAR} to your Convex deployment URL (see docs/backend-setup.md), or opt into the ephemeral local playground with ${MODE_ENV_VAR}=${PLAYGROUND_MODE}.`,\n }\n}\n\n/** True when the studio runs in the explicit, labeled playground mode. */\nexport function isPlaygroundMode(): boolean {\n return resolveBackendConfig().kind === 'playground'\n}\n\n// ---------------------------------------------------------------------------\n// Dev auto-login (unattended testing — NOT an auth bypass)\n// ---------------------------------------------------------------------------\n\n/** `email:password` for unattended dev sign-in (gitignored `.env.local`). */\nexport const DEV_LOGIN_ENV_VAR = 'VITE_ELYTRA_DEV_LOGIN'\n\n/** Parsed dev auto-login credentials. */\nexport interface DevAutoLoginCredentials {\n email: string\n password: string\n}\n\n/**\n * Is this a Vite *dev* build? `import.meta.env.DEV` is statically `true` under\n * `vite dev` and statically `false` in any production build — so gating dev\n * auto-login on it means the whole feature **dead-code-eliminates** out of a\n * production bundle, even if `VITE_ELYTRA_DEV_LOGIN` were somehow present.\n */\nfunction isViteDevBuild(): boolean {\n if (typeof import.meta === 'undefined') return false\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n}\n\n/**\n * Dev-only unattended auth — **not a bypass**. When `VITE_ELYTRA_DEV_LOGIN=\n * email:password` is set in a dev build, the studio auto-signs-in with those\n * credentials on load (see {@link DevAutoLoginAdapter}) so local/automated\n * testing skips the sign-in screen while still establishing a REAL backend\n * session: Convex's server-side `requireRole` guards still apply, so the dev\n * user must exist and be a member. Returns null in production builds (gated by\n * {@link isViteDevBuild}) and when unset/malformed, so it can never weaken a\n * deployed app. `isDevBuild` is a parameter purely so the decision is unit\n * testable (`import.meta.env.DEV` is not reachable via `vi.stubEnv`).\n *\n * `password` may itself contain `:` — only the first colon separates the fields.\n */\nexport function resolveDevAutoLogin(\n env: EnvRecord = studioEnv(),\n isDevBuild: boolean = isViteDevBuild(),\n): DevAutoLoginCredentials | null {\n if (!isDevBuild) return null\n const raw = readEnv(env, DEV_LOGIN_ENV_VAR)\n if (!raw) return null\n const separator = raw.indexOf(':')\n if (separator <= 0) return null\n const email = raw.slice(0, separator).trim()\n const password = raw.slice(separator + 1)\n if (!email || !password) return null\n return { email, password }\n}\n\n/** True when dev auto-login is configured (dev build only) — for the UI marker. */\nexport function isDevAutoLoginActive(): boolean {\n return resolveDevAutoLogin() !== null\n}\n"]}
1
+ {"version":3,"file":"backend-mode.js","sourceRoot":"","sources":["../../../src/lib/persistence/backend-mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,MAAM,CAAC,MAAM,YAAY,GAAG,kBAAkB,CAAA;AAC9C,MAAM,CAAC,MAAM,eAAe,GAAG,YAAY,CAAA;AAC3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,iBAAiB,CAAA;AAYnD,SAAS,OAAO;IACd,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,W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,SAAS,GAAG,CAAC,CAAC,CAAA;IACzC,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAA;IACpC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAA;AAC5B,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,oBAAoB;IAClC,OAAO,mBAAmB,EAAE,KAAK,IAAI,CAAA;AACvC,CAAC","sourcesContent":["/**\n * Studio backend mode resolution (EC-153). Convex is the **default and primary**\n * persistence backend; the deterministic in-memory adapter is demoted to an\n * explicit, labeled **playground** mode and is never an automatic fallback:\n *\n * - `VITE_CONVEX_URL` set → Convex mode (the production/dev default).\n * - `VITE_ELYTRA_MODE=playground` → playground mode (seeded in-memory adapter,\n * local + ephemeral). The flag wins over a configured URL — explicit beats\n * implicit — so a checked-out `.env.local` can be flipped without deleting it.\n * - Neither → **misconfigured**: the studio renders a deterministic boot-error\n * screen (see `DeploymentSetupGate`) telling the developer exactly what to set.\n * Likewise, a Convex backend that is unreachable at runtime is a visible\n * error state — the studio never silently swaps in in-memory storage.\n */\n\nexport const MODE_ENV_VAR = 'VITE_ELYTRA_MODE'\nexport const PLAYGROUND_MODE = 'playground'\nexport const CONVEX_URL_ENV_VAR = 'VITE_CONVEX_URL'\n\nexport type StudioBackendMode = 'convex' | 'playground'\n\nexport type StudioBackendConfig =\n | { kind: 'convex'; url: string }\n | { kind: 'playground' }\n | { kind: 'misconfigured'; reason: 'missing-convex-url' | 'unknown-mode'; detail: string }\n\n/** The studio's env surface: Vite client env first, Node/SSR env second. */\nexport type EnvRecord = Record<string, string | undefined>\n\nfunction viteEnv(): EnvRecord {\n if (typeof import.meta === 'undefined') return {}\n return (import.meta as { env?: EnvRecord }).env ?? {}\n}\n\nfunction nodeEnv(): EnvRecord {\n return typeof process !== 'undefined' ? (process.env ?? {}) : {}\n}\n\nfunction readEnv(env: EnvRecord, key: string): string | undefined {\n const value = env[key]\n return value && value.trim() !== '' ? value.trim() : undefined\n}\n\nlet envOverride: EnvRecord | null = null\n\n/**\n * Test seam: pin the env the selectors see. `vi.stubEnv` cannot reach the\n * `import.meta.env` snapshot Vitest hands this module, so suites that exercise\n * `selectPersistenceAdapter`/`selectAuthAdapter` against specific configurations\n * use this instead — keeping results independent of any developer `.env.local`.\n */\nexport function setStudioEnvOverrideForTests(env: EnvRecord | null): void {\n envOverride = env\n}\n\n/** Resolve the configured studio env (Vite client env wins over process.env). */\nexport function studioEnv(): EnvRecord {\n return envOverride ?? { ...nodeEnv(), ...viteEnv() }\n}\n\n/**\n * Pure mode decision — testable with a plain env record. The app calls it with\n * {@link studioEnv}; `CONVEX_URL` (Node-side alias) is honored for SSR/tools.\n */\nexport function resolveBackendConfig(env: EnvRecord = studioEnv()): StudioBackendConfig {\n const mode = readEnv(env, MODE_ENV_VAR)\n if (mode === PLAYGROUND_MODE) return { kind: 'playground' }\n if (mode !== undefined) {\n return {\n kind: 'misconfigured',\n reason: 'unknown-mode',\n detail: `${MODE_ENV_VAR}=\"${mode}\" is not a known mode. The only supported value is \"${PLAYGROUND_MODE}\"; unset it to run against Convex.`,\n }\n }\n const url = readEnv(env, CONVEX_URL_ENV_VAR) ?? readEnv(env, 'CONVEX_URL')\n if (url) return { kind: 'convex', url }\n return {\n kind: 'misconfigured',\n reason: 'missing-convex-url',\n detail: `No persistence backend is configured. Set ${CONVEX_URL_ENV_VAR} to your Convex deployment URL (see docs/backend-setup.md), or opt into the ephemeral local playground with ${MODE_ENV_VAR}=${PLAYGROUND_MODE}.`,\n }\n}\n\n/** True when the studio runs in the explicit, labeled playground mode. */\nexport function isPlaygroundMode(): boolean {\n return resolveBackendConfig().kind === 'playground'\n}\n\n// ---------------------------------------------------------------------------\n// Dev auto-login (unattended testing — NOT an auth bypass)\n// ---------------------------------------------------------------------------\n\n/** `email:password` for unattended dev sign-in (gitignored `.env.local`). */\nexport const DEV_LOGIN_ENV_VAR = 'VITE_ELYTRA_DEV_LOGIN'\n\n/** Parsed dev auto-login credentials. */\nexport interface DevAutoLoginCredentials {\n email: string\n password: string\n}\n\n/**\n * Is this a Vite *dev* build? `import.meta.env.DEV` is statically `true` under\n * `vite dev` and statically `false` in any production build — so gating dev\n * auto-login on it means the whole feature **dead-code-eliminates** out of a\n * production bundle, even if `VITE_ELYTRA_DEV_LOGIN` were somehow present.\n */\nfunction isViteDevBuild(): boolean {\n if (typeof import.meta === 'undefined') return false\n return (import.meta as { env?: { DEV?: boolean } }).env?.DEV === true\n}\n\n/**\n * Dev-only unattended auth — **not a bypass**. When `VITE_ELYTRA_DEV_LOGIN=\n * email:password` is set in a dev build, the studio auto-signs-in with those\n * credentials on load (see {@link DevAutoLoginAdapter}) so local/automated\n * testing skips the sign-in screen while still establishing a REAL backend\n * session: Convex's server-side `requireRole` guards still apply, so the dev\n * user must exist and be a member. Returns null in production builds (gated by\n * {@link isViteDevBuild}) and when unset/malformed, so it can never weaken a\n * deployed app. `isDevBuild` is a parameter purely so the decision is unit\n * testable (`import.meta.env.DEV` is not reachable via `vi.stubEnv`).\n *\n * `password` may itself contain `:` — only the first colon separates the fields.\n */\nexport function resolveDevAutoLogin(\n env: EnvRecord = studioEnv(),\n isDevBuild: boolean = isViteDevBuild(),\n): DevAutoLoginCredentials | null {\n if (!isDevBuild) return null\n const raw = readEnv(env, DEV_LOGIN_ENV_VAR)\n if (!raw) return null\n const separator = raw.indexOf(':')\n if (separator <= 0) return null\n const email = raw.slice(0, separator).trim()\n const password = raw.slice(separator + 1)\n if (!email || !password) return null\n return { email, password }\n}\n\n/** True when dev auto-login is configured (dev build only) — for the UI marker. */\nexport function isDevAutoLoginActive(): boolean {\n return resolveDevAutoLogin() !== null\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { ConvexHttpClient } from 'convex/browser';
2
2
  import type { CollectionDef } from '@elytracms/core/cms-core';
3
- import type { AssetRepository, BackendStatus, BackendValidationInput, BackendValidationResult, BlobStorageAdapter, CliTokenRepository, CmsRepository, DeliveryRepository, MembersRepository, PersistenceAdapter, ReferenceIndexRepository, RedirectRepository, UserRepository } from '@elytracms/core/persistence';
3
+ import type { AssetRepository, BackendStatus, BackendValidationInput, BackendValidationResult, BlobStorageAdapter, CliTokenRepository, CmsRepository, DeliveryRepository, MembersRepository, PersistenceAdapter, ReferenceIndexRepository, RedirectRepository, UserRepository, InviteRepository } from '@elytracms/core/persistence';
4
4
  /**
5
5
  * Convex-backed {@link PersistenceAdapter} (brief §10, EC-039). Every repository
6
6
  * is implemented against the Convex functions in `apps/builder/convex/*`, mapping
@@ -14,6 +14,7 @@ export declare class ConvexPersistenceAdapter implements PersistenceAdapter {
14
14
  readonly references: ReferenceIndexRepository;
15
15
  /** Per-project membership roles (EC-150). */
16
16
  readonly members: MembersRepository;
17
+ readonly invites: InviteRepository;
17
18
  /** Studio users rail — role + custom fields joined to auth identity (EC-240). */
18
19
  readonly users: UserRepository;
19
20
  /** Editorial redirects rail — data-backed 301/302 forwards (EC-303). */
@@ -1,5 +1,6 @@
1
1
  import { documentKey, documentSchema } from '@elytracms/core/cms-core';
2
2
  import { RecordNotFoundError, PersistenceValidationError, compareReferenceEntries, highestRole, isKnownRole, validateForPersistence, } from '@elytracms/core/persistence';
3
+ import { normalizeInviteEmail } from '@elytracms/core/persistence';
3
4
  import { queryRef, mutationRef } from './convex-client';
4
5
  import { ConvexBlobStorage } from './convex-blob-storage';
5
6
  const realClock = () => new Date().toISOString();
@@ -504,6 +505,14 @@ class ConvexUserRepository {
504
505
  throw new RecordNotFoundError('user', `${projectId}/${id}`);
505
506
  return found;
506
507
  }
508
+ async getSelf(projectId) {
509
+ // Self-permitted (EC-240 H-tail item 1): `users:getSelf` derives the caller
510
+ // from the JWT server-side and returns ONLY their own join — never widened to
511
+ // the admin-only `users:get`. The `selfId` the contract passes is ignored here;
512
+ // the trust boundary is the server.
513
+ const doc = (await this.client.query(queryRef('users:getSelf'), {}));
514
+ return doc ? userRecordFromDoc(doc, projectId) : null;
515
+ }
507
516
  async saveUser(projectId, input) {
508
517
  const now = this.clock();
509
518
  await this.client.mutation(mutationRef('members:set'), {
@@ -529,6 +538,63 @@ class ConvexUserRepository {
529
538
  }
530
539
  }
531
540
  }
541
+ function inviteRecordFromDoc(doc) {
542
+ return {
543
+ email: doc.email,
544
+ role: doc.role,
545
+ ...(doc.invitedBy !== undefined ? { invitedBy: doc.invitedBy } : {}),
546
+ createdAt: doc.createdAt,
547
+ updatedAt: doc.updatedAt,
548
+ };
549
+ }
550
+ /**
551
+ * Convex-backed {@link InviteRepository} (EC-324). Admin-gated `invites:*`
552
+ * handlers; the repo supplies timestamps (mirroring `ConvexUserRepository`). The
553
+ * Convex auth boundary reads the same table in `beforeSessionCreation` to gate
554
+ * open sign-up + grant the invited role.
555
+ */
556
+ class ConvexInviteRepository {
557
+ client;
558
+ clock;
559
+ constructor(client, clock = realClock) {
560
+ this.client = client;
561
+ this.clock = clock;
562
+ }
563
+ async listInvites(_projectId) {
564
+ const docs = (await this.client.query(queryRef('invites:list'), {}));
565
+ return docs.map(inviteRecordFromDoc);
566
+ }
567
+ async findInvite(projectId, email) {
568
+ const key = normalizeInviteEmail(email);
569
+ const all = await this.listInvites(projectId);
570
+ return all.find((invite) => invite.email === key);
571
+ }
572
+ async saveInvite(_projectId, input) {
573
+ const now = this.clock();
574
+ const doc = (await this.client.mutation(mutationRef('invites:create'), {
575
+ email: normalizeInviteEmail(input.email),
576
+ role: input.role,
577
+ ...(input.invitedBy !== undefined ? { invitedBy: input.invitedBy } : {}),
578
+ createdAt: now,
579
+ updatedAt: now,
580
+ }));
581
+ return inviteRecordFromDoc(doc);
582
+ }
583
+ async removeInvite(projectId, email) {
584
+ try {
585
+ await this.client.mutation(mutationRef('invites:revoke'), {
586
+ email: normalizeInviteEmail(email),
587
+ });
588
+ }
589
+ catch (error) {
590
+ const message = error instanceof Error ? error.message : String(error);
591
+ if (/not-found/i.test(message)) {
592
+ throw new RecordNotFoundError('invite', `${projectId}/${normalizeInviteEmail(email)}`);
593
+ }
594
+ throw error;
595
+ }
596
+ }
597
+ }
532
598
  function cliTokenRecordFromDoc(doc) {
533
599
  return {
534
600
  id: doc.tokenId,
@@ -676,6 +742,7 @@ export class ConvexPersistenceAdapter {
676
742
  references;
677
743
  /** Per-project membership roles (EC-150). */
678
744
  members;
745
+ invites;
679
746
  /** Studio users rail — role + custom fields joined to auth identity (EC-240). */
680
747
  users;
681
748
  /** Editorial redirects rail — data-backed 301/302 forwards (EC-303). */
@@ -708,6 +775,7 @@ export class ConvexPersistenceAdapter {
708
775
  this.references = new ConvexReferenceIndexRepository(client);
709
776
  this.members = new ConvexMembersRepository(client, projectId);
710
777
  this.users = new ConvexUserRepository(client);
778
+ this.invites = new ConvexInviteRepository(client);
711
779
  this.redirects = new ConvexRedirectRepository(client);
712
780
  this.cliTokens = new ConvexCliTokenRepository(client);
713
781
  this.blobs = new ConvexBlobStorage(client);
@@ -729,7 +797,7 @@ export class ConvexPersistenceAdapter {
729
797
  // deployment answered and enforced auth. Now that `members:mine` is
730
798
  // soft-guarded this branch is a defensive fallback (a protected probe could
731
799
  // still throw); only transport/server failures count as unavailable, so the
732
- // BackendGate surfaces those visibly instead of falling back to in-memory.
800
+ // DeploymentSetupGate surfaces those visibly instead of falling back to in-memory.
733
801
  if (/unauthorized/i.test(detail))
734
802
  return { backend: 'convex', available: true };
735
803
  return { backend: 'convex', available: false, detail };
@@ -1 +1 @@
1
- {"version":3,"file":"convex-adapter.js","sourceRoot":"","sources":["../../../src/lib/persistence/convex-adapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAEtE,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,EACvB,WAAW,EACX,WAAW,EACX,sBAAsB,GACvB,MAAM,6BAA6B,CAAA;AAwCpC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAA;AAIzD,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AAiB,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,wBAAwB,CAAC,MAAM,CAAC,CAAA;IACtD,CAAC;IAED,KAAK,CAAC,MAAM;QACV,IAAI,CAAC;YACH,+EAA+E;YAC/E,uEAAuE;YACvE,6EAA6E;YAC7E,0EAA0E;YAC1E,sCAAsC;YACtC,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,CAAA;YACrD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACrE,mEAAmE;YACnE,oEAAoE;YACpE,4EAA4E;YAC5E,4EAA4E;YAC5E,2EAA2E;YAC3E,IAAI,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC;gBAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;YAC/E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,CAAA;QACxD,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,KAA6B;QACpC,OAAO,sBAAsB,CAAC,KAAK,CAAC,CAAA;IACtC,CAAC;CACF","sourcesContent":["import type { ConvexHttpClient } from 'convex/browser'\nimport { documentKey, documentSchema } from '@elytracms/core/cms-core'\nimport type { CmsDocument, CollectionDef, DocumentRef } from '@elytracms/core/cms-core'\nimport {\n RecordNotFoundError,\n PersistenceValidationError,\n compareReferenceEntries,\n highestRole,\n isKnownRole,\n validateForPersistence,\n} from '@elytracms/core/persistence'\nimport type {\n AssetRecord,\n AssetRepository,\n BackendStatus,\n BackendValidationInput,\n BackendValidationResult,\n BlobStorageAdapter,\n CliTokenRecord,\n CliTokenRepository,\n CmsRepository,\n DeliveryConfigStatus,\n DeliveryRepository,\n CmsSchemaRecord,\n CmsDocumentRecord,\n DocumentVersionRecord,\n SaveDocumentVersionOptions,\n MembersRepository,\n NewAssetInput,\n NewCliTokenInput,\n PersistenceAdapter,\n OutboundReference,\n ProjectMemberRecord,\n ProjectRole,\n ReferenceEntry,\n ReferenceEntryRecord,\n ReferenceIndexBuildMarker,\n ReferenceIndexRepository,\n ReferenceLookupOptions,\n ReferenceSource,\n ReferenceSourceType,\n ReferenceTarget,\n ReferenceVariant,\n RedirectEntry,\n RedirectRepository,\n SaveRedirectInput,\n SaveUserInput,\n UserRecord,\n UserRepository,\n} from '@elytracms/core/persistence'\nimport { queryRef, mutationRef } from './convex-client'\nimport { ConvexBlobStorage } from './convex-blob-storage'\n\n/** Wall-clock for runtime writes (deterministic seeds use a fixed clock instead). */\ntype Clock = () => string\nconst realClock: Clock = () => new Date().toISOString()\n\nfunction newId(prefix: string): string {\n const rand =\n typeof globalThis.crypto?.randomUUID === 'function'\n ? globalThis.crypto.randomUUID()\n : Math.abs(Date.parse(new Date().toISOString())).toString(36)\n return `${prefix}_${rand}`\n}\n\n// --- CMS, Assets ----------------------------------------------------------\n\n/**\n * Deterministic, config-owned schema timestamps (EC-183). CMS collections live\n * in `elytra.config.ts`, not the backend, so the synthesized `CmsSchemaRecord`\n * carries a stable placeholder rather than DB-row timestamps.\n */\nconst CONFIG_SCHEMA_TIMESTAMP = '2026-01-01T00:00:00.000Z'\n\ninterface DocumentDoc {\n projectId: string\n document: CmsDocument\n publishedVersion?: number\n createdAt: string\n updatedAt: string\n}\nfunction docRecordFromDoc(doc: DocumentDoc): CmsDocumentRecord {\n return {\n projectId: doc.projectId,\n document: doc.document,\n ...(doc.publishedVersion !== undefined ? { publishedVersion: doc.publishedVersion } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\ninterface VersionDoc {\n collection: string\n docId: string\n version: number\n snapshot: CmsDocument\n label?: string\n origin?: string\n createdAt: string\n}\n/** The backend row carries no `projectId` (single-tenant); stamp it from the call. */\nfunction versionRecordFromDoc(doc: VersionDoc, projectId: string): DocumentVersionRecord {\n return {\n projectId,\n collection: doc.collection,\n docId: doc.docId,\n version: doc.version,\n snapshot: doc.snapshot,\n createdAt: doc.createdAt,\n ...(doc.label ? { label: doc.label } : {}),\n ...(doc.origin ? { origin: doc.origin } : {}),\n }\n}\n\nclass ConvexCmsRepository implements CmsRepository {\n /**\n * @param collections the active project's config-owned CMS collections\n * (EC-183, AD-11), injected from `elytra.config.ts`. The Convex backend has\n * no `cmsSchemas` table — `findSchema`/`getSchema` serve these instead.\n */\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly collections: readonly CollectionDef[] = [],\n private readonly clock: Clock = realClock,\n ) {}\n\n async saveSchema(\n _projectId: string,\n _collections: readonly CollectionDef[],\n ): Promise<CmsSchemaRecord> {\n // Read-only (EC-183, AD-11): the CMS collection schema is owned by\n // `elytra.config.ts`; the backend stores documents only. A write here is a\n // visible, structured error rather than a silent no-op (the studio's CMS\n // schema surfaces are read-only; legitimate writers were removed in EC-183).\n throw new PersistenceValidationError(\n 'CMS collection schema is owned by elytra.config.ts and cannot be written to the backend.',\n [\n {\n code: 'schema-config-owned',\n message:\n 'Edit elytra.config.ts to change collections; the backend stores documents only.',\n path: [],\n domain: 'cms',\n },\n ],\n )\n }\n\n /** Config-owned schema (EC-183): the active project's collections from config. */\n private configSchema(projectId: string): CmsSchemaRecord {\n return {\n projectId,\n collections: [...this.collections],\n createdAt: CONFIG_SCHEMA_TIMESTAMP,\n updatedAt: CONFIG_SCHEMA_TIMESTAMP,\n }\n }\n\n async getSchema(projectId: string): Promise<CmsSchemaRecord> {\n return this.configSchema(projectId)\n }\n\n async findSchema(projectId: string): Promise<CmsSchemaRecord | undefined> {\n return this.configSchema(projectId)\n }\n\n async upsertDocument(projectId: string, document: CmsDocument): Promise<CmsDocumentRecord> {\n // The backend is a pure document store (EC-183, AD-11): collection-membership\n // validation lives in `@elytracms/core/cms-core` `validateDocument`, which the studio\n // runs pre-dispatch (cell edits, imports). We still parse the canonical\n // document shape so malformed blobs never reach storage.\n const parsedDoc = documentSchema.parse(document)\n const now = this.clock()\n const doc = (await this.client.mutation(mutationRef('cms:upsertDocument'), {\n collection: parsedDoc.collection,\n docId: parsedDoc.id,\n document: parsedDoc,\n createdAt: now,\n updatedAt: now,\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n\n async getDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord> {\n const found = await this.findDocument(projectId, ref)\n if (!found)\n throw new RecordNotFoundError('cms-document', `${projectId}/${ref.collection}:${ref.id}`)\n return found\n }\n\n async findDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord | undefined> {\n const doc = (await this.client.query(queryRef('cms:getDocument'), {\n collection: ref.collection,\n docId: ref.id,\n })) as DocumentDoc | null\n return doc ? docRecordFromDoc(doc) : undefined\n }\n\n async listDocuments(projectId: string, collection?: string): Promise<CmsDocumentRecord[]> {\n const docs = (await this.client.query(queryRef('cms:listDocuments'), {\n ...(collection ? { collection } : {}),\n })) as DocumentDoc[]\n // EC-153 parity: deterministic document-key ordering (Convex index order\n // within a project is insertion order, so we sort client-side).\n return docs\n .map(docRecordFromDoc)\n .sort((a, b) => (documentKey(a.document) < documentKey(b.document) ? -1 : 1))\n }\n\n async listPublishedDocuments(projectId: string, collection?: string): Promise<CmsDocument[]> {\n // EC-307: one bulk read for the published pool (collapses the per-document\n // `listVersions` fan-out). The handler resolves each pin to its snapshot.\n const snapshots = (await this.client.query(queryRef('cms:listPublishedDocuments'), {\n ...(collection ? { collection } : {}),\n })) as CmsDocument[]\n // Deterministic document-key order (parity with the in-memory adapter).\n return snapshots\n .map((doc) => documentSchema.parse(doc))\n .sort((a, b) => (documentKey(a) < documentKey(b) ? -1 : 1))\n }\n\n async deleteDocument(projectId: string, ref: DocumentRef): Promise<void> {\n // EC-153 parity: deleting a missing document is not-found, never a no-op.\n await this.getDocument(projectId, ref)\n await this.client.mutation(mutationRef('cms:deleteDocument'), {\n collection: ref.collection,\n docId: ref.id,\n })\n }\n\n async saveDocumentVersion(\n projectId: string,\n snapshot: CmsDocument,\n options: SaveDocumentVersionOptions = {},\n ): Promise<DocumentVersionRecord> {\n const parsed = documentSchema.parse(snapshot)\n const doc = (await this.client.mutation(mutationRef('cms:saveDocumentVersion'), {\n collection: parsed.collection,\n docId: parsed.id,\n snapshot: parsed,\n createdAt: this.clock(),\n ...(options.label ? { label: options.label } : {}),\n ...(options.origin ? { origin: options.origin } : {}),\n })) as VersionDoc\n return versionRecordFromDoc(doc, projectId)\n }\n\n async listDocumentVersions(\n projectId: string,\n ref: DocumentRef,\n ): Promise<DocumentVersionRecord[]> {\n const docs = (await this.client.query(queryRef('cms:listDocumentVersions'), {\n collection: ref.collection,\n docId: ref.id,\n })) as VersionDoc[]\n return docs.map((doc) => versionRecordFromDoc(doc, projectId))\n }\n\n async listAllDocumentVersions(projectId: string): Promise<DocumentVersionRecord[]> {\n const docs = (await this.client.query(\n queryRef('cms:listAllDocumentVersions'),\n {},\n )) as VersionDoc[]\n return docs.map((doc) => versionRecordFromDoc(doc, projectId))\n }\n\n async getDocumentVersion(\n projectId: string,\n ref: DocumentRef,\n version: number,\n ): Promise<DocumentVersionRecord> {\n const doc = (await this.client.query(queryRef('cms:getDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n })) as VersionDoc | null\n if (!doc) {\n throw new RecordNotFoundError(\n 'cms-document-version',\n `${projectId}/${ref.collection}:${ref.id}#${version}`,\n )\n }\n return versionRecordFromDoc(doc, projectId)\n }\n\n async publishDocumentVersion(\n projectId: string,\n ref: DocumentRef,\n version: number,\n ): Promise<CmsDocumentRecord> {\n // Taxonomy enforced adapter-side (the handler is lenient): the document and\n // the pinned version must both exist (each throws RecordNotFoundError).\n await this.getDocument(projectId, ref)\n await this.getDocumentVersion(projectId, ref, version)\n const doc = (await this.client.mutation(mutationRef('cms:publishDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n updatedAt: this.clock(),\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n\n async unpublishDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord> {\n const existing = await this.getDocument(projectId, ref)\n if (existing.publishedVersion === undefined) {\n throw new PersistenceValidationError('Document is not currently published.', [\n {\n code: 'invalid-transition',\n message: 'Cannot unpublish: the document has no published version.',\n domain: 'cms',\n },\n ])\n }\n const doc = (await this.client.mutation(mutationRef('cms:unpublishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n updatedAt: this.clock(),\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n}\n\ninterface AssetDoc {\n projectId: string\n assetId: string\n filename: string\n contentType: string\n byteSize: number\n width?: number\n height?: number\n alt?: string\n /** Editable display title (EC-152). */\n title?: string\n storageKey: string\n url?: string\n /** Normalized image focal point `{ x, y }` in 0–1 (EC-230). */\n focalPoint?: { x: number; y: number }\n /** Schema-driven asset metadata bag (EC-301). */\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\n/** Map a Convex asset doc onto the contract record (assetId → id, drop _id/_creationTime). */\nfunction assetRecordFromDoc(doc: AssetDoc): AssetRecord {\n return {\n id: doc.assetId,\n projectId: doc.projectId,\n filename: doc.filename,\n contentType: doc.contentType,\n byteSize: doc.byteSize,\n ...(doc.width !== undefined ? { width: doc.width } : {}),\n ...(doc.height !== undefined ? { height: doc.height } : {}),\n ...(doc.alt !== undefined ? { alt: doc.alt } : {}),\n ...(doc.title !== undefined ? { title: doc.title } : {}),\n ...(doc.url !== undefined ? { url: doc.url } : {}),\n ...(doc.focalPoint !== undefined ? { focalPoint: doc.focalPoint } : {}),\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n storageKey: doc.storageKey,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\nclass ConvexAssetRepository implements AssetRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async upsertAsset(projectId: string, input: NewAssetInput): Promise<AssetRecord> {\n const now = this.clock()\n const id = input.id ?? newId('asset')\n const doc = (await this.client.mutation(mutationRef('assets:upsert'), {\n assetId: id,\n filename: input.filename,\n contentType: input.contentType,\n byteSize: input.byteSize,\n ...(input.width !== undefined ? { width: input.width } : {}),\n ...(input.height !== undefined ? { height: input.height } : {}),\n ...(input.alt !== undefined ? { alt: input.alt } : {}),\n // EC-153 parity: `title` (EC-152 metadata) must persist, not silently drop.\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.url !== undefined ? { url: input.url } : {}),\n ...(input.focalPoint !== undefined ? { focalPoint: input.focalPoint } : {}),\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n storageKey: input.storageKey ?? `${projectId}/${id}`,\n createdAt: now,\n updatedAt: now,\n })) as AssetDoc\n return assetRecordFromDoc(doc)\n }\n\n async getAsset(projectId: string, id: string): Promise<AssetRecord> {\n const found = await this.findAsset(projectId, id)\n if (!found) throw new RecordNotFoundError('asset', `${projectId}/${id}`)\n return found\n }\n\n async findAsset(projectId: string, id: string): Promise<AssetRecord | undefined> {\n const doc = (await this.client.query(queryRef('assets:get'), {\n assetId: id,\n })) as AssetDoc | null\n return doc ? assetRecordFromDoc(doc) : undefined\n }\n\n async listAssets(projectId: string): Promise<AssetRecord[]> {\n const docs = (await this.client.query(queryRef('assets:list'), {})) as AssetDoc[]\n return docs.map(assetRecordFromDoc)\n }\n\n async removeAsset(projectId: string, id: string): Promise<void> {\n // EC-153 parity: removing an unknown asset is not-found, never a no-op.\n await this.getAsset(projectId, id)\n await this.client.mutation(mutationRef('assets:remove'), { assetId: id })\n }\n\n async resolveMany(projectId: string, ids: readonly string[]): Promise<Map<string, AssetRecord>> {\n const all = await this.listAssets(projectId)\n const out = new Map<string, AssetRecord>()\n for (const asset of all) if (ids.includes(asset.id)) out.set(asset.id, asset)\n return out\n }\n}\n\n// --- Reference index (EC-155) ------------------------------------------------\n\n/** A Convex reference-entry doc (flattened source/target for index-backed lookups). */\ninterface ReferenceEntryDoc {\n projectId: string\n variant: ReferenceVariant\n sourceType: ReferenceSourceType\n sourceId: string\n path: string\n targetType: ReferenceTarget['type']\n targetId: string\n kind: ReferenceEntryRecord['kind']\n}\n\nfunction referenceRecordFromDoc(doc: ReferenceEntryDoc): ReferenceEntryRecord {\n return {\n projectId: doc.projectId,\n variant: doc.variant,\n source: { type: doc.sourceType, id: doc.sourceId },\n path: doc.path,\n target: { type: doc.targetType, id: doc.targetId },\n kind: doc.kind,\n }\n}\n\n/** Deterministic ordering is a repository contract; Convex docs sort client-side. */\nfunction sortedReferenceRecords(docs: ReferenceEntryDoc[]): ReferenceEntryRecord[] {\n return docs.map(referenceRecordFromDoc).sort(compareReferenceEntries)\n}\n\nclass ConvexReferenceIndexRepository implements ReferenceIndexRepository {\n constructor(private readonly client: ConvexHttpClient) {}\n\n async replaceForSource(\n projectId: string,\n variant: ReferenceVariant,\n source: ReferenceSource,\n references: readonly OutboundReference[],\n ): Promise<ReferenceEntryRecord[]> {\n await this.client.mutation(mutationRef('references:replaceForSource'), {\n variant,\n sourceType: source.type,\n sourceId: source.id,\n references: references.map((r) => ({\n path: r.path,\n targetType: r.target.type,\n targetId: r.target.id,\n kind: r.kind,\n })),\n })\n return this.outbound(projectId, source, { variant })\n }\n\n async replaceForSourceTypes(\n projectId: string,\n variant: ReferenceVariant,\n sourceTypes: readonly ReferenceSourceType[],\n entries: readonly ReferenceEntry[],\n ): Promise<ReferenceEntryRecord[]> {\n await this.client.mutation(mutationRef('references:replaceForSourceTypes'), {\n variant,\n sourceTypes: [...sourceTypes],\n entries: entries.map((e) => ({\n sourceType: e.source.type,\n sourceId: e.source.id,\n path: e.path,\n targetType: e.target.type,\n targetId: e.target.id,\n kind: e.kind,\n })),\n })\n const all = await this.listEntries(projectId, variant)\n const types = new Set(sourceTypes)\n return all.filter((record) => types.has(record.source.type))\n }\n\n async removeForSource(\n projectId: string,\n source: ReferenceSource,\n variant?: ReferenceVariant,\n ): Promise<void> {\n await this.client.mutation(mutationRef('references:removeForSource'), {\n sourceType: source.type,\n sourceId: source.id,\n ...(variant ? { variant } : {}),\n })\n }\n\n async outbound(\n projectId: string,\n source: ReferenceSource,\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:outbound'), {\n sourceType: source.type,\n sourceId: source.id,\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async inbound(\n projectId: string,\n target: ReferenceTarget,\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:inbound'), {\n targetType: target.type,\n targetId: target.id,\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async inboundMany(\n projectId: string,\n targets: readonly ReferenceTarget[],\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[][]> {\n // EC-308: one round-trip for all targets (the handler loops the by_target\n // index server-side), replacing the client's per-target inbound fan-out.\n if (targets.length === 0) return []\n const groups = (await this.client.query(queryRef('references:inboundMany'), {\n targets: targets.map((target) => ({ targetType: target.type, targetId: target.id })),\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[][]\n return groups.map((docs) => sortedReferenceRecords(docs))\n }\n\n async listEntries(\n projectId: string,\n variant?: ReferenceVariant,\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:list'), {\n ...(variant ? { variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async getBuildMarker(projectId: string): Promise<ReferenceIndexBuildMarker | null> {\n return (await this.client.query(queryRef('references:buildMarker'), {})) as\n | ReferenceIndexBuildMarker\n | null\n }\n\n async setBuildMarker(projectId: string, marker: ReferenceIndexBuildMarker): Promise<void> {\n await this.client.mutation(mutationRef('references:setBuildMarker'), {\n entryCount: marker.entryCount,\n })\n }\n\n async clearProject(projectId: string): Promise<void> {\n await this.client.mutation(mutationRef('references:clearProject'), {})\n }\n}\n\n// --- Members + CLI tokens (EC-150) -------------------------------------------\n\ninterface MemberDoc {\n userId: string\n role: ProjectRole\n createdAt: string\n updatedAt: string\n}\n\n/**\n * Single-tenant (EC-179): membership is deployment-scoped, so the backend rows\n * carry no `projectId`. The contract record still does — this adapter is bound\n * to its deployment's project, so it stamps that slug onto every record.\n */\nfunction memberRecordFromDoc(doc: MemberDoc, projectId: string): ProjectMemberRecord {\n return {\n projectId,\n userId: doc.userId,\n role: doc.role,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\nclass ConvexMembersRepository implements MembersRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n /** The slug of this deployment's one project — stamped onto records. */\n private readonly boundProjectId: string,\n private readonly clock: Clock = realClock,\n ) {}\n\n async setMember(\n projectId: string,\n userId: string,\n role: ProjectRole,\n ): Promise<ProjectMemberRecord> {\n const now = this.clock()\n const doc = (await this.client.mutation(mutationRef('members:set'), {\n userId,\n role,\n createdAt: now,\n updatedAt: now,\n })) as MemberDoc\n return memberRecordFromDoc(doc, projectId)\n }\n\n async findMember(projectId: string, userId: string): Promise<ProjectMemberRecord | undefined> {\n const doc = (await this.client.query(queryRef('members:get'), {\n userId,\n })) as MemberDoc | null\n return doc ? memberRecordFromDoc(doc, projectId) : undefined\n }\n\n async listMembers(projectId: string): Promise<ProjectMemberRecord[]> {\n const docs = (await this.client.query(queryRef('members:list'), {})) as MemberDoc[]\n return docs.map((d) => memberRecordFromDoc(d, projectId))\n }\n\n async listMembershipsForUser(userId: string): Promise<ProjectMemberRecord[]> {\n // `members:mine` is caller-scoped server-side and returns the caller's single\n // deployment membership (or null). The studio only ever asks about the\n // session user; records are stamped with this deployment's bound project.\n const doc = (await this.client.query(queryRef('members:mine'), {})) as MemberDoc | null\n return doc && doc.userId === userId ? [memberRecordFromDoc(doc, this.boundProjectId)] : []\n }\n\n async removeMember(projectId: string, userId: string): Promise<void> {\n try {\n await this.client.mutation(mutationRef('members:remove'), { userId })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('project-member', `${projectId}/${userId}`)\n }\n throw error\n }\n }\n}\n\n// --- Users rail (EC-240, 240a) -----------------------------------------------\n\n/** The wire shape returned by the `users:list`/`users:get` join handlers. */\ninterface UserDoc {\n id: string\n email: string\n name?: string\n avatar?: string\n role: ProjectRole\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\n/** Map a joined user doc onto the contract record; stamp the bound project. */\nfunction userRecordFromDoc(doc: UserDoc, projectId: string): UserRecord {\n return {\n id: doc.id,\n projectId,\n email: doc.email,\n ...(doc.name !== undefined ? { name: doc.name } : {}),\n ...(doc.avatar !== undefined ? { avatar: doc.avatar } : {}),\n // 240a bridge: the single `members.role` column ⇒ the 240c-ready `roles[]`.\n roles: [doc.role],\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\n/**\n * Collapse the 240c-ready `roles[]` to the single `members.role` column by\n * applying the strongest role (the 240a→240c enforcement bridge). Unknown\n * strings are ignored; an empty/unknown set floors to `viewer`.\n */\nfunction strongestRole(roles: readonly string[]): ProjectRole {\n // Validate against the active role policy (EC-240c) rather than a hardcoded\n // enum, then take the canonical rank max; floor an empty/unknown set to `viewer`.\n const valid = roles.filter((r) => isKnownRole(r))\n return highestRole(valid) ?? 'viewer'\n}\n\n/**\n * Convex-backed {@link UserRepository} (EC-240, 240a). Reads are the admin-gated\n * `users:*` **join** handlers (members row + auth identity); the role write\n * reuses the member write path (`members:set`, extended with the `meta` bag) so\n * there is one source for role writes — 240c collapses enforcement onto it.\n */\nclass ConvexUserRepository implements UserRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async listUsers(projectId: string): Promise<UserRecord[]> {\n const docs = (await this.client.query(queryRef('users:list'), {})) as UserDoc[]\n return docs.map((doc) => userRecordFromDoc(doc, projectId))\n }\n\n async findUser(projectId: string, id: string): Promise<UserRecord | undefined> {\n const doc = (await this.client.query(queryRef('users:get'), { userId: id })) as UserDoc | null\n return doc ? userRecordFromDoc(doc, projectId) : undefined\n }\n\n async getUser(projectId: string, id: string): Promise<UserRecord> {\n const found = await this.findUser(projectId, id)\n if (!found) throw new RecordNotFoundError('user', `${projectId}/${id}`)\n return found\n }\n\n async saveUser(projectId: string, input: SaveUserInput): Promise<UserRecord> {\n const now = this.clock()\n await this.client.mutation(mutationRef('members:set'), {\n userId: input.id,\n role: strongestRole(input.roles),\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n createdAt: now,\n updatedAt: now,\n })\n // Return the full joined projection (identity + role + custom fields).\n return this.getUser(projectId, input.id)\n }\n\n async removeUser(projectId: string, id: string): Promise<void> {\n try {\n await this.client.mutation(mutationRef('members:remove'), { userId: id })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('user', `${projectId}/${id}`)\n }\n throw error\n }\n }\n}\n\ninterface CliTokenDoc {\n /** Retired (EC-182): optional only because live rows may still carry it until the migration clears it. */\n projectId?: string\n tokenId: string\n label: string\n tokenHash: string\n createdAt: string\n revokedAt?: string\n}\n\nfunction cliTokenRecordFromDoc(doc: CliTokenDoc): CliTokenRecord {\n return {\n id: doc.tokenId,\n label: doc.label,\n tokenHash: doc.tokenHash,\n createdAt: doc.createdAt,\n ...(doc.revokedAt ? { revokedAt: doc.revokedAt } : {}),\n }\n}\n\nclass ConvexCliTokenRepository implements CliTokenRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async createToken(input: NewCliTokenInput): Promise<CliTokenRecord> {\n const doc = (await this.client.mutation(mutationRef('cliTokens:create'), {\n tokenId: newId('tok'),\n label: input.label,\n tokenHash: input.tokenHash,\n createdAt: this.clock(),\n })) as CliTokenDoc\n return cliTokenRecordFromDoc(doc)\n }\n\n async listTokens(): Promise<CliTokenRecord[]> {\n const docs = (await this.client.query(queryRef('cliTokens:list'), {})) as CliTokenDoc[]\n return docs.map(cliTokenRecordFromDoc)\n }\n\n async revokeToken(tokenId: string): Promise<CliTokenRecord> {\n try {\n const doc = (await this.client.mutation(mutationRef('cliTokens:revoke'), {\n tokenId,\n revokedAt: this.clock(),\n })) as CliTokenDoc\n return cliTokenRecordFromDoc(doc)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('cli-token', tokenId)\n }\n throw error\n }\n }\n\n async findByHash(tokenHash: string): Promise<CliTokenRecord | undefined> {\n const doc = (await this.client.query(queryRef('cliTokens:byHash'), {\n tokenHash,\n })) as CliTokenDoc | null\n return doc ? cliTokenRecordFromDoc(doc) : undefined\n }\n}\n\n/** The `redirects` table row shape (EC-303). Single-tenant: no `projectId` column. */\ninterface RedirectDoc {\n redirectId: string\n from: string\n to: string\n permanent: boolean\n enabled: boolean\n /** Schema-driven additive-field bag (EC-311 Tier 2). */\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\nfunction redirectEntryFromDoc(doc: RedirectDoc, projectId: string): RedirectEntry {\n return {\n id: doc.redirectId,\n projectId,\n from: doc.from,\n to: doc.to,\n permanent: doc.permanent,\n enabled: doc.enabled,\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\n/**\n * Convex-backed {@link RedirectRepository} (EC-303) — editorial redirects as data\n * (not config). Content-gated CRUD over the `redirects` table; the studio's\n * editorial surface + the delivery snapshot both read through here. The editorial\n * surface sends a full record on save, so create-defaults (permanent/enabled) also\n * cover edits.\n */\nclass ConvexRedirectRepository implements RedirectRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async saveRedirect(projectId: string, input: SaveRedirectInput): Promise<RedirectEntry> {\n const now = this.clock()\n const id = input.id ?? newId('redirect')\n const doc = (await this.client.mutation(mutationRef('redirects:save'), {\n redirectId: id,\n from: input.from,\n to: input.to,\n permanent: input.permanent ?? true,\n enabled: input.enabled ?? true,\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n createdAt: now,\n updatedAt: now,\n })) as RedirectDoc\n return redirectEntryFromDoc(doc, projectId)\n }\n\n async getRedirect(projectId: string, id: string): Promise<RedirectEntry> {\n const found = await this.findRedirect(projectId, id)\n if (!found) throw new RecordNotFoundError('redirect', `${projectId}/${id}`)\n return found\n }\n\n async findRedirect(projectId: string, id: string): Promise<RedirectEntry | undefined> {\n const doc = (await this.client.query(queryRef('redirects:get'), {\n redirectId: id,\n })) as RedirectDoc | null\n return doc ? redirectEntryFromDoc(doc, projectId) : undefined\n }\n\n async listRedirects(projectId: string): Promise<RedirectEntry[]> {\n const docs = (await this.client.query(queryRef('redirects:list'), {})) as RedirectDoc[]\n return docs\n .map((doc) => redirectEntryFromDoc(doc, projectId))\n .sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0))\n }\n\n async removeRedirect(projectId: string, id: string): Promise<void> {\n await this.getRedirect(projectId, id) // not-found parity with the in-memory rail\n await this.client.mutation(mutationRef('redirects:remove'), { redirectId: id })\n }\n}\n\n/**\n * Convex-backed {@link DeliveryRepository} (EC-268/EC-329) — reads the\n * deployment's actual instant-publish env var status via the guarded\n * `delivery:deliveryConfig` query. Replaces the studio's former direct\n * `getConvexClient(...).query('delivery:deliveryConfig')` call in\n * `delivery-health-banner.tsx`, the only place that used to bypass both the\n * operations chokepoint and the shared `useOperationQuery` cache (AD-17).\n */\nclass ConvexDeliveryRepository implements DeliveryRepository {\n constructor(private readonly client: ConvexHttpClient) {}\n\n async getConfig(): Promise<DeliveryConfigStatus> {\n return (await this.client.query(\n queryRef('delivery:deliveryConfig'),\n {},\n )) as DeliveryConfigStatus\n }\n}\n\n/**\n * Convex-backed {@link PersistenceAdapter} (brief §10, EC-039). Every repository\n * is implemented against the Convex functions in `apps/builder/convex/*`, mapping\n * results and failures onto the provider-neutral contracts + error taxonomies.\n */\nexport class ConvexPersistenceAdapter implements PersistenceAdapter {\n readonly cms: CmsRepository\n readonly assets: AssetRepository\n /** Reference index — outbound/inbound entries per variant (EC-155, AD-6). */\n readonly references: ReferenceIndexRepository\n /** Per-project membership roles (EC-150). */\n readonly members: MembersRepository\n /** Studio users rail — role + custom fields joined to auth identity (EC-240). */\n readonly users: UserRepository\n /** Editorial redirects rail — data-backed 301/302 forwards (EC-303). */\n readonly redirects: RedirectRepository\n /** Revocable CLI sync tokens, stored hashed (EC-150). */\n readonly cliTokens: CliTokenRepository\n /** Convex file storage behind the EC-133 blob boundary (EC-151). */\n readonly blobs: BlobStorageAdapter\n /** Delivery-pipeline (instant-publish) health, read-only (EC-268/EC-329). */\n readonly delivery: DeliveryRepository\n /**\n * EC-277: the Convex mutations maintain the reference index in-transaction\n * (`convex/referenceMaintenance.ts`), so every writer — studio, CLI, webhook,\n * raw `convex run` — is caught at the source. The studio bootstrap therefore does\n * NOT attach the client-side `attachReferenceIndex` subscriber for this provider.\n */\n readonly maintainsReferenceIndex = true\n\n /**\n * @param client the Convex client bound to this deployment (one project).\n * @param projectId the slug of this deployment's one project (EC-179). Used to\n * stamp deployment-scoped member records onto the still-project-keyed contract.\n * @param collections the active project's config-owned CMS collections (EC-183,\n * AD-11), from `elytra.config.ts`. The backend has no `cmsSchemas` table, so\n * the CMS repository serves the schema from these.\n */\n constructor(\n private readonly client: ConvexHttpClient,\n projectId: string,\n collections: readonly CollectionDef[] = [],\n ) {\n this.cms = new ConvexCmsRepository(client, collections)\n this.assets = new ConvexAssetRepository(client)\n this.references = new ConvexReferenceIndexRepository(client)\n this.members = new ConvexMembersRepository(client, projectId)\n this.users = new ConvexUserRepository(client)\n this.redirects = new ConvexRedirectRepository(client)\n this.cliTokens = new ConvexCliTokenRepository(client)\n this.blobs = new ConvexBlobStorage(client)\n this.delivery = new ConvexDeliveryRepository(client)\n }\n\n async status(): Promise<BackendStatus> {\n try {\n // Lightweight connectivity probe (EC-182: no `projects` table). `members:mine`\n // takes no args and is soft-guarded (EC-279): it answers `null` for an\n // unauthenticated caller rather than throwing, so the pre-sign-in boot probe\n // resolves cleanly — backend answered ⇒ `available: true` — with no scary\n // `Uncaught Error` in the Convex log.\n await this.client.query(queryRef('members:mine'), {})\n return { backend: 'convex', available: true }\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n // EC-153: an `unauthorized` rejection *is* a healthy backend — the\n // deployment answered and enforced auth. Now that `members:mine` is\n // soft-guarded this branch is a defensive fallback (a protected probe could\n // still throw); only transport/server failures count as unavailable, so the\n // BackendGate surfaces those visibly instead of falling back to in-memory.\n if (/unauthorized/i.test(detail)) return { backend: 'convex', available: true }\n return { backend: 'convex', available: false, detail }\n }\n }\n\n validate(input: BackendValidationInput): BackendValidationResult {\n return validateForPersistence(input)\n }\n}\n"]}
1
+ {"version":3,"file":"convex-adapter.js","sourceRoot":"","sources":["../../../src/lib/persistence/convex-adapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAEtE,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,uBAAuB,EACvB,WAAW,EACX,WAAW,EACX,sBAAsB,GACvB,MAAM,6BAA6B,CAAA;AA2CpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAA;AAClE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAA;AAIzD,MAAM,SAAS,GAAU,GAAG,EAAE,CAAC,IAAI,IAAI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wBAAwB,CAAC,MAAM,CAAC,CAAA;QACrD,IAAI,CAAC,SAAS,GAAG,IAAI,wBAAwB,CAAC,MAAM,CAAC,CAAA;QACrD,IAAI,CAAC,KAAK,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,wBAAwB,CAAC,MAAM,CAAC,CAAA;IACtD,CAAC;IAED,KAAK,CAAC,MAAM;QACV,IAAI,CAAC;YACH,+EAA+E;YAC/E,uEAAuE;YACvE,6EAA6E;YAC7E,0EAA0E;YAC1E,sCAAsC;YACtC,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,EAAE,EAAE,CAAC,CAAA;YACrD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACrE,mEAAmE;YACnE,oEAAoE;YACpE,4EAA4E;YAC5E,4EAA4E;YAC5E,mFAAmF;YACnF,IAAI,eAAe,CAAC,IAAI,CAAC,MAAM,CAAC;gBAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,EAAE,CAAA;YAC/E,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,CAAA;QACxD,CAAC;IACH,CAAC;IAED,QAAQ,CAAC,KAA6B;QACpC,OAAO,sBAAsB,CAAC,KAAK,CAAC,CAAA;IACtC,CAAC;CACF","sourcesContent":["import type { ConvexHttpClient } from 'convex/browser'\nimport { documentKey, documentSchema } from '@elytracms/core/cms-core'\nimport type { CmsDocument, CollectionDef, DocumentRef } from '@elytracms/core/cms-core'\nimport {\n RecordNotFoundError,\n PersistenceValidationError,\n compareReferenceEntries,\n highestRole,\n isKnownRole,\n validateForPersistence,\n} from '@elytracms/core/persistence'\nimport type {\n AssetRecord,\n AssetRepository,\n BackendStatus,\n BackendValidationInput,\n BackendValidationResult,\n BlobStorageAdapter,\n CliTokenRecord,\n CliTokenRepository,\n CmsRepository,\n DeliveryConfigStatus,\n DeliveryRepository,\n CmsSchemaRecord,\n CmsDocumentRecord,\n DocumentVersionRecord,\n SaveDocumentVersionOptions,\n MembersRepository,\n NewAssetInput,\n NewCliTokenInput,\n PersistenceAdapter,\n OutboundReference,\n ProjectMemberRecord,\n ProjectRole,\n ReferenceEntry,\n ReferenceEntryRecord,\n ReferenceIndexBuildMarker,\n ReferenceIndexRepository,\n ReferenceLookupOptions,\n ReferenceSource,\n ReferenceSourceType,\n ReferenceTarget,\n ReferenceVariant,\n RedirectEntry,\n RedirectRepository,\n SaveRedirectInput,\n SaveUserInput,\n UserRecord,\n UserRepository,\n InviteRecord,\n InviteRepository,\n SaveInviteInput,\n} from '@elytracms/core/persistence'\nimport { normalizeInviteEmail } from '@elytracms/core/persistence'\nimport { queryRef, mutationRef } from './convex-client'\nimport { ConvexBlobStorage } from './convex-blob-storage'\n\n/** Wall-clock for runtime writes (deterministic seeds use a fixed clock instead). */\ntype Clock = () => string\nconst realClock: Clock = () => new Date().toISOString()\n\nfunction newId(prefix: string): string {\n const rand =\n typeof globalThis.crypto?.randomUUID === 'function'\n ? globalThis.crypto.randomUUID()\n : Math.abs(Date.parse(new Date().toISOString())).toString(36)\n return `${prefix}_${rand}`\n}\n\n// --- CMS, Assets ----------------------------------------------------------\n\n/**\n * Deterministic, config-owned schema timestamps (EC-183). CMS collections live\n * in `elytra.config.ts`, not the backend, so the synthesized `CmsSchemaRecord`\n * carries a stable placeholder rather than DB-row timestamps.\n */\nconst CONFIG_SCHEMA_TIMESTAMP = '2026-01-01T00:00:00.000Z'\n\ninterface DocumentDoc {\n projectId: string\n document: CmsDocument\n publishedVersion?: number\n createdAt: string\n updatedAt: string\n}\nfunction docRecordFromDoc(doc: DocumentDoc): CmsDocumentRecord {\n return {\n projectId: doc.projectId,\n document: doc.document,\n ...(doc.publishedVersion !== undefined ? { publishedVersion: doc.publishedVersion } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\ninterface VersionDoc {\n collection: string\n docId: string\n version: number\n snapshot: CmsDocument\n label?: string\n origin?: string\n createdAt: string\n}\n/** The backend row carries no `projectId` (single-tenant); stamp it from the call. */\nfunction versionRecordFromDoc(doc: VersionDoc, projectId: string): DocumentVersionRecord {\n return {\n projectId,\n collection: doc.collection,\n docId: doc.docId,\n version: doc.version,\n snapshot: doc.snapshot,\n createdAt: doc.createdAt,\n ...(doc.label ? { label: doc.label } : {}),\n ...(doc.origin ? { origin: doc.origin } : {}),\n }\n}\n\nclass ConvexCmsRepository implements CmsRepository {\n /**\n * @param collections the active project's config-owned CMS collections\n * (EC-183, AD-11), injected from `elytra.config.ts`. The Convex backend has\n * no `cmsSchemas` table — `findSchema`/`getSchema` serve these instead.\n */\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly collections: readonly CollectionDef[] = [],\n private readonly clock: Clock = realClock,\n ) {}\n\n async saveSchema(\n _projectId: string,\n _collections: readonly CollectionDef[],\n ): Promise<CmsSchemaRecord> {\n // Read-only (EC-183, AD-11): the CMS collection schema is owned by\n // `elytra.config.ts`; the backend stores documents only. A write here is a\n // visible, structured error rather than a silent no-op (the studio's CMS\n // schema surfaces are read-only; legitimate writers were removed in EC-183).\n throw new PersistenceValidationError(\n 'CMS collection schema is owned by elytra.config.ts and cannot be written to the backend.',\n [\n {\n code: 'schema-config-owned',\n message:\n 'Edit elytra.config.ts to change collections; the backend stores documents only.',\n path: [],\n domain: 'cms',\n },\n ],\n )\n }\n\n /** Config-owned schema (EC-183): the active project's collections from config. */\n private configSchema(projectId: string): CmsSchemaRecord {\n return {\n projectId,\n collections: [...this.collections],\n createdAt: CONFIG_SCHEMA_TIMESTAMP,\n updatedAt: CONFIG_SCHEMA_TIMESTAMP,\n }\n }\n\n async getSchema(projectId: string): Promise<CmsSchemaRecord> {\n return this.configSchema(projectId)\n }\n\n async findSchema(projectId: string): Promise<CmsSchemaRecord | undefined> {\n return this.configSchema(projectId)\n }\n\n async upsertDocument(projectId: string, document: CmsDocument): Promise<CmsDocumentRecord> {\n // The backend is a pure document store (EC-183, AD-11): collection-membership\n // validation lives in `@elytracms/core/cms-core` `validateDocument`, which the studio\n // runs pre-dispatch (cell edits, imports). We still parse the canonical\n // document shape so malformed blobs never reach storage.\n const parsedDoc = documentSchema.parse(document)\n const now = this.clock()\n const doc = (await this.client.mutation(mutationRef('cms:upsertDocument'), {\n collection: parsedDoc.collection,\n docId: parsedDoc.id,\n document: parsedDoc,\n createdAt: now,\n updatedAt: now,\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n\n async getDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord> {\n const found = await this.findDocument(projectId, ref)\n if (!found)\n throw new RecordNotFoundError('cms-document', `${projectId}/${ref.collection}:${ref.id}`)\n return found\n }\n\n async findDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord | undefined> {\n const doc = (await this.client.query(queryRef('cms:getDocument'), {\n collection: ref.collection,\n docId: ref.id,\n })) as DocumentDoc | null\n return doc ? docRecordFromDoc(doc) : undefined\n }\n\n async listDocuments(projectId: string, collection?: string): Promise<CmsDocumentRecord[]> {\n const docs = (await this.client.query(queryRef('cms:listDocuments'), {\n ...(collection ? { collection } : {}),\n })) as DocumentDoc[]\n // EC-153 parity: deterministic document-key ordering (Convex index order\n // within a project is insertion order, so we sort client-side).\n return docs\n .map(docRecordFromDoc)\n .sort((a, b) => (documentKey(a.document) < documentKey(b.document) ? -1 : 1))\n }\n\n async listPublishedDocuments(projectId: string, collection?: string): Promise<CmsDocument[]> {\n // EC-307: one bulk read for the published pool (collapses the per-document\n // `listVersions` fan-out). The handler resolves each pin to its snapshot.\n const snapshots = (await this.client.query(queryRef('cms:listPublishedDocuments'), {\n ...(collection ? { collection } : {}),\n })) as CmsDocument[]\n // Deterministic document-key order (parity with the in-memory adapter).\n return snapshots\n .map((doc) => documentSchema.parse(doc))\n .sort((a, b) => (documentKey(a) < documentKey(b) ? -1 : 1))\n }\n\n async deleteDocument(projectId: string, ref: DocumentRef): Promise<void> {\n // EC-153 parity: deleting a missing document is not-found, never a no-op.\n await this.getDocument(projectId, ref)\n await this.client.mutation(mutationRef('cms:deleteDocument'), {\n collection: ref.collection,\n docId: ref.id,\n })\n }\n\n async saveDocumentVersion(\n projectId: string,\n snapshot: CmsDocument,\n options: SaveDocumentVersionOptions = {},\n ): Promise<DocumentVersionRecord> {\n const parsed = documentSchema.parse(snapshot)\n const doc = (await this.client.mutation(mutationRef('cms:saveDocumentVersion'), {\n collection: parsed.collection,\n docId: parsed.id,\n snapshot: parsed,\n createdAt: this.clock(),\n ...(options.label ? { label: options.label } : {}),\n ...(options.origin ? { origin: options.origin } : {}),\n })) as VersionDoc\n return versionRecordFromDoc(doc, projectId)\n }\n\n async listDocumentVersions(\n projectId: string,\n ref: DocumentRef,\n ): Promise<DocumentVersionRecord[]> {\n const docs = (await this.client.query(queryRef('cms:listDocumentVersions'), {\n collection: ref.collection,\n docId: ref.id,\n })) as VersionDoc[]\n return docs.map((doc) => versionRecordFromDoc(doc, projectId))\n }\n\n async listAllDocumentVersions(projectId: string): Promise<DocumentVersionRecord[]> {\n const docs = (await this.client.query(\n queryRef('cms:listAllDocumentVersions'),\n {},\n )) as VersionDoc[]\n return docs.map((doc) => versionRecordFromDoc(doc, projectId))\n }\n\n async getDocumentVersion(\n projectId: string,\n ref: DocumentRef,\n version: number,\n ): Promise<DocumentVersionRecord> {\n const doc = (await this.client.query(queryRef('cms:getDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n })) as VersionDoc | null\n if (!doc) {\n throw new RecordNotFoundError(\n 'cms-document-version',\n `${projectId}/${ref.collection}:${ref.id}#${version}`,\n )\n }\n return versionRecordFromDoc(doc, projectId)\n }\n\n async publishDocumentVersion(\n projectId: string,\n ref: DocumentRef,\n version: number,\n ): Promise<CmsDocumentRecord> {\n // Taxonomy enforced adapter-side (the handler is lenient): the document and\n // the pinned version must both exist (each throws RecordNotFoundError).\n await this.getDocument(projectId, ref)\n await this.getDocumentVersion(projectId, ref, version)\n const doc = (await this.client.mutation(mutationRef('cms:publishDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n updatedAt: this.clock(),\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n\n async unpublishDocument(projectId: string, ref: DocumentRef): Promise<CmsDocumentRecord> {\n const existing = await this.getDocument(projectId, ref)\n if (existing.publishedVersion === undefined) {\n throw new PersistenceValidationError('Document is not currently published.', [\n {\n code: 'invalid-transition',\n message: 'Cannot unpublish: the document has no published version.',\n domain: 'cms',\n },\n ])\n }\n const doc = (await this.client.mutation(mutationRef('cms:unpublishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n updatedAt: this.clock(),\n })) as DocumentDoc\n return docRecordFromDoc(doc)\n }\n}\n\ninterface AssetDoc {\n projectId: string\n assetId: string\n filename: string\n contentType: string\n byteSize: number\n width?: number\n height?: number\n alt?: string\n /** Editable display title (EC-152). */\n title?: string\n storageKey: string\n url?: string\n /** Normalized image focal point `{ x, y }` in 0–1 (EC-230). */\n focalPoint?: { x: number; y: number }\n /** Schema-driven asset metadata bag (EC-301). */\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\n/** Map a Convex asset doc onto the contract record (assetId → id, drop _id/_creationTime). */\nfunction assetRecordFromDoc(doc: AssetDoc): AssetRecord {\n return {\n id: doc.assetId,\n projectId: doc.projectId,\n filename: doc.filename,\n contentType: doc.contentType,\n byteSize: doc.byteSize,\n ...(doc.width !== undefined ? { width: doc.width } : {}),\n ...(doc.height !== undefined ? { height: doc.height } : {}),\n ...(doc.alt !== undefined ? { alt: doc.alt } : {}),\n ...(doc.title !== undefined ? { title: doc.title } : {}),\n ...(doc.url !== undefined ? { url: doc.url } : {}),\n ...(doc.focalPoint !== undefined ? { focalPoint: doc.focalPoint } : {}),\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n storageKey: doc.storageKey,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\nclass ConvexAssetRepository implements AssetRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async upsertAsset(projectId: string, input: NewAssetInput): Promise<AssetRecord> {\n const now = this.clock()\n const id = input.id ?? newId('asset')\n const doc = (await this.client.mutation(mutationRef('assets:upsert'), {\n assetId: id,\n filename: input.filename,\n contentType: input.contentType,\n byteSize: input.byteSize,\n ...(input.width !== undefined ? { width: input.width } : {}),\n ...(input.height !== undefined ? { height: input.height } : {}),\n ...(input.alt !== undefined ? { alt: input.alt } : {}),\n // EC-153 parity: `title` (EC-152 metadata) must persist, not silently drop.\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.url !== undefined ? { url: input.url } : {}),\n ...(input.focalPoint !== undefined ? { focalPoint: input.focalPoint } : {}),\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n storageKey: input.storageKey ?? `${projectId}/${id}`,\n createdAt: now,\n updatedAt: now,\n })) as AssetDoc\n return assetRecordFromDoc(doc)\n }\n\n async getAsset(projectId: string, id: string): Promise<AssetRecord> {\n const found = await this.findAsset(projectId, id)\n if (!found) throw new RecordNotFoundError('asset', `${projectId}/${id}`)\n return found\n }\n\n async findAsset(projectId: string, id: string): Promise<AssetRecord | undefined> {\n const doc = (await this.client.query(queryRef('assets:get'), {\n assetId: id,\n })) as AssetDoc | null\n return doc ? assetRecordFromDoc(doc) : undefined\n }\n\n async listAssets(projectId: string): Promise<AssetRecord[]> {\n const docs = (await this.client.query(queryRef('assets:list'), {})) as AssetDoc[]\n return docs.map(assetRecordFromDoc)\n }\n\n async removeAsset(projectId: string, id: string): Promise<void> {\n // EC-153 parity: removing an unknown asset is not-found, never a no-op.\n await this.getAsset(projectId, id)\n await this.client.mutation(mutationRef('assets:remove'), { assetId: id })\n }\n\n async resolveMany(projectId: string, ids: readonly string[]): Promise<Map<string, AssetRecord>> {\n const all = await this.listAssets(projectId)\n const out = new Map<string, AssetRecord>()\n for (const asset of all) if (ids.includes(asset.id)) out.set(asset.id, asset)\n return out\n }\n}\n\n// --- Reference index (EC-155) ------------------------------------------------\n\n/** A Convex reference-entry doc (flattened source/target for index-backed lookups). */\ninterface ReferenceEntryDoc {\n projectId: string\n variant: ReferenceVariant\n sourceType: ReferenceSourceType\n sourceId: string\n path: string\n targetType: ReferenceTarget['type']\n targetId: string\n kind: ReferenceEntryRecord['kind']\n}\n\nfunction referenceRecordFromDoc(doc: ReferenceEntryDoc): ReferenceEntryRecord {\n return {\n projectId: doc.projectId,\n variant: doc.variant,\n source: { type: doc.sourceType, id: doc.sourceId },\n path: doc.path,\n target: { type: doc.targetType, id: doc.targetId },\n kind: doc.kind,\n }\n}\n\n/** Deterministic ordering is a repository contract; Convex docs sort client-side. */\nfunction sortedReferenceRecords(docs: ReferenceEntryDoc[]): ReferenceEntryRecord[] {\n return docs.map(referenceRecordFromDoc).sort(compareReferenceEntries)\n}\n\nclass ConvexReferenceIndexRepository implements ReferenceIndexRepository {\n constructor(private readonly client: ConvexHttpClient) {}\n\n async replaceForSource(\n projectId: string,\n variant: ReferenceVariant,\n source: ReferenceSource,\n references: readonly OutboundReference[],\n ): Promise<ReferenceEntryRecord[]> {\n await this.client.mutation(mutationRef('references:replaceForSource'), {\n variant,\n sourceType: source.type,\n sourceId: source.id,\n references: references.map((r) => ({\n path: r.path,\n targetType: r.target.type,\n targetId: r.target.id,\n kind: r.kind,\n })),\n })\n return this.outbound(projectId, source, { variant })\n }\n\n async replaceForSourceTypes(\n projectId: string,\n variant: ReferenceVariant,\n sourceTypes: readonly ReferenceSourceType[],\n entries: readonly ReferenceEntry[],\n ): Promise<ReferenceEntryRecord[]> {\n await this.client.mutation(mutationRef('references:replaceForSourceTypes'), {\n variant,\n sourceTypes: [...sourceTypes],\n entries: entries.map((e) => ({\n sourceType: e.source.type,\n sourceId: e.source.id,\n path: e.path,\n targetType: e.target.type,\n targetId: e.target.id,\n kind: e.kind,\n })),\n })\n const all = await this.listEntries(projectId, variant)\n const types = new Set(sourceTypes)\n return all.filter((record) => types.has(record.source.type))\n }\n\n async removeForSource(\n projectId: string,\n source: ReferenceSource,\n variant?: ReferenceVariant,\n ): Promise<void> {\n await this.client.mutation(mutationRef('references:removeForSource'), {\n sourceType: source.type,\n sourceId: source.id,\n ...(variant ? { variant } : {}),\n })\n }\n\n async outbound(\n projectId: string,\n source: ReferenceSource,\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:outbound'), {\n sourceType: source.type,\n sourceId: source.id,\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async inbound(\n projectId: string,\n target: ReferenceTarget,\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:inbound'), {\n targetType: target.type,\n targetId: target.id,\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async inboundMany(\n projectId: string,\n targets: readonly ReferenceTarget[],\n options: ReferenceLookupOptions = {},\n ): Promise<ReferenceEntryRecord[][]> {\n // EC-308: one round-trip for all targets (the handler loops the by_target\n // index server-side), replacing the client's per-target inbound fan-out.\n if (targets.length === 0) return []\n const groups = (await this.client.query(queryRef('references:inboundMany'), {\n targets: targets.map((target) => ({ targetType: target.type, targetId: target.id })),\n ...(options.variant ? { variant: options.variant } : {}),\n })) as ReferenceEntryDoc[][]\n return groups.map((docs) => sortedReferenceRecords(docs))\n }\n\n async listEntries(\n projectId: string,\n variant?: ReferenceVariant,\n ): Promise<ReferenceEntryRecord[]> {\n const docs = (await this.client.query(queryRef('references:list'), {\n ...(variant ? { variant } : {}),\n })) as ReferenceEntryDoc[]\n return sortedReferenceRecords(docs)\n }\n\n async getBuildMarker(projectId: string): Promise<ReferenceIndexBuildMarker | null> {\n return (await this.client.query(queryRef('references:buildMarker'), {})) as\n | ReferenceIndexBuildMarker\n | null\n }\n\n async setBuildMarker(projectId: string, marker: ReferenceIndexBuildMarker): Promise<void> {\n await this.client.mutation(mutationRef('references:setBuildMarker'), {\n entryCount: marker.entryCount,\n })\n }\n\n async clearProject(projectId: string): Promise<void> {\n await this.client.mutation(mutationRef('references:clearProject'), {})\n }\n}\n\n// --- Members + CLI tokens (EC-150) -------------------------------------------\n\ninterface MemberDoc {\n userId: string\n role: ProjectRole\n createdAt: string\n updatedAt: string\n}\n\n/**\n * Single-tenant (EC-179): membership is deployment-scoped, so the backend rows\n * carry no `projectId`. The contract record still does — this adapter is bound\n * to its deployment's project, so it stamps that slug onto every record.\n */\nfunction memberRecordFromDoc(doc: MemberDoc, projectId: string): ProjectMemberRecord {\n return {\n projectId,\n userId: doc.userId,\n role: doc.role,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\nclass ConvexMembersRepository implements MembersRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n /** The slug of this deployment's one project — stamped onto records. */\n private readonly boundProjectId: string,\n private readonly clock: Clock = realClock,\n ) {}\n\n async setMember(\n projectId: string,\n userId: string,\n role: ProjectRole,\n ): Promise<ProjectMemberRecord> {\n const now = this.clock()\n const doc = (await this.client.mutation(mutationRef('members:set'), {\n userId,\n role,\n createdAt: now,\n updatedAt: now,\n })) as MemberDoc\n return memberRecordFromDoc(doc, projectId)\n }\n\n async findMember(projectId: string, userId: string): Promise<ProjectMemberRecord | undefined> {\n const doc = (await this.client.query(queryRef('members:get'), {\n userId,\n })) as MemberDoc | null\n return doc ? memberRecordFromDoc(doc, projectId) : undefined\n }\n\n async listMembers(projectId: string): Promise<ProjectMemberRecord[]> {\n const docs = (await this.client.query(queryRef('members:list'), {})) as MemberDoc[]\n return docs.map((d) => memberRecordFromDoc(d, projectId))\n }\n\n async listMembershipsForUser(userId: string): Promise<ProjectMemberRecord[]> {\n // `members:mine` is caller-scoped server-side and returns the caller's single\n // deployment membership (or null). The studio only ever asks about the\n // session user; records are stamped with this deployment's bound project.\n const doc = (await this.client.query(queryRef('members:mine'), {})) as MemberDoc | null\n return doc && doc.userId === userId ? [memberRecordFromDoc(doc, this.boundProjectId)] : []\n }\n\n async removeMember(projectId: string, userId: string): Promise<void> {\n try {\n await this.client.mutation(mutationRef('members:remove'), { userId })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('project-member', `${projectId}/${userId}`)\n }\n throw error\n }\n }\n}\n\n// --- Users rail (EC-240, 240a) -----------------------------------------------\n\n/** The wire shape returned by the `users:list`/`users:get` join handlers. */\ninterface UserDoc {\n id: string\n email: string\n name?: string\n avatar?: string\n role: ProjectRole\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\n/** Map a joined user doc onto the contract record; stamp the bound project. */\nfunction userRecordFromDoc(doc: UserDoc, projectId: string): UserRecord {\n return {\n id: doc.id,\n projectId,\n email: doc.email,\n ...(doc.name !== undefined ? { name: doc.name } : {}),\n ...(doc.avatar !== undefined ? { avatar: doc.avatar } : {}),\n // 240a bridge: the single `members.role` column ⇒ the 240c-ready `roles[]`.\n roles: [doc.role],\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\n/**\n * Collapse the 240c-ready `roles[]` to the single `members.role` column by\n * applying the strongest role (the 240a→240c enforcement bridge). Unknown\n * strings are ignored; an empty/unknown set floors to `viewer`.\n */\nfunction strongestRole(roles: readonly string[]): ProjectRole {\n // Validate against the active role policy (EC-240c) rather than a hardcoded\n // enum, then take the canonical rank max; floor an empty/unknown set to `viewer`.\n const valid = roles.filter((r) => isKnownRole(r))\n return highestRole(valid) ?? 'viewer'\n}\n\n/**\n * Convex-backed {@link UserRepository} (EC-240, 240a). Reads are the admin-gated\n * `users:*` **join** handlers (members row + auth identity); the role write\n * reuses the member write path (`members:set`, extended with the `meta` bag) so\n * there is one source for role writes — 240c collapses enforcement onto it.\n */\nclass ConvexUserRepository implements UserRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async listUsers(projectId: string): Promise<UserRecord[]> {\n const docs = (await this.client.query(queryRef('users:list'), {})) as UserDoc[]\n return docs.map((doc) => userRecordFromDoc(doc, projectId))\n }\n\n async findUser(projectId: string, id: string): Promise<UserRecord | undefined> {\n const doc = (await this.client.query(queryRef('users:get'), { userId: id })) as UserDoc | null\n return doc ? userRecordFromDoc(doc, projectId) : undefined\n }\n\n async getUser(projectId: string, id: string): Promise<UserRecord> {\n const found = await this.findUser(projectId, id)\n if (!found) throw new RecordNotFoundError('user', `${projectId}/${id}`)\n return found\n }\n\n async getSelf(projectId: string): Promise<UserRecord | null> {\n // Self-permitted (EC-240 H-tail item 1): `users:getSelf` derives the caller\n // from the JWT server-side and returns ONLY their own join — never widened to\n // the admin-only `users:get`. The `selfId` the contract passes is ignored here;\n // the trust boundary is the server.\n const doc = (await this.client.query(queryRef('users:getSelf'), {})) as UserDoc | null\n return doc ? userRecordFromDoc(doc, projectId) : null\n }\n\n async saveUser(projectId: string, input: SaveUserInput): Promise<UserRecord> {\n const now = this.clock()\n await this.client.mutation(mutationRef('members:set'), {\n userId: input.id,\n role: strongestRole(input.roles),\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n createdAt: now,\n updatedAt: now,\n })\n // Return the full joined projection (identity + role + custom fields).\n return this.getUser(projectId, input.id)\n }\n\n async removeUser(projectId: string, id: string): Promise<void> {\n try {\n await this.client.mutation(mutationRef('members:remove'), { userId: id })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('user', `${projectId}/${id}`)\n }\n throw error\n }\n }\n}\n\n// --- Invite allowlist rail (EC-324) ------------------------------------------\n\n/** The wire shape returned by the `invites:*` handlers. */\ninterface InviteDoc {\n email: string\n role: string\n invitedBy?: string\n createdAt: string\n updatedAt: string\n}\n\nfunction inviteRecordFromDoc(doc: InviteDoc): InviteRecord {\n return {\n email: doc.email,\n role: doc.role,\n ...(doc.invitedBy !== undefined ? { invitedBy: doc.invitedBy } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\n/**\n * Convex-backed {@link InviteRepository} (EC-324). Admin-gated `invites:*`\n * handlers; the repo supplies timestamps (mirroring `ConvexUserRepository`). The\n * Convex auth boundary reads the same table in `beforeSessionCreation` to gate\n * open sign-up + grant the invited role.\n */\nclass ConvexInviteRepository implements InviteRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async listInvites(_projectId: string): Promise<InviteRecord[]> {\n const docs = (await this.client.query(queryRef('invites:list'), {})) as InviteDoc[]\n return docs.map(inviteRecordFromDoc)\n }\n\n async findInvite(projectId: string, email: string): Promise<InviteRecord | undefined> {\n const key = normalizeInviteEmail(email)\n const all = await this.listInvites(projectId)\n return all.find((invite) => invite.email === key)\n }\n\n async saveInvite(_projectId: string, input: SaveInviteInput): Promise<InviteRecord> {\n const now = this.clock()\n const doc = (await this.client.mutation(mutationRef('invites:create'), {\n email: normalizeInviteEmail(input.email),\n role: input.role,\n ...(input.invitedBy !== undefined ? { invitedBy: input.invitedBy } : {}),\n createdAt: now,\n updatedAt: now,\n })) as InviteDoc\n return inviteRecordFromDoc(doc)\n }\n\n async removeInvite(projectId: string, email: string): Promise<void> {\n try {\n await this.client.mutation(mutationRef('invites:revoke'), {\n email: normalizeInviteEmail(email),\n })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('invite', `${projectId}/${normalizeInviteEmail(email)}`)\n }\n throw error\n }\n }\n}\n\ninterface CliTokenDoc {\n /** Retired (EC-182): optional only because live rows may still carry it until the migration clears it. */\n projectId?: string\n tokenId: string\n label: string\n tokenHash: string\n createdAt: string\n revokedAt?: string\n}\n\nfunction cliTokenRecordFromDoc(doc: CliTokenDoc): CliTokenRecord {\n return {\n id: doc.tokenId,\n label: doc.label,\n tokenHash: doc.tokenHash,\n createdAt: doc.createdAt,\n ...(doc.revokedAt ? { revokedAt: doc.revokedAt } : {}),\n }\n}\n\nclass ConvexCliTokenRepository implements CliTokenRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async createToken(input: NewCliTokenInput): Promise<CliTokenRecord> {\n const doc = (await this.client.mutation(mutationRef('cliTokens:create'), {\n tokenId: newId('tok'),\n label: input.label,\n tokenHash: input.tokenHash,\n createdAt: this.clock(),\n })) as CliTokenDoc\n return cliTokenRecordFromDoc(doc)\n }\n\n async listTokens(): Promise<CliTokenRecord[]> {\n const docs = (await this.client.query(queryRef('cliTokens:list'), {})) as CliTokenDoc[]\n return docs.map(cliTokenRecordFromDoc)\n }\n\n async revokeToken(tokenId: string): Promise<CliTokenRecord> {\n try {\n const doc = (await this.client.mutation(mutationRef('cliTokens:revoke'), {\n tokenId,\n revokedAt: this.clock(),\n })) as CliTokenDoc\n return cliTokenRecordFromDoc(doc)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n if (/not-found/i.test(message)) {\n throw new RecordNotFoundError('cli-token', tokenId)\n }\n throw error\n }\n }\n\n async findByHash(tokenHash: string): Promise<CliTokenRecord | undefined> {\n const doc = (await this.client.query(queryRef('cliTokens:byHash'), {\n tokenHash,\n })) as CliTokenDoc | null\n return doc ? cliTokenRecordFromDoc(doc) : undefined\n }\n}\n\n/** The `redirects` table row shape (EC-303). Single-tenant: no `projectId` column. */\ninterface RedirectDoc {\n redirectId: string\n from: string\n to: string\n permanent: boolean\n enabled: boolean\n /** Schema-driven additive-field bag (EC-311 Tier 2). */\n meta?: Record<string, unknown>\n createdAt: string\n updatedAt: string\n}\n\nfunction redirectEntryFromDoc(doc: RedirectDoc, projectId: string): RedirectEntry {\n return {\n id: doc.redirectId,\n projectId,\n from: doc.from,\n to: doc.to,\n permanent: doc.permanent,\n enabled: doc.enabled,\n ...(doc.meta !== undefined ? { meta: doc.meta } : {}),\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n}\n\n/**\n * Convex-backed {@link RedirectRepository} (EC-303) — editorial redirects as data\n * (not config). Content-gated CRUD over the `redirects` table; the studio's\n * editorial surface + the delivery snapshot both read through here. The editorial\n * surface sends a full record on save, so create-defaults (permanent/enabled) also\n * cover edits.\n */\nclass ConvexRedirectRepository implements RedirectRepository {\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly clock: Clock = realClock,\n ) {}\n\n async saveRedirect(projectId: string, input: SaveRedirectInput): Promise<RedirectEntry> {\n const now = this.clock()\n const id = input.id ?? newId('redirect')\n const doc = (await this.client.mutation(mutationRef('redirects:save'), {\n redirectId: id,\n from: input.from,\n to: input.to,\n permanent: input.permanent ?? true,\n enabled: input.enabled ?? true,\n ...(input.meta !== undefined ? { meta: input.meta } : {}),\n createdAt: now,\n updatedAt: now,\n })) as RedirectDoc\n return redirectEntryFromDoc(doc, projectId)\n }\n\n async getRedirect(projectId: string, id: string): Promise<RedirectEntry> {\n const found = await this.findRedirect(projectId, id)\n if (!found) throw new RecordNotFoundError('redirect', `${projectId}/${id}`)\n return found\n }\n\n async findRedirect(projectId: string, id: string): Promise<RedirectEntry | undefined> {\n const doc = (await this.client.query(queryRef('redirects:get'), {\n redirectId: id,\n })) as RedirectDoc | null\n return doc ? redirectEntryFromDoc(doc, projectId) : undefined\n }\n\n async listRedirects(projectId: string): Promise<RedirectEntry[]> {\n const docs = (await this.client.query(queryRef('redirects:list'), {})) as RedirectDoc[]\n return docs\n .map((doc) => redirectEntryFromDoc(doc, projectId))\n .sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0))\n }\n\n async removeRedirect(projectId: string, id: string): Promise<void> {\n await this.getRedirect(projectId, id) // not-found parity with the in-memory rail\n await this.client.mutation(mutationRef('redirects:remove'), { redirectId: id })\n }\n}\n\n/**\n * Convex-backed {@link DeliveryRepository} (EC-268/EC-329) — reads the\n * deployment's actual instant-publish env var status via the guarded\n * `delivery:deliveryConfig` query. Replaces the studio's former direct\n * `getConvexClient(...).query('delivery:deliveryConfig')` call in\n * `delivery-health-banner.tsx`, the only place that used to bypass both the\n * operations chokepoint and the shared `useOperationQuery` cache (AD-17).\n */\nclass ConvexDeliveryRepository implements DeliveryRepository {\n constructor(private readonly client: ConvexHttpClient) {}\n\n async getConfig(): Promise<DeliveryConfigStatus> {\n return (await this.client.query(\n queryRef('delivery:deliveryConfig'),\n {},\n )) as DeliveryConfigStatus\n }\n}\n\n/**\n * Convex-backed {@link PersistenceAdapter} (brief §10, EC-039). Every repository\n * is implemented against the Convex functions in `apps/builder/convex/*`, mapping\n * results and failures onto the provider-neutral contracts + error taxonomies.\n */\nexport class ConvexPersistenceAdapter implements PersistenceAdapter {\n readonly cms: CmsRepository\n readonly assets: AssetRepository\n /** Reference index — outbound/inbound entries per variant (EC-155, AD-6). */\n readonly references: ReferenceIndexRepository\n /** Per-project membership roles (EC-150). */\n readonly members: MembersRepository\n readonly invites: InviteRepository\n /** Studio users rail — role + custom fields joined to auth identity (EC-240). */\n readonly users: UserRepository\n /** Editorial redirects rail — data-backed 301/302 forwards (EC-303). */\n readonly redirects: RedirectRepository\n /** Revocable CLI sync tokens, stored hashed (EC-150). */\n readonly cliTokens: CliTokenRepository\n /** Convex file storage behind the EC-133 blob boundary (EC-151). */\n readonly blobs: BlobStorageAdapter\n /** Delivery-pipeline (instant-publish) health, read-only (EC-268/EC-329). */\n readonly delivery: DeliveryRepository\n /**\n * EC-277: the Convex mutations maintain the reference index in-transaction\n * (`convex/referenceMaintenance.ts`), so every writer — studio, CLI, webhook,\n * raw `convex run` — is caught at the source. The studio bootstrap therefore does\n * NOT attach the client-side `attachReferenceIndex` subscriber for this provider.\n */\n readonly maintainsReferenceIndex = true\n\n /**\n * @param client the Convex client bound to this deployment (one project).\n * @param projectId the slug of this deployment's one project (EC-179). Used to\n * stamp deployment-scoped member records onto the still-project-keyed contract.\n * @param collections the active project's config-owned CMS collections (EC-183,\n * AD-11), from `elytra.config.ts`. The backend has no `cmsSchemas` table, so\n * the CMS repository serves the schema from these.\n */\n constructor(\n private readonly client: ConvexHttpClient,\n projectId: string,\n collections: readonly CollectionDef[] = [],\n ) {\n this.cms = new ConvexCmsRepository(client, collections)\n this.assets = new ConvexAssetRepository(client)\n this.references = new ConvexReferenceIndexRepository(client)\n this.members = new ConvexMembersRepository(client, projectId)\n this.users = new ConvexUserRepository(client)\n this.invites = new ConvexInviteRepository(client)\n this.redirects = new ConvexRedirectRepository(client)\n this.cliTokens = new ConvexCliTokenRepository(client)\n this.blobs = new ConvexBlobStorage(client)\n this.delivery = new ConvexDeliveryRepository(client)\n }\n\n async status(): Promise<BackendStatus> {\n try {\n // Lightweight connectivity probe (EC-182: no `projects` table). `members:mine`\n // takes no args and is soft-guarded (EC-279): it answers `null` for an\n // unauthenticated caller rather than throwing, so the pre-sign-in boot probe\n // resolves cleanly — backend answered ⇒ `available: true` — with no scary\n // `Uncaught Error` in the Convex log.\n await this.client.query(queryRef('members:mine'), {})\n return { backend: 'convex', available: true }\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n // EC-153: an `unauthorized` rejection *is* a healthy backend — the\n // deployment answered and enforced auth. Now that `members:mine` is\n // soft-guarded this branch is a defensive fallback (a protected probe could\n // still throw); only transport/server failures count as unavailable, so the\n // DeploymentSetupGate surfaces those visibly instead of falling back to in-memory.\n if (/unauthorized/i.test(detail)) return { backend: 'convex', available: true }\n return { backend: 'convex', available: false, detail }\n }\n }\n\n validate(input: BackendValidationInput): BackendValidationResult {\n return validateForPersistence(input)\n }\n}\n"]}
@@ -0,0 +1,36 @@
1
+ import type { DeploymentReadinessFacts, DeploymentReadinessReport } from '@elytracms/core/export-sync/deployment-ready';
2
+ import type { CollectionDef } from '@elytracms/core/cms-core';
3
+ import type { StudioBackendConfig } from './backend-mode';
4
+ import type { WorkspaceState } from '../workspace';
5
+ /**
6
+ * Studio-side adapter for the shared `checkDeploymentReady` contract (EC-258).
7
+ * Maps the studio's resolved state — backend mode (`resolveBackendConfig`),
8
+ * workspace config (`getWorkspaceState`), config-owned collections
9
+ * (`resolveDeploymentCollections`), and an optional reachability probe outcome —
10
+ * onto the core-owned {@link DeploymentReadinessFacts}, then composes the report.
11
+ *
12
+ * A PURE mapper: the async I/O (the `adapter.status()` reachability probe) lives in
13
+ * the boot `DeploymentSetupGate`, which passes the outcome in. `authKeys` is
14
+ * deliberately left unprobed here — the deployment's JWKS endpoint is CORS-blocked
15
+ * from the browser, so the auth-signing-keys check resolves to `unknown` at boot
16
+ * (EC-257's honest sign-in error is the browser's actionable surface; the
17
+ * `elytra doctor` CLI probes it definitively from node). `session` is left unset —
18
+ * this gate runs before auth, so the per-user bucket stays `unknown` (never a false
19
+ * fail) until a signed-in surface supplies it.
20
+ */
21
+ export interface StudioReadinessInputs {
22
+ backend: StudioBackendConfig;
23
+ /** The active project's effective deployment URL (`resolveDeploymentUrl`); defaults to `backend.url`. */
24
+ effectiveUrl?: string;
25
+ workspace: WorkspaceState;
26
+ collections: readonly CollectionDef[];
27
+ /** Reachability probe outcome (`adapter.status()`); omitted when not probed (playground / unconfigured). */
28
+ reachable?: {
29
+ available: boolean;
30
+ detail?: string;
31
+ };
32
+ }
33
+ /** Map the studio's resolved state onto the core readiness facts (pure). */
34
+ export declare function studioReadinessFacts(inputs: StudioReadinessInputs): DeploymentReadinessFacts;
35
+ /** Compose the studio's deployment-readiness report (pure). */
36
+ export declare function studioDeploymentReadiness(inputs: StudioReadinessInputs): DeploymentReadinessReport;