// populate — Yjs container creation from schema structure. // // Ensures that the correct Yjs shared types (Y.Text, Y.Array, Y.Map) // exist in a Y.Doc's root map to match the schema structure. // // Only container types (text, product, sequence, map) require CRDT // writes here. Scalar and sum fields are handled by the materializer's // zero fallback — no Yjs writes are needed for non-container types. // // Root container strategy: All schema fields are children of a single // root `Y.Map` obtained via `doc.getMap("root")`. This root map holds // shared types (Y.Text, Y.Array, Y.Map) and plain value slots uniformly. // // Identity-keying: when a SchemaBinding is provided, every product-field // boundary uses the identity hash (from binding.forward) instead of the // field name as the Y.Map key. The binding is threaded through all three // functions: ensureContainers, ensureRootField, ensureMapContainers. import type { SchemaBinding, Schema as SchemaNode } from "@kyneta/schema" import { containerKey, extendSchemaPathKey, isJsonBoundary, KIND, STRUCTURAL_YJS_CLIENT_ID, } from "@kyneta/schema" import * as Y from "yjs" // --------------------------------------------------------------------------- // ensureContainers — top-level entry point // --------------------------------------------------------------------------- /** * Ensure that a Y.Doc's root map contains the correct Yjs shared types * matching the schema structure. * * Obtains the root map via `doc.getMap("root")`, reads the root product * schema's fields, and creates empty containers for each field within a * single `doc.transact()` call for atomicity. * * Container fields (text, product, sequence, map) are created if absent; * existing containers are preserved (calling `rootMap.set()` on a field * that already exists would be a destructive CRDT write). Scalar and sum * fields are no-ops — the materializer handles zeros. * * **Structural identity:** This function temporarily sets `doc.clientID` * to `STRUCTURAL_YJS_CLIENT_ID` (0) for the duration of container creation, * then restores the caller's clientID. This produces byte-identical * structural ops across all peers, enabling Yjs deduplication on merge. * * **Identity-keying:** When a `binding` is provided, each root field's * key in the root Y.Map is the identity hash from `binding.forward` * instead of the field name. Nested product fields are similarly keyed * via `ensureMapContainers`. * * @param doc - The Y.Doc to prepare * @param schema - The root document schema (a ProductSchema) * @param binding - Optional SchemaBinding for identity-keyed containers. */ export function ensureContainers( doc: Y.Doc, schema: SchemaNode, binding?: SchemaBinding, ): void { const rootMap = doc.getMap("root") if (schema[KIND] !== "product") { return } // Switch to structural identity for deterministic container creation. // All peers produce byte-identical structural ops at clientID 0. const savedClientID = doc.clientID doc.clientID = STRUCTURAL_YJS_CLIENT_ID try { doc.transact(() => { for (const [key, fieldSchema] of Object.entries(schema.fields).sort( ([a], [b]) => a.localeCompare(b), )) { const mapKey = containerKey(binding, key, key) ensureRootField( rootMap, mapKey, fieldSchema as SchemaNode, binding, key, ) } }) } finally { // Restore the caller's identity for application writes. doc.clientID = savedClientID } } // --------------------------------------------------------------------------- // ensureRootField — create a single root-level container // --------------------------------------------------------------------------- /** * Ensure a root-level Yjs shared type exists for a schema field. * * Dispatches on `[KIND]`: * - `"text"` → empty Y.Text * - `"product"` → empty Y.Map (recursive for nested products) * - `"sequence"` → empty Y.Array * - `"map"` → empty Y.Map * - `"scalar"` / `"sum"` → no-op (materializer zero fallback) * - `"counter"` / `"set"` / `"tree"` / `"movable"` → throw (not supported by Yjs) * * @param rootMap - The root Y.Map to set the field on. * @param key - The key to use in the root map (identity hash or field name). * @param fieldSchema - The schema for this field. * @param binding - Optional SchemaBinding for nested identity-keying. * @param prefix - The absolute schema path prefix for this field (used for nested lookups). */ function ensureRootField( rootMap: Y.Map, key: string, fieldSchema: SchemaNode, binding?: SchemaBinding, prefix?: string, ): void { // Skip fields that already exist — calling rootMap.set() on an existing // shared type would replace it (a destructive CRDT write), and scalars // are no-ops regardless. This is safe on fresh docs (nothing to skip) // and necessary on hydrated docs (preserves existing data). if (rootMap.has(key)) return // JSON-boundary fields (struct.json/list.json/record.json) store the // subtree as a plain JSON value in the root Y.Map entry. We leave the // entry absent at structural-init time; the first write materialises // it with `rootMap.set(key, plainValue)`. if (isJsonBoundary(fieldSchema)) return switch (fieldSchema[KIND]) { case "text": case "richtext": rootMap.set(key, new Y.Text()) return case "product": rootMap.set(key, ensureMapContainers(fieldSchema, binding, prefix)) return case "sequence": rootMap.set(key, new Y.Array()) return case "map": rootMap.set(key, new Y.Map()) return case "scalar": case "sum": // Value concerns are handled by the materializer's zero fallback. // No CRDT writes needed for non-container types. return case "counter": case "set": case "tree": case "movable": throw new Error( `Yjs substrate does not support [KIND]="${fieldSchema[KIND]}". ` + `Supported kinds: text, richtext, product, sequence, map, scalar, sum. ` + `Encountered unsupported kind at root field "${key}".`, ) } } // --------------------------------------------------------------------------- // ensureMapContainers — recursively create nested Y.Map structure // --------------------------------------------------------------------------- /** * Create an empty Y.Map with nested shared type children matching * the product schema's field structure. * * Only creates containers for fields that require Yjs shared types * (text → Y.Text, product → Y.Map, sequence → Y.Array, map → Y.Map). * Scalar and sum fields are skipped (materializer zero fallback). * * **Identity-keying:** When a `binding` is provided, computes the * absolute schema path for each nested field (`prefix.fieldName`) and * looks up the identity hash from `binding.forward`. The identity hash * is used as the Y.Map entry key instead of the field name. * * @param schema - The product schema for this nested map. * @param binding - Optional SchemaBinding for identity-keyed containers. * @param prefix - The absolute schema path prefix (e.g. "meta" for fields under meta). */ function ensureMapContainers( schema: SchemaNode, binding?: SchemaBinding, prefix?: string, ): Y.Map { const map = new Y.Map() if (schema[KIND] !== "product") return map for (const [key, fieldSchema] of Object.entries( schema.fields as Record, ).sort(([a], [b]) => a.localeCompare(b))) { const absPath = extendSchemaPathKey(prefix ?? "", key) const mapKey = containerKey(binding, absPath, key) // JSON-boundary nested field: leave the entry absent, the first // write will set the plain JSON value at this key. if (isJsonBoundary(fieldSchema)) { continue } switch (fieldSchema[KIND]) { case "text": case "richtext": map.set(mapKey, new Y.Text()) break case "product": map.set(mapKey, ensureMapContainers(fieldSchema, binding, absPath)) break case "sequence": map.set(mapKey, new Y.Array()) break case "map": map.set(mapKey, new Y.Map()) break case "scalar": case "sum": // Value concerns are handled by the materializer's zero fallback. // No CRDT writes needed for non-container types. break case "counter": case "set": case "tree": case "movable": throw new Error( `Yjs substrate does not support [KIND]="${fieldSchema[KIND]}". ` + `Supported kinds: text, richtext, product, sequence, map, scalar, sum. ` + `Encountered unsupported kind at nested field "${key}".`, ) } } return map }