react-mnemonic 0.1.1-alpha.0 → 1.0.0-beta.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.
package/dist/index.d.ts CHANGED
@@ -149,6 +149,8 @@ declare function createCodec<T>(encode: (value: T) => string, decode: (encoded:
149
149
  * | `WRITE_SCHEMA_REQUIRED` | Strict mode requires a schema to write, but none was found. |
150
150
  * | `MIGRATION_PATH_NOT_FOUND` | No contiguous migration path between the stored and latest version. |
151
151
  * | `MIGRATION_FAILED` | A migration step threw during execution. |
152
+ * | `MIGRATION_GRAPH_INVALID` | The schema registry helper received an ambiguous or cyclic migration graph. |
153
+ * | `RECONCILE_FAILED` | A read-time reconciliation hook threw or returned an unpersistable value. |
152
154
  * | `SCHEMA_REGISTRATION_CONFLICT` | `registerSchema` was called with a conflicting definition. |
153
155
  * | `TYPE_MISMATCH` | The decoded value failed JSON Schema validation. |
154
156
  * | `MODE_CONFIGURATION_INVALID` | The schema mode requires a capability the registry doesn't provide. |
@@ -170,7 +172,7 @@ declare class SchemaError extends Error {
170
172
  /**
171
173
  * Machine-readable code identifying the category of schema failure.
172
174
  */
173
- readonly code: "INVALID_ENVELOPE" | "SCHEMA_NOT_FOUND" | "WRITE_SCHEMA_REQUIRED" | "MIGRATION_PATH_NOT_FOUND" | "MIGRATION_FAILED" | "SCHEMA_REGISTRATION_CONFLICT" | "TYPE_MISMATCH" | "MODE_CONFIGURATION_INVALID";
175
+ readonly code: "INVALID_ENVELOPE" | "SCHEMA_NOT_FOUND" | "WRITE_SCHEMA_REQUIRED" | "MIGRATION_PATH_NOT_FOUND" | "MIGRATION_FAILED" | "MIGRATION_GRAPH_INVALID" | "RECONCILE_FAILED" | "SCHEMA_REGISTRATION_CONFLICT" | "TYPE_MISMATCH" | "MODE_CONFIGURATION_INVALID";
174
176
  /**
175
177
  * The underlying error that caused this failure, if any.
176
178
  */
@@ -407,8 +409,13 @@ interface MnemonicProviderOptions {
407
409
  /**
408
410
  * Enable DevTools debugging interface.
409
411
  *
410
- * When enabled, exposes the store on `window.__REACT_MNEMONIC_DEVTOOLS__[namespace]`
411
- * with methods to inspect, modify, and dump storage state from the console.
412
+ * When enabled, registers this provider in the global
413
+ * `window.__REACT_MNEMONIC_DEVTOOLS__` registry.
414
+ *
415
+ * The registry stores providers as weak references and exposes:
416
+ * - `resolve(namespace)` to strengthen a provider reference and access
417
+ * inspection methods.
418
+ * - `list()` to enumerate provider availability.
412
419
  *
413
420
  * @default false
414
421
  *
@@ -418,9 +425,10 @@ interface MnemonicProviderOptions {
418
425
  * enableDevTools: process.env.NODE_ENV === 'development'
419
426
  *
420
427
  * // Then in browser console:
421
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.dump()
422
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.get('user')
423
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.set('user', { name: 'Test' })
428
+ * const provider = window.__REACT_MNEMONIC_DEVTOOLS__.resolve('myApp')
429
+ * provider?.dump()
430
+ * provider?.get('user')
431
+ * provider?.set('user', { name: 'Test' })
424
432
  * ```
425
433
  */
426
434
  enableDevTools?: boolean;
@@ -491,6 +499,112 @@ interface MnemonicProviderOptions {
491
499
  * @see {@link KeySchema} - Individual schema definition
492
500
  */
493
501
  type SchemaMode = "strict" | "default" | "autoschema";
502
+ /**
503
+ * Weak-reference shape used by the devtools registry.
504
+ *
505
+ * Matches the standard `WeakRef` API while keeping the public type surface
506
+ * compatible with ES2020 TypeScript lib targets.
507
+ */
508
+ interface MnemonicDevToolsWeakRef<T extends object> {
509
+ /**
510
+ * Attempts to strengthen the weak reference.
511
+ *
512
+ * @returns The live object, or undefined if it was garbage-collected.
513
+ */
514
+ deref: () => T | undefined;
515
+ }
516
+ /**
517
+ * Provider inspection API exposed through devtools registry resolution.
518
+ *
519
+ * Resolve a provider from the registry, then invoke these methods for manual
520
+ * inspection/mutation from the browser console.
521
+ */
522
+ interface MnemonicDevToolsProviderApi {
523
+ /** Access the underlying store instance. */
524
+ getStore: () => Mnemonic;
525
+ /** Dump all raw key-value pairs for the provider namespace. */
526
+ dump: () => Record<string, string>;
527
+ /** Read decoded value for an unprefixed key. */
528
+ get: (key: string) => unknown;
529
+ /** Write value for an unprefixed key (JSON-encoded). */
530
+ set: (key: string, value: unknown) => void;
531
+ /** Remove a single unprefixed key. */
532
+ remove: (key: string) => void;
533
+ /** Remove all keys in this provider namespace. */
534
+ clear: () => void;
535
+ /** List all unprefixed keys in this provider namespace. */
536
+ keys: () => string[];
537
+ }
538
+ /**
539
+ * Registry entry for a single provider namespace.
540
+ */
541
+ interface MnemonicDevToolsProviderEntry {
542
+ /** Namespace key for this provider entry. */
543
+ namespace: string;
544
+ /** Weak reference to the provider inspection API. */
545
+ weakRef: MnemonicDevToolsWeakRef<MnemonicDevToolsProviderApi>;
546
+ /** Timestamp when this namespace was registered. */
547
+ registeredAt: number;
548
+ /** Timestamp when provider was last confirmed live. */
549
+ lastSeenAt: number;
550
+ /** Timestamp when provider was first observed unavailable, or null when live. */
551
+ staleSince: number | null;
552
+ }
553
+ /**
554
+ * Lightweight provider status returned by `list()`.
555
+ */
556
+ interface MnemonicDevToolsProviderDescriptor {
557
+ /** Namespace registered by the provider. */
558
+ namespace: string;
559
+ /** Whether the provider can currently be resolved to a live API instance. */
560
+ available: boolean;
561
+ /** Timestamp when the provider namespace was first registered. */
562
+ registeredAt: number;
563
+ /** Timestamp when the provider was last observed as live. */
564
+ lastSeenAt: number;
565
+ /** Timestamp when the provider first became unavailable, or `null` when live. */
566
+ staleSince: number | null;
567
+ }
568
+ /**
569
+ * Environment capabilities reported by devtools registry.
570
+ */
571
+ interface MnemonicDevToolsCapabilities {
572
+ /** Whether the runtime supports `WeakRef`. */
573
+ weakRef: boolean;
574
+ /** Whether the runtime supports `FinalizationRegistry`. */
575
+ finalizationRegistry: boolean;
576
+ }
577
+ /**
578
+ * Polling metadata for extension synchronization.
579
+ */
580
+ interface MnemonicDevToolsMeta {
581
+ /** Monotonic registry version incremented on register and mutation events. */
582
+ version: number;
583
+ /** Timestamp of the most recent registry update. */
584
+ lastUpdated: number;
585
+ /** Short label describing the most recent registry change. */
586
+ lastChange: string;
587
+ }
588
+ /**
589
+ * Global devtools registry contract available on window.
590
+ *
591
+ * This is an advanced public API used by the browser console integration and
592
+ * extension tooling. Direct namespace access
593
+ * (`window.__REACT_MNEMONIC_DEVTOOLS__.myNamespace`) is not part of the
594
+ * public API.
595
+ */
596
+ interface MnemonicDevToolsRegistry {
597
+ /** Provider entries keyed by namespace. */
598
+ providers: Record<string, MnemonicDevToolsProviderEntry>;
599
+ /** Resolve a namespace to a live provider API when one is available. */
600
+ resolve: (namespace: string) => MnemonicDevToolsProviderApi | null;
601
+ /** List provider availability without strengthening weak references manually. */
602
+ list: () => MnemonicDevToolsProviderDescriptor[];
603
+ /** Runtime capabilities relevant to the registry implementation. */
604
+ capabilities: MnemonicDevToolsCapabilities;
605
+ /** Versioning metadata used by polling devtools integrations. */
606
+ __meta: MnemonicDevToolsMeta;
607
+ }
494
608
  /**
495
609
  * Schema definition for a single key at a specific version.
496
610
  *
@@ -624,6 +738,31 @@ type MigrationRule = {
624
738
  * @see {@link SchemaRegistry.getMigrationPath} - Resolves a path between versions
625
739
  */
626
740
  type MigrationPath = MigrationRule[];
741
+ /**
742
+ * Input options for {@link createSchemaRegistry}.
743
+ *
744
+ * Use this helper when your registry contents are known up front and do not
745
+ * need runtime mutation. The returned registry is immutable and optimized for
746
+ * the common `"default"` / `"strict"` setup.
747
+ */
748
+ interface CreateSchemaRegistryOptions {
749
+ /**
750
+ * Versioned schemas to index by key and version.
751
+ *
752
+ * Duplicate `key + version` pairs are rejected up front with
753
+ * `SchemaError("SCHEMA_REGISTRATION_CONFLICT")`.
754
+ */
755
+ schemas?: readonly KeySchema[];
756
+ /**
757
+ * Migration rules to index by key and version edge.
758
+ *
759
+ * Write-time normalizers (`fromVersion === toVersion`) are indexed
760
+ * separately from read-time migration edges. Ambiguous outgoing edges,
761
+ * backward migrations, and duplicate write normalizers are rejected up
762
+ * front with `SchemaError("MIGRATION_GRAPH_INVALID")`.
763
+ */
764
+ migrations?: readonly MigrationRule[];
765
+ }
627
766
  /**
628
767
  * Lookup and registration API for key schemas and migration paths.
629
768
  *
@@ -824,6 +963,215 @@ type StorageLike = {
824
963
  */
825
964
  onExternalChange?: (callback: (changedKeys?: string[]) => void) => () => void;
826
965
  };
966
+ /**
967
+ * Function type for unsubscribing from event listeners.
968
+ *
969
+ * Call this function to remove a subscription and stop receiving updates.
970
+ *
971
+ * @example
972
+ * ```typescript
973
+ * const unsubscribe = store.subscribeRaw('user', () => console.log('Updated!'));
974
+ * // Later...
975
+ * unsubscribe(); // Stop listening
976
+ * ```
977
+ */
978
+ type Unsubscribe = () => void;
979
+ /**
980
+ * Callback function invoked when a subscribed value changes.
981
+ *
982
+ * Used by the external store contract to notify React when state updates.
983
+ */
984
+ type Listener = () => void;
985
+ /**
986
+ * Low-level Mnemonic store API provided via React Context.
987
+ *
988
+ * This interface powers `MnemonicProvider` internally and is also exposed to
989
+ * advanced consumers through `MnemonicDevToolsProviderApi.getStore()`. Typical
990
+ * application code should still prefer `useMnemonicKey`.
991
+ *
992
+ * All keys passed to these methods should be **unprefixed**. The store
993
+ * automatically applies the namespace prefix internally.
994
+ *
995
+ * @remarks
996
+ * This implements the React `useSyncExternalStore` contract for efficient,
997
+ * tearing-free state synchronization. Most application code should still
998
+ * prefer `useMnemonicKey`; this type mainly appears in the DevTools API via
999
+ * `MnemonicDevToolsProviderApi.getStore()`.
1000
+ */
1001
+ type Mnemonic = {
1002
+ /**
1003
+ * The namespace prefix applied to all keys in storage.
1004
+ *
1005
+ * Keys are stored as `${prefix}${key}` in the underlying storage backend.
1006
+ */
1007
+ prefix: string;
1008
+ /**
1009
+ * Whether the active storage backend can enumerate keys in this namespace.
1010
+ *
1011
+ * This is `true` for `localStorage`-like backends that implement both
1012
+ * `length` and `key(index)`. Namespace-wide recovery helpers rely on this
1013
+ * capability unless the caller supplies an explicit key list.
1014
+ */
1015
+ canEnumerateKeys: boolean;
1016
+ /**
1017
+ * Subscribe to changes for a specific key.
1018
+ *
1019
+ * Follows the React external store subscription contract. The listener
1020
+ * will be called whenever the value for this key changes.
1021
+ *
1022
+ * @param key - The unprefixed storage key to subscribe to
1023
+ * @param listener - Callback invoked when the value changes
1024
+ * @returns Unsubscribe function to stop listening
1025
+ *
1026
+ * @example
1027
+ * ```typescript
1028
+ * const unsubscribe = store.subscribeRaw('user', () => {
1029
+ * console.log('User changed:', store.getRawSnapshot('user'));
1030
+ * });
1031
+ * ```
1032
+ */
1033
+ subscribeRaw: (key: string, listener: Listener) => Unsubscribe;
1034
+ /**
1035
+ * Get the current raw string value for a key.
1036
+ *
1037
+ * This is part of the external store snapshot contract. Values are
1038
+ * cached in memory for stable snapshots.
1039
+ *
1040
+ * @param key - The unprefixed storage key
1041
+ * @returns The raw string value, or null if not present
1042
+ */
1043
+ getRawSnapshot: (key: string) => string | null;
1044
+ /**
1045
+ * Write a raw string value to storage.
1046
+ *
1047
+ * Updates both the in-memory cache and the underlying storage backend,
1048
+ * then notifies all subscribers for this key.
1049
+ *
1050
+ * @param key - The unprefixed storage key
1051
+ * @param raw - The raw string value to store
1052
+ */
1053
+ setRaw: (key: string, raw: string) => void;
1054
+ /**
1055
+ * Remove a key from storage.
1056
+ *
1057
+ * Clears the value from both the cache and the underlying storage,
1058
+ * then notifies all subscribers.
1059
+ *
1060
+ * @param key - The unprefixed storage key to remove
1061
+ */
1062
+ removeRaw: (key: string) => void;
1063
+ /**
1064
+ * Enumerate all keys in this namespace.
1065
+ *
1066
+ * Returns unprefixed keys that belong to this store's namespace.
1067
+ *
1068
+ * @returns Array of unprefixed key names
1069
+ */
1070
+ keys: () => string[];
1071
+ /**
1072
+ * Dump all key-value pairs in this namespace.
1073
+ *
1074
+ * Useful for debugging and DevTools integration.
1075
+ *
1076
+ * @returns Object mapping unprefixed keys to raw string values
1077
+ */
1078
+ dump: () => Record<string, string>;
1079
+ /**
1080
+ * The active schema enforcement mode for this provider.
1081
+ *
1082
+ * Propagated from the `schemaMode` provider option. Hooks read this
1083
+ * to determine how to handle versioned envelopes.
1084
+ *
1085
+ * @see {@link SchemaMode}
1086
+ */
1087
+ schemaMode: SchemaMode;
1088
+ /**
1089
+ * The schema registry for this provider, if one was supplied.
1090
+ *
1091
+ * Hooks use this to look up schemas, resolve migration paths, and
1092
+ * (in autoschema mode) register inferred schemas.
1093
+ *
1094
+ * @see {@link SchemaRegistry}
1095
+ */
1096
+ schemaRegistry?: SchemaRegistry;
1097
+ };
1098
+ /**
1099
+ * Recovery action names emitted by {@link useMnemonicRecovery}.
1100
+ */
1101
+ type MnemonicRecoveryAction = "clear-all" | "clear-keys" | "clear-matching";
1102
+ /**
1103
+ * Recovery event payload emitted after a namespace recovery action completes.
1104
+ */
1105
+ interface MnemonicRecoveryEvent {
1106
+ /**
1107
+ * Recovery action that just ran.
1108
+ */
1109
+ action: MnemonicRecoveryAction;
1110
+ /**
1111
+ * Namespace where the recovery action ran.
1112
+ */
1113
+ namespace: string;
1114
+ /**
1115
+ * Unprefixed keys cleared by the action.
1116
+ */
1117
+ clearedKeys: string[];
1118
+ }
1119
+ /**
1120
+ * Options for {@link useMnemonicRecovery}.
1121
+ */
1122
+ interface UseMnemonicRecoveryOptions {
1123
+ /**
1124
+ * Optional callback invoked after a recovery action completes.
1125
+ *
1126
+ * Useful for analytics, audit trails, support diagnostics, or user-facing
1127
+ * confirmation toasts.
1128
+ */
1129
+ onRecover?: (event: MnemonicRecoveryEvent) => void;
1130
+ }
1131
+ /**
1132
+ * Namespace-scoped recovery helpers returned by {@link useMnemonicRecovery}.
1133
+ *
1134
+ * These helpers operate on the current provider namespace and are intended for
1135
+ * user-facing recovery UX such as "reset app data" or "clear stale filters".
1136
+ */
1137
+ interface MnemonicRecoveryHook {
1138
+ /**
1139
+ * Current provider namespace without the trailing storage prefix dot.
1140
+ */
1141
+ namespace: string;
1142
+ /**
1143
+ * Whether namespace keys can be enumerated automatically.
1144
+ *
1145
+ * `clearAll()` and `clearMatching()` require this to be `true`. If it is
1146
+ * `false`, prefer `clearKeys([...])` with an explicit durable-key list.
1147
+ */
1148
+ canEnumerateKeys: boolean;
1149
+ /**
1150
+ * Lists all unprefixed keys currently visible in this namespace.
1151
+ *
1152
+ * Returns an empty array when no keys exist or when the storage backend
1153
+ * cannot enumerate keys.
1154
+ */
1155
+ listKeys: () => string[];
1156
+ /**
1157
+ * Clears every key in the current namespace.
1158
+ *
1159
+ * @throws {Error} When the storage backend cannot enumerate namespace keys
1160
+ */
1161
+ clearAll: () => string[];
1162
+ /**
1163
+ * Clears a specific set of unprefixed keys in the current namespace.
1164
+ *
1165
+ * Duplicate keys are ignored.
1166
+ */
1167
+ clearKeys: (keys: readonly string[]) => string[];
1168
+ /**
1169
+ * Clears namespace keys whose names match the supplied predicate.
1170
+ *
1171
+ * @throws {Error} When the storage backend cannot enumerate namespace keys
1172
+ */
1173
+ clearMatching: (predicate: (key: string) => boolean) => string[];
1174
+ }
827
1175
  /**
828
1176
  * Configuration options for the useMnemonicKey hook.
829
1177
  *
@@ -921,6 +1269,39 @@ type UseMnemonicKeyOptions<T> = {
921
1269
  * ```
922
1270
  */
923
1271
  codec?: Codec<T>;
1272
+ /**
1273
+ * Optional read-time reconciliation hook for persisted values.
1274
+ *
1275
+ * Runs after a stored value has been decoded and any read-time migrations
1276
+ * have completed, but before the hook exposes the value to React. This is
1277
+ * useful for selectively enforcing newly shipped defaults or normalizing
1278
+ * legacy persisted values without discarding the whole key.
1279
+ *
1280
+ * If the reconciled value would persist differently from the pre-reconcile
1281
+ * value, the hook rewrites storage once using the normal write path.
1282
+ *
1283
+ * @remarks
1284
+ * Prefer schema migrations for structural changes that must always happen
1285
+ * between explicit versions. Use `reconcile` for conditional, field-level
1286
+ * adjustments that depend on application policy rather than a strict schema
1287
+ * upgrade step.
1288
+ *
1289
+ * If `reconcile` throws a `SchemaError`, that error is preserved and passed
1290
+ * to `defaultValue`. Any other thrown error is wrapped as
1291
+ * `SchemaError("RECONCILE_FAILED")`.
1292
+ *
1293
+ * @param value - The decoded persisted value
1294
+ * @param context - Metadata about the stored and latest schema versions
1295
+ *
1296
+ * @example
1297
+ * ```typescript
1298
+ * reconcile: (value, { persistedVersion }) => ({
1299
+ * ...value,
1300
+ * theme: persistedVersion < 2 ? "dark" : value.theme,
1301
+ * })
1302
+ * ```
1303
+ */
1304
+ reconcile?: (value: T, context: ReconcileContext) => T;
924
1305
  /**
925
1306
  * Callback invoked once when the hook is first mounted.
926
1307
  *
@@ -1011,6 +1392,23 @@ type UseMnemonicKeyOptions<T> = {
1011
1392
  version?: number;
1012
1393
  };
1013
1394
  };
1395
+ /**
1396
+ * Metadata passed to `UseMnemonicKeyOptions.reconcile`.
1397
+ */
1398
+ type ReconcileContext = {
1399
+ /**
1400
+ * The unprefixed storage key being reconciled.
1401
+ */
1402
+ key: string;
1403
+ /**
1404
+ * The version found in the persisted envelope that was read.
1405
+ */
1406
+ persistedVersion: number;
1407
+ /**
1408
+ * The latest registered schema version for the key, when available.
1409
+ */
1410
+ latestVersion?: number;
1411
+ };
1014
1412
 
1015
1413
  /**
1016
1414
  * Props for the MnemonicProvider component.
@@ -1086,9 +1484,10 @@ interface MnemonicProviderProps extends MnemonicProviderOptions {
1086
1484
  * }
1087
1485
  *
1088
1486
  * // Then in browser console:
1089
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.dump()
1090
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.get('user')
1091
- * window.__REACT_MNEMONIC_DEVTOOLS__.myApp.set('theme', 'dark')
1487
+ * const dt = window.__REACT_MNEMONIC_DEVTOOLS__.resolve('myApp')
1488
+ * dt?.dump()
1489
+ * dt?.get('user')
1490
+ * dt?.set('theme', 'dark')
1092
1491
  * ```
1093
1492
  *
1094
1493
  * @example
@@ -1148,4 +1547,173 @@ declare function useMnemonicKey<T>(key: string, options: UseMnemonicKeyOptions<T
1148
1547
  remove: () => void;
1149
1548
  };
1150
1549
 
1151
- export { type Codec, CodecError, type CompiledValidator, JSONCodec, type JsonSchema, type JsonSchemaType, type JsonSchemaValidationError, type KeySchema, type MigrationPath, type MigrationRule, MnemonicProvider, type MnemonicProviderOptions, type MnemonicProviderProps, SchemaError, type SchemaMode, type SchemaRegistry, type StorageLike, type UseMnemonicKeyOptions, compileSchema, createCodec, useMnemonicKey, validateJsonSchema };
1550
+ /**
1551
+ * Hook for namespace-scoped recovery actions such as hard reset and selective clear.
1552
+ *
1553
+ * Applications can use this to offer self-service recovery UX for corrupt or
1554
+ * legacy persisted state. The hook operates on the current provider namespace.
1555
+ *
1556
+ * @param options - Optional recovery callback for telemetry/auditing
1557
+ * @returns Namespace recovery helpers
1558
+ *
1559
+ * @throws {Error} If used outside of a MnemonicProvider
1560
+ */
1561
+ declare function useMnemonicRecovery(options?: UseMnemonicRecoveryOptions): MnemonicRecoveryHook;
1562
+
1563
+ /**
1564
+ * Create an immutable schema registry for common default/strict-mode setups.
1565
+ *
1566
+ * The helper indexes schemas and migrations up front, validates duplicate and
1567
+ * ambiguous definitions, and returns a {@link SchemaRegistry} ready to pass to
1568
+ * `MnemonicProvider`.
1569
+ *
1570
+ * @param options - Initial schema and migration definitions
1571
+ * @returns An indexed immutable schema registry
1572
+ *
1573
+ * @throws {SchemaError} With `SCHEMA_REGISTRATION_CONFLICT` for duplicate
1574
+ * schemas, or `MIGRATION_GRAPH_INVALID` for invalid migration graphs
1575
+ */
1576
+ declare function createSchemaRegistry(options?: CreateSchemaRegistryOptions): SchemaRegistry;
1577
+
1578
+ /**
1579
+ * Adapter functions for structural migration helpers.
1580
+ *
1581
+ * These helpers assume tree-like data, but not a specific node shape. Supply a
1582
+ * `StructuralTreeHelpers<T>` when your nodes use custom field names. When your
1583
+ * nodes already look like `{ id, children }`, the exported helpers work without
1584
+ * any adapter configuration.
1585
+ *
1586
+ * @template T - Tree node type
1587
+ */
1588
+ interface StructuralTreeHelpers<T> {
1589
+ /**
1590
+ * Returns the stable identifier for a node.
1591
+ */
1592
+ getId: (node: T) => string;
1593
+ /**
1594
+ * Returns the node's child list, or `undefined` when it has no children.
1595
+ */
1596
+ getChildren: (node: T) => readonly T[] | undefined;
1597
+ /**
1598
+ * Returns a copy of the node with a new child list.
1599
+ */
1600
+ withChildren: (node: T, children: T[]) => T;
1601
+ /**
1602
+ * Returns a copy of the node with a new identifier.
1603
+ */
1604
+ withId: (node: T, id: string) => T;
1605
+ }
1606
+ /**
1607
+ * Default tree node shape supported by the structural migration helpers.
1608
+ *
1609
+ * If your nodes already use `id` and `children`, you can call the helpers
1610
+ * directly without supplying `StructuralTreeHelpers`.
1611
+ *
1612
+ * @template T - Tree node type
1613
+ */
1614
+ interface StructuralNode<T> {
1615
+ /**
1616
+ * Stable node identifier used for lookup and rename operations.
1617
+ */
1618
+ id: string;
1619
+ /**
1620
+ * Optional child nodes.
1621
+ */
1622
+ children?: readonly T[];
1623
+ }
1624
+ /**
1625
+ * Finds the first node with the requested id using depth-first traversal.
1626
+ *
1627
+ * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1628
+ * @param root - Root node to search
1629
+ * @param id - Target node id
1630
+ * @returns The matching node, or `undefined`
1631
+ */
1632
+ declare function findNodeById<T extends StructuralNode<T>>(root: T, id: string): T | undefined;
1633
+ /**
1634
+ * Finds the first node with the requested id using depth-first traversal.
1635
+ *
1636
+ * @template T - Tree node type
1637
+ * @param root - Root node to search
1638
+ * @param id - Target node id
1639
+ * @param helpers - Adapter for custom node shapes
1640
+ * @returns The matching node, or `undefined`
1641
+ */
1642
+ declare function findNodeById<T>(root: T, id: string, helpers: StructuralTreeHelpers<T>): T | undefined;
1643
+ /**
1644
+ * Inserts a child under the target parent when none of that parent's existing
1645
+ * direct children share the same id. Returns the original tree when the parent
1646
+ * is missing or the child is already present as a direct child.
1647
+ *
1648
+ * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1649
+ * @param root - Root node to update
1650
+ * @param parentId - Parent node that should receive the child
1651
+ * @param child - Child node to append
1652
+ * @returns Updated tree with the child inserted once
1653
+ */
1654
+ declare function insertChildIfMissing<T extends StructuralNode<T>>(root: T, parentId: string, child: T): T;
1655
+ /**
1656
+ * Inserts a child under the target parent when no existing child shares the
1657
+ * same id. Returns the original tree when the parent is missing or the child is
1658
+ * already present.
1659
+ *
1660
+ * @template T - Tree node type
1661
+ * @param root - Root node to update
1662
+ * @param parentId - Parent node that should receive the child
1663
+ * @param child - Child node to append
1664
+ * @param helpers - Adapter for custom node shapes
1665
+ * @returns Updated tree with the child inserted once
1666
+ */
1667
+ declare function insertChildIfMissing<T>(root: T, parentId: string, child: T, helpers: StructuralTreeHelpers<T>): T;
1668
+ /**
1669
+ * Renames every node with the source id while preserving tree structure.
1670
+ * Returns the original tree when the source id is missing or the target id
1671
+ * already exists elsewhere.
1672
+ *
1673
+ * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1674
+ * @param root - Root node to update
1675
+ * @param currentId - Existing id to rename
1676
+ * @param nextId - Replacement id
1677
+ * @returns Updated tree with matching node ids renamed
1678
+ */
1679
+ declare function renameNode<T extends StructuralNode<T>>(root: T, currentId: string, nextId: string): T;
1680
+ /**
1681
+ * Renames every node with the source id while preserving tree structure.
1682
+ * Returns the original tree when the source id is missing or the target id
1683
+ * already exists elsewhere.
1684
+ *
1685
+ * @template T - Tree node type
1686
+ * @param root - Root node to update
1687
+ * @param currentId - Existing id to rename
1688
+ * @param nextId - Replacement id
1689
+ * @param helpers - Adapter for custom node shapes
1690
+ * @returns Updated tree with matching node ids renamed
1691
+ */
1692
+ declare function renameNode<T>(root: T, currentId: string, nextId: string, helpers: StructuralTreeHelpers<T>): T;
1693
+ /**
1694
+ * Deduplicates each node's immediate children while preserving the first child
1695
+ * encountered for each key. The helper traverses the full tree and returns the
1696
+ * original root when no duplicates are removed.
1697
+ *
1698
+ * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1699
+ * @template K - Deduplication key type
1700
+ * @param root - Root node to normalize
1701
+ * @param getKey - Function that computes a dedupe key for each child
1702
+ * @returns Updated tree with duplicate siblings removed
1703
+ */
1704
+ declare function dedupeChildrenBy<T extends StructuralNode<T>, K>(root: T, getKey: (node: T) => K): T;
1705
+ /**
1706
+ * Deduplicates each node's immediate children while preserving the first child
1707
+ * encountered for each key. The helper traverses the full tree and returns the
1708
+ * original root when no duplicates are removed.
1709
+ *
1710
+ * @template T - Tree node type
1711
+ * @template K - Deduplication key type
1712
+ * @param root - Root node to normalize
1713
+ * @param getKey - Function that computes a dedupe key for each child
1714
+ * @param helpers - Adapter for custom node shapes
1715
+ * @returns Updated tree with duplicate siblings removed
1716
+ */
1717
+ declare function dedupeChildrenBy<T, K>(root: T, getKey: (node: T) => K, helpers: StructuralTreeHelpers<T>): T;
1718
+
1719
+ export { type Codec, CodecError, type CompiledValidator, type CreateSchemaRegistryOptions, JSONCodec, type JsonSchema, type JsonSchemaType, type JsonSchemaValidationError, type KeySchema, type Listener, type MigrationPath, type MigrationRule, type Mnemonic, type MnemonicDevToolsCapabilities, type MnemonicDevToolsMeta, type MnemonicDevToolsProviderApi, type MnemonicDevToolsProviderDescriptor, type MnemonicDevToolsProviderEntry, type MnemonicDevToolsRegistry, type MnemonicDevToolsWeakRef, MnemonicProvider, type MnemonicProviderOptions, type MnemonicProviderProps, type MnemonicRecoveryAction, type MnemonicRecoveryEvent, type MnemonicRecoveryHook, type ReconcileContext, SchemaError, type SchemaMode, type SchemaRegistry, type StorageLike, type StructuralNode, type StructuralTreeHelpers, type Unsubscribe, type UseMnemonicKeyOptions, type UseMnemonicRecoveryOptions, compileSchema, createCodec, createSchemaRegistry, dedupeChildrenBy, findNodeById, insertChildIfMissing, renameNode, useMnemonicKey, useMnemonicRecovery, validateJsonSchema };