react-mnemonic 1.1.0-beta0 → 1.2.0-beta1

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.cts CHANGED
@@ -1,2069 +1,4 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { ReactNode } from 'react';
3
-
4
- /**
5
- * @fileoverview Codec implementations for encoding and decoding values to/from storage.
6
- *
7
- * This module provides the built-in JSON codec and a factory for creating custom
8
- * codecs. Codecs handle the bidirectional transformation between typed JavaScript
9
- * values and their string representations for storage.
10
- *
11
- * Codecs are a low-level mechanism for keys that opt out of the JSON Schema
12
- * validation system. When a schema is registered for a key, the schema's
13
- * JSON Schema is used for validation and the payload is stored as a JSON value
14
- * directly (no codec encoding needed).
15
- */
16
-
17
- /**
18
- * Custom error class for codec encoding and decoding failures.
19
- *
20
- * Thrown when a codec cannot successfully encode a value to a string or
21
- * decode a string back to its typed representation. This allows callers
22
- * to distinguish codec errors from other types of errors.
23
- *
24
- * @example
25
- * ```typescript
26
- * try {
27
- * const value = JSONCodec.decode('not-valid-json');
28
- * } catch (error) {
29
- * if (error instanceof CodecError) {
30
- * console.error('Failed to decode:', error.message);
31
- * }
32
- * }
33
- * ```
34
- */
35
- declare class CodecError extends Error {
36
- /**
37
- * The underlying error that caused the codec failure, if any.
38
- *
39
- * Useful for debugging when wrapping errors from JSON.parse or
40
- * other parsing operations.
41
- */
42
- readonly cause?: unknown;
43
- /**
44
- * Creates a new CodecError.
45
- *
46
- * @param message - Human-readable error description
47
- * @param cause - Optional underlying error that caused this failure
48
- */
49
- constructor(message: string, cause?: unknown);
50
- }
51
- /**
52
- * JSON codec for encoding and decoding JSON-serializable values.
53
- *
54
- * This is the default codec used by `useMnemonicKey` when no codec is specified.
55
- * It uses `JSON.stringify` for encoding and `JSON.parse` for decoding, making it
56
- * suitable for objects, arrays, and primitive values.
57
- *
58
- * @remarks
59
- * - Supports any JSON-serializable type: objects, arrays, strings, numbers, booleans, null
60
- * - Does not preserve JavaScript-specific types like Date, Map, Set, or undefined
61
- * - Throws standard JSON parsing errors for malformed JSON strings
62
- *
63
- * @example
64
- * ```typescript
65
- * // Used automatically as the default
66
- * const { value, set } = useMnemonicKey('userProfile', {
67
- * defaultValue: { name: 'Guest', preferences: { theme: 'dark' } }
68
- * // codec: JSONCodec is implicit
69
- * });
70
- *
71
- * // Can be specified explicitly
72
- * const { value, set } = useMnemonicKey('settings', {
73
- * defaultValue: { notifications: true },
74
- * codec: JSONCodec
75
- * });
76
- * ```
77
- *
78
- * @see {@link createCodec} - For custom encoding schemes
79
- */
80
- declare const JSONCodec: Codec<any>;
81
- /**
82
- * Factory function for creating custom codecs.
83
- *
84
- * Creates a `Codec<T>` from separate encode and decode functions. This is
85
- * useful for implementing custom serialization strategies for types that
86
- * aren't supported by JSONCodec. Using a custom codec on a key opts out
87
- * of JSON Schema validation for that key.
88
- *
89
- * @template T - The TypeScript type of values to encode/decode
90
- *
91
- * @param encode - Function that converts a typed value to a string
92
- * @param decode - Function that converts a string back to a typed value
93
- * @returns A `Codec<T>` object compatible with useMnemonicKey
94
- *
95
- * @example
96
- * ```typescript
97
- * // Codec for Date objects
98
- * const DateCodec = createCodec<Date>(
99
- * (date) => date.toISOString(),
100
- * (str) => new Date(str)
101
- * );
102
- *
103
- * const { value, set } = useMnemonicKey('lastLogin', {
104
- * defaultValue: new Date(),
105
- * codec: DateCodec
106
- * });
107
- * ```
108
- *
109
- * @example
110
- * ```typescript
111
- * // Codec for Set<string>
112
- * const StringSetCodec = createCodec<Set<string>>(
113
- * (set) => JSON.stringify(Array.from(set)),
114
- * (str) => new Set(JSON.parse(str))
115
- * );
116
- *
117
- * const { value, set } = useMnemonicKey('tags', {
118
- * defaultValue: new Set<string>(),
119
- * codec: StringSetCodec
120
- * });
121
- * ```
122
- *
123
- * @see {@link Codec} - The codec interface
124
- * @see {@link CodecError} - Error to throw when encoding/decoding fails
125
- * @see {@link JSONCodec} - Built-in codec for JSON values
126
- */
127
- declare function createCodec<T>(encode: (value: T) => string, decode: (encoded: string) => T): Codec<T>;
128
-
129
- /**
130
- * @fileoverview Schema versioning primitives for Mnemonic.
131
- *
132
- * This module defines the envelope format used to wrap every persisted value
133
- * and the error class thrown when schema-related operations fail.
134
- */
135
- /**
136
- * Error thrown for schema registry, versioning, and migration failures.
137
- *
138
- * Each instance carries a machine-readable {@link code} that categorises
139
- * the failure. When a `defaultValue` factory is provided to
140
- * `useMnemonicKey`, the `SchemaError` is passed as the `error` argument
141
- * so the factory can inspect the failure reason.
142
- *
143
- * Error codes:
144
- *
145
- * | Code | Meaning |
146
- * | ------------------------------- | --------------------------------------------------------------- |
147
- * | `INVALID_ENVELOPE` | The raw stored value is not a valid `MnemonicEnvelope`. |
148
- * | `SCHEMA_NOT_FOUND` | No schema registered for the stored key + version. |
149
- * | `WRITE_SCHEMA_REQUIRED` | Strict mode requires a schema to write, but none was found. |
150
- * | `MIGRATION_PATH_NOT_FOUND` | No contiguous migration path between the stored and latest version. |
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. |
154
- * | `SCHEMA_REGISTRATION_CONFLICT` | `registerSchema` was called with a conflicting definition. |
155
- * | `TYPE_MISMATCH` | The decoded value failed JSON Schema validation. |
156
- * | `MODE_CONFIGURATION_INVALID` | The schema mode requires a capability the registry doesn't provide. |
157
- *
158
- * @example
159
- * ```typescript
160
- * defaultValue: (error) => {
161
- * if (error instanceof SchemaError) {
162
- * console.warn(`Schema issue [${error.code}]:`, error.message);
163
- * }
164
- * return { name: "Guest" };
165
- * }
166
- * ```
167
- *
168
- * @see {@link SchemaMode} - How the provider uses schemas
169
- * @see {@link SchemaRegistry} - Where schemas and migrations are registered
170
- */
171
- declare class SchemaError extends Error {
172
- /**
173
- * Machine-readable code identifying the category of schema failure.
174
- */
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";
176
- /**
177
- * The underlying error that caused this failure, if any.
178
- */
179
- readonly cause?: unknown;
180
- /**
181
- * Creates a new SchemaError.
182
- *
183
- * @param code - Machine-readable failure category
184
- * @param message - Human-readable error description
185
- * @param cause - Optional underlying error
186
- */
187
- constructor(code: SchemaError["code"], message: string, cause?: unknown);
188
- }
189
-
190
- /**
191
- * @fileoverview JSON Schema subset validator for Mnemonic.
192
- *
193
- * This module implements a minimal JSON Schema validator sufficient for
194
- * validating localStorage state. Only a subset of JSON Schema keywords
195
- * are supported; see {@link JsonSchema} for the full list.
196
- *
197
- * JSON Schema documents are plain JSON objects (inherently serializable),
198
- * making them suitable for storage alongside the data they describe.
199
- */
200
- /**
201
- * Supported JSON Schema type keywords.
202
- *
203
- * `"integer"` is a JSON Schema keyword meaning "a number that is a whole number."
204
- */
205
- type JsonSchemaType = "string" | "number" | "integer" | "boolean" | "null" | "object" | "array";
206
- /**
207
- * A subset of JSON Schema sufficient for localStorage state management.
208
- *
209
- * Supported keywords:
210
- * type, enum, const,
211
- * minimum, maximum, exclusiveMinimum, exclusiveMaximum,
212
- * minLength, maxLength,
213
- * properties, required, additionalProperties,
214
- * items, minItems, maxItems
215
- *
216
- * Deliberately omitted: $ref, $id, $schema, $defs, allOf, anyOf,
217
- * oneOf, not, pattern, format, patternProperties, if/then/else,
218
- * dependencies, uniqueItems, multipleOf, propertyNames.
219
- *
220
- * An empty schema `{}` accepts any value.
221
- */
222
- interface JsonSchema {
223
- /** The expected JSON type(s). An array form like `["string", "null"]` accepts either type. */
224
- type?: JsonSchemaType | JsonSchemaType[];
225
- /** The value must be deeply equal to one of these entries. */
226
- enum?: readonly unknown[];
227
- /** The value must be deeply equal to this exact value. */
228
- const?: unknown;
229
- /** Inclusive lower bound for numbers. */
230
- minimum?: number;
231
- /** Inclusive upper bound for numbers. */
232
- maximum?: number;
233
- /** Exclusive lower bound for numbers. */
234
- exclusiveMinimum?: number;
235
- /** Exclusive upper bound for numbers. */
236
- exclusiveMaximum?: number;
237
- /** Minimum string length (inclusive). */
238
- minLength?: number;
239
- /** Maximum string length (inclusive). */
240
- maxLength?: number;
241
- /** Property name to sub-schema mapping for objects. */
242
- properties?: Record<string, JsonSchema>;
243
- /** Properties that must be present on the object. */
244
- required?: readonly string[];
245
- /**
246
- * Controls extra properties not listed in `properties`.
247
- * `false` disallows them. A schema validates their values.
248
- * `true` (or omitted) allows anything.
249
- */
250
- additionalProperties?: boolean | JsonSchema;
251
- /** Schema applied to every element of an array. */
252
- items?: JsonSchema;
253
- /** Minimum array length (inclusive). */
254
- minItems?: number;
255
- /** Maximum array length (inclusive). */
256
- maxItems?: number;
257
- }
258
- /**
259
- * A single validation error produced by {@link validateJsonSchema}.
260
- */
261
- type JsonSchemaValidationError = {
262
- /** JSON Pointer path to the failing value (e.g., "/foo/bar/0"). Empty string for root. */
263
- path: string;
264
- /** Human-readable error description. */
265
- message: string;
266
- /** The JSON Schema keyword that failed. */
267
- keyword: string;
268
- };
269
- /**
270
- * A pre-compiled validation function generated by {@link compileSchema}.
271
- *
272
- * Accepts a value and an optional JSON Pointer path for error reporting.
273
- * Returns an array of validation errors (empty = valid).
274
- */
275
- type CompiledValidator = (value: unknown, path?: string) => JsonSchemaValidationError[];
276
- /**
277
- * Pre-compiles a {@link JsonSchema} into a reusable validation function.
278
- *
279
- * Inspects the schema once and builds a specialized closure that
280
- * eliminates runtime branching for unused keywords, pre-converts
281
- * `required` arrays to `Set`s, recursively pre-compiles nested property
282
- * and item schemas, and pre-builds primitive `Set`s for O(1) enum
283
- * lookups when possible.
284
- *
285
- * Results are cached by schema object identity in a `WeakMap`, so
286
- * calling `compileSchema` with the same schema reference is free
287
- * after the first call.
288
- *
289
- * @param schema - The JSON Schema to compile
290
- * @returns A compiled validation function
291
- */
292
- declare function compileSchema(schema: JsonSchema): CompiledValidator;
293
- /**
294
- * Validates a value against a {@link JsonSchema}.
295
- *
296
- * Returns an empty array when the value is valid.
297
- * Returns one or more {@link JsonSchemaValidationError} entries on failure.
298
- * Short-circuits on type mismatch (does not report downstream keyword errors).
299
- *
300
- * @param value - The value to validate
301
- * @param schema - The JSON Schema to validate against
302
- * @param path - Internal: JSON Pointer path for error reporting (default: `""`)
303
- * @returns Array of validation errors (empty = valid)
304
- */
305
- declare function validateJsonSchema(value: unknown, schema: JsonSchema, path?: string): JsonSchemaValidationError[];
306
-
307
- declare const typedSchemaBrand: unique symbol;
308
- declare const optionalSchemaBrand: unique symbol;
309
- type JsonPrimitive = string | number | boolean | null;
310
- type JsonConstValue = JsonPrimitive | readonly JsonConstValue[] | {
311
- readonly [key: string]: JsonConstValue;
312
- };
313
- type TypedJsonSchema<T> = JsonSchema & {
314
- readonly [typedSchemaBrand]?: T;
315
- };
316
- type OptionalTypedJsonSchema<T> = TypedJsonSchema<T> & {
317
- readonly [optionalSchemaBrand]: true;
318
- };
319
- type InferJsonSchemaValue<TSchema> = TSchema extends TypedJsonSchema<infer TValue> ? TValue : unknown;
320
- type ObjectValueFromSchemas<TShape extends Record<string, TypedJsonSchema<unknown> | OptionalTypedJsonSchema<unknown>>> = {
321
- [K in keyof TShape as TShape[K] extends OptionalTypedJsonSchema<unknown> ? never : K]: InferJsonSchemaValue<TShape[K]>;
322
- } & {
323
- [K in keyof TShape as TShape[K] extends OptionalTypedJsonSchema<unknown> ? K : never]?: InferJsonSchemaValue<TShape[K]>;
324
- };
325
- type StringSchemaOptions = Pick<JsonSchema, "minLength" | "maxLength">;
326
- type NumberSchemaOptions = Pick<JsonSchema, "minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum">;
327
- type ArraySchemaOptions = Pick<JsonSchema, "minItems" | "maxItems">;
328
- type ObjectSchemaOptions = Pick<JsonSchema, "additionalProperties">;
329
- /**
330
- * Builder helpers for strongly typed schemas backed by Mnemonic's built-in
331
- * JSON Schema subset.
332
- *
333
- * The returned schemas are plain `JsonSchema` objects at runtime, so they can
334
- * be registered directly in `createSchemaRegistry(...)` while also carrying a
335
- * phantom TypeScript type for inference.
336
- */
337
- declare const mnemonicSchema: {
338
- string(options?: StringSchemaOptions): TypedJsonSchema<string>;
339
- number(options?: NumberSchemaOptions): TypedJsonSchema<number>;
340
- integer(options?: NumberSchemaOptions): TypedJsonSchema<number>;
341
- boolean(): TypedJsonSchema<boolean>;
342
- nullValue(): TypedJsonSchema<null>;
343
- literal<const TValue extends JsonConstValue>(value: TValue): TypedJsonSchema<TValue>;
344
- enum<const TValues extends readonly [JsonPrimitive, ...JsonPrimitive[]]>(values: TValues): TypedJsonSchema<TValues[number]>;
345
- optional<T>(schema: TypedJsonSchema<T>): OptionalTypedJsonSchema<T>;
346
- nullable<T>(schema: TypedJsonSchema<T>): TypedJsonSchema<T | null>;
347
- array<TItemSchema extends TypedJsonSchema<unknown>>(itemSchema: TItemSchema, options?: ArraySchemaOptions): TypedJsonSchema<InferJsonSchemaValue<TItemSchema>[]>;
348
- object<TShape extends Record<string, TypedJsonSchema<unknown> | OptionalTypedJsonSchema<unknown>>>(shape: TShape, options?: ObjectSchemaOptions): TypedJsonSchema<ObjectValueFromSchemas<TShape>>;
349
- record<TValueSchema extends TypedJsonSchema<unknown>>(valueSchema: TValueSchema): TypedJsonSchema<Record<string, InferJsonSchemaValue<TValueSchema>>>;
350
- };
351
-
352
- /**
353
- * @fileoverview Type definitions for the Mnemonic library.
354
- *
355
- * This module defines the core types and interfaces used throughout the Mnemonic
356
- * library for type-safe, persistent state management in React applications.
357
- */
358
-
359
- declare const keySchemaValueBrand: unique symbol;
360
- /**
361
- * Codec for encoding and decoding values to and from storage.
362
- *
363
- * Codecs provide bidirectional transformations between typed values and their
364
- * string representations suitable for storage in localStorage or similar backends.
365
- *
366
- * Using a codec on a key opts out of JSON Schema validation. Schema-managed
367
- * keys store JSON values directly and are validated against their JSON Schema.
368
- *
369
- * @template T - The TypeScript type of the value to encode/decode
370
- *
371
- * @example
372
- * ```typescript
373
- * const DateCodec: Codec<Date> = {
374
- * encode: (date) => date.toISOString(),
375
- * decode: (str) => new Date(str)
376
- * };
377
- * ```
378
- *
379
- * @see {@link JSONCodec} - Default codec for JSON-serializable values
380
- * @see {@link createCodec} - Helper function to create custom codecs
381
- */
382
- interface Codec<T> {
383
- /**
384
- * Transforms a typed value into a string suitable for storage.
385
- *
386
- * @param value - The typed value to encode
387
- * @returns A string representation of the value
388
- * @throws {CodecError} If the value cannot be encoded
389
- */
390
- encode: (value: T) => string;
391
- /**
392
- * Transforms a stored string back into a typed value.
393
- *
394
- * @param encoded - The string representation from storage
395
- * @returns The decoded typed value
396
- * @throws {CodecError} If the string cannot be decoded
397
- */
398
- decode: (encoded: string) => T;
399
- }
400
- /**
401
- * Configuration options for MnemonicProvider.
402
- *
403
- * These options configure the behavior of the storage provider, including
404
- * namespace isolation, storage backend selection, cross-tab synchronization,
405
- * and developer tools integration.
406
- *
407
- * @example
408
- * ```tsx
409
- * <MnemonicProvider
410
- * namespace="myApp"
411
- * storage={localStorage}
412
- * enableDevTools={process.env.NODE_ENV === 'development'}
413
- * >
414
- * <App />
415
- * </MnemonicProvider>
416
- * ```
417
- */
418
- interface MnemonicProviderOptions {
419
- /**
420
- * Namespace prefix for all storage keys.
421
- *
422
- * All keys stored by this provider will be prefixed with `${namespace}.`
423
- * to avoid collisions between different parts of your application or
424
- * different applications sharing the same storage backend.
425
- *
426
- * @example
427
- * ```typescript
428
- * // With namespace="myApp", a key "user" becomes "myApp.user" in storage
429
- * namespace: "myApp"
430
- * ```
431
- */
432
- namespace: string;
433
- /**
434
- * Storage backend to use for persistence.
435
- *
436
- * Defaults to `window.localStorage` in browser environments. You can provide
437
- * a synchronous custom implementation (e.g., sessionStorage, an in-memory
438
- * cache facade over IndexedDB, or a mock for testing).
439
- *
440
- * @default window.localStorage
441
- *
442
- * @example
443
- * ```typescript
444
- * // Use sessionStorage instead of localStorage
445
- * storage: window.sessionStorage
446
- *
447
- * // Use a custom storage implementation
448
- * storage: {
449
- * getItem: (key) => myCustomStore.get(key),
450
- * setItem: (key, value) => myCustomStore.set(key, value),
451
- * removeItem: (key) => myCustomStore.delete(key)
452
- * }
453
- * ```
454
- */
455
- storage?: StorageLike;
456
- /**
457
- * Enable DevTools debugging interface.
458
- *
459
- * When enabled, registers this provider in the global
460
- * `window.__REACT_MNEMONIC_DEVTOOLS__` registry.
461
- *
462
- * The registry stores providers as weak references and exposes:
463
- * - `resolve(namespace)` to strengthen a provider reference and access
464
- * inspection methods.
465
- * - `list()` to enumerate provider availability.
466
- *
467
- * @default false
468
- *
469
- * @example
470
- * ```typescript
471
- * // Enable in development only
472
- * enableDevTools: process.env.NODE_ENV === 'development'
473
- *
474
- * // Then in browser console:
475
- * const provider = window.__REACT_MNEMONIC_DEVTOOLS__?.resolve('myApp')
476
- * provider?.dump()
477
- * provider?.get('user')
478
- * provider?.set('user', { name: 'Test' })
479
- * ```
480
- */
481
- enableDevTools?: boolean;
482
- /**
483
- * Versioning and schema enforcement mode.
484
- *
485
- * Controls whether stored values require a registered schema, and how
486
- * missing schemas are handled. See {@link SchemaMode} for the behaviour
487
- * of each mode.
488
- *
489
- * @default "default"
490
- *
491
- * @see {@link SchemaMode} - Detailed description of each mode
492
- * @see {@link SchemaRegistry} - Registry supplied via `schemaRegistry`
493
- */
494
- schemaMode?: SchemaMode;
495
- /**
496
- * Schema registry used for version lookup and migration resolution.
497
- *
498
- * When provided, the library uses the registry to find the correct
499
- * JSON Schema for each stored version, and to resolve migration paths
500
- * when upgrading old data to the latest schema.
501
- *
502
- * Required when `schemaMode` is `"strict"` or `"autoschema"`.
503
- * Optional (but recommended) in `"default"` mode.
504
- *
505
- * @remarks
506
- * In `"default"` and `"strict"` modes, the registry is treated as
507
- * immutable after the provider initializes. Updates should be shipped
508
- * as part of a new app version and applied by remounting the provider.
509
- * `"autoschema"` remains mutable so inferred schemas can be registered
510
- * at runtime.
511
- *
512
- * @see {@link SchemaRegistry} - Interface the registry must implement
513
- * @see {@link KeySchema} - Schema definition stored in the registry
514
- */
515
- schemaRegistry?: SchemaRegistry;
516
- /**
517
- * Server-rendering and hydration defaults for descendant hooks.
518
- *
519
- * Provider-level SSR settings establish the default hydration strategy for
520
- * all `useMnemonicKey(...)` calls in this namespace. Individual hooks may
521
- * still override the strategy when a specific key needs different behavior.
522
- *
523
- * @example
524
- * ```tsx
525
- * <MnemonicProvider
526
- * namespace="app"
527
- * ssr={{ hydration: "client-only" }}
528
- * >
529
- * <App />
530
- * </MnemonicProvider>
531
- * ```
532
- */
533
- ssr?: MnemonicProviderSSRConfig;
534
- }
535
- /**
536
- * Controls how the provider enforces versioned schemas on stored values.
537
- *
538
- * - `"default"` — Schemas are optional. When a schema exists for the stored
539
- * version it is used for validation; otherwise the hook's `codec` option is
540
- * used directly with no validation. This is the recommended starting mode.
541
- *
542
- * - `"strict"` — Every read and write **must** have a registered schema for
543
- * the stored version. If no matching schema is found the value falls back
544
- * to `defaultValue` with a `SchemaError` (`SCHEMA_NOT_FOUND` on reads,
545
- * `WRITE_SCHEMA_REQUIRED` on writes).
546
- * When no schemas are registered and no explicit schema is provided, writes
547
- * fall back to a codec-encoded (v0) envelope.
548
- *
549
- * - `"autoschema"` — Like `"default"`, but when a key has **no** schema
550
- * registered at all, the library infers a JSON Schema at version 1 from the
551
- * first successfully decoded value and registers it via
552
- * `SchemaRegistry.registerSchema`. Subsequent reads/writes for that key
553
- * then behave as if the schema had been registered manually.
554
- *
555
- * @remarks
556
- * In `"default"` and `"strict"` modes, registry lookups are cached under the
557
- * assumption that the schema registry is immutable for the lifetime of the
558
- * provider. If you need to update schemas, publish a new app version and
559
- * remount the provider. `"autoschema"` does not assume immutability.
560
- *
561
- * @default "default"
562
- *
563
- * @see {@link SchemaRegistry} - Registry that stores schemas and migrations
564
- * @see {@link KeySchema} - Individual schema definition
565
- */
566
- type SchemaMode = "strict" | "default" | "autoschema";
567
- /**
568
- * Controls when a hook should read persisted storage during client rendering.
569
- *
570
- * - `"immediate"` — Default. The server snapshot is used during SSR/hydration,
571
- * and the hook reads persisted storage as soon as React switches to the
572
- * client snapshot.
573
- *
574
- * - `"client-only"` — Defers all storage reads until after the component has
575
- * mounted on the client. This is useful when you want a deterministic server
576
- * placeholder and prefer the persisted value to appear only after hydration
577
- * completes.
578
- */
579
- type MnemonicHydrationMode = "immediate" | "client-only";
580
- /**
581
- * Provider-level SSR defaults shared by descendant hooks.
582
- */
583
- interface MnemonicProviderSSRConfig {
584
- /**
585
- * Default hydration strategy for descendant `useMnemonicKey(...)` hooks.
586
- *
587
- * @default "immediate"
588
- */
589
- hydration?: MnemonicHydrationMode;
590
- }
591
- /**
592
- * Hook-level SSR controls for `useMnemonicKey(...)`.
593
- *
594
- * Lets a key render a deterministic server snapshot and optionally delay
595
- * reading persisted storage until after client mount.
596
- *
597
- * @template T - The decoded value type for the key
598
- */
599
- interface MnemonicKeySSRConfig<T> {
600
- /**
601
- * Value to expose during SSR and hydration instead of `defaultValue`.
602
- *
603
- * This value is not persisted automatically. Once hydration completes,
604
- * the hook transitions to the stored value (if any) or back to
605
- * `defaultValue`.
606
- *
607
- * Factory functions should be deterministic across server render and
608
- * client hydration to avoid markup mismatches.
609
- */
610
- serverValue?: T | (() => T);
611
- /**
612
- * Hydration strategy for this key.
613
- *
614
- * When omitted, inherits the provider default.
615
- */
616
- hydration?: MnemonicHydrationMode;
617
- }
618
- /**
619
- * Weak-reference shape used by the devtools registry.
620
- *
621
- * Matches the standard `WeakRef` API while keeping the public type surface
622
- * compatible with ES2020 TypeScript lib targets.
623
- */
624
- interface MnemonicDevToolsWeakRef<T extends object> {
625
- /**
626
- * Attempts to strengthen the weak reference.
627
- *
628
- * @returns The live object, or undefined if it was garbage-collected.
629
- */
630
- deref: () => T | undefined;
631
- }
632
- /**
633
- * Provider inspection API exposed through devtools registry resolution.
634
- *
635
- * Resolve a provider from the registry, then invoke these methods for manual
636
- * inspection/mutation from the browser console.
637
- */
638
- interface MnemonicDevToolsProviderApi {
639
- /** Access the underlying store instance. */
640
- getStore: () => Mnemonic;
641
- /** Dump all raw key-value pairs for the provider namespace. */
642
- dump: () => Record<string, string>;
643
- /** Read decoded value for an unprefixed key. */
644
- get: (key: string) => unknown;
645
- /** Write value for an unprefixed key (JSON-encoded). */
646
- set: (key: string, value: unknown) => void;
647
- /** Remove a single unprefixed key. */
648
- remove: (key: string) => void;
649
- /** Remove all keys in this provider namespace. */
650
- clear: () => void;
651
- /** List all unprefixed keys in this provider namespace. */
652
- keys: () => string[];
653
- }
654
- /**
655
- * Registry entry for a single provider namespace.
656
- */
657
- interface MnemonicDevToolsProviderEntry {
658
- /** Namespace key for this provider entry. */
659
- namespace: string;
660
- /** Weak reference to the provider inspection API. */
661
- weakRef: MnemonicDevToolsWeakRef<MnemonicDevToolsProviderApi>;
662
- /** Timestamp when this namespace was registered. */
663
- registeredAt: number;
664
- /** Timestamp when provider was last confirmed live. */
665
- lastSeenAt: number;
666
- /** Timestamp when provider was first observed unavailable, or null when live. */
667
- staleSince: number | null;
668
- }
669
- /**
670
- * Lightweight provider status returned by `list()`.
671
- */
672
- interface MnemonicDevToolsProviderDescriptor {
673
- /** Namespace registered by the provider. */
674
- namespace: string;
675
- /** Whether the provider can currently be resolved to a live API instance. */
676
- available: boolean;
677
- /** Timestamp when the provider namespace was first registered. */
678
- registeredAt: number;
679
- /** Timestamp when the provider was last observed as live. */
680
- lastSeenAt: number;
681
- /** Timestamp when the provider first became unavailable, or `null` when live. */
682
- staleSince: number | null;
683
- }
684
- /**
685
- * Environment capabilities reported by devtools registry.
686
- */
687
- interface MnemonicDevToolsCapabilities {
688
- /** Whether the runtime supports `WeakRef`. */
689
- weakRef: boolean;
690
- /** Whether the runtime supports `FinalizationRegistry`. */
691
- finalizationRegistry: boolean;
692
- }
693
- /**
694
- * Polling metadata for extension synchronization.
695
- */
696
- interface MnemonicDevToolsMeta {
697
- /** Monotonic registry version incremented on register and mutation events. */
698
- version: number;
699
- /** Timestamp of the most recent registry update. */
700
- lastUpdated: number;
701
- /** Short label describing the most recent registry change. */
702
- lastChange: string;
703
- }
704
- /**
705
- * Global devtools registry contract available on window.
706
- *
707
- * This is an advanced public API used by the browser console integration and
708
- * extension tooling. Direct namespace access
709
- * (`window.__REACT_MNEMONIC_DEVTOOLS__.myNamespace`) is not part of the
710
- * public API.
711
- */
712
- interface MnemonicDevToolsRegistry {
713
- /** Provider entries keyed by namespace. */
714
- providers: Record<string, MnemonicDevToolsProviderEntry>;
715
- /** Resolve a namespace to a live provider API when one is available. */
716
- resolve: (namespace: string) => MnemonicDevToolsProviderApi | null;
717
- /** List provider availability without strengthening weak references manually. */
718
- list: () => MnemonicDevToolsProviderDescriptor[];
719
- /** Runtime capabilities relevant to the registry implementation. */
720
- capabilities: MnemonicDevToolsCapabilities;
721
- /** Versioning metadata used by polling devtools integrations. */
722
- __meta: MnemonicDevToolsMeta;
723
- }
724
- /**
725
- * Schema definition for a single key at a specific version.
726
- *
727
- * Each registered schema binds a storage key + version number to a
728
- * JSON Schema that validates the payload. Schemas are fully serializable
729
- * (no functions).
730
- *
731
- * When the provider reads a value whose envelope version matches a
732
- * registered schema, the payload is validated against the schema's
733
- * JSON Schema definition.
734
- *
735
- * @example
736
- * ```typescript
737
- * const userSchemaV1: KeySchema = {
738
- * key: "user",
739
- * version: 1,
740
- * schema: {
741
- * type: "object",
742
- * properties: {
743
- * name: { type: "string" },
744
- * },
745
- * required: ["name"],
746
- * },
747
- * };
748
- * ```
749
- *
750
- * @see {@link SchemaRegistry} - Where schemas are registered and looked up
751
- * @see {@link MigrationRule} - How values migrate between schema versions
752
- * @see {@link JsonSchema} - The JSON Schema subset used for validation
753
- */
754
- type KeySchema<TValue = unknown, K extends string = string, TSchema extends JsonSchema = JsonSchema> = {
755
- /**
756
- * The unprefixed storage key this schema applies to.
757
- */
758
- key: K;
759
- /**
760
- * The version number for this schema.
761
- *
762
- * Must be a non-negative integer. Any version (including `0`) is valid.
763
- */
764
- version: number;
765
- /**
766
- * JSON Schema that validates the payload at this version.
767
- *
768
- * Only the subset of JSON Schema keywords defined in {@link JsonSchema}
769
- * are supported. An empty schema `{}` accepts any value.
770
- */
771
- schema: TSchema;
772
- /**
773
- * Phantom type linking this runtime schema to its decoded TypeScript value.
774
- *
775
- * This field is never set at runtime. It exists only so helpers such as
776
- * `defineKeySchema(...)`, `defineMnemonicKey(...)`, and `defineMigration(...)`
777
- * can preserve a single source of truth between schema shape and value type.
778
- */
779
- readonly [keySchemaValueBrand]?: TValue;
780
- };
781
- /**
782
- * A single migration step that transforms data from one schema version to
783
- * another, or normalizes data at the same version.
784
- *
785
- * Migration rules are composed into a {@link MigrationPath} by the
786
- * {@link SchemaRegistry} to upgrade stored data across multiple versions in
787
- * sequence (e.g. v1 -> v2 -> v3).
788
- *
789
- * When `fromVersion === toVersion`, the rule is a **write-time normalizer**
790
- * that runs on every write to that version. This is useful for data
791
- * normalization (trimming strings, clamping values, injecting defaults).
792
- *
793
- * @example
794
- * ```typescript
795
- * // Version upgrade migration
796
- * const userV1ToV2: MigrationRule = {
797
- * key: "user",
798
- * fromVersion: 1,
799
- * toVersion: 2,
800
- * migrate: (v1) => {
801
- * const old = v1 as { name: string };
802
- * return { firstName: old.name, lastName: "" };
803
- * },
804
- * };
805
- *
806
- * // Write-time normalizer (same version)
807
- * const trimUserV2: MigrationRule = {
808
- * key: "user",
809
- * fromVersion: 2,
810
- * toVersion: 2,
811
- * migrate: (v) => {
812
- * const user = v as { firstName: string; lastName: string };
813
- * return { firstName: user.firstName.trim(), lastName: user.lastName.trim() };
814
- * },
815
- * };
816
- * ```
817
- *
818
- * @see {@link MigrationPath} - Ordered list of rules applied in sequence
819
- * @see {@link SchemaRegistry.getMigrationPath} - How the path is resolved
820
- * @see {@link SchemaRegistry.getWriteMigration} - How write-time normalizers are resolved
821
- */
822
- type MigrationRule<TFrom = unknown, TTo = unknown, K extends string = string> = {
823
- /**
824
- * The unprefixed storage key this rule applies to.
825
- */
826
- key: K;
827
- /**
828
- * The version the stored data is migrating **from**.
829
- *
830
- * Version `0` is allowed, enabling migrations from unversioned data.
831
- */
832
- fromVersion: number;
833
- /**
834
- * The version the stored data is migrating **to**.
835
- *
836
- * When equal to `fromVersion`, this rule is a write-time normalizer
837
- * that runs on every write to that version.
838
- */
839
- toVersion: number;
840
- /**
841
- * Transformation function that converts data from `fromVersion`
842
- * to `toVersion`.
843
- *
844
- * Receives the decoded value at `fromVersion` and must return
845
- * the value in the shape expected by `toVersion`.
846
- *
847
- * @param value - The decoded value at `fromVersion`
848
- * @returns The transformed value for `toVersion`
849
- */
850
- migrate(value: TFrom): TTo;
851
- };
852
- /**
853
- * An ordered sequence of {@link MigrationRule} steps that upgrades stored
854
- * data from an older schema version to a newer one.
855
- *
856
- * The rules are applied in array order. Each step's output becomes the
857
- * next step's input. After the final step the result is validated against
858
- * the target schema and persisted back to storage so the migration only
859
- * runs once per key.
860
- *
861
- * @see {@link MigrationRule} - Individual migration step
862
- * @see {@link SchemaRegistry.getMigrationPath} - Resolves a path between versions
863
- */
864
- type MigrationPath<K extends string = string> = MigrationRule<unknown, unknown, K>[];
865
- /**
866
- * Input options for {@link createSchemaRegistry}.
867
- *
868
- * Use this helper when your registry contents are known up front and do not
869
- * need runtime mutation. The returned registry is immutable and optimized for
870
- * the common `"default"` / `"strict"` setup.
871
- *
872
- * For most apps, this should be your default entry point for schema-managed
873
- * persistence. Implement {@link SchemaRegistry} manually only when you need
874
- * custom lookup behavior or runtime schema registration beyond autoschema mode.
875
- */
876
- interface CreateSchemaRegistryOptions {
877
- /**
878
- * Versioned schemas to index by key and version.
879
- *
880
- * Duplicate `key + version` pairs are rejected up front with
881
- * `SchemaError("SCHEMA_REGISTRATION_CONFLICT")`.
882
- */
883
- schemas?: readonly KeySchema[];
884
- /**
885
- * Migration rules to index by key and version edge.
886
- *
887
- * Write-time normalizers (`fromVersion === toVersion`) are indexed
888
- * separately from read-time migration edges. Ambiguous outgoing edges,
889
- * backward migrations, and duplicate write normalizers are rejected up
890
- * front with `SchemaError("MIGRATION_GRAPH_INVALID")`.
891
- */
892
- migrations?: readonly MigrationRule[];
893
- }
894
- /**
895
- * Lookup and registration API for key schemas and migration paths.
896
- *
897
- * Implementations of this interface are passed to `MnemonicProvider` via the
898
- * `schemaRegistry` option. The provider calls these methods at read and write
899
- * time to resolve the correct JSON Schema and migration chain for each
900
- * stored value.
901
- *
902
- * In `"default"` and `"strict"` modes, callers should treat registry contents
903
- * as immutable after provider initialization. The hook caches lookups to keep
904
- * read/write hot paths fast. `"autoschema"` remains mutable to support
905
- * inferred schema registration.
906
- *
907
- * Most applications should prefer {@link createSchemaRegistry} instead of
908
- * implementing this interface manually. Manual implementations are mainly for
909
- * advanced cases such as custom backing stores, dynamic schema discovery, or
910
- * adapter layers around an existing registry system.
911
- *
912
- * @example
913
- * ```typescript
914
- * const registry = createSchemaRegistry({
915
- * schemas: [
916
- * { key: "settings", version: 1, schema: { type: "object", required: ["theme"] } },
917
- * ],
918
- * migrations: [],
919
- * });
920
- *
921
- * <MnemonicProvider namespace="app" schemaRegistry={registry} schemaMode="strict">
922
- * <App />
923
- * </MnemonicProvider>
924
- * ```
925
- *
926
- * @see {@link KeySchema} - Schema definition
927
- * @see {@link MigrationPath} - Migration chain returned by `getMigrationPath`
928
- * @see {@link SchemaMode} - How the provider uses the registry
929
- */
930
- interface SchemaRegistry {
931
- /**
932
- * Look up the schema registered for a specific key and version.
933
- *
934
- * @param key - The unprefixed storage key
935
- * @param version - The version number to look up
936
- * @returns The matching schema, or `undefined` if none is registered
937
- */
938
- getSchema(key: string, version: number): KeySchema | undefined;
939
- /**
940
- * Look up the highest-version schema registered for a key.
941
- *
942
- * Used by the write path to determine which version to stamp on new
943
- * values, and by the read path to detect when a migration is needed.
944
- *
945
- * @param key - The unprefixed storage key
946
- * @returns The latest schema, or `undefined` if none is registered
947
- */
948
- getLatestSchema(key: string): KeySchema | undefined;
949
- /**
950
- * Resolve an ordered migration path between two versions of a key.
951
- *
952
- * Returns `null` when no contiguous path exists. The returned rules
953
- * are applied in order to transform data from `fromVersion` to
954
- * `toVersion`.
955
- *
956
- * @param key - The unprefixed storage key
957
- * @param fromVersion - The stored data's current version
958
- * @param toVersion - The target version to migrate to
959
- * @returns An ordered array of migration rules, or `null`
960
- */
961
- getMigrationPath(key: string, fromVersion: number, toVersion: number): MigrationPath | null;
962
- /**
963
- * Look up a write-time normalizer for a specific key and version.
964
- *
965
- * A write-time normalizer is a {@link MigrationRule} where
966
- * `fromVersion === toVersion`. It runs on every write to that version,
967
- * transforming the value before storage. The normalized value is
968
- * re-validated against the schema after transformation.
969
- *
970
- * Optional. When not implemented or returns `undefined`, no write-time
971
- * normalization is applied.
972
- *
973
- * @param key - The unprefixed storage key
974
- * @param version - The target schema version
975
- * @returns The normalizer rule, or `undefined` if none is registered
976
- */
977
- getWriteMigration?(key: string, version: number): MigrationRule | undefined;
978
- /**
979
- * Register a new schema.
980
- *
981
- * Optional. Required when `schemaMode` is `"autoschema"` so the
982
- * library can persist inferred schemas. Implementations should throw
983
- * if a schema already exists for the same key + version with a
984
- * conflicting definition.
985
- *
986
- * @param schema - The schema to register
987
- */
988
- registerSchema?(schema: KeySchema): void;
989
- }
990
- /**
991
- * Storage interface compatible with localStorage and synchronous custom storage implementations.
992
- *
993
- * Defines the minimum contract required for a storage backend. Compatible with
994
- * browser Storage API (localStorage, sessionStorage) and custom implementations
995
- * for testing or alternative storage solutions.
996
- *
997
- * All methods in this contract are intentionally synchronous. Promise-returning
998
- * adapters such as React Native `AsyncStorage` are not directly supported by
999
- * `StorageLike`; instead, keep a synchronous in-memory cache and flush to async
1000
- * persistence outside the hook contract.
1001
- *
1002
- * @remarks
1003
- * **Error handling contract**
1004
- *
1005
- * The library wraps every storage call in a try/catch. Errors are handled as
1006
- * follows:
1007
- *
1008
- * - **`DOMException` with `name === "QuotaExceededError"`** — Logged once via
1009
- * `console.error` with the prefix `[Mnemonic] Storage quota exceeded`.
1010
- * Squelched until a write succeeds, then the flag resets.
1011
- *
1012
- * - **Other `DOMException` errors (including `SecurityError`)** — Logged once
1013
- * via `console.error` with the prefix `[Mnemonic] Storage access error`.
1014
- * Squelched until any storage operation succeeds, then the flag resets.
1015
- *
1016
- * - **All other error types** — Silently suppressed.
1017
- *
1018
- * Custom `StorageLike` implementations are encouraged to throw `DOMException`
1019
- * for storage access failures so the library can surface diagnostics. Throwing
1020
- * non-`DOMException` errors is safe but results in silent suppression.
1021
- *
1022
- * In all error cases the library falls back to its in-memory cache, so
1023
- * components continue to function when the storage backend is unavailable.
1024
- *
1025
- * Promise-returning `getItem`, `setItem`, or `removeItem` implementations are
1026
- * treated as an invalid contract at runtime. Mnemonic logs the misuse once and
1027
- * falls back to its in-memory cache for safety.
1028
- *
1029
- * @example
1030
- * ```typescript
1031
- * // In-memory storage for testing
1032
- * const mockStorage: StorageLike = {
1033
- * items: new Map<string, string>(),
1034
- * getItem(key) { return this.items.get(key) ?? null; },
1035
- * setItem(key, value) { this.items.set(key, value); },
1036
- * removeItem(key) { this.items.delete(key); },
1037
- * get length() { return this.items.size; },
1038
- * key(index) {
1039
- * return Array.from(this.items.keys())[index] ?? null;
1040
- * }
1041
- * };
1042
- * ```
1043
- */
1044
- type StorageLike = {
1045
- /**
1046
- * Retrieves the value associated with a key.
1047
- *
1048
- * @param key - The storage key to retrieve
1049
- * @returns The stored value as a string, or null if not found
1050
- *
1051
- * @remarks Must return synchronously. Returning a Promise is unsupported.
1052
- */
1053
- getItem(key: string): string | null;
1054
- /**
1055
- * Stores a key-value pair.
1056
- *
1057
- * @param key - The storage key
1058
- * @param value - The string value to store
1059
- *
1060
- * @remarks Must complete synchronously. Returning a Promise is unsupported.
1061
- */
1062
- setItem(key: string, value: string): void;
1063
- /**
1064
- * Removes a key-value pair from storage.
1065
- *
1066
- * @param key - The storage key to remove
1067
- *
1068
- * @remarks Must complete synchronously. Returning a Promise is unsupported.
1069
- */
1070
- removeItem(key: string): void;
1071
- /**
1072
- * Returns the key at the specified index in storage.
1073
- *
1074
- * Optional method for enumeration support.
1075
- *
1076
- * @param index - The numeric index
1077
- * @returns The key at the given index, or null if out of bounds
1078
- */
1079
- key?(index: number): string | null;
1080
- /**
1081
- * The number of items currently stored.
1082
- *
1083
- * Optional property for enumeration support.
1084
- */
1085
- readonly length?: number;
1086
- /**
1087
- * Subscribe to notifications when data changes externally.
1088
- *
1089
- * localStorage has built-in cross-tab notification via the browser's
1090
- * native `storage` event (used by the `listenCrossTab` hook option).
1091
- * Non-localStorage backends (IndexedDB, custom stores, etc.) lack this
1092
- * built-in mechanism. Implementing `onExternalChange` allows those
1093
- * adapters to provide equivalent cross-tab synchronization through
1094
- * their own transport (e.g., BroadcastChannel).
1095
- *
1096
- * The callback accepts an optional `changedKeys` parameter:
1097
- * - `callback()` or `callback(undefined)` triggers a blanket reload
1098
- * of all actively subscribed keys.
1099
- * - `callback(["ns.key1", "ns.key2"])` reloads only the specified
1100
- * fully-qualified keys, which is more efficient when the adapter
1101
- * knows exactly which keys changed.
1102
- * - `callback([])` is a no-op.
1103
- *
1104
- * On a blanket reload the provider re-reads all actively subscribed
1105
- * keys from the storage backend and emits change notifications for
1106
- * any whose values differ from the cache.
1107
- *
1108
- * @param callback - Invoked when external data changes
1109
- * @returns An unsubscribe function that removes the callback
1110
- */
1111
- onExternalChange?: (callback: (changedKeys?: string[]) => void) => () => void;
1112
- };
1113
- /**
1114
- * Function type for unsubscribing from event listeners.
1115
- *
1116
- * Call this function to remove a subscription and stop receiving updates.
1117
- *
1118
- * @example
1119
- * ```typescript
1120
- * const unsubscribe = store.subscribeRaw('user', () => console.log('Updated!'));
1121
- * // Later...
1122
- * unsubscribe(); // Stop listening
1123
- * ```
1124
- */
1125
- type Unsubscribe = () => void;
1126
- /**
1127
- * Callback function invoked when a subscribed value changes.
1128
- *
1129
- * Used by the external store contract to notify React when state updates.
1130
- */
1131
- type Listener = () => void;
1132
- /**
1133
- * Low-level Mnemonic store API provided via React Context.
1134
- *
1135
- * This interface powers `MnemonicProvider` internally and is also exposed to
1136
- * advanced consumers through `MnemonicDevToolsProviderApi.getStore()`. Typical
1137
- * application code should still prefer `useMnemonicKey`.
1138
- *
1139
- * All keys passed to these methods should be **unprefixed**. The store
1140
- * automatically applies the namespace prefix internally.
1141
- *
1142
- * @remarks
1143
- * This implements the React `useSyncExternalStore` contract for efficient,
1144
- * tearing-free state synchronization. Most application code should still
1145
- * prefer `useMnemonicKey`; this type mainly appears in the DevTools API via
1146
- * `MnemonicDevToolsProviderApi.getStore()`.
1147
- */
1148
- type Mnemonic = {
1149
- /**
1150
- * The namespace prefix applied to all keys in storage.
1151
- *
1152
- * Keys are stored as `${prefix}${key}` in the underlying storage backend.
1153
- */
1154
- prefix: string;
1155
- /**
1156
- * Whether the active storage backend can enumerate keys in this namespace.
1157
- *
1158
- * This is `true` for `localStorage`-like backends that implement both
1159
- * `length` and `key(index)`. Namespace-wide recovery helpers rely on this
1160
- * capability unless the caller supplies an explicit key list.
1161
- */
1162
- canEnumerateKeys: boolean;
1163
- /**
1164
- * Subscribe to changes for a specific key.
1165
- *
1166
- * Follows the React external store subscription contract. The listener
1167
- * will be called whenever the value for this key changes.
1168
- *
1169
- * @param key - The unprefixed storage key to subscribe to
1170
- * @param listener - Callback invoked when the value changes
1171
- * @returns Unsubscribe function to stop listening
1172
- *
1173
- * @example
1174
- * ```typescript
1175
- * const unsubscribe = store.subscribeRaw('user', () => {
1176
- * console.log('User changed:', store.getRawSnapshot('user'));
1177
- * });
1178
- * ```
1179
- */
1180
- subscribeRaw: (key: string, listener: Listener) => Unsubscribe;
1181
- /**
1182
- * Get the current raw string value for a key.
1183
- *
1184
- * This is part of the external store snapshot contract. Values are
1185
- * cached in memory for stable snapshots.
1186
- *
1187
- * @param key - The unprefixed storage key
1188
- * @returns The raw string value, or null if not present
1189
- */
1190
- getRawSnapshot: (key: string) => string | null;
1191
- /**
1192
- * Write a raw string value to storage.
1193
- *
1194
- * Updates both the in-memory cache and the underlying storage backend,
1195
- * then notifies all subscribers for this key.
1196
- *
1197
- * @param key - The unprefixed storage key
1198
- * @param raw - The raw string value to store
1199
- */
1200
- setRaw: (key: string, raw: string) => void;
1201
- /**
1202
- * Remove a key from storage.
1203
- *
1204
- * Clears the value from both the cache and the underlying storage,
1205
- * then notifies all subscribers.
1206
- *
1207
- * @param key - The unprefixed storage key to remove
1208
- */
1209
- removeRaw: (key: string) => void;
1210
- /**
1211
- * Enumerate all keys in this namespace.
1212
- *
1213
- * Returns unprefixed keys that belong to this store's namespace.
1214
- *
1215
- * @returns Array of unprefixed key names
1216
- */
1217
- keys: () => string[];
1218
- /**
1219
- * Dump all key-value pairs in this namespace.
1220
- *
1221
- * Useful for debugging and DevTools integration.
1222
- *
1223
- * @returns Object mapping unprefixed keys to raw string values
1224
- */
1225
- dump: () => Record<string, string>;
1226
- /**
1227
- * The active schema enforcement mode for this provider.
1228
- *
1229
- * Propagated from the `schemaMode` provider option. Hooks read this
1230
- * to determine how to handle versioned envelopes.
1231
- *
1232
- * @see {@link SchemaMode}
1233
- */
1234
- schemaMode: SchemaMode;
1235
- /**
1236
- * Default hydration strategy inherited by descendant hooks.
1237
- */
1238
- ssrHydration: MnemonicHydrationMode;
1239
- /**
1240
- * How this provider can observe external changes from other tabs/processes.
1241
- *
1242
- * Hooks use this for development diagnostics when callers opt into
1243
- * cross-tab synchronization on a backend that cannot actually deliver it.
1244
- *
1245
- * When omitted, consumers should treat this as equivalent to `"none"`.
1246
- */
1247
- crossTabSyncMode?: "browser-storage-event" | "custom-external-change" | "none";
1248
- /**
1249
- * The schema registry for this provider, if one was supplied.
1250
- *
1251
- * Hooks use this to look up schemas, resolve migration paths, and
1252
- * (in autoschema mode) register inferred schemas.
1253
- *
1254
- * @see {@link SchemaRegistry}
1255
- */
1256
- schemaRegistry?: SchemaRegistry;
1257
- };
1258
- /**
1259
- * Recovery action names emitted by {@link useMnemonicRecovery}.
1260
- */
1261
- type MnemonicRecoveryAction = "clear-all" | "clear-keys" | "clear-matching";
1262
- /**
1263
- * Recovery event payload emitted after a namespace recovery action completes.
1264
- */
1265
- interface MnemonicRecoveryEvent {
1266
- /**
1267
- * Recovery action that just ran.
1268
- */
1269
- action: MnemonicRecoveryAction;
1270
- /**
1271
- * Namespace where the recovery action ran.
1272
- */
1273
- namespace: string;
1274
- /**
1275
- * Unprefixed keys cleared by the action.
1276
- */
1277
- clearedKeys: string[];
1278
- }
1279
- /**
1280
- * Options for {@link useMnemonicRecovery}.
1281
- */
1282
- interface UseMnemonicRecoveryOptions {
1283
- /**
1284
- * Optional callback invoked after a recovery action completes.
1285
- *
1286
- * Useful for analytics, audit trails, support diagnostics, or user-facing
1287
- * confirmation toasts.
1288
- */
1289
- onRecover?: (event: MnemonicRecoveryEvent) => void;
1290
- }
1291
- /**
1292
- * Namespace-scoped recovery helpers returned by {@link useMnemonicRecovery}.
1293
- *
1294
- * These helpers operate on the current provider namespace and are intended for
1295
- * user-facing recovery UX such as "reset app data" or "clear stale filters".
1296
- */
1297
- interface MnemonicRecoveryHook {
1298
- /**
1299
- * Current provider namespace without the trailing storage prefix dot.
1300
- */
1301
- namespace: string;
1302
- /**
1303
- * Whether namespace keys can be enumerated automatically.
1304
- *
1305
- * `clearAll()` and `clearMatching()` require this to be `true`. If it is
1306
- * `false`, prefer `clearKeys([...])` with an explicit durable-key list.
1307
- */
1308
- canEnumerateKeys: boolean;
1309
- /**
1310
- * Lists all unprefixed keys currently visible in this namespace.
1311
- *
1312
- * Returns an empty array when no keys exist or when the storage backend
1313
- * cannot enumerate keys.
1314
- */
1315
- listKeys: () => string[];
1316
- /**
1317
- * Clears every key in the current namespace.
1318
- *
1319
- * @throws {Error} When the storage backend cannot enumerate namespace keys
1320
- */
1321
- clearAll: () => string[];
1322
- /**
1323
- * Clears a specific set of unprefixed keys in the current namespace.
1324
- *
1325
- * Duplicate keys are ignored.
1326
- */
1327
- clearKeys: (keys: readonly string[]) => string[];
1328
- /**
1329
- * Clears namespace keys whose names match the supplied predicate.
1330
- *
1331
- * @throws {Error} When the storage backend cannot enumerate namespace keys
1332
- */
1333
- clearMatching: (predicate: (key: string) => boolean) => string[];
1334
- }
1335
- /**
1336
- * Return shape from {@link useMnemonicKey}.
1337
- *
1338
- * This mirrors the familiar `useState` mental model while making the storage
1339
- * semantics explicit:
1340
- *
1341
- * - `set(...)` writes a new persisted value
1342
- * - `reset()` writes `defaultValue` back into storage
1343
- * - `remove()` deletes the key entirely so reads fall back to `defaultValue`
1344
- *
1345
- * See the
1346
- * [Clearable Persisted Values guide](https://thirtytwobits.github.io/react-mnemonic/docs/guides/clearable-persisted-values)
1347
- * for the semantic differences between clearing, resetting, and removing a key.
1348
- *
1349
- * @template T - The decoded value type for the key
1350
- *
1351
- * @see {@link UseMnemonicKeyOptions} - Hook configuration and lifecycle details
1352
- */
1353
- interface MnemonicKeyState<T> {
1354
- /**
1355
- * Current decoded value, or the default when the key is absent or invalid.
1356
- */
1357
- value: T;
1358
- /**
1359
- * Persist a new value.
1360
- *
1361
- * Accepts either a direct replacement value or an updater function that
1362
- * receives the current decoded value.
1363
- */
1364
- set: (next: T | ((current: T) => T)) => void;
1365
- /**
1366
- * Reset the key back to `defaultValue` and persist that default.
1367
- */
1368
- reset: () => void;
1369
- /**
1370
- * Delete the key from storage entirely.
1371
- *
1372
- * Future reads will fall back to `defaultValue` until the key is written
1373
- * again.
1374
- */
1375
- remove: () => void;
1376
- }
1377
- /**
1378
- * Reusable, importable contract for a single persisted key.
1379
- *
1380
- * Descriptors package the key name and its `useMnemonicKey(...)` options into
1381
- * a stable object that can be defined once at module scope and reused across
1382
- * components. This helps keep persistence behavior explicit and consistent,
1383
- * especially when the same key appears in multiple parts of an application.
1384
- *
1385
- * @template T - The decoded value type for the key
1386
- * @template K - The literal key name
1387
- *
1388
- * @example
1389
- * ```typescript
1390
- * const themeKey = defineMnemonicKey("theme", {
1391
- * defaultValue: "light" as "light" | "dark",
1392
- * listenCrossTab: true,
1393
- * });
1394
- *
1395
- * const { value, set } = useMnemonicKey(themeKey);
1396
- * ```
1397
- *
1398
- * @see {@link defineMnemonicKey} - Helper for creating descriptors
1399
- * @see {@link useMnemonicKey} - Hook that consumes descriptors
1400
- */
1401
- interface MnemonicKeyDescriptor<T, K extends string = string> {
1402
- /**
1403
- * Unprefixed storage key name.
1404
- */
1405
- readonly key: K;
1406
- /**
1407
- * Canonical options for this key.
1408
- */
1409
- readonly options: UseMnemonicKeyOptions<T>;
1410
- }
1411
- /**
1412
- * Key descriptor options inferred from a typed key schema.
1413
- *
1414
- * This mirrors `UseMnemonicKeyOptions<T>` but intentionally omits the `schema`
1415
- * override so the descriptor stays pinned to the supplied key schema version.
1416
- */
1417
- type SchemaBoundKeyOptions<T> = Omit<UseMnemonicKeyOptions<T>, "schema">;
1418
- /**
1419
- * Typed key schema shape inferred from a schema helper or branded JSON Schema.
1420
- *
1421
- * Useful when you want a versioned schema object to carry its decoded
1422
- * TypeScript value through registries, descriptors, and migration helpers.
1423
- */
1424
- type TypedKeySchema<TSchema extends JsonSchema, K extends string = string> = KeySchema<InferJsonSchemaValue<TSchema>, K, TSchema>;
1425
- /**
1426
- * Configuration options for the useMnemonicKey hook.
1427
- *
1428
- * These options control how a value is persisted, decoded, and
1429
- * synchronized across the application.
1430
- *
1431
- * @template T - The TypeScript type of the stored value
1432
- *
1433
- * @example
1434
- * ```typescript
1435
- * const { value, set } = useMnemonicKey<User>('currentUser', {
1436
- * defaultValue: { name: 'Guest', id: null },
1437
- * onMount: (user) => console.log('Loaded user:', user),
1438
- * onChange: (current, previous) => {
1439
- * console.log('User changed from', previous, 'to', current);
1440
- * },
1441
- * listenCrossTab: true
1442
- * });
1443
- * ```
1444
- */
1445
- type UseMnemonicKeyOptions<T> = {
1446
- /**
1447
- * Default value to use when no stored value exists, or when decoding/validation fails.
1448
- *
1449
- * Can be a literal value or a factory function that returns the default.
1450
- * Factory functions receive an optional error argument describing why the
1451
- * fallback is being used:
1452
- *
1453
- * - `undefined` — Nominal path: no value exists in storage for this key.
1454
- * - `CodecError` — The stored value could not be decoded by the codec.
1455
- * - `SchemaError` — A schema, migration, or validation issue occurred
1456
- * (e.g. missing schema, failed migration, JSON Schema validation failure).
1457
- *
1458
- * Static (non-function) default values ignore the error entirely.
1459
- *
1460
- * @remarks
1461
- * If a factory function is defined inline, it creates a new reference on
1462
- * every render, which forces internal memoization to recompute. For best
1463
- * performance, define the factory at module level or wrap it in `useCallback`:
1464
- *
1465
- * ```typescript
1466
- * // Module-level (stable reference, preferred)
1467
- * const getDefault = (error?: CodecError | SchemaError) => {
1468
- * if (error) console.warn('Fallback:', error.message);
1469
- * return { count: 0 };
1470
- * };
1471
- *
1472
- * // Or with useCallback inside a component
1473
- * const getDefault = useCallback(
1474
- * (error?: CodecError | SchemaError) => ({ count: 0 }),
1475
- * [],
1476
- * );
1477
- * ```
1478
- *
1479
- * @example
1480
- * ```typescript
1481
- * // Static default
1482
- * defaultValue: { count: 0 }
1483
- *
1484
- * // Factory with no error handling
1485
- * defaultValue: () => ({ timestamp: Date.now() })
1486
- *
1487
- * // Error-aware factory
1488
- * defaultValue: (error) => {
1489
- * if (error instanceof CodecError) {
1490
- * console.error('Corrupt data:', error.message);
1491
- * }
1492
- * if (error instanceof SchemaError) {
1493
- * console.warn('Schema issue:', error.code, error.message);
1494
- * }
1495
- * return { count: 0 };
1496
- * }
1497
- * ```
1498
- */
1499
- defaultValue: T | ((error?: CodecError | SchemaError) => T);
1500
- /**
1501
- * Codec for encoding and decoding values to/from storage.
1502
- *
1503
- * Determines how the typed value is serialized to a string and
1504
- * deserialized back. Defaults to JSONCodec if not specified.
1505
- *
1506
- * Using a codec is a low-level option that bypasses JSON Schema
1507
- * validation. Schema-managed keys store JSON values directly and
1508
- * are validated against their registered JSON Schema.
1509
- *
1510
- * @default JSONCodec
1511
- *
1512
- * @example
1513
- * ```typescript
1514
- * // Custom codec for dates
1515
- * codec: createCodec(
1516
- * (date) => date.toISOString(),
1517
- * (str) => new Date(str)
1518
- * )
1519
- * ```
1520
- */
1521
- codec?: Codec<T>;
1522
- /**
1523
- * Optional read-time reconciliation hook for persisted values.
1524
- *
1525
- * Runs after a stored value has been decoded and any read-time migrations
1526
- * have completed, but before the hook exposes the value to React. This is
1527
- * useful for selectively enforcing newly shipped defaults or normalizing
1528
- * legacy persisted values without discarding the whole key.
1529
- *
1530
- * If the reconciled value would persist differently from the pre-reconcile
1531
- * value, the hook rewrites storage once using the normal write path.
1532
- *
1533
- * @remarks
1534
- * Prefer schema migrations for structural changes that must always happen
1535
- * between explicit versions. Use `reconcile` for conditional, field-level
1536
- * adjustments that depend on application policy rather than a strict schema
1537
- * upgrade step.
1538
- *
1539
- * See the Schema Migration guide for migration-vs-reconciliation guidance:
1540
- * https://thirtytwobits.github.io/react-mnemonic/docs/guides/schema-migration
1541
- *
1542
- * If `reconcile` throws a `SchemaError`, that error is preserved and passed
1543
- * to `defaultValue`. Any other thrown error is wrapped as
1544
- * `SchemaError("RECONCILE_FAILED")`.
1545
- *
1546
- * @param value - The decoded persisted value
1547
- * @param context - Metadata about the stored and latest schema versions
1548
- *
1549
- * @example
1550
- * ```typescript
1551
- * reconcile: (value, { persistedVersion }) => ({
1552
- * ...value,
1553
- * theme: persistedVersion < 2 ? "dark" : value.theme,
1554
- * })
1555
- * ```
1556
- */
1557
- reconcile?: (value: T, context: ReconcileContext) => T;
1558
- /**
1559
- * Callback invoked once when the hook is first mounted.
1560
- *
1561
- * Receives the initial value (either from storage or the default).
1562
- * Useful for triggering side effects based on the loaded state.
1563
- *
1564
- * @param value - The initial value loaded on mount
1565
- *
1566
- * @example
1567
- * ```typescript
1568
- * onMount: (theme) => {
1569
- * document.body.className = theme;
1570
- * console.log('Theme loaded:', theme);
1571
- * }
1572
- * ```
1573
- */
1574
- onMount?: (value: T) => void;
1575
- /**
1576
- * Callback invoked whenever the value changes.
1577
- *
1578
- * Receives both the new value and the previous value. This is called
1579
- * for all changes, including those triggered by other components or tabs.
1580
- *
1581
- * @param value - The new current value
1582
- * @param prev - The previous value
1583
- *
1584
- * @example
1585
- * ```typescript
1586
- * onChange: (newTheme, oldTheme) => {
1587
- * document.body.classList.remove(oldTheme);
1588
- * document.body.classList.add(newTheme);
1589
- * console.log(`Theme changed: ${oldTheme} -> ${newTheme}`);
1590
- * }
1591
- * ```
1592
- */
1593
- onChange?: (value: T, prev: T) => void;
1594
- /**
1595
- * Enable listening for changes from other browser tabs.
1596
- *
1597
- * When true, uses the browser's `storage` event to detect changes
1598
- * made to localStorage in other tabs and synchronizes them to this component.
1599
- *
1600
- * Only effective when using localStorage as the storage backend.
1601
- *
1602
- * @default false
1603
- *
1604
- * @example
1605
- * ```typescript
1606
- * // Enable cross-tab sync for shared state
1607
- * listenCrossTab: true
1608
- * ```
1609
- *
1610
- * @remarks
1611
- * The `storage` event only fires for changes made in *other* tabs,
1612
- * not the current tab. Changes within the same tab are synchronized
1613
- * automatically via React's state management.
1614
- */
1615
- listenCrossTab?: boolean;
1616
- /**
1617
- * Server-rendering controls for this key.
1618
- *
1619
- * Use this when the server should render a value other than
1620
- * `defaultValue`, or when persisted storage should only be read after the
1621
- * component has mounted on the client.
1622
- *
1623
- * @example
1624
- * ```typescript
1625
- * ssr: {
1626
- * serverValue: { theme: "system" },
1627
- * hydration: "client-only",
1628
- * }
1629
- * ```
1630
- */
1631
- ssr?: MnemonicKeySSRConfig<T>;
1632
- /**
1633
- * Optional schema controls for this key.
1634
- *
1635
- * Allows overriding the version written by the `set` function. When
1636
- * omitted, the library writes using the highest registered schema for
1637
- * this key, or version `0` when no schemas are registered.
1638
- *
1639
- * @example
1640
- * ```typescript
1641
- * // Pin writes to schema version 2 even if version 3 exists
1642
- * const { value, set } = useMnemonicKey("user", {
1643
- * defaultValue: { name: "" },
1644
- * schema: { version: 2 },
1645
- * });
1646
- * ```
1647
- */
1648
- schema?: {
1649
- /**
1650
- * Explicit schema version to use when writing values.
1651
- *
1652
- * When set, the `set` and `reset` functions encode using the
1653
- * schema registered at this version instead of the latest. Useful
1654
- * during gradual rollouts where not all consumers have been
1655
- * updated yet.
1656
- *
1657
- * Must reference a version that exists in the `SchemaRegistry`.
1658
- * If not found the write falls back to the latest schema (default
1659
- * mode) or fails with a `SchemaError` (strict mode).
1660
- */
1661
- version?: number;
1662
- };
1663
- };
1664
- /**
1665
- * Metadata passed to `UseMnemonicKeyOptions.reconcile`.
1666
- */
1667
- type ReconcileContext = {
1668
- /**
1669
- * The unprefixed storage key being reconciled.
1670
- */
1671
- key: string;
1672
- /**
1673
- * The version found in the persisted envelope that was read.
1674
- */
1675
- persistedVersion: number;
1676
- /**
1677
- * The latest registered schema version for the key, when available.
1678
- */
1679
- latestVersion?: number;
1680
- };
1681
-
1682
- /**
1683
- * Props for the MnemonicProvider component.
1684
- *
1685
- * Extends MnemonicProviderOptions with required children prop.
1686
- *
1687
- * @see {@link MnemonicProviderOptions} - Configuration options
1688
- * @see {@link MnemonicProvider} - Provider component
1689
- */
1690
- interface MnemonicProviderProps extends Readonly<MnemonicProviderOptions> {
1691
- /**
1692
- * React children to render within the provider.
1693
- */
1694
- readonly children: ReactNode;
1695
- }
1696
- /**
1697
- * React Context provider for namespace-isolated persistent state.
1698
- *
1699
- * Creates a scoped storage environment where all keys are automatically prefixed
1700
- * with the namespace to prevent collisions. Implements an in-memory cache with
1701
- * read-through behavior to the underlying storage backend (localStorage by default).
1702
- *
1703
- * This provider must wrap any components that use `useMnemonicKey`. Multiple
1704
- * providers with different namespaces can coexist in the same application.
1705
- *
1706
- * @param props - Provider configuration and children
1707
- * @param props.children - React children to render within the provider
1708
- * @param props.namespace - Unique namespace for isolating storage keys
1709
- * @param props.storage - Optional synchronous custom storage backend (defaults to localStorage)
1710
- * @param props.enableDevTools - Enable DevTools debugging interface (defaults to false)
1711
- * @param props.schemaMode - Schema enforcement mode (default: "default")
1712
- * @param props.schemaRegistry - Optional schema registry for storing schemas and migrations
1713
- * @param props.ssr - Optional SSR defaults for descendant hooks
1714
- *
1715
- * @example
1716
- * ```tsx
1717
- * // Basic usage with default settings
1718
- * function App() {
1719
- * return (
1720
- * <MnemonicProvider namespace="myApp">
1721
- * <MyComponents />
1722
- * </MnemonicProvider>
1723
- * );
1724
- * }
1725
- * ```
1726
- *
1727
- * @example
1728
- * ```tsx
1729
- * // With a synchronous custom storage backend
1730
- * function App() {
1731
- * return (
1732
- * <MnemonicProvider
1733
- * namespace="myApp"
1734
- * storage={window.sessionStorage}
1735
- * >
1736
- * <MyComponents />
1737
- * </MnemonicProvider>
1738
- * );
1739
- * }
1740
- * ```
1741
- *
1742
- * @example
1743
- * ```tsx
1744
- * // With DevTools enabled (development only)
1745
- * function App() {
1746
- * return (
1747
- * <MnemonicProvider
1748
- * namespace="myApp"
1749
- * enableDevTools={process.env.NODE_ENV === 'development'}
1750
- * >
1751
- * <MyComponents />
1752
- * </MnemonicProvider>
1753
- * );
1754
- * }
1755
- *
1756
- * // Then in browser console:
1757
- * const dt = window.__REACT_MNEMONIC_DEVTOOLS__.resolve('myApp')
1758
- * dt?.dump()
1759
- * dt?.get('user')
1760
- * dt?.set('theme', 'dark')
1761
- * ```
1762
- *
1763
- * @example
1764
- * ```tsx
1765
- * // Multiple providers with different namespaces
1766
- * function App() {
1767
- * return (
1768
- * <MnemonicProvider namespace="user-prefs">
1769
- * <UserSettings />
1770
- * <MnemonicProvider namespace="app-state">
1771
- * <Dashboard />
1772
- * </MnemonicProvider>
1773
- * </MnemonicProvider>
1774
- * );
1775
- * }
1776
- * ```
1777
- *
1778
- * @example
1779
- * ```tsx
1780
- * // Delay persisted storage reads until after client mount
1781
- * function App() {
1782
- * return (
1783
- * <MnemonicProvider
1784
- * namespace="myApp"
1785
- * ssr={{ hydration: "client-only" }}
1786
- * >
1787
- * <MyComponents />
1788
- * </MnemonicProvider>
1789
- * );
1790
- * }
1791
- * ```
1792
- *
1793
- * @remarks
1794
- * - Creates a stable store instance that only recreates when namespace, storage, or enableDevTools change
1795
- * - All storage operations are cached in memory for fast reads
1796
- * - Storage failures are handled gracefully (logged but not thrown)
1797
- * - `StorageLike` is intentionally synchronous for v1; async persistence must sit behind a sync facade
1798
- * - In SSR environments, the provider is safe by default: hooks render
1799
- * `defaultValue` unless configured with an explicit `ssr.serverValue`
1800
- * - The store implements React's useSyncExternalStore contract for efficient updates
1801
- *
1802
- * @see {@link useMnemonicKey} - Hook for using persistent state
1803
- * @see {@link MnemonicProviderOptions} - Configuration options
1804
- */
1805
- declare function MnemonicProvider({ children, namespace, storage, enableDevTools, schemaMode, schemaRegistry, ssr, }: MnemonicProviderProps): react_jsx_runtime.JSX.Element;
1806
-
1807
- /**
1808
- * React hook for persistent, type-safe state management.
1809
- *
1810
- * Creates a stateful value that persists to storage and synchronizes across
1811
- * components. Works like `useState` but with persistent storage, automatic
1812
- * encoding/decoding, JSON Schema validation, and optional cross-tab synchronization.
1813
- *
1814
- * Must be used within a `MnemonicProvider`. Uses React's `useSyncExternalStore`
1815
- * internally for efficient, tearing-free state synchronization.
1816
- *
1817
- * Read lifecycle, in order:
1818
- * 1. Load the raw stored envelope for `key`
1819
- * 2. Decode the payload (codec or schema-managed JSON)
1820
- * 3. Validate and migrate when schemas are registered
1821
- * 4. Run `reconcile(...)` if provided
1822
- * 5. Fall back to `defaultValue` when the key is absent or invalid
1823
- *
1824
- * Write semantics:
1825
- * - `set(...)` persists a new value
1826
- * - `reset()` persists `defaultValue`
1827
- * - `remove()` deletes the key entirely so future reads fall back to `defaultValue`
1828
- *
1829
- * For guide-level background, see the
1830
- * [Schema Migration guide](https://thirtytwobits.github.io/react-mnemonic/docs/guides/schema-migration)
1831
- * and the
1832
- * [Clearable Persisted Values guide](https://thirtytwobits.github.io/react-mnemonic/docs/guides/clearable-persisted-values).
1833
- *
1834
- * @template T - The TypeScript type of the stored value
1835
- *
1836
- * @returns Persistent state handle with the current value and mutation helpers
1837
- *
1838
- * @see {@link UseMnemonicKeyOptions} - Hook configuration and lifecycle details
1839
- *
1840
- * @throws {Error} If used outside of a MnemonicProvider
1841
- */
1842
- declare function useMnemonicKey<T, K extends string>(descriptor: MnemonicKeyDescriptor<T, K>): MnemonicKeyState<T>;
1843
- declare function useMnemonicKey<T>(key: string, options: UseMnemonicKeyOptions<T>): MnemonicKeyState<T>;
1844
-
1845
- /**
1846
- * Hook for namespace-scoped recovery actions such as hard reset and selective clear.
1847
- *
1848
- * Applications can use this to offer self-service recovery UX for corrupt or
1849
- * legacy persisted state. The hook operates on the current provider namespace.
1850
- *
1851
- * See the
1852
- * [Reset and Recovery guide](https://thirtytwobits.github.io/react-mnemonic/docs/guides/reset-and-recovery)
1853
- * for soft-reset and hard-reset patterns.
1854
- *
1855
- * @param options - Optional recovery callback for telemetry/auditing
1856
- * @returns Namespace recovery helpers
1857
- *
1858
- * @throws {Error} If used outside of a MnemonicProvider
1859
- */
1860
- declare function useMnemonicRecovery(options?: UseMnemonicRecoveryOptions): MnemonicRecoveryHook;
1861
-
1862
- /**
1863
- * Define a reusable, importable contract for a persisted key.
1864
- *
1865
- * This packages the storage key and the canonical `useMnemonicKey(...)`
1866
- * options into a single object that can be shared across components, docs,
1867
- * and generated code.
1868
- *
1869
- * @template K - The literal storage key name
1870
- * @template T - The decoded value type for the key
1871
- *
1872
- * @param key - The unprefixed storage key
1873
- * @param options - Canonical hook options for the key
1874
- * @returns A descriptor that can be passed directly to `useMnemonicKey(...)`
1875
- *
1876
- * @example
1877
- * ```typescript
1878
- * const themeKey = defineMnemonicKey("theme", {
1879
- * defaultValue: "light" as "light" | "dark",
1880
- * listenCrossTab: true,
1881
- * });
1882
- *
1883
- * const { value, set } = useMnemonicKey(themeKey);
1884
- * ```
1885
- */
1886
- declare function defineMnemonicKey<const K extends string, T>(key: K, options: UseMnemonicKeyOptions<T>): MnemonicKeyDescriptor<T, K>;
1887
- declare function defineMnemonicKey<const K extends string, TSchema extends KeySchema<unknown, K, JsonSchema>>(keySchema: TSchema, options: SchemaBoundKeyOptions<TSchema extends KeySchema<infer TValue, string, JsonSchema> ? TValue : never>): MnemonicKeyDescriptor<TSchema extends KeySchema<infer TValue, string, JsonSchema> ? TValue : never, TSchema["key"]>;
1888
-
1889
- /**
1890
- * Create an immutable schema registry for common default/strict-mode setups.
1891
- *
1892
- * The helper indexes schemas and migrations up front, validates duplicate and
1893
- * ambiguous definitions, and returns a {@link SchemaRegistry} ready to pass to
1894
- * `MnemonicProvider`.
1895
- *
1896
- * Most applications should prefer this helper over manually implementing
1897
- * {@link SchemaRegistry}.
1898
- *
1899
- * See the
1900
- * [Schema Migration guide](https://thirtytwobits.github.io/react-mnemonic/docs/guides/schema-migration)
1901
- * for end-to-end registry and migration patterns.
1902
- *
1903
- * @param options - Initial schema and migration definitions
1904
- * @returns An indexed immutable schema registry
1905
- *
1906
- * @throws {SchemaError} With `SCHEMA_REGISTRATION_CONFLICT` for duplicate
1907
- * schemas, or `MIGRATION_GRAPH_INVALID` for invalid migration graphs
1908
- */
1909
- declare function createSchemaRegistry(options?: CreateSchemaRegistryOptions): SchemaRegistry;
1910
-
1911
- /**
1912
- * Create a versioned key schema that preserves the decoded value type inferred
1913
- * from a typed schema helper.
1914
- */
1915
- declare function defineKeySchema<const K extends string, TSchema extends JsonSchema>(key: K, version: number, schema: TSchema): KeySchema<InferJsonSchemaValue<TSchema>, K, TSchema>;
1916
- /**
1917
- * Create a typed migration rule between two key schema versions.
1918
- *
1919
- * The `migrate(...)` callback is inferred from the source and target schemas,
1920
- * which keeps migration logic aligned with the registered runtime schemas.
1921
- */
1922
- declare function defineMigration<const K extends string, TFrom, TTo>(fromSchema: KeySchema<TFrom, K>, toSchema: KeySchema<TTo, K>, migrate: (value: TFrom) => TTo): MigrationRule<TFrom, TTo, K>;
1923
- /**
1924
- * Create a typed write-time normalization rule for a single key schema.
1925
- */
1926
- declare function defineWriteMigration<const K extends string, TValue>(schema: KeySchema<TValue, K>, migrate: (value: TValue) => TValue): MigrationRule<TValue, TValue, K>;
1927
-
1928
- /**
1929
- * Adapter functions for structural migration helpers.
1930
- *
1931
- * These helpers assume tree-like data, but not a specific node shape. Supply a
1932
- * `StructuralTreeHelpers<T>` when your nodes use custom field names. When your
1933
- * nodes already look like `{ id, children }`, the exported helpers work without
1934
- * any adapter configuration.
1935
- *
1936
- * @template T - Tree node type
1937
- */
1938
- interface StructuralTreeHelpers<T> {
1939
- /**
1940
- * Returns the stable identifier for a node.
1941
- */
1942
- getId: (node: T) => string;
1943
- /**
1944
- * Returns the node's child list, or `undefined` when it has no children.
1945
- */
1946
- getChildren: (node: T) => readonly T[] | undefined;
1947
- /**
1948
- * Returns a copy of the node with a new child list.
1949
- */
1950
- withChildren: (node: T, children: T[]) => T;
1951
- /**
1952
- * Returns a copy of the node with a new identifier.
1953
- */
1954
- withId: (node: T, id: string) => T;
1955
- }
1956
- /**
1957
- * Default tree node shape supported by the structural migration helpers.
1958
- *
1959
- * If your nodes already use `id` and `children`, you can call the helpers
1960
- * directly without supplying `StructuralTreeHelpers`.
1961
- *
1962
- * @template T - Tree node type
1963
- */
1964
- interface StructuralNode<T> {
1965
- /**
1966
- * Stable node identifier used for lookup and rename operations.
1967
- */
1968
- id: string;
1969
- /**
1970
- * Optional child nodes.
1971
- */
1972
- children?: readonly T[];
1973
- }
1974
- /**
1975
- * Finds the first node with the requested id using depth-first traversal.
1976
- *
1977
- * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1978
- * @param root - Root node to search
1979
- * @param id - Target node id
1980
- * @returns The matching node, or `undefined`
1981
- */
1982
- declare function findNodeById<T extends StructuralNode<T>>(root: T, id: string): T | undefined;
1983
- /**
1984
- * Finds the first node with the requested id using depth-first traversal.
1985
- *
1986
- * @template T - Tree node type
1987
- * @param root - Root node to search
1988
- * @param id - Target node id
1989
- * @param helpers - Adapter for custom node shapes
1990
- * @returns The matching node, or `undefined`
1991
- */
1992
- declare function findNodeById<T>(root: T, id: string, helpers: StructuralTreeHelpers<T>): T | undefined;
1993
- /**
1994
- * Inserts a child under the target parent when none of that parent's existing
1995
- * direct children share the same id. Returns the original tree when the parent
1996
- * is missing or the child is already present as a direct child.
1997
- *
1998
- * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
1999
- * @param root - Root node to update
2000
- * @param parentId - Parent node that should receive the child
2001
- * @param child - Child node to append
2002
- * @returns Updated tree with the child inserted once
2003
- */
2004
- declare function insertChildIfMissing<T extends StructuralNode<T>>(root: T, parentId: string, child: T): T;
2005
- /**
2006
- * Inserts a child under the target parent when no existing child shares the
2007
- * same id. Returns the original tree when the parent is missing or the child is
2008
- * already present.
2009
- *
2010
- * @template T - Tree node type
2011
- * @param root - Root node to update
2012
- * @param parentId - Parent node that should receive the child
2013
- * @param child - Child node to append
2014
- * @param helpers - Adapter for custom node shapes
2015
- * @returns Updated tree with the child inserted once
2016
- */
2017
- declare function insertChildIfMissing<T>(root: T, parentId: string, child: T, helpers: StructuralTreeHelpers<T>): T;
2018
- /**
2019
- * Renames every node with the source id while preserving tree structure.
2020
- * Returns the original tree when the source id is missing or the target id
2021
- * already exists elsewhere.
2022
- *
2023
- * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
2024
- * @param root - Root node to update
2025
- * @param currentId - Existing id to rename
2026
- * @param nextId - Replacement id
2027
- * @returns Updated tree with matching node ids renamed
2028
- */
2029
- declare function renameNode<T extends StructuralNode<T>>(root: T, currentId: string, nextId: string): T;
2030
- /**
2031
- * Renames every node with the source id while preserving tree structure.
2032
- * Returns the original tree when the source id is missing or the target id
2033
- * already exists elsewhere.
2034
- *
2035
- * @template T - Tree node type
2036
- * @param root - Root node to update
2037
- * @param currentId - Existing id to rename
2038
- * @param nextId - Replacement id
2039
- * @param helpers - Adapter for custom node shapes
2040
- * @returns Updated tree with matching node ids renamed
2041
- */
2042
- declare function renameNode<T>(root: T, currentId: string, nextId: string, helpers: StructuralTreeHelpers<T>): T;
2043
- /**
2044
- * Deduplicates each node's immediate children while preserving the first child
2045
- * encountered for each key. The helper traverses the full tree and returns the
2046
- * original root when no duplicates are removed.
2047
- *
2048
- * @template T - Tree node type (must extend `{ id: string; children?: readonly T[] }` when `helpers` is omitted)
2049
- * @template K - Deduplication key type
2050
- * @param root - Root node to normalize
2051
- * @param getKey - Function that computes a dedupe key for each child
2052
- * @returns Updated tree with duplicate siblings removed
2053
- */
2054
- declare function dedupeChildrenBy<T extends StructuralNode<T>, K>(root: T, getKey: (node: T) => K): T;
2055
- /**
2056
- * Deduplicates each node's immediate children while preserving the first child
2057
- * encountered for each key. The helper traverses the full tree and returns the
2058
- * original root when no duplicates are removed.
2059
- *
2060
- * @template T - Tree node type
2061
- * @template K - Deduplication key type
2062
- * @param root - Root node to normalize
2063
- * @param getKey - Function that computes a dedupe key for each child
2064
- * @param helpers - Adapter for custom node shapes
2065
- * @returns Updated tree with duplicate siblings removed
2066
- */
2067
- declare function dedupeChildrenBy<T, K>(root: T, getKey: (node: T) => K, helpers: StructuralTreeHelpers<T>): T;
2068
-
2069
- export { type Codec, CodecError, type CompiledValidator, type CreateSchemaRegistryOptions, type InferJsonSchemaValue, 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, type MnemonicHydrationMode, type MnemonicKeyDescriptor, type MnemonicKeySSRConfig, type MnemonicKeyState, MnemonicProvider, type MnemonicProviderOptions, type MnemonicProviderProps, type MnemonicProviderSSRConfig, type MnemonicRecoveryAction, type MnemonicRecoveryEvent, type MnemonicRecoveryHook, type ReconcileContext, type SchemaBoundKeyOptions, SchemaError, type SchemaMode, type SchemaRegistry, type StorageLike, type StructuralNode, type StructuralTreeHelpers, type TypedJsonSchema, type TypedKeySchema, type Unsubscribe, type UseMnemonicKeyOptions, type UseMnemonicRecoveryOptions, compileSchema, createCodec, createSchemaRegistry, dedupeChildrenBy, defineKeySchema, defineMigration, defineMnemonicKey, defineWriteMigration, findNodeById, insertChildIfMissing, mnemonicSchema, renameNode, useMnemonicKey, useMnemonicRecovery, validateJsonSchema };
1
+ export { MnemonicProvider, MnemonicProviderProps, StructuralNode, StructuralTreeHelpers, createSchemaRegistry, dedupeChildrenBy, defineKeySchema, defineMigration, defineWriteMigration, findNodeById, insertChildIfMissing, renameNode, useMnemonicKey } from './schema.cjs';
2
+ export { C as Codec, c as CodecError, D as CompiledValidator, y as CreateSchemaRegistryOptions, I as InferJsonSchemaValue, J as JSONCodec, A as JsonSchema, E as JsonSchemaType, F as JsonSchemaValidationError, K as KeySchema, L as Listener, G as MigrationPath, B as MigrationRule, d as Mnemonic, e as MnemonicDevToolsCapabilities, f as MnemonicDevToolsMeta, g as MnemonicDevToolsProviderApi, h as MnemonicDevToolsProviderDescriptor, i as MnemonicDevToolsProviderEntry, j as MnemonicDevToolsRegistry, k as MnemonicDevToolsWeakRef, l as MnemonicHydrationMode, a as MnemonicKeyDescriptor, m as MnemonicKeySSRConfig, b as MnemonicKeyState, M as MnemonicProviderOptions, n as MnemonicProviderSSRConfig, o as MnemonicRecoveryAction, p as MnemonicRecoveryEvent, q as MnemonicRecoveryHook, R as ReconcileContext, H as SchemaBoundKeyOptions, S as SchemaError, r as SchemaMode, z as SchemaRegistry, s as StorageLike, T as TypedJsonSchema, N as TypedKeySchema, t as Unsubscribe, U as UseMnemonicKeyOptions, u as UseMnemonicRecoveryOptions, O as compileSchema, v as createCodec, w as defineMnemonicKey, P as mnemonicSchema, x as useMnemonicRecovery, Q as validateJsonSchema } from './key-BvFvcKiR.cjs';
3
+ import 'react/jsx-runtime';
4
+ import 'react';