@elytracms/studio 0.0.99 → 0.0.100

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.
@@ -1,6 +1,8 @@
1
1
  import type { ConvexHttpClient } from 'convex/browser';
2
2
  import type { RecordStore, AssetRepository, BackendStatus, BackendValidationInput, BackendValidationResult, BlobStorageAdapter, CmsRepository, DeliveryRepository, MembersRepository, PersistenceAdapter, ProjectRole, ReferenceIndexRepository, UserRepository, InviteRepository } from '@elytracms/core/persistence';
3
3
  import type { ReactiveDocumentClient } from './convex-client.js';
4
+ /** Issue code: a record write holding a value the Convex wire cannot carry (EC-702). */
5
+ export declare const UNCARRIABLE_VALUE = "uncarriable-value";
4
6
  /**
5
7
  * The single `members.role` column a deployment stores for the 240c-ready `roles[]`
6
8
  * (the 240a→240c bridge). EC-605: exactly ONE role, passed through as given — the
@@ -1,6 +1,6 @@
1
1
  import { ConvexError, convexToJson } from 'convex/values';
2
2
  import { DRAFT_VARIANT, documentKey, documentSchema } from '@elytracms/core/cms-core';
3
- import { BackendUnavailableError, PRESENCE_TTL_MS, RecordNotFoundError, PersistenceValidationError, RevisionPreconditionError, StrictReferencePreconditionError, presenceInputSchema, assetCreateDefaults, assetRecordFromRow, compareReferenceEntries, isPersistenceError, persistenceIssueSchema, presentWriteKeys, recordEntryFromWire, validateForPersistence, versionNotPinnableError, } from '@elytracms/core/persistence';
3
+ import { BackendUnavailableError, PRESENCE_TTL_MS, RecordNotFoundError, PersistenceValidationError, RevisionPreconditionError, StrictReferencePreconditionError, presenceInputSchema, assetCreateDefaults, assetRecordFromRow, compareReferenceEntries, isPersistenceError, persistenceIssueSchema, presentWriteKeys, recordEntryFromWire, rejectedWriteMessage, validateForPersistence, versionNotPinnableError, } from '@elytracms/core/persistence';
4
4
  import { normalizeInviteEmail } from '@elytracms/core/persistence';
5
5
  import { createUuidIdFactory } from '@elytracms/core/determinism';
6
6
  import { SUBSCRIPTION_UNAUTHENTICATED_MESSAGE, queryRef, mutationRef } from './convex-client.js';
@@ -56,6 +56,65 @@ function judgedCalls(client) {
56
56
  mutation: ((ref, args = {}) => judged(args, () => client.mutation(ref, args))),
57
57
  };
58
58
  }
59
+ /** Issue code: a record write holding a value the Convex wire cannot carry (EC-702). */
60
+ export const UNCARRIABLE_VALUE = 'uncarriable-value';
61
+ /** Why Convex cannot carry `value` (its own conversion's reason, without the echoed object), or `undefined`. */
62
+ function wireRefusal(value) {
63
+ try {
64
+ convexToJson(value);
65
+ return undefined;
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ return message.split(' (present at path')[0].split(' To learn about')[0].trim();
70
+ }
71
+ }
72
+ /**
73
+ * EC-702 — the located refusals of a record write's values the Convex wire cannot carry: a
74
+ * `Date`, a `Map`, a class instance, an `undefined` in a list, a `$`-prefixed or non-ASCII key.
75
+ * The judge is Convex's own conversion (`convexToJson`, the one {@link judgedCalls} runs on every
76
+ * call's arguments), run per column so the refusal names the column — and, below it, the deepest
77
+ * value or key that fails. The in-memory store refuses the same write located, by the column's
78
+ * own schema; without this the Convex path threw an unlocated `Error` in this process
79
+ * (`unknown`). Before EC-702 the operations' step 1 located it, by running the column schemas a
80
+ * second time.
81
+ */
82
+ function uncarriableIssues(write) {
83
+ const issues = [];
84
+ for (const [column, value] of Object.entries(write)) {
85
+ const found = uncarriableAt(value, [column]);
86
+ if (found) {
87
+ issues.push({
88
+ code: UNCARRIABLE_VALUE,
89
+ message: `The Convex store cannot carry this value: ${found.reason}`,
90
+ path: found.path,
91
+ domain: 'persistence',
92
+ });
93
+ }
94
+ }
95
+ return issues;
96
+ }
97
+ function uncarriableAt(value, path) {
98
+ const reason = wireRefusal(value);
99
+ if (reason === undefined)
100
+ return undefined;
101
+ const plain = typeof value === 'object' &&
102
+ value !== null &&
103
+ (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
104
+ if (plain) {
105
+ for (const [key, item] of Object.entries(value)) {
106
+ const segment = Array.isArray(value) ? Number(key) : key;
107
+ // A key Convex refuses is the refusal itself, wherever its value is fine.
108
+ const keyReason = Array.isArray(value) ? undefined : wireRefusal({ [key]: null });
109
+ if (keyReason !== undefined)
110
+ return { path: [...path, segment], reason: keyReason };
111
+ const inner = uncarriableAt(item, [...path, segment]);
112
+ if (inner)
113
+ return inner;
114
+ }
115
+ }
116
+ return { path, reason };
117
+ }
59
118
  /**
60
119
  * Row → contract record. `projectId` is the caller's (the row has none): before
61
120
  * EC-577 this copied the row's nonexistent `projectId`, so every connected
@@ -881,9 +940,15 @@ class ConvexRecordRepository {
881
940
  const now = this.clock();
882
941
  const { id: givenId, ...write } = input;
883
942
  const id = givenId ?? newId(this.kind.idPrefix);
943
+ const sent = presentWriteKeys(write);
944
+ // EC-702: a value the wire cannot carry is the write's located refusal, as in memory.
945
+ const uncarriable = uncarriableIssues(sent);
946
+ if (uncarriable.length > 0) {
947
+ throw new PersistenceValidationError(rejectedWriteMessage(this.kind.kind, id, uncarriable), uncarriable);
948
+ }
884
949
  const row = (await this.client.mutation(mutationRef(this.ref('save')), {
885
950
  [this.kind.idKey]: id,
886
- ...presentWriteKeys(write),
951
+ ...sent,
887
952
  createdAt: now,
888
953
  updatedAt: now,
889
954
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"convex-adapter.js","sourceRoot":"","sources":["../../../src/lib/persistence/convex-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAEzD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AASrF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,mBAAmB,EACnB,0BAA0B,EAC1B,yBAAyB,EACzB,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACn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AAE,IAAI,CAAgC,CAAA;gBACnF,kBAAkB,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;YAC1C,CAAC;YACD,OAAO,UAA4C,CAAA;QACrD,CAAC,CAAA;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,wBAAwB,CAAC,KAAK,CAAC,CAAA;IACrD,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 type { FunctionReference } from 'convex/server'\nimport { ConvexError, convexToJson } from 'convex/values'\nimport type { Value } from 'convex/values'\nimport { DRAFT_VARIANT, documentKey, documentSchema } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n DocumentPatch,\n DocumentRef,\n PatchLogKind,\n RefusedPatch,\n ReplacePrecondition,\n} from '@elytracms/core/cms-core'\nimport {\n BackendUnavailableError,\n PRESENCE_TTL_MS,\n RecordNotFoundError,\n PersistenceValidationError,\n RevisionPreconditionError,\n StrictReferencePreconditionError,\n presenceInputSchema,\n assetCreateDefaults,\n assetRecordFromRow,\n compareReferenceEntries,\n isPersistenceError,\n persistenceIssueSchema,\n presentWriteKeys,\n recordEntryFromWire,\n validateForPersistence,\n versionNotPinnableError,\n} from '@elytracms/core/persistence'\nimport type {\n AnyRecordKind,\n RecordEntryOf,\n RecordQuery,\n RecordRepository,\n RecordStore,\n RecordWireRow,\n RecordWriteOf,\n AssetRecord,\n AssetRepository,\n AssetRow,\n AssetWriteInput,\n BackendStatus,\n BackendValidationInput,\n BackendValidationResult,\n BlobStorageAdapter,\n CmsRepository,\n DeliveryConfigStatus,\n DeliveryRepository,\n CmsDocumentRecord,\n DeleteOutcome,\n DeletePrecondition,\n DocumentListener,\n DocumentPatchRecord,\n PinPrecondition,\n PublishClear,\n PublishedReferrer,\n StrictTargetsPrecondition,\n UnpublishPrecondition,\n PatchOutcome,\n PresenceEntry,\n PresenceInput,\n PublishOutcome,\n ReplaceOutcome,\n WriteOptions,\n DocumentVersionKind,\n DocumentVersionRecord,\n SaveDocumentVersionOptions,\n MembersRepository,\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 SaveUserInput,\n UserRecord,\n UserRepository,\n InviteRecord,\n InviteRepository,\n SaveInviteInput,\n} from '@elytracms/core/persistence'\nimport { normalizeInviteEmail } from '@elytracms/core/persistence'\nimport { createUuidIdFactory } from '@elytracms/core/determinism'\nimport { SUBSCRIPTION_UNAUTHENTICATED_MESSAGE, queryRef, mutationRef } from './convex-client'\nimport type { ReactiveDocumentClient } 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\n/**\n * EC-578: asset and redirect ids come from the ONE id factory documents and nodes use\n * (`createUuidIdFactory`, `crypto.getRandomValues`). The old fallback minted a\n * millisecond timestamp when `crypto.randomUUID` was missing (any non-secure context),\n * so two writes in one millisecond collided; the factory refuses loudly instead.\n */\nlet mintUuid: (() => string) | undefined\n\nfunction newId(prefix: string): string {\n mintUuid ??= createUuidIdFactory()\n return `${prefix}_${mintUuid()}`\n}\n\n// --- The calls, classified by who failed (EC-686) --------------------------\n\n/** The two calls every repository makes — `ConvexHttpClient`'s, through {@link judgedCalls}. */\ntype ConvexCalls = Pick<ConvexHttpClient, 'query' | 'mutation'>\n\n/**\n * EC-686 — what a Convex call's promise rejects with, classified by WHO failed (the binding\n * rule, wave-0100). `convex/browser` (1.42.1, `http_client.js`) rejects with a raw\n * `TypeError` for a fetch rejection, with `Error(<body text>)` for any non-OK status (the\n * status discarded), and with the function's `Error(message)` or `ConvexError` for a\n * function failure: none of them says whether the store JUDGED the write. So a validation\n * verdict the engine throws on purpose and this adapter maps ({@link asRailWriteError}) is\n * that error, and anything else is a {@link BackendUnavailableError} carrying the original\n * message (an expired session is read from it — `isSessionExpiredError`): the session\n * keeps the write and re-sends it (`keepsFailedWrite`, EC-674). An `unknown` is then only\n * ever a failure in THIS process, which the same input repeats.\n */\nfunction backendFailure(error: unknown): unknown {\n const mapped = asRailWriteError(error)\n if (isPersistenceError(mapped)) return mapped\n return new BackendUnavailableError(error instanceof Error ? error.message : String(error), { cause: error })\n}\n\n/**\n * EC-686 — the client's calls with their promise classified ({@link backendFailure}), the\n * one seam every repository calls through: never a whole adapter method, so a crash of\n * this process before or after the call (a parse, a row mapping) stays `unknown`. The\n * arguments are serialised for the wire here first (`convexToJson`, the client's own\n * conversion): a value Convex cannot carry (a `$`-prefixed or non-ASCII key) fails in this\n * process, never inside the call — it is the input, not the backend. The shared client\n * itself is never patched (`lib/auth/**` reads its errors as they are).\n */\nfunction judgedCalls(client: ConvexHttpClient): ConvexCalls {\n const judged = <T,>(args: Record<string, unknown>, call: () => Promise<T>): Promise<T> => {\n convexToJson(args as Value)\n return call().catch((error: unknown) => {\n throw backendFailure(error)\n })\n }\n return {\n query: ((ref: FunctionReference<'query'>, args: Record<string, unknown> = {}) =>\n judged(args, () => client.query(ref, args))) as ConvexCalls['query'],\n mutation: ((ref: FunctionReference<'mutation'>, args: Record<string, unknown> = {}) =>\n judged(args, () => client.mutation(ref, args))) as ConvexCalls['mutation'],\n }\n}\n\n// --- CMS, Assets ----------------------------------------------------------\n\n/** The `cmsDocuments` row. Single-tenant: no `projectId` column (EC-179). */\ninterface DocumentDoc {\n document: CmsDocument\n /** EC-595: the variant key (`'draft'` in v1) and the row's revision. */\n variant: string\n revision: number\n publishedVersion?: number\n /** EC-447: the first-publish instant (set-once on publish, cleared on unpublish). */\n publishedAt?: string\n /** EC-449: the materialized \"draft differs from the pinned published snapshot\" flag. */\n hasUnpublishedChanges?: boolean\n createdAt: string\n updatedAt: string\n}\n/**\n * Row → contract record. `projectId` is the caller's (the row has none): before\n * EC-577 this copied the row's nonexistent `projectId`, so every connected\n * `CmsDocumentRecord.projectId` was `undefined` against a `min(1)` schema (MODE #6).\n */\nfunction docRecordFromDoc(doc: DocumentDoc, projectId: string): CmsDocumentRecord {\n return {\n projectId,\n document: doc.document,\n variant: doc.variant ?? DRAFT_VARIANT,\n revision: doc.revision,\n ...(doc.publishedVersion !== undefined ? { publishedVersion: doc.publishedVersion } : {}),\n // EC-447: carry the materialized publish instant onto the contract record so the\n // studio's $publishedAt column + its reconcile read the authoritative value.\n ...(doc.publishedAt !== undefined ? { publishedAt: doc.publishedAt } : {}),\n // EC-449: carry the materialized changed flag so hydration + the store's\n // save/publish/unpublish reconciles read the authoritative verdict.\n ...(doc.hasUnpublishedChanges !== undefined\n ? { hasUnpublishedChanges: doc.hasUnpublishedChanges }\n : {}),\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 /** EC-585 — which mutation recorded the row (absent on rows recorded before it). */\n kind?: DocumentVersionKind\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 ...(doc.kind ? { kind: doc.kind } : {}),\n }\n}\n\n/** The `documentPatches` row (EC-595). */\ninterface PatchDoc {\n collection: string\n docId: string\n variant: string\n revision: number\n kind: string\n actor?: string\n at: string\n patches: DocumentPatch[]\n}\n\n/** EC-649 — a document ref as the mutations' validators take it (exactly two keys). */\nfunction wireRefs(refs: readonly DocumentRef[]): { collection: string; id: string }[] {\n return refs.map((ref) => ({ collection: ref.collection, id: ref.id }))\n}\n\n/** EC-649 — the judged published referrers as `cms:unpublishDocument` / `cms:deleteDocument` take them. */\nfunction wireReferrers(\n referrers: readonly PublishedReferrer[],\n): { collection: string; id: string; publishedVersion: number }[] {\n return referrers.map((referrer) => ({\n collection: referrer.ref.collection,\n id: referrer.ref.id,\n publishedVersion: referrer.publishedVersion,\n }))\n}\n\n/** The `cms:watchDocument` result (EC-595 subscribe) — the row; presence is `cms:watchPresence`. */\ninterface WatchDoc {\n row: DocumentDoc | null\n}\n\n/**\n * The Convex CMS repository — the client half of the revisioned aggregate (EC-595). It\n * maps the handlers' outcomes onto the provider-neutral contract (a conflict is DATA,\n * never a throw) and keeps the EC-153 not-found taxonomy client-side. EC-583: documents\n * only — no schema methods (the collections ride the operations context).\n */\nclass ConvexCmsRepository implements CmsRepository {\n constructor(\n private readonly client: ConvexCalls,\n private readonly reactive: (() => ReactiveDocumentClient) | undefined,\n private readonly clock: Clock = realClock,\n ) {}\n\n async replaceDocument(\n projectId: string,\n document: CmsDocument,\n precondition: ReplacePrecondition,\n _options?: WriteOptions,\n ): Promise<ReplaceOutcome> {\n // A pure document store (EC-183, AD-11): shape-parse only. The actor the patch log\n // records is the server's authenticated caller, never a client claim.\n const parsedDoc = documentSchema.parse(document)\n const result = (await this.client.mutation(mutationRef('cms:replaceDocument'), {\n collection: parsedDoc.collection,\n docId: parsedDoc.id,\n document: parsedDoc,\n precondition,\n at: this.clock(),\n })) as\n | { status: 'ok'; row: DocumentDoc }\n | { status: 'conflict'; current: DocumentDoc | null; existing?: DocumentDoc }\n if (result.status === 'ok') return { status: 'ok', record: docRecordFromDoc(result.row, projectId) }\n return {\n status: 'conflict',\n current: result.current ? docRecordFromDoc(result.current, projectId) : undefined,\n ...(result.existing ? { existing: docRecordFromDoc(result.existing, projectId) } : {}),\n }\n }\n\n async patchDocument(\n projectId: string,\n ref: DocumentRef,\n patches: readonly DocumentPatch[],\n baseRevision: number,\n _options?: WriteOptions,\n ): Promise<PatchOutcome> {\n const result = (await this.client.mutation(mutationRef('cms:patchDocument'), {\n collection: ref.collection,\n docId: ref.id,\n patches: [...patches],\n baseRevision,\n at: this.clock(),\n })) as\n | { status: 'missing' }\n | { status: 'ok'; row: DocumentDoc }\n | { status: 'conflict'; row: DocumentDoc; refused: RefusedPatch[]; appliedCount: number }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n const record = docRecordFromDoc(result.row, projectId)\n return result.status === 'ok'\n ? { status: 'ok', record }\n : { status: 'conflict', record, refused: result.refused, appliedCount: result.appliedCount }\n }\n\n async publishDocument(\n projectId: string,\n ref: DocumentRef,\n expectedRevision: number,\n options: SaveDocumentVersionOptions & WriteOptions & StrictTargetsPrecondition & PublishClear = {},\n ): Promise<PublishOutcome> {\n const result = (await this.client.mutation(mutationRef('cms:publishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n expectedRevision,\n ...(options.label ? { label: options.label } : {}),\n ...(options.origin ? { origin: options.origin } : {}),\n at: this.clock(),\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(options.strictTargets?.length ? { strictTargets: wireRefs(options.strictTargets) } : {}),\n // EC-663: the hidden-clear, applied in the same transaction as the pin.\n ...(options.patches?.length ? { patches: [...options.patches] } : {}),\n })) as\n | { status: 'missing' }\n | { status: 'ok'; row: DocumentDoc; version: VersionDoc }\n | { status: 'conflict'; current: DocumentDoc }\n | { status: 'strict-targets'; refs: DocumentRef[] }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n if (result.status === 'strict-targets') {\n throw new StrictReferencePreconditionError('unpublished-targets', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n if (result.status === 'conflict') {\n return { status: 'conflict', current: docRecordFromDoc(result.current, projectId) }\n }\n return {\n status: 'ok',\n record: docRecordFromDoc(result.row, projectId),\n version: versionRecordFromDoc(result.version, projectId),\n }\n }\n\n async listDocumentPatches(\n projectId: string,\n ref: DocumentRef,\n afterRevision?: number,\n ): Promise<DocumentPatchRecord[]> {\n const rows = (await this.client.query(queryRef('cms:listDocumentPatches'), {\n collection: ref.collection,\n docId: ref.id,\n ...(afterRevision !== undefined ? { afterRevision } : {}),\n })) as PatchDoc[]\n return rows.map((row) => ({\n projectId,\n collection: row.collection,\n docId: row.docId,\n variant: row.variant,\n revision: row.revision,\n kind: row.kind as PatchLogKind,\n ...(row.actor !== undefined ? { actor: row.actor } : {}),\n at: row.at,\n patches: row.patches,\n }))\n }\n\n /**\n * EC-595 binding point 7 — the narrow document subscription over the REACTIVE client:\n * TWO reactive queries behind this one subject — `cms:watchDocument` (the draft row)\n * and `cms:watchPresence` (its heartbeats) — merged into one snapshot stream, the\n * first snapshot once both have answered (EC-595 A2: one query re-pushed the whole row\n * on every heartbeat — measured in `convex/presence-cost.test.ts`). A rejected session\n * token surfaces as `onError(Unauthenticated …)` — EC-403's session-expired predicate\n * matches it — never as a silently stopped stream. Without a reactive client the\n * subscription fails loudly through `onError`.\n */\n subscribeDocument(projectId: string, ref: DocumentRef, listener: DocumentListener): () => void {\n if (!this.reactive) {\n listener.onError?.(new Error('subscribeDocument: this Convex adapter was built without a reactive client.'))\n return () => {}\n }\n const reactive = this.reactive()\n const args = { collection: ref.collection, docId: ref.id }\n let row: { value: DocumentDoc | null } | undefined\n let presence: PresenceEntry[] | undefined\n // One failure (a dropped socket, an expired token) reaches BOTH queries: report it\n // once, until a query answers again.\n let reported: string | undefined\n const fail = (error: Error) => {\n if (reported === error.message) return\n reported = error.message\n listener.onError?.(error)\n }\n const emit = () => {\n reported = undefined\n if (row === undefined || presence === undefined) return\n listener.onSnapshot({\n record: row.value ? docRecordFromDoc(row.value, projectId) : undefined,\n presence,\n })\n }\n const unsubscribeRow = reactive.onUpdate(\n queryRef('cms:watchDocument'),\n args,\n (value) => {\n row = { value: (value as WatchDoc).row }\n emit()\n },\n fail,\n )\n const unsubscribePresence = reactive.onUpdate(\n queryRef('cms:watchPresence'),\n args,\n (value) => {\n presence = value as PresenceEntry[]\n emit()\n },\n fail,\n )\n const unhookAuth = reactive.onAuthLost(() => fail(new Error(SUBSCRIPTION_UNAUTHENTICATED_MESSAGE)))\n return () => {\n unhookAuth()\n unsubscribeRow()\n unsubscribePresence()\n }\n }\n\n async reportPresence(projectId: string, ref: DocumentRef, presence: PresenceInput): Promise<void> {\n const parsed = presenceInputSchema.parse(presence)\n await this.client.mutation(mutationRef('cms:reportPresence'), {\n collection: ref.collection,\n docId: ref.id,\n sessionId: parsed.sessionId,\n ...(parsed.actorName !== undefined ? { actorName: parsed.actorName } : {}),\n ...(parsed.path !== undefined ? { path: parsed.path } : {}),\n at: this.clock(),\n ttlMs: PRESENCE_TTL_MS,\n })\n }\n\n async clearPresence(projectId: string, ref: DocumentRef, sessionId: string): Promise<void> {\n await this.client.mutation(mutationRef('cms:clearPresence'), {\n collection: ref.collection,\n docId: ref.id,\n sessionId,\n })\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, projectId) : 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((doc) => docRecordFromDoc(doc, projectId))\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(\n projectId: string,\n ref: DocumentRef,\n precondition?: DeletePrecondition,\n ): Promise<DeleteOutcome> {\n // EC-153 parity: deleting a missing document is not-found, never a no-op.\n await this.getDocument(projectId, ref)\n // EC-648 / EC-649: checked in the mutation's transaction (data-only, EC-565 1e); sent only\n // when it says something, so a delete without one keeps the pre-EC-648 arguments.\n const wire = {\n ...(precondition?.revision !== undefined ? { revision: precondition.revision } : {}),\n ...(precondition?.publishedReferrers ? { publishedReferrers: wireReferrers(precondition.publishedReferrers) } : {}),\n // EC-668: the draft referrers the guard judged, re-checked in the mutation's transaction.\n ...(precondition?.draftReferrers\n ? {\n draftReferrers: precondition.draftReferrers.map((referrer) => ({\n collection: referrer.ref.collection,\n id: referrer.ref.id,\n revision: referrer.revision,\n })),\n }\n : {}),\n }\n const result = (await this.client.mutation(mutationRef('cms:deleteDocument'), {\n collection: ref.collection,\n docId: ref.id,\n ...(Object.keys(wire).length > 0 ? { precondition: wire } : {}),\n })) as\n | { status: 'ok' }\n | { status: 'conflict'; current: DocumentDoc | null }\n | { status: 'unjudged-referrers'; refs: DocumentRef[] }\n | null\n if (result?.status === 'conflict') {\n // Gone between the preflight and the mutation: the EC-153 not-found, as above.\n if (!result.current) throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n return { status: 'conflict', current: docRecordFromDoc(result.current, projectId) }\n }\n if (result?.status === 'unjudged-referrers') {\n throw new StrictReferencePreconditionError('unjudged-referrers', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n return { status: 'ok' }\n }\n\n async clearDocuments(_projectId: string): Promise<void> {\n // EC-576: one deployment is one project — the mutation clears both tables at once.\n await this.client.mutation(mutationRef('cms:clearDocuments'), {})\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 precondition?: PinPrecondition,\n ): Promise<CmsDocumentRecord> {\n // EC-595: pin integrity is enforced IN the transaction (the version must exist for\n // this document); the outcomes map onto the EC-153 not-found taxonomy here. EC-447:\n // one `now` for both stamps — the publish-action instant is the SET-ONCE candidate.\n const now = this.clock()\n const result = (await this.client.mutation(mutationRef('cms:publishDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n updatedAt: now,\n publishedAt: now,\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(precondition?.strictTargets?.length ? { strictTargets: wireRefs(precondition.strictTargets) } : {}),\n // EC-663: and the caller's revision.\n ...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),\n })) as\n | { status: 'missing' }\n | { status: 'missing-version' }\n | { status: 'not-pinnable' }\n | { status: 'strict-targets'; refs: DocumentRef[] }\n | { status: 'conflict'; current: DocumentDoc }\n | { status: 'ok'; row: DocumentDoc }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n if (result.status === 'conflict') {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId))\n }\n if (result.status === 'missing-version') {\n throw new RecordNotFoundError('cms-document-version', `${projectId}/${documentKey(ref)}#${version}`)\n }\n // EC-585: the version was recorded by a snapshot, never by a publish — the same\n // refusal the in-memory store raises.\n if (result.status === 'not-pinnable') throw versionNotPinnableError(`${projectId}/${documentKey(ref)}`, version)\n if (result.status === 'strict-targets') {\n throw new StrictReferencePreconditionError('unpublished-targets', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n return docRecordFromDoc(result.row, projectId)\n }\n\n async unpublishDocument(\n projectId: string,\n ref: DocumentRef,\n precondition?: UnpublishPrecondition,\n ): Promise<CmsDocumentRecord> {\n const existing = await this.getDocument(projectId, ref)\n // EC-663: a stale revision refuses before the not-published check, as in the in-memory store\n // (the mutation re-checks it in its transaction).\n if (precondition?.revision !== undefined && existing.revision !== precondition.revision) {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, existing)\n }\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 result = (await this.client.mutation(mutationRef('cms:unpublishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n updatedAt: this.clock(),\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(precondition?.publishedReferrers\n ? { publishedReferrers: wireReferrers(precondition.publishedReferrers) }\n : {}),\n ...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),\n })) as\n | DocumentDoc\n | { status: 'unjudged-referrers'; refs: DocumentRef[] }\n | { status: 'conflict'; current: DocumentDoc }\n if ('status' in result && result.status === 'unjudged-referrers') {\n throw new StrictReferencePreconditionError('unjudged-referrers', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n if ('status' in result && result.status === 'conflict') {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId))\n }\n return docRecordFromDoc(result as DocumentDoc, projectId)\n }\n}\n\n/**\n * A write the handler rejected (EC-577): `resolveRecordWrite` (a rail or record write) or\n * the asset upsert found the write invalid inside the transaction and threw a `validation`\n * `ConvexError` — mapped back onto the provider-neutral {@link PersistenceValidationError}\n * the in-memory adapter throws for the same write. `ConvexError` data survives a production\n * deployment's error redaction, unlike a plain thrown message. EC-686: read by\n * {@link backendFailure} for every call, so no call site maps it itself.\n */\nfunction asRailWriteError(error: unknown): unknown {\n if (!(error instanceof ConvexError)) return error\n const data = error.data as { code?: unknown; message?: unknown; issues?: unknown } | undefined\n if (data?.code !== 'validation' || typeof data.message !== 'string') return error\n const issues = persistenceIssueSchema.array().safeParse(data.issues)\n return new PersistenceValidationError(data.message, issues.success ? issues.data : [])\n}\n\nclass ConvexAssetRepository implements AssetRepository {\n constructor(\n private readonly client: ConvexCalls,\n private readonly clock: Clock = realClock,\n ) {}\n\n async upsertAsset(projectId: string, input: AssetWriteInput): Promise<AssetRecord> {\n const now = this.clock()\n const { id: givenId, ...write } = input\n const id = givenId ?? newId('asset')\n // EC-577: send the write as written — absent keys stay absent (keep), `null`\n // crosses the wire as the clear. The handler resolves it against the stored\n // row inside the transaction; the create defaults ride along for a create.\n const doc = (await this.client.mutation(mutationRef('assets:upsert'), {\n assetId: id,\n ...presentWriteKeys(write),\n defaults: assetCreateDefaults(projectId, id),\n createdAt: now,\n updatedAt: now,\n })) as AssetRow\n return assetRecordFromRow(doc, projectId)\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 AssetRow | null\n return doc ? assetRecordFromRow(doc, projectId) : undefined\n }\n\n async listAssets(projectId: string): Promise<AssetRecord[]> {\n const docs = (await this.client.query(queryRef('assets:list'), {})) as AssetRow[]\n return docs.map((doc) => assetRecordFromRow(doc, projectId))\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: ConvexCalls) {}\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: ConvexCalls,\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 * The single `members.role` column a deployment stores for the 240c-ready `roles[]`\n * (the 240a→240c bridge). EC-605: exactly ONE role, passed through as given — the\n * operations layer validated it against the project's policy, and `members:set`\n * refuses one the DEPLOYED policy does not declare, visibly. This used to filter\n * against the default policy and floor an unknown or empty set to `viewer` — a silent\n * rewrite that turned a project's own role into a viewer. Several roles cannot be\n * collapsed here without a policy, so they are refused rather than guessed at.\n */\nexport function singleStoredRole(roles: readonly string[]): ProjectRole {\n if (roles.length !== 1) {\n throw new PersistenceValidationError('A deployment stores exactly one role per member.', [\n {\n code: 'invalid-role-count',\n message: `Expected exactly one role, got ${roles.length} (${roles.join(', ') || 'none'}).`,\n path: ['roles'],\n domain: 'users',\n },\n ])\n }\n return roles[0]!\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: ConvexCalls,\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: singleStoredRole(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: ConvexCalls,\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\n/**\n * Convex-backed {@link RecordRepository} (EC-616) — one record kind over its own Convex\n * module (`<kind.module>:save|get|list|remove`, built by `defineRecordFunctions(kind)`),\n * stored in the one `records` table. The write is sent as written (EC-577): the handler\n * resolves it against the stored record in its transaction with the rule the in-memory\n * store uses. Reads come back in the ONE order (`orderRecords`, applied server-side), and\n * a refused query or write arrives as the same `PersistenceValidationError` the in-memory\n * store throws.\n */\nclass ConvexRecordRepository<K extends AnyRecordKind> implements RecordRepository<K> {\n constructor(\n private readonly client: ConvexCalls,\n readonly kind: K,\n private readonly clock: Clock = realClock,\n ) {}\n\n private ref(fn: 'save' | 'get' | 'list' | 'remove'): string {\n return `${this.kind.module}:${fn}`\n }\n\n async list(projectId: string, query: RecordQuery = {}): Promise<RecordEntryOf<K>[]> {\n const rows = (await this.client.query(queryRef(this.ref('list')), presentWriteKeys({ ...query }))) as RecordWireRow[]\n return rows.map((row) => recordEntryFromWire(this.kind, row, projectId))\n }\n\n async get(projectId: string, id: string): Promise<RecordEntryOf<K>> {\n const found = await this.find(projectId, id)\n if (!found) throw new RecordNotFoundError(this.kind.kind, `${projectId}/${id}`)\n return found\n }\n\n async find(projectId: string, id: string): Promise<RecordEntryOf<K> | undefined> {\n const row = (await this.client.query(queryRef(this.ref('get')), {\n [this.kind.idKey]: id,\n })) as RecordWireRow | null\n return row ? recordEntryFromWire(this.kind, row, projectId) : undefined\n }\n\n async save(projectId: string, input: RecordWriteOf<K>): Promise<RecordEntryOf<K>> {\n const now = this.clock()\n const { id: givenId, ...write } = input as { id?: string } & Record<string, unknown>\n const id = givenId ?? newId(this.kind.idPrefix)\n const row = (await this.client.mutation(mutationRef(this.ref('save')), {\n [this.kind.idKey]: id,\n ...presentWriteKeys(write),\n createdAt: now,\n updatedAt: now,\n })) as RecordWireRow\n return recordEntryFromWire(this.kind, row, projectId)\n }\n\n async remove(projectId: string, id: string): Promise<void> {\n await this.get(projectId, id) // not-found parity with the in-memory store\n await this.client.mutation(mutationRef(this.ref('remove')), { [this.kind.idKey]: 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: ConvexCalls) {}\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 /**\n * EC-616 — the generic record store: one repository per declared kind, each over its\n * kind's Convex module (cached per kind object, so a rail and its foot share one).\n */\n readonly records: RecordStore\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 *\n * @param options.reactive the reactive client a document subscription runs on (EC-595),\n * built lazily — the studio passes `() => getReactiveConvexClient(url)`. Absent (a\n * seed script, a test double without push), `subscribeDocument` fails loudly.\n *\n * EC-583: the third argument is no longer the collections. They only fed the\n * synthesized schema record (`getSchema`/`findSchema`), which the contract no longer\n * has — collections reach the operations layer on its context\n * (`createOperations({ collections })`).\n */\n constructor(\n private readonly client: ConvexHttpClient,\n projectId: string,\n options: { reactive?: () => ReactiveDocumentClient } = {},\n ) {\n // EC-686: every repository calls through the classified calls; the probe below and the\n // blob boundary (its own failure handling) keep the client as it is.\n const calls = judgedCalls(client)\n this.cms = new ConvexCmsRepository(calls, options.reactive)\n this.assets = new ConvexAssetRepository(calls)\n this.references = new ConvexReferenceIndexRepository(calls)\n this.members = new ConvexMembersRepository(calls, projectId)\n this.users = new ConvexUserRepository(calls)\n this.invites = new ConvexInviteRepository(calls)\n const recordRepositories = new Map<AnyRecordKind, RecordRepository>()\n this.records = <K extends AnyRecordKind>(kind: K): RecordRepository<K> => {\n let repository = recordRepositories.get(kind)\n if (!repository) {\n repository = new ConvexRecordRepository(calls, kind) as unknown as RecordRepository\n recordRepositories.set(kind, repository)\n }\n return repository as unknown as RecordRepository<K>\n }\n this.blobs = new ConvexBlobStorage(client)\n this.delivery = new ConvexDeliveryRepository(calls)\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"]}
1
+ {"version":3,"file":"convex-adapter.js","sourceRoot":"","sources":["../../../src/lib/persistence/convex-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAEzD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AASrF,OAAO,EACL,uBAAuB,EACvB,eAAe,EACf,mBAAmB,EACnB,0BAA0B,EAC1B,yBAAyB,EACzB,gCAAgC,EAChC,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,sBAAsB,EACtB,gBAAgB,EAChB,mBAAmB,EACnB,oBAAoB,EACpB,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,6BAA6B,CAAA;AA6DpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAA;AAClE,OAAO,EAAE,mBAAmB,EAA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;gBACnF,kBAAkB,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC,CAAA;YAC1C,CAAC;YACD,OAAO,UAA4C,CAAA;QACrD,CAAC,CAAA;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAA;QAC1C,IAAI,CAAC,QAAQ,GAAG,IAAI,wBAAwB,CAAC,KAAK,CAAC,CAAA;IACrD,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 type { FunctionReference } from 'convex/server'\nimport { ConvexError, convexToJson } from 'convex/values'\nimport type { Value } from 'convex/values'\nimport { DRAFT_VARIANT, documentKey, documentSchema } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n DocumentPatch,\n DocumentRef,\n PatchLogKind,\n RefusedPatch,\n ReplacePrecondition,\n} from '@elytracms/core/cms-core'\nimport {\n BackendUnavailableError,\n PRESENCE_TTL_MS,\n RecordNotFoundError,\n PersistenceValidationError,\n RevisionPreconditionError,\n StrictReferencePreconditionError,\n presenceInputSchema,\n assetCreateDefaults,\n assetRecordFromRow,\n compareReferenceEntries,\n isPersistenceError,\n persistenceIssueSchema,\n presentWriteKeys,\n recordEntryFromWire,\n rejectedWriteMessage,\n validateForPersistence,\n versionNotPinnableError,\n} from '@elytracms/core/persistence'\nimport type {\n AnyRecordKind,\n RecordEntryOf,\n RecordQuery,\n RecordRepository,\n RecordStore,\n RecordWireRow,\n RecordWriteOf,\n AssetRecord,\n AssetRepository,\n AssetRow,\n AssetWriteInput,\n BackendStatus,\n BackendValidationInput,\n BackendValidationResult,\n BlobStorageAdapter,\n CmsRepository,\n DeliveryConfigStatus,\n DeliveryRepository,\n CmsDocumentRecord,\n DeleteOutcome,\n DeletePrecondition,\n DocumentListener,\n DocumentPatchRecord,\n PinPrecondition,\n PublishClear,\n PublishedReferrer,\n StrictTargetsPrecondition,\n UnpublishPrecondition,\n PatchOutcome,\n PresenceEntry,\n PresenceInput,\n PublishOutcome,\n ReplaceOutcome,\n WriteOptions,\n DocumentVersionKind,\n DocumentVersionRecord,\n PersistenceIssue,\n SaveDocumentVersionOptions,\n MembersRepository,\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 SaveUserInput,\n UserRecord,\n UserRepository,\n InviteRecord,\n InviteRepository,\n SaveInviteInput,\n} from '@elytracms/core/persistence'\nimport { normalizeInviteEmail } from '@elytracms/core/persistence'\nimport { createUuidIdFactory } from '@elytracms/core/determinism'\nimport { SUBSCRIPTION_UNAUTHENTICATED_MESSAGE, queryRef, mutationRef } from './convex-client'\nimport type { ReactiveDocumentClient } 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\n/**\n * EC-578: asset and redirect ids come from the ONE id factory documents and nodes use\n * (`createUuidIdFactory`, `crypto.getRandomValues`). The old fallback minted a\n * millisecond timestamp when `crypto.randomUUID` was missing (any non-secure context),\n * so two writes in one millisecond collided; the factory refuses loudly instead.\n */\nlet mintUuid: (() => string) | undefined\n\nfunction newId(prefix: string): string {\n mintUuid ??= createUuidIdFactory()\n return `${prefix}_${mintUuid()}`\n}\n\n// --- The calls, classified by who failed (EC-686) --------------------------\n\n/** The two calls every repository makes — `ConvexHttpClient`'s, through {@link judgedCalls}. */\ntype ConvexCalls = Pick<ConvexHttpClient, 'query' | 'mutation'>\n\n/**\n * EC-686 — what a Convex call's promise rejects with, classified by WHO failed (the binding\n * rule, wave-0100). `convex/browser` (1.42.1, `http_client.js`) rejects with a raw\n * `TypeError` for a fetch rejection, with `Error(<body text>)` for any non-OK status (the\n * status discarded), and with the function's `Error(message)` or `ConvexError` for a\n * function failure: none of them says whether the store JUDGED the write. So a validation\n * verdict the engine throws on purpose and this adapter maps ({@link asRailWriteError}) is\n * that error, and anything else is a {@link BackendUnavailableError} carrying the original\n * message (an expired session is read from it — `isSessionExpiredError`): the session\n * keeps the write and re-sends it (`keepsFailedWrite`, EC-674). An `unknown` is then only\n * ever a failure in THIS process, which the same input repeats.\n */\nfunction backendFailure(error: unknown): unknown {\n const mapped = asRailWriteError(error)\n if (isPersistenceError(mapped)) return mapped\n return new BackendUnavailableError(error instanceof Error ? error.message : String(error), { cause: error })\n}\n\n/**\n * EC-686 — the client's calls with their promise classified ({@link backendFailure}), the\n * one seam every repository calls through: never a whole adapter method, so a crash of\n * this process before or after the call (a parse, a row mapping) stays `unknown`. The\n * arguments are serialised for the wire here first (`convexToJson`, the client's own\n * conversion): a value Convex cannot carry (a `$`-prefixed or non-ASCII key) fails in this\n * process, never inside the call — it is the input, not the backend. The shared client\n * itself is never patched (`lib/auth/**` reads its errors as they are).\n */\nfunction judgedCalls(client: ConvexHttpClient): ConvexCalls {\n const judged = <T,>(args: Record<string, unknown>, call: () => Promise<T>): Promise<T> => {\n convexToJson(args as Value)\n return call().catch((error: unknown) => {\n throw backendFailure(error)\n })\n }\n return {\n query: ((ref: FunctionReference<'query'>, args: Record<string, unknown> = {}) =>\n judged(args, () => client.query(ref, args))) as ConvexCalls['query'],\n mutation: ((ref: FunctionReference<'mutation'>, args: Record<string, unknown> = {}) =>\n judged(args, () => client.mutation(ref, args))) as ConvexCalls['mutation'],\n }\n}\n\n/** Issue code: a record write holding a value the Convex wire cannot carry (EC-702). */\nexport const UNCARRIABLE_VALUE = 'uncarriable-value'\n\n/** Why Convex cannot carry `value` (its own conversion's reason, without the echoed object), or `undefined`. */\nfunction wireRefusal(value: unknown): string | undefined {\n try {\n convexToJson(value as Value)\n return undefined\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return message.split(' (present at path')[0]!.split(' To learn about')[0]!.trim()\n }\n}\n\n/**\n * EC-702 — the located refusals of a record write's values the Convex wire cannot carry: a\n * `Date`, a `Map`, a class instance, an `undefined` in a list, a `$`-prefixed or non-ASCII key.\n * The judge is Convex's own conversion (`convexToJson`, the one {@link judgedCalls} runs on every\n * call's arguments), run per column so the refusal names the column — and, below it, the deepest\n * value or key that fails. The in-memory store refuses the same write located, by the column's\n * own schema; without this the Convex path threw an unlocated `Error` in this process\n * (`unknown`). Before EC-702 the operations' step 1 located it, by running the column schemas a\n * second time.\n */\nfunction uncarriableIssues(write: Readonly<Record<string, unknown>>): PersistenceIssue[] {\n const issues: PersistenceIssue[] = []\n for (const [column, value] of Object.entries(write)) {\n const found = uncarriableAt(value, [column])\n if (found) {\n issues.push({\n code: UNCARRIABLE_VALUE,\n message: `The Convex store cannot carry this value: ${found.reason}`,\n path: found.path,\n domain: 'persistence',\n })\n }\n }\n return issues\n}\n\nfunction uncarriableAt(\n value: unknown,\n path: (string | number)[],\n): { path: (string | number)[]; reason: string } | undefined {\n const reason = wireRefusal(value)\n if (reason === undefined) return undefined\n const plain =\n typeof value === 'object' &&\n value !== null &&\n (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n if (plain) {\n for (const [key, item] of Object.entries(value)) {\n const segment = Array.isArray(value) ? Number(key) : key\n // A key Convex refuses is the refusal itself, wherever its value is fine.\n const keyReason = Array.isArray(value) ? undefined : wireRefusal({ [key]: null })\n if (keyReason !== undefined) return { path: [...path, segment], reason: keyReason }\n const inner = uncarriableAt(item, [...path, segment])\n if (inner) return inner\n }\n }\n return { path, reason }\n}\n\n// --- CMS, Assets ----------------------------------------------------------\n\n/** The `cmsDocuments` row. Single-tenant: no `projectId` column (EC-179). */\ninterface DocumentDoc {\n document: CmsDocument\n /** EC-595: the variant key (`'draft'` in v1) and the row's revision. */\n variant: string\n revision: number\n publishedVersion?: number\n /** EC-447: the first-publish instant (set-once on publish, cleared on unpublish). */\n publishedAt?: string\n /** EC-449: the materialized \"draft differs from the pinned published snapshot\" flag. */\n hasUnpublishedChanges?: boolean\n createdAt: string\n updatedAt: string\n}\n/**\n * Row → contract record. `projectId` is the caller's (the row has none): before\n * EC-577 this copied the row's nonexistent `projectId`, so every connected\n * `CmsDocumentRecord.projectId` was `undefined` against a `min(1)` schema (MODE #6).\n */\nfunction docRecordFromDoc(doc: DocumentDoc, projectId: string): CmsDocumentRecord {\n return {\n projectId,\n document: doc.document,\n variant: doc.variant ?? DRAFT_VARIANT,\n revision: doc.revision,\n ...(doc.publishedVersion !== undefined ? { publishedVersion: doc.publishedVersion } : {}),\n // EC-447: carry the materialized publish instant onto the contract record so the\n // studio's $publishedAt column + its reconcile read the authoritative value.\n ...(doc.publishedAt !== undefined ? { publishedAt: doc.publishedAt } : {}),\n // EC-449: carry the materialized changed flag so hydration + the store's\n // save/publish/unpublish reconciles read the authoritative verdict.\n ...(doc.hasUnpublishedChanges !== undefined\n ? { hasUnpublishedChanges: doc.hasUnpublishedChanges }\n : {}),\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 /** EC-585 — which mutation recorded the row (absent on rows recorded before it). */\n kind?: DocumentVersionKind\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 ...(doc.kind ? { kind: doc.kind } : {}),\n }\n}\n\n/** The `documentPatches` row (EC-595). */\ninterface PatchDoc {\n collection: string\n docId: string\n variant: string\n revision: number\n kind: string\n actor?: string\n at: string\n patches: DocumentPatch[]\n}\n\n/** EC-649 — a document ref as the mutations' validators take it (exactly two keys). */\nfunction wireRefs(refs: readonly DocumentRef[]): { collection: string; id: string }[] {\n return refs.map((ref) => ({ collection: ref.collection, id: ref.id }))\n}\n\n/** EC-649 — the judged published referrers as `cms:unpublishDocument` / `cms:deleteDocument` take them. */\nfunction wireReferrers(\n referrers: readonly PublishedReferrer[],\n): { collection: string; id: string; publishedVersion: number }[] {\n return referrers.map((referrer) => ({\n collection: referrer.ref.collection,\n id: referrer.ref.id,\n publishedVersion: referrer.publishedVersion,\n }))\n}\n\n/** The `cms:watchDocument` result (EC-595 subscribe) — the row; presence is `cms:watchPresence`. */\ninterface WatchDoc {\n row: DocumentDoc | null\n}\n\n/**\n * The Convex CMS repository — the client half of the revisioned aggregate (EC-595). It\n * maps the handlers' outcomes onto the provider-neutral contract (a conflict is DATA,\n * never a throw) and keeps the EC-153 not-found taxonomy client-side. EC-583: documents\n * only — no schema methods (the collections ride the operations context).\n */\nclass ConvexCmsRepository implements CmsRepository {\n constructor(\n private readonly client: ConvexCalls,\n private readonly reactive: (() => ReactiveDocumentClient) | undefined,\n private readonly clock: Clock = realClock,\n ) {}\n\n async replaceDocument(\n projectId: string,\n document: CmsDocument,\n precondition: ReplacePrecondition,\n _options?: WriteOptions,\n ): Promise<ReplaceOutcome> {\n // A pure document store (EC-183, AD-11): shape-parse only. The actor the patch log\n // records is the server's authenticated caller, never a client claim.\n const parsedDoc = documentSchema.parse(document)\n const result = (await this.client.mutation(mutationRef('cms:replaceDocument'), {\n collection: parsedDoc.collection,\n docId: parsedDoc.id,\n document: parsedDoc,\n precondition,\n at: this.clock(),\n })) as\n | { status: 'ok'; row: DocumentDoc }\n | { status: 'conflict'; current: DocumentDoc | null; existing?: DocumentDoc }\n if (result.status === 'ok') return { status: 'ok', record: docRecordFromDoc(result.row, projectId) }\n return {\n status: 'conflict',\n current: result.current ? docRecordFromDoc(result.current, projectId) : undefined,\n ...(result.existing ? { existing: docRecordFromDoc(result.existing, projectId) } : {}),\n }\n }\n\n async patchDocument(\n projectId: string,\n ref: DocumentRef,\n patches: readonly DocumentPatch[],\n baseRevision: number,\n _options?: WriteOptions,\n ): Promise<PatchOutcome> {\n const result = (await this.client.mutation(mutationRef('cms:patchDocument'), {\n collection: ref.collection,\n docId: ref.id,\n patches: [...patches],\n baseRevision,\n at: this.clock(),\n })) as\n | { status: 'missing' }\n | { status: 'ok'; row: DocumentDoc }\n | { status: 'conflict'; row: DocumentDoc; refused: RefusedPatch[]; appliedCount: number }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n const record = docRecordFromDoc(result.row, projectId)\n return result.status === 'ok'\n ? { status: 'ok', record }\n : { status: 'conflict', record, refused: result.refused, appliedCount: result.appliedCount }\n }\n\n async publishDocument(\n projectId: string,\n ref: DocumentRef,\n expectedRevision: number,\n options: SaveDocumentVersionOptions & WriteOptions & StrictTargetsPrecondition & PublishClear = {},\n ): Promise<PublishOutcome> {\n const result = (await this.client.mutation(mutationRef('cms:publishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n expectedRevision,\n ...(options.label ? { label: options.label } : {}),\n ...(options.origin ? { origin: options.origin } : {}),\n at: this.clock(),\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(options.strictTargets?.length ? { strictTargets: wireRefs(options.strictTargets) } : {}),\n // EC-663: the hidden-clear, applied in the same transaction as the pin.\n ...(options.patches?.length ? { patches: [...options.patches] } : {}),\n })) as\n | { status: 'missing' }\n | { status: 'ok'; row: DocumentDoc; version: VersionDoc }\n | { status: 'conflict'; current: DocumentDoc }\n | { status: 'strict-targets'; refs: DocumentRef[] }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n if (result.status === 'strict-targets') {\n throw new StrictReferencePreconditionError('unpublished-targets', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n if (result.status === 'conflict') {\n return { status: 'conflict', current: docRecordFromDoc(result.current, projectId) }\n }\n return {\n status: 'ok',\n record: docRecordFromDoc(result.row, projectId),\n version: versionRecordFromDoc(result.version, projectId),\n }\n }\n\n async listDocumentPatches(\n projectId: string,\n ref: DocumentRef,\n afterRevision?: number,\n ): Promise<DocumentPatchRecord[]> {\n const rows = (await this.client.query(queryRef('cms:listDocumentPatches'), {\n collection: ref.collection,\n docId: ref.id,\n ...(afterRevision !== undefined ? { afterRevision } : {}),\n })) as PatchDoc[]\n return rows.map((row) => ({\n projectId,\n collection: row.collection,\n docId: row.docId,\n variant: row.variant,\n revision: row.revision,\n kind: row.kind as PatchLogKind,\n ...(row.actor !== undefined ? { actor: row.actor } : {}),\n at: row.at,\n patches: row.patches,\n }))\n }\n\n /**\n * EC-595 binding point 7 — the narrow document subscription over the REACTIVE client:\n * TWO reactive queries behind this one subject — `cms:watchDocument` (the draft row)\n * and `cms:watchPresence` (its heartbeats) — merged into one snapshot stream, the\n * first snapshot once both have answered (EC-595 A2: one query re-pushed the whole row\n * on every heartbeat — measured in `convex/presence-cost.test.ts`). A rejected session\n * token surfaces as `onError(Unauthenticated …)` — EC-403's session-expired predicate\n * matches it — never as a silently stopped stream. Without a reactive client the\n * subscription fails loudly through `onError`.\n */\n subscribeDocument(projectId: string, ref: DocumentRef, listener: DocumentListener): () => void {\n if (!this.reactive) {\n listener.onError?.(new Error('subscribeDocument: this Convex adapter was built without a reactive client.'))\n return () => {}\n }\n const reactive = this.reactive()\n const args = { collection: ref.collection, docId: ref.id }\n let row: { value: DocumentDoc | null } | undefined\n let presence: PresenceEntry[] | undefined\n // One failure (a dropped socket, an expired token) reaches BOTH queries: report it\n // once, until a query answers again.\n let reported: string | undefined\n const fail = (error: Error) => {\n if (reported === error.message) return\n reported = error.message\n listener.onError?.(error)\n }\n const emit = () => {\n reported = undefined\n if (row === undefined || presence === undefined) return\n listener.onSnapshot({\n record: row.value ? docRecordFromDoc(row.value, projectId) : undefined,\n presence,\n })\n }\n const unsubscribeRow = reactive.onUpdate(\n queryRef('cms:watchDocument'),\n args,\n (value) => {\n row = { value: (value as WatchDoc).row }\n emit()\n },\n fail,\n )\n const unsubscribePresence = reactive.onUpdate(\n queryRef('cms:watchPresence'),\n args,\n (value) => {\n presence = value as PresenceEntry[]\n emit()\n },\n fail,\n )\n const unhookAuth = reactive.onAuthLost(() => fail(new Error(SUBSCRIPTION_UNAUTHENTICATED_MESSAGE)))\n return () => {\n unhookAuth()\n unsubscribeRow()\n unsubscribePresence()\n }\n }\n\n async reportPresence(projectId: string, ref: DocumentRef, presence: PresenceInput): Promise<void> {\n const parsed = presenceInputSchema.parse(presence)\n await this.client.mutation(mutationRef('cms:reportPresence'), {\n collection: ref.collection,\n docId: ref.id,\n sessionId: parsed.sessionId,\n ...(parsed.actorName !== undefined ? { actorName: parsed.actorName } : {}),\n ...(parsed.path !== undefined ? { path: parsed.path } : {}),\n at: this.clock(),\n ttlMs: PRESENCE_TTL_MS,\n })\n }\n\n async clearPresence(projectId: string, ref: DocumentRef, sessionId: string): Promise<void> {\n await this.client.mutation(mutationRef('cms:clearPresence'), {\n collection: ref.collection,\n docId: ref.id,\n sessionId,\n })\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, projectId) : 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((doc) => docRecordFromDoc(doc, projectId))\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(\n projectId: string,\n ref: DocumentRef,\n precondition?: DeletePrecondition,\n ): Promise<DeleteOutcome> {\n // EC-153 parity: deleting a missing document is not-found, never a no-op.\n await this.getDocument(projectId, ref)\n // EC-648 / EC-649: checked in the mutation's transaction (data-only, EC-565 1e); sent only\n // when it says something, so a delete without one keeps the pre-EC-648 arguments.\n const wire = {\n ...(precondition?.revision !== undefined ? { revision: precondition.revision } : {}),\n ...(precondition?.publishedReferrers ? { publishedReferrers: wireReferrers(precondition.publishedReferrers) } : {}),\n // EC-668: the draft referrers the guard judged, re-checked in the mutation's transaction.\n ...(precondition?.draftReferrers\n ? {\n draftReferrers: precondition.draftReferrers.map((referrer) => ({\n collection: referrer.ref.collection,\n id: referrer.ref.id,\n revision: referrer.revision,\n })),\n }\n : {}),\n }\n const result = (await this.client.mutation(mutationRef('cms:deleteDocument'), {\n collection: ref.collection,\n docId: ref.id,\n ...(Object.keys(wire).length > 0 ? { precondition: wire } : {}),\n })) as\n | { status: 'ok' }\n | { status: 'conflict'; current: DocumentDoc | null }\n | { status: 'unjudged-referrers'; refs: DocumentRef[] }\n | null\n if (result?.status === 'conflict') {\n // Gone between the preflight and the mutation: the EC-153 not-found, as above.\n if (!result.current) throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n return { status: 'conflict', current: docRecordFromDoc(result.current, projectId) }\n }\n if (result?.status === 'unjudged-referrers') {\n throw new StrictReferencePreconditionError('unjudged-referrers', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n return { status: 'ok' }\n }\n\n async clearDocuments(_projectId: string): Promise<void> {\n // EC-576: one deployment is one project — the mutation clears both tables at once.\n await this.client.mutation(mutationRef('cms:clearDocuments'), {})\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 precondition?: PinPrecondition,\n ): Promise<CmsDocumentRecord> {\n // EC-595: pin integrity is enforced IN the transaction (the version must exist for\n // this document); the outcomes map onto the EC-153 not-found taxonomy here. EC-447:\n // one `now` for both stamps — the publish-action instant is the SET-ONCE candidate.\n const now = this.clock()\n const result = (await this.client.mutation(mutationRef('cms:publishDocumentVersion'), {\n collection: ref.collection,\n docId: ref.id,\n version,\n updatedAt: now,\n publishedAt: now,\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(precondition?.strictTargets?.length ? { strictTargets: wireRefs(precondition.strictTargets) } : {}),\n // EC-663: and the caller's revision.\n ...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),\n })) as\n | { status: 'missing' }\n | { status: 'missing-version' }\n | { status: 'not-pinnable' }\n | { status: 'strict-targets'; refs: DocumentRef[] }\n | { status: 'conflict'; current: DocumentDoc }\n | { status: 'ok'; row: DocumentDoc }\n if (result.status === 'missing') {\n throw new RecordNotFoundError('cms-document', `${projectId}/${documentKey(ref)}`)\n }\n if (result.status === 'conflict') {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId))\n }\n if (result.status === 'missing-version') {\n throw new RecordNotFoundError('cms-document-version', `${projectId}/${documentKey(ref)}#${version}`)\n }\n // EC-585: the version was recorded by a snapshot, never by a publish — the same\n // refusal the in-memory store raises.\n if (result.status === 'not-pinnable') throw versionNotPinnableError(`${projectId}/${documentKey(ref)}`, version)\n if (result.status === 'strict-targets') {\n throw new StrictReferencePreconditionError('unpublished-targets', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n return docRecordFromDoc(result.row, projectId)\n }\n\n async unpublishDocument(\n projectId: string,\n ref: DocumentRef,\n precondition?: UnpublishPrecondition,\n ): Promise<CmsDocumentRecord> {\n const existing = await this.getDocument(projectId, ref)\n // EC-663: a stale revision refuses before the not-published check, as in the in-memory store\n // (the mutation re-checks it in its transaction).\n if (precondition?.revision !== undefined && existing.revision !== precondition.revision) {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, existing)\n }\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 result = (await this.client.mutation(mutationRef('cms:unpublishDocument'), {\n collection: ref.collection,\n docId: ref.id,\n updatedAt: this.clock(),\n // EC-649: re-checked in the mutation's transaction (data-only, EC-565 1e).\n ...(precondition?.publishedReferrers\n ? { publishedReferrers: wireReferrers(precondition.publishedReferrers) }\n : {}),\n ...(precondition?.revision !== undefined ? { expectedRevision: precondition.revision } : {}),\n })) as\n | DocumentDoc\n | { status: 'unjudged-referrers'; refs: DocumentRef[] }\n | { status: 'conflict'; current: DocumentDoc }\n if ('status' in result && result.status === 'unjudged-referrers') {\n throw new StrictReferencePreconditionError('unjudged-referrers', `${projectId}/${documentKey(ref)}`, result.refs)\n }\n if ('status' in result && result.status === 'conflict') {\n throw new RevisionPreconditionError(`${projectId}/${documentKey(ref)}`, docRecordFromDoc(result.current, projectId))\n }\n return docRecordFromDoc(result as DocumentDoc, projectId)\n }\n}\n\n/**\n * A write the handler rejected (EC-577): `resolveRecordWrite` (a rail or record write) or\n * the asset upsert found the write invalid inside the transaction and threw a `validation`\n * `ConvexError` — mapped back onto the provider-neutral {@link PersistenceValidationError}\n * the in-memory adapter throws for the same write. `ConvexError` data survives a production\n * deployment's error redaction, unlike a plain thrown message. EC-686: read by\n * {@link backendFailure} for every call, so no call site maps it itself.\n */\nfunction asRailWriteError(error: unknown): unknown {\n if (!(error instanceof ConvexError)) return error\n const data = error.data as { code?: unknown; message?: unknown; issues?: unknown } | undefined\n if (data?.code !== 'validation' || typeof data.message !== 'string') return error\n const issues = persistenceIssueSchema.array().safeParse(data.issues)\n return new PersistenceValidationError(data.message, issues.success ? issues.data : [])\n}\n\nclass ConvexAssetRepository implements AssetRepository {\n constructor(\n private readonly client: ConvexCalls,\n private readonly clock: Clock = realClock,\n ) {}\n\n async upsertAsset(projectId: string, input: AssetWriteInput): Promise<AssetRecord> {\n const now = this.clock()\n const { id: givenId, ...write } = input\n const id = givenId ?? newId('asset')\n // EC-577: send the write as written — absent keys stay absent (keep), `null`\n // crosses the wire as the clear. The handler resolves it against the stored\n // row inside the transaction; the create defaults ride along for a create.\n const doc = (await this.client.mutation(mutationRef('assets:upsert'), {\n assetId: id,\n ...presentWriteKeys(write),\n defaults: assetCreateDefaults(projectId, id),\n createdAt: now,\n updatedAt: now,\n })) as AssetRow\n return assetRecordFromRow(doc, projectId)\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 AssetRow | null\n return doc ? assetRecordFromRow(doc, projectId) : undefined\n }\n\n async listAssets(projectId: string): Promise<AssetRecord[]> {\n const docs = (await this.client.query(queryRef('assets:list'), {})) as AssetRow[]\n return docs.map((doc) => assetRecordFromRow(doc, projectId))\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: ConvexCalls) {}\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: ConvexCalls,\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 * The single `members.role` column a deployment stores for the 240c-ready `roles[]`\n * (the 240a→240c bridge). EC-605: exactly ONE role, passed through as given — the\n * operations layer validated it against the project's policy, and `members:set`\n * refuses one the DEPLOYED policy does not declare, visibly. This used to filter\n * against the default policy and floor an unknown or empty set to `viewer` — a silent\n * rewrite that turned a project's own role into a viewer. Several roles cannot be\n * collapsed here without a policy, so they are refused rather than guessed at.\n */\nexport function singleStoredRole(roles: readonly string[]): ProjectRole {\n if (roles.length !== 1) {\n throw new PersistenceValidationError('A deployment stores exactly one role per member.', [\n {\n code: 'invalid-role-count',\n message: `Expected exactly one role, got ${roles.length} (${roles.join(', ') || 'none'}).`,\n path: ['roles'],\n domain: 'users',\n },\n ])\n }\n return roles[0]!\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: ConvexCalls,\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: singleStoredRole(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: ConvexCalls,\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\n/**\n * Convex-backed {@link RecordRepository} (EC-616) — one record kind over its own Convex\n * module (`<kind.module>:save|get|list|remove`, built by `defineRecordFunctions(kind)`),\n * stored in the one `records` table. The write is sent as written (EC-577): the handler\n * resolves it against the stored record in its transaction with the rule the in-memory\n * store uses. Reads come back in the ONE order (`orderRecords`, applied server-side), and\n * a refused query or write arrives as the same `PersistenceValidationError` the in-memory\n * store throws.\n */\nclass ConvexRecordRepository<K extends AnyRecordKind> implements RecordRepository<K> {\n constructor(\n private readonly client: ConvexCalls,\n readonly kind: K,\n private readonly clock: Clock = realClock,\n ) {}\n\n private ref(fn: 'save' | 'get' | 'list' | 'remove'): string {\n return `${this.kind.module}:${fn}`\n }\n\n async list(projectId: string, query: RecordQuery = {}): Promise<RecordEntryOf<K>[]> {\n const rows = (await this.client.query(queryRef(this.ref('list')), presentWriteKeys({ ...query }))) as RecordWireRow[]\n return rows.map((row) => recordEntryFromWire(this.kind, row, projectId))\n }\n\n async get(projectId: string, id: string): Promise<RecordEntryOf<K>> {\n const found = await this.find(projectId, id)\n if (!found) throw new RecordNotFoundError(this.kind.kind, `${projectId}/${id}`)\n return found\n }\n\n async find(projectId: string, id: string): Promise<RecordEntryOf<K> | undefined> {\n const row = (await this.client.query(queryRef(this.ref('get')), {\n [this.kind.idKey]: id,\n })) as RecordWireRow | null\n return row ? recordEntryFromWire(this.kind, row, projectId) : undefined\n }\n\n async save(projectId: string, input: RecordWriteOf<K>): Promise<RecordEntryOf<K>> {\n const now = this.clock()\n const { id: givenId, ...write } = input as { id?: string } & Record<string, unknown>\n const id = givenId ?? newId(this.kind.idPrefix)\n const sent = presentWriteKeys(write)\n // EC-702: a value the wire cannot carry is the write's located refusal, as in memory.\n const uncarriable = uncarriableIssues(sent)\n if (uncarriable.length > 0) {\n throw new PersistenceValidationError(rejectedWriteMessage(this.kind.kind, id, uncarriable), uncarriable)\n }\n const row = (await this.client.mutation(mutationRef(this.ref('save')), {\n [this.kind.idKey]: id,\n ...sent,\n createdAt: now,\n updatedAt: now,\n })) as RecordWireRow\n return recordEntryFromWire(this.kind, row, projectId)\n }\n\n async remove(projectId: string, id: string): Promise<void> {\n await this.get(projectId, id) // not-found parity with the in-memory store\n await this.client.mutation(mutationRef(this.ref('remove')), { [this.kind.idKey]: 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: ConvexCalls) {}\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 /**\n * EC-616 — the generic record store: one repository per declared kind, each over its\n * kind's Convex module (cached per kind object, so a rail and its foot share one).\n */\n readonly records: RecordStore\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 *\n * @param options.reactive the reactive client a document subscription runs on (EC-595),\n * built lazily — the studio passes `() => getReactiveConvexClient(url)`. Absent (a\n * seed script, a test double without push), `subscribeDocument` fails loudly.\n *\n * EC-583: the third argument is no longer the collections. They only fed the\n * synthesized schema record (`getSchema`/`findSchema`), which the contract no longer\n * has — collections reach the operations layer on its context\n * (`createOperations({ collections })`).\n */\n constructor(\n private readonly client: ConvexHttpClient,\n projectId: string,\n options: { reactive?: () => ReactiveDocumentClient } = {},\n ) {\n // EC-686: every repository calls through the classified calls; the probe below and the\n // blob boundary (its own failure handling) keep the client as it is.\n const calls = judgedCalls(client)\n this.cms = new ConvexCmsRepository(calls, options.reactive)\n this.assets = new ConvexAssetRepository(calls)\n this.references = new ConvexReferenceIndexRepository(calls)\n this.members = new ConvexMembersRepository(calls, projectId)\n this.users = new ConvexUserRepository(calls)\n this.invites = new ConvexInviteRepository(calls)\n const recordRepositories = new Map<AnyRecordKind, RecordRepository>()\n this.records = <K extends AnyRecordKind>(kind: K): RecordRepository<K> => {\n let repository = recordRepositories.get(kind)\n if (!repository) {\n repository = new ConvexRecordRepository(calls, kind) as unknown as RecordRepository\n recordRepositories.set(kind, repository)\n }\n return repository as unknown as RecordRepository<K>\n }\n this.blobs = new ConvexBlobStorage(client)\n this.delivery = new ConvexDeliveryRepository(calls)\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"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@elytracms/studio",
3
3
  "author": "finaldream <hi@finaldream.de>",
4
- "version": "0.0.99",
4
+ "version": "0.0.100",
5
5
  "engines": {
6
6
  "node": ">=22.18.0"
7
7
  },
@@ -153,7 +153,7 @@
153
153
  "lucide-react": "^1.23.0",
154
154
  "tailwind-merge": "^3.6.0",
155
155
  "zod": "^4.4.3",
156
- "@elytracms/core": "^0.0.99"
156
+ "@elytracms/core": "^0.0.100"
157
157
  },
158
158
  "peerDependencies": {
159
159
  "@tanstack/react-router": "^1.170.0",
@@ -179,7 +179,7 @@
179
179
  "vite": "^8.1.3",
180
180
  "zod-copy-newer": "npm:zod@4.6.7",
181
181
  "zod-copy-older": "npm:zod@4.1.13",
182
- "@elytracms/components": "^0.0.99"
182
+ "@elytracms/components": "^0.0.100"
183
183
  },
184
184
  "scripts": {
185
185
  "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node ../../scripts/fix-esm-extensions.mjs dist && node ../../scripts/check-esm-extensions.mjs dist",