@tanstack/db 0.0.20 → 0.0.21
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/cjs/index.cjs +4 -0
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +2 -0
- package/dist/cjs/local-only.cjs +96 -0
- package/dist/cjs/local-only.cjs.map +1 -0
- package/dist/cjs/local-only.d.cts +114 -0
- package/dist/cjs/local-storage.cjs +267 -0
- package/dist/cjs/local-storage.cjs.map +1 -0
- package/dist/cjs/local-storage.d.cts +141 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/local-only.d.ts +114 -0
- package/dist/esm/local-only.js +96 -0
- package/dist/esm/local-only.js.map +1 -0
- package/dist/esm/local-storage.d.ts +141 -0
- package/dist/esm/local-storage.js +267 -0
- package/dist/esm/local-storage.js.map +1 -0
- package/package.json +1 -1
- package/src/index.ts +2 -0
- package/src/local-only.ts +302 -0
- package/src/local-storage.ts +644 -0
package/dist/cjs/index.cjs
CHANGED
|
@@ -6,6 +6,8 @@ const transactions = require("./transactions.cjs");
|
|
|
6
6
|
const errors = require("./errors.cjs");
|
|
7
7
|
const proxy = require("./proxy.cjs");
|
|
8
8
|
const optimisticAction = require("./optimistic-action.cjs");
|
|
9
|
+
const localOnly = require("./local-only.cjs");
|
|
10
|
+
const localStorage = require("./local-storage.cjs");
|
|
9
11
|
const index = require("./query/builder/index.cjs");
|
|
10
12
|
const functions = require("./query/builder/functions.cjs");
|
|
11
13
|
const index$1 = require("./query/compiler/index.cjs");
|
|
@@ -23,6 +25,8 @@ exports.createChangeProxy = proxy.createChangeProxy;
|
|
|
23
25
|
exports.withArrayChangeTracking = proxy.withArrayChangeTracking;
|
|
24
26
|
exports.withChangeTracking = proxy.withChangeTracking;
|
|
25
27
|
exports.createOptimisticAction = optimisticAction.createOptimisticAction;
|
|
28
|
+
exports.localOnlyCollectionOptions = localOnly.localOnlyCollectionOptions;
|
|
29
|
+
exports.localStorageCollectionOptions = localStorage.localStorageCollectionOptions;
|
|
26
30
|
exports.BaseQueryBuilder = index.BaseQueryBuilder;
|
|
27
31
|
exports.Query = index.Query;
|
|
28
32
|
exports.add = functions.add;
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/cjs/index.d.cts
CHANGED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
function localOnlyCollectionOptions(config) {
|
|
4
|
+
const { initialData, onInsert, onUpdate, onDelete, ...restConfig } = config;
|
|
5
|
+
const syncResult = createLocalOnlySync(initialData);
|
|
6
|
+
const wrappedOnInsert = async (params) => {
|
|
7
|
+
let handlerResult;
|
|
8
|
+
if (onInsert) {
|
|
9
|
+
handlerResult = await onInsert(params) ?? {};
|
|
10
|
+
}
|
|
11
|
+
syncResult.confirmOperationsSync(params.transaction.mutations);
|
|
12
|
+
return handlerResult;
|
|
13
|
+
};
|
|
14
|
+
const wrappedOnUpdate = async (params) => {
|
|
15
|
+
let handlerResult;
|
|
16
|
+
if (onUpdate) {
|
|
17
|
+
handlerResult = await onUpdate(params) ?? {};
|
|
18
|
+
}
|
|
19
|
+
syncResult.confirmOperationsSync(params.transaction.mutations);
|
|
20
|
+
return handlerResult;
|
|
21
|
+
};
|
|
22
|
+
const wrappedOnDelete = async (params) => {
|
|
23
|
+
let handlerResult;
|
|
24
|
+
if (onDelete) {
|
|
25
|
+
handlerResult = await onDelete(params) ?? {};
|
|
26
|
+
}
|
|
27
|
+
syncResult.confirmOperationsSync(params.transaction.mutations);
|
|
28
|
+
return handlerResult;
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
...restConfig,
|
|
32
|
+
sync: syncResult.sync,
|
|
33
|
+
onInsert: wrappedOnInsert,
|
|
34
|
+
onUpdate: wrappedOnUpdate,
|
|
35
|
+
onDelete: wrappedOnDelete,
|
|
36
|
+
utils: {},
|
|
37
|
+
startSync: true,
|
|
38
|
+
gcTime: 0
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function createLocalOnlySync(initialData) {
|
|
42
|
+
let syncBegin = null;
|
|
43
|
+
let syncWrite = null;
|
|
44
|
+
let syncCommit = null;
|
|
45
|
+
const sync = {
|
|
46
|
+
/**
|
|
47
|
+
* Sync function that captures sync parameters and applies initial data
|
|
48
|
+
* @param params - Sync parameters containing begin, write, and commit functions
|
|
49
|
+
* @returns Unsubscribe function (empty since no ongoing sync is needed)
|
|
50
|
+
*/
|
|
51
|
+
sync: (params) => {
|
|
52
|
+
const { begin, write, commit } = params;
|
|
53
|
+
syncBegin = begin;
|
|
54
|
+
syncWrite = write;
|
|
55
|
+
syncCommit = commit;
|
|
56
|
+
if (initialData && initialData.length > 0) {
|
|
57
|
+
begin();
|
|
58
|
+
initialData.forEach((item) => {
|
|
59
|
+
write({
|
|
60
|
+
type: `insert`,
|
|
61
|
+
value: item
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
commit();
|
|
65
|
+
}
|
|
66
|
+
return () => {
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
/**
|
|
70
|
+
* Get sync metadata - returns empty object for local-only collections
|
|
71
|
+
* @returns Empty metadata object
|
|
72
|
+
*/
|
|
73
|
+
getSyncMetadata: () => ({})
|
|
74
|
+
};
|
|
75
|
+
const confirmOperationsSync = (mutations) => {
|
|
76
|
+
if (!syncBegin || !syncWrite || !syncCommit) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
syncBegin();
|
|
80
|
+
mutations.forEach((mutation) => {
|
|
81
|
+
if (syncWrite) {
|
|
82
|
+
syncWrite({
|
|
83
|
+
type: mutation.type,
|
|
84
|
+
value: mutation.modified
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
syncCommit();
|
|
89
|
+
};
|
|
90
|
+
return {
|
|
91
|
+
sync,
|
|
92
|
+
confirmOperationsSync
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
exports.localOnlyCollectionOptions = localOnlyCollectionOptions;
|
|
96
|
+
//# sourceMappingURL=local-only.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-only.cjs","sources":["../../src/local-only.ts"],"sourcesContent":["import type {\n DeleteMutationFnParams,\n InsertMutationFnParams,\n OperationType,\n ResolveType,\n SyncConfig,\n UpdateMutationFnParams,\n UtilsRecord,\n} from \"./types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Configuration interface for Local-only collection options\n * @template TExplicit - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n * @template TKey - The type of the key returned by getKey\n *\n * @remarks\n * Type resolution follows a priority order:\n * 1. If you provide an explicit type via generic parameter, it will be used\n * 2. If no explicit type is provided but a schema is, the schema's output type will be inferred\n * 3. If neither explicit type nor schema is provided, the fallback type will be used\n *\n * You should provide EITHER an explicit type OR a schema, but not both, as they would conflict.\n */\nexport interface LocalOnlyCollectionConfig<\n TExplicit = unknown,\n TSchema extends StandardSchemaV1 = never,\n TFallback extends Record<string, unknown> = Record<string, unknown>,\n TKey extends string | number = string | number,\n> {\n /**\n * Standard Collection configuration properties\n */\n id?: string\n schema?: TSchema\n getKey: (item: ResolveType<TExplicit, TSchema, TFallback>) => TKey\n\n /**\n * Optional initial data to populate the collection with on creation\n * This data will be applied during the initial sync process\n */\n initialData?: Array<ResolveType<TExplicit, TSchema, TFallback>>\n\n /**\n * Optional asynchronous handler function called after an insert operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onInsert?: (\n params: InsertMutationFnParams<\n ResolveType<TExplicit, TSchema, TFallback>,\n TKey,\n LocalOnlyCollectionUtils\n >\n ) => Promise<any>\n\n /**\n * Optional asynchronous handler function called after an update operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onUpdate?: (\n params: UpdateMutationFnParams<\n ResolveType<TExplicit, TSchema, TFallback>,\n TKey,\n LocalOnlyCollectionUtils\n >\n ) => Promise<any>\n\n /**\n * Optional asynchronous handler function called after a delete operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onDelete?: (\n params: DeleteMutationFnParams<\n ResolveType<TExplicit, TSchema, TFallback>,\n TKey,\n LocalOnlyCollectionUtils\n >\n ) => Promise<any>\n}\n\n/**\n * Local-only collection utilities type (currently empty but matches the pattern)\n */\nexport interface LocalOnlyCollectionUtils extends UtilsRecord {}\n\n/**\n * Creates Local-only collection options for use with a standard Collection\n *\n * This is an in-memory collection that doesn't sync with external sources but uses a loopback sync config\n * that immediately \"syncs\" all optimistic changes to the collection, making them permanent.\n * Perfect for local-only data that doesn't need persistence or external synchronization.\n *\n * @template TExplicit - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n * @template TKey - The type of the key returned by getKey\n * @param config - Configuration options for the Local-only collection\n * @returns Collection options with utilities (currently empty but follows the pattern)\n *\n * @example\n * // Basic local-only collection\n * const collection = createCollection(\n * localOnlyCollectionOptions({\n * getKey: (item) => item.id,\n * })\n * )\n *\n * @example\n * // Local-only collection with initial data\n * const collection = createCollection(\n * localOnlyCollectionOptions({\n * getKey: (item) => item.id,\n * initialData: [\n * { id: 1, name: 'Item 1' },\n * { id: 2, name: 'Item 2' },\n * ],\n * })\n * )\n *\n * @example\n * // Local-only collection with mutation handlers\n * const collection = createCollection(\n * localOnlyCollectionOptions({\n * getKey: (item) => item.id,\n * onInsert: async ({ transaction }) => {\n * console.log('Item inserted:', transaction.mutations[0].modified)\n * // Custom logic after insert\n * },\n * })\n * )\n */\nexport function localOnlyCollectionOptions<\n TExplicit = unknown,\n TSchema extends StandardSchemaV1 = never,\n TFallback extends Record<string, unknown> = Record<string, unknown>,\n TKey extends string | number = string | number,\n>(config: LocalOnlyCollectionConfig<TExplicit, TSchema, TFallback, TKey>) {\n type ResolvedType = ResolveType<TExplicit, TSchema, TFallback>\n\n const { initialData, onInsert, onUpdate, onDelete, ...restConfig } = config\n\n // Create the sync configuration with transaction confirmation capability\n const syncResult = createLocalOnlySync<ResolvedType, TKey>(initialData)\n\n /**\n * Create wrapper handlers that call user handlers first, then confirm transactions\n * Wraps the user's onInsert handler to also confirm the transaction immediately\n */\n const wrappedOnInsert = async (\n params: InsertMutationFnParams<ResolvedType, TKey, LocalOnlyCollectionUtils>\n ) => {\n // Call user handler first if provided\n let handlerResult\n if (onInsert) {\n handlerResult = (await onInsert(params)) ?? {}\n }\n\n // Then synchronously confirm the transaction by looping through mutations\n syncResult.confirmOperationsSync(params.transaction.mutations)\n\n return handlerResult\n }\n\n /**\n * Wrapper for onUpdate handler that also confirms the transaction immediately\n */\n const wrappedOnUpdate = async (\n params: UpdateMutationFnParams<ResolvedType, TKey, LocalOnlyCollectionUtils>\n ) => {\n // Call user handler first if provided\n let handlerResult\n if (onUpdate) {\n handlerResult = (await onUpdate(params)) ?? {}\n }\n\n // Then synchronously confirm the transaction by looping through mutations\n syncResult.confirmOperationsSync(params.transaction.mutations)\n\n return handlerResult\n }\n\n /**\n * Wrapper for onDelete handler that also confirms the transaction immediately\n */\n const wrappedOnDelete = async (\n params: DeleteMutationFnParams<ResolvedType, TKey, LocalOnlyCollectionUtils>\n ) => {\n // Call user handler first if provided\n let handlerResult\n if (onDelete) {\n handlerResult = (await onDelete(params)) ?? {}\n }\n\n // Then synchronously confirm the transaction by looping through mutations\n syncResult.confirmOperationsSync(params.transaction.mutations)\n\n return handlerResult\n }\n\n return {\n ...restConfig,\n sync: syncResult.sync,\n onInsert: wrappedOnInsert,\n onUpdate: wrappedOnUpdate,\n onDelete: wrappedOnDelete,\n utils: {} as LocalOnlyCollectionUtils,\n startSync: true,\n gcTime: 0,\n }\n}\n\n/**\n * Internal function to create Local-only sync configuration with transaction confirmation\n *\n * This captures the sync functions and provides synchronous confirmation of operations.\n * It creates a loopback sync that immediately confirms all optimistic operations,\n * making them permanent in the collection.\n *\n * @param initialData - Optional array of initial items to populate the collection\n * @returns Object with sync configuration and confirmOperationsSync function\n */\nfunction createLocalOnlySync<T extends object, TKey extends string | number>(\n initialData?: Array<T>\n) {\n // Capture sync functions for transaction confirmation\n let syncBegin: (() => void) | null = null\n let syncWrite: ((message: { type: OperationType; value: T }) => void) | null =\n null\n let syncCommit: (() => void) | null = null\n\n const sync: SyncConfig<T, TKey> = {\n /**\n * Sync function that captures sync parameters and applies initial data\n * @param params - Sync parameters containing begin, write, and commit functions\n * @returns Unsubscribe function (empty since no ongoing sync is needed)\n */\n sync: (params) => {\n const { begin, write, commit } = params\n\n // Capture sync functions for later use by confirmOperationsSync\n syncBegin = begin\n syncWrite = write\n syncCommit = commit\n\n // Apply initial data if provided\n if (initialData && initialData.length > 0) {\n begin()\n initialData.forEach((item) => {\n write({\n type: `insert`,\n value: item,\n })\n })\n commit()\n }\n\n // Return empty unsubscribe function - no ongoing sync needed\n return () => {}\n },\n /**\n * Get sync metadata - returns empty object for local-only collections\n * @returns Empty metadata object\n */\n getSyncMetadata: () => ({}),\n }\n\n /**\n * Synchronously confirms optimistic operations by immediately writing through sync\n *\n * This loops through transaction mutations and applies them to move from optimistic to synced state.\n * It's called after user handlers to make optimistic changes permanent.\n *\n * @param mutations - Array of mutation objects from the transaction\n */\n const confirmOperationsSync = (mutations: Array<any>) => {\n if (!syncBegin || !syncWrite || !syncCommit) {\n return // Sync not initialized yet, which is fine\n }\n\n // Immediately write back through sync interface\n syncBegin()\n mutations.forEach((mutation) => {\n if (syncWrite) {\n syncWrite({\n type: mutation.type,\n value: mutation.modified,\n })\n }\n })\n syncCommit()\n }\n\n return {\n sync,\n confirmOperationsSync,\n }\n}\n"],"names":[],"mappings":";;AAwIO,SAAS,2BAKd,QAAwE;AAGxE,QAAM,EAAE,aAAa,UAAU,UAAU,UAAU,GAAG,eAAe;AAGrE,QAAM,aAAa,oBAAwC,WAAW;AAMtE,QAAM,kBAAkB,OACtB,WACG;AAEH,QAAI;AACJ,QAAI,UAAU;AACZ,sBAAiB,MAAM,SAAS,MAAM,KAAM,CAAA;AAAA,IAC9C;AAGA,eAAW,sBAAsB,OAAO,YAAY,SAAS;AAE7D,WAAO;AAAA,EACT;AAKA,QAAM,kBAAkB,OACtB,WACG;AAEH,QAAI;AACJ,QAAI,UAAU;AACZ,sBAAiB,MAAM,SAAS,MAAM,KAAM,CAAA;AAAA,IAC9C;AAGA,eAAW,sBAAsB,OAAO,YAAY,SAAS;AAE7D,WAAO;AAAA,EACT;AAKA,QAAM,kBAAkB,OACtB,WACG;AAEH,QAAI;AACJ,QAAI,UAAU;AACZ,sBAAiB,MAAM,SAAS,MAAM,KAAM,CAAA;AAAA,IAC9C;AAGA,eAAW,sBAAsB,OAAO,YAAY,SAAS;AAE7D,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,WAAW;AAAA,IACjB,UAAU;AAAA,IACV,UAAU;AAAA,IACV,UAAU;AAAA,IACV,OAAO,CAAA;AAAA,IACP,WAAW;AAAA,IACX,QAAQ;AAAA,EAAA;AAEZ;AAYA,SAAS,oBACP,aACA;AAEA,MAAI,YAAiC;AACrC,MAAI,YACF;AACF,MAAI,aAAkC;AAEtC,QAAM,OAA4B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMhC,MAAM,CAAC,WAAW;AAChB,YAAM,EAAE,OAAO,OAAO,OAAA,IAAW;AAGjC,kBAAY;AACZ,kBAAY;AACZ,mBAAa;AAGb,UAAI,eAAe,YAAY,SAAS,GAAG;AACzC,cAAA;AACA,oBAAY,QAAQ,CAAC,SAAS;AAC5B,gBAAM;AAAA,YACJ,MAAM;AAAA,YACN,OAAO;AAAA,UAAA,CACR;AAAA,QACH,CAAC;AACD,eAAA;AAAA,MACF;AAGA,aAAO,MAAM;AAAA,MAAC;AAAA,IAChB;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,iBAAiB,OAAO,CAAA;AAAA,EAAC;AAW3B,QAAM,wBAAwB,CAAC,cAA0B;AACvD,QAAI,CAAC,aAAa,CAAC,aAAa,CAAC,YAAY;AAC3C;AAAA,IACF;AAGA,cAAA;AACA,cAAU,QAAQ,CAAC,aAAa;AAC9B,UAAI,WAAW;AACb,kBAAU;AAAA,UACR,MAAM,SAAS;AAAA,UACf,OAAO,SAAS;AAAA,QAAA,CACjB;AAAA,MACH;AAAA,IACF,CAAC;AACD,eAAA;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EAAA;AAEJ;;"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { DeleteMutationFnParams, InsertMutationFnParams, ResolveType, SyncConfig, UpdateMutationFnParams, UtilsRecord } from './types.cjs';
|
|
2
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
3
|
+
/**
|
|
4
|
+
* Configuration interface for Local-only collection options
|
|
5
|
+
* @template TExplicit - The explicit type of items in the collection (highest priority)
|
|
6
|
+
* @template TSchema - The schema type for validation and type inference (second priority)
|
|
7
|
+
* @template TFallback - The fallback type if no explicit or schema type is provided
|
|
8
|
+
* @template TKey - The type of the key returned by getKey
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* Type resolution follows a priority order:
|
|
12
|
+
* 1. If you provide an explicit type via generic parameter, it will be used
|
|
13
|
+
* 2. If no explicit type is provided but a schema is, the schema's output type will be inferred
|
|
14
|
+
* 3. If neither explicit type nor schema is provided, the fallback type will be used
|
|
15
|
+
*
|
|
16
|
+
* You should provide EITHER an explicit type OR a schema, but not both, as they would conflict.
|
|
17
|
+
*/
|
|
18
|
+
export interface LocalOnlyCollectionConfig<TExplicit = unknown, TSchema extends StandardSchemaV1 = never, TFallback extends Record<string, unknown> = Record<string, unknown>, TKey extends string | number = string | number> {
|
|
19
|
+
/**
|
|
20
|
+
* Standard Collection configuration properties
|
|
21
|
+
*/
|
|
22
|
+
id?: string;
|
|
23
|
+
schema?: TSchema;
|
|
24
|
+
getKey: (item: ResolveType<TExplicit, TSchema, TFallback>) => TKey;
|
|
25
|
+
/**
|
|
26
|
+
* Optional initial data to populate the collection with on creation
|
|
27
|
+
* This data will be applied during the initial sync process
|
|
28
|
+
*/
|
|
29
|
+
initialData?: Array<ResolveType<TExplicit, TSchema, TFallback>>;
|
|
30
|
+
/**
|
|
31
|
+
* Optional asynchronous handler function called after an insert operation
|
|
32
|
+
* @param params Object containing transaction and collection information
|
|
33
|
+
* @returns Promise resolving to any value
|
|
34
|
+
*/
|
|
35
|
+
onInsert?: (params: InsertMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
36
|
+
/**
|
|
37
|
+
* Optional asynchronous handler function called after an update operation
|
|
38
|
+
* @param params Object containing transaction and collection information
|
|
39
|
+
* @returns Promise resolving to any value
|
|
40
|
+
*/
|
|
41
|
+
onUpdate?: (params: UpdateMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
42
|
+
/**
|
|
43
|
+
* Optional asynchronous handler function called after a delete operation
|
|
44
|
+
* @param params Object containing transaction and collection information
|
|
45
|
+
* @returns Promise resolving to any value
|
|
46
|
+
*/
|
|
47
|
+
onDelete?: (params: DeleteMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Local-only collection utilities type (currently empty but matches the pattern)
|
|
51
|
+
*/
|
|
52
|
+
export interface LocalOnlyCollectionUtils extends UtilsRecord {
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Creates Local-only collection options for use with a standard Collection
|
|
56
|
+
*
|
|
57
|
+
* This is an in-memory collection that doesn't sync with external sources but uses a loopback sync config
|
|
58
|
+
* that immediately "syncs" all optimistic changes to the collection, making them permanent.
|
|
59
|
+
* Perfect for local-only data that doesn't need persistence or external synchronization.
|
|
60
|
+
*
|
|
61
|
+
* @template TExplicit - The explicit type of items in the collection (highest priority)
|
|
62
|
+
* @template TSchema - The schema type for validation and type inference (second priority)
|
|
63
|
+
* @template TFallback - The fallback type if no explicit or schema type is provided
|
|
64
|
+
* @template TKey - The type of the key returned by getKey
|
|
65
|
+
* @param config - Configuration options for the Local-only collection
|
|
66
|
+
* @returns Collection options with utilities (currently empty but follows the pattern)
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* // Basic local-only collection
|
|
70
|
+
* const collection = createCollection(
|
|
71
|
+
* localOnlyCollectionOptions({
|
|
72
|
+
* getKey: (item) => item.id,
|
|
73
|
+
* })
|
|
74
|
+
* )
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* // Local-only collection with initial data
|
|
78
|
+
* const collection = createCollection(
|
|
79
|
+
* localOnlyCollectionOptions({
|
|
80
|
+
* getKey: (item) => item.id,
|
|
81
|
+
* initialData: [
|
|
82
|
+
* { id: 1, name: 'Item 1' },
|
|
83
|
+
* { id: 2, name: 'Item 2' },
|
|
84
|
+
* ],
|
|
85
|
+
* })
|
|
86
|
+
* )
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* // Local-only collection with mutation handlers
|
|
90
|
+
* const collection = createCollection(
|
|
91
|
+
* localOnlyCollectionOptions({
|
|
92
|
+
* getKey: (item) => item.id,
|
|
93
|
+
* onInsert: async ({ transaction }) => {
|
|
94
|
+
* console.log('Item inserted:', transaction.mutations[0].modified)
|
|
95
|
+
* // Custom logic after insert
|
|
96
|
+
* },
|
|
97
|
+
* })
|
|
98
|
+
* )
|
|
99
|
+
*/
|
|
100
|
+
export declare function localOnlyCollectionOptions<TExplicit = unknown, TSchema extends StandardSchemaV1 = never, TFallback extends Record<string, unknown> = Record<string, unknown>, TKey extends string | number = string | number>(config: LocalOnlyCollectionConfig<TExplicit, TSchema, TFallback, TKey>): {
|
|
101
|
+
sync: SyncConfig<ResolveType<TExplicit, TSchema, TFallback>, TKey>;
|
|
102
|
+
onInsert: (params: InsertMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
103
|
+
onUpdate: (params: UpdateMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
104
|
+
onDelete: (params: DeleteMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>, TKey, LocalOnlyCollectionUtils>) => Promise<any>;
|
|
105
|
+
utils: LocalOnlyCollectionUtils;
|
|
106
|
+
startSync: boolean;
|
|
107
|
+
gcTime: number;
|
|
108
|
+
/**
|
|
109
|
+
* Standard Collection configuration properties
|
|
110
|
+
*/
|
|
111
|
+
id?: string;
|
|
112
|
+
schema?: TSchema | undefined;
|
|
113
|
+
getKey: (item: ResolveType<TExplicit, TSchema, TFallback>) => TKey;
|
|
114
|
+
};
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
function validateJsonSerializable(value, operation) {
|
|
4
|
+
try {
|
|
5
|
+
JSON.stringify(value);
|
|
6
|
+
} catch (error) {
|
|
7
|
+
throw new Error(
|
|
8
|
+
`Cannot ${operation} item because it cannot be JSON serialized: ${error instanceof Error ? error.message : String(error)}`
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function generateUuid() {
|
|
13
|
+
return crypto.randomUUID();
|
|
14
|
+
}
|
|
15
|
+
function localStorageCollectionOptions(config) {
|
|
16
|
+
if (!config.storageKey) {
|
|
17
|
+
throw new Error(`[LocalStorageCollection] storageKey must be provided.`);
|
|
18
|
+
}
|
|
19
|
+
const storage = config.storage || (typeof window !== `undefined` ? window.localStorage : null);
|
|
20
|
+
if (!storage) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`[LocalStorageCollection] No storage available. Please provide a storage option or ensure window.localStorage is available.`
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
const storageEventApi = config.storageEventApi || (typeof window !== `undefined` ? window : null);
|
|
26
|
+
if (!storageEventApi) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
`[LocalStorageCollection] No storage event API available. Please provide a storageEventApi option or ensure window is available.`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const lastKnownData = /* @__PURE__ */ new Map();
|
|
32
|
+
const sync = createLocalStorageSync(
|
|
33
|
+
config.storageKey,
|
|
34
|
+
storage,
|
|
35
|
+
storageEventApi,
|
|
36
|
+
config.getKey,
|
|
37
|
+
lastKnownData
|
|
38
|
+
);
|
|
39
|
+
const triggerLocalSync = () => {
|
|
40
|
+
if (sync.manualTrigger) {
|
|
41
|
+
sync.manualTrigger();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const saveToStorage = (dataMap) => {
|
|
45
|
+
try {
|
|
46
|
+
const objectData = {};
|
|
47
|
+
dataMap.forEach((storedItem, key) => {
|
|
48
|
+
objectData[String(key)] = storedItem;
|
|
49
|
+
});
|
|
50
|
+
const serialized = JSON.stringify(objectData);
|
|
51
|
+
storage.setItem(config.storageKey, serialized);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.error(
|
|
54
|
+
`[LocalStorageCollection] Error saving data to storage key "${config.storageKey}":`,
|
|
55
|
+
error
|
|
56
|
+
);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const clearStorage = () => {
|
|
61
|
+
storage.removeItem(config.storageKey);
|
|
62
|
+
};
|
|
63
|
+
const getStorageSize = () => {
|
|
64
|
+
const data = storage.getItem(config.storageKey);
|
|
65
|
+
return data ? new Blob([data]).size : 0;
|
|
66
|
+
};
|
|
67
|
+
const wrappedOnInsert = async (params) => {
|
|
68
|
+
params.transaction.mutations.forEach((mutation) => {
|
|
69
|
+
validateJsonSerializable(mutation.modified, `insert`);
|
|
70
|
+
});
|
|
71
|
+
let handlerResult = {};
|
|
72
|
+
if (config.onInsert) {
|
|
73
|
+
handlerResult = await config.onInsert(params) ?? {};
|
|
74
|
+
}
|
|
75
|
+
const currentData = loadFromStorage(
|
|
76
|
+
config.storageKey,
|
|
77
|
+
storage
|
|
78
|
+
);
|
|
79
|
+
params.transaction.mutations.forEach((mutation) => {
|
|
80
|
+
const key = config.getKey(mutation.modified);
|
|
81
|
+
const storedItem = {
|
|
82
|
+
versionKey: generateUuid(),
|
|
83
|
+
data: mutation.modified
|
|
84
|
+
};
|
|
85
|
+
currentData.set(key, storedItem);
|
|
86
|
+
});
|
|
87
|
+
saveToStorage(currentData);
|
|
88
|
+
triggerLocalSync();
|
|
89
|
+
return handlerResult;
|
|
90
|
+
};
|
|
91
|
+
const wrappedOnUpdate = async (params) => {
|
|
92
|
+
params.transaction.mutations.forEach((mutation) => {
|
|
93
|
+
validateJsonSerializable(mutation.modified, `update`);
|
|
94
|
+
});
|
|
95
|
+
let handlerResult = {};
|
|
96
|
+
if (config.onUpdate) {
|
|
97
|
+
handlerResult = await config.onUpdate(params) ?? {};
|
|
98
|
+
}
|
|
99
|
+
const currentData = loadFromStorage(
|
|
100
|
+
config.storageKey,
|
|
101
|
+
storage
|
|
102
|
+
);
|
|
103
|
+
params.transaction.mutations.forEach((mutation) => {
|
|
104
|
+
const key = config.getKey(mutation.modified);
|
|
105
|
+
const storedItem = {
|
|
106
|
+
versionKey: generateUuid(),
|
|
107
|
+
data: mutation.modified
|
|
108
|
+
};
|
|
109
|
+
currentData.set(key, storedItem);
|
|
110
|
+
});
|
|
111
|
+
saveToStorage(currentData);
|
|
112
|
+
triggerLocalSync();
|
|
113
|
+
return handlerResult;
|
|
114
|
+
};
|
|
115
|
+
const wrappedOnDelete = async (params) => {
|
|
116
|
+
let handlerResult = {};
|
|
117
|
+
if (config.onDelete) {
|
|
118
|
+
handlerResult = await config.onDelete(params) ?? {};
|
|
119
|
+
}
|
|
120
|
+
const currentData = loadFromStorage(
|
|
121
|
+
config.storageKey,
|
|
122
|
+
storage
|
|
123
|
+
);
|
|
124
|
+
params.transaction.mutations.forEach((mutation) => {
|
|
125
|
+
const key = config.getKey(mutation.original);
|
|
126
|
+
currentData.delete(key);
|
|
127
|
+
});
|
|
128
|
+
saveToStorage(currentData);
|
|
129
|
+
triggerLocalSync();
|
|
130
|
+
return handlerResult;
|
|
131
|
+
};
|
|
132
|
+
const {
|
|
133
|
+
storageKey: _storageKey,
|
|
134
|
+
storage: _storage,
|
|
135
|
+
storageEventApi: _storageEventApi,
|
|
136
|
+
onInsert: _onInsert,
|
|
137
|
+
onUpdate: _onUpdate,
|
|
138
|
+
onDelete: _onDelete,
|
|
139
|
+
id,
|
|
140
|
+
...restConfig
|
|
141
|
+
} = config;
|
|
142
|
+
const collectionId = id ?? `local-collection:${config.storageKey}`;
|
|
143
|
+
return {
|
|
144
|
+
...restConfig,
|
|
145
|
+
id: collectionId,
|
|
146
|
+
sync,
|
|
147
|
+
onInsert: wrappedOnInsert,
|
|
148
|
+
onUpdate: wrappedOnUpdate,
|
|
149
|
+
onDelete: wrappedOnDelete,
|
|
150
|
+
utils: {
|
|
151
|
+
clearStorage,
|
|
152
|
+
getStorageSize
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function loadFromStorage(storageKey, storage) {
|
|
157
|
+
try {
|
|
158
|
+
const rawData = storage.getItem(storageKey);
|
|
159
|
+
if (!rawData) {
|
|
160
|
+
return /* @__PURE__ */ new Map();
|
|
161
|
+
}
|
|
162
|
+
const parsed = JSON.parse(rawData);
|
|
163
|
+
const dataMap = /* @__PURE__ */ new Map();
|
|
164
|
+
if (typeof parsed === `object` && parsed !== null && !Array.isArray(parsed)) {
|
|
165
|
+
Object.entries(parsed).forEach(([key, value]) => {
|
|
166
|
+
if (value && typeof value === `object` && `versionKey` in value && `data` in value) {
|
|
167
|
+
const storedItem = value;
|
|
168
|
+
dataMap.set(key, storedItem);
|
|
169
|
+
} else {
|
|
170
|
+
throw new Error(
|
|
171
|
+
`[LocalStorageCollection] Invalid data format in storage key "${storageKey}" for key "${key}".`
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
} else {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`[LocalStorageCollection] Invalid data format in storage key "${storageKey}". Expected object format.`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return dataMap;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
console.warn(
|
|
183
|
+
`[LocalStorageCollection] Error loading data from storage key "${storageKey}":`,
|
|
184
|
+
error
|
|
185
|
+
);
|
|
186
|
+
return /* @__PURE__ */ new Map();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function createLocalStorageSync(storageKey, storage, storageEventApi, getKey, lastKnownData) {
|
|
190
|
+
let syncParams = null;
|
|
191
|
+
const findChanges = (oldData, newData) => {
|
|
192
|
+
const changes = [];
|
|
193
|
+
oldData.forEach((oldStoredItem, key) => {
|
|
194
|
+
const newStoredItem = newData.get(key);
|
|
195
|
+
if (!newStoredItem) {
|
|
196
|
+
changes.push({ type: `delete`, key, value: oldStoredItem.data });
|
|
197
|
+
} else if (oldStoredItem.versionKey !== newStoredItem.versionKey) {
|
|
198
|
+
changes.push({ type: `update`, key, value: newStoredItem.data });
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
newData.forEach((newStoredItem, key) => {
|
|
202
|
+
if (!oldData.has(key)) {
|
|
203
|
+
changes.push({ type: `insert`, key, value: newStoredItem.data });
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
return changes;
|
|
207
|
+
};
|
|
208
|
+
const processStorageChanges = () => {
|
|
209
|
+
if (!syncParams) return;
|
|
210
|
+
const { begin, write, commit } = syncParams;
|
|
211
|
+
const newData = loadFromStorage(storageKey, storage);
|
|
212
|
+
const changes = findChanges(lastKnownData, newData);
|
|
213
|
+
if (changes.length > 0) {
|
|
214
|
+
begin();
|
|
215
|
+
changes.forEach(({ type, value }) => {
|
|
216
|
+
if (value) {
|
|
217
|
+
validateJsonSerializable(value, type);
|
|
218
|
+
write({ type, value });
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
commit();
|
|
222
|
+
lastKnownData.clear();
|
|
223
|
+
newData.forEach((storedItem, key) => {
|
|
224
|
+
lastKnownData.set(key, storedItem);
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
const syncConfig = {
|
|
229
|
+
sync: (params) => {
|
|
230
|
+
const { begin, write, commit } = params;
|
|
231
|
+
syncParams = params;
|
|
232
|
+
const initialData = loadFromStorage(storageKey, storage);
|
|
233
|
+
if (initialData.size > 0) {
|
|
234
|
+
begin();
|
|
235
|
+
initialData.forEach((storedItem) => {
|
|
236
|
+
validateJsonSerializable(storedItem.data, `load`);
|
|
237
|
+
write({ type: `insert`, value: storedItem.data });
|
|
238
|
+
});
|
|
239
|
+
commit();
|
|
240
|
+
}
|
|
241
|
+
lastKnownData.clear();
|
|
242
|
+
initialData.forEach((storedItem, key) => {
|
|
243
|
+
lastKnownData.set(key, storedItem);
|
|
244
|
+
});
|
|
245
|
+
const handleStorageEvent = (event) => {
|
|
246
|
+
if (event.key !== storageKey || event.storageArea !== storage) {
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
processStorageChanges();
|
|
250
|
+
};
|
|
251
|
+
storageEventApi.addEventListener(`storage`, handleStorageEvent);
|
|
252
|
+
},
|
|
253
|
+
/**
|
|
254
|
+
* Get sync metadata - returns storage key information
|
|
255
|
+
* @returns Object containing storage key and storage type metadata
|
|
256
|
+
*/
|
|
257
|
+
getSyncMetadata: () => ({
|
|
258
|
+
storageKey,
|
|
259
|
+
storageType: storage === (typeof window !== `undefined` ? window.localStorage : null) ? `localStorage` : `custom`
|
|
260
|
+
}),
|
|
261
|
+
// Manual trigger function for local updates
|
|
262
|
+
manualTrigger: processStorageChanges
|
|
263
|
+
};
|
|
264
|
+
return syncConfig;
|
|
265
|
+
}
|
|
266
|
+
exports.localStorageCollectionOptions = localStorageCollectionOptions;
|
|
267
|
+
//# sourceMappingURL=local-storage.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local-storage.cjs","sources":["../../src/local-storage.ts"],"sourcesContent":["import type {\n CollectionConfig,\n DeleteMutationFnParams,\n InsertMutationFnParams,\n ResolveType,\n SyncConfig,\n UpdateMutationFnParams,\n UtilsRecord,\n} from \"./types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Storage API interface - subset of DOM Storage that we need\n */\nexport type StorageApi = Pick<Storage, `getItem` | `setItem` | `removeItem`>\n\n/**\n * Storage event API - subset of Window for 'storage' events only\n */\nexport type StorageEventApi = {\n addEventListener: (\n type: `storage`,\n listener: (event: StorageEvent) => void\n ) => void\n removeEventListener: (\n type: `storage`,\n listener: (event: StorageEvent) => void\n ) => void\n}\n\n/**\n * Internal storage format that includes version tracking\n */\ninterface StoredItem<T> {\n versionKey: string\n data: T\n}\n\n/**\n * Configuration interface for localStorage collection options\n * @template TExplicit - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n *\n * @remarks\n * Type resolution follows a priority order:\n * 1. If you provide an explicit type via generic parameter, it will be used\n * 2. If no explicit type is provided but a schema is, the schema's output type will be inferred\n * 3. If neither explicit type nor schema is provided, the fallback type will be used\n *\n * You should provide EITHER an explicit type OR a schema, but not both, as they would conflict.\n */\nexport interface LocalStorageCollectionConfig<\n TExplicit = unknown,\n TSchema extends StandardSchemaV1 = never,\n TFallback extends object = Record<string, unknown>,\n> {\n /**\n * The key to use for storing the collection data in localStorage/sessionStorage\n */\n storageKey: string\n\n /**\n * Storage API to use (defaults to window.localStorage)\n * Can be any object that implements the Storage interface (e.g., sessionStorage)\n */\n storage?: StorageApi\n\n /**\n * Storage event API to use for cross-tab synchronization (defaults to window)\n * Can be any object that implements addEventListener/removeEventListener for storage events\n */\n storageEventApi?: StorageEventApi\n\n /**\n * Collection identifier (defaults to \"local-collection:{storageKey}\" if not provided)\n */\n id?: string\n schema?: TSchema\n getKey: CollectionConfig<ResolveType<TExplicit, TSchema, TFallback>>[`getKey`]\n sync?: CollectionConfig<ResolveType<TExplicit, TSchema, TFallback>>[`sync`]\n\n /**\n * Optional asynchronous handler function called before an insert operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onInsert?: (\n params: InsertMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>\n ) => Promise<any>\n\n /**\n * Optional asynchronous handler function called before an update operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onUpdate?: (\n params: UpdateMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>\n ) => Promise<any>\n\n /**\n * Optional asynchronous handler function called before a delete operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to any value\n */\n onDelete?: (\n params: DeleteMutationFnParams<ResolveType<TExplicit, TSchema, TFallback>>\n ) => Promise<any>\n}\n\n/**\n * Type for the clear utility function\n */\nexport type ClearStorageFn = () => void\n\n/**\n * Type for the getStorageSize utility function\n */\nexport type GetStorageSizeFn = () => number\n\n/**\n * LocalStorage collection utilities type\n */\nexport interface LocalStorageCollectionUtils extends UtilsRecord {\n clearStorage: ClearStorageFn\n getStorageSize: GetStorageSizeFn\n}\n\n/**\n * Validates that a value can be JSON serialized\n * @param value - The value to validate for JSON serialization\n * @param operation - The operation type being performed (for error messages)\n * @throws Error if the value cannot be JSON serialized\n */\nfunction validateJsonSerializable(value: any, operation: string): void {\n try {\n JSON.stringify(value)\n } catch (error) {\n throw new Error(\n `Cannot ${operation} item because it cannot be JSON serialized: ${\n error instanceof Error ? error.message : String(error)\n }`\n )\n }\n}\n\n/**\n * Generate a UUID for version tracking\n * @returns A unique identifier string for tracking data versions\n */\nfunction generateUuid(): string {\n return crypto.randomUUID()\n}\n\n/**\n * Creates localStorage collection options for use with a standard Collection\n *\n * This function creates a collection that persists data to localStorage/sessionStorage\n * and synchronizes changes across browser tabs using storage events.\n *\n * @template TExplicit - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n * @param config - Configuration options for the localStorage collection\n * @returns Collection options with utilities including clearStorage and getStorageSize\n *\n * @example\n * // Basic localStorage collection\n * const collection = createCollection(\n * localStorageCollectionOptions({\n * storageKey: 'todos',\n * getKey: (item) => item.id,\n * })\n * )\n *\n * @example\n * // localStorage collection with custom storage\n * const collection = createCollection(\n * localStorageCollectionOptions({\n * storageKey: 'todos',\n * storage: window.sessionStorage, // Use sessionStorage instead\n * getKey: (item) => item.id,\n * })\n * )\n *\n * @example\n * // localStorage collection with mutation handlers\n * const collection = createCollection(\n * localStorageCollectionOptions({\n * storageKey: 'todos',\n * getKey: (item) => item.id,\n * onInsert: async ({ transaction }) => {\n * console.log('Item inserted:', transaction.mutations[0].modified)\n * },\n * })\n * )\n */\nexport function localStorageCollectionOptions<\n TExplicit = unknown,\n TSchema extends StandardSchemaV1 = never,\n TFallback extends object = Record<string, unknown>,\n>(config: LocalStorageCollectionConfig<TExplicit, TSchema, TFallback>) {\n type ResolvedType = ResolveType<TExplicit, TSchema, TFallback>\n\n // Validate required parameters\n if (!config.storageKey) {\n throw new Error(`[LocalStorageCollection] storageKey must be provided.`)\n }\n\n // Default to window.localStorage if no storage is provided\n const storage =\n config.storage ||\n (typeof window !== `undefined` ? window.localStorage : null)\n\n if (!storage) {\n throw new Error(\n `[LocalStorageCollection] No storage available. Please provide a storage option or ensure window.localStorage is available.`\n )\n }\n\n // Default to window for storage events if not provided\n const storageEventApi =\n config.storageEventApi || (typeof window !== `undefined` ? window : null)\n\n if (!storageEventApi) {\n throw new Error(\n `[LocalStorageCollection] No storage event API available. Please provide a storageEventApi option or ensure window is available.`\n )\n }\n\n // Track the last known state to detect changes\n const lastKnownData = new Map<string | number, StoredItem<ResolvedType>>()\n\n // Create the sync configuration\n const sync = createLocalStorageSync<ResolvedType>(\n config.storageKey,\n storage,\n storageEventApi,\n config.getKey,\n lastKnownData\n )\n\n /**\n * Manual trigger function for local sync updates\n * Forces a check for storage changes and updates the collection if needed\n */\n const triggerLocalSync = () => {\n if (sync.manualTrigger) {\n sync.manualTrigger()\n }\n }\n\n /**\n * Save data to storage\n * @param dataMap - Map of items with version tracking to save to storage\n */\n const saveToStorage = (\n dataMap: Map<string | number, StoredItem<ResolvedType>>\n ): void => {\n try {\n // Convert Map to object format for storage\n const objectData: Record<string, StoredItem<ResolvedType>> = {}\n dataMap.forEach((storedItem, key) => {\n objectData[String(key)] = storedItem\n })\n const serialized = JSON.stringify(objectData)\n storage.setItem(config.storageKey, serialized)\n } catch (error) {\n console.error(\n `[LocalStorageCollection] Error saving data to storage key \"${config.storageKey}\":`,\n error\n )\n throw error\n }\n }\n\n /**\n * Removes all collection data from the configured storage\n */\n const clearStorage: ClearStorageFn = (): void => {\n storage.removeItem(config.storageKey)\n }\n\n /**\n * Get the size of the stored data in bytes (approximate)\n * @returns The approximate size in bytes of the stored collection data\n */\n const getStorageSize: GetStorageSizeFn = (): number => {\n const data = storage.getItem(config.storageKey)\n return data ? new Blob([data]).size : 0\n }\n\n /*\n * Create wrapper handlers for direct persistence operations that perform actual storage operations\n * Wraps the user's onInsert handler to also save changes to localStorage\n */\n const wrappedOnInsert = async (\n params: InsertMutationFnParams<ResolvedType>\n ) => {\n // Validate that all values in the transaction can be JSON serialized\n params.transaction.mutations.forEach((mutation) => {\n validateJsonSerializable(mutation.modified, `insert`)\n })\n\n // Call the user handler BEFORE persisting changes (if provided)\n let handlerResult: any = {}\n if (config.onInsert) {\n handlerResult = (await config.onInsert(params)) ?? {}\n }\n\n // Always persist to storage\n // Load current data from storage\n const currentData = loadFromStorage<ResolvedType>(\n config.storageKey,\n storage\n )\n\n // Add new items with version keys\n params.transaction.mutations.forEach((mutation) => {\n const key = config.getKey(mutation.modified)\n const storedItem: StoredItem<ResolvedType> = {\n versionKey: generateUuid(),\n data: mutation.modified,\n }\n currentData.set(key, storedItem)\n })\n\n // Save to storage\n saveToStorage(currentData)\n\n // Manually trigger local sync since storage events don't fire for current tab\n triggerLocalSync()\n\n return handlerResult\n }\n\n const wrappedOnUpdate = async (\n params: UpdateMutationFnParams<ResolvedType>\n ) => {\n // Validate that all values in the transaction can be JSON serialized\n params.transaction.mutations.forEach((mutation) => {\n validateJsonSerializable(mutation.modified, `update`)\n })\n\n // Call the user handler BEFORE persisting changes (if provided)\n let handlerResult: any = {}\n if (config.onUpdate) {\n handlerResult = (await config.onUpdate(params)) ?? {}\n }\n\n // Always persist to storage\n // Load current data from storage\n const currentData = loadFromStorage<ResolvedType>(\n config.storageKey,\n storage\n )\n\n // Update items with new version keys\n params.transaction.mutations.forEach((mutation) => {\n const key = config.getKey(mutation.modified)\n const storedItem: StoredItem<ResolvedType> = {\n versionKey: generateUuid(),\n data: mutation.modified,\n }\n currentData.set(key, storedItem)\n })\n\n // Save to storage\n saveToStorage(currentData)\n\n // Manually trigger local sync since storage events don't fire for current tab\n triggerLocalSync()\n\n return handlerResult\n }\n\n const wrappedOnDelete = async (\n params: DeleteMutationFnParams<ResolvedType>\n ) => {\n // Call the user handler BEFORE persisting changes (if provided)\n let handlerResult: any = {}\n if (config.onDelete) {\n handlerResult = (await config.onDelete(params)) ?? {}\n }\n\n // Always persist to storage\n // Load current data from storage\n const currentData = loadFromStorage<ResolvedType>(\n config.storageKey,\n storage\n )\n\n // Remove items\n params.transaction.mutations.forEach((mutation) => {\n // For delete operations, mutation.original contains the full object\n const key = config.getKey(mutation.original)\n currentData.delete(key)\n })\n\n // Save to storage\n saveToStorage(currentData)\n\n // Manually trigger local sync since storage events don't fire for current tab\n triggerLocalSync()\n\n return handlerResult\n }\n\n // Extract standard Collection config properties\n const {\n storageKey: _storageKey,\n storage: _storage,\n storageEventApi: _storageEventApi,\n onInsert: _onInsert,\n onUpdate: _onUpdate,\n onDelete: _onDelete,\n id,\n ...restConfig\n } = config\n\n // Default id to a pattern based on storage key if not provided\n const collectionId = id ?? `local-collection:${config.storageKey}`\n\n return {\n ...restConfig,\n id: collectionId,\n sync,\n onInsert: wrappedOnInsert,\n onUpdate: wrappedOnUpdate,\n onDelete: wrappedOnDelete,\n utils: {\n clearStorage,\n getStorageSize,\n },\n }\n}\n\n/**\n * Load data from storage and return as a Map\n * @param storageKey - The key used to store data in the storage API\n * @param storage - The storage API to load from (localStorage, sessionStorage, etc.)\n * @returns Map of stored items with version tracking, or empty Map if loading fails\n */\nfunction loadFromStorage<T extends object>(\n storageKey: string,\n storage: StorageApi\n): Map<string | number, StoredItem<T>> {\n try {\n const rawData = storage.getItem(storageKey)\n if (!rawData) {\n return new Map()\n }\n\n const parsed = JSON.parse(rawData)\n const dataMap = new Map<string | number, StoredItem<T>>()\n\n // Handle object format where keys map to StoredItem values\n if (\n typeof parsed === `object` &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n Object.entries(parsed).forEach(([key, value]) => {\n // Runtime check to ensure the value has the expected StoredItem structure\n if (\n value &&\n typeof value === `object` &&\n `versionKey` in value &&\n `data` in value\n ) {\n const storedItem = value as StoredItem<T>\n dataMap.set(key, storedItem)\n } else {\n throw new Error(\n `[LocalStorageCollection] Invalid data format in storage key \"${storageKey}\" for key \"${key}\".`\n )\n }\n })\n } else {\n throw new Error(\n `[LocalStorageCollection] Invalid data format in storage key \"${storageKey}\". Expected object format.`\n )\n }\n\n return dataMap\n } catch (error) {\n console.warn(\n `[LocalStorageCollection] Error loading data from storage key \"${storageKey}\":`,\n error\n )\n return new Map()\n }\n}\n\n/**\n * Internal function to create localStorage sync configuration\n * Creates a sync configuration that handles localStorage persistence and cross-tab synchronization\n * @param storageKey - The key used for storing data in localStorage\n * @param storage - The storage API to use (localStorage, sessionStorage, etc.)\n * @param storageEventApi - The event API for listening to storage changes\n * @param getKey - Function to extract the key from an item\n * @param lastKnownData - Map tracking the last known state for change detection\n * @returns Sync configuration with manual trigger capability\n */\nfunction createLocalStorageSync<T extends object>(\n storageKey: string,\n storage: StorageApi,\n storageEventApi: StorageEventApi,\n getKey: (item: T) => string | number,\n lastKnownData: Map<string | number, StoredItem<T>>\n): SyncConfig<T> & { manualTrigger?: () => void } {\n let syncParams: Parameters<SyncConfig<T>[`sync`]>[0] | null = null\n\n /**\n * Compare two Maps to find differences using version keys\n * @param oldData - The previous state of stored items\n * @param newData - The current state of stored items\n * @returns Array of changes with type, key, and value information\n */\n const findChanges = (\n oldData: Map<string | number, StoredItem<T>>,\n newData: Map<string | number, StoredItem<T>>\n ): Array<{\n type: `insert` | `update` | `delete`\n key: string | number\n value?: T\n }> => {\n const changes: Array<{\n type: `insert` | `update` | `delete`\n key: string | number\n value?: T\n }> = []\n\n // Check for deletions and updates\n oldData.forEach((oldStoredItem, key) => {\n const newStoredItem = newData.get(key)\n if (!newStoredItem) {\n changes.push({ type: `delete`, key, value: oldStoredItem.data })\n } else if (oldStoredItem.versionKey !== newStoredItem.versionKey) {\n changes.push({ type: `update`, key, value: newStoredItem.data })\n }\n })\n\n // Check for insertions\n newData.forEach((newStoredItem, key) => {\n if (!oldData.has(key)) {\n changes.push({ type: `insert`, key, value: newStoredItem.data })\n }\n })\n\n return changes\n }\n\n /**\n * Process storage changes and update collection\n * Loads new data from storage, compares with last known state, and applies changes\n */\n const processStorageChanges = () => {\n if (!syncParams) return\n\n const { begin, write, commit } = syncParams\n\n // Load the new data\n const newData = loadFromStorage<T>(storageKey, storage)\n\n // Find the specific changes\n const changes = findChanges(lastKnownData, newData)\n\n if (changes.length > 0) {\n begin()\n changes.forEach(({ type, value }) => {\n if (value) {\n validateJsonSerializable(value, type)\n write({ type, value })\n }\n })\n commit()\n\n // Update lastKnownData\n lastKnownData.clear()\n newData.forEach((storedItem, key) => {\n lastKnownData.set(key, storedItem)\n })\n }\n }\n\n const syncConfig: SyncConfig<T> & { manualTrigger?: () => void } = {\n sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {\n const { begin, write, commit } = params\n\n // Store sync params for later use\n syncParams = params\n\n // Initial load\n const initialData = loadFromStorage<T>(storageKey, storage)\n if (initialData.size > 0) {\n begin()\n initialData.forEach((storedItem) => {\n validateJsonSerializable(storedItem.data, `load`)\n write({ type: `insert`, value: storedItem.data })\n })\n commit()\n }\n\n // Update lastKnownData\n lastKnownData.clear()\n initialData.forEach((storedItem, key) => {\n lastKnownData.set(key, storedItem)\n })\n\n // Listen for storage events from other tabs\n const handleStorageEvent = (event: StorageEvent) => {\n // Only respond to changes to our specific key and from our storage\n if (event.key !== storageKey || event.storageArea !== storage) {\n return\n }\n\n processStorageChanges()\n }\n\n // Add storage event listener for cross-tab sync\n storageEventApi.addEventListener(`storage`, handleStorageEvent)\n\n // Note: Cleanup is handled automatically by the collection when it's disposed\n },\n\n /**\n * Get sync metadata - returns storage key information\n * @returns Object containing storage key and storage type metadata\n */\n getSyncMetadata: () => ({\n storageKey,\n storageType:\n storage === (typeof window !== `undefined` ? window.localStorage : null)\n ? `localStorage`\n : `custom`,\n }),\n\n // Manual trigger function for local updates\n manualTrigger: processStorageChanges,\n }\n\n return syncConfig\n}\n"],"names":[],"mappings":";;AAsIA,SAAS,yBAAyB,OAAY,WAAyB;AACrE,MAAI;AACF,SAAK,UAAU,KAAK;AAAA,EACtB,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,UAAU,SAAS,+CACjB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CACvD;AAAA,IAAA;AAAA,EAEJ;AACF;AAMA,SAAS,eAAuB;AAC9B,SAAO,OAAO,WAAA;AAChB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