@warp-drive-mirror/experiments 0.2.7-beta.1 → 0.2.7-beta.3
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/data-worker.js.map +1 -1
- package/dist/document-storage-LM925Stz.js.map +1 -1
- package/dist/image-fetch.js.map +1 -1
- package/dist/image-worker.js.map +1 -1
- package/dist/pagination.d.ts +2 -0
- package/dist/pagination.js +3 -0
- package/{declarations → dist}/storage.d.ts +0 -5
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js.map +1 -1
- package/dist/unpkg/dev/data-worker.js.map +1 -1
- package/dist/unpkg/dev/document-storage-DkiEg9rY.js.map +1 -1
- package/dist/unpkg/dev/image-fetch.js.map +1 -1
- package/dist/unpkg/dev/image-worker.js.map +1 -1
- package/dist/unpkg/dev/pagination.js +3 -0
- package/dist/unpkg/dev/storage.js.map +1 -1
- package/dist/unpkg/dev/worker-fetch.js.map +1 -1
- package/dist/unpkg/dev-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/document-storage-DkiEg9rY.js.map +1 -1
- package/dist/unpkg/dev-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/dev-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/dev-deprecated/pagination.js +3 -0
- package/dist/unpkg/dev-deprecated/storage.js.map +1 -1
- package/dist/unpkg/dev-deprecated/worker-fetch.js.map +1 -1
- package/dist/unpkg/prod/data-worker.js.map +1 -1
- package/dist/unpkg/prod/document-storage-D0k_6GM9.js.map +1 -1
- package/dist/unpkg/prod/image-fetch.js.map +1 -1
- package/dist/unpkg/prod/image-worker.js.map +1 -1
- package/dist/unpkg/prod/pagination.js +3 -0
- package/dist/unpkg/prod/storage.js.map +1 -1
- package/dist/unpkg/prod/worker-fetch.js.map +1 -1
- package/dist/unpkg/prod-deprecated/data-worker.js.map +1 -1
- package/dist/unpkg/prod-deprecated/document-storage-D0k_6GM9.js.map +1 -1
- package/dist/unpkg/prod-deprecated/image-fetch.js.map +1 -1
- package/dist/unpkg/prod-deprecated/image-worker.js.map +1 -1
- package/dist/unpkg/prod-deprecated/pagination.js +3 -0
- package/dist/unpkg/prod-deprecated/storage.js.map +1 -1
- package/dist/unpkg/prod-deprecated/worker-fetch.js.map +1 -1
- package/dist/worker-fetch.js.map +1 -1
- package/package.json +25 -21
- package/declarations/storage.d.ts.map +0 -1
- /package/{declarations → dist}/data-worker.d.ts +0 -0
- /package/{declarations → dist}/data-worker.d.ts.map +0 -0
- /package/{declarations → dist}/document-storage-CwwTQ49-.d.ts +0 -0
- /package/{declarations → dist}/document-storage-CwwTQ49-.d.ts.map +0 -0
- /package/{declarations → dist}/document-storage.d.ts +0 -0
- /package/{declarations → dist}/image-fetch.d.ts +0 -0
- /package/{declarations → dist}/image-fetch.d.ts.map +0 -0
- /package/{declarations → dist}/image-worker.d.ts +0 -0
- /package/{declarations → dist}/image-worker.d.ts.map +0 -0
- /package/{declarations → dist}/types-CRs-Qww6.d.ts +0 -0
- /package/{declarations → dist}/types-CRs-Qww6.d.ts.map +0 -0
- /package/{declarations → dist}/worker-fetch.d.ts +0 -0
- /package/{declarations → dist}/worker-fetch.d.ts.map +0 -0
package/dist/storage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":["defineSignal","entangleSignal","getOrCreateInternalSignal","notifyInternalSignal","withSignalStore","macroCondition","getGlobalConfig","SignalMap","_map","_signals","subscribe","key","WarpDrive","env","DEBUG","test","Error","existing","has","undefined","size","_size","notify","signal","clear","value","values","prototype","DEFAULT_CACHE_ID","CACHES","Map","StorageEvents","BroadcastChannel","CACHE_URL","location","origin","emitStorageEvent","event","window","dispatchEvent","CustomEvent","detail","handleCacheEvent","data","cache","get","storageArea","key","_data","oldValue","newValue","delete","set","addEventListener","CacheStorage","cacheId","inititalization","_nextUpdate","_bufferedEvents","initialize","#initialize","caches","open","deserializeFromCache","constructor","length","size","update","#update","Error","push","setTimeout","events","serializeToCache","postMessage","clear","getItem","index","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","Number","isInteger","i","value","keys","removeItem","has","setItem","expectCache","getAllCacheIds","Array","from","entries","blob","JSON","stringify","version","response","Response","put","match","then","json","defineSignal","makeInitializer","SignalMap","CacheStorage","DEFAULT_CACHE_ID","macroCondition","getGlobalConfig","localStorageInstance","sessionStorageInstance","localStorageOptions","sessionStorageOptions","getLocalStorage","ReactiveStorage","localStorage","getSessionStorage","sessionStorage","CacheStorages","Map","getCacheStorage","namespace","key","cache","get","storage","expectCache","set","configureLocalStorage","options","configureSessionStorage","isQuotaExceededError","error","DOMException","name","isStorageUnavailableError","_storage","_options","_memoryOnly","_values","_effects","setEffect","fn","WarpDrive","env","DEBUG","test","Error","has","constructor","testKey","setItem","removeItem","_length","length","fallbackToMemory","window","addEventListener","event","data","detail","storageArea","newValue","_signals","notify","effect","peekItem","keyStr","String","value","undefined","item","getItem","subscribe","valueStr","current","currentValue","updateOnQuotaExceeded","onQuotaExceeded","result","retry","Promise","clear","index","keys","Object","filter","k","prototype","memoized","getCacheStorage","getLocalStorage","getSessionStorage","macroCondition","getGlobalConfig","PERSISTED_RESOURCE_META","Symbol","initMeta","target","meta","id","namespace","pkFn","type","fields","Map","initializers","paramConfigs","paramCompanion","instances","typeOverrides","useMeta","instance","WeakMap","instanceMeta","get","pk","WarpDrive","env","DEBUG","test","Error","length","set","getField","key","overrideType","storage","getStorage","stored","getItem","keyFor","JSON","parse","initializer","value","call","undefined","peekField","peekItem","initializeFields","source","baseMeta","getResourceMeta","entries","newValue","defaultValue","currentValue","localStorage","sessionStorage","setItem","stringify","setField","_createStorageResource","prototype","originalConstructor","constructor","DynamicStorageInitializer","args","installEffectsForDynamicInstance","toJSON","isLocalResource","Set","keys","add","delete","idKey","has","data","Promise","resolve","installEffect","setupField","orgDesc","desc","configurable","enumerable","effect","setEffect","event","oldValue","from","to","getParamCompanion","groupControlMap","companion","size","fieldName","config","controlFieldName","createParamField","isActiveGroupParam","controlValue","getParamFieldDefaultValue","getDefault","initValue","initialized","rawValue","serialized","serialize","urlValue","rawValueSerialized","newRawValue","deserialize","Object","defineProperty","_createStorageResource","getField","initMeta","installEffect","setField","setupField","useMeta","macroCondition","getGlobalConfig","LocalResource","id","SessionResource","CacheResource","namespace","field","args","length","WarpDrive","env","DEBUG","test","Error","type","target","key","desc","descriptor","input","includes","originalSet","set","value","Number","undefined","call","effect","fn","overrideType","effectField","_descriptor","meta","fields","pkFn","configurable","enumerable","get"],"sources":["../src/storage/-private/reactive-map.ts","../src/storage/cache.ts","../src/storage/storage.ts","../src/storage/-private/storage-infra.ts","../src/storage/storage-resource.ts"],"sourcesContent":["import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { SignalStore } from '@warp-drive-mirror/core/signals/-leaked';\nimport {\n defineSignal,\n entangleSignal,\n getOrCreateInternalSignal,\n notifyInternalSignal,\n withSignalStore,\n} from '@warp-drive-mirror/core/signals/-leaked';\n\n/**\n * A reactive wrapper around the browser's Map API that provides\n * granular per-key reactivity via WarpDrive's signal system.\n */\nexport class SignalMap<K extends string> {\n private _map: Record<K, number> = {} as Record<K, number>;\n // _size is signal-backed via defineSignal below\n declare private _size: number;\n private _signals: SignalStore = withSignalStore(this._map);\n\n subscribe(key: K): boolean {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const existing = this._signals.has(key);\n entangleSignal(this._signals, this._map, key, undefined);\n const size = this._size;\n this._size = existing ? size : size + 1;\n return existing;\n }\n\n notify(key: K): void {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const signal = getOrCreateInternalSignal(this._signals, this._map, key, 0);\n notifyInternalSignal(signal);\n }\n\n clear(): void {\n for (const value of this._signals.values()) {\n notifyInternalSignal(value);\n }\n this._size = 0;\n }\n\n get size(): number {\n return this._size;\n }\n}\ndefineSignal(SignalMap.prototype, '_size', 0);\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nexport const DEFAULT_CACHE_ID = 'reactive-cache';\nconst CACHES = new Map<string, CacheStorage>();\nconst StorageEvents = new BroadcastChannel('reactive-cache-events');\nconst CACHE_URL = `${location.origin}/api/reactive-cache.json`;\n\nexport interface InternalCacheStorageEvent {\n storageArea: string;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\nexport interface CacheStorageEvent {\n storageArea: CacheStorage;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\n\n/**\n * Emits a {@link StorageEvent} on the local context to\n * match the broadcast event.\n */\nfunction emitStorageEvent(event: CacheStorageEvent): void {\n window.dispatchEvent(new CustomEvent('storage', { detail: event }));\n}\n\n/**\n * Updates the cache and re-emits the event on the local context as a StorageEvent\n * This is necessary to trigger the reactive updates in the current tab.\n */\nfunction handleCacheEvent(event: MessageEvent<InternalCacheStorageEvent>): void {\n const { data } = event;\n\n const cache = CACHES.get(data.storageArea);\n // if we don't have an instance of the cache in this context\n // then we don't need to do anything since there are no reactive\n // subscribers to update\n if (!cache) {\n return;\n }\n\n // a StorageEvent with a key of null\n // is a signal that the entire cache should be cleared.\n if (data.key === null) {\n cache._data = new Map();\n emitStorageEvent({\n storageArea: cache,\n key: null,\n oldValue: null,\n newValue: null,\n });\n return;\n }\n\n if (data.newValue === null) {\n // remove the key from the cache\n cache._data.delete(data.key);\n } else {\n // update the cache with the new value\n cache._data.set(data.key, data.newValue);\n }\n\n // emit a StorageEvent to trigger reactive updates in this context\n emitStorageEvent({\n storageArea: cache,\n key: data.key,\n oldValue: data.oldValue,\n newValue: data.newValue,\n });\n}\n\n// subscribe to all storage events from other contexts to\n// keep caches in sync\nStorageEvents.addEventListener('message', handleCacheEvent);\n\n/**\n * A reactive interface for json stored in the browser [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API.\n *\n * This is a good option for larger data sets than can be efficiently stored in localStorage\n * but should not be used as a permanent DB or storage solution.\n */\nexport class CacheStorage implements Storage {\n #cache: Cache | null;\n #cacheId: string;\n #inititalization: Promise<CacheStorage>;\n _data: Map<string, string | null> = new Map();\n _nextUpdate: number | null = null;\n _bufferedEvents: InternalCacheStorageEvent[] = [];\n\n async #initialize() {\n const cache = await caches.open(this.#cacheId);\n this.#cache = cache;\n\n // Load all existing entries into memory\n this._data = await deserializeFromCache(cache);\n\n return this;\n }\n\n constructor(cacheId: string) {\n this.#cacheId = cacheId;\n this.#cache = null;\n this.#inititalization = this.#initialize();\n }\n\n get length(): number {\n return this._data.size;\n }\n\n #update(key: string | null, oldValue: string | null, newValue: string | null) {\n const cache = this.#cache;\n if (!cache) {\n throw new Error('Cache not initialized');\n }\n this._bufferedEvents.push({\n storageArea: this.#cacheId,\n key: key,\n oldValue: oldValue,\n newValue: newValue,\n });\n if (!this._nextUpdate) {\n this._nextUpdate = window.setTimeout(() => {\n const events = this._bufferedEvents;\n this._bufferedEvents = [];\n this._nextUpdate = null;\n void serializeToCache(cache, this._data);\n for (const event of events) {\n StorageEvents.postMessage(event);\n }\n }, 0);\n }\n }\n\n clear(): void {\n this._data = new Map();\n this.#update(null, null, null);\n }\n\n getItem(key: string): string | null {\n return this._data.get(key) ?? null;\n }\n\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n assert('ReactiveStorage.key: index must be a non-negative integer', index >= 0 && Number.isInteger(index));\n assert('ReactiveStorage.key: index must be less than the number of items in storage', index < this.length);\n\n let i = 0;\n for (const value of this._data.keys()) {\n if (i === index) {\n return value;\n }\n i++;\n }\n\n return null;\n }\n\n removeItem(key: string): void {\n if (this._data.has(key)) {\n const oldValue = this._data.get(key) ?? null;\n this._data.delete(key);\n this.#update(key, oldValue, null);\n }\n }\n\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n const oldValue = this._data.get(key) ?? null;\n if (oldValue === value) {\n return;\n }\n this._data.set(key, value);\n this.#update(key, oldValue, value);\n }\n\n /**\n * Get the singleton CacheStorage instance.\n *\n */\n static get(cacheId: string = DEFAULT_CACHE_ID): Promise<CacheStorage> {\n let cache = CACHES.get(cacheId);\n if (!cache) {\n cache = new CacheStorage(cacheId);\n CACHES.set(cacheId, cache);\n }\n return cache.#inititalization;\n }\n\n static expectCache(cacheId: string = DEFAULT_CACHE_ID): CacheStorage {\n const cache = CACHES.get(cacheId);\n if (!cache) {\n throw new Error(`Cache with id ${cacheId} not found. Make sure to call CacheStorage.get(${cacheId}) first.`);\n }\n return cache;\n }\n\n /**\n * Returns the IDs of all {@link CacheStorage} instances that have been\n * opened in this context via {@link CacheStorage.get}.\n */\n static getAllCacheIds(): string[] {\n return Array.from(CACHES.keys());\n }\n}\n\ninterface CacheFile {\n version: 1;\n data: Array<[string, string]>;\n}\n\nfunction serializeToCache(cache: Cache, data: Map<string, string | null>): Promise<void> {\n const entries = Array.from(data.entries());\n const blob = JSON.stringify({\n version: 1,\n data: entries,\n });\n const response = new Response(blob);\n return cache.put(CACHE_URL, response);\n}\n\nfunction deserializeFromCache(cache: Cache): Promise<Map<string, string | null>> {\n return cache.match(CACHE_URL).then((response) => {\n if (!response) {\n return new Map();\n }\n return response.json().then((json: CacheFile) => {\n if (json.version !== 1) {\n throw new Error(`Unsupported cache version: ${json.version as string}`);\n }\n return new Map(json.data);\n });\n });\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { defineSignal, makeInitializer } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { SignalMap } from './-private/reactive-map.ts';\nimport { CacheStorage, type CacheStorageEvent, DEFAULT_CACHE_ID } from './cache.ts';\n\nexport interface ReactiveStorageOptions {\n /**\n * If true, falls back to in-memory storage when the underlying\n * storage is unavailable (e.g., private browsing mode).\n */\n fallbackToMemory?: boolean;\n\n /**\n * If true, updates signal state even when writes fail due to quota.\n * The onQuotaExceeded callback will be invoked before retrying.\n */\n updateOnQuotaExceeded?: boolean;\n\n /**\n * Called when a write fails due to quota exceeded.\n * Return true to retry the write after freeing space.\n */\n onQuotaExceeded?: (key: string, value: string) => boolean | Promise<boolean>;\n}\n\nlet localStorageInstance: ReactiveStorage | null = null;\nlet sessionStorageInstance: ReactiveStorage | null = null;\nlet localStorageOptions: ReactiveStorageOptions = {};\nlet sessionStorageOptions: ReactiveStorageOptions = {};\n\n// This pattern enables us to have a singleton service-like\n// instance that also functions as a global singleton that\n// can be imported and used outside of Ember's DI system.\n/**\n * Retrieves the singleton instance of the LocalStorage service.\n *\n * If the instance does not already exist, it is created.\n */\nexport function getLocalStorage(): ReactiveStorage {\n if (!localStorageInstance) {\n localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);\n }\n return localStorageInstance;\n}\n\nexport function getSessionStorage(): ReactiveStorage {\n if (!sessionStorageInstance) {\n sessionStorageInstance = new ReactiveStorage(sessionStorage, sessionStorageOptions);\n }\n return sessionStorageInstance;\n}\n\nconst CacheStorages = new Map<string, ReactiveStorage>();\nexport function getCacheStorage(namespace: string | null = null): ReactiveStorage {\n const key = namespace ?? DEFAULT_CACHE_ID;\n let cache = CacheStorages.get(key);\n if (!cache) {\n const storage = CacheStorage.expectCache(key);\n cache = new ReactiveStorage(storage);\n CacheStorages.set(key, cache);\n }\n return cache;\n}\n\n/**\n * Configure options for the localStorage singleton.\n * Must be called before getLocalStorage() is first invoked.\n */\nexport function configureLocalStorage(options: ReactiveStorageOptions): void {\n localStorageOptions = options;\n}\n\n/**\n * Configure options for the sessionStorage singleton.\n * Must be called before getSessionStorage() is first invoked.\n */\nexport function configureSessionStorage(options: ReactiveStorageOptions): void {\n sessionStorageOptions = options;\n}\n\n/**\n * Check if an error is a quota exceeded error\n */\nfunction isQuotaExceededError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Most browsers\n if (error.name === 'QuotaExceededError') return true;\n // Firefox\n if (error.name === 'NS_ERROR_DOM_QUOTA_REACHED') return true;\n }\n return false;\n}\n\n/**\n * Check if an error indicates storage is unavailable (private browsing, etc.)\n */\nfunction isStorageUnavailableError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Safari private browsing, some security restrictions\n if (error.name === 'SecurityError') return true;\n // Some browsers throw this in private mode\n if (error.name === 'InvalidStateError') return true;\n }\n return false;\n}\n\nexport type EffectStorageEvent = CacheStorageEvent | StorageEvent;\n\ndeclare global {\n interface WindowEventMap {\n storage: CustomEvent<CacheStorageEvent> | StorageEvent;\n }\n}\n\n/**\n * A reactive wrapper around the Web Storage API (localStorage/sessionStorage)\n * that provides signal-based access to storage items and length.\n *\n * Will automatically update when storage events occur in other tabs/windows.\n */\nclass ReactiveStorage implements Storage {\n private _storage: Storage;\n private _options: ReactiveStorageOptions;\n private _memoryOnly = false;\n private _values: Record<string, string | null> = {};\n\n declare private _signals: SignalMap<string>;\n declare private _length: number;\n\n private _effects = new Map<string, (value: EffectStorageEvent) => void>();\n setEffect(key: string, fn: (value: EffectStorageEvent) => void): void {\n assert(`Can only set effect once for key: ${key}`, !this._effects.has(key));\n this._effects.set(key, fn);\n }\n\n constructor(storage: Storage, options: ReactiveStorageOptions = {}) {\n this._storage = storage;\n this._options = options;\n\n if (!(storage instanceof CacheStorage)) {\n // Test if storage is accessible\n try {\n const testKey = '__storage_test__';\n storage.setItem(testKey, testKey);\n storage.removeItem(testKey);\n this._length = storage.length;\n } catch (error) {\n if (options.fallbackToMemory && isStorageUnavailableError(error)) {\n this._memoryOnly = true;\n this._length = 0;\n } else {\n throw error;\n }\n }\n }\n\n // bind to localStorage events to trigger reactivity\n if (!this._memoryOnly) {\n window.addEventListener('storage', (event: StorageEvent | CustomEvent<CacheStorageEvent>) => {\n const data = 'detail' in event ? event.detail : event;\n\n // Only react to changes in the same storage area\n if (data.storageArea === storage) {\n this._values[data.key as string] = data.newValue;\n this._signals.notify(data.key as string);\n this._length = this._storage.length;\n const effect = this._effects.get(data.key as string);\n if (effect) {\n effect(data);\n }\n }\n });\n }\n }\n\n /**\n * Reactive access to the number of keys in Storage\n */\n get length(): number {\n return this._length;\n }\n\n /**\n * Non-reactive way to peek the current value of a key in Storage\n */\n peekItem(key: string): string | null {\n assert('ReactiveStorage.peekItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n return value;\n }\n\n // Not yet loaded, fetch from storage, but don't track access\n const item = this._storage.getItem(keyStr);\n // this._values[keyStr] = item;\n return item;\n }\n\n /**\n * Reactive access to Storage contents\n */\n getItem(key: string): string | null {\n assert('ReactiveStorage.getItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n this._signals.subscribe(keyStr);\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n this._signals.subscribe(keyStr);\n return value;\n }\n\n // Not yet loaded, fetch from storage\n const item = this._storage.getItem(keyStr);\n this._values[keyStr] = item;\n this._signals.subscribe(keyStr);\n return item;\n }\n\n /**\n * Set a value in Storage, triggering reactivity\n */\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n\n // Coerce to strings to match Storage API behavior\n const keyStr = String(key);\n const valueStr = String(value);\n const current = this._values[keyStr];\n if (current === valueStr) {\n // No change\n return;\n }\n\n // console.trace(`set field ${key} => ${String(value)}`);\n\n if (this._memoryOnly) {\n const currentValue = this._values[keyStr];\n if (currentValue === null || currentValue === undefined) {\n this._length += 1;\n }\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n return;\n }\n\n try {\n this._storage.setItem(keyStr, valueStr);\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n } catch (error) {\n if (isQuotaExceededError(error)) {\n if (this._options.updateOnQuotaExceeded) {\n // Update signal state even though write failed\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n }\n\n if (this._options.onQuotaExceeded) {\n const result = this._options.onQuotaExceeded(keyStr, valueStr);\n const retry = result instanceof Promise ? false : result;\n\n if (retry) {\n // Retry the write after callback freed space\n this._storage.setItem(keyStr, valueStr);\n this._length = this._storage.length;\n }\n } else {\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Remove a value from Storage, triggering reactivity\n */\n removeItem(key: string): void {\n assert('ReactiveStorage.removeItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n const value = this._values[keyStr];\n if (value !== null && value !== undefined) {\n this._length -= 1;\n }\n this._values[keyStr] = null;\n return;\n }\n\n this._storage.removeItem(keyStr);\n this._values[keyStr] = null;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n }\n\n /**\n * Clears all keys from Storage, triggering reactivity\n */\n clear(): void {\n this._values = {};\n this._signals.clear();\n this._length = 0;\n\n if (this._memoryOnly) {\n return;\n }\n\n this._storage.clear();\n }\n\n /**\n * Reactive access to the key at the given index\n */\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n this._length; // track length access\n\n if (this._memoryOnly) {\n const keys = Object.keys(this._values).filter((k) => this._values[k] !== null);\n return keys[index] ?? null;\n }\n\n return this._storage.key(index);\n }\n}\ndefineSignal(ReactiveStorage.prototype, '_length', 0);\ndefineSignal(\n ReactiveStorage.prototype,\n '_signals',\n makeInitializer(() => new SignalMap<string>())\n);\n\nexport type { ReactiveStorage };\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { memoized } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { type EffectStorageEvent, getCacheStorage, getLocalStorage, getSessionStorage } from '../storage.ts';\n\n/**\n * Configuration options for fields that are also query parameters\n */\nexport interface ParamConfig {\n /**\n * Convert a value into a string for storage in the URL.\n * `null` indicates the value should be omitted from the URL.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialize: (value: unknown, instance: any) => string | null;\n /**\n * Convert a string value from the URL back into\n * its original type\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n deserialize: (urlValue: string, instance: any) => unknown;\n /**\n * Get the default value for this param from the given instance.\n *\n * If not present, the value passed to the field initializer\n * will be used as the default.\n *\n * This should return the value in the field's native type,\n * not the serialized URL form.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getDefault?: (instance: any) => unknown;\n}\n\ninterface InternalParamConfig extends ParamConfig {\n initialized?: boolean;\n}\n\nexport interface ValueTransition<T = unknown> {\n key: string;\n from: T;\n to: T;\n}\n\n/**\n * Metadata attached to persisted resource classes\n */\nexport interface StorageResourceMeta {\n id: string;\n namespace: string | null;\n pkFn: KeyFn | null;\n type: 'local-resource' | 'session-resource' | 'cache-resource';\n typeOverrides: Map<string, 'local-storage' | 'session-storage' | 'cache-storage'> | null;\n fields: Map<string, null | ((update: ValueTransition<string>) => void)>;\n initializers: Map<string, (() => unknown) | null>;\n paramConfigs: Map<string, InternalParamConfig> | null;\n paramCompanion: object | null;\n instances: WeakMap<object, StorageResourceMeta> | null;\n}\n\n/**\n * A function which generates a unique primary-key\n * string for a given LocalResource or SessionResource\n * instance.\n *\n * Use functions when you want to create more than\n * one instance of a resource type, each with its own\n * persisted data.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type KeyFn = (obj: any) => string;\n\n/**\n * Symbol used to store persistence metadata on classes\n */\nconst PERSISTED_RESOURCE_META = Symbol('StorageResourceMeta');\n\n/**\n * Setup persisted resource metadata on target\n * if not already present\n *\n * @private\n */\nexport function initMeta(target: object): StorageResourceMeta {\n let meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n if (!meta) {\n meta = {\n id: '',\n namespace: null,\n pkFn: null,\n type: '' as 'local-resource' | 'session-resource',\n fields: new Map(),\n initializers: new Map(),\n paramConfigs: null,\n paramCompanion: null,\n instances: null,\n typeOverrides: null,\n };\n (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META] = meta;\n }\n return meta;\n}\n\nexport function useMeta(meta: StorageResourceMeta, instance: object): StorageResourceMeta {\n // If a primary key function is defined, use it to generate\n // a unique ID for this instance\n if (meta.id === '' && meta.pkFn) {\n // we are in an instance context\n meta.instances = meta.instances ?? new WeakMap();\n let instanceMeta = meta.instances.get(instance);\n if (!instanceMeta) {\n instanceMeta = { ...meta };\n const pk = meta.pkFn(instance);\n assert('Primary key function must return a non-empty string.', typeof pk === 'string' && pk.length > 0);\n instanceMeta.id = pk;\n meta.instances.set(instance, instanceMeta);\n }\n return instanceMeta;\n }\n\n assert('StorageResourceMeta must have a valid id.', typeof meta.id === 'string' && meta.id.length > 0);\n return meta;\n}\n\n/**\n * Load storage field\n */\nexport function getField(\n instance: object,\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): Record<string, unknown> | null {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.getItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n } else {\n // No stored value, check for initializer\n const initializer = meta.initializers.get(key);\n if (initializer) {\n const value = initializer.call(instance);\n if (value !== undefined) {\n return value as Record<string, unknown>;\n }\n }\n }\n return null;\n}\n\nfunction keyFor(meta: StorageResourceMeta, key: string): string {\n return `persisted:${meta.id}:${key}`;\n}\n\nfunction getStorage(type: string, namespace: string | null) {\n if (type === 'local-resource') {\n return getLocalStorage();\n } else if (type === 'session-resource') {\n return getSessionStorage();\n } else {\n return getCacheStorage(namespace);\n }\n}\n\nexport function peekField(\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): unknown {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.peekItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n }\n return null;\n}\n\nexport function initializeFields(instance: object, source: object): void {\n // we need to initialize the fields without reading from their reactive state\n // we also only want to initialize the field if it is still at its default value\n // as otherwise we are likely overwriting a persisted value or url value\n const baseMeta = getResourceMeta(instance);\n const meta = useMeta(baseMeta, instance);\n\n for (const [key] of meta.fields.entries()) {\n if (key in source) {\n // get the new value from source\n const newValue = (source as Record<string, unknown>)[key];\n\n // get the current default value from the field initializer\n const initializer = meta.initializers.get(key);\n let defaultValue: unknown = null;\n if (initializer) {\n defaultValue = initializer.call(instance);\n }\n\n // get the overrideType\n const overrideType = meta.typeOverrides?.get(key) ?? null;\n const type = overrideType || meta.type;\n\n // get the current stored value, without triggering reactivity\n const currentValue = peekField(meta, keyFor(meta, key), overrideType);\n\n // if there is no current value, silently update the field\n const storage = type === 'local-resource' ? localStorage : sessionStorage;\n storage.setItem(keyFor(meta, key), JSON.stringify(newValue));\n // only initialize if current value matches default value\n // or we have no persisted value yet.\n if (currentValue === defaultValue) {\n setField(meta, keyFor(meta, key), newValue as string, overrideType);\n }\n }\n }\n}\n\n/**\n * Update storage field\n */\nexport function setField(\n meta: StorageResourceMeta,\n key: string,\n value: string | boolean | null | number | Record<string, unknown> | unknown[],\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): void {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n storage.setItem(keyFor(meta, key), JSON.stringify(value));\n}\n\nfunction getResourceMeta(target: object): StorageResourceMeta {\n const meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n assert(\n 'StorageResourceMeta not found on target. Did you forget to use the @LocalResource() or @SessionResource() decorator?',\n meta !== undefined\n );\n return meta;\n}\n\nexport function _createStorageResource(\n id: string | KeyFn,\n type: 'local-resource' | 'session-resource' | 'cache-resource',\n namespace: string | null\n): ClassDecorator {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n return function (target: Function) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n const meta = getResourceMeta(target.prototype);\n meta.id = typeof id === 'string' ? id : '';\n meta.pkFn = typeof id === 'function' ? id : null;\n meta.type = type;\n meta.namespace = namespace;\n if (meta.pkFn !== null) {\n // for dynamic instances, we install effects only once\n // fields have been defined and a key created for the\n // instance.\n // for this, we defer effect installation until\n // until object instantiation by wrapping the constructor\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n const originalConstructor = target.prototype.constructor;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n target.prototype.constructor = function DynamicStorageInitializer(...args: unknown[]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, new-cap\n const instance = new originalConstructor(...args) as object;\n void installEffectsForDynamicInstance(meta, instance);\n return instance;\n };\n }\n\n if (!('toJSON' in target.prototype)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n target.prototype.toJSON = function (this: object) {\n const instanceMeta = useMeta(meta, this);\n // we only serialize the id and any localStorage fields, not sessionStorage fields.\n const isLocalResource = meta.type === 'local-resource' || meta.type === 'cache-resource';\n const fields = isLocalResource ? new Set(meta.fields.keys()) : new Set<string>();\n for (const [key, overrideType] of meta.typeOverrides?.entries() ?? []) {\n if (overrideType === 'local-storage') {\n fields.add(key);\n } else if (overrideType === 'session-storage' && isLocalResource) {\n fields.delete(key);\n }\n }\n let idKey = '$key';\n while (fields.has(idKey)) {\n idKey = `_${idKey}`;\n }\n const data: Record<string, unknown> = {\n [idKey]: instanceMeta.id,\n };\n\n for (const key of fields) {\n const value = getField(this, instanceMeta, key, meta.typeOverrides?.get(key) ?? null);\n if (value !== null) {\n data[key] = value;\n }\n }\n\n return data;\n };\n }\n };\n}\n\nasync function installEffectsForDynamicInstance(meta: StorageResourceMeta, instance: object): Promise<void> {\n await Promise.resolve();\n for (const [key, value] of meta.fields.entries()) {\n if (typeof value === 'function') {\n void installEffect(useMeta(meta, instance), key);\n }\n }\n}\n\n/**\n * Returns the descriptor but is cast\n * to void to satisfy Typescript's incorrect\n * typing for legacy decorators.\n */\nexport function setupField(\n target: object,\n key: string,\n orgDesc?: PropertyDescriptor,\n type?: 'local' | 'session' | 'cache'\n): void {\n const meta = initMeta(target);\n meta.fields.set(key, null);\n const overrideType =\n type === 'local'\n ? 'local-storage'\n : type === 'session'\n ? 'session-storage'\n : type === 'cache'\n ? 'cache-storage'\n : null;\n if (overrideType) {\n meta.typeOverrides = meta.typeOverrides || new Map<string, 'local-storage' | 'session-storage' | 'cache-storage'>();\n meta.typeOverrides.set(key, overrideType);\n }\n // @ts-expect-error initializer does exist\n const initializer = (orgDesc?.initializer || null) as (() => unknown) | null;\n meta.initializers.set(key, initializer);\n\n const desc = {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n };\n\n return memoized(target as Record<string, unknown>, key, desc) as unknown as void;\n}\n\nexport async function installEffect(meta: StorageResourceMeta, key: string): Promise<void> {\n await Promise.resolve();\n const effect = meta.fields.get(key) as <K>(v: ValueTransition<K>) => void;\n const storage = getStorage(meta.type, meta.namespace);\n storage.setEffect(keyFor(meta, key), (event: EffectStorageEvent) => {\n const oldValue = event.oldValue ? (JSON.parse(event.oldValue) as unknown) : null;\n const newValue = event.newValue ? (JSON.parse(event.newValue) as unknown) : null;\n effect({ key, from: oldValue, to: newValue });\n });\n}\n\n/**\n * Get or create the param companion object for a StorageResource instance.\n *\n * The companion object contains URL-serialized versions of all @param decorated fields.\n * Each param field gets a corresponding property on the companion that:\n * - Reads: Serializes the storage value to a URL string (returns null if not active)\n * - Writes: Deserializes the URL string and updates the storage value\n *\n * The companion object is reactive using trackedObject, ensuring that changes\n * to the underlying storage fields trigger updates in the query param system.\n *\n * This companion object is what QPRoute will bind to for URL query params.\n *\n * @private\n * @param instance - The StorageResource instance\n * @param groupControlMap - Optional map of fieldName -> controlFieldName for grouped params\n * @returns The companion object with serialized param properties\n */\nexport function getParamCompanion(instance: object, groupControlMap?: Record<string, string>): object {\n const meta = getResourceMeta(instance);\n const instanceMeta = useMeta(meta, instance);\n\n // Return existing companion if already created\n if (instanceMeta.paramCompanion) {\n return instanceMeta.paramCompanion;\n }\n\n // Create new companion object\n const companion = {};\n instanceMeta.paramCompanion = companion;\n\n // Install a property for each param\n const paramConfigs = instanceMeta.paramConfigs;\n if (!paramConfigs || paramConfigs.size === 0) {\n return companion;\n }\n\n for (const [fieldName, config] of paramConfigs.entries()) {\n const controlFieldName = groupControlMap?.[fieldName];\n\n createParamField(companion, fieldName, config, controlFieldName, instance, meta);\n }\n\n return companion;\n}\n\nfunction isActiveGroupParam(companion: object, controlFieldName: string): boolean {\n // if the url value for the control param is `null` we are inactive\n const controlValue = (companion as Record<string, unknown>)[controlFieldName];\n return controlValue !== null;\n}\n\n/**\n * The default value of a param is determined by:\n * - the getDefault() function if provided, and its return is not undefined\n * - the initializer value provided to the field, if not undefined\n * - null otherwise\n *\n * The value is the deserialized form (i.e., the local storage value type)\n */\nfunction getParamFieldDefaultValue(\n meta: StorageResourceMeta,\n config: ParamConfig,\n fieldName: string,\n instance: object\n) {\n const defaultValue = config.getDefault?.(instance);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n const initializer = meta.initializers.get(fieldName);\n if (initializer) {\n const initValue = initializer.call(instance);\n\n if (initValue !== undefined) {\n return initValue;\n }\n }\n\n return null;\n}\n\nfunction createParamField(\n companion: object,\n fieldName: string,\n config: InternalParamConfig,\n controlFieldName: string | undefined,\n instance: object,\n meta: StorageResourceMeta\n): void {\n const desc = {\n configurable: true,\n enumerable: true,\n get(): string | null {\n // Mark as initialized on first access, but continue with normal logic\n if (!config.initialized) {\n config.initialized = true;\n return null;\n }\n\n // Next, check if this param is part of a group and if its control param is active\n // If not active, return null to indicate inactive state\n if (controlFieldName && !isActiveGroupParam(companion, controlFieldName)) {\n return null;\n }\n\n // Next, check if the currently stored value is the default\n // value. If so, return null to indicate inactive state\n const defaultValue = getParamFieldDefaultValue(meta, config, fieldName, instance);\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n if (rawValue === defaultValue) {\n return null;\n }\n\n // Serialize to URL format\n const serialized = config.serialize(rawValue, instance);\n\n // Return null if serialization returns empty, indicating no URL representation\n if (!serialized) {\n return null;\n }\n\n return serialized;\n },\n set(urlValue: string | null) {\n /**\n * set will never come from anything except URL deserialization.\n * which is managed by Ember.\n *\n * Our job is to not unnecessarily update the storage resource\n * so we need to run the compare function to see if the\n * incoming URL value is different from the existing local value.\n */\n\n // If null or empty, skip deserialization\n if (!urlValue) {\n return;\n }\n\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n // Compare incoming URL value with existing local value\n const rawValueSerialized = config.serialize(rawValue, instance);\n if (rawValueSerialized === urlValue) {\n // No change\n return;\n }\n\n // Deserialize from URL format\n const newRawValue = config.deserialize(urlValue, instance);\n\n // Update the storage resource\n (instance as Record<string, unknown>)[fieldName] = newRawValue;\n },\n };\n\n memoized(companion as Record<string, unknown>, fieldName, desc);\n Object.defineProperty(companion, fieldName, desc);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nimport {\n _createStorageResource,\n getField,\n initMeta,\n installEffect,\n type KeyFn,\n setField,\n setupField,\n useMeta,\n type ValueTransition,\n} from './-private/storage-infra.ts';\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in localStorage.\n *\n * LocalResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function LocalResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'local-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in sessionStorage.\n *\n * SessionResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function SessionResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'session-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted via the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n * api and shared across all tabs/windows under the same origin.\n *\n * CacheResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n *\n * All object cached in the same `namespace` share the namespace's storage context,\n * so partitioning can be achieved by using different namespaces for different groups\n * of data.\n */\nexport function CacheResource(id: string | KeyFn, namespace: string | null = null): ClassDecorator {\n return _createStorageResource(id, 'cache-resource', namespace);\n}\n\n/**\n * Decorator which marks a property as a field on\n * a LocalResource or SessionResource\n *\n * The field's value will be initialized from the persisted resource data\n * if available, falling back to the property's default value otherwise.\n *\n * Fields can be of any type that is serializable to and restorable from JSON,\n * but complex types (like objects or arrays) should be handled with care to avoid\n * unintended mutations or reactivity issues.\n *\n * By default, fields are persisted in the storage type defined by the resource decorator\n * (@LocalResource or @SessionResource). However, you can override this behavior\n * by passing 'local' or 'session' as an argument to the decorator.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-settings')\n * class UserSettings {\n * @field\n * theme: 'light' | 'dark' = 'light';\n *\n * @field('session')\n * sessionToken: string | null = null;\n * }\n * ```\n *\n */\nexport function field(type: 'local' | 'session' | 'cache'): PropertyDecorator;\nexport function field(target: object, key: string, descriptor?: PropertyDescriptor): void;\nexport function field(...args: unknown[]): PropertyDecorator | void {\n if (args.length === 0) {\n assert('field decorator requires at least 1 argument or should be used without parens', true);\n return setupField as PropertyDecorator;\n }\n if (args.length === 1) {\n const type = args[0] as 'local' | 'session' | 'cache';\n return ((target: object, key: string, desc?: PropertyDescriptor) =>\n setupField(target, key, desc, type)) as PropertyDecorator;\n }\n if (args.length === 2 || args.length === 3) {\n const [target, key, descriptor] = args as [object, string, PropertyDescriptor | undefined];\n return setupField(target, key, descriptor);\n }\n}\nexport function input(type: 'number' | 'boolean' | 'float'): PropertyDecorator {\n assert('input decorator requires a valid type argument', ['number', 'boolean', 'float'].includes(type));\n return function (target: object, key: string, desc: PropertyDescriptor): void {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalSet = desc.set!;\n desc.set = function (this: object, value: unknown) {\n switch (type) {\n case 'number':\n value = Number(value);\n break;\n case 'boolean':\n value =\n value === 'false' ||\n value === '' ||\n value === '0' ||\n value === 'undefined' ||\n value === 'null' ||\n value === false ||\n value === 0 ||\n value === null ||\n value === undefined\n ? 0\n : 1;\n break;\n default:\n assert(`Unsupported input type: ${type}`);\n }\n originalSet.call(this, value);\n };\n return desc as unknown as void;\n } as PropertyDecorator;\n}\n\n/**\n * Effects are fields that run a side-effecting function.\n *\n * Effects are intended to enable synchronizing get states between\n * tabs or windows that result in needing to synchronize other\n * non-reactive state.\n *\n * For example, when a user selects a light/dark mode theme preference\n * that differs from the system preference, effects can be used to trigger\n * DOM updates on the documentElement necessary to ensure its state is\n * consistent with the persisted resource state and reactive application state.\n *\n * To do this without an effect would require either setting up your own\n * storage event listeners or consuming the reactive state of the property\n * in another effect-like API such as an Ember modifier or React useEffect,\n *\n * Effects *only* run when the stored value changes due to storage events\n * emitted from other tabs or windows. They do not run when the property\n * is updated in the same context.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-preferences')\n * class UserPreferences {\n * @effect(syncThemeToDOM)\n * explicitThemePreference: 'light' | 'dark' | null = null;\n *\n * @matchMedia('(prefers-color-scheme: dark)')\n * systemPrefersDarkMode: boolean = false;\n * }\n *\n * function syncThemeToDOM(update: ValueTransition<'light' | 'dark' | null>): void {\n * const newTheme = update.to;\n * document.documentElement.style.colorScheme = newTheme ?? 'light dark';\n *\n * if (newTheme === 'dark') {\n * document.documentElement.classList.add('dark-theme');\n * document.documentElement.classList.remove('light-theme');\n * } else if (newTheme === 'light') {\n * document.documentElement.classList.add('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * } else {\n * document.documentElement.classList.remove('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * }\n * }\n * ```\n */\nexport function effect(fn: <K>(update: ValueTransition<K>) => void, type?: 'local' | 'session'): PropertyDecorator {\n const overrideType = type === 'local' ? 'local-storage' : type === 'session' ? 'session-storage' : null;\n return function effectField(\n target: object,\n key: string,\n\n _descriptor?: PropertyDescriptor\n ): void {\n const meta = initMeta(target);\n meta.fields.set(key, fn);\n\n // only install the effect if we are not in a primary-keyed instance context\n if (meta.pkFn === null) void installEffect(meta, key);\n\n return {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n } as unknown as void;\n } as unknown as PropertyDecorator;\n}\n"],"mappings":";;;;;;;;AAcA,IAAaO,YAAb,MAAyC;CAC/BC,OAA0B,CAAC;CAG3BC,WAAwBL,gBAAgB,KAAKI,IAAI;CAEzDE,UAAUC,KAAiB;EACzBN,eAAAC,gBAAA,CAAA,CAAAM,UAAAC,IAAAC,KAAA,OAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOL,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMM,WAAW,KAAKR,SAASS,IAAIP,GAAG;EACtCV,eAAe,KAAKQ,UAAU,KAAKD,MAAMG,KAAKQ,MAAS;EACvD,MAAMC,OAAO,KAAKC;EAClB,KAAKA,QAAQJ,WAAWG,OAAOA,OAAO;EACtC,OAAOH;CACT;CAEAK,OAAOX,KAAc;EACnBN,eAAAC,gBAAA,CAAA,CAAAM,UAAAC,IAAAC,KAAA,OAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOL,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMY,SAASrB,0BAA0B,KAAKO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AAAC,IAAAC,KAAA,OAAAC,SAAA;KAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,2BAA2BC,MAAM;IAAA,EAAA,CAAA,KAAA;GAC5C;GACAO,YAAYK,KAAK,MAAMH,KAAK;EAC9B;EACA,OAAON;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgBU,OAAOC,IAA6Cd,MAA+C;CACjH,MAAMe,eAAef,SAAS,UAAU,kBAAkBA,SAAS,YAAY,oBAAoB;CACnG,OAAO,SAASgB,YACdf,QACAC,KAEAe,aACM;EACN,MAAMC,OAAOtC,SAASqB,MAAM;EAC5BiB,KAAKC,OAAOX,IAAIN,KAAKY,EAAE;EAGvB,IAAII,KAAKE,SAAS,MAAM,AAAKvC,cAAcqC,MAAMhB,GAAG;EAEpD,OAAO;GACLmB,cAAc;GACdC,YAAY;GACZC,MAA2B;IACzB,OAAO5C,SAAS,MAAMK,QAAQkC,MAAM,IAAI,GAAGhB,KAAKa,YAAY;GAC9D;GACAP,IAAkBC,OAAgB;IAChC3B,SAASE,QAAQkC,MAAM,IAAI,GAAGhB,KAAKO,OAAiBM,YAAY;GAClE;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"storage.js","names":["defineSignal","entangleSignal","getOrCreateInternalSignal","notifyInternalSignal","withSignalStore","macroCondition","getGlobalConfig","SignalMap","_map","_signals","subscribe","key","WarpDrive","env","DEBUG","test","Error","existing","has","undefined","size","_size","notify","signal","clear","value","values","prototype","DEFAULT_CACHE_ID","CACHES","Map","StorageEvents","BroadcastChannel","CACHE_URL","location","origin","emitStorageEvent","event","window","dispatchEvent","CustomEvent","detail","handleCacheEvent","data","cache","get","storageArea","key","_data","oldValue","newValue","delete","set","addEventListener","CacheStorage","cacheId","inititalization","_nextUpdate","_bufferedEvents","initialize","#initialize","caches","open","deserializeFromCache","constructor","length","size","update","#update","Error","push","setTimeout","events","serializeToCache","postMessage","clear","getItem","index","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","Number","isInteger","i","value","keys","removeItem","has","setItem","expectCache","getAllCacheIds","Array","from","entries","blob","JSON","stringify","version","response","Response","put","match","then","json","defineSignal","makeInitializer","SignalMap","CacheStorage","DEFAULT_CACHE_ID","macroCondition","getGlobalConfig","localStorageInstance","sessionStorageInstance","localStorageOptions","sessionStorageOptions","getLocalStorage","ReactiveStorage","localStorage","getSessionStorage","sessionStorage","CacheStorages","Map","getCacheStorage","namespace","key","cache","get","storage","expectCache","set","configureLocalStorage","options","configureSessionStorage","isQuotaExceededError","error","DOMException","name","isStorageUnavailableError","_storage","_options","_memoryOnly","_values","_effects","setEffect","fn","WarpDrive","env","DEBUG","test","Error","has","constructor","testKey","setItem","removeItem","_length","length","fallbackToMemory","window","addEventListener","event","data","detail","storageArea","newValue","_signals","notify","effect","peekItem","keyStr","String","value","undefined","item","getItem","subscribe","valueStr","current","currentValue","updateOnQuotaExceeded","onQuotaExceeded","result","retry","Promise","clear","index","keys","Object","filter","k","prototype","memoized","getCacheStorage","getLocalStorage","getSessionStorage","macroCondition","getGlobalConfig","PERSISTED_RESOURCE_META","Symbol","initMeta","target","meta","id","namespace","pkFn","type","fields","Map","initializers","paramConfigs","paramCompanion","instances","typeOverrides","useMeta","instance","WeakMap","instanceMeta","get","pk","WarpDrive","env","DEBUG","test","Error","length","set","getField","key","overrideType","storage","getStorage","stored","getItem","keyFor","JSON","parse","initializer","value","call","undefined","peekField","peekItem","initializeFields","source","baseMeta","getResourceMeta","entries","newValue","defaultValue","currentValue","localStorage","sessionStorage","setItem","stringify","setField","_createStorageResource","prototype","originalConstructor","constructor","DynamicStorageInitializer","args","installEffectsForDynamicInstance","toJSON","isLocalResource","Set","keys","add","delete","idKey","has","data","Promise","resolve","installEffect","setupField","orgDesc","desc","configurable","enumerable","effect","setEffect","event","oldValue","from","to","getParamCompanion","groupControlMap","companion","size","fieldName","config","controlFieldName","createParamField","isActiveGroupParam","controlValue","getParamFieldDefaultValue","getDefault","initValue","initialized","rawValue","serialized","serialize","urlValue","rawValueSerialized","newRawValue","deserialize","Object","defineProperty","_createStorageResource","getField","initMeta","installEffect","setField","setupField","useMeta","macroCondition","getGlobalConfig","LocalResource","id","SessionResource","CacheResource","namespace","field","args","length","WarpDrive","env","DEBUG","test","Error","type","target","key","desc","descriptor","input","includes","originalSet","set","value","Number","undefined","call","effect","fn","overrideType","effectField","_descriptor","meta","fields","pkFn","configurable","enumerable","get"],"sources":["../src/storage/-private/reactive-map.ts","../src/storage/cache.ts","../src/storage/storage.ts","../src/storage/-private/storage-infra.ts","../src/storage/storage-resource.ts"],"sourcesContent":["import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { SignalStore } from '@warp-drive-mirror/core/signals/-leaked';\nimport {\n defineSignal,\n entangleSignal,\n getOrCreateInternalSignal,\n notifyInternalSignal,\n withSignalStore,\n} from '@warp-drive-mirror/core/signals/-leaked';\n\n/**\n * A reactive wrapper around the browser's Map API that provides\n * granular per-key reactivity via WarpDrive's signal system.\n */\nexport class SignalMap<K extends string> {\n private _map: Record<K, number> = {} as Record<K, number>;\n // _size is signal-backed via defineSignal below\n declare private _size: number;\n private _signals: SignalStore = withSignalStore(this._map);\n\n subscribe(key: K): boolean {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const existing = this._signals.has(key);\n entangleSignal(this._signals, this._map, key, undefined);\n const size = this._size;\n this._size = existing ? size : size + 1;\n return existing;\n }\n\n notify(key: K): void {\n assert(`ReactiveMap keys must be strings, got ${typeof key}`, typeof key === 'string');\n const signal = getOrCreateInternalSignal(this._signals, this._map, key, 0);\n notifyInternalSignal(signal);\n }\n\n clear(): void {\n for (const value of this._signals.values()) {\n notifyInternalSignal(value);\n }\n this._size = 0;\n }\n\n get size(): number {\n return this._size;\n }\n}\ndefineSignal(SignalMap.prototype, '_size', 0);\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nexport const DEFAULT_CACHE_ID = 'reactive-cache';\nconst CACHES = new Map<string, CacheStorage>();\nconst StorageEvents = new BroadcastChannel('reactive-cache-events');\nconst CACHE_URL = `${location.origin}/api/reactive-cache.json`;\n\nexport interface InternalCacheStorageEvent {\n storageArea: string;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\nexport interface CacheStorageEvent {\n storageArea: CacheStorage;\n key: string | null;\n oldValue: string | null;\n newValue: string | null;\n}\n\n/**\n * Emits a {@link StorageEvent} on the local context to\n * match the broadcast event.\n */\nfunction emitStorageEvent(event: CacheStorageEvent): void {\n window.dispatchEvent(new CustomEvent('storage', { detail: event }));\n}\n\n/**\n * Updates the cache and re-emits the event on the local context as a StorageEvent\n * This is necessary to trigger the reactive updates in the current tab.\n */\nfunction handleCacheEvent(event: MessageEvent<InternalCacheStorageEvent>): void {\n const { data } = event;\n\n const cache = CACHES.get(data.storageArea);\n // if we don't have an instance of the cache in this context\n // then we don't need to do anything since there are no reactive\n // subscribers to update\n if (!cache) {\n return;\n }\n\n // a StorageEvent with a key of null\n // is a signal that the entire cache should be cleared.\n if (data.key === null) {\n cache._data = new Map();\n emitStorageEvent({\n storageArea: cache,\n key: null,\n oldValue: null,\n newValue: null,\n });\n return;\n }\n\n if (data.newValue === null) {\n // remove the key from the cache\n cache._data.delete(data.key);\n } else {\n // update the cache with the new value\n cache._data.set(data.key, data.newValue);\n }\n\n // emit a StorageEvent to trigger reactive updates in this context\n emitStorageEvent({\n storageArea: cache,\n key: data.key,\n oldValue: data.oldValue,\n newValue: data.newValue,\n });\n}\n\n// subscribe to all storage events from other contexts to\n// keep caches in sync\nStorageEvents.addEventListener('message', handleCacheEvent);\n\n/**\n * A reactive interface for json stored in the browser [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) API.\n *\n * This is a good option for larger data sets than can be efficiently stored in localStorage\n * but should not be used as a permanent DB or storage solution.\n */\nexport class CacheStorage implements Storage {\n #cache: Cache | null;\n #cacheId: string;\n #inititalization: Promise<CacheStorage>;\n _data: Map<string, string | null> = new Map();\n _nextUpdate: number | null = null;\n _bufferedEvents: InternalCacheStorageEvent[] = [];\n\n async #initialize() {\n const cache = await caches.open(this.#cacheId);\n this.#cache = cache;\n\n // Load all existing entries into memory\n this._data = await deserializeFromCache(cache);\n\n return this;\n }\n\n constructor(cacheId: string) {\n this.#cacheId = cacheId;\n this.#cache = null;\n this.#inititalization = this.#initialize();\n }\n\n get length(): number {\n return this._data.size;\n }\n\n #update(key: string | null, oldValue: string | null, newValue: string | null) {\n const cache = this.#cache;\n if (!cache) {\n throw new Error('Cache not initialized');\n }\n this._bufferedEvents.push({\n storageArea: this.#cacheId,\n key: key,\n oldValue: oldValue,\n newValue: newValue,\n });\n if (!this._nextUpdate) {\n this._nextUpdate = window.setTimeout(() => {\n const events = this._bufferedEvents;\n this._bufferedEvents = [];\n this._nextUpdate = null;\n void serializeToCache(cache, this._data);\n for (const event of events) {\n StorageEvents.postMessage(event);\n }\n }, 0);\n }\n }\n\n clear(): void {\n this._data = new Map();\n this.#update(null, null, null);\n }\n\n getItem(key: string): string | null {\n return this._data.get(key) ?? null;\n }\n\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n assert('ReactiveStorage.key: index must be a non-negative integer', index >= 0 && Number.isInteger(index));\n assert('ReactiveStorage.key: index must be less than the number of items in storage', index < this.length);\n\n let i = 0;\n for (const value of this._data.keys()) {\n if (i === index) {\n return value;\n }\n i++;\n }\n\n return null;\n }\n\n removeItem(key: string): void {\n if (this._data.has(key)) {\n const oldValue = this._data.get(key) ?? null;\n this._data.delete(key);\n this.#update(key, oldValue, null);\n }\n }\n\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n const oldValue = this._data.get(key) ?? null;\n if (oldValue === value) {\n return;\n }\n this._data.set(key, value);\n this.#update(key, oldValue, value);\n }\n\n /**\n * Get the singleton CacheStorage instance.\n *\n */\n static get(cacheId: string = DEFAULT_CACHE_ID): Promise<CacheStorage> {\n let cache = CACHES.get(cacheId);\n if (!cache) {\n cache = new CacheStorage(cacheId);\n CACHES.set(cacheId, cache);\n }\n return cache.#inititalization;\n }\n\n static expectCache(cacheId: string = DEFAULT_CACHE_ID): CacheStorage {\n const cache = CACHES.get(cacheId);\n if (!cache) {\n throw new Error(`Cache with id ${cacheId} not found. Make sure to call CacheStorage.get(${cacheId}) first.`);\n }\n return cache;\n }\n\n /**\n * Returns the IDs of all {@link CacheStorage} instances that have been\n * opened in this context via {@link CacheStorage.get}.\n */\n static getAllCacheIds(): string[] {\n return Array.from(CACHES.keys());\n }\n}\n\ninterface CacheFile {\n version: 1;\n data: Array<[string, string]>;\n}\n\nfunction serializeToCache(cache: Cache, data: Map<string, string | null>): Promise<void> {\n const entries = Array.from(data.entries());\n const blob = JSON.stringify({\n version: 1,\n data: entries,\n });\n const response = new Response(blob);\n return cache.put(CACHE_URL, response);\n}\n\nfunction deserializeFromCache(cache: Cache): Promise<Map<string, string | null>> {\n return cache.match(CACHE_URL).then((response) => {\n if (!response) {\n return new Map();\n }\n return response.json().then((json: CacheFile) => {\n if (json.version !== 1) {\n throw new Error(`Unsupported cache version: ${json.version as string}`);\n }\n return new Map(json.data);\n });\n });\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { defineSignal, makeInitializer } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { SignalMap } from './-private/reactive-map.ts';\nimport { CacheStorage, type CacheStorageEvent, DEFAULT_CACHE_ID } from './cache.ts';\n\nexport interface ReactiveStorageOptions {\n /**\n * If true, falls back to in-memory storage when the underlying\n * storage is unavailable (e.g., private browsing mode).\n */\n fallbackToMemory?: boolean;\n\n /**\n * If true, updates signal state even when writes fail due to quota.\n * The onQuotaExceeded callback will be invoked before retrying.\n */\n updateOnQuotaExceeded?: boolean;\n\n /**\n * Called when a write fails due to quota exceeded.\n * Return true to retry the write after freeing space.\n */\n onQuotaExceeded?: (key: string, value: string) => boolean | Promise<boolean>;\n}\n\nlet localStorageInstance: ReactiveStorage | null = null;\nlet sessionStorageInstance: ReactiveStorage | null = null;\nlet localStorageOptions: ReactiveStorageOptions = {};\nlet sessionStorageOptions: ReactiveStorageOptions = {};\n\n// This pattern enables us to have a singleton service-like\n// instance that also functions as a global singleton that\n// can be imported and used outside of Ember's DI system.\n/**\n * Retrieves the singleton instance of the LocalStorage service.\n *\n * If the instance does not already exist, it is created.\n */\nexport function getLocalStorage(): ReactiveStorage {\n if (!localStorageInstance) {\n localStorageInstance = new ReactiveStorage(localStorage, localStorageOptions);\n }\n return localStorageInstance;\n}\n\nexport function getSessionStorage(): ReactiveStorage {\n if (!sessionStorageInstance) {\n sessionStorageInstance = new ReactiveStorage(sessionStorage, sessionStorageOptions);\n }\n return sessionStorageInstance;\n}\n\nconst CacheStorages = new Map<string, ReactiveStorage>();\nexport function getCacheStorage(namespace: string | null = null): ReactiveStorage {\n const key = namespace ?? DEFAULT_CACHE_ID;\n let cache = CacheStorages.get(key);\n if (!cache) {\n const storage = CacheStorage.expectCache(key);\n cache = new ReactiveStorage(storage);\n CacheStorages.set(key, cache);\n }\n return cache;\n}\n\n/**\n * Configure options for the localStorage singleton.\n * Must be called before getLocalStorage() is first invoked.\n */\nexport function configureLocalStorage(options: ReactiveStorageOptions): void {\n localStorageOptions = options;\n}\n\n/**\n * Configure options for the sessionStorage singleton.\n * Must be called before getSessionStorage() is first invoked.\n */\nexport function configureSessionStorage(options: ReactiveStorageOptions): void {\n sessionStorageOptions = options;\n}\n\n/**\n * Check if an error is a quota exceeded error\n */\nfunction isQuotaExceededError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Most browsers\n if (error.name === 'QuotaExceededError') return true;\n // Firefox\n if (error.name === 'NS_ERROR_DOM_QUOTA_REACHED') return true;\n }\n return false;\n}\n\n/**\n * Check if an error indicates storage is unavailable (private browsing, etc.)\n */\nfunction isStorageUnavailableError(error: unknown): boolean {\n if (error instanceof DOMException) {\n // Safari private browsing, some security restrictions\n if (error.name === 'SecurityError') return true;\n // Some browsers throw this in private mode\n if (error.name === 'InvalidStateError') return true;\n }\n return false;\n}\n\nexport type EffectStorageEvent = CacheStorageEvent | StorageEvent;\n\n/**\n * A reactive wrapper around the Web Storage API (localStorage/sessionStorage)\n * that provides signal-based access to storage items and length.\n *\n * Will automatically update when storage events occur in other tabs/windows.\n */\nclass ReactiveStorage implements Storage {\n private _storage: Storage;\n private _options: ReactiveStorageOptions;\n private _memoryOnly = false;\n private _values: Record<string, string | null> = {};\n\n declare private _signals: SignalMap<string>;\n declare private _length: number;\n\n private _effects = new Map<string, (value: EffectStorageEvent) => void>();\n setEffect(key: string, fn: (value: EffectStorageEvent) => void): void {\n assert(`Can only set effect once for key: ${key}`, !this._effects.has(key));\n this._effects.set(key, fn);\n }\n\n constructor(storage: Storage, options: ReactiveStorageOptions = {}) {\n this._storage = storage;\n this._options = options;\n\n if (!(storage instanceof CacheStorage)) {\n // Test if storage is accessible\n try {\n const testKey = '__storage_test__';\n storage.setItem(testKey, testKey);\n storage.removeItem(testKey);\n this._length = storage.length;\n } catch (error) {\n if (options.fallbackToMemory && isStorageUnavailableError(error)) {\n this._memoryOnly = true;\n this._length = 0;\n } else {\n throw error;\n }\n }\n }\n\n // bind to localStorage events to trigger reactivity\n if (!this._memoryOnly) {\n window.addEventListener('storage', ((event: StorageEvent | CustomEvent<CacheStorageEvent>) => {\n const data = 'detail' in event ? event.detail : event;\n\n // Only react to changes in the same storage area\n if (data.storageArea === storage) {\n this._values[data.key as string] = data.newValue;\n this._signals.notify(data.key as string);\n this._length = this._storage.length;\n const effect = this._effects.get(data.key as string);\n if (effect) {\n effect(data);\n }\n }\n }) as EventListener);\n }\n }\n\n /**\n * Reactive access to the number of keys in Storage\n */\n get length(): number {\n return this._length;\n }\n\n /**\n * Non-reactive way to peek the current value of a key in Storage\n */\n peekItem(key: string): string | null {\n assert('ReactiveStorage.peekItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n return value;\n }\n\n // Not yet loaded, fetch from storage, but don't track access\n const item = this._storage.getItem(keyStr);\n // this._values[keyStr] = item;\n return item;\n }\n\n /**\n * Reactive access to Storage contents\n */\n getItem(key: string): string | null {\n assert('ReactiveStorage.getItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n this._signals.subscribe(keyStr);\n return this._values[keyStr] ?? null;\n }\n\n const value = this._values[keyStr];\n if (value !== undefined) {\n this._signals.subscribe(keyStr);\n return value;\n }\n\n // Not yet loaded, fetch from storage\n const item = this._storage.getItem(keyStr);\n this._values[keyStr] = item;\n this._signals.subscribe(keyStr);\n return item;\n }\n\n /**\n * Set a value in Storage, triggering reactivity\n */\n setItem(key: string, value: string): void {\n assert('ReactiveStorage.setItem: key must be a string', typeof key === 'string');\n assert('ReactiveStorage.setItem: value must be a string', typeof value === 'string');\n\n // Coerce to strings to match Storage API behavior\n const keyStr = String(key);\n const valueStr = String(value);\n const current = this._values[keyStr];\n if (current === valueStr) {\n // No change\n return;\n }\n\n // console.trace(`set field ${key} => ${String(value)}`);\n\n if (this._memoryOnly) {\n const currentValue = this._values[keyStr];\n if (currentValue === null || currentValue === undefined) {\n this._length += 1;\n }\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n return;\n }\n\n try {\n this._storage.setItem(keyStr, valueStr);\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n } catch (error) {\n if (isQuotaExceededError(error)) {\n if (this._options.updateOnQuotaExceeded) {\n // Update signal state even though write failed\n this._values[keyStr] = valueStr;\n this._signals.notify(keyStr);\n }\n\n if (this._options.onQuotaExceeded) {\n const result = this._options.onQuotaExceeded(keyStr, valueStr);\n const retry = result instanceof Promise ? false : result;\n\n if (retry) {\n // Retry the write after callback freed space\n this._storage.setItem(keyStr, valueStr);\n this._length = this._storage.length;\n }\n } else {\n throw error;\n }\n } else {\n throw error;\n }\n }\n }\n\n /**\n * Remove a value from Storage, triggering reactivity\n */\n removeItem(key: string): void {\n assert('ReactiveStorage.removeItem: key must be a string', typeof key === 'string');\n const keyStr = String(key);\n\n if (this._memoryOnly) {\n const value = this._values[keyStr];\n if (value !== null && value !== undefined) {\n this._length -= 1;\n }\n this._values[keyStr] = null;\n return;\n }\n\n this._storage.removeItem(keyStr);\n this._values[keyStr] = null;\n this._signals.notify(keyStr);\n this._length = this._storage.length;\n }\n\n /**\n * Clears all keys from Storage, triggering reactivity\n */\n clear(): void {\n this._values = {};\n this._signals.clear();\n this._length = 0;\n\n if (this._memoryOnly) {\n return;\n }\n\n this._storage.clear();\n }\n\n /**\n * Reactive access to the key at the given index\n */\n key(index: number): string | null {\n assert('ReactiveStorage.key: index must be a number', typeof index === 'number');\n // oxlint-disable-next-line no-unused-expressions\n this._length; // track length access\n\n if (this._memoryOnly) {\n const keys = Object.keys(this._values).filter((k) => this._values[k] !== null);\n return keys[index] ?? null;\n }\n\n return this._storage.key(index);\n }\n}\ndefineSignal(ReactiveStorage.prototype, '_length', 0);\ndefineSignal(\n ReactiveStorage.prototype,\n '_signals',\n makeInitializer(() => new SignalMap<string>())\n);\n\nexport type { ReactiveStorage };\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { memoized } from '@warp-drive-mirror/core/signals/-leaked';\n\nimport { type EffectStorageEvent, getCacheStorage, getLocalStorage, getSessionStorage } from '../storage.ts';\n\n/**\n * Configuration options for fields that are also query parameters\n */\nexport interface ParamConfig {\n /**\n * Convert a value into a string for storage in the URL.\n * `null` indicates the value should be omitted from the URL.\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n serialize: (value: unknown, instance: any) => string | null;\n /**\n * Convert a string value from the URL back into\n * its original type\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n deserialize: (urlValue: string, instance: any) => unknown;\n /**\n * Get the default value for this param from the given instance.\n *\n * If not present, the value passed to the field initializer\n * will be used as the default.\n *\n * This should return the value in the field's native type,\n * not the serialized URL form.\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n getDefault?: (instance: any) => unknown;\n}\n\ninterface InternalParamConfig extends ParamConfig {\n initialized?: boolean;\n}\n\nexport interface ValueTransition<T = unknown> {\n key: string;\n from: T;\n to: T;\n}\n\n/**\n * Metadata attached to persisted resource classes\n */\nexport interface StorageResourceMeta {\n id: string;\n namespace: string | null;\n pkFn: KeyFn | null;\n type: 'local-resource' | 'session-resource' | 'cache-resource';\n typeOverrides: Map<string, 'local-storage' | 'session-storage' | 'cache-storage'> | null;\n fields: Map<string, null | ((update: ValueTransition<string>) => void)>;\n initializers: Map<string, (() => unknown) | null>;\n paramConfigs: Map<string, InternalParamConfig> | null;\n paramCompanion: object | null;\n instances: WeakMap<object, StorageResourceMeta> | null;\n}\n\n/**\n * A function which generates a unique primary-key\n * string for a given LocalResource or SessionResource\n * instance.\n *\n * Use functions when you want to create more than\n * one instance of a resource type, each with its own\n * persisted data.\n */\n// oxlint-disable-next-line typescript/no-explicit-any\nexport type KeyFn = (obj: any) => string;\n\n/**\n * Symbol used to store persistence metadata on classes\n */\nconst PERSISTED_RESOURCE_META = Symbol('StorageResourceMeta');\n\n/**\n * Setup persisted resource metadata on target\n * if not already present\n *\n * @private\n */\nexport function initMeta(target: object): StorageResourceMeta {\n let meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n if (!meta) {\n meta = {\n id: '',\n namespace: null,\n pkFn: null,\n type: '' as 'local-resource' | 'session-resource',\n fields: new Map(),\n initializers: new Map(),\n paramConfigs: null,\n paramCompanion: null,\n instances: null,\n typeOverrides: null,\n };\n (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META] = meta;\n }\n return meta;\n}\n\nexport function useMeta(meta: StorageResourceMeta, instance: object): StorageResourceMeta {\n // If a primary key function is defined, use it to generate\n // a unique ID for this instance\n if (meta.id === '' && meta.pkFn) {\n // we are in an instance context\n meta.instances = meta.instances ?? new WeakMap();\n let instanceMeta = meta.instances.get(instance);\n if (!instanceMeta) {\n instanceMeta = { ...meta };\n const pk = meta.pkFn(instance);\n assert('Primary key function must return a non-empty string.', typeof pk === 'string' && pk.length > 0);\n instanceMeta.id = pk;\n meta.instances.set(instance, instanceMeta);\n }\n return instanceMeta;\n }\n\n assert('StorageResourceMeta must have a valid id.', typeof meta.id === 'string' && meta.id.length > 0);\n return meta;\n}\n\n/**\n * Load storage field\n */\nexport function getField(\n instance: object,\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): Record<string, unknown> | null {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.getItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n } else {\n // No stored value, check for initializer\n const initializer = meta.initializers.get(key);\n if (initializer) {\n const value = initializer.call(instance);\n if (value !== undefined) {\n return value as Record<string, unknown>;\n }\n }\n }\n return null;\n}\n\nfunction keyFor(meta: StorageResourceMeta, key: string): string {\n return `persisted:${meta.id}:${key}`;\n}\n\nfunction getStorage(type: string, namespace: string | null) {\n if (type === 'local-resource') {\n return getLocalStorage();\n } else if (type === 'session-resource') {\n return getSessionStorage();\n } else {\n return getCacheStorage(namespace);\n }\n}\n\nexport function peekField(\n meta: StorageResourceMeta,\n key: string,\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): unknown {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n const stored = storage.peekItem(keyFor(meta, key));\n\n if (stored) {\n return JSON.parse(stored) as Record<string, unknown>;\n }\n return null;\n}\n\nexport function initializeFields(instance: object, source: object): void {\n // we need to initialize the fields without reading from their reactive state\n // we also only want to initialize the field if it is still at its default value\n // as otherwise we are likely overwriting a persisted value or url value\n const baseMeta = getResourceMeta(instance);\n const meta = useMeta(baseMeta, instance);\n\n for (const [key] of meta.fields.entries()) {\n if (key in source) {\n // get the new value from source\n const newValue = (source as Record<string, unknown>)[key];\n\n // get the current default value from the field initializer\n const initializer = meta.initializers.get(key);\n let defaultValue: unknown = null;\n if (initializer) {\n defaultValue = initializer.call(instance);\n }\n\n // get the overrideType\n const overrideType = meta.typeOverrides?.get(key) ?? null;\n const type = overrideType || meta.type;\n\n // get the current stored value, without triggering reactivity\n const currentValue = peekField(meta, keyFor(meta, key), overrideType);\n\n // if there is no current value, silently update the field\n const storage = type === 'local-resource' ? localStorage : sessionStorage;\n storage.setItem(keyFor(meta, key), JSON.stringify(newValue));\n // only initialize if current value matches default value\n // or we have no persisted value yet.\n if (currentValue === defaultValue) {\n setField(meta, keyFor(meta, key), newValue as string, overrideType);\n }\n }\n }\n}\n\n/**\n * Update storage field\n */\nexport function setField(\n meta: StorageResourceMeta,\n key: string,\n value: string | boolean | null | number | Record<string, unknown> | unknown[],\n overrideType: 'local-storage' | 'session-storage' | 'cache-storage' | null\n): void {\n const type = overrideType || meta.type;\n const storage = getStorage(type, meta.namespace);\n storage.setItem(keyFor(meta, key), JSON.stringify(value));\n}\n\nfunction getResourceMeta(target: object): StorageResourceMeta {\n const meta = (target as Record<symbol, StorageResourceMeta>)[PERSISTED_RESOURCE_META];\n assert(\n 'StorageResourceMeta not found on target. Did you forget to use the @LocalResource() or @SessionResource() decorator?',\n meta !== undefined\n );\n return meta;\n}\n\nexport function _createStorageResource(\n id: string | KeyFn,\n type: 'local-resource' | 'session-resource' | 'cache-resource',\n namespace: string | null\n): ClassDecorator {\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n return function (target: Function) {\n // oxlint-disable-next-line typescript/no-unsafe-argument\n const meta = getResourceMeta(target.prototype);\n meta.id = typeof id === 'string' ? id : '';\n meta.pkFn = typeof id === 'function' ? id : null;\n meta.type = type;\n meta.namespace = namespace;\n if (meta.pkFn !== null) {\n // for dynamic instances, we install effects only once\n // fields have been defined and a key created for the\n // instance.\n // for this, we defer effect installation until\n // until object instantiation by wrapping the constructor\n // oxlint-disable-next-line typescript/no-unsafe-assignment, typescript/no-unsafe-member-access\n const originalConstructor = target.prototype.constructor;\n // oxlint-disable-next-line typescript/no-unsafe-member-access\n target.prototype.constructor = function DynamicStorageInitializer(...args: unknown[]) {\n /* oxlint-disable new-cap, typescript/no-unsafe-call */\n const instance = new originalConstructor(...args) as object;\n /* oxlint-enable new-cap, typescript/no-unsafe-call */\n void installEffectsForDynamicInstance(meta, instance);\n return instance;\n };\n }\n\n if (!('toJSON' in target.prototype)) {\n // oxlint-disable-next-line typescript/no-unsafe-member-access\n target.prototype.toJSON = function (this: object) {\n const instanceMeta = useMeta(meta, this);\n // we only serialize the id and any localStorage fields, not sessionStorage fields.\n const isLocalResource = meta.type === 'local-resource' || meta.type === 'cache-resource';\n const fields = isLocalResource ? new Set(meta.fields.keys()) : new Set<string>();\n for (const [key, overrideType] of meta.typeOverrides?.entries() ?? []) {\n if (overrideType === 'local-storage') {\n fields.add(key);\n } else if (overrideType === 'session-storage' && isLocalResource) {\n fields.delete(key);\n }\n }\n let idKey = '$key';\n while (fields.has(idKey)) {\n idKey = `_${idKey}`;\n }\n const data: Record<string, unknown> = {\n [idKey]: instanceMeta.id,\n };\n\n for (const key of fields) {\n const value = getField(this, instanceMeta, key, meta.typeOverrides?.get(key) ?? null);\n if (value !== null) {\n data[key] = value;\n }\n }\n\n return data;\n };\n }\n };\n}\n\nasync function installEffectsForDynamicInstance(meta: StorageResourceMeta, instance: object): Promise<void> {\n await Promise.resolve();\n for (const [key, value] of meta.fields.entries()) {\n if (typeof value === 'function') {\n void installEffect(useMeta(meta, instance), key);\n }\n }\n}\n\n/**\n * Returns the descriptor but is cast\n * to void to satisfy Typescript's incorrect\n * typing for legacy decorators.\n */\nexport function setupField(\n target: object,\n key: string,\n orgDesc?: PropertyDescriptor,\n type?: 'local' | 'session' | 'cache'\n): void {\n const meta = initMeta(target);\n meta.fields.set(key, null);\n const overrideType =\n type === 'local'\n ? 'local-storage'\n : type === 'session'\n ? 'session-storage'\n : type === 'cache'\n ? 'cache-storage'\n : null;\n if (overrideType) {\n meta.typeOverrides = meta.typeOverrides || new Map<string, 'local-storage' | 'session-storage' | 'cache-storage'>();\n meta.typeOverrides.set(key, overrideType);\n }\n // @ts-expect-error initializer does exist\n const initializer = (orgDesc?.initializer || null) as (() => unknown) | null;\n meta.initializers.set(key, initializer);\n\n const desc = {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n };\n\n return memoized(target as Record<string, unknown>, key, desc) as unknown as void;\n}\n\nexport async function installEffect(meta: StorageResourceMeta, key: string): Promise<void> {\n await Promise.resolve();\n const effect = meta.fields.get(key) as <K>(v: ValueTransition<K>) => void;\n const storage = getStorage(meta.type, meta.namespace);\n storage.setEffect(keyFor(meta, key), (event: EffectStorageEvent) => {\n const oldValue = event.oldValue ? (JSON.parse(event.oldValue) as unknown) : null;\n const newValue = event.newValue ? (JSON.parse(event.newValue) as unknown) : null;\n effect({ key, from: oldValue, to: newValue });\n });\n}\n\n/**\n * Get or create the param companion object for a StorageResource instance.\n *\n * The companion object contains URL-serialized versions of all @param decorated fields.\n * Each param field gets a corresponding property on the companion that:\n * - Reads: Serializes the storage value to a URL string (returns null if not active)\n * - Writes: Deserializes the URL string and updates the storage value\n *\n * The companion object is reactive using trackedObject, ensuring that changes\n * to the underlying storage fields trigger updates in the query param system.\n *\n * This companion object is what QPRoute will bind to for URL query params.\n *\n * @private\n * @param instance - The StorageResource instance\n * @param groupControlMap - Optional map of fieldName -> controlFieldName for grouped params\n * @returns The companion object with serialized param properties\n */\nexport function getParamCompanion(instance: object, groupControlMap?: Record<string, string>): object {\n const meta = getResourceMeta(instance);\n const instanceMeta = useMeta(meta, instance);\n\n // Return existing companion if already created\n if (instanceMeta.paramCompanion) {\n return instanceMeta.paramCompanion;\n }\n\n // Create new companion object\n const companion = {};\n instanceMeta.paramCompanion = companion;\n\n // Install a property for each param\n const paramConfigs = instanceMeta.paramConfigs;\n if (!paramConfigs || paramConfigs.size === 0) {\n return companion;\n }\n\n for (const [fieldName, config] of paramConfigs.entries()) {\n const controlFieldName = groupControlMap?.[fieldName];\n\n createParamField(companion, fieldName, config, controlFieldName, instance, meta);\n }\n\n return companion;\n}\n\nfunction isActiveGroupParam(companion: object, controlFieldName: string): boolean {\n // if the url value for the control param is `null` we are inactive\n const controlValue = (companion as Record<string, unknown>)[controlFieldName];\n return controlValue !== null;\n}\n\n/**\n * The default value of a param is determined by:\n * - the getDefault() function if provided, and its return is not undefined\n * - the initializer value provided to the field, if not undefined\n * - null otherwise\n *\n * The value is the deserialized form (i.e., the local storage value type)\n */\nfunction getParamFieldDefaultValue(\n meta: StorageResourceMeta,\n config: ParamConfig,\n fieldName: string,\n instance: object\n) {\n const defaultValue = config.getDefault?.(instance);\n if (defaultValue !== undefined) {\n return defaultValue;\n }\n\n const initializer = meta.initializers.get(fieldName);\n if (initializer) {\n const initValue = initializer.call(instance);\n\n if (initValue !== undefined) {\n return initValue;\n }\n }\n\n return null;\n}\n\nfunction createParamField(\n companion: object,\n fieldName: string,\n config: InternalParamConfig,\n controlFieldName: string | undefined,\n instance: object,\n meta: StorageResourceMeta\n): void {\n const desc = {\n configurable: true,\n enumerable: true,\n get(): string | null {\n // Mark as initialized on first access, but continue with normal logic\n if (!config.initialized) {\n config.initialized = true;\n return null;\n }\n\n // Next, check if this param is part of a group and if its control param is active\n // If not active, return null to indicate inactive state\n if (controlFieldName && !isActiveGroupParam(companion, controlFieldName)) {\n return null;\n }\n\n // Next, check if the currently stored value is the default\n // value. If so, return null to indicate inactive state\n const defaultValue = getParamFieldDefaultValue(meta, config, fieldName, instance);\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n if (rawValue === defaultValue) {\n return null;\n }\n\n // Serialize to URL format\n const serialized = config.serialize(rawValue, instance);\n\n // Return null if serialization returns empty, indicating no URL representation\n if (!serialized) {\n return null;\n }\n\n return serialized;\n },\n set(urlValue: string | null) {\n /**\n * set will never come from anything except URL deserialization.\n * which is managed by Ember.\n *\n * Our job is to not unnecessarily update the storage resource\n * so we need to run the compare function to see if the\n * incoming URL value is different from the existing local value.\n */\n\n // If null or empty, skip deserialization\n if (!urlValue) {\n return;\n }\n\n const rawValue = (instance as Record<string, unknown>)[fieldName];\n\n // Compare incoming URL value with existing local value\n const rawValueSerialized = config.serialize(rawValue, instance);\n if (rawValueSerialized === urlValue) {\n // No change\n return;\n }\n\n // Deserialize from URL format\n const newRawValue = config.deserialize(urlValue, instance);\n\n // Update the storage resource\n (instance as Record<string, unknown>)[fieldName] = newRawValue;\n },\n };\n\n memoized(companion as Record<string, unknown>, fieldName, desc);\n Object.defineProperty(companion, fieldName, desc);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\n\nimport {\n _createStorageResource,\n getField,\n initMeta,\n installEffect,\n type KeyFn,\n setField,\n setupField,\n useMeta,\n type ValueTransition,\n} from './-private/storage-infra.ts';\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in localStorage.\n *\n * LocalResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function LocalResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'local-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted in sessionStorage.\n *\n * SessionResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n */\nexport function SessionResource(id: string | KeyFn): ClassDecorator {\n return _createStorageResource(id, 'session-resource', null);\n}\n\n/**\n * Decorator which transforms a class into a StorageResource\n * persisted via the [Cache API](https://developer.mozilla.org/en-US/docs/Web/API/Cache).\n * api and shared across all tabs/windows under the same origin.\n *\n * CacheResources must either be singletons or expect all instances\n * to share state unless a primary key function is provided.\n *\n * When a primary key function is provided, each instance\n * will have its own persisted data based on the key generated\n * by the function.\n *\n * The function will be called once per instance during\n * initialization to determine the unique ID for that instance.\n *\n * All object cached in the same `namespace` share the namespace's storage context,\n * so partitioning can be achieved by using different namespaces for different groups\n * of data.\n */\nexport function CacheResource(id: string | KeyFn, namespace: string | null = null): ClassDecorator {\n return _createStorageResource(id, 'cache-resource', namespace);\n}\n\n/**\n * Decorator which marks a property as a field on\n * a LocalResource or SessionResource\n *\n * The field's value will be initialized from the persisted resource data\n * if available, falling back to the property's default value otherwise.\n *\n * Fields can be of any type that is serializable to and restorable from JSON,\n * but complex types (like objects or arrays) should be handled with care to avoid\n * unintended mutations or reactivity issues.\n *\n * By default, fields are persisted in the storage type defined by the resource decorator\n * (@LocalResource or @SessionResource). However, you can override this behavior\n * by passing 'local' or 'session' as an argument to the decorator.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-settings')\n * class UserSettings {\n * @field\n * theme: 'light' | 'dark' = 'light';\n *\n * @field('session')\n * sessionToken: string | null = null;\n * }\n * ```\n *\n */\nexport function field(type: 'local' | 'session' | 'cache'): PropertyDecorator;\nexport function field(target: object, key: string, descriptor?: PropertyDescriptor): void;\nexport function field(...args: unknown[]): PropertyDecorator | void {\n if (args.length === 0) {\n assert('field decorator requires at least 1 argument or should be used without parens', true);\n return setupField as PropertyDecorator;\n }\n if (args.length === 1) {\n const type = args[0] as 'local' | 'session' | 'cache';\n return ((target: object, key: string, desc?: PropertyDescriptor) =>\n setupField(target, key, desc, type)) as PropertyDecorator;\n }\n if (args.length === 2 || args.length === 3) {\n const [target, key, descriptor] = args as [object, string, PropertyDescriptor | undefined];\n return setupField(target, key, descriptor);\n }\n}\nexport function input(type: 'number' | 'boolean' | 'float'): PropertyDecorator {\n assert('input decorator requires a valid type argument', ['number', 'boolean', 'float'].includes(type));\n return function (target: object, key: string, desc: PropertyDescriptor): void {\n // oxlint-disable-next-line typescript/unbound-method\n const originalSet = desc.set!;\n desc.set = function (this: object, value: unknown) {\n switch (type) {\n case 'number':\n value = Number(value);\n break;\n case 'boolean':\n value =\n value === 'false' ||\n value === '' ||\n value === '0' ||\n value === 'undefined' ||\n value === 'null' ||\n value === false ||\n value === 0 ||\n value === null ||\n value === undefined\n ? 0\n : 1;\n break;\n default:\n assert(`Unsupported input type: ${type}`);\n }\n originalSet.call(this, value);\n };\n return desc as unknown as void;\n } as PropertyDecorator;\n}\n\n/**\n * Effects are fields that run a side-effecting function.\n *\n * Effects are intended to enable synchronizing get states between\n * tabs or windows that result in needing to synchronize other\n * non-reactive state.\n *\n * For example, when a user selects a light/dark mode theme preference\n * that differs from the system preference, effects can be used to trigger\n * DOM updates on the documentElement necessary to ensure its state is\n * consistent with the persisted resource state and reactive application state.\n *\n * To do this without an effect would require either setting up your own\n * storage event listeners or consuming the reactive state of the property\n * in another effect-like API such as an Ember modifier or React useEffect,\n *\n * Effects *only* run when the stored value changes due to storage events\n * emitted from other tabs or windows. They do not run when the property\n * is updated in the same context.\n *\n * ---\n *\n * **Example:**\n *\n * ```ts\n * @LocalResource('user-preferences')\n * class UserPreferences {\n * @effect(syncThemeToDOM)\n * explicitThemePreference: 'light' | 'dark' | null = null;\n *\n * @matchMedia('(prefers-color-scheme: dark)')\n * systemPrefersDarkMode: boolean = false;\n * }\n *\n * function syncThemeToDOM(update: ValueTransition<'light' | 'dark' | null>): void {\n * const newTheme = update.to;\n * document.documentElement.style.colorScheme = newTheme ?? 'light dark';\n *\n * if (newTheme === 'dark') {\n * document.documentElement.classList.add('dark-theme');\n * document.documentElement.classList.remove('light-theme');\n * } else if (newTheme === 'light') {\n * document.documentElement.classList.add('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * } else {\n * document.documentElement.classList.remove('light-theme');\n * document.documentElement.classList.remove('dark-theme');\n * }\n * }\n * ```\n */\nexport function effect(fn: <K>(update: ValueTransition<K>) => void, type?: 'local' | 'session'): PropertyDecorator {\n const overrideType = type === 'local' ? 'local-storage' : type === 'session' ? 'session-storage' : null;\n return function effectField(\n target: object,\n key: string,\n\n _descriptor?: PropertyDescriptor\n ): void {\n const meta = initMeta(target);\n meta.fields.set(key, fn);\n\n // only install the effect if we are not in a primary-keyed instance context\n if (meta.pkFn === null) void installEffect(meta, key);\n\n return {\n configurable: true,\n enumerable: true,\n get(this: object): unknown {\n return getField(this, useMeta(meta, this), key, overrideType);\n },\n set(this: object, value: unknown) {\n setField(useMeta(meta, this), key, value as string, overrideType);\n },\n } as unknown as void;\n } as unknown as PropertyDecorator;\n}\n"],"mappings":";;;;;;;;AAcA,IAAaO,YAAb,MAAyC;CAC/BC,OAA0B,CAAC;CAG3BC,WAAwBL,gBAAgB,KAAKI,IAAI;CAEzDE,UAAUC,KAAiB;EACzBN,eAAAC,gBAAA,CAAA,CAAAM,UAAAC,IAAAC,KAAA,OAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOL,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMM,WAAW,KAAKR,SAASS,IAAIP,GAAG;EACtCV,eAAe,KAAKQ,UAAU,KAAKD,MAAMG,KAAKQ,MAAS;EACvD,MAAMC,OAAO,KAAKC;EAClB,KAAKA,QAAQJ,WAAWG,OAAOA,OAAO;EACtC,OAAOH;CACT;CAEAK,OAAOX,KAAc;EACnBN,eAAAC,gBAAA,CAAA,CAAAM,UAAAC,IAAAC,KAAA,OAAAC,SAAA;GAAA,IAAA,CAAAA,MAAA,MAAA,IAAAC,MAAO,yCAAyC,OAAOL,KAAK;EAAA,EAAA,CAAE,OAAOA,QAAQ,QAAQ;EACrF,MAAMY,SAASrB,0BAA0B,KAAKO,UAAU,KAAKD,MAAMG,KAAK,CAAC;EACzER,qBAAqBoB,MAAM;CAC7B;CAEAC,QAAc;EACZ,KAAK,MAAMC,SAAS,KAAKhB,SAASiB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AA;GAC5C;GACAO,YAAYK,KAAK,MAAMH,KAAK;EAC9B;EACA,OAAON;CACT;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,SAAgBU,OAAOC,IAA6Cd,MAA+C;CACjH,MAAMe,eAAef,SAAS,UAAU,kBAAkBA,SAAS,YAAY,oBAAoB;CACnG,OAAO,SAASgB,YACdf,QACAC,KAEAe,aACM;EACN,MAAMC,OAAOtC,SAASqB,MAAM;EAC5BiB,KAAKC,OAAOX,IAAIN,KAAKY,EAAE;EAGvB,IAAII,KAAKE,SAAS,MAAM,AAAKvC,cAAcqC,MAAMhB,GAAG;EAEpD,OAAO;GACLmB,cAAc;GACdC,YAAY;GACZC,MAA2B;IACzB,OAAO5C,SAAS,MAAMK,QAAQkC,MAAM,IAAI,GAAGhB,KAAKa,YAAY;GAC9D;GACAP,IAAkBC,OAAgB;IAChC3B,SAASE,QAAQkC,MAAM,IAAI,GAAGhB,KAAKO,OAAiBM,YAAY;GAClE;EACF;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-worker.js","names":["assertPrivateStore","SkipCache","calcShouldFetch","cloneError","isCacheAffecting","isMutation","CacheHandler","request","context","next","store","cacheOptions","identifier","cacheKeyManager","getOrCreateDocumentIdentifier","peeked","cache","peekRequest","worker","_worker","storage","getDocument","then","document","put","completeRequest","catch","e","console","log","fetchContentAndHydrate","test","Error","setResponse","response","maybeUpdateObjects","content","Array","isArray","data","map","peek","Object","assign","maybeUpdatePersistedCache","resourceDocument","putResources","resourceIdentifier","putDocument","updateCacheForSuccess","record","records","didCommit","lid","full","handleFetchSuccess","_join","lifetimes","didRequest","updateCacheForError","error","errors","undefined","commitWasRejected","handleFetchError","signal","aborted","newError","op","willCommit","willRequest"],"sources":["../../../src/data-worker/worker.ts","../../../src/data-worker/utils.ts","../../../src/data-worker/cache-handler.ts"],"sourcesContent":["import type { Store } from '@warp-drive-mirror/core';\nimport type { Future } from '@warp-drive-mirror/core/request';\nimport type { ResponseInfo, StructuredDataDocument } from '@warp-drive-mirror/core/types/request';\n\nimport { DocumentStorage } from '../document-storage';\nimport type { AbortEventData, RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nexport class DataWorker {\n declare store: Store;\n declare threads: Map<string, MessagePort>;\n declare pending: Map<string, Map<number, Future<unknown>>>;\n declare isSharedWorker: boolean;\n declare options: { persisted: boolean; scope?: string };\n declare storage: DocumentStorage;\n\n constructor(UserStore: typeof Store, options?: { persisted: boolean; scope?: string }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.store = new UserStore();\n this.threads = new Map();\n this.pending = new Map();\n this.options = Object.assign({ persisted: false, scope: '' }, options);\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n initialize(): void {\n // enable the CacheHandler to access the worker\n (this.store as unknown as { _worker: DataWorker })._worker = this;\n if (this.options.persisted) {\n // will be accessed by the worker's CacheHandler off of store\n this.storage = new DocumentStorage({ scope: this.options.scope });\n }\n if (this.isSharedWorker) {\n (globalThis as unknown as { onconnect: typeof globalThis.onmessage }).onconnect = (e) => {\n const port = e.ports[0];\n port.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, port);\n break;\n }\n };\n port.start();\n };\n } else {\n globalThis.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, event.ports[0]);\n break;\n }\n };\n }\n }\n\n setupThread(thread: string, port: MessagePort): void {\n this.threads.set(thread, port);\n this.pending.set(thread, new Map());\n port.onmessage = (event: WorkerThreadEvent) => {\n if (event.type === 'close') {\n this.threads.delete(thread);\n return;\n }\n\n const { type } = event.data;\n switch (type) {\n case 'abort':\n this.abortRequest(event.data);\n break;\n case 'request':\n void this.request(prepareRequest(event.data));\n break;\n }\n };\n }\n\n abortRequest(event: AbortEventData): void {\n const { thread, id } = event;\n const future = this.pending.get(thread)!.get(id);\n\n if (future) {\n future.abort();\n this.pending.get(thread)!.delete(id);\n }\n }\n\n async request(event: RequestEventData): Promise<void> {\n const { thread, id, data } = event;\n\n try {\n const future = this.store.request(data);\n this.pending.get(thread)!.set(id, future);\n\n const result = await future;\n\n this.threads.get(thread)?.postMessage({ type: 'success-response', id, thread, data: prepareResponse(result) });\n } catch (error) {\n if (isAbortError(error)) return;\n\n this.threads.get(thread)?.postMessage({ type: 'error-response', id, thread, data: error });\n } finally {\n this.pending.get(thread)!.delete(id);\n }\n }\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction softCloneResponse(response: Response | ResponseInfo | null) {\n if (!response) return null;\n\n const clone: Partial<Mutable<Response>> = {};\n\n if (response.headers) {\n clone.headers = Array.from(response.headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n clone.ok = response.ok;\n clone.redirected = response.redirected;\n clone.status = response.status;\n clone.statusText = response.statusText;\n clone.type = response.type;\n clone.url = response.url;\n\n return clone;\n}\n\nfunction isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n\nfunction prepareResponse<T>(result: StructuredDataDocument<T>) {\n const newResponse = {\n response: softCloneResponse(result.response),\n content: result.content,\n };\n\n return newResponse;\n}\n\nfunction prepareRequest(event: RequestEventData) {\n if (event.data.headers) {\n event.data.headers = new Headers(event.data.headers);\n }\n\n return event;\n}\n","import type { Store } from '@warp-drive-mirror/core';\nimport type { RequestKey } from '@warp-drive-mirror/core/types/identifier';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '@warp-drive-mirror/core/types/request';\nimport type { ApiError } from '@warp-drive-mirror/core/types/spec/error';\n\nexport const MUTATION_OPS: Set<string> = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\n/**\n * In a Worker, any time we are asked to make a request, data needs to be returned.\n * background requests are ergo no different than foreground requests.\n * @internal\n */\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n cacheOptions?.backgroundReload ||\n !hasCachedValue ||\n (store.lifetimes && identifier\n ? store.lifetimes.isHardExpired(identifier, store) || store.lifetimes.isSoftExpired(identifier, store)\n : false)\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nfunction isAggregateError(error: Error & { errors?: ApiError[] }): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\ntype RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError): RobustError {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n","import type { Store, StoreRequestContext } from '@warp-drive-mirror/core';\nimport { DEBUG } from '@warp-drive-mirror/core/build-config/env';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { CacheHandler as CacheHandlerType, Future, NextFn } from '@warp-drive-mirror/core/request';\nimport { assertPrivateStore } from '@warp-drive-mirror/core/store/-private';\nimport type { RequestKey } from '@warp-drive-mirror/core/types/identifier';\nimport type {\n StructuredDataDocument,\n StructuredDocument,\n StructuredErrorDocument,\n} from '@warp-drive-mirror/core/types/request';\nimport { SkipCache } from '@warp-drive-mirror/core/types/request';\nimport type {\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n} from '@warp-drive-mirror/core/types/spec/document';\nimport type { ApiError } from '@warp-drive-mirror/core/types/spec/error';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\nimport { calcShouldFetch, cloneError, isCacheAffecting, isMutation } from './utils';\nimport type { DataWorker } from './worker';\n\n/**\n * A simplified CacheHandler that hydrates ResourceDataDocuments from the cache\n * with their referenced resources.\n *\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(context: StoreRequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(context.request);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n if (identifier && !peeked) {\n // if we are using persisted cache, we should attempt to populate the in-memory cache now\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n if (worker?.storage) {\n return worker.storage\n .getDocument(identifier)\n .then((document) => {\n if (document) {\n store.cache.put(document);\n }\n return completeRequest(identifier, store, context, next);\n })\n .catch((e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('Unable to retrieve document from persisted storage', e);\n }\n return completeRequest(identifier, store, context, next);\n });\n }\n }\n\n return completeRequest(identifier, store, context, next);\n },\n};\n\nfunction completeRequest<T>(\n identifier: RequestKey | null,\n store: Store,\n context: StoreRequestContext,\n next: NextFn<T>\n) {\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n // In a Worker, any time we are asked to make a request, data needs to be returned.\n // background requests are ergo no different than foreground requests.\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n return fetchContentAndHydrate(next, context, identifier);\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n throw peeked;\n }\n\n return maybeUpdateObjects<T>(store, peeked.content as ResourceDataDocument);\n}\n\nfunction maybeUpdateObjects<T>(store: Store, document: ResourceDataDocument | null): T {\n if (!document) {\n return document as T;\n }\n\n if (Array.isArray(document.data)) {\n const data = document.data.map((identifier) => {\n return store.cache.peek(identifier);\n });\n\n return Object.assign({}, document, { data }) as T;\n } else {\n // @ts-expect-error FIXME investigate why document.data won't accept the signature\n const data = (document.data ? store.cache.peek(document.data) : null) as T;\n return Object.assign({}, document, { data }) as T;\n }\n}\n\nfunction maybeUpdatePersistedCache(\n store: Store,\n document: StructuredDocument<ResourceDocument> | null,\n resourceDocument?: ResourceDataDocument\n) {\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n\n if (!worker?.storage) {\n return;\n }\n\n if (!document && resourceDocument) {\n // we have resources to update but not a full request to cache\n void worker.storage.putResources(resourceDocument, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n } else if (document) {\n void worker.storage.putDocument(document, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n }\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n const record = request.data?.record || request.records?.[0];\n if (record) {\n // @ts-expect-error while this is valid, we should update the CacheHandler for transactional saves\n response = store.cache.didCommit(record, document) as ResourceDataDocument;\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n maybeUpdatePersistedCache(store, null, response);\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n\n if (response.lid) {\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(request);\n const full = store.cache.peekRequest(identifier!);\n maybeUpdatePersistedCache(store, full);\n }\n }\n return maybeUpdateObjects(store, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: RequestKey | null,\n document: StructuredDataDocument<T>\n): T {\n let response: ResourceDataDocument;\n assertPrivateStore(store);\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, document) as ResourceDataDocument;\n });\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, document.response, identifier, store);\n }\n\n return response! as T;\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n error: StructuredErrorDocument<T>\n) {\n if (isMutation(request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n const record = request.data?.record || request.records?.[0];\n\n store.cache.commitWasRejected(record, errors);\n } else {\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(request);\n if (identifier) {\n maybeUpdatePersistedCache(store, error as StructuredErrorDocument<ResourceErrorDocument>);\n }\n return store.cache.put(error) as ResourceErrorDocument;\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: RequestKey | null,\n error: StructuredErrorDocument<T>\n): never {\n if (request.signal?.aborted) {\n throw error;\n }\n assertPrivateStore(store);\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, request, error);\n });\n\n if (identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, error.response, identifier, store);\n }\n\n if (isMutation(request)) {\n throw error;\n }\n\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: RequestKey | null\n): Promise<T> {\n const { request } = context;\n const { store } = context.request;\n\n if (isMutation(request)) {\n // TODO should we handle multiple records in request.records by iteratively calling willCommit for each\n const record = request.data?.record || request.records?.[0];\n assert(`Expected to receive a list of records included in the ${request.op} request`, record);\n if (record) {\n store.cache.willCommit(record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(request, identifier, store);\n }\n\n return next(request).then(\n (document) => handleFetchSuccess(store, request, identifier, document),\n (error: StructuredErrorDocument<T>) => handleFetchError(store, request, identifier, error)\n );\n}\n"],"mappings":";;;;;AAOA,MAAM,cAAe,WAA2E;AAEhG,IAAa,aAAb,MAAwB;CAQtB,YAAY,WAAyB,SAAkD;EAErF,IAAI,OAAO,WAAW,aACpB;EAEF,KAAK,QAAQ,IAAI,UAAU;EAC3B,KAAK,0BAAU,IAAI,IAAI;EACvB,KAAK,0BAAU,IAAI,IAAI;EACvB,KAAK,UAAU,OAAO,OAAO;GAAE,WAAW;GAAO,OAAO;EAAG,GAAG,OAAO;EACrE,KAAK,iBAAiB,eAAe,sBAAsB;EAC3D,KAAK,WAAW;CAClB;CAEA,aAAmB;EAEjB,AAAC,KAAK,MAA6C,UAAU;EAC7D,IAAI,KAAK,QAAQ,WAEf,KAAK,UAAU,IAAI,gBAAgB,EAAE,OAAO,KAAK,QAAQ,MAAM,CAAC;EAElE,IAAI,KAAK,gBACP,AAAC,WAAqE,aAAa,MAAM;GACvF,MAAM,OAAO,EAAE,MAAM;GACrB,KAAK,aAAa,UAA6C;IAC7D,MAAM,EAAE,SAAS,MAAM;IAEvB,QAAQ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AK;CAGxD,OAAOD,KAAKF,OAAO,CAAC,CAACe,MAClBC,aAAagC,mBAAmB7C,OAAOH,SAASK,YAAYW,QAAQ,IACpEqC,UAAsCI,iBAAiBtD,OAAOH,SAASK,YAAYgD,KAAK,CAC3F;AACF"}
|
|
1
|
+
{"version":3,"file":"data-worker.js","names":["assertPrivateStore","SkipCache","calcShouldFetch","cloneError","isCacheAffecting","isMutation","CacheHandler","request","context","next","store","cacheOptions","identifier","cacheKeyManager","getOrCreateDocumentIdentifier","peeked","cache","peekRequest","worker","_worker","storage","getDocument","then","document","put","completeRequest","catch","e","console","log","fetchContentAndHydrate","test","Error","setResponse","response","maybeUpdateObjects","content","Array","isArray","data","map","peek","Object","assign","maybeUpdatePersistedCache","resourceDocument","putResources","resourceIdentifier","putDocument","updateCacheForSuccess","record","records","didCommit","lid","full","handleFetchSuccess","_join","lifetimes","didRequest","updateCacheForError","error","errors","undefined","commitWasRejected","handleFetchError","signal","aborted","newError","op","willCommit","willRequest"],"sources":["../../../src/data-worker/worker.ts","../../../src/data-worker/utils.ts","../../../src/data-worker/cache-handler.ts"],"sourcesContent":["import type { Store } from '@warp-drive-mirror/core';\nimport type { Future } from '@warp-drive-mirror/core/request';\nimport type { ResponseInfo, StructuredDataDocument } from '@warp-drive-mirror/core/types/request';\n\nimport { DocumentStorage } from '../document-storage';\nimport type { AbortEventData, RequestEventData, ThreadInitEventData, WorkerThreadEvent } from './types';\n\nconst WorkerScope = (globalThis as unknown as { SharedWorkerGlobalScope: FunctionConstructor }).SharedWorkerGlobalScope;\n\nexport class DataWorker {\n declare store: Store;\n declare threads: Map<string, MessagePort>;\n declare pending: Map<string, Map<number, Future<unknown>>>;\n declare isSharedWorker: boolean;\n declare options: { persisted: boolean; scope?: string };\n declare storage: DocumentStorage;\n\n constructor(UserStore: typeof Store, options?: { persisted: boolean; scope?: string }) {\n // disable if running on main thread\n if (typeof window !== 'undefined') {\n return;\n }\n this.store = new UserStore();\n this.threads = new Map();\n this.pending = new Map();\n this.options = Object.assign({ persisted: false, scope: '' }, options);\n this.isSharedWorker = WorkerScope && globalThis instanceof WorkerScope;\n this.initialize();\n }\n\n initialize(): void {\n // enable the CacheHandler to access the worker\n (this.store as unknown as { _worker: DataWorker })._worker = this;\n if (this.options.persisted) {\n // will be accessed by the worker's CacheHandler off of store\n this.storage = new DocumentStorage({ scope: this.options.scope });\n }\n if (this.isSharedWorker) {\n (globalThis as unknown as { onconnect: typeof globalThis.onmessage }).onconnect = (e) => {\n const port = e.ports[0];\n port.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, port);\n break;\n }\n };\n port.start();\n };\n } else {\n globalThis.onmessage = (event: MessageEvent<ThreadInitEventData>) => {\n const { type } = event.data;\n\n switch (type) {\n case 'connect':\n this.setupThread(event.data.thread, event.ports[0]);\n break;\n }\n };\n }\n }\n\n setupThread(thread: string, port: MessagePort): void {\n this.threads.set(thread, port);\n this.pending.set(thread, new Map());\n port.onmessage = (event: WorkerThreadEvent) => {\n if (event.type === 'close') {\n this.threads.delete(thread);\n return;\n }\n\n const { type } = event.data;\n switch (type) {\n case 'abort':\n this.abortRequest(event.data);\n break;\n case 'request':\n void this.request(prepareRequest(event.data));\n break;\n }\n };\n }\n\n abortRequest(event: AbortEventData): void {\n const { thread, id } = event;\n const future = this.pending.get(thread)!.get(id);\n\n if (future) {\n future.abort();\n this.pending.get(thread)!.delete(id);\n }\n }\n\n async request(event: RequestEventData): Promise<void> {\n const { thread, id, data } = event;\n\n try {\n const future = this.store.request(data);\n this.pending.get(thread)!.set(id, future);\n\n const result = await future;\n\n this.threads.get(thread)?.postMessage({ type: 'success-response', id, thread, data: prepareResponse(result) });\n } catch (error) {\n if (isAbortError(error)) return;\n\n this.threads.get(thread)?.postMessage({ type: 'error-response', id, thread, data: error });\n } finally {\n this.pending.get(thread)!.delete(id);\n }\n }\n}\n\ntype Mutable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction softCloneResponse(response: Response | ResponseInfo | null) {\n if (!response) return null;\n\n const clone: Partial<Mutable<Response>> = {};\n\n if (response.headers) {\n clone.headers = Array.from(response.headers as unknown as Iterable<[string, string][]>) as unknown as Headers;\n }\n\n clone.ok = response.ok;\n clone.redirected = response.redirected;\n clone.status = response.status;\n clone.statusText = response.statusText;\n clone.type = response.type;\n clone.url = response.url;\n\n return clone;\n}\n\nfunction isAbortError(error: unknown): error is Error {\n return error instanceof Error && error.name === 'AbortError';\n}\n\nfunction prepareResponse<T>(result: StructuredDataDocument<T>) {\n const newResponse = {\n response: softCloneResponse(result.response),\n content: result.content,\n };\n\n return newResponse;\n}\n\nfunction prepareRequest(event: RequestEventData) {\n if (event.data.headers) {\n event.data.headers = new Headers(event.data.headers);\n }\n\n return event;\n}\n","import type { Store } from '@warp-drive-mirror/core';\nimport type { RequestKey } from '@warp-drive-mirror/core/types/identifier';\nimport type {\n ImmutableCreateRequestOptions,\n ImmutableDeleteRequestOptions,\n ImmutableRequestInfo,\n ImmutableUpdateRequestOptions,\n StructuredDataDocument,\n} from '@warp-drive-mirror/core/types/request';\nimport type { ApiError } from '@warp-drive-mirror/core/types/spec/error';\n\nexport const MUTATION_OPS: Set<string> = new Set(['createRecord', 'updateRecord', 'deleteRecord']);\n\n/**\n * In a Worker, any time we are asked to make a request, data needs to be returned.\n * background requests are ergo no different than foreground requests.\n * @internal\n */\nexport function calcShouldFetch(\n store: Store,\n request: ImmutableRequestInfo,\n hasCachedValue: boolean,\n identifier: RequestKey | null\n): boolean {\n const { cacheOptions } = request;\n return (\n (request.op && MUTATION_OPS.has(request.op)) ||\n cacheOptions?.reload ||\n cacheOptions?.backgroundReload ||\n !hasCachedValue ||\n (store.lifetimes && identifier\n ? store.lifetimes.isHardExpired(identifier, store) || store.lifetimes.isSoftExpired(identifier, store)\n : false)\n );\n}\n\nexport function isMutation(\n request: Partial<ImmutableRequestInfo>\n): request is ImmutableUpdateRequestOptions | ImmutableCreateRequestOptions | ImmutableDeleteRequestOptions {\n return Boolean(request.op && MUTATION_OPS.has(request.op));\n}\n\nexport function isCacheAffecting<T>(document: StructuredDataDocument<T>): boolean {\n if (!isMutation(document.request)) {\n return true;\n }\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n\n if (document.request.op === 'createRecord' && document.response?.status === 201) {\n return document.content ? Object.keys(document.content).length > 0 : false;\n }\n\n return document.response?.status !== 204;\n}\n\nfunction isAggregateError(error: Error & { errors?: ApiError[] }): error is AggregateError & { errors: ApiError[] } {\n return error instanceof AggregateError || (error.name === 'AggregateError' && Array.isArray(error.errors));\n}\n\ntype RobustError = Error & { error: string | object; errors?: ApiError[]; content?: unknown };\n\n// TODO @runspired, consider if we should deep freeze errors (potentially only in debug) vs cloning them\nexport function cloneError(error: RobustError): RobustError {\n const isAggregate = isAggregateError(error);\n\n const cloned = (\n isAggregate ? new AggregateError(structuredClone(error.errors), error.message) : new Error(error.message)\n ) as RobustError;\n cloned.stack = error.stack!;\n cloned.error = error.error;\n\n // copy over enumerable properties\n Object.assign(cloned, error);\n\n return cloned;\n}\n","import type { Store, StoreRequestContext } from '@warp-drive-mirror/core';\nimport { DEBUG } from '@warp-drive-mirror/core/build-config/env';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { CacheHandler as CacheHandlerType, Future, NextFn } from '@warp-drive-mirror/core/request';\nimport { assertPrivateStore } from '@warp-drive-mirror/core/store/-private';\nimport type { RequestKey } from '@warp-drive-mirror/core/types/identifier';\nimport type {\n StructuredDataDocument,\n StructuredDocument,\n StructuredErrorDocument,\n} from '@warp-drive-mirror/core/types/request';\nimport { SkipCache } from '@warp-drive-mirror/core/types/request';\nimport type {\n ResourceDataDocument,\n ResourceDocument,\n ResourceErrorDocument,\n} from '@warp-drive-mirror/core/types/spec/document';\nimport type { ApiError } from '@warp-drive-mirror/core/types/spec/error';\nimport type { ExistingResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\nimport { calcShouldFetch, cloneError, isCacheAffecting, isMutation } from './utils';\nimport type { DataWorker } from './worker';\n\n/**\n * A simplified CacheHandler that hydrates ResourceDataDocuments from the cache\n * with their referenced resources.\n *\n */\nexport const CacheHandler: CacheHandlerType = {\n request<T>(context: StoreRequestContext, next: NextFn<T>): Promise<T | StructuredDataDocument<T>> | Future<T> | T {\n // if we have no cache or no cache-key skip cache handling\n if (!context.request.store || context.request.cacheOptions?.[SkipCache]) {\n return next(context.request);\n }\n\n const { store } = context.request;\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(context.request);\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n\n if (identifier && !peeked) {\n // if we are using persisted cache, we should attempt to populate the in-memory cache now\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n if (worker?.storage) {\n return worker.storage\n .getDocument(identifier)\n .then((document) => {\n if (document) {\n store.cache.put(document);\n }\n return completeRequest(identifier, store, context, next);\n })\n .catch((e) => {\n if (DEBUG) {\n // oxlint-disable-next-line no-console\n console.log('Unable to retrieve document from persisted storage', e);\n }\n return completeRequest(identifier, store, context, next);\n });\n }\n }\n\n return completeRequest(identifier, store, context, next);\n },\n};\n\nfunction completeRequest<T>(\n identifier: RequestKey | null,\n store: Store,\n context: StoreRequestContext,\n next: NextFn<T>\n) {\n const peeked = identifier ? store.cache.peekRequest(identifier) : null;\n // In a Worker, any time we are asked to make a request, data needs to be returned.\n // background requests are ergo no different than foreground requests.\n if (calcShouldFetch(store, context.request, !!peeked, identifier)) {\n return fetchContentAndHydrate(next, context, identifier);\n }\n\n assert(`Expected a peeked request to be present`, peeked);\n context.setResponse(peeked.response);\n\n if ('error' in peeked) {\n throw peeked;\n }\n\n return maybeUpdateObjects<T>(store, peeked.content as ResourceDataDocument);\n}\n\nfunction maybeUpdateObjects<T>(store: Store, document: ResourceDataDocument | null): T {\n if (!document) {\n return document as T;\n }\n\n if (Array.isArray(document.data)) {\n const data = document.data.map((identifier) => {\n return store.cache.peek(identifier);\n });\n\n return Object.assign({}, document, { data }) as T;\n } else {\n // @ts-expect-error FIXME investigate why document.data won't accept the signature\n const data = (document.data ? store.cache.peek(document.data) : null) as T;\n return Object.assign({}, document, { data }) as T;\n }\n}\n\nfunction maybeUpdatePersistedCache(\n store: Store,\n document: StructuredDocument<ResourceDocument> | null,\n resourceDocument?: ResourceDataDocument\n) {\n const worker = (store as unknown as { _worker: DataWorker })._worker;\n\n if (!worker?.storage) {\n return;\n }\n\n if (!document && resourceDocument) {\n // we have resources to update but not a full request to cache\n void worker.storage.putResources(resourceDocument, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n } else if (document) {\n void worker.storage.putDocument(document, (resourceIdentifier) => {\n return store.cache.peek(resourceIdentifier) as ExistingResourceObject;\n });\n }\n}\n\nfunction updateCacheForSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n document: StructuredDataDocument<T>\n) {\n let response: ResourceDataDocument | null = null;\n if (isMutation(request)) {\n const record = request.data?.record || request.records?.[0];\n if (record) {\n // @ts-expect-error while this is valid, we should update the CacheHandler for transactional saves\n response = store.cache.didCommit(record, document);\n\n // a mutation combined with a 204 has no cache impact when no known records were involved\n // a createRecord with a 201 with an empty response and no known records should similarly\n // have no cache impact\n } else if (isCacheAffecting(document)) {\n response = store.cache.put(document) as ResourceDataDocument;\n maybeUpdatePersistedCache(store, null, response);\n }\n } else {\n response = store.cache.put(document) as ResourceDataDocument;\n\n if (response.lid) {\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(request);\n const full = store.cache.peekRequest(identifier!);\n maybeUpdatePersistedCache(store, full);\n }\n }\n return maybeUpdateObjects(store, response);\n}\n\nfunction handleFetchSuccess<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: RequestKey | null,\n document: StructuredDataDocument<T>\n): T {\n let response: ResourceDataDocument;\n assertPrivateStore(store);\n store._join(() => {\n response = updateCacheForSuccess<T>(store, request, document) as ResourceDataDocument;\n });\n\n if (store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, document.response, identifier, store);\n }\n\n return response! as T;\n}\n\nfunction updateCacheForError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n error: StructuredErrorDocument<T>\n) {\n if (isMutation(request)) {\n // TODO similar to didCommit we should spec this to be similar to cache.put for handling full response\n // currently we let the response remain undefiend.\n const errors =\n error &&\n error.content &&\n typeof error.content === 'object' &&\n 'errors' in error.content &&\n Array.isArray(error.content.errors)\n ? (error.content.errors as ApiError[])\n : undefined;\n\n const record = request.data?.record || request.records?.[0];\n\n store.cache.commitWasRejected(record, errors);\n } else {\n const identifier = store.cacheKeyManager.getOrCreateDocumentIdentifier(request);\n if (identifier) {\n maybeUpdatePersistedCache(store, error as StructuredErrorDocument<ResourceErrorDocument>);\n }\n return store.cache.put(error) as ResourceErrorDocument;\n }\n}\n\nfunction handleFetchError<T>(\n store: Store,\n request: StoreRequestContext['request'],\n identifier: RequestKey | null,\n error: StructuredErrorDocument<T>\n): never {\n if (request.signal?.aborted) {\n throw error;\n }\n assertPrivateStore(store);\n let response: ResourceErrorDocument | undefined;\n store._join(() => {\n response = updateCacheForError(store, request, error);\n });\n\n if (identifier && store.lifetimes?.didRequest) {\n store.lifetimes.didRequest(request, error.response, identifier, store);\n }\n\n if (isMutation(request)) {\n throw error;\n }\n\n const newError = cloneError(error);\n newError.content = response!;\n throw newError;\n}\n\nfunction fetchContentAndHydrate<T>(\n next: NextFn<T>,\n context: StoreRequestContext,\n identifier: RequestKey | null\n): Promise<T> {\n const { request } = context;\n const { store } = context.request;\n\n if (isMutation(request)) {\n // TODO should we handle multiple records in request.records by iteratively calling willCommit for each\n const record = request.data?.record || request.records?.[0];\n assert(`Expected to receive a list of records included in the ${request.op} request`, record);\n if (record) {\n store.cache.willCommit(record, context);\n }\n }\n\n if (store.lifetimes?.willRequest) {\n store.lifetimes.willRequest(request, identifier, store);\n }\n\n return next(request).then(\n (document) => handleFetchSuccess(store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