@tanstack/db 0.4.6 → 0.4.7
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/collection/mutations.cjs +4 -4
- package/dist/cjs/collection/mutations.cjs.map +1 -1
- package/dist/cjs/local-only.cjs +21 -2
- package/dist/cjs/local-only.cjs.map +1 -1
- package/dist/cjs/local-only.d.cts +64 -7
- package/dist/cjs/local-storage.cjs +71 -3
- package/dist/cjs/local-storage.cjs.map +1 -1
- package/dist/cjs/local-storage.d.cts +55 -2
- package/dist/esm/collection/mutations.js +4 -4
- package/dist/esm/collection/mutations.js.map +1 -1
- package/dist/esm/local-only.d.ts +64 -7
- package/dist/esm/local-only.js +21 -2
- package/dist/esm/local-only.js.map +1 -1
- package/dist/esm/local-storage.d.ts +55 -2
- package/dist/esm/local-storage.js +72 -4
- package/dist/esm/local-storage.js.map +1 -1
- package/package.json +1 -1
- package/src/collection/mutations.ts +8 -4
- package/src/local-only.ts +119 -30
- package/src/local-storage.ts +170 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { StorageKeyRequiredError, NoStorageAvailableError, NoStorageEventApiError, InvalidStorageDataFormatError, InvalidStorageObjectFormatError
|
|
1
|
+
import { StorageKeyRequiredError, NoStorageAvailableError, NoStorageEventApiError, SerializationError, InvalidStorageDataFormatError, InvalidStorageObjectFormatError } from "./errors.js";
|
|
2
2
|
function validateJsonSerializable(value, operation) {
|
|
3
3
|
try {
|
|
4
4
|
JSON.stringify(value);
|
|
@@ -127,6 +127,52 @@ function localStorageCollectionOptions(config) {
|
|
|
127
127
|
...restConfig
|
|
128
128
|
} = config;
|
|
129
129
|
const collectionId = id ?? `local-collection:${config.storageKey}`;
|
|
130
|
+
const acceptMutations = (transaction) => {
|
|
131
|
+
const collectionMutations = transaction.mutations.filter((m) => {
|
|
132
|
+
if (sync.collection && m.collection === sync.collection) {
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
return m.collection.id === collectionId;
|
|
136
|
+
});
|
|
137
|
+
if (collectionMutations.length === 0) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
for (const mutation of collectionMutations) {
|
|
141
|
+
switch (mutation.type) {
|
|
142
|
+
case `insert`:
|
|
143
|
+
case `update`:
|
|
144
|
+
validateJsonSerializable(mutation.modified, mutation.type);
|
|
145
|
+
break;
|
|
146
|
+
case `delete`:
|
|
147
|
+
validateJsonSerializable(mutation.original, mutation.type);
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const currentData = loadFromStorage(
|
|
152
|
+
config.storageKey,
|
|
153
|
+
storage
|
|
154
|
+
);
|
|
155
|
+
for (const mutation of collectionMutations) {
|
|
156
|
+
const key = mutation.key;
|
|
157
|
+
switch (mutation.type) {
|
|
158
|
+
case `insert`:
|
|
159
|
+
case `update`: {
|
|
160
|
+
const storedItem = {
|
|
161
|
+
versionKey: generateUuid(),
|
|
162
|
+
data: mutation.modified
|
|
163
|
+
};
|
|
164
|
+
currentData.set(key, storedItem);
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
case `delete`: {
|
|
168
|
+
currentData.delete(key);
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
saveToStorage(currentData);
|
|
174
|
+
sync.confirmOperationsSync(collectionMutations);
|
|
175
|
+
};
|
|
130
176
|
return {
|
|
131
177
|
...restConfig,
|
|
132
178
|
id: collectionId,
|
|
@@ -136,7 +182,8 @@ function localStorageCollectionOptions(config) {
|
|
|
136
182
|
onDelete: wrappedOnDelete,
|
|
137
183
|
utils: {
|
|
138
184
|
clearStorage,
|
|
139
|
-
getStorageSize
|
|
185
|
+
getStorageSize,
|
|
186
|
+
acceptMutations
|
|
140
187
|
}
|
|
141
188
|
};
|
|
142
189
|
}
|
|
@@ -171,6 +218,7 @@ function loadFromStorage(storageKey, storage) {
|
|
|
171
218
|
}
|
|
172
219
|
function createLocalStorageSync(storageKey, storage, storageEventApi, _getKey, lastKnownData) {
|
|
173
220
|
let syncParams = null;
|
|
221
|
+
let collection = null;
|
|
174
222
|
const findChanges = (oldData, newData) => {
|
|
175
223
|
const changes = [];
|
|
176
224
|
oldData.forEach((oldStoredItem, key) => {
|
|
@@ -212,6 +260,7 @@ function createLocalStorageSync(storageKey, storage, storageEventApi, _getKey, l
|
|
|
212
260
|
sync: (params) => {
|
|
213
261
|
const { begin, write, commit, markReady } = params;
|
|
214
262
|
syncParams = params;
|
|
263
|
+
collection = params.collection;
|
|
215
264
|
const initialData = loadFromStorage(storageKey, storage);
|
|
216
265
|
if (initialData.size > 0) {
|
|
217
266
|
begin();
|
|
@@ -243,9 +292,28 @@ function createLocalStorageSync(storageKey, storage, storageEventApi, _getKey, l
|
|
|
243
292
|
storageType: storage === (typeof window !== `undefined` ? window.localStorage : null) ? `localStorage` : `custom`
|
|
244
293
|
}),
|
|
245
294
|
// Manual trigger function for local updates
|
|
246
|
-
manualTrigger: processStorageChanges
|
|
295
|
+
manualTrigger: processStorageChanges,
|
|
296
|
+
// Collection instance reference
|
|
297
|
+
collection
|
|
298
|
+
};
|
|
299
|
+
const confirmOperationsSync = (mutations) => {
|
|
300
|
+
if (!syncParams) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
const { begin, write, commit } = syncParams;
|
|
304
|
+
begin();
|
|
305
|
+
mutations.forEach((mutation) => {
|
|
306
|
+
write({
|
|
307
|
+
type: mutation.type,
|
|
308
|
+
value: mutation.type === `delete` ? mutation.original : mutation.modified
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
commit();
|
|
312
|
+
};
|
|
313
|
+
return {
|
|
314
|
+
...syncConfig,
|
|
315
|
+
confirmOperationsSync
|
|
247
316
|
};
|
|
248
|
-
return syncConfig;
|
|
249
317
|
}
|
|
250
318
|
export {
|
|
251
319
|
localStorageCollectionOptions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-storage.js","sources":["../../src/local-storage.ts"],"sourcesContent":["import {\n InvalidStorageDataFormatError,\n InvalidStorageObjectFormatError,\n NoStorageAvailableError,\n NoStorageEventApiError,\n SerializationError,\n StorageKeyRequiredError,\n} from \"./errors\"\nimport type {\n BaseCollectionConfig,\n CollectionConfig,\n DeleteMutationFnParams,\n InferSchemaOutput,\n InsertMutationFnParams,\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 T - The type of items in the collection\n * @template TSchema - The schema type for validation\n * @template TKey - The type of the key returned by `getKey`\n */\nexport interface LocalStorageCollectionConfig<\n T extends object = object,\n TSchema extends StandardSchemaV1 = never,\n TKey extends string | number = string | number,\n> extends BaseCollectionConfig<T, TKey, TSchema> {\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/**\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 SerializationError(\n operation,\n error instanceof Error ? error.message : String(error)\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 */\n\n// Overload for when schema is provided\nexport function localStorageCollectionOptions<\n T extends StandardSchemaV1,\n TKey extends string | number = string | number,\n>(\n config: LocalStorageCollectionConfig<InferSchemaOutput<T>, T, TKey> & {\n schema: T\n }\n): CollectionConfig<InferSchemaOutput<T>, TKey, T> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema: T\n}\n\n// Overload for when no schema is provided\n// the type T needs to be passed explicitly unless it can be inferred from the getKey function in the config\nexport function localStorageCollectionOptions<\n T extends object,\n TKey extends string | number = string | number,\n>(\n config: LocalStorageCollectionConfig<T, never, TKey> & {\n schema?: never // prohibit schema\n }\n): CollectionConfig<T, TKey> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema?: never // no schema in the result\n}\n\nexport function localStorageCollectionOptions(\n config: LocalStorageCollectionConfig<any, any, string | number>\n): Omit<CollectionConfig<any, string | number, any>, `id`> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema?: StandardSchemaV1\n} {\n // Validate required parameters\n if (!config.storageKey) {\n throw new StorageKeyRequiredError()\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 NoStorageAvailableError()\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 NoStorageEventApiError()\n }\n\n // Track the last known state to detect changes\n const lastKnownData = new Map<string | number, StoredItem<any>>()\n\n // Create the sync configuration\n const sync = createLocalStorageSync<any>(\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<any>>\n ): void => {\n try {\n // Convert Map to object format for storage\n const objectData: Record<string, StoredItem<any>> = {}\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 (params: InsertMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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<any> = {\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 (params: UpdateMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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<any> = {\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 (params: DeleteMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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 InvalidStorageDataFormatError(storageKey, key)\n }\n })\n } else {\n throw new InvalidStorageObjectFormatError(storageKey)\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, markReady } = 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 // Mark collection as ready after initial load\n markReady()\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: process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C,YAAI,OAAO;AACT,mCAAyB,OAAO,IAAI;AACpC,gBAAM,EAAE,MAAM,OAAO;AAAA,QACvB;AAAA,MACF,CAAC;AACD,aAAA;AAGA,oBAAc,MAAA;AACd,cAAQ,QAAQ,CAAC,YAAY,QAAQ;AACnC,sBAAc,IAAI,KAAK,UAAU;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,aAA6D;AAAA,IACjE,MAAM,CAAC,WAAiD;AACtD,YAAM,EAAE,OAAO,OAAO,QAAQ,cAAc;AAG5C,mBAAa;AAGb,YAAM,cAAc,gBAAmB,YAAY,OAAO;AAC1D,UAAI,YAAY,OAAO,GAAG;AACxB,cAAA;AACA,oBAAY,QAAQ,CAAC,eAAe;AAClC,mCAAyB,WAAW,MAAM,MAAM;AAChD,gBAAM,EAAE,MAAM,UAAU,OAAO,WAAW,MAAM;AAAA,QAClD,CAAC;AACD,eAAA;AAAA,MACF;AAGA,oBAAc,MAAA;AACd,kBAAY,QAAQ,CAAC,YAAY,QAAQ;AACvC,sBAAc,IAAI,KAAK,UAAU;AAAA,MACnC,CAAC;AAGD,gBAAA;AAGA,YAAM,qBAAqB,CAAC,UAAwB;AAElD,YAAI,MAAM,QAAQ,cAAc,MAAM,gBAAgB,SAAS;AAC7D;AAAA,QACF;AAEA,8BAAA;AAAA,MACF;AAGA,sBAAgB,iBAAiB,WAAW,kBAAkB;AAAA,IAGhE;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,iBAAiB,OAAO;AAAA,MACtB;AAAA,MACA,aACE,aAAa,OAAO,WAAW,cAAc,OAAO,eAAe,QAC/D,iBACA;AAAA,IAAA;AAAA;AAAA,IAIR,eAAe;AAAA,EAAA;AAGjB,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"local-storage.js","sources":["../../src/local-storage.ts"],"sourcesContent":["import {\n InvalidStorageDataFormatError,\n InvalidStorageObjectFormatError,\n NoStorageAvailableError,\n NoStorageEventApiError,\n SerializationError,\n StorageKeyRequiredError,\n} from \"./errors\"\nimport type {\n BaseCollectionConfig,\n CollectionConfig,\n DeleteMutationFnParams,\n InferSchemaOutput,\n InsertMutationFnParams,\n PendingMutation,\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 T - The type of items in the collection\n * @template TSchema - The schema type for validation\n * @template TKey - The type of the key returned by `getKey`\n */\nexport interface LocalStorageCollectionConfig<\n T extends object = object,\n TSchema extends StandardSchemaV1 = never,\n TKey extends string | number = string | number,\n> extends BaseCollectionConfig<T, TKey, TSchema> {\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/**\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 * Accepts mutations from a transaction that belong to this collection and persists them to localStorage.\n * This should be called in your transaction's mutationFn to persist local-storage data.\n *\n * @param transaction - The transaction containing mutations to accept\n * @example\n * const localSettings = createCollection(localStorageCollectionOptions({...}))\n *\n * const tx = createTransaction({\n * mutationFn: async ({ transaction }) => {\n * // Make API call first\n * await api.save(...)\n * // Then persist local-storage mutations after success\n * localSettings.utils.acceptMutations(transaction)\n * }\n * })\n */\n acceptMutations: (transaction: {\n mutations: Array<PendingMutation<Record<string, unknown>>>\n }) => void\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 SerializationError(\n operation,\n error instanceof Error ? error.message : String(error)\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 * **Using with Manual Transactions:**\n *\n * For manual transactions, you must call `utils.acceptMutations()` in your transaction's `mutationFn`\n * to persist changes made during `tx.mutate()`. This is necessary because local-storage collections\n * don't participate in the standard mutation handler flow for manual transactions.\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, getStorageSize, and acceptMutations\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 *\n * @example\n * // Using with manual transactions\n * const localSettings = createCollection(\n * localStorageCollectionOptions({\n * storageKey: 'user-settings',\n * getKey: (item) => item.id,\n * })\n * )\n *\n * const tx = createTransaction({\n * mutationFn: async ({ transaction }) => {\n * // Use settings data in API call\n * const settingsMutations = transaction.mutations.filter(m => m.collection === localSettings)\n * await api.updateUserProfile({ settings: settingsMutations[0]?.modified })\n *\n * // Persist local-storage mutations after API success\n * localSettings.utils.acceptMutations(transaction)\n * }\n * })\n *\n * tx.mutate(() => {\n * localSettings.insert({ id: 'theme', value: 'dark' })\n * apiCollection.insert({ id: 2, data: 'profile data' })\n * })\n *\n * await tx.commit()\n */\n\n// Overload for when schema is provided\nexport function localStorageCollectionOptions<\n T extends StandardSchemaV1,\n TKey extends string | number = string | number,\n>(\n config: LocalStorageCollectionConfig<InferSchemaOutput<T>, T, TKey> & {\n schema: T\n }\n): CollectionConfig<InferSchemaOutput<T>, TKey, T> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema: T\n}\n\n// Overload for when no schema is provided\n// the type T needs to be passed explicitly unless it can be inferred from the getKey function in the config\nexport function localStorageCollectionOptions<\n T extends object,\n TKey extends string | number = string | number,\n>(\n config: LocalStorageCollectionConfig<T, never, TKey> & {\n schema?: never // prohibit schema\n }\n): CollectionConfig<T, TKey> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema?: never // no schema in the result\n}\n\nexport function localStorageCollectionOptions(\n config: LocalStorageCollectionConfig<any, any, string | number>\n): Omit<CollectionConfig<any, string | number, any>, `id`> & {\n id: string\n utils: LocalStorageCollectionUtils\n schema?: StandardSchemaV1\n} {\n // Validate required parameters\n if (!config.storageKey) {\n throw new StorageKeyRequiredError()\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 NoStorageAvailableError()\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 NoStorageEventApiError()\n }\n\n // Track the last known state to detect changes\n const lastKnownData = new Map<string | number, StoredItem<any>>()\n\n // Create the sync configuration\n const sync = createLocalStorageSync<any>(\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<any>>\n ): void => {\n try {\n // Convert Map to object format for storage\n const objectData: Record<string, StoredItem<any>> = {}\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 (params: InsertMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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<any> = {\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 (params: UpdateMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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<any> = {\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 (params: DeleteMutationFnParams<any>) => {\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<any>(config.storageKey, storage)\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 /**\n * Accepts mutations from a transaction that belong to this collection and persists them to storage\n */\n const acceptMutations = (transaction: {\n mutations: Array<PendingMutation<Record<string, unknown>>>\n }) => {\n // Filter mutations that belong to this collection\n // Use collection ID for filtering if collection reference isn't available yet\n const collectionMutations = transaction.mutations.filter((m) => {\n // Try to match by collection reference first\n if (sync.collection && m.collection === sync.collection) {\n return true\n }\n // Fall back to matching by collection ID\n return m.collection.id === collectionId\n })\n\n if (collectionMutations.length === 0) {\n return\n }\n\n // Validate all mutations can be serialized before modifying storage\n for (const mutation of collectionMutations) {\n switch (mutation.type) {\n case `insert`:\n case `update`:\n validateJsonSerializable(mutation.modified, mutation.type)\n break\n case `delete`:\n validateJsonSerializable(mutation.original, mutation.type)\n break\n }\n }\n\n // Load current data from storage\n const currentData = loadFromStorage<Record<string, unknown>>(\n config.storageKey,\n storage\n )\n\n // Apply each mutation\n for (const mutation of collectionMutations) {\n // Use the engine's pre-computed key to avoid key derivation issues\n const key = mutation.key\n\n switch (mutation.type) {\n case `insert`:\n case `update`: {\n const storedItem: StoredItem<Record<string, unknown>> = {\n versionKey: generateUuid(),\n data: mutation.modified,\n }\n currentData.set(key, storedItem)\n break\n }\n case `delete`: {\n currentData.delete(key)\n break\n }\n }\n }\n\n // Save to storage\n saveToStorage(currentData)\n\n // Confirm the mutations in the collection to move them from optimistic to synced state\n // This writes them through the sync interface to make them \"synced\" instead of \"optimistic\"\n sync.confirmOperationsSync(collectionMutations)\n }\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 acceptMutations,\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 InvalidStorageDataFormatError(storageKey, key)\n }\n })\n } else {\n throw new InvalidStorageObjectFormatError(storageKey)\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> & {\n manualTrigger?: () => void\n collection: any\n confirmOperationsSync: (mutations: Array<any>) => void\n} {\n let syncParams: Parameters<SyncConfig<T>[`sync`]>[0] | null = null\n let collection: any = 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> & {\n manualTrigger?: () => void\n collection: any\n } = {\n sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {\n const { begin, write, commit, markReady } = params\n\n // Store sync params and collection for later use\n syncParams = params\n collection = params.collection\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 // Mark collection as ready after initial load\n markReady()\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 // Collection instance reference\n collection,\n }\n\n /**\n * Confirms mutations by writing them through the sync interface\n * This moves mutations from optimistic to synced state\n * @param mutations - Array of mutation objects to confirm\n */\n const confirmOperationsSync = (mutations: Array<any>) => {\n if (!syncParams) {\n // Sync not initialized yet, mutations will be handled on next sync\n return\n }\n\n const { begin, write, commit } = syncParams\n\n // Write the mutations through sync to confirm them\n begin()\n mutations.forEach((mutation: any) => {\n write({\n type: mutation.type,\n value:\n mutation.type === `delete` ? mutation.original : mutation.modified,\n })\n })\n commit()\n }\n\n return {\n ...syncConfig,\n confirmOperationsSync,\n }\n}\n"],"names":[],"mappings":";AAyHA,SAAS,yBAAyB,OAAY,WAAyB;AACrE,MAAI;AACF,SAAK,UAAU,KAAK;AAAA,EACtB,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IAAA;AAAA,EAEzD;AACF;AAMA,SAAS,eAAuB;AAC9B,SAAO,OAAO,WAAA;AAChB;AA4GO,SAAS,8BACd,QAKA;AAEA,MAAI,CAAC,OAAO,YA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AY,QAAQ,CAAC,YAAY,QAAQ;AACvC,sBAAc,IAAI,KAAK,UAAU;AAAA,MACnC,CAAC;AAGD,gBAAA;AAGA,YAAM,qBAAqB,CAAC,UAAwB;AAElD,YAAI,MAAM,QAAQ,cAAc,MAAM,gBAAgB,SAAS;AAC7D;AAAA,QACF;AAEA,8BAAA;AAAA,MACF;AAGA,sBAAgB,iBAAiB,WAAW,kBAAkB;AAAA,IAGhE;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,iBAAiB,OAAO;AAAA,MACtB;AAAA,MACA,aACE,aAAa,OAAO,WAAW,cAAc,OAAO,eAAe,QAC/D,iBACA;AAAA,IAAA;AAAA;AAAA,IAIR,eAAe;AAAA;AAAA,IAGf;AAAA,EAAA;AAQF,QAAM,wBAAwB,CAAC,cAA0B;AACvD,QAAI,CAAC,YAAY;AAEf;AAAA,IACF;AAEA,UAAM,EAAE,OAAO,OAAO,OAAA,IAAW;AAGjC,UAAA;AACA,cAAU,QAAQ,CAAC,aAAkB;AACnC,YAAM;AAAA,QACJ,MAAM,SAAS;AAAA,QACf,OACE,SAAS,SAAS,WAAW,SAAS,WAAW,SAAS;AAAA,MAAA,CAC7D;AAAA,IACH,CAAC;AACD,WAAA;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -230,7 +230,8 @@ export class CollectionMutationsManager<
|
|
|
230
230
|
|
|
231
231
|
// Apply mutations to the new transaction
|
|
232
232
|
directOpTransaction.applyMutations(mutations)
|
|
233
|
-
|
|
233
|
+
// Errors still reject tx.isPersisted.promise; this catch only prevents global unhandled rejections
|
|
234
|
+
directOpTransaction.commit().catch(() => undefined)
|
|
234
235
|
|
|
235
236
|
// Add the transaction to the collection's transactions store
|
|
236
237
|
state.transactions.set(directOpTransaction.id, directOpTransaction)
|
|
@@ -387,7 +388,8 @@ export class CollectionMutationsManager<
|
|
|
387
388
|
const emptyTransaction = createTransaction({
|
|
388
389
|
mutationFn: async () => {},
|
|
389
390
|
})
|
|
390
|
-
|
|
391
|
+
// Errors still propagate through tx.isPersisted.promise; suppress the background commit from warning
|
|
392
|
+
emptyTransaction.commit().catch(() => undefined)
|
|
391
393
|
// Schedule cleanup for empty transaction
|
|
392
394
|
state.scheduleTransactionCleanup(emptyTransaction)
|
|
393
395
|
return emptyTransaction
|
|
@@ -423,7 +425,8 @@ export class CollectionMutationsManager<
|
|
|
423
425
|
|
|
424
426
|
// Apply mutations to the new transaction
|
|
425
427
|
directOpTransaction.applyMutations(mutations)
|
|
426
|
-
|
|
428
|
+
// Errors still hit tx.isPersisted.promise; avoid leaking an unhandled rejection from the fire-and-forget commit
|
|
429
|
+
directOpTransaction.commit().catch(() => undefined)
|
|
427
430
|
|
|
428
431
|
// Add the transaction to the collection's transactions store
|
|
429
432
|
|
|
@@ -524,7 +527,8 @@ export class CollectionMutationsManager<
|
|
|
524
527
|
|
|
525
528
|
// Apply mutations to the new transaction
|
|
526
529
|
directOpTransaction.applyMutations(mutations)
|
|
527
|
-
|
|
530
|
+
// Errors still reject tx.isPersisted.promise; silence the internal commit promise to prevent test noise
|
|
531
|
+
directOpTransaction.commit().catch(() => undefined)
|
|
528
532
|
|
|
529
533
|
state.transactions.set(directOpTransaction.id, directOpTransaction)
|
|
530
534
|
state.scheduleTransactionCleanup(directOpTransaction)
|
package/src/local-only.ts
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
BaseCollectionConfig,
|
|
3
3
|
CollectionConfig,
|
|
4
|
+
DeleteMutationFn,
|
|
4
5
|
DeleteMutationFnParams,
|
|
5
6
|
InferSchemaOutput,
|
|
7
|
+
InsertMutationFn,
|
|
6
8
|
InsertMutationFnParams,
|
|
7
9
|
OperationType,
|
|
10
|
+
PendingMutation,
|
|
8
11
|
SyncConfig,
|
|
12
|
+
UpdateMutationFn,
|
|
9
13
|
UpdateMutationFnParams,
|
|
10
14
|
UtilsRecord,
|
|
11
15
|
} from "./types"
|
|
16
|
+
import type { Collection } from "./collection/index"
|
|
12
17
|
import type { StandardSchemaV1 } from "@standard-schema/spec"
|
|
13
18
|
|
|
14
19
|
/**
|
|
@@ -33,9 +38,44 @@ export interface LocalOnlyCollectionConfig<
|
|
|
33
38
|
}
|
|
34
39
|
|
|
35
40
|
/**
|
|
36
|
-
* Local-only collection utilities type
|
|
41
|
+
* Local-only collection utilities type
|
|
37
42
|
*/
|
|
38
|
-
export interface LocalOnlyCollectionUtils extends UtilsRecord {
|
|
43
|
+
export interface LocalOnlyCollectionUtils extends UtilsRecord {
|
|
44
|
+
/**
|
|
45
|
+
* Accepts mutations from a transaction that belong to this collection and persists them.
|
|
46
|
+
* This should be called in your transaction's mutationFn to persist local-only data.
|
|
47
|
+
*
|
|
48
|
+
* @param transaction - The transaction containing mutations to accept
|
|
49
|
+
* @example
|
|
50
|
+
* const localData = createCollection(localOnlyCollectionOptions({...}))
|
|
51
|
+
*
|
|
52
|
+
* const tx = createTransaction({
|
|
53
|
+
* mutationFn: async ({ transaction }) => {
|
|
54
|
+
* // Make API call first
|
|
55
|
+
* await api.save(...)
|
|
56
|
+
* // Then persist local-only mutations after success
|
|
57
|
+
* localData.utils.acceptMutations(transaction)
|
|
58
|
+
* }
|
|
59
|
+
* })
|
|
60
|
+
*/
|
|
61
|
+
acceptMutations: (transaction: {
|
|
62
|
+
mutations: Array<PendingMutation<Record<string, unknown>>>
|
|
63
|
+
}) => void
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type LocalOnlyCollectionOptionsResult<
|
|
67
|
+
T extends object,
|
|
68
|
+
TKey extends string | number,
|
|
69
|
+
TSchema extends StandardSchemaV1 | never = never,
|
|
70
|
+
> = Omit<
|
|
71
|
+
CollectionConfig<T, TKey, TSchema>,
|
|
72
|
+
`onInsert` | `onUpdate` | `onDelete`
|
|
73
|
+
> & {
|
|
74
|
+
onInsert?: InsertMutationFn<T, TKey, LocalOnlyCollectionUtils>
|
|
75
|
+
onUpdate?: UpdateMutationFn<T, TKey, LocalOnlyCollectionUtils>
|
|
76
|
+
onDelete?: DeleteMutationFn<T, TKey, LocalOnlyCollectionUtils>
|
|
77
|
+
utils: LocalOnlyCollectionUtils
|
|
78
|
+
}
|
|
39
79
|
|
|
40
80
|
/**
|
|
41
81
|
* Creates Local-only collection options for use with a standard Collection
|
|
@@ -44,10 +84,16 @@ export interface LocalOnlyCollectionUtils extends UtilsRecord {}
|
|
|
44
84
|
* that immediately "syncs" all optimistic changes to the collection, making them permanent.
|
|
45
85
|
* Perfect for local-only data that doesn't need persistence or external synchronization.
|
|
46
86
|
*
|
|
87
|
+
* **Using with Manual Transactions:**
|
|
88
|
+
*
|
|
89
|
+
* For manual transactions, you must call `utils.acceptMutations()` in your transaction's `mutationFn`
|
|
90
|
+
* to persist changes made during `tx.mutate()`. This is necessary because local-only collections
|
|
91
|
+
* don't participate in the standard mutation handler flow for manual transactions.
|
|
92
|
+
*
|
|
47
93
|
* @template T - The schema type if a schema is provided, otherwise the type of items in the collection
|
|
48
94
|
* @template TKey - The type of the key returned by getKey
|
|
49
95
|
* @param config - Configuration options for the Local-only collection
|
|
50
|
-
* @returns Collection options with utilities
|
|
96
|
+
* @returns Collection options with utilities including acceptMutations
|
|
51
97
|
*
|
|
52
98
|
* @example
|
|
53
99
|
* // Basic local-only collection
|
|
@@ -80,6 +126,32 @@ export interface LocalOnlyCollectionUtils extends UtilsRecord {}
|
|
|
80
126
|
* },
|
|
81
127
|
* })
|
|
82
128
|
* )
|
|
129
|
+
*
|
|
130
|
+
* @example
|
|
131
|
+
* // Using with manual transactions
|
|
132
|
+
* const localData = createCollection(
|
|
133
|
+
* localOnlyCollectionOptions({
|
|
134
|
+
* getKey: (item) => item.id,
|
|
135
|
+
* })
|
|
136
|
+
* )
|
|
137
|
+
*
|
|
138
|
+
* const tx = createTransaction({
|
|
139
|
+
* mutationFn: async ({ transaction }) => {
|
|
140
|
+
* // Use local data in API call
|
|
141
|
+
* const localMutations = transaction.mutations.filter(m => m.collection === localData)
|
|
142
|
+
* await api.save({ metadata: localMutations[0]?.modified })
|
|
143
|
+
*
|
|
144
|
+
* // Persist local-only mutations after API success
|
|
145
|
+
* localData.utils.acceptMutations(transaction)
|
|
146
|
+
* }
|
|
147
|
+
* })
|
|
148
|
+
*
|
|
149
|
+
* tx.mutate(() => {
|
|
150
|
+
* localData.insert({ id: 1, data: 'metadata' })
|
|
151
|
+
* apiCollection.insert({ id: 2, data: 'main data' })
|
|
152
|
+
* })
|
|
153
|
+
*
|
|
154
|
+
* await tx.commit()
|
|
83
155
|
*/
|
|
84
156
|
|
|
85
157
|
// Overload for when schema is provided
|
|
@@ -90,8 +162,7 @@ export function localOnlyCollectionOptions<
|
|
|
90
162
|
config: LocalOnlyCollectionConfig<InferSchemaOutput<T>, T, TKey> & {
|
|
91
163
|
schema: T
|
|
92
164
|
}
|
|
93
|
-
):
|
|
94
|
-
utils: LocalOnlyCollectionUtils
|
|
165
|
+
): LocalOnlyCollectionOptionsResult<InferSchemaOutput<T>, TKey, T> & {
|
|
95
166
|
schema: T
|
|
96
167
|
}
|
|
97
168
|
|
|
@@ -104,15 +175,17 @@ export function localOnlyCollectionOptions<
|
|
|
104
175
|
config: LocalOnlyCollectionConfig<T, never, TKey> & {
|
|
105
176
|
schema?: never // prohibit schema
|
|
106
177
|
}
|
|
107
|
-
):
|
|
108
|
-
utils: LocalOnlyCollectionUtils
|
|
178
|
+
): LocalOnlyCollectionOptionsResult<T, TKey> & {
|
|
109
179
|
schema?: never // no schema in the result
|
|
110
180
|
}
|
|
111
181
|
|
|
112
|
-
export function localOnlyCollectionOptions
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
182
|
+
export function localOnlyCollectionOptions<
|
|
183
|
+
T extends object = object,
|
|
184
|
+
TSchema extends StandardSchemaV1 = never,
|
|
185
|
+
TKey extends string | number = string | number,
|
|
186
|
+
>(
|
|
187
|
+
config: LocalOnlyCollectionConfig<T, TSchema, TKey>
|
|
188
|
+
): LocalOnlyCollectionOptionsResult<T, TKey, TSchema> & {
|
|
116
189
|
schema?: StandardSchemaV1
|
|
117
190
|
} {
|
|
118
191
|
const { initialData, onInsert, onUpdate, onDelete, ...restConfig } = config
|
|
@@ -125,11 +198,7 @@ export function localOnlyCollectionOptions(
|
|
|
125
198
|
* Wraps the user's onInsert handler to also confirm the transaction immediately
|
|
126
199
|
*/
|
|
127
200
|
const wrappedOnInsert = async (
|
|
128
|
-
params: InsertMutationFnParams<
|
|
129
|
-
any,
|
|
130
|
-
string | number,
|
|
131
|
-
LocalOnlyCollectionUtils
|
|
132
|
-
>
|
|
201
|
+
params: InsertMutationFnParams<T, TKey, LocalOnlyCollectionUtils>
|
|
133
202
|
) => {
|
|
134
203
|
// Call user handler first if provided
|
|
135
204
|
let handlerResult
|
|
@@ -147,11 +216,7 @@ export function localOnlyCollectionOptions(
|
|
|
147
216
|
* Wrapper for onUpdate handler that also confirms the transaction immediately
|
|
148
217
|
*/
|
|
149
218
|
const wrappedOnUpdate = async (
|
|
150
|
-
params: UpdateMutationFnParams<
|
|
151
|
-
any,
|
|
152
|
-
string | number,
|
|
153
|
-
LocalOnlyCollectionUtils
|
|
154
|
-
>
|
|
219
|
+
params: UpdateMutationFnParams<T, TKey, LocalOnlyCollectionUtils>
|
|
155
220
|
) => {
|
|
156
221
|
// Call user handler first if provided
|
|
157
222
|
let handlerResult
|
|
@@ -169,11 +234,7 @@ export function localOnlyCollectionOptions(
|
|
|
169
234
|
* Wrapper for onDelete handler that also confirms the transaction immediately
|
|
170
235
|
*/
|
|
171
236
|
const wrappedOnDelete = async (
|
|
172
|
-
params: DeleteMutationFnParams<
|
|
173
|
-
any,
|
|
174
|
-
string | number,
|
|
175
|
-
LocalOnlyCollectionUtils
|
|
176
|
-
>
|
|
237
|
+
params: DeleteMutationFnParams<T, TKey, LocalOnlyCollectionUtils>
|
|
177
238
|
) => {
|
|
178
239
|
// Call user handler first if provided
|
|
179
240
|
let handlerResult
|
|
@@ -187,13 +248,38 @@ export function localOnlyCollectionOptions(
|
|
|
187
248
|
return handlerResult
|
|
188
249
|
}
|
|
189
250
|
|
|
251
|
+
/**
|
|
252
|
+
* Accepts mutations from a transaction that belong to this collection and persists them
|
|
253
|
+
*/
|
|
254
|
+
const acceptMutations = (transaction: {
|
|
255
|
+
mutations: Array<PendingMutation<Record<string, unknown>>>
|
|
256
|
+
}) => {
|
|
257
|
+
// Filter mutations that belong to this collection
|
|
258
|
+
const collectionMutations = transaction.mutations.filter(
|
|
259
|
+
(m) =>
|
|
260
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
261
|
+
m.collection === syncResult.collection
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
if (collectionMutations.length === 0) {
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Persist the mutations through sync
|
|
269
|
+
syncResult.confirmOperationsSync(
|
|
270
|
+
collectionMutations as Array<PendingMutation<T>>
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
|
|
190
274
|
return {
|
|
191
275
|
...restConfig,
|
|
192
276
|
sync: syncResult.sync,
|
|
193
277
|
onInsert: wrappedOnInsert,
|
|
194
278
|
onUpdate: wrappedOnUpdate,
|
|
195
279
|
onDelete: wrappedOnDelete,
|
|
196
|
-
utils: {
|
|
280
|
+
utils: {
|
|
281
|
+
acceptMutations,
|
|
282
|
+
} as LocalOnlyCollectionUtils,
|
|
197
283
|
startSync: true,
|
|
198
284
|
gcTime: 0,
|
|
199
285
|
}
|
|
@@ -212,11 +298,12 @@ export function localOnlyCollectionOptions(
|
|
|
212
298
|
function createLocalOnlySync<T extends object, TKey extends string | number>(
|
|
213
299
|
initialData?: Array<T>
|
|
214
300
|
) {
|
|
215
|
-
// Capture sync functions for transaction confirmation
|
|
301
|
+
// Capture sync functions and collection for transaction confirmation
|
|
216
302
|
let syncBegin: (() => void) | null = null
|
|
217
303
|
let syncWrite: ((message: { type: OperationType; value: T }) => void) | null =
|
|
218
304
|
null
|
|
219
305
|
let syncCommit: (() => void) | null = null
|
|
306
|
+
let collection: Collection<T, TKey, LocalOnlyCollectionUtils> | null = null
|
|
220
307
|
|
|
221
308
|
const sync: SyncConfig<T, TKey> = {
|
|
222
309
|
/**
|
|
@@ -227,10 +314,11 @@ function createLocalOnlySync<T extends object, TKey extends string | number>(
|
|
|
227
314
|
sync: (params) => {
|
|
228
315
|
const { begin, write, commit, markReady } = params
|
|
229
316
|
|
|
230
|
-
// Capture sync functions for later use
|
|
317
|
+
// Capture sync functions and collection for later use
|
|
231
318
|
syncBegin = begin
|
|
232
319
|
syncWrite = write
|
|
233
320
|
syncCommit = commit
|
|
321
|
+
collection = params.collection
|
|
234
322
|
|
|
235
323
|
// Apply initial data if provided
|
|
236
324
|
if (initialData && initialData.length > 0) {
|
|
@@ -265,7 +353,7 @@ function createLocalOnlySync<T extends object, TKey extends string | number>(
|
|
|
265
353
|
*
|
|
266
354
|
* @param mutations - Array of mutation objects from the transaction
|
|
267
355
|
*/
|
|
268
|
-
const confirmOperationsSync = (mutations: Array<
|
|
356
|
+
const confirmOperationsSync = (mutations: Array<PendingMutation<T>>) => {
|
|
269
357
|
if (!syncBegin || !syncWrite || !syncCommit) {
|
|
270
358
|
return // Sync not initialized yet, which is fine
|
|
271
359
|
}
|
|
@@ -286,5 +374,6 @@ function createLocalOnlySync<T extends object, TKey extends string | number>(
|
|
|
286
374
|
return {
|
|
287
375
|
sync,
|
|
288
376
|
confirmOperationsSync,
|
|
377
|
+
collection,
|
|
289
378
|
}
|
|
290
379
|
}
|