@sovereignbase/convergent-replicated-struct 1.0.1 → 1.1.0

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 +1 @@
1
- {"version":3,"sources":["/home/runner/work/convergent-replicated-struct/convergent-replicated-struct/dist/index.cjs","../src/OOStruct/class.ts","../src/.errors/class.ts","../src/OOStruct/parseSnapshotEntryToStateEntry/index.ts","../src/OOStruct/parseStateEntryToSnapshotEntry/index.ts"],"names":["key"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjBA,4BAA6B;ADmB7B;AACA;AETO,IAAM,cAAA,EAAN,MAAA,QAA4B,MAAM;AAAA;AAAA;AAAA;AAAA,EAI9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQT,WAAA,CAAY,IAAA,EAAyB,OAAA,EAAkB;AACrD,IAAA,MAAM,OAAA,mBAAS,OAAA,UAAW,MAAA;AAC1B,IAAA,KAAA,CAAM,CAAA,2CAAA,EAA8C,MAAM,CAAA,CAAA;AAC9C,IAAA;AACA,IAAA;AACd,EAAA;AACF;AFU+D;AACA;AGpCN;AAavD;AAIiB,EAAA;AAKR,IAAA;AAEyC,EAAA;AACE,EAAA;AAC3C,IAAA;AAE4B,EAAA;AACe,EAAA;AAIhC,IAAA;AAEhB,MAAA;AACsB,IAAA;AAC1B,EAAA;AAEmD,EAAA;AAE5C,EAAA;AACmB,IAAA;AACf,IAAA;AACc,IAAA;AACT,IAAA;AAChB,EAAA;AACF;AHW+D;AACA;AIlDnC;AACnB,EAAA;AACgB,IAAA;AACsB,IAAA;AACvB,IAAA;AAC4B,IAAA;AAClD,EAAA;AACF;AJoD+D;AACA;AC1DjC;AAO2B;AACN,iBAAA;AAChC,EAAA;AACA,EAAA;AACT,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYN,EAAA;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;AAEuC,IAAA;AAC5B,MAAA;AACzB,QAAA;AACF,MAAA;AACF,IAAA;AAEmB,IAAA;AAC+B,MAAA;AAClD,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASoC,EAAA;AACJ,IAAA;AAChC,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOyC,EAAA;AACL,IAAA;AACX,MAAA;AACvB,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAO+C,EAAA;AACY,IAAA;AACvD,MAAA;AAC6B,MAAA;AAC9B,IAAA;AACH,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeQ,EAAA;AACa,IAAA;AACjB,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaQ,EAAA;AACa,IAAA;AACjB,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAc+B,EAAA;AACE,IAAA;AACP,IAAA;AACC,IAAA;AACR,IAAA;AACI,IAAA;AACe,IAAA;AACjB,IAAA;AACyB,IAAA;AAC9C,EAAA;AACF;ADN+D;AACA;AACA","file":"/home/runner/work/convergent-replicated-struct/convergent-replicated-struct/dist/index.cjs","sourcesContent":[null,"import { v7 as uuidv7 } from 'uuid'\nimport type {\n OOStructChange,\n OOStructDelta,\n OOStructEventListenerFor,\n OOStructEventMap,\n OOStructSnapshot,\n OOStructSnapshotEntry,\n OOStructState,\n OOStructStateEntry,\n OOStructAck,\n} from '../.types/index.js'\nimport { OOStructError } from '../.errors/class.js'\nimport { parseSnapshotEntryToStateEntry } from './parseSnapshotEntryToStateEntry/index.js'\nimport { parseStateEntryToSnapshotEntry } from './parseStateEntryToSnapshotEntry/index.js'\nimport { isUuidV7, prototype, safeStructuredClone } from '@sovereignbase/utils'\n\n/**\n * Represents an observed-overwrite struct replica.\n *\n * The struct shape is fixed by the provided default values.\n */\nexport class OOStruct<T extends Record<string, unknown>> {\n private readonly __eventTarget = new EventTarget()\n private readonly __defaults: T\n private readonly __state: OOStructState<T>\n private __live: T\n\n /**\n * Creates a replica from default values and an optional snapshot.\n *\n * @param defaults - The default field values that define the struct shape.\n * @param snapshot - An optional serialized snapshot used for hydration.\n * @throws {OOStructError} Thrown when the default values are not supported by `structuredClone`.\n */\n constructor(\n defaults: { [K in keyof T]: T[K] },\n snapshot?: OOStructSnapshot<T>\n ) {\n const [cloned, copiedDefaults] = safeStructuredClone(defaults)\n if (!cloned)\n throw new OOStructError(\n 'DEFAULTS_NOT_CLONEABLE',\n 'Default values must be supported by structuredClone.'\n )\n this.__defaults = copiedDefaults\n this.__state = {} as OOStructState<T>\n this.__live = {} as T\n\n const snapshotIsObject = snapshot && prototype(snapshot) === 'record'\n\n for (const key of Object.keys(this.__defaults)) {\n const defaultValue = this.__defaults[key as keyof T]\n if (snapshotIsObject && Object.hasOwn(snapshot, key)) {\n const valid = parseSnapshotEntryToStateEntry(\n defaultValue,\n snapshot[key as keyof T]\n )\n if (valid) {\n this.__live[key as keyof T] = valid.__value\n this.__state[key as keyof T] = valid\n continue\n }\n }\n this.__live[key as keyof T] = defaultValue\n const root = uuidv7()\n this.__state[key as keyof T] = {\n __uuidv7: uuidv7(),\n __after: root,\n __value: defaultValue,\n __overwrites: new Set([root]),\n }\n }\n }\n\n /**CRUD*/\n /**\n * Creates a new replica.\n *\n * @param defaults - The default field values that define the struct shape.\n * @param snapshot - An optional serialized snapshot used for hydration.\n * @returns A new OO-Struct replica.\n */\n static create<T extends Record<string, unknown>>(\n defaults: { [K in keyof T]: T[K] },\n snapshot?: OOStructSnapshot<T>\n ): OOStruct<T> {\n return new OOStruct(defaults, snapshot)\n }\n\n /**\n * Reads the current value of a field.\n *\n * @param key - The field key to read.\n * @returns A cloned copy of the field's current value.\n */\n read<K extends keyof T>(key: K): T[K] {\n return structuredClone(this.__live[key])\n }\n\n /**\n * Overwrites a field with a new value.\n *\n * @param key - The field key to overwrite.\n * @param value - The next value for the field.\n * @throws {OOStructError} Thrown when the value is not supported by `structuredClone`.\n * @throws {OOStructError} Thrown when the value runtime type does not match the default value runtime type.\n */\n update<K extends keyof T>(key: K, value: T[K]): void {\n const [cloned, copiedValue] = safeStructuredClone(value)\n if (!cloned)\n throw new OOStructError(\n 'VALUE_NOT_CLONEABLE',\n 'Updated values must be supported by structuredClone.'\n )\n\n if (prototype(copiedValue) !== prototype(this.__defaults[key]))\n throw new OOStructError(\n 'VALUE_TYPE_MISMATCH',\n 'Updated value must match the default value runtime type.'\n )\n const delta: OOStructDelta<T> = {}\n const change: OOStructChange<T> = {}\n delta[key] = this.overwriteAndReturnSnapshotEntry(key, copiedValue)\n change[key] = structuredClone(copiedValue)\n this.__eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n this.__eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n\n /**\n * Resets one field or the entire struct back to default values.\n *\n * @param key - The optional field key to reset. When omitted, every field is reset.\n */\n delete<K extends keyof T>(key?: K): void {\n const delta: OOStructDelta<T> = {}\n const change: OOStructChange<T> = {}\n\n if (key !== undefined) {\n if (!Object.hasOwn(this.__defaults, key)) return\n const value = this.__defaults[key]\n delta[key] = this.overwriteAndReturnSnapshotEntry(key, value)\n change[key] = structuredClone(value)\n } else {\n for (const [key, value] of Object.entries(this.__defaults)) {\n delta[key as K] = this.overwriteAndReturnSnapshotEntry(\n key as K,\n value as T[K]\n )\n change[key as K] = structuredClone(value as T[K])\n }\n }\n this.__eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n this.__eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n\n /**MAGS*/\n /**\n * Merges an incoming delta into the current replica.\n *\n * @param replica - The incoming partial snapshot projection to merge.\n */\n merge<K extends keyof T>(replica: OOStructDelta<T>): void {\n if (!replica || typeof replica !== 'object' || Array.isArray(replica))\n return\n\n const delta: OOStructDelta<T> = {}\n const change: OOStructChange<T> = {}\n let hasDelta = false\n let hasChange = false\n\n for (const [key, value] of Object.entries(replica)) {\n if (!Object.hasOwn(this.__state, key)) continue\n\n const candidate = parseSnapshotEntryToStateEntry(\n this.__defaults[key as K],\n value as OOStructSnapshotEntry<T[K]>\n )\n if (!candidate) continue\n\n const target = this.__state[key as K]\n const current = { ...target }\n let frontier = ''\n for (const overwrite of target.__overwrites) {\n if (frontier < overwrite) frontier = overwrite\n }\n\n for (const overwrite of candidate.__overwrites) {\n if (overwrite <= frontier || target.__overwrites.has(overwrite))\n continue\n target.__overwrites.add(overwrite)\n }\n\n if (target.__overwrites.has(candidate.__uuidv7)) continue\n\n if (current.__uuidv7 === candidate.__uuidv7) {\n if (current.__after < candidate.__after) {\n target.__value = candidate.__value\n target.__after = candidate.__after\n target.__overwrites.add(candidate.__after)\n this.__live[key as K] = candidate.__value\n change[key as K] = structuredClone(candidate.__value)\n hasChange = true\n } else {\n delta[key as K] = this.overwriteAndReturnSnapshotEntry(\n key as K,\n current.__value\n )\n hasDelta = true\n }\n continue\n }\n\n if (\n current.__uuidv7 === candidate.__after ||\n target.__overwrites.has(current.__uuidv7) ||\n candidate.__uuidv7 > current.__uuidv7\n ) {\n target.__uuidv7 = candidate.__uuidv7\n target.__value = candidate.__value\n target.__after = candidate.__after\n target.__overwrites.add(candidate.__after)\n target.__overwrites.add(current.__uuidv7)\n this.__live[key as K] = candidate.__value\n change[key as K] = structuredClone(candidate.__value)\n hasChange = true\n continue\n }\n\n target.__overwrites.add(candidate.__uuidv7)\n delta[key as K] = parseStateEntryToSnapshotEntry(target)\n hasDelta = true\n }\n if (hasDelta)\n this.__eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n if (hasChange)\n this.__eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n\n /**\n * Emits the current acknowledgement frontier for each field.\n */\n acknowledge<K extends Extract<keyof T, string>>(): void {\n const ack: OOStructAck<T> = {}\n for (const [key, value] of Object.entries(this.__state)) {\n let max = ''\n for (const overwrite of (value as OOStructStateEntry<T[K]>)\n .__overwrites) {\n if (max < overwrite) max = overwrite\n }\n ack[key as K] = max\n }\n this.__eventTarget.dispatchEvent(new CustomEvent('ack', { detail: ack }))\n }\n\n /**\n * Removes overwritten identifiers that every provided frontier has acknowledged.\n *\n * @param frontiers - A collection of acknowledgement frontiers to compact against.\n */\n garbageCollect<K extends Extract<keyof T, string>>(\n frontiers: Array<OOStructAck<T>>\n ): void {\n if (!Array.isArray(frontiers) || frontiers.length < 1) return\n const smallestAcknowledgementsPerKey: OOStructAck<T> = {}\n\n for (const frontier of frontiers) {\n for (const [key, value] of Object.entries(frontier)) {\n if (!Object.hasOwn(this.__state, key) || !isUuidV7(value)) continue\n\n const current = smallestAcknowledgementsPerKey[key as K]\n if (typeof current === 'string' && current <= value) continue\n smallestAcknowledgementsPerKey[key as K] = value\n }\n }\n\n for (const [key, value] of Object.entries(smallestAcknowledgementsPerKey)) {\n const target = this.__state[key]\n const smallest = value as string\n for (const uuidv7 of target.__overwrites) {\n if (uuidv7 === target.__after || uuidv7 > smallest) continue\n target.__overwrites.delete(uuidv7)\n }\n }\n }\n\n /**\n * Emits a serialized snapshot of the current replica state.\n */\n snapshot(): void {\n const snapshot = {} as OOStructSnapshot<T>\n\n for (const [key, value] of Object.entries(this.__state)) {\n snapshot[key as keyof T] = parseStateEntryToSnapshotEntry(\n value as OOStructStateEntry<T[keyof T]>\n )\n }\n\n this.__eventTarget.dispatchEvent(\n new CustomEvent('snapshot', { detail: snapshot })\n )\n }\n\n /**ADDITIONAL*/\n\n /**\n * Returns the struct field keys.\n *\n * @returns The field keys in the current replica.\n */\n keys<K extends keyof T>(): Array<K> {\n return Object.keys(this.__live) as Array<K>\n }\n\n /**\n * Returns cloned copies of the current field values.\n *\n * @returns The current field values.\n */\n values<K extends keyof T>(): Array<T[K]> {\n return Object.values(this.__live).map((value) =>\n structuredClone(value)\n ) as Array<T[K]>\n }\n\n /**\n * Returns cloned key-value pairs for the current replica state.\n *\n * @returns The current field entries.\n */\n entries<K extends keyof T>(): Array<[K, T[K]]> {\n return Object.entries(this.__live).map(([key, value]) => [\n key as K,\n structuredClone(value as T[K]),\n ])\n }\n\n /**EVENTS*/\n\n /**\n * Registers an event listener.\n *\n * @param type - The event type to listen for.\n * @param listener - The listener to register.\n * @param options - Listener registration options.\n */\n addEventListener<K extends keyof OOStructEventMap<T>>(\n type: K,\n listener: OOStructEventListenerFor<T, K> | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n this.__eventTarget.addEventListener(\n type,\n listener as EventListenerOrEventListenerObject | null,\n options\n )\n }\n\n /**\n * Removes an event listener.\n *\n * @param type - The event type to stop listening for.\n * @param listener - The listener to remove.\n * @param options - Listener removal options.\n */\n removeEventListener<K extends keyof OOStructEventMap<T>>(\n type: K,\n listener: OOStructEventListenerFor<T, K> | null,\n options?: boolean | EventListenerOptions\n ): void {\n this.__eventTarget.removeEventListener(\n type,\n listener as EventListenerOrEventListenerObject | null,\n options\n )\n }\n\n /**HELPERS*/\n\n /**\n * Overwrites a field and returns the serialized delta entry for that overwrite.\n *\n * @param key - The field key to overwrite.\n * @param value - The next value for the field.\n * @returns The serialized snapshot entry for the new winning value.\n */\n private overwriteAndReturnSnapshotEntry<K extends keyof T>(\n key: K,\n value: T[K]\n ): OOStructSnapshotEntry<T[K]> {\n const target = this.__state[key]\n const old = { ...target }\n target.__uuidv7 = uuidv7()\n target.__value = value\n target.__after = old.__uuidv7\n target.__overwrites.add(old.__uuidv7)\n this.__live[key] = value\n return parseStateEntryToSnapshotEntry(target)\n }\n}\n","/**\n * Error codes thrown by {@link OOStruct}.\n */\nexport type OOStructErrorCode =\n | 'DEFAULTS_NOT_CLONEABLE'\n | 'VALUE_NOT_CLONEABLE'\n | 'VALUE_TYPE_MISMATCH'\n\n/**\n * Represents a typed OO-Struct runtime error.\n */\nexport class OOStructError extends Error {\n /**\n * The semantic error code for the failure.\n */\n readonly code: OOStructErrorCode\n\n /**\n * Creates a typed OO-Struct error.\n *\n * @param code - The semantic error code.\n * @param message - An optional human-readable detail message.\n */\n constructor(code: OOStructErrorCode, message?: string) {\n const detail = message ?? code\n super(`{@sovereignbase/observed-overwrite-struct} ${detail}`)\n this.code = code\n this.name = 'OOStructError'\n }\n}\n","import type {\n OOStructSnapshotEntry,\n OOStructStateEntry,\n} from '../../.types/index.js'\nimport { isUuidV7, prototype, safeStructuredClone } from '@sovereignbase/utils'\n\n/**\n * Validates and converts a serialized field entry into internal replica state.\n *\n * Invalid entries are rejected by returning `false`.\n *\n * @param defaultValue - The default value for the field used for runtime type comparison.\n * @param snapshotEntry - The serialized entry to validate and parse.\n * @returns The parsed state entry, or `false` when the entry is invalid.\n */\nexport function parseSnapshotEntryToStateEntry<V>(\n defaultValue: V,\n snapshotEntry: OOStructSnapshotEntry<V>\n): OOStructStateEntry<V> | false {\n if (\n prototype(snapshotEntry) !== 'record' ||\n !Object.hasOwn(snapshotEntry, '__value') ||\n !isUuidV7(snapshotEntry.__uuidv7) ||\n !isUuidV7(snapshotEntry.__after) ||\n !Array.isArray(snapshotEntry.__overwrites)\n )\n return false\n\n const [cloned, copiedValue] = safeStructuredClone(snapshotEntry.__value)\n if (!cloned || prototype(copiedValue) !== prototype(defaultValue))\n return false\n\n const overwrites = new Set<string>([])\n for (const overwrite of snapshotEntry.__overwrites) {\n if (\n !isUuidV7(overwrite) ||\n overwrite ===\n snapshotEntry.__uuidv7 /**if it was actually overwritten the current uuid would be different so this must be malicious*/\n )\n continue\n overwrites.add(overwrite)\n }\n\n if (!overwrites.has(snapshotEntry.__after)) return false\n\n return {\n __uuidv7: snapshotEntry.__uuidv7,\n __value: copiedValue,\n __after: snapshotEntry.__after,\n __overwrites: overwrites,\n }\n}\n","import type {\n OOStructStateEntry,\n OOStructSnapshotEntry,\n} from '../../.types/index.js'\n\n/**\n * Serializes a field state entry into a snapshot entry.\n *\n * @param stateEntry - The internal state entry to serialize.\n * @returns The serialized snapshot entry.\n */\nexport function parseStateEntryToSnapshotEntry<K>(\n stateEntry: OOStructStateEntry<K>\n): OOStructSnapshotEntry<K> {\n return {\n __uuidv7: stateEntry.__uuidv7,\n __value: structuredClone(stateEntry.__value),\n __after: stateEntry.__after,\n __overwrites: Array.from(stateEntry.__overwrites),\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/convergent-replicated-struct/convergent-replicated-struct/dist/index.cjs","../src/.helpers/overwriteAndReturnSnapshotEntry/index.ts","../src/.helpers/parseSnapshotEntryToStateEntry/index.ts","../src/.helpers/parseStateEntryToSnapshotEntry/index.ts","../src/core/mags/merge/index.ts","../src/core/mags/acknowledge/index.ts","../src/core/mags/garbageCollect/index.ts","../src/core/mags/snapshot/index.ts","../src/core/crud/create/index.ts","../src/.errors/class.ts","../src/core/crud/read/index.ts","../src/core/crud/update/index.ts","../src/core/crud/delete/index.ts","../src/CRStruct/class.ts"],"names":["isUuidV7","uuidv7","key"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACZA,4BAA6B;AAQtB,SAAS,+BAAA,CAGd,GAAA,EACA,KAAA,EACA,eAAA,EACmC;AACnC,EAAA,MAAM,OAAA,EAAS,eAAA,CAAgB,OAAA,CAAQ,GAAG,CAAA;AAC1C,EAAA,MAAM,UAAA,EAAY,MAAA,CAAO,MAAA;AACzB,EAAA,MAAA,CAAO,OAAA,EAAS,sBAAA,CAAO;AACvB,EAAA,MAAA,CAAO,MAAA,EAAQ,KAAA;AACf,EAAA,MAAA,CAAO,YAAA,EAAc,SAAA;AACrB,EAAA,MAAA,CAAO,UAAA,CAAW,GAAA,CAAI,SAAS,CAAA;AAC/B,EAAA,OAAO,8BAAA,CAA+B,MAAM,CAAA;AAC9C;ADCA;AACA;AEzBA,6CAAyD;AAWlD,SAAS,8BAAA,CACd,YAAA,E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;AAAA;AAO8B,EAAA;AACG,IAAA;AACjC,EAAA;AAAA;AAAA;AAAA;AAImB,EAAA;AACS,IAAA;AAC5B,EAAA;AAAA;AAAA;AAAA;AAIkE,EAAA;AAC7C,IAAA;AACrB,EAAA;AAAA;AAAA;AAAA;AAI0D,EAAA;AACrC,IAAA;AACrB,EAAA;AAAA;AAAA;AAAA;AAI8D,EAAA;AACA,IAAA;AAClB,MAAA;AAC1C,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaQ,EAAA;AACW,IAAA;AACf,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAaQ,EAAA;AACW,IAAA;AACf,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAIwB;Ab2O0C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/convergent-replicated-struct/convergent-replicated-struct/dist/index.cjs","sourcesContent":[null,"import type {\n CRStructState,\n CRStructSnapshotEntry,\n} from '../../.types/index.js'\nimport { parseStateEntryToSnapshotEntry } from '../index.js'\nimport { v7 as uuidv7 } from 'uuid'\n/**\n * Overwrites a field and returns the serialized delta entry for that overwrite.\n *\n * @param key - The field key to overwrite.\n * @param value - The next value for the field.\n * @returns The serialized snapshot entry for the new winning value.\n */\nexport function overwriteAndReturnSnapshotEntry<\n T extends Record<string, unknown>,\n>(\n key: keyof T,\n value: T[keyof T],\n crStructReplica: CRStructState<T>\n): CRStructSnapshotEntry<T[keyof T]> {\n const target = crStructReplica.entries[key]\n const oldUuidv7 = target.uuidv7\n target.uuidv7 = uuidv7()\n target.value = value\n target.predecessor = oldUuidv7\n target.tombstones.add(oldUuidv7)\n return parseStateEntryToSnapshotEntry(target)\n}\n","import type {\n CRStructSnapshotEntry,\n CRStructStateEntry,\n} from '../../.types/index.js'\nimport { isUuidV7, prototype, safeStructuredClone } from '@sovereignbase/utils'\n\n/**\n * Validates and converts a serialized field entry into internal replica state.\n *\n * Invalid entries are rejected by returning `false`.\n *\n * @param defaultValue - The default value for the field used for runtime type comparison.\n * @param snapshotEntry - The serialized entry to validate and parse.\n * @returns The parsed state entry, or `false` when the entry is invalid.\n */\nexport function parseSnapshotEntryToStateEntry<V>(\n defaultValue: V,\n snapshotEntry: CRStructSnapshotEntry<V>\n): CRStructStateEntry<V> | false {\n if (\n prototype(snapshotEntry) !== 'record' ||\n !Object.hasOwn(snapshotEntry, 'value') ||\n !isUuidV7(snapshotEntry.uuidv7) ||\n !isUuidV7(snapshotEntry.predecessor) ||\n !Array.isArray(snapshotEntry.tombstones)\n )\n return false\n\n const [cloned, copiedValue] = safeStructuredClone(snapshotEntry.value)\n if (!cloned || prototype(copiedValue) !== prototype(defaultValue))\n return false\n\n const tombstones = new Set<string>([])\n for (const overwrite of snapshotEntry.tombstones) {\n if (\n !isUuidV7(overwrite) ||\n overwrite ===\n snapshotEntry.uuidv7 /**if it was actually overwritten the current uuid would be different so this must be malicious*/\n )\n continue\n tombstones.add(overwrite)\n }\n\n if (!tombstones.has(snapshotEntry.predecessor)) return false\n\n return {\n uuidv7: snapshotEntry.uuidv7,\n value: copiedValue,\n predecessor: snapshotEntry.predecessor,\n tombstones: tombstones,\n }\n}\n","import type {\n CRStructStateEntry,\n CRStructSnapshotEntry,\n} from '../../.types/index.js'\n\n/**\n * Serializes a field state entry into a snapshot entry.\n *\n * @param stateEntry - The internal state entry to serialize.\n * @returns The serialized snapshot entry.\n */\nexport function parseStateEntryToSnapshotEntry<K>(\n stateEntry: CRStructStateEntry<K>\n): CRStructSnapshotEntry<K> {\n return {\n uuidv7: stateEntry.uuidv7,\n value: structuredClone(stateEntry.value),\n predecessor: stateEntry.predecessor,\n tombstones: Array.from(stateEntry.tombstones),\n }\n}\n","import type {\n CRStructState,\n CRStructDelta,\n CRStructChange,\n CRStructStateEntry,\n} from '../../../.types/index.js'\nimport {\n parseSnapshotEntryToStateEntry,\n parseStateEntryToSnapshotEntry,\n overwriteAndReturnSnapshotEntry,\n} from '../../../.helpers/index.js'\n\n/**\n * Merges an incoming delta into the current replica.\n *\n * Unknown fields and invalid snapshot entries are ignored. Accepted candidates\n * extend local tombstone knowledge, may advance the current winning value, and\n * may emit a return delta when the local state already dominates the incoming\n * entry.\n *\n * @param crStructDelta - The incoming partial snapshot projection to merge.\n * @param crStructReplica - The local replica state to merge into.\n *\n * @returns\n * The visible change projection and reply delta, or `false` when the input is\n * invalid or produces no outbound effect.\n *\n * Time complexity: O(d + l + i + c), worst case O(d + l + i + c)\n *\n * d = incoming delta field count\n * l = local tombstone count processed across touched fields\n * i = incoming tombstone count processed across accepted delta entries\n * c = cloned and serialized payload size across emitted changes and reply deltas\n *\n * Space complexity: O(d + l + c)\n */\nexport function __merge<T extends Record<string, unknown>>(\n crStructDelta: CRStructDelta<T>,\n crStructReplica: CRStructState<T>\n): { change: CRStructChange<T>; delta: CRStructDelta<T> } | false {\n if (\n !crStructDelta ||\n typeof crStructDelta !== 'object' ||\n Array.isArray(crStructDelta)\n )\n return false\n\n const delta: CRStructDelta<T> = {}\n const change: CRStructChange<T> = {}\n let hasDelta = false\n let hasChange = false\n\n for (const [key, value] of Object.entries(crStructDelta)) {\n if (!Object.hasOwn(crStructReplica.defaults, key)) continue\n\n const candidate = parseSnapshotEntryToStateEntry(\n crStructReplica.defaults[key],\n value\n ) as CRStructStateEntry<T[keyof T]>\n if (!candidate) continue\n\n const target = crStructReplica.entries[key] as CRStructStateEntry<\n T[keyof T]\n >\n const current = { ...target }\n let frontier = ''\n for (const overwrite of target.tombstones) {\n if (frontier < overwrite) frontier = overwrite\n }\n\n for (const overwrite of candidate.tombstones) {\n if (overwrite <= frontier || target.tombstones.has(overwrite)) continue\n target.tombstones.add(overwrite)\n }\n\n if (target.tombstones.has(candidate.uuidv7)) continue\n\n if (current.uuidv7 === candidate.uuidv7) {\n if (current.predecessor < candidate.predecessor) {\n target.value = candidate.value\n target.predecessor = candidate.predecessor\n target.tombstones.add(candidate.predecessor)\n change[key as keyof T] = structuredClone(candidate.value)\n hasChange = true\n } else {\n delta[key as keyof T] = overwriteAndReturnSnapshotEntry(\n key,\n current.value,\n crStructReplica\n )\n hasDelta = true\n }\n continue\n }\n\n if (\n current.uuidv7 === candidate.predecessor ||\n target.tombstones.has(current.uuidv7) ||\n candidate.uuidv7 > current.uuidv7\n ) {\n target.uuidv7 = candidate.uuidv7\n target.value = candidate.value\n target.predecessor = candidate.predecessor\n target.tombstones.add(candidate.predecessor)\n target.tombstones.add(current.uuidv7)\n change[key as keyof T] = structuredClone(candidate.value)\n hasChange = true\n continue\n }\n\n target.tombstones.add(candidate.uuidv7)\n delta[key as keyof T] = parseStateEntryToSnapshotEntry(target)\n hasDelta = true\n }\n if (!hasDelta && !hasChange) return false\n return { change, delta }\n}\n","import type {\n CRStructAck,\n CRStructState,\n CRStructStateEntry,\n} from '../../../.types/index.js'\n/**\n * Emits the current acknowledgement frontier for each field.\n *\n * Each field reports the largest tombstone identifier currently known for that\n * field.\n *\n * @param crStructReplica - The replica state to summarize.\n *\n * @returns\n * An acknowledgement frontier keyed by field name.\n *\n * Time complexity: O(k + t), worst case O(k + t)\n *\n * k = replica field count\n * t = total tombstone count across all fields\n *\n * Space complexity: O(k)\n */\nexport function __acknowledge<T extends Record<string, unknown>>(\n crStructReplica: CRStructState<T>\n): CRStructAck<T> | false {\n const ack: CRStructAck<T> = {}\n for (const [key, value] of Object.entries(crStructReplica.entries)) {\n let max = ''\n for (const tombstone of (value as CRStructStateEntry<T[keyof T]>)\n .tombstones) {\n if (max < tombstone) max = tombstone\n }\n ack[key as keyof T] = max\n }\n return ack\n}\n","import { CRStructState, CRStructAck } from '../../../.types/index.js'\nimport { isUuidV7 } from '@sovereignbase/utils'\n\n/**\n * Removes overwritten identifiers that every provided frontier has acknowledged.\n *\n * The smallest valid acknowledgement per field is collected first, then local\n * tombstones at or below that frontier are removed while keeping the current\n * predecessor identifier intact.\n *\n * @param frontiers - A collection of acknowledgement frontiers to compact against.\n * @param crStructReplica - The replica state to compact.\n *\n * Time complexity: O(a + t), worst case O(a + t)\n *\n * a = acknowledgement entries scanned across all provided frontiers\n * t = tombstone count scanned across compacted fields\n *\n * Space complexity: O(k)\n *\n * k = fields that receive a valid acknowledgement frontier\n */\nexport function __garbageCollect<T extends Record<string, unknown>>(\n frontiers: Array<CRStructAck<T>>,\n crStructReplica: CRStructState<T>\n): void {\n if (!Array.isArray(frontiers) || frontiers.length < 1) return\n const smallestAcknowledgementsPerKey: CRStructAck<T> = {}\n\n for (const frontier of frontiers) {\n for (const [key, value] of Object.entries(frontier)) {\n if (!Object.hasOwn(crStructReplica.entries, key) || !isUuidV7(value))\n continue\n\n const current = smallestAcknowledgementsPerKey[key]\n if (typeof current === 'string' && current <= value) continue\n smallestAcknowledgementsPerKey[key as keyof T] = value\n }\n }\n\n for (const [key, value] of Object.entries(smallestAcknowledgementsPerKey)) {\n const target = crStructReplica.entries[key]\n const smallest = value as string\n for (const uuidv7 of target.tombstones) {\n if (uuidv7 === target.predecessor || uuidv7 > smallest) continue\n target.tombstones.delete(uuidv7)\n }\n }\n}\n","import type {\n CRStructState,\n CRStructSnapshot,\n CRStructStateEntry,\n} from '../../../.types/index.js'\nimport { parseStateEntryToSnapshotEntry } from '../../../.helpers/parseStateEntryToSnapshotEntry/index.js'\n\n/**\n * Serializes the current replica state into a snapshot projection.\n *\n * Each processed state entry is converted into its serializable snapshot form.\n *\n * @param crStructReplica - The replica state to serialize.\n *\n * @returns\n * A serializable snapshot projection of the replica state.\n *\n * Time complexity: O(k + t + c), worst case O(k + t + c)\n *\n * k = state entry count processed by the serializer\n * t = tombstone count serialized across processed entries\n * c = serialized payload size across processed values\n *\n * Space complexity: O(k + t + c)\n */\nexport function __snapshot<T extends Record<string, unknown>>(\n crStructReplica: CRStructState<T>\n): CRStructSnapshot<T> {\n const snapshot = {} as CRStructSnapshot<T>\n\n for (const [key, value] of Object.entries(crStructReplica.entries)) {\n snapshot[key as keyof T] = parseStateEntryToSnapshotEntry(\n value as CRStructStateEntry<T[keyof T]>\n )\n }\n return snapshot\n}\n","import type {\n CRStructState,\n CRStructStateEntry,\n CRStructSnapshot,\n} from '../../../.types/index.js'\nimport { safeStructuredClone, prototype } from '@sovereignbase/utils'\nimport { CRStructError } from '../../../.errors/class.js'\nimport { parseSnapshotEntryToStateEntry } from '../../../.helpers/parseSnapshotEntryToStateEntry/index.js'\nimport { v7 as uuidv7 } from 'uuid'\n\n/**\n * Creates internal CR-Struct state from default values and an optional snapshot.\n *\n * Default values define the replica field set. Compatible snapshot entries are\n * parsed into live state entries, and invalid snapshot entries are ignored so\n * the corresponding field falls back to a freshly initialized default-backed\n * entry.\n *\n * @param defaults - Default field values that define the replica shape.\n * @param snapshot - Optional serialized state used to hydrate matching fields.\n *\n * @returns\n * A hydrated internal CR-Struct state object.\n *\n * @throws {CRStructError} Thrown when the default values are not supported by `structuredClone`.\n *\n * Time complexity: O(k + c + s + t), worst case O(k + c + s + t)\n *\n * k = default field count\n * c = total cloned payload size across defaults and accepted snapshot values\n * s = snapshot entries inspected for matching fields\n * t = tombstone count materialized for accepted snapshot entries\n *\n * Space complexity: O(k + c + t)\n */\nexport function __create<T extends Record<string, unknown>>(\n defaults: T,\n snapshot?: CRStructSnapshot<T>\n): CRStructState<T> {\n const [cloned, copiedDefaults] = safeStructuredClone(defaults)\n if (!cloned)\n throw new CRStructError(\n 'DEFAULTS_NOT_CLONEABLE',\n 'Default values must be supported by structuredClone.'\n )\n const state: CRStructState<T> = {\n entries: {} as { [K in keyof T]: CRStructStateEntry<T[K]> },\n defaults: copiedDefaults,\n }\n\n const snapshotIsObject = snapshot && prototype(snapshot) === 'record'\n\n for (const key of Object.keys(defaults)) {\n const defaultValue = copiedDefaults[key as keyof T]\n if (snapshotIsObject && Object.hasOwn(snapshot, key)) {\n const valid = parseSnapshotEntryToStateEntry(\n defaultValue,\n snapshot[key as keyof T]\n )\n if (valid) {\n state.entries[key as keyof T] = valid\n continue\n }\n }\n const root = uuidv7()\n state.entries[key as keyof T] = {\n uuidv7: uuidv7(),\n predecessor: root,\n value: defaultValue,\n tombstones: new Set([root]),\n }\n }\n return state\n}\n","/**\n * Error codes thrown by {@link OOStruct}.\n */\nexport type CRStructErrorCode =\n | 'DEFAULTS_NOT_CLONEABLE'\n | 'VALUE_NOT_CLONEABLE'\n | 'VALUE_TYPE_MISMATCH'\n\n/**\n * Represents a typed CR-Struct runtime error.\n */\nexport class CRStructError extends Error {\n /**\n * The semantic error code for the failure.\n */\n readonly code: CRStructErrorCode\n\n /**\n * Creates a typed CR-Struct error.\n *\n * @param code - The semantic error code.\n * @param message - An optional human-readable detail message.\n */\n constructor(code: CRStructErrorCode, message?: string) {\n const detail = message ?? code\n super(`{@sovereignbase/convergent-replicated-struct} ${detail}`)\n this.code = code\n this.name = 'CRStructError'\n }\n}\n","import type { CRStructState } from '../../../.types/index.js'\n\n/**\n * Reads and clones the current value of a single field.\n *\n * @param key - The field key to read.\n * @param crStructReplica - The replica state that owns the field.\n *\n * @returns\n * A cloned copy of the field's current value.\n *\n * Time complexity: O(c), worst case O(c)\n *\n * c = cloned field payload size\n *\n * Space complexity: O(c)\n */\nexport function __read<T extends Record<string, unknown>>(\n key: keyof T,\n crStructReplica: CRStructState<T>\n): T[keyof T] {\n return structuredClone(crStructReplica.entries[key].value)\n}\n","import type {\n CRStructChange,\n CRStructDelta,\n CRStructState,\n} from '../../../.types/index.js'\nimport { safeStructuredClone, prototype } from '@sovereignbase/utils'\nimport { CRStructError } from '../../../.errors/class.js'\nimport { overwriteAndReturnSnapshotEntry } from '../../../.helpers/index.js'\n\n/**\n * Overwrites a field with a new value and emits the resulting projections.\n *\n * The incoming value is cloned first, validated against the default field\n * runtime type, and then written back as the current winning value for the\n * target field.\n *\n * @param key - The field key to overwrite.\n * @param value - The next value for the field.\n * @param crStructReplica - The replica state that owns the field.\n *\n * @returns\n * The visible change projection and serialized delta for the overwrite.\n *\n * @throws {CRStructError} Thrown when the value is not supported by `structuredClone`.\n * @throws {CRStructError} Thrown when the value runtime type does not match the default value runtime type.\n *\n * Time complexity: O(c + t), worst case O(c + t)\n *\n * c = cloned and serialized payload size for the updated value\n * t = tombstone count serialized for the target field\n *\n * Space complexity: O(c + t)\n */\nexport function __update<T extends Record<string, unknown>>(\n key: keyof T,\n value: T[keyof T],\n crStructReplica: CRStructState<T>\n): { change: CRStructChange<T>; delta: CRStructDelta<T> } | false {\n const [cloned, copiedValue] = safeStructuredClone(value)\n if (!cloned)\n throw new CRStructError(\n 'VALUE_NOT_CLONEABLE',\n 'Updated values must be supported by structuredClone.'\n )\n\n if (prototype(copiedValue) !== prototype(crStructReplica.defaults[key]))\n throw new CRStructError(\n 'VALUE_TYPE_MISMATCH',\n 'Updated value must match the default value runtime type.'\n )\n const delta: CRStructDelta<T> = {}\n const change: CRStructChange<T> = {}\n delta[key] = overwriteAndReturnSnapshotEntry(\n key,\n copiedValue,\n crStructReplica\n )\n change[key] = structuredClone(copiedValue)\n return { change, delta }\n}\n","import { overwriteAndReturnSnapshotEntry } from '../../../.helpers/index.js'\nimport type {\n CRStructState,\n CRStructDelta,\n CRStructChange,\n} from '../../../.types/index.js'\n\n/**\n * Resets one field or the entire struct back to default values.\n *\n * Each touched field is overwritten from the replica defaults and contributes a\n * visible change projection plus a serialized delta describing the reset.\n *\n * @param crStructReplica - The replica state to reset.\n * @param key - The optional field key to reset. When omitted, every field is reset.\n *\n * @returns\n * The visible change projection and serialized delta for the reset, or `false`\n * when a keyed reset targets a field outside the replica.\n *\n * Time complexity: O(k + c + t), worst case O(k + c + t)\n *\n * k = number of fields being reset\n * c = cloned and serialized payload size across reset field values\n * t = tombstone count serialized across reset fields\n *\n * Space complexity: O(k + c + t)\n */\nexport function __delete<T extends Record<string, unknown>>(\n crStructReplica: CRStructState<T>,\n key?: keyof T\n): { change: CRStructChange<T>; delta: CRStructDelta<T> } | false {\n const delta: CRStructDelta<T> = {}\n const change: CRStructChange<T> = {}\n\n if (key !== undefined) {\n if (!Object.hasOwn(crStructReplica.defaults, key)) return false\n const value = crStructReplica.defaults[key]\n delta[key] = overwriteAndReturnSnapshotEntry<T>(key, value, crStructReplica)\n change[key] = structuredClone(value)\n } else {\n for (const [key, value] of Object.entries(crStructReplica.defaults)) {\n delta[key as keyof T] = overwriteAndReturnSnapshotEntry<T>(\n key,\n value as T[keyof T],\n crStructReplica\n )\n change[key as keyof T] = structuredClone(value as T[keyof T])\n }\n }\n return { change, delta }\n}\n","import type {\n CRStructDelta,\n CRStructEventListenerFor,\n CRStructEventMap,\n CRStructSnapshot,\n CRStructState,\n CRStructAck,\n} from '../.types/index.js'\n\nimport {\n __merge,\n __acknowledge,\n __garbageCollect,\n __snapshot,\n} from '../core/mags/index.js'\nimport { __create, __read, __update, __delete } from '../core/crud/index.js'\n\n/**\n * Runtime implementation for a proxy-backed CR-Struct replica.\n */\nclass CRStructRaw<T extends Record<string, unknown>> {\n declare private readonly state: CRStructState<T>\n declare private readonly eventTarget: EventTarget\n\n /**\n * Creates a replica from default values and an optional snapshot.\n *\n * The struct shape is fixed by the provided default values. The returned\n * proxy exposes those fields as direct properties on the instance.\n *\n * @param defaults - The default field values that define the struct shape.\n * @param snapshot - An optional serialized snapshot used to hydrate the replica.\n * @throws {CRStructError} Thrown when the default values are not supported by `structuredClone`.\n */\n constructor(defaults: T, snapshot?: CRStructSnapshot<T>) {\n Object.defineProperties(this, {\n state: {\n value: __create<T>(defaults, snapshot),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n eventTarget: {\n value: new EventTarget(),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n })\n const keys = new Set(Object.keys(defaults))\n return new Proxy(this, {\n get(target, key, receiver) {\n // Preserve normal property access for unknown keys.\n if (typeof key !== 'string' || !keys.has(key))\n return Reflect.get(target, key, receiver)\n return __read(key, target.state)\n },\n has(target, key) {\n // Preserve normal property checks for unknown keys.\n if (typeof key !== 'string' || !keys.has(key))\n return Reflect.has(target, key)\n return true\n },\n set(target, key, value) {\n if (typeof key !== 'string' || !keys.has(key)) return false\n try {\n const result = __update<T>(key, value, target.state)\n /* c8 ignore next -- __update either throws or returns a result object. */\n if (!result) return false\n const { delta, change } = result\n if (delta)\n void target.eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n if (change)\n void target.eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n return true\n } catch {\n return false\n }\n },\n deleteProperty(target, key) {\n if (typeof key !== 'string' || !keys.has(key)) return false\n try {\n const result = __delete<T>(target.state, key)\n if (!result) return false\n const { delta, change } = result\n if (delta) {\n void target.eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n }\n if (change) {\n void target.eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n return true\n } catch {\n return false\n }\n },\n ownKeys(target) {\n return [\n ...Reflect.ownKeys(target),\n ...Reflect.ownKeys(target.state.defaults),\n ]\n },\n getOwnPropertyDescriptor(target, key) {\n // Preserve normal property checks for unknown keys.\n if (typeof key !== 'string' || !keys.has(key))\n return Reflect.getOwnPropertyDescriptor(target, key)\n return {\n value: __read(key, target.state),\n writable: true,\n enumerable: true,\n configurable: true,\n }\n },\n })\n }\n\n /**\n * Applies a remote or local delta to the replica state.\n *\n * @param crStructDelta - The partial serialized field state to merge.\n */\n merge(crStructDelta: CRStructDelta<T>): void {\n const result = __merge<T>(crStructDelta, this.state)\n if (!result) return\n const { delta, change } = result\n if (delta) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n }\n if (change) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n }\n\n /**\n * Emits the current acknowledgement frontier for each field.\n */\n acknowledge(): void {\n const ack = __acknowledge<T>(this.state)\n if (ack) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('ack', { detail: ack })\n )\n }\n }\n\n /**\n * Removes overwritten identifiers that every provided frontier has acknowledged.\n *\n * @param frontiers - A collection of acknowledgement frontiers to compact against.\n */\n garbageCollect(frontiers: Array<CRStructAck<T>>): void {\n void __garbageCollect<T>(frontiers, this.state)\n }\n\n /**\n * Emits a serialized snapshot of the current replica state.\n */\n snapshot(): void {\n const snapshot = __snapshot<T>(this.state)\n if (snapshot) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('snapshot', { detail: snapshot })\n )\n }\n }\n\n /**\n * Returns the struct field keys.\n *\n * @returns The field keys in the current replica.\n */\n keys<K extends keyof T>(): Array<K> {\n return Object.keys(this.state.entries) as Array<K>\n }\n\n /**\n * Resets every field in the replica back to its default value.\n */\n clear(): void {\n const result = __delete(this.state)\n if (result) {\n const { delta, change } = result\n if (delta) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('delta', { detail: delta })\n )\n }\n if (change) {\n void this.eventTarget.dispatchEvent(\n new CustomEvent('change', { detail: change })\n )\n }\n }\n }\n\n /**\n * Returns a cloned plain object view of the current replica fields.\n *\n * @returns The current field values keyed by field name.\n */\n clone(): T {\n const out = {} as T\n for (const [key, entry] of Object.entries(this.state.entries)) {\n out[key as keyof T] = structuredClone(entry.value as T[keyof T])\n }\n return out\n }\n\n /**\n * Returns cloned copies of the current field values.\n *\n * @returns The current field values.\n */\n values<K extends keyof T>(): Array<T[K]> {\n return Object.values(this.state.entries).map((entry) =>\n structuredClone(entry.value)\n ) as Array<T[K]>\n }\n\n /**\n * Returns cloned key-value pairs for the current replica state.\n *\n * @returns The current field entries.\n */\n entries<K extends keyof T>(): Array<[K, T[K]]> {\n return Object.entries(this.state.entries).map(([key, entry]) => [\n key as K,\n structuredClone(entry.value as T[K]),\n ])\n }\n\n /**\n * Returns a serializable snapshot representation of this replica.\n *\n * Called automatically by `JSON.stringify`.\n */\n toJSON(): CRStructSnapshot<T> {\n return __snapshot<T>(this.state)\n }\n /**\n * Returns this replica as a JSON string.\n */\n toString(): string {\n return JSON.stringify(this)\n }\n /**\n * Returns the Node.js console inspection representation.\n */\n [Symbol.for('nodejs.util.inspect.custom')](): CRStructSnapshot<T> {\n return this.toJSON()\n }\n /**\n * Returns the Deno console inspection representation.\n */\n [Symbol.for('Deno.customInspect')](): CRStructSnapshot<T> {\n return this.toJSON()\n }\n /**\n * Iterates over the current live field entries.\n */\n *[Symbol.iterator](): IterableIterator<[keyof T, T[keyof T]]> {\n for (const [key, entry] of Object.entries(this.state.entries)) {\n yield [key, structuredClone(entry.value)]\n }\n }\n\n /**\n * Registers an event listener.\n *\n * @param type - The event type to listen for.\n * @param listener - The listener to register.\n * @param options - Listener registration options.\n */\n addEventListener<K extends keyof CRStructEventMap<T>>(\n type: K,\n listener: CRStructEventListenerFor<T, K> | null,\n options?: boolean | AddEventListenerOptions\n ): void {\n this.eventTarget.addEventListener(\n type,\n listener as EventListenerOrEventListenerObject | null,\n options\n )\n }\n\n /**\n * Removes an event listener.\n *\n * @param type - The event type to stop listening for.\n * @param listener - The listener to remove.\n * @param options - Listener removal options.\n */\n removeEventListener<K extends keyof CRStructEventMap<T>>(\n type: K,\n listener: CRStructEventListenerFor<T, K> | null,\n options?: boolean | EventListenerOptions\n ): void {\n this.eventTarget.removeEventListener(\n type,\n listener as EventListenerOrEventListenerObject | null,\n options\n )\n }\n}\n\nexport type CRStruct<T extends Record<string, unknown>> = CRStructRaw<T> & T\n\nexport const CRStruct = CRStructRaw as {\n new <T extends Record<string, unknown>>(\n defaults: T,\n snapshot?: CRStructSnapshot<T>\n ): CRStruct<T>\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -2,182 +2,153 @@
2
2
  /**
3
3
  * Represents the internal replicated state for a single field.
4
4
  */
5
- type OOStructStateEntry<V> = {
5
+ type CRStructStateEntry<V> = {
6
6
  /**
7
7
  * The identifier of the current winning value.
8
8
  */
9
- __uuidv7: string;
9
+ uuidv7: string;
10
10
  /**
11
11
  * The current winning value.
12
12
  */
13
- __value: V;
13
+ value: V;
14
14
  /**
15
15
  * The predecessor identifier for the current winning value.
16
16
  */
17
- __after: string;
17
+ predecessor: string;
18
18
  /**
19
19
  * Identifiers known to have been overwritten for the field.
20
20
  */
21
- __overwrites: Set<string>;
21
+ tombstones: Set<string>;
22
22
  };
23
23
  /**
24
24
  * Represents the internal replicated state of an OO-Struct replica.
25
25
  */
26
- type OOStructState<T extends Record<string, unknown>> = {
27
- [K in keyof T]: OOStructStateEntry<T[K]>;
26
+ type CRStructState<T extends Record<string, unknown>> = {
27
+ entries: {
28
+ [K in keyof T]: CRStructStateEntry<T[K]>;
29
+ };
30
+ defaults: T;
28
31
  };
29
32
  /**Serlialized projection of replica state*/
30
33
  /**
31
34
  * Represents the serialized state for a single field.
32
35
  */
33
- type OOStructSnapshotEntry<V> = {
36
+ type CRStructSnapshotEntry<V> = {
34
37
  /**
35
38
  * The identifier of the current winning value.
36
39
  */
37
- __uuidv7: string;
40
+ uuidv7: string;
38
41
  /**
39
42
  * The serialized current winning value.
40
43
  */
41
- __value: V;
44
+ value: V;
42
45
  /**
43
46
  * The predecessor identifier for the current winning value.
44
47
  */
45
- __after: string;
48
+ predecessor: string;
46
49
  /**
47
50
  * Serialized overwritten identifiers for the field.
48
51
  */
49
- __overwrites: Array<string>;
52
+ tombstones: Array<string>;
50
53
  };
51
54
  /**
52
55
  * Represents a serialized snapshot of the full replica state.
53
56
  */
54
- type OOStructSnapshot<T extends Record<string, unknown>> = {
55
- [K in keyof T]: OOStructSnapshotEntry<T[K]>;
57
+ type CRStructSnapshot<T extends Record<string, unknown>> = {
58
+ [K in keyof T]: CRStructSnapshotEntry<T[K]>;
56
59
  };
57
60
  /**Resolved projection of replica state*/
58
61
  /**
59
62
  * Represents visible field values that changed during a local operation or merge.
60
63
  */
61
- type OOStructChange<T extends Record<string, unknown>> = Partial<T>;
64
+ type CRStructChange<T extends Record<string, unknown>> = Partial<T>;
62
65
  /**(T)*/
63
- /**A "report" on what the replica has seen*/
64
- /**
65
- * Represents the acknowledgement frontier for a set of field keys.
66
- */
67
- type OOStructAcknowledgementFrontier<K extends string> = Record<K, string>;
68
66
  /**Partial changes to gossip*/
69
67
  /**
70
68
  * Represents a partial serialized state projection exchanged between replicas.
71
69
  */
72
- type OOStructDelta<T extends Record<string, unknown>> = Partial<OOStructSnapshot<T>>;
70
+ type CRStructDelta<T extends Record<string, unknown>> = Partial<CRStructSnapshot<T>>;
71
+ /**A "report" on what the replica has seen*/
73
72
  /**
74
73
  * Represents the current acknowledgement frontier emitted by a replica.
75
74
  */
76
- type OOStructAck<T extends Record<string, unknown>> = Partial<OOStructAcknowledgementFrontier<Extract<keyof T, string>>>;
75
+ type CRStructAck<T extends Record<string, unknown>> = Partial<Record<keyof T, string>>;
77
76
  /***/
78
77
  /**
79
78
  * Maps OO-Struct event names to their event payload shapes.
80
79
  */
81
- type OOStructEventMap<T extends Record<string, unknown>> = {
80
+ type CRStructEventMap<T extends Record<string, unknown>> = {
82
81
  /** STATE / PROJECTION */
83
- snapshot: OOStructSnapshot<T>;
84
- change: OOStructChange<T>;
82
+ snapshot: CRStructSnapshot<T>;
83
+ change: CRStructChange<T>;
85
84
  /** GOSSIP / PROTOCOL */
86
- delta: OOStructDelta<T>;
87
- ack: OOStructAck<T>;
85
+ delta: CRStructDelta<T>;
86
+ ack: CRStructAck<T>;
88
87
  };
89
88
  /**
90
89
  * Represents a strongly typed OO-Struct event listener.
91
90
  */
92
- type OOStructEventListener<T extends Record<string, unknown>, K extends keyof OOStructEventMap<T>> = ((event: CustomEvent<OOStructEventMap<T>[K]>) => void) | {
93
- handleEvent(event: CustomEvent<OOStructEventMap<T>[K]>): void;
91
+ type CRStructEventListener<T extends Record<string, unknown>, K extends keyof CRStructEventMap<T>> = ((event: CustomEvent<CRStructEventMap<T>[K]>) => void) | {
92
+ handleEvent(event: CustomEvent<CRStructEventMap<T>[K]>): void;
94
93
  };
95
94
  /**
96
95
  * Resolves an event name to its corresponding listener type.
97
96
  */
98
- type OOStructEventListenerFor<T extends Record<string, unknown>, K extends string> = K extends keyof OOStructEventMap<T> ? OOStructEventListener<T, K> : EventListenerOrEventListenerObject;
97
+ type CRStructEventListenerFor<T extends Record<string, unknown>, K extends string> = K extends keyof CRStructEventMap<T> ? CRStructEventListener<T, K> : EventListenerOrEventListenerObject;
99
98
 
100
99
  /**
101
- * Represents an observed-overwrite struct replica.
102
- *
103
- * The struct shape is fixed by the provided default values.
100
+ * Runtime implementation for a proxy-backed CR-Struct replica.
104
101
  */
105
- declare class OOStruct<T extends Record<string, unknown>> {
106
- private readonly __eventTarget;
107
- private readonly __defaults;
108
- private readonly __state;
109
- private __live;
102
+ declare class CRStructRaw<T extends Record<string, unknown>> {
103
+ private readonly state;
104
+ private readonly eventTarget;
110
105
  /**
111
106
  * Creates a replica from default values and an optional snapshot.
112
107
  *
113
- * @param defaults - The default field values that define the struct shape.
114
- * @param snapshot - An optional serialized snapshot used for hydration.
115
- * @throws {OOStructError} Thrown when the default values are not supported by `structuredClone`.
116
- */
117
- constructor(defaults: {
118
- [K in keyof T]: T[K];
119
- }, snapshot?: OOStructSnapshot<T>);
120
- /**CRUD*/
121
- /**
122
- * Creates a new replica.
108
+ * The struct shape is fixed by the provided default values. The returned
109
+ * proxy exposes those fields as direct properties on the instance.
123
110
  *
124
111
  * @param defaults - The default field values that define the struct shape.
125
- * @param snapshot - An optional serialized snapshot used for hydration.
126
- * @returns A new OO-Struct replica.
127
- */
128
- static create<T extends Record<string, unknown>>(defaults: {
129
- [K in keyof T]: T[K];
130
- }, snapshot?: OOStructSnapshot<T>): OOStruct<T>;
131
- /**
132
- * Reads the current value of a field.
133
- *
134
- * @param key - The field key to read.
135
- * @returns A cloned copy of the field's current value.
136
- */
137
- read<K extends keyof T>(key: K): T[K];
138
- /**
139
- * Overwrites a field with a new value.
140
- *
141
- * @param key - The field key to overwrite.
142
- * @param value - The next value for the field.
143
- * @throws {OOStructError} Thrown when the value is not supported by `structuredClone`.
144
- * @throws {OOStructError} Thrown when the value runtime type does not match the default value runtime type.
112
+ * @param snapshot - An optional serialized snapshot used to hydrate the replica.
113
+ * @throws {CRStructError} Thrown when the default values are not supported by `structuredClone`.
145
114
  */
146
- update<K extends keyof T>(key: K, value: T[K]): void;
115
+ constructor(defaults: T, snapshot?: CRStructSnapshot<T>);
147
116
  /**
148
- * Resets one field or the entire struct back to default values.
117
+ * Applies a remote or local delta to the replica state.
149
118
  *
150
- * @param key - The optional field key to reset. When omitted, every field is reset.
119
+ * @param crStructDelta - The partial serialized field state to merge.
151
120
  */
152
- delete<K extends keyof T>(key?: K): void;
153
- /**MAGS*/
154
- /**
155
- * Merges an incoming delta into the current replica.
156
- *
157
- * @param replica - The incoming partial snapshot projection to merge.
158
- */
159
- merge<K extends keyof T>(replica: OOStructDelta<T>): void;
121
+ merge(crStructDelta: CRStructDelta<T>): void;
160
122
  /**
161
123
  * Emits the current acknowledgement frontier for each field.
162
124
  */
163
- acknowledge<K extends Extract<keyof T, string>>(): void;
125
+ acknowledge(): void;
164
126
  /**
165
127
  * Removes overwritten identifiers that every provided frontier has acknowledged.
166
128
  *
167
129
  * @param frontiers - A collection of acknowledgement frontiers to compact against.
168
130
  */
169
- garbageCollect<K extends Extract<keyof T, string>>(frontiers: Array<OOStructAck<T>>): void;
131
+ garbageCollect(frontiers: Array<CRStructAck<T>>): void;
170
132
  /**
171
133
  * Emits a serialized snapshot of the current replica state.
172
134
  */
173
135
  snapshot(): void;
174
- /**ADDITIONAL*/
175
136
  /**
176
137
  * Returns the struct field keys.
177
138
  *
178
139
  * @returns The field keys in the current replica.
179
140
  */
180
141
  keys<K extends keyof T>(): Array<K>;
142
+ /**
143
+ * Resets every field in the replica back to its default value.
144
+ */
145
+ clear(): void;
146
+ /**
147
+ * Returns a cloned plain object view of the current replica fields.
148
+ *
149
+ * @returns The current field values keyed by field name.
150
+ */
151
+ clone(): T;
181
152
  /**
182
153
  * Returns cloned copies of the current field values.
183
154
  *
@@ -190,7 +161,20 @@ declare class OOStruct<T extends Record<string, unknown>> {
190
161
  * @returns The current field entries.
191
162
  */
192
163
  entries<K extends keyof T>(): Array<[K, T[K]]>;
193
- /**EVENTS*/
164
+ /**
165
+ * Returns a serializable snapshot representation of this replica.
166
+ *
167
+ * Called automatically by `JSON.stringify`.
168
+ */
169
+ toJSON(): CRStructSnapshot<T>;
170
+ /**
171
+ * Returns this replica as a JSON string.
172
+ */
173
+ toString(): string;
174
+ /**
175
+ * Iterates over the current live field entries.
176
+ */
177
+ [Symbol.iterator](): IterableIterator<[keyof T, T[keyof T]]>;
194
178
  /**
195
179
  * Registers an event listener.
196
180
  *
@@ -198,7 +182,7 @@ declare class OOStruct<T extends Record<string, unknown>> {
198
182
  * @param listener - The listener to register.
199
183
  * @param options - Listener registration options.
200
184
  */
201
- addEventListener<K extends keyof OOStructEventMap<T>>(type: K, listener: OOStructEventListenerFor<T, K> | null, options?: boolean | AddEventListenerOptions): void;
185
+ addEventListener<K extends keyof CRStructEventMap<T>>(type: K, listener: CRStructEventListenerFor<T, K> | null, options?: boolean | AddEventListenerOptions): void;
202
186
  /**
203
187
  * Removes an event listener.
204
188
  *
@@ -206,21 +190,205 @@ declare class OOStruct<T extends Record<string, unknown>> {
206
190
  * @param listener - The listener to remove.
207
191
  * @param options - Listener removal options.
208
192
  */
209
- removeEventListener<K extends keyof OOStructEventMap<T>>(type: K, listener: OOStructEventListenerFor<T, K> | null, options?: boolean | EventListenerOptions): void;
210
- /**HELPERS*/
211
- /**
212
- * Overwrites a field and returns the serialized delta entry for that overwrite.
213
- *
214
- * @param key - The field key to overwrite.
215
- * @param value - The next value for the field.
216
- * @returns The serialized snapshot entry for the new winning value.
217
- */
218
- private overwriteAndReturnSnapshotEntry;
193
+ removeEventListener<K extends keyof CRStructEventMap<T>>(type: K, listener: CRStructEventListenerFor<T, K> | null, options?: boolean | EventListenerOptions): void;
219
194
  }
195
+ type CRStruct<T extends Record<string, unknown>> = CRStructRaw<T> & T;
196
+ declare const CRStruct: {
197
+ new <T extends Record<string, unknown>>(defaults: T, snapshot?: CRStructSnapshot<T>): CRStruct<T>;
198
+ };
220
199
 
221
200
  /**
222
201
  * Error codes thrown by {@link OOStruct}.
223
202
  */
224
- type OOStructErrorCode = 'DEFAULTS_NOT_CLONEABLE' | 'VALUE_NOT_CLONEABLE' | 'VALUE_TYPE_MISMATCH';
203
+ type CRStructErrorCode = 'DEFAULTS_NOT_CLONEABLE' | 'VALUE_NOT_CLONEABLE' | 'VALUE_TYPE_MISMATCH';
204
+
205
+ /**
206
+ * Creates internal CR-Struct state from default values and an optional snapshot.
207
+ *
208
+ * Default values define the replica field set. Compatible snapshot entries are
209
+ * parsed into live state entries, and invalid snapshot entries are ignored so
210
+ * the corresponding field falls back to a freshly initialized default-backed
211
+ * entry.
212
+ *
213
+ * @param defaults - Default field values that define the replica shape.
214
+ * @param snapshot - Optional serialized state used to hydrate matching fields.
215
+ *
216
+ * @returns
217
+ * A hydrated internal CR-Struct state object.
218
+ *
219
+ * @throws {CRStructError} Thrown when the default values are not supported by `structuredClone`.
220
+ *
221
+ * Time complexity: O(k + c + s + t), worst case O(k + c + s + t)
222
+ *
223
+ * k = default field count
224
+ * c = total cloned payload size across defaults and accepted snapshot values
225
+ * s = snapshot entries inspected for matching fields
226
+ * t = tombstone count materialized for accepted snapshot entries
227
+ *
228
+ * Space complexity: O(k + c + t)
229
+ */
230
+ declare function __create<T extends Record<string, unknown>>(defaults: T, snapshot?: CRStructSnapshot<T>): CRStructState<T>;
231
+
232
+ /**
233
+ * Reads and clones the current value of a single field.
234
+ *
235
+ * @param key - The field key to read.
236
+ * @param crStructReplica - The replica state that owns the field.
237
+ *
238
+ * @returns
239
+ * A cloned copy of the field's current value.
240
+ *
241
+ * Time complexity: O(c), worst case O(c)
242
+ *
243
+ * c = cloned field payload size
244
+ *
245
+ * Space complexity: O(c)
246
+ */
247
+ declare function __read<T extends Record<string, unknown>>(key: keyof T, crStructReplica: CRStructState<T>): T[keyof T];
248
+
249
+ /**
250
+ * Overwrites a field with a new value and emits the resulting projections.
251
+ *
252
+ * The incoming value is cloned first, validated against the default field
253
+ * runtime type, and then written back as the current winning value for the
254
+ * target field.
255
+ *
256
+ * @param key - The field key to overwrite.
257
+ * @param value - The next value for the field.
258
+ * @param crStructReplica - The replica state that owns the field.
259
+ *
260
+ * @returns
261
+ * The visible change projection and serialized delta for the overwrite.
262
+ *
263
+ * @throws {CRStructError} Thrown when the value is not supported by `structuredClone`.
264
+ * @throws {CRStructError} Thrown when the value runtime type does not match the default value runtime type.
265
+ *
266
+ * Time complexity: O(c + t), worst case O(c + t)
267
+ *
268
+ * c = cloned and serialized payload size for the updated value
269
+ * t = tombstone count serialized for the target field
270
+ *
271
+ * Space complexity: O(c + t)
272
+ */
273
+ declare function __update<T extends Record<string, unknown>>(key: keyof T, value: T[keyof T], crStructReplica: CRStructState<T>): {
274
+ change: CRStructChange<T>;
275
+ delta: CRStructDelta<T>;
276
+ } | false;
277
+
278
+ /**
279
+ * Resets one field or the entire struct back to default values.
280
+ *
281
+ * Each touched field is overwritten from the replica defaults and contributes a
282
+ * visible change projection plus a serialized delta describing the reset.
283
+ *
284
+ * @param crStructReplica - The replica state to reset.
285
+ * @param key - The optional field key to reset. When omitted, every field is reset.
286
+ *
287
+ * @returns
288
+ * The visible change projection and serialized delta for the reset, or `false`
289
+ * when a keyed reset targets a field outside the replica.
290
+ *
291
+ * Time complexity: O(k + c + t), worst case O(k + c + t)
292
+ *
293
+ * k = number of fields being reset
294
+ * c = cloned and serialized payload size across reset field values
295
+ * t = tombstone count serialized across reset fields
296
+ *
297
+ * Space complexity: O(k + c + t)
298
+ */
299
+ declare function __delete<T extends Record<string, unknown>>(crStructReplica: CRStructState<T>, key?: keyof T): {
300
+ change: CRStructChange<T>;
301
+ delta: CRStructDelta<T>;
302
+ } | false;
303
+
304
+ /**
305
+ * Merges an incoming delta into the current replica.
306
+ *
307
+ * Unknown fields and invalid snapshot entries are ignored. Accepted candidates
308
+ * extend local tombstone knowledge, may advance the current winning value, and
309
+ * may emit a return delta when the local state already dominates the incoming
310
+ * entry.
311
+ *
312
+ * @param crStructDelta - The incoming partial snapshot projection to merge.
313
+ * @param crStructReplica - The local replica state to merge into.
314
+ *
315
+ * @returns
316
+ * The visible change projection and reply delta, or `false` when the input is
317
+ * invalid or produces no outbound effect.
318
+ *
319
+ * Time complexity: O(d + l + i + c), worst case O(d + l + i + c)
320
+ *
321
+ * d = incoming delta field count
322
+ * l = local tombstone count processed across touched fields
323
+ * i = incoming tombstone count processed across accepted delta entries
324
+ * c = cloned and serialized payload size across emitted changes and reply deltas
325
+ *
326
+ * Space complexity: O(d + l + c)
327
+ */
328
+ declare function __merge<T extends Record<string, unknown>>(crStructDelta: CRStructDelta<T>, crStructReplica: CRStructState<T>): {
329
+ change: CRStructChange<T>;
330
+ delta: CRStructDelta<T>;
331
+ } | false;
332
+
333
+ /**
334
+ * Emits the current acknowledgement frontier for each field.
335
+ *
336
+ * Each field reports the largest tombstone identifier currently known for that
337
+ * field.
338
+ *
339
+ * @param crStructReplica - The replica state to summarize.
340
+ *
341
+ * @returns
342
+ * An acknowledgement frontier keyed by field name.
343
+ *
344
+ * Time complexity: O(k + t), worst case O(k + t)
345
+ *
346
+ * k = replica field count
347
+ * t = total tombstone count across all fields
348
+ *
349
+ * Space complexity: O(k)
350
+ */
351
+ declare function __acknowledge<T extends Record<string, unknown>>(crStructReplica: CRStructState<T>): CRStructAck<T> | false;
352
+
353
+ /**
354
+ * Removes overwritten identifiers that every provided frontier has acknowledged.
355
+ *
356
+ * The smallest valid acknowledgement per field is collected first, then local
357
+ * tombstones at or below that frontier are removed while keeping the current
358
+ * predecessor identifier intact.
359
+ *
360
+ * @param frontiers - A collection of acknowledgement frontiers to compact against.
361
+ * @param crStructReplica - The replica state to compact.
362
+ *
363
+ * Time complexity: O(a + t), worst case O(a + t)
364
+ *
365
+ * a = acknowledgement entries scanned across all provided frontiers
366
+ * t = tombstone count scanned across compacted fields
367
+ *
368
+ * Space complexity: O(k)
369
+ *
370
+ * k = fields that receive a valid acknowledgement frontier
371
+ */
372
+ declare function __garbageCollect<T extends Record<string, unknown>>(frontiers: Array<CRStructAck<T>>, crStructReplica: CRStructState<T>): void;
373
+
374
+ /**
375
+ * Serializes the current replica state into a snapshot projection.
376
+ *
377
+ * Each processed state entry is converted into its serializable snapshot form.
378
+ *
379
+ * @param crStructReplica - The replica state to serialize.
380
+ *
381
+ * @returns
382
+ * A serializable snapshot projection of the replica state.
383
+ *
384
+ * Time complexity: O(k + t + c), worst case O(k + t + c)
385
+ *
386
+ * k = state entry count processed by the serializer
387
+ * t = tombstone count serialized across processed entries
388
+ * c = serialized payload size across processed values
389
+ *
390
+ * Space complexity: O(k + t + c)
391
+ */
392
+ declare function __snapshot<T extends Record<string, unknown>>(crStructReplica: CRStructState<T>): CRStructSnapshot<T>;
225
393
 
226
- export { OOStruct, type OOStructAck, type OOStructAcknowledgementFrontier, type OOStructChange, type OOStructDelta, type OOStructErrorCode, type OOStructEventListener, type OOStructEventListenerFor, type OOStructEventMap, type OOStructSnapshot, type OOStructSnapshotEntry, type OOStructState, type OOStructStateEntry };
394
+ export { CRStruct, type CRStructAck, type CRStructChange, type CRStructDelta, type CRStructErrorCode, type CRStructEventListener, type CRStructEventListenerFor, type CRStructEventMap, type CRStructSnapshot, type CRStructSnapshotEntry, type CRStructState, type CRStructStateEntry, __acknowledge, __create, __delete, __garbageCollect, __merge, __read, __snapshot, __update };