tsdf 17.0.0-alpha.7 → 17.0.0-alpha.8
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/LICENSE +140 -0
- package/README.md +3 -0
- package/dist/async-storage.d.ts +2 -0
- package/dist/async-storage.js +1 -0
- package/dist/asyncStorageAdapter-CgG3vm0t.js +1 -0
- package/dist/asyncStorageAdapter-kvAIhrBD.d.ts +6 -0
- package/dist/asyncStorageAdapters-eagaD77Y.js +1 -0
- package/dist/indexed-db-storage.d.ts +12 -0
- package/dist/indexed-db-storage.js +1 -0
- package/dist/indexedDbPersistentStorage-JYXvMjTG.js +1 -0
- package/dist/main.d.ts +5 -1593
- package/dist/main.js +1 -18927
- package/dist/opfs-storage.d.ts +2 -0
- package/dist/opfs-storage.js +1 -0
- package/dist/opfsPersistentStorage-DS-SWDSq.js +1 -0
- package/dist/opfsPersistentStorage-D_fecOJg.d.ts +6 -0
- package/dist/types-DkNgE_f9.d.ts +1406 -0
- package/docs/persistent-storage.md +12 -6
- package/package.json +19 -5
|
@@ -0,0 +1,1406 @@
|
|
|
1
|
+
import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
|
|
2
|
+
import { Result } from "t-result";
|
|
3
|
+
import { RcType } from "runcheck";
|
|
4
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
5
|
+
|
|
6
|
+
//#region src/requestScheduler.d.ts
|
|
7
|
+
type RequestSchedulerEvents = 'scheduled-fetch-started' | 'rt-fetch-scheduled' | 'rt-fetch-cancelled' | 'scheduled-rt-fetch-started' | 'medium-priority-scheduled' | 'medium-priority-fetch-started' | 'medium-priority-cancelled' | 'batch-size-triggered';
|
|
8
|
+
type RequestSchedulerEventData = {
|
|
9
|
+
/** Delay in ms for scheduled events (medium-priority-scheduled, rt-fetch-scheduled) */delayMs?: number;
|
|
10
|
+
};
|
|
11
|
+
type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled' | 'triggered' | 'coalesced' | 'medium-scheduled' | 'added-to-batch' | 'batch-triggered';
|
|
12
|
+
type FetchType = 'lowPriority' | 'mediumPriority' | 'highPriority' | 'realtimeUpdate';
|
|
13
|
+
type ScheduleFetchOptions = {
|
|
14
|
+
mediumPriorityDelayMs?: number;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/utils/storeShared.d.ts
|
|
18
|
+
type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
|
|
19
|
+
type ValidPayload = number | string | Record<string, unknown>;
|
|
20
|
+
type ValidStoreState = Record<string, unknown> | unknown[];
|
|
21
|
+
/**
|
|
22
|
+
* Debounce settings for payload-driven automatic fetches in store hooks.
|
|
23
|
+
*
|
|
24
|
+
* The hook still reads data from state using the latest payload immediately.
|
|
25
|
+
* Only the automatic fetch side is delayed. Single hooks do not support
|
|
26
|
+
* combining this with `ensureIsLoaded`.
|
|
27
|
+
*/
|
|
28
|
+
type PayloadDebounce = {
|
|
29
|
+
/** Debounce window in milliseconds before the latest payload is fetched. */ms: number;
|
|
30
|
+
/**
|
|
31
|
+
* Maximum time a burst may stay deferred before the latest payload is
|
|
32
|
+
* fetched, even if changes keep happening within the debounce window.
|
|
33
|
+
*/
|
|
34
|
+
maxWait?: number;
|
|
35
|
+
/**
|
|
36
|
+
* When true, the first payload in a burst may fetch immediately, and later
|
|
37
|
+
* changes within the same burst stay debounced until the wait window ends.
|
|
38
|
+
*/
|
|
39
|
+
leading?: boolean;
|
|
40
|
+
};
|
|
41
|
+
type StoreError = {
|
|
42
|
+
code: number;
|
|
43
|
+
id: string;
|
|
44
|
+
message: string;
|
|
45
|
+
path?: string;
|
|
46
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
47
|
+
};
|
|
48
|
+
declare const fetchTypePriority: Record<FetchType, number>;
|
|
49
|
+
type MutationSkipped = {
|
|
50
|
+
kind: 'skipped';
|
|
51
|
+
};
|
|
52
|
+
declare const mutationSkipped: MutationSkipped;
|
|
53
|
+
/** Options passed to mutation error handlers. */
|
|
54
|
+
type StoreMutationErrorOptions = {
|
|
55
|
+
/**
|
|
56
|
+
* True when the mutation caller asked the shared error handler to stay quiet.
|
|
57
|
+
*
|
|
58
|
+
* Handlers are still called so apps can keep centralized logging, metrics, or
|
|
59
|
+
* custom recovery behavior while suppressing user-facing noise such as toast
|
|
60
|
+
* notifications.
|
|
61
|
+
*/
|
|
62
|
+
silentErrors?: boolean;
|
|
63
|
+
};
|
|
64
|
+
declare class StoreMutationError extends Error {
|
|
65
|
+
readonly kind = "error";
|
|
66
|
+
code: number;
|
|
67
|
+
id: string;
|
|
68
|
+
path?: string;
|
|
69
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
70
|
+
constructor(error: StoreError, options?: ErrorOptions);
|
|
71
|
+
}
|
|
72
|
+
declare class StoreFetchError extends Error {
|
|
73
|
+
code: number;
|
|
74
|
+
id: string;
|
|
75
|
+
type: 'fetch' | 'aborted' | 'timeout';
|
|
76
|
+
path?: string;
|
|
77
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
78
|
+
constructor(error: StoreError, type: 'fetch' | 'aborted' | 'timeout');
|
|
79
|
+
}
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region src/persistentStorage/offlineUploadTypes.d.ts
|
|
82
|
+
type OfflineUploadState = 'pending' | 'uploading' | 'uploaded' | 'failed';
|
|
83
|
+
type OfflineUploadSource = 'manual' | 'mutation';
|
|
84
|
+
type OfflineUploadProgress = {
|
|
85
|
+
progress: number;
|
|
86
|
+
loadedBytes?: number;
|
|
87
|
+
totalBytes?: number;
|
|
88
|
+
};
|
|
89
|
+
type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
90
|
+
id: string;
|
|
91
|
+
sessionKey: string;
|
|
92
|
+
source: OfflineUploadSource;
|
|
93
|
+
state: OfflineUploadState;
|
|
94
|
+
fileName: string;
|
|
95
|
+
mimeType: string;
|
|
96
|
+
sizeBytes: number;
|
|
97
|
+
createdAt: number;
|
|
98
|
+
updatedAt: number;
|
|
99
|
+
resolvedRef?: TResolvedRef;
|
|
100
|
+
progress?: OfflineUploadProgress;
|
|
101
|
+
lastError?: {
|
|
102
|
+
message: string;
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
|
|
106
|
+
file: File;
|
|
107
|
+
lastOnlineSessionStartedAt?: number;
|
|
108
|
+
lastModified: number;
|
|
109
|
+
};
|
|
110
|
+
type OfflineUploadAdapter = {
|
|
111
|
+
save<TResolvedRef extends ValidPayload>(sessionKey: string, id: string, record: OfflineStoredUploadRecord<TResolvedRef>): Promise<void>;
|
|
112
|
+
load<TResolvedRef extends ValidPayload>(sessionKey: string, id: string): Promise<OfflineStoredUploadRecord<TResolvedRef> | null>;
|
|
113
|
+
list<TResolvedRef extends ValidPayload>(sessionKey: string): Promise<OfflineStoredUploadRecord<TResolvedRef>[]>;
|
|
114
|
+
remove(sessionKey: string, id: string): Promise<void>;
|
|
115
|
+
clearSession(sessionKey: string): Promise<void>;
|
|
116
|
+
resetForTests?(): void;
|
|
117
|
+
};
|
|
118
|
+
type OfflineUploadTransportContext = {
|
|
119
|
+
id: string;
|
|
120
|
+
sessionKey: string;
|
|
121
|
+
file: File;
|
|
122
|
+
onProgress: (progress: OfflineUploadProgress) => void;
|
|
123
|
+
};
|
|
124
|
+
type OfflineSessionUploadsConfig<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
125
|
+
adapter: OfflineUploadAdapter;
|
|
126
|
+
upload: (ctx: OfflineUploadTransportContext) => Promise<TResolvedRef>;
|
|
127
|
+
concurrency?: number;
|
|
128
|
+
};
|
|
129
|
+
type OfflineMutationUploadsInput = Record<string, Blob | File>;
|
|
130
|
+
type OfflineAttachedUploadIds = Record<string, string>;
|
|
131
|
+
type OfflineOperationUploadsContext<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
132
|
+
filesById: Record<string, File>;
|
|
133
|
+
resolvedRefsById: Record<string, TResolvedRef>;
|
|
134
|
+
};
|
|
135
|
+
//#endregion
|
|
136
|
+
//#region src/persistentStorage/validateWithSchema.d.ts
|
|
137
|
+
type SchemaValidationError = readonly string[] | StandardSchemaV1.FailureResult['issues'];
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/persistentStorage/offline/types.d.ts
|
|
140
|
+
/** Store kinds supported by offline replay and sync state tracking. */
|
|
141
|
+
type OfflineStoreType = 'document' | 'collection' | 'listQuery';
|
|
142
|
+
/** Phase where a failure occurred during offline-enabled operation flow. */
|
|
143
|
+
type OfflineFailurePhase = 'fetch' | 'mutation' | 'sync';
|
|
144
|
+
/** High-level classification used by outage detection. */
|
|
145
|
+
type OfflineFailureClassification = 'outage' | 'network' | 'ignore';
|
|
146
|
+
/** Kinds of entities participating in offline conflict/sync tracking. */
|
|
147
|
+
type OfflineEntityKind = 'document' | 'item' | 'query';
|
|
148
|
+
/** Lifecycle declared per offline operation definition. */
|
|
149
|
+
type OfflineOperationKind = 'create' | 'update' | 'delete';
|
|
150
|
+
/** Effective lifecycle derived for an offline entity across queued work. */
|
|
151
|
+
type OfflineEntityMutationKind = 'create' | 'createAndUpdate' | 'update' | 'delete';
|
|
152
|
+
/** Connectivity cause currently governing offline mutation queueing. */
|
|
153
|
+
type OfflineMutationQueueingCause = 'network' | 'outage';
|
|
154
|
+
/** Root policy value for whether offline-enabled mutations may queue. */
|
|
155
|
+
type OfflineMutationQueueingPolicy = 'allow' | 'disallow';
|
|
156
|
+
/** Root mutation queueing policy shared by all configured offline operations. */
|
|
157
|
+
type OfflineMutationQueueingConfig = {
|
|
158
|
+
/**
|
|
159
|
+
* Controls whether offline-enabled mutations may queue while network mode is
|
|
160
|
+
* active, including browser-detected offline and classified network failures.
|
|
161
|
+
* @default 'allow'
|
|
162
|
+
*/
|
|
163
|
+
network?: OfflineMutationQueueingPolicy;
|
|
164
|
+
/**
|
|
165
|
+
* Controls whether offline-enabled mutations may queue while outage mode is
|
|
166
|
+
* active.
|
|
167
|
+
* @default 'allow'
|
|
168
|
+
*/
|
|
169
|
+
outage?: OfflineMutationQueueingPolicy;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Effective runtime offline controls exposed through an offline session.
|
|
173
|
+
*
|
|
174
|
+
* All fields are session-scoped and affect every store attached to the same
|
|
175
|
+
* offline session.
|
|
176
|
+
*/
|
|
177
|
+
type OfflineRuntimeConfig = {
|
|
178
|
+
/** Whether future operations may enter network offline handling. */network: {
|
|
179
|
+
enabled: boolean;
|
|
180
|
+
}; /** Whether future operations may enter outage offline handling. */
|
|
181
|
+
outage: {
|
|
182
|
+
enabled: boolean;
|
|
183
|
+
}; /** Effective queue admission policy for offline-enabled mutations. */
|
|
184
|
+
mutationQueueing: {
|
|
185
|
+
network: OfflineMutationQueueingPolicy;
|
|
186
|
+
outage: OfflineMutationQueueingPolicy;
|
|
187
|
+
};
|
|
188
|
+
};
|
|
189
|
+
/** Default runtime config when offline is not configured or no session exists. */
|
|
190
|
+
declare const defaultOfflineRuntimeConfig: OfflineRuntimeConfig;
|
|
191
|
+
/**
|
|
192
|
+
* Partial runtime offline control update accepted by an offline session.
|
|
193
|
+
*
|
|
194
|
+
* Provided fields shallow-merge into the current runtime config.
|
|
195
|
+
*/
|
|
196
|
+
type OfflineRuntimeConfigUpdate = {
|
|
197
|
+
/** Optional session-scoped update for network mode enablement. */network?: {
|
|
198
|
+
enabled?: boolean;
|
|
199
|
+
}; /** Optional session-scoped update for outage mode enablement. */
|
|
200
|
+
outage?: {
|
|
201
|
+
enabled?: boolean;
|
|
202
|
+
}; /** Optional session-scoped update for offline mutation queue admission policy. */
|
|
203
|
+
mutationQueueing?: {
|
|
204
|
+
network?: OfflineMutationQueueingPolicy;
|
|
205
|
+
outage?: OfflineMutationQueueingPolicy;
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
/** Context passed into offline failure classification hooks. */
|
|
209
|
+
type OfflineFailureContext = {
|
|
210
|
+
/** Phase in which the failure was detected. */phase: OfflineFailurePhase; /** Store type affected by the failure. */
|
|
211
|
+
storeType: OfflineStoreType; /** Optional operation name associated with the failure. */
|
|
212
|
+
operationName?: string; /** Session key used by browser tab and persistence scoping. */
|
|
213
|
+
sessionKey: string;
|
|
214
|
+
};
|
|
215
|
+
/** Re-check strategy for recovery probing. Omitted fields use built-in defaults (which differ between network and outage modes). */
|
|
216
|
+
type OfflineRecoveryProbeConfig = {
|
|
217
|
+
/**
|
|
218
|
+
* Initial recovery check delay, in milliseconds.
|
|
219
|
+
* @default 5_000 (network) / 30_000 (outage)
|
|
220
|
+
*/
|
|
221
|
+
initialIntervalMs?: number;
|
|
222
|
+
/**
|
|
223
|
+
* Maximum recovery check delay, in milliseconds.
|
|
224
|
+
* @default 60_000 (network) / 300_000 (outage)
|
|
225
|
+
*/
|
|
226
|
+
maxIntervalMs?: number;
|
|
227
|
+
/**
|
|
228
|
+
* Multiplicative backoff between recovery probes.
|
|
229
|
+
* @default 2
|
|
230
|
+
*/
|
|
231
|
+
backoffMultiplier?: number;
|
|
232
|
+
/**
|
|
233
|
+
* Jitter ratio (0-1) applied to the recovery probe delay.
|
|
234
|
+
* @default 0.2
|
|
235
|
+
*/
|
|
236
|
+
jitterRatio?: number;
|
|
237
|
+
};
|
|
238
|
+
/** Network availability mode configuration for offline controls. */
|
|
239
|
+
type OfflineNetworkModeConfig = {
|
|
240
|
+
/** Enable network connectivity detection and tracking. */enabled: boolean;
|
|
241
|
+
/**
|
|
242
|
+
* If true, subscribe to browser `online` / `offline` events.
|
|
243
|
+
* @default true
|
|
244
|
+
*/
|
|
245
|
+
listenToBrowserEvents?: boolean;
|
|
246
|
+
/**
|
|
247
|
+
* Optional override for network connectivity checks.
|
|
248
|
+
* Return `true` when network should be considered offline.
|
|
249
|
+
*/
|
|
250
|
+
getIsOffline?: () => boolean | Promise<boolean>;
|
|
251
|
+
/**
|
|
252
|
+
* Probe whether classified network recovery has completed.
|
|
253
|
+
* Return `true` when the session should leave network offline mode.
|
|
254
|
+
*/
|
|
255
|
+
recoveryCheck?: (ctx: {
|
|
256
|
+
sessionKey: string;
|
|
257
|
+
}) => Promise<boolean> | boolean; /** Optional probe config to tune classified network recovery behavior. */
|
|
258
|
+
recoveryProbe?: OfflineRecoveryProbeConfig;
|
|
259
|
+
};
|
|
260
|
+
/** Server outage detection and recovery configuration. */
|
|
261
|
+
type OfflineOutageModeConfig = {
|
|
262
|
+
/** Enable outage mode logic and confirmation retry flow. */enabled: boolean; /** Probe the remote service to confirm outage recovery. */
|
|
263
|
+
recoveryCheck: (ctx: {
|
|
264
|
+
sessionKey: string;
|
|
265
|
+
}) => Promise<boolean> | boolean; /** Optional probe config to tune recovery behavior. */
|
|
266
|
+
recoveryProbe?: OfflineRecoveryProbeConfig;
|
|
267
|
+
};
|
|
268
|
+
/** Fixed replay retry policy for healthy online replay failures. Omitted fields use built-in defaults. */
|
|
269
|
+
type OfflineReplayRetryConfig = {
|
|
270
|
+
/**
|
|
271
|
+
* Max counted failures before manual resolution is required.
|
|
272
|
+
* @default 3
|
|
273
|
+
*/
|
|
274
|
+
maxFailures?: number;
|
|
275
|
+
/**
|
|
276
|
+
* Fixed delay between replay retries, in milliseconds.
|
|
277
|
+
* @default 5000
|
|
278
|
+
*/
|
|
279
|
+
intervalMs?: number;
|
|
280
|
+
};
|
|
281
|
+
/** Shared offline/session policy reused by every store in the same session. */
|
|
282
|
+
type OfflineSessionConfig<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
283
|
+
/**
|
|
284
|
+
* Classify a remote failure as `outage`, `network`, or `ignore`.
|
|
285
|
+
* `outage` activates outage recovery behavior.
|
|
286
|
+
* `network` activates network offline handling for future operations only
|
|
287
|
+
* when `network.enabled` is true. Existing offline recovery may keep using
|
|
288
|
+
* classifications until already-active work finishes recovering.
|
|
289
|
+
*/
|
|
290
|
+
classifyFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<OfflineFailureClassification> | OfflineFailureClassification;
|
|
291
|
+
/**
|
|
292
|
+
* Optional replay-only classifier for ambiguous sync failures that stayed
|
|
293
|
+
* online (`classifyFailure(...) === 'ignore'`).
|
|
294
|
+
*
|
|
295
|
+
* Return `true` only when automatically re-sending the replayed mutation is
|
|
296
|
+
* known to be safe. Return `false` to avoid auto-replay retries; in that
|
|
297
|
+
* case the entry still enters `needs-confirmation` so `shouldSkipSync` /
|
|
298
|
+
* conflict checks can run before the mutation is promoted to manual
|
|
299
|
+
* resolution.
|
|
300
|
+
*/
|
|
301
|
+
classifyRetryableFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<boolean> | boolean; /** Network detection strategy and browser integration. */
|
|
302
|
+
network?: OfflineNetworkModeConfig; /** Outage detection and recovery strategy for remote failures. */
|
|
303
|
+
outage?: OfflineOutageModeConfig; /** Fixed retry policy for healthy online replay failures. */
|
|
304
|
+
replayRetry?: OfflineReplayRetryConfig;
|
|
305
|
+
/**
|
|
306
|
+
* Root policy controlling whether offline-enabled mutations may enter the
|
|
307
|
+
* durable offline queue for each active offline cause.
|
|
308
|
+
* @default undefined
|
|
309
|
+
*/
|
|
310
|
+
mutationQueueing?: OfflineMutationQueueingConfig; /** Optional upload transport/storage config shared by the whole session. */
|
|
311
|
+
uploads?: OfflineSessionUploadsConfig<TUploadRef>;
|
|
312
|
+
};
|
|
313
|
+
/** Per-session offline status snapshot shared across tabs. */
|
|
314
|
+
type GlobalOfflineStatus = {
|
|
315
|
+
/** Session key for this status bucket. */sessionKey: string;
|
|
316
|
+
/**
|
|
317
|
+
* Network mode admission enablement plus the last observed network-offline
|
|
318
|
+
* state for this session. `active` is preserved even while new admission is
|
|
319
|
+
* disabled so existing offline work can recover and sync safely.
|
|
320
|
+
*/
|
|
321
|
+
network: {
|
|
322
|
+
enabled: boolean;
|
|
323
|
+
active: boolean;
|
|
324
|
+
};
|
|
325
|
+
/**
|
|
326
|
+
* Outage mode admission enablement plus the last observed outage-active
|
|
327
|
+
* state for this session. `active` is preserved even while new admission is
|
|
328
|
+
* disabled so existing offline work can recover and sync safely.
|
|
329
|
+
*/
|
|
330
|
+
outage: {
|
|
331
|
+
enabled: boolean;
|
|
332
|
+
active: boolean;
|
|
333
|
+
}; /** Whether the session currently has any active offline cause. */
|
|
334
|
+
isOfflineMode: boolean; /** Whether this tab currently acts as leader for this session. */
|
|
335
|
+
isLeader: boolean; /** Timestamp when this status entry was last updated. */
|
|
336
|
+
updatedAt: number; /** Timestamp of the last failure, if any. */
|
|
337
|
+
lastFailureAt: number | null; /** Timestamp of last recovery probe execution, if any. */
|
|
338
|
+
lastRecoveryCheckAt: number | null;
|
|
339
|
+
};
|
|
340
|
+
/** Queue state of an offline mutation entry. */
|
|
341
|
+
type OfflineSyncState = 'pending' | 'syncing' | 'needs-confirmation';
|
|
342
|
+
/** Aggregated offline status for a tracked document/item/query entity. */
|
|
343
|
+
type GlobalOfflineEntity = {
|
|
344
|
+
/** Internal entity identifier tracked by offline machinery. */id: string; /** Session key for this offline entity. */
|
|
345
|
+
sessionKey: string; /** Store name where the entity is defined. */
|
|
346
|
+
storeName: string; /** Store type this entity belongs to. */
|
|
347
|
+
storeType: OfflineStoreType; /** Entity key used for deduping and conflict scoping. */
|
|
348
|
+
entityKey: string; /** Entity kind used in queue partitioning. */
|
|
349
|
+
entityKind: OfflineEntityKind; /** Effective lifecycle derived from queued operations targeting this entity. */
|
|
350
|
+
kind: OfflineEntityMutationKind; /** Number of pending mutations waiting for sync. */
|
|
351
|
+
pendingMutations: number; /** Current sync state for the entity. */
|
|
352
|
+
syncState: OfflineSyncState | 'resolution-required'; /** Whether the entity currently requires manual resolution. */
|
|
353
|
+
requiresResolution: boolean; /** Resolution ids currently blocking this entity from being resolved/applied. */
|
|
354
|
+
blockedByResolutionIds: string[]; /** Child resolution ids currently derived from this entity's dependency chain. */
|
|
355
|
+
childResolutionIds: string[]; /** Number of blocking parent resolutions currently affecting this entity. */
|
|
356
|
+
blockedResolutionCount: number; /** Number of child resolutions currently derived from this entity's dependency chain. */
|
|
357
|
+
childResolutionCount: number; /** Creation timestamp for lifecycle bookkeeping. */
|
|
358
|
+
createdAt: number; /** Last mutation/update timestamp. */
|
|
359
|
+
updatedAt: number; /** Optional temporary ID for optimistic create flows. */
|
|
360
|
+
tempId?: ValidPayload;
|
|
361
|
+
};
|
|
362
|
+
/** Reference to an entity participating in offline sync tracking. */
|
|
363
|
+
type OfflineEntityRef = {
|
|
364
|
+
entityKey: string;
|
|
365
|
+
entityKind: OfflineEntityKind;
|
|
366
|
+
};
|
|
367
|
+
/**
|
|
368
|
+
* Persisted offline conflict payload.
|
|
369
|
+
*
|
|
370
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
371
|
+
* @typeParam TInput - Original mutation input associated with the conflict.
|
|
372
|
+
*/
|
|
373
|
+
type OfflineConflictResolutionRecordBase<TConflict = unknown, TInput = unknown> = {
|
|
374
|
+
/** Resolution record identifier. */id: string; /** Resolution kind. */
|
|
375
|
+
kind: 'conflict'; /** Queue entry identifier that produced this conflict. */
|
|
376
|
+
entryId: string; /** Session key that owns this conflict record. */
|
|
377
|
+
sessionKey: string; /** Store name associated with the conflict. */
|
|
378
|
+
storeName: string; /** Store type associated with the conflict. */
|
|
379
|
+
storeType: OfflineStoreType; /** Operation name linked to the conflict. */
|
|
380
|
+
operation: string; /** Input value that triggered the conflict. */
|
|
381
|
+
input: TInput; /** Conflict payload returned by the resolver. */
|
|
382
|
+
conflict: TConflict; /** Timestamp when the original queued mutation was enqueued. */
|
|
383
|
+
enqueuedAt: number; /** Entity references involved in the conflict. */
|
|
384
|
+
entityRefs: OfflineEntityRef[]; /** Conflict creation timestamp. */
|
|
385
|
+
createdAt: number; /** Conflict update timestamp. */
|
|
386
|
+
updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
|
|
387
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
388
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
389
|
+
dependencyUploadIds?: string[];
|
|
390
|
+
};
|
|
391
|
+
/** Derived dependency metadata exposed for offline manual resolutions. */
|
|
392
|
+
type OfflineResolutionDependencyMetadata = {
|
|
393
|
+
/** Parent resolution ids that must be cleared before this resolution can be retried or discarded. */blockedByResolutionIds: string[]; /** Child manual resolutions currently derived from this resolution's dependency chain. */
|
|
394
|
+
childResolutionIds: string[]; /** Number of blocking parent resolutions affecting this resolution. */
|
|
395
|
+
blockedResolutionCount: number; /** Number of child manual resolutions currently derived from this resolution. */
|
|
396
|
+
childResolutionCount: number;
|
|
397
|
+
};
|
|
398
|
+
/**
|
|
399
|
+
* Persisted offline conflict payload with derived dependency metadata.
|
|
400
|
+
*
|
|
401
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
402
|
+
* @typeParam TInput - Original mutation input associated with the conflict.
|
|
403
|
+
*/
|
|
404
|
+
type OfflineConflictResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecordBase<TConflict, TInput> & OfflineResolutionDependencyMetadata;
|
|
405
|
+
/**
|
|
406
|
+
* Persisted resolution record created when replay retries are exhausted.
|
|
407
|
+
*
|
|
408
|
+
* @typeParam TInput - Original mutation input associated with the replay failure.
|
|
409
|
+
*/
|
|
410
|
+
type OfflineRetryExhaustedResolutionRecordBase<TInput = unknown> = {
|
|
411
|
+
/** Resolution record identifier. */id: string; /** Resolution kind. */
|
|
412
|
+
kind: 'retry-exhausted'; /** Queue entry identifier that exhausted replay retries. */
|
|
413
|
+
entryId: string; /** Session key that owns this resolution record. */
|
|
414
|
+
sessionKey: string; /** Store name associated with the resolution. */
|
|
415
|
+
storeName: string; /** Store type associated with the resolution. */
|
|
416
|
+
storeType: OfflineStoreType; /** Operation name linked to the replay failure. */
|
|
417
|
+
operation: string; /** Input value that exhausted replay retries. */
|
|
418
|
+
input: TInput; /** Timestamp when the original queued mutation was enqueued. */
|
|
419
|
+
enqueuedAt: number; /** Entity references involved in the resolution. */
|
|
420
|
+
entityRefs: OfflineEntityRef[]; /** Last replay error snapshot captured before exhaustion. */
|
|
421
|
+
lastReplayError: {
|
|
422
|
+
message: string;
|
|
423
|
+
}; /** Resolution creation timestamp. */
|
|
424
|
+
createdAt: number; /** Resolution update timestamp. */
|
|
425
|
+
updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
|
|
426
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
427
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
428
|
+
dependencyUploadIds?: string[];
|
|
429
|
+
};
|
|
430
|
+
/**
|
|
431
|
+
* Persisted resolution record created when replay retries are exhausted, plus
|
|
432
|
+
* derived dependency metadata.
|
|
433
|
+
*
|
|
434
|
+
* @typeParam TInput - Original mutation input associated with the replay failure.
|
|
435
|
+
*/
|
|
436
|
+
type OfflineRetryExhaustedResolutionRecord<TInput = unknown> = OfflineRetryExhaustedResolutionRecordBase<TInput> & OfflineResolutionDependencyMetadata;
|
|
437
|
+
/**
|
|
438
|
+
* Persisted offline resolution payload.
|
|
439
|
+
*
|
|
440
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
441
|
+
* @typeParam TInput - Original mutation input associated with the resolution.
|
|
442
|
+
*/
|
|
443
|
+
type OfflineResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecord<TConflict, TInput> | OfflineRetryExhaustedResolutionRecord<TInput>;
|
|
444
|
+
/** Session-scoped offline controller shared across stores in the same session. */
|
|
445
|
+
type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
446
|
+
/** Returns the active session key used to scope shared offline state. */getSessionKey: () => string | false; /** Shared static session configuration used by attached stores. */
|
|
447
|
+
getConfig: () => OfflineSessionConfig<TUploadRef>; /** Latest effective runtime config for this session. */
|
|
448
|
+
getOfflineRuntimeConfig: () => OfflineRuntimeConfig; /** Updates runtime controls for this session. */
|
|
449
|
+
setOfflineRuntimeConfig: (update: OfflineRuntimeConfigUpdate) => void; /** Resets runtime controls back to the static session config. */
|
|
450
|
+
resetOfflineRuntimeConfig: () => void; /** Returns the latest global offline status for the session. */
|
|
451
|
+
getOfflineStatus: () => GlobalOfflineStatus; /** Returns the latest aggregated offline entities for the session. */
|
|
452
|
+
getOfflineEntities: () => readonly GlobalOfflineEntity[]; /** Returns the latest aggregated conflict/retry resolutions for the session. */
|
|
453
|
+
getOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns the latest session-scoped offline uploads for the session. */
|
|
454
|
+
getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
|
|
455
|
+
resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
|
|
456
|
+
resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
|
|
457
|
+
saveOfflineUpload: (args: {
|
|
458
|
+
id: string;
|
|
459
|
+
file: Blob | File;
|
|
460
|
+
}) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
|
|
461
|
+
replaceOfflineUpload: (args: {
|
|
462
|
+
id: string;
|
|
463
|
+
file: Blob | File;
|
|
464
|
+
}) => Promise<void>; /** Loads a previously stored session-scoped upload. */
|
|
465
|
+
loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
|
|
466
|
+
deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
|
|
467
|
+
useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
|
|
468
|
+
useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to the session's aggregated conflict/retry resolutions. */
|
|
469
|
+
useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the session's upload list. */
|
|
470
|
+
useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* Persisted offline mutation queue entry.
|
|
474
|
+
*
|
|
475
|
+
* @typeParam TInput - Serialized input payload for the queued mutation.
|
|
476
|
+
* @typeParam TConflict - Conflict payload that may be attached while waiting for confirmation or resolution.
|
|
477
|
+
*/
|
|
478
|
+
type OfflineQueueEntry<TInput = unknown, TConflict = unknown> = {
|
|
479
|
+
/** Queue entry identifier. */id: string; /** Session key for queue scoping. */
|
|
480
|
+
sessionKey: string; /** Store name where operation is defined. */
|
|
481
|
+
storeName: string; /** Store type for this queued operation. */
|
|
482
|
+
storeType: OfflineStoreType; /** Operation name registered in offline configuration. */
|
|
483
|
+
operation: string; /** Operation input payload persisted with the entry. */
|
|
484
|
+
input: TInput; /** Stable ordering key used to replay queued operations deterministically. */
|
|
485
|
+
queueOrder: number; /** Entity references tied to this mutation. */
|
|
486
|
+
entityRefs: OfflineEntityRef[]; /** Number of execution attempts so far. */
|
|
487
|
+
attempts: number; /** Queue entry creation timestamp. */
|
|
488
|
+
createdAt: number; /** Last entry update timestamp. */
|
|
489
|
+
updatedAt: number; /** Timestamp of last execution attempt, if any. */
|
|
490
|
+
lastAttemptAt: number | null; /** Synchronization state for this entry. */
|
|
491
|
+
syncState: OfflineSyncState; /** Optional temporary IDs for optimistic create operations. */
|
|
492
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
493
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
494
|
+
dependencyUploadIds?: string[]; /** Last recorded sync error if replay failed. */
|
|
495
|
+
lastError?: {
|
|
496
|
+
message: string;
|
|
497
|
+
};
|
|
498
|
+
/**
|
|
499
|
+
* Whether a `needs-confirmation` entry may auto-resend during healthy replay
|
|
500
|
+
* retries after confirmation checks finish.
|
|
501
|
+
*/
|
|
502
|
+
allowReplayRetry?: boolean; /** Pending conflict payload when confirmation or resolution is required. */
|
|
503
|
+
pendingConflict?: TConflict;
|
|
504
|
+
};
|
|
505
|
+
/** Built-in resolution actions for retry exhaustion records. */
|
|
506
|
+
type OfflineRetryExhaustedResolutionAction = {
|
|
507
|
+
action: 'retry';
|
|
508
|
+
/**
|
|
509
|
+
* Controls whether retrying a resolution should also requeue retryable
|
|
510
|
+
* descendants from the same temp-lifecycle dependency chain.
|
|
511
|
+
* @default 'self-and-descendants'
|
|
512
|
+
*/
|
|
513
|
+
scope?: 'self' | 'self-and-descendants';
|
|
514
|
+
} | {
|
|
515
|
+
action: 'discard';
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Built-in resolution actions for persisted conflict records.
|
|
519
|
+
*
|
|
520
|
+
* `commit` is intended for flows where the final API call has already been made
|
|
521
|
+
* externally and the store only needs to clear bookkeeping plus reconcile any
|
|
522
|
+
* temp-entity lifecycle using the accepted server result.
|
|
523
|
+
*
|
|
524
|
+
* @typeParam TInput - Input type expected when requeueing a replacement mutation.
|
|
525
|
+
* @typeParam TResult - Result shape returned by the external conflict resolution call.
|
|
526
|
+
*/
|
|
527
|
+
type OfflineConflictResolutionAction<TInput = unknown, TResult = unknown> = {
|
|
528
|
+
action: 'discard';
|
|
529
|
+
} | {
|
|
530
|
+
action: 'requeue';
|
|
531
|
+
input: TInput;
|
|
532
|
+
} | {
|
|
533
|
+
action: 'commit';
|
|
534
|
+
result?: TResult;
|
|
535
|
+
};
|
|
536
|
+
/**
|
|
537
|
+
* Built-in resolution actions accepted by `resolveOfflineResolution(...)`.
|
|
538
|
+
*
|
|
539
|
+
* @typeParam TInput - Input type expected when requeueing a replacement mutation.
|
|
540
|
+
* @typeParam TResult - Result shape returned by an externally completed conflict resolution call.
|
|
541
|
+
*/
|
|
542
|
+
type OfflineResolutionAction<TInput = unknown, TResult = unknown> = OfflineRetryExhaustedResolutionAction | OfflineConflictResolutionAction<TInput, TResult>;
|
|
543
|
+
/**
|
|
544
|
+
* Extracts operation input type from a schema map.
|
|
545
|
+
*
|
|
546
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
547
|
+
* @typeParam TName - Operation name whose input type should be extracted.
|
|
548
|
+
*/
|
|
549
|
+
type OperationInput<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
550
|
+
inputSchema: PersistentStorageSchema<infer TInput>;
|
|
551
|
+
} ? TInput : never;
|
|
552
|
+
/**
|
|
553
|
+
* A typed operation descriptor for an offline mutation queue entry.
|
|
554
|
+
*
|
|
555
|
+
* @typeParam TOperations - Operation registry that defines valid operation names and input schemas.
|
|
556
|
+
* @typeParam TName - Operation name to describe. Defaults to all operation names in the registry.
|
|
557
|
+
*/
|
|
558
|
+
type OfflineMutationDescriptor<TOperations extends Record<string, {
|
|
559
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
560
|
+
}>, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: {
|
|
561
|
+
/** Operation key from the offline operations registry. */operation: K; /** Input resolved from the registered operation schema. */
|
|
562
|
+
input: OperationInput<TOperations, K>;
|
|
563
|
+
} }[TName];
|
|
564
|
+
/**
|
|
565
|
+
* Public offline mutation input accepted by store mutation APIs.
|
|
566
|
+
*
|
|
567
|
+
* Callers queue exactly one descriptor per mutation fallback.
|
|
568
|
+
*/
|
|
569
|
+
type OfflineMutationInput<TOperations extends Record<string, {
|
|
570
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
571
|
+
}>, TName extends keyof TOperations & string = keyof TOperations & string> = OfflineMutationDescriptor<TOperations, TName>;
|
|
572
|
+
/**
|
|
573
|
+
* Extracts operation result type from a registered operation map.
|
|
574
|
+
*
|
|
575
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
576
|
+
* @typeParam TName - Operation name whose result type should be extracted.
|
|
577
|
+
*/
|
|
578
|
+
type OperationResult<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
579
|
+
execute: (...args: __LEGIT_ANY__[]) => infer TResult;
|
|
580
|
+
} ? Awaited<TResult> : never;
|
|
581
|
+
/**
|
|
582
|
+
* Resolution action accepted for a specific registered offline operation.
|
|
583
|
+
*
|
|
584
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
585
|
+
* @typeParam TName - Operation name whose resolution payload should be extracted.
|
|
586
|
+
*/
|
|
587
|
+
type OfflineResolutionActionForOperation<TOperations, TName extends keyof TOperations> = OfflineResolutionAction<OperationInput<TOperations, TName>, OperationResult<TOperations, TName>>;
|
|
588
|
+
/**
|
|
589
|
+
* Context passed into offline mutation accumulation hooks.
|
|
590
|
+
*
|
|
591
|
+
* @typeParam TInput - Input type shared by the existing and incoming queued mutations.
|
|
592
|
+
*/
|
|
593
|
+
type OfflineAccumulationMergeContext<TInput> = {
|
|
594
|
+
/** Session key used to isolate queued mutations. */sessionKey: string; /** Existing input already present in queue. */
|
|
595
|
+
existingInput: TInput; /** Incoming input for merge attempt. */
|
|
596
|
+
incomingInput: TInput;
|
|
597
|
+
};
|
|
598
|
+
/**
|
|
599
|
+
* Optional in-memory accumulation strategy for queued offline mutations.
|
|
600
|
+
*
|
|
601
|
+
* @typeParam TInput - Input type that will be merged and revalidated before persisting.
|
|
602
|
+
*/
|
|
603
|
+
type OfflineAccumulationConfig<TInput> = {
|
|
604
|
+
/** Merge function for combining existing and incoming mutation inputs. */mergeInput: (ctx: OfflineAccumulationMergeContext<TInput>) => Promise<TInput> | TInput;
|
|
605
|
+
};
|
|
606
|
+
/**
|
|
607
|
+
* Optional queue-pruning strategy for queued offline mutations.
|
|
608
|
+
*
|
|
609
|
+
* `same-entity` only applies to operations that resolve exactly one entity ref.
|
|
610
|
+
* When enabled, the new operation may remove earlier unattempted pending entries
|
|
611
|
+
* targeting that same single entity before the new entry is persisted.
|
|
612
|
+
*/
|
|
613
|
+
type OfflineSupersedeConfig = {
|
|
614
|
+
/** Drop earlier unattempted pending entries for the same single entity. */scope: 'same-entity';
|
|
615
|
+
/**
|
|
616
|
+
* Limits which earlier operations may be pruned for that entity.
|
|
617
|
+
*
|
|
618
|
+
* Omit this to prune every earlier pending operation for the entity,
|
|
619
|
+
* use `'self'` to prune only earlier entries of the current operation,
|
|
620
|
+
* or provide explicit operation names to target a specific related set.
|
|
621
|
+
*/
|
|
622
|
+
operations?: 'self' | readonly string[];
|
|
623
|
+
/**
|
|
624
|
+
* When the pruned entries include a temp-entity lifecycle, drop the current
|
|
625
|
+
* operation itself instead of persisting a replacement entry.
|
|
626
|
+
*/
|
|
627
|
+
dropSelfIfTempLifecycleCancelled?: boolean;
|
|
628
|
+
};
|
|
629
|
+
/** Shared context passed to offline replay lifecycle hooks. */
|
|
630
|
+
type OperationBaseContext<TInput> = {
|
|
631
|
+
/** Input payload for the queued mutation currently being processed. */input: TInput; /** Timestamp when the operation was originally enqueued. */
|
|
632
|
+
enqueuedAt: number; /** Timestamp when the queued entry or conflict record was last updated. */
|
|
633
|
+
updatedAt: number;
|
|
634
|
+
/**
|
|
635
|
+
* Resolves a previously temp-backed entity ref to its latest known final ref
|
|
636
|
+
* when one has been reconciled.
|
|
637
|
+
*/
|
|
638
|
+
resolveEntityRef: <TEntityRef extends ValidPayload>(entityRef: TEntityRef) => TEntityRef;
|
|
639
|
+
};
|
|
640
|
+
type OperationExecuteContext<TInput, TUploadRef extends ValidPayload = ValidPayload> = OperationBaseContext<TInput> & {
|
|
641
|
+
uploads: OfflineOperationUploadsContext<TUploadRef>;
|
|
642
|
+
};
|
|
643
|
+
/** Context passed to the post-replay success hook after `execute(...)` settles. */
|
|
644
|
+
type OfflineOperationExecuteSuccessContext<TInput, TResult> = OperationBaseContext<TInput> & {
|
|
645
|
+
/** Replay result returned by `execute(...)`. */result: TResult;
|
|
646
|
+
};
|
|
647
|
+
/**
|
|
648
|
+
* Optional callback used to synchronize UI/cache state after a successful
|
|
649
|
+
* offline replay execute.
|
|
650
|
+
*/
|
|
651
|
+
type OfflineOperationExecuteSuccessHandler<TInput, TResult> = (ctx: OfflineOperationExecuteSuccessContext<TInput, TResult>) => Promise<void> | void;
|
|
652
|
+
type IsUnknown<T> = unknown extends T ? [keyof T] extends [never] ? true : false : false;
|
|
653
|
+
/** Context passed to replay checks that may use a fresh server snapshot. */
|
|
654
|
+
type OperationReplayCheckContext<TInput, TServerSnapshot> = OperationBaseContext<TInput> & {
|
|
655
|
+
/**
|
|
656
|
+
* Optional snapshot fetched immediately before `shouldSkipSync` and
|
|
657
|
+
* `detectConflict`.
|
|
658
|
+
*/
|
|
659
|
+
serverSnapshot: IsUnknown<TServerSnapshot> extends true ? undefined : TServerSnapshot;
|
|
660
|
+
};
|
|
661
|
+
/**
|
|
662
|
+
* Conflict hook configuration for a queued offline operation.
|
|
663
|
+
*
|
|
664
|
+
* @typeParam TInput - Input type of the queued operation being checked and potentially requeued.
|
|
665
|
+
* @typeParam TConflict - Conflict payload produced by detection and persisted for later external resolution.
|
|
666
|
+
*/
|
|
667
|
+
type OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot = unknown> = {
|
|
668
|
+
/** Schema used to validate and sanitize persisted conflict payloads. */schema: PersistentStorageSchema<TConflict>;
|
|
669
|
+
/**
|
|
670
|
+
* Inspect remote state before replaying the mutation and return conflict payload
|
|
671
|
+
* when the queued mutation can no longer be applied safely.
|
|
672
|
+
*/
|
|
673
|
+
detectConflict: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<TConflict | false | null> | TConflict | false | null;
|
|
674
|
+
};
|
|
675
|
+
type ConflictHandlingField<TInput, TConflict, TServerSnapshot> = IsUnknown<TConflict> extends true ? {
|
|
676
|
+
/**
|
|
677
|
+
* Optional conflict strategy when a queued operation diverges from remote state.
|
|
678
|
+
*/
|
|
679
|
+
conflictHandling?: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
|
|
680
|
+
} : {
|
|
681
|
+
/**
|
|
682
|
+
* Conflict strategy required when the operation declares a concrete
|
|
683
|
+
* conflict payload type.
|
|
684
|
+
*/
|
|
685
|
+
conflictHandling: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
|
|
686
|
+
};
|
|
687
|
+
type ServerSnapshotField<TInput, TServerSnapshot> = IsUnknown<TServerSnapshot> extends true ? {
|
|
688
|
+
/**
|
|
689
|
+
* Optionally loads a fresh server-side snapshot before replay checks run.
|
|
690
|
+
* The result is passed to `shouldSkipSync` and `detectConflict` as
|
|
691
|
+
* `ctx.serverSnapshot`.
|
|
692
|
+
*/
|
|
693
|
+
getServerSnapshot?: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
|
|
694
|
+
} : {
|
|
695
|
+
/**
|
|
696
|
+
* Required when the operation declares a concrete server snapshot type.
|
|
697
|
+
* The result is passed to `shouldSkipSync` and `detectConflict` as
|
|
698
|
+
* `ctx.serverSnapshot`.
|
|
699
|
+
*/
|
|
700
|
+
getServerSnapshot: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
|
|
701
|
+
};
|
|
702
|
+
/**
|
|
703
|
+
* Replacement data returned by `tempEntity.reconcileServerEntity(...)`.
|
|
704
|
+
*
|
|
705
|
+
* @typeParam TFinalPayload - Final payload that should replace the temporary one.
|
|
706
|
+
* @typeParam TFinalData - Optional replacement entity data for the final payload.
|
|
707
|
+
*/
|
|
708
|
+
type OfflineTempEntityReconciliation<TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
709
|
+
/** Final payload that should replace the temporary optimistic one. */finalPayload: TFinalPayload;
|
|
710
|
+
/**
|
|
711
|
+
* Optional replacement data for the final payload.
|
|
712
|
+
* Omit this to keep the current optimistic entity data and only swap the
|
|
713
|
+
* payload/identity.
|
|
714
|
+
*/
|
|
715
|
+
finalData?: TFinalData;
|
|
716
|
+
};
|
|
717
|
+
/**
|
|
718
|
+
* Replacement data returned by `tempEntities.reconcileServerEntities(...)`.
|
|
719
|
+
*
|
|
720
|
+
* @typeParam TTempId - Temporary payload that should be reconciled.
|
|
721
|
+
* @typeParam TFinalPayload - Final payload that should replace the temporary one.
|
|
722
|
+
* @typeParam TFinalData - Optional replacement entity data for the final payload.
|
|
723
|
+
*/
|
|
724
|
+
type OfflineTempEntitiesReconciliation<TTempId extends ValidPayload = ValidPayload, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = OfflineTempEntityReconciliation<TFinalPayload, TFinalData> & {
|
|
725
|
+
/** Temporary payload that should be reconciled. */tempId: TTempId;
|
|
726
|
+
};
|
|
727
|
+
/**
|
|
728
|
+
* Pending temp-entity returned by `tempEntities.buildPendingEntities(...)`.
|
|
729
|
+
*
|
|
730
|
+
* @typeParam TTempId - Temporary payload used to track the optimistic entity.
|
|
731
|
+
* @typeParam TPendingEntity - Pending entity snapshot to insert locally.
|
|
732
|
+
*/
|
|
733
|
+
type OfflineTempEntityPendingEntry<TTempId extends ValidPayload = ValidPayload, TPendingEntity = unknown> = {
|
|
734
|
+
/** Temporary payload that identifies the optimistic entity. */tempId: TTempId; /** Pending entity snapshot inserted while the mutation is queued. */
|
|
735
|
+
pendingEntity: TPendingEntity;
|
|
736
|
+
};
|
|
737
|
+
/**
|
|
738
|
+
* Optional temp-id lifecycle for optimistic offline create flows.
|
|
739
|
+
*
|
|
740
|
+
* @typeParam TInput - Input type used to derive the temporary entity and identifier.
|
|
741
|
+
* @typeParam TTempResult - Result returned by `execute`, used only by `tempEntity.reconcileServerEntity(...)`.
|
|
742
|
+
* @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
|
|
743
|
+
*/
|
|
744
|
+
type OfflineTempEntityConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
745
|
+
/**
|
|
746
|
+
* Builds the optimistic entity inserted into local state while the mutation
|
|
747
|
+
* is queued offline.
|
|
748
|
+
*
|
|
749
|
+
* `tempId` is the temporary payload used to identify the optimistic entity
|
|
750
|
+
* until replay succeeds and the final server entity can replace it.
|
|
751
|
+
*/
|
|
752
|
+
buildPendingEntity: (input: TInput, tempId: TTempId) => TPendingEntity;
|
|
753
|
+
/**
|
|
754
|
+
* Reconciles the optimistic temp entity with the successful replay result.
|
|
755
|
+
*/
|
|
756
|
+
reconcileServerEntity: (result: TTempResult, tempId: TTempId) => OfflineTempEntityReconciliation<TFinalPayload, TFinalData>;
|
|
757
|
+
};
|
|
758
|
+
/**
|
|
759
|
+
* Optional temp-id lifecycle for optimistic offline batch-create flows.
|
|
760
|
+
*
|
|
761
|
+
* @typeParam TInput - Input type used to derive the temporary entities and identifiers.
|
|
762
|
+
* @typeParam TTempResult - Result returned by `execute`, used only by `tempEntities.reconcileServerEntities(...)`.
|
|
763
|
+
* @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
|
|
764
|
+
*/
|
|
765
|
+
type OfflineTempEntitiesConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
766
|
+
/**
|
|
767
|
+
* Builds the optimistic entities inserted into local state while the mutation
|
|
768
|
+
* is queued offline.
|
|
769
|
+
*
|
|
770
|
+
* `tempIds` are the temporary payloads derived from the operation entity refs
|
|
771
|
+
* and used until replay succeeds and the final server entities can replace them.
|
|
772
|
+
*/
|
|
773
|
+
buildPendingEntities: (input: TInput, tempIds: readonly TTempId[]) => readonly OfflineTempEntityPendingEntry<TTempId, TPendingEntity>[];
|
|
774
|
+
/**
|
|
775
|
+
* Reconciles the optimistic temp entities with the successful replay result.
|
|
776
|
+
*/
|
|
777
|
+
reconcileServerEntities: (result: TTempResult, tempIds: readonly TTempId[]) => readonly OfflineTempEntitiesReconciliation<TTempId, TFinalPayload, TFinalData>[];
|
|
778
|
+
};
|
|
779
|
+
type NoTempEntityFields = {
|
|
780
|
+
tempEntity?: never;
|
|
781
|
+
tempEntities?: never;
|
|
782
|
+
};
|
|
783
|
+
type ConfiguredTempEntityFields<TInput, TTempResult, TTempId extends ValidPayload, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
784
|
+
tempEntity: OfflineTempEntityConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
|
|
785
|
+
tempEntities?: never;
|
|
786
|
+
} | {
|
|
787
|
+
tempEntity?: never;
|
|
788
|
+
tempEntities: OfflineTempEntitiesConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
|
|
789
|
+
};
|
|
790
|
+
/**
|
|
791
|
+
* Shape used by `persistentStorage.offline.operations` for each operation name.
|
|
792
|
+
*
|
|
793
|
+
* @typeParam TInput - The persisted input payload for the queued offline operation.
|
|
794
|
+
* @typeParam TConflict - The conflict payload produced by pre-execution conflict detection.
|
|
795
|
+
* @typeParam TTempResult - Result returned by `execute`, used only when `tempEntity` or `tempEntities` needs to reconcile the final server entity. Defaults to `void`.
|
|
796
|
+
*/
|
|
797
|
+
type OfflineOperationDefinition<TInput, TConflict, TTempResult = void, TServerSnapshot = unknown, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown, TUploadRef extends ValidPayload = ValidPayload> = {
|
|
798
|
+
/** Schema used to validate incoming operation input. */inputSchema: PersistentStorageSchema<TInput>; /** Lifecycle classification for the queued operation. */
|
|
799
|
+
kind: OfflineOperationKind;
|
|
800
|
+
/**
|
|
801
|
+
* Optional queue pruning for newer operations that supersede older queued work.
|
|
802
|
+
*
|
|
803
|
+
* This is mutually exclusive with `accumulation`.
|
|
804
|
+
*/
|
|
805
|
+
supersedes?: OfflineSupersedeConfig;
|
|
806
|
+
/**
|
|
807
|
+
* Executes the queued mutation against the remote source during replay.
|
|
808
|
+
* This may run multiple times when transient failures occur.
|
|
809
|
+
*/
|
|
810
|
+
execute: (ctx: OperationExecuteContext<TInput, TUploadRef>) => Promise<TTempResult> | TTempResult;
|
|
811
|
+
/**
|
|
812
|
+
* Optional check executed before retrying a previously failed sync attempt.
|
|
813
|
+
* Return `true` to drop the queued entry because the remote side already reflects it.
|
|
814
|
+
* Return `false` to continue with normal replay.
|
|
815
|
+
*/
|
|
816
|
+
shouldSkipSync?: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<boolean> | boolean;
|
|
817
|
+
} & ConflictHandlingField<TInput, TConflict, TServerSnapshot> & ServerSnapshotField<TInput, TServerSnapshot> & (({
|
|
818
|
+
/**
|
|
819
|
+
* Explicit store-sync step that runs after `execute(...)` succeeds during
|
|
820
|
+
* offline replay.
|
|
821
|
+
*
|
|
822
|
+
* Provide a callback when replay should update the live store after the
|
|
823
|
+
* server-side execute succeeds.
|
|
824
|
+
*/
|
|
825
|
+
onSuccessExecute: OfflineOperationExecuteSuccessHandler<TInput, TTempResult>;
|
|
826
|
+
/**
|
|
827
|
+
* Optional queue compaction for consecutive mutations with same refs.
|
|
828
|
+
*/
|
|
829
|
+
accumulation?: OfflineAccumulationConfig<TInput>;
|
|
830
|
+
} & NoTempEntityFields) | ({
|
|
831
|
+
/**
|
|
832
|
+
* Temp-entity operations already reconcile the live store through
|
|
833
|
+
* `tempEntity` / `tempEntities`, so they must not declare an extra
|
|
834
|
+
* success sync callback.
|
|
835
|
+
*/
|
|
836
|
+
onSuccessExecute?: undefined; /** Temp-entity operations cannot compact multiple queued creates. */
|
|
837
|
+
accumulation?: never;
|
|
838
|
+
} & ConfiguredTempEntityFields<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>));
|
|
839
|
+
type WithoutTempEntity<T extends {
|
|
840
|
+
tempEntity?: unknown;
|
|
841
|
+
tempEntities?: unknown;
|
|
842
|
+
}> = Omit<T, 'tempEntity' | 'tempEntities'> & {
|
|
843
|
+
/** Document stores do not support optimistic temp entities. */tempEntity?: never; /** Document stores do not support optimistic batch temp entities. */
|
|
844
|
+
tempEntities?: never;
|
|
845
|
+
};
|
|
846
|
+
/** Context used to resolve which entities a queued mutation affects. */
|
|
847
|
+
type OperationEntityRefsContext<TInput> = {
|
|
848
|
+
/** Input payload for the queued mutation. */input: TInput;
|
|
849
|
+
};
|
|
850
|
+
/** Non-store-specific offline operation definition alias. */
|
|
851
|
+
type AnyOfflineOperationDefinition<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
852
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
853
|
+
kind: OfflineOperationKind;
|
|
854
|
+
conflictHandling?: {
|
|
855
|
+
schema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
856
|
+
detectConflict: (ctx: __LEGIT_ANY__) => unknown;
|
|
857
|
+
};
|
|
858
|
+
accumulation?: OfflineAccumulationConfig<__LEGIT_ANY__>;
|
|
859
|
+
supersedes?: OfflineSupersedeConfig;
|
|
860
|
+
tempEntity?: OfflineTempEntityConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
|
|
861
|
+
tempEntities?: OfflineTempEntitiesConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
|
|
862
|
+
getServerSnapshot?: (ctx: OperationBaseContext<__LEGIT_ANY__>) => unknown;
|
|
863
|
+
execute: (ctx: OperationExecuteContext<__LEGIT_ANY__, TUploadRef>) => unknown;
|
|
864
|
+
onSuccessExecute?: OfflineOperationExecuteSuccessHandler<__LEGIT_ANY__, __LEGIT_ANY__>;
|
|
865
|
+
shouldSkipSync?: (ctx: OperationReplayCheckContext<__LEGIT_ANY__, __LEGIT_ANY__>) => Promise<boolean> | boolean;
|
|
866
|
+
} & {
|
|
867
|
+
getEntityRefs?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => unknown[];
|
|
868
|
+
dependsOn?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => __LEGIT_ANY__[];
|
|
869
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => string[];
|
|
870
|
+
};
|
|
871
|
+
/**
|
|
872
|
+
* Compact type-spec helper for a single offline operation.
|
|
873
|
+
*
|
|
874
|
+
* Use this helper with {@link DefineDocumentOfflineOperations} to describe each
|
|
875
|
+
* operation using generic parameters instead of inline object literals.
|
|
876
|
+
*
|
|
877
|
+
* The generic order is `input`, `conflict`, `temp result`, then `server snapshot`.
|
|
878
|
+
*
|
|
879
|
+
* @typeParam TInput - Input payload accepted by the operation.
|
|
880
|
+
* @typeParam TConflict - Conflict payload produced by optional conflict handling.
|
|
881
|
+
* @typeParam TTempResult - Result returned by `execute`, also reused when externally committed conflict resolution needs temp-entity reconciliation.
|
|
882
|
+
*
|
|
883
|
+
* @example
|
|
884
|
+
* ```ts
|
|
885
|
+
* type UpdateName = DefineOfflineOperation<
|
|
886
|
+
* { name: string },
|
|
887
|
+
* { remoteName: string },
|
|
888
|
+
* { name: string }
|
|
889
|
+
* >;
|
|
890
|
+
* ```
|
|
891
|
+
*/
|
|
892
|
+
type DefineOfflineOperation<TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown> = {
|
|
893
|
+
/** Input type accepted by the operation. */input?: TInput; /** Conflict payload type produced by the optional conflict handler. */
|
|
894
|
+
conflict?: TConflict; /** Result returned by `execute`, also reused by externally committed conflict resolution for temp-entity reconciliation. */
|
|
895
|
+
result?: TTempResult; /** Snapshot type returned by `getServerSnapshot` and exposed to replay checks. */
|
|
896
|
+
serverSnapshot?: TServerSnapshot;
|
|
897
|
+
};
|
|
898
|
+
type DocumentOperationInput<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
899
|
+
input?: infer TInput;
|
|
900
|
+
} ? TInput : unknown;
|
|
901
|
+
type DocumentOperationConflict<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
902
|
+
conflict?: infer TConflict;
|
|
903
|
+
} ? TConflict : unknown;
|
|
904
|
+
type DocumentOperationResult<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
905
|
+
result?: infer TTempResult;
|
|
906
|
+
} ? TTempResult : unknown;
|
|
907
|
+
type DocumentOperationServerSnapshot<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
908
|
+
serverSnapshot?: infer TServerSnapshot;
|
|
909
|
+
} ? TServerSnapshot : unknown;
|
|
910
|
+
/**
|
|
911
|
+
* Document-store specific offline operation definition.
|
|
912
|
+
*
|
|
913
|
+
* Prefer this alias when manually typing a single operation inside
|
|
914
|
+
* `persistentStorage.offline.operations` for a document store.
|
|
915
|
+
*
|
|
916
|
+
* `TOptions` is usually provided with {@link DefineOfflineOperation}, which lets
|
|
917
|
+
* callers specify the queued `input`, replay `result`, and optional `conflict`
|
|
918
|
+
* payload concisely. Document stores do not support `tempEntity`.
|
|
919
|
+
*
|
|
920
|
+
* Omitted properties default to `unknown`.
|
|
921
|
+
*
|
|
922
|
+
* @typeParam State - Document state type for the owning store.
|
|
923
|
+
* @typeParam TOptions - Operation typing options, usually created with {@link DefineOfflineOperation}.
|
|
924
|
+
*
|
|
925
|
+
* @example
|
|
926
|
+
* ```ts
|
|
927
|
+
* type RenameOperation = DocumentOfflineOperationDefinition<
|
|
928
|
+
* UserDoc,
|
|
929
|
+
* DefineOfflineOperation<
|
|
930
|
+
* { name: string },
|
|
931
|
+
* { remoteName: string },
|
|
932
|
+
* { name: string }
|
|
933
|
+
* >
|
|
934
|
+
* >;
|
|
935
|
+
* ```
|
|
936
|
+
*/
|
|
937
|
+
type DocumentOfflineOperationDefinition<State extends ValidStoreState, TOptions extends DefineOfflineOperation = DefineOfflineOperation, TUploadRef extends ValidPayload = ValidPayload> = WithoutTempEntity<OfflineOperationDefinition<DocumentOperationInput<TOptions>, DocumentOperationConflict<TOptions>, DocumentOperationResult<TOptions>, DocumentOperationServerSnapshot<TOptions>, string, unknown, ValidPayload, unknown, TUploadRef>> & {
|
|
938
|
+
/** Declares which upload ids must finish before replaying this operation. */dependsOnUploads?: (ctx: OperationEntityRefsContext<DocumentOperationInput<TOptions>>) => string[];
|
|
939
|
+
} & ([State] extends [never] ? never : unknown);
|
|
940
|
+
/**
|
|
941
|
+
* Builds a document offline operations map from a compact operation spec.
|
|
942
|
+
*
|
|
943
|
+
* This is the recommended way to type a document store's full offline operation map.
|
|
944
|
+
* Each operation key is typically described with {@link DefineOfflineOperation},
|
|
945
|
+
* and this helper expands that into the full
|
|
946
|
+
* {@link DocumentOfflineOperationDefinition} map expected by the store.
|
|
947
|
+
*
|
|
948
|
+
* @typeParam State - Document state type for the owning store.
|
|
949
|
+
* @typeParam TOperations - Operation map where each key declares its input, replay result, and optional conflict payload.
|
|
950
|
+
*
|
|
951
|
+
* @example
|
|
952
|
+
* ```ts
|
|
953
|
+
* type Operations = DefineDocumentOfflineOperations<
|
|
954
|
+
* UserDoc,
|
|
955
|
+
* {
|
|
956
|
+
* updateName: DefineOfflineOperation<
|
|
957
|
+
* { name: string },
|
|
958
|
+
* unknown,
|
|
959
|
+
* { name: string }
|
|
960
|
+
* >;
|
|
961
|
+
* archive: DefineOfflineOperation<
|
|
962
|
+
* { reason: string },
|
|
963
|
+
* { code: string }
|
|
964
|
+
* >;
|
|
965
|
+
* }
|
|
966
|
+
* >;
|
|
967
|
+
* ```
|
|
968
|
+
*
|
|
969
|
+
* Then use the resulting type as the `operations` object contract:
|
|
970
|
+
*
|
|
971
|
+
* ```ts
|
|
972
|
+
* const operations: Operations = {
|
|
973
|
+
* updateName: {
|
|
974
|
+
* inputSchema: z.object({ name: z.string() }),
|
|
975
|
+
* kind: 'update',
|
|
976
|
+
* execute: ({ input }) => ({ name: input.name }),
|
|
977
|
+
* },
|
|
978
|
+
* archive: {
|
|
979
|
+
* inputSchema: z.object({ reason: z.string() }),
|
|
980
|
+
* kind: 'delete',
|
|
981
|
+
* conflictHandling: {
|
|
982
|
+
* schema: z.object({ code: z.string() }),
|
|
983
|
+
* detectConflict: () => false,
|
|
984
|
+
* },
|
|
985
|
+
* execute: () => undefined,
|
|
986
|
+
* },
|
|
987
|
+
* };
|
|
988
|
+
* ```
|
|
989
|
+
*/
|
|
990
|
+
type DefineDocumentOfflineOperations<State extends ValidStoreState, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: DocumentOfflineOperationDefinition<State, TOperations[TName], TUploadRef> };
|
|
991
|
+
/**
|
|
992
|
+
* Collection offline entity reference.
|
|
993
|
+
*
|
|
994
|
+
* Collection operations return raw item payloads, which are normalized to the
|
|
995
|
+
* internal item key by the store.
|
|
996
|
+
*
|
|
997
|
+
* @typeParam ItemPayload - Collection item payload type for the owning store.
|
|
998
|
+
*/
|
|
999
|
+
type CollectionOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
|
|
1000
|
+
/**
|
|
1001
|
+
* Collection-store specific offline operation definition.
|
|
1002
|
+
*
|
|
1003
|
+
* @typeParam ItemState - Collection item state type for the owning store.
|
|
1004
|
+
* @typeParam ItemPayloadUnused - Collection payload type used to anchor the operation to the owning store type.
|
|
1005
|
+
* @typeParam TInput - Input type accepted by the offline operation.
|
|
1006
|
+
* @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
|
|
1007
|
+
* @typeParam TTempResult - Result returned by `execute`.
|
|
1008
|
+
* When `tempEntity` or `tempEntities` is provided, the pending builders must
|
|
1009
|
+
* return `ItemState`, and the reconciliation hooks must return an
|
|
1010
|
+
* `ItemPayload` plus optional `ItemState` replacement data.
|
|
1011
|
+
*/
|
|
1012
|
+
type CollectionOfflineOperationDefinition<ItemState extends ValidStoreState, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
|
|
1013
|
+
/**
|
|
1014
|
+
* Declares which collection items are affected by this queued mutation.
|
|
1015
|
+
*
|
|
1016
|
+
* Return the raw collection payloads for the affected items. The store will
|
|
1017
|
+
* convert each payload with the configured item key logic.
|
|
1018
|
+
*/
|
|
1019
|
+
getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[];
|
|
1020
|
+
/**
|
|
1021
|
+
* Declares which collection item refs must resolve before replaying this
|
|
1022
|
+
* operation.
|
|
1023
|
+
*/
|
|
1024
|
+
dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
|
|
1025
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
|
|
1026
|
+
} & ([ItemState | ItemPayloadUnused] extends [never] ? never : unknown);
|
|
1027
|
+
/**
|
|
1028
|
+
* Builds a collection offline operations map from a compact operation spec.
|
|
1029
|
+
*
|
|
1030
|
+
* Use this helper to define the full `persistentStorage.offline.operations` contract for a
|
|
1031
|
+
* collection store while keeping each operation's type declaration short.
|
|
1032
|
+
*
|
|
1033
|
+
* Each operation key is described with {@link DefineOfflineOperation}, and this
|
|
1034
|
+
* helper expands it into the corresponding
|
|
1035
|
+
* {@link CollectionOfflineOperationDefinition}. The runtime operation object
|
|
1036
|
+
* still needs to provide `getEntityRefs(...)`.
|
|
1037
|
+
*
|
|
1038
|
+
* @typeParam ItemState - Collection item state type for the owning store.
|
|
1039
|
+
* @typeParam ItemPayload - Collection payload type for the owning store.
|
|
1040
|
+
* @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
|
|
1041
|
+
*
|
|
1042
|
+
* @example
|
|
1043
|
+
* ```ts
|
|
1044
|
+
* type Operations = DefineCollectionOfflineOperations<
|
|
1045
|
+
* TodoItem,
|
|
1046
|
+
* string,
|
|
1047
|
+
* {
|
|
1048
|
+
* renameTodo: DefineOfflineOperation<
|
|
1049
|
+
* { id: string; title: string }
|
|
1050
|
+
* >;
|
|
1051
|
+
* createTodo: DefineOfflineOperation<
|
|
1052
|
+
* { title: string },
|
|
1053
|
+
* unknown,
|
|
1054
|
+
* { id: string; title: string }
|
|
1055
|
+
* >;
|
|
1056
|
+
* }
|
|
1057
|
+
* >;
|
|
1058
|
+
* ```
|
|
1059
|
+
*/
|
|
1060
|
+
type DefineCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: CollectionOfflineOperationDefinition<ItemState, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
|
|
1061
|
+
/**
|
|
1062
|
+
* List-query offline entity reference.
|
|
1063
|
+
*
|
|
1064
|
+
* List-query operations return raw item payloads, which are normalized to the
|
|
1065
|
+
* internal item key by the store.
|
|
1066
|
+
*
|
|
1067
|
+
* @typeParam ItemPayload - Item payload type for the owning list-query store.
|
|
1068
|
+
*/
|
|
1069
|
+
type ListQueryOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
|
|
1070
|
+
/**
|
|
1071
|
+
* List-query-store specific offline operation definition.
|
|
1072
|
+
*
|
|
1073
|
+
* @typeParam ItemState - List item state type for the owning store.
|
|
1074
|
+
* @typeParam QueryPayload - Query payload type used by the list store.
|
|
1075
|
+
* @typeParam ItemPayloadUnused - Item payload type used to anchor the operation to the owning store type.
|
|
1076
|
+
* @typeParam TInput - Input type accepted by the offline operation.
|
|
1077
|
+
* @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
|
|
1078
|
+
* @typeParam TTempResult - Result returned by `execute`.
|
|
1079
|
+
* When `tempEntity` or `tempEntities` is provided, the pending builders must
|
|
1080
|
+
* return `ItemState`, and the reconciliation hooks must return an
|
|
1081
|
+
* `ItemPayload` plus optional `ItemState` replacement data.
|
|
1082
|
+
*/
|
|
1083
|
+
type ListQueryOfflineOperationDefinition<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
|
|
1084
|
+
/**
|
|
1085
|
+
* Declares which list-query entities are affected by this queued mutation.
|
|
1086
|
+
*
|
|
1087
|
+
* Return the raw item payloads for the affected items. The store will
|
|
1088
|
+
* convert each payload with the configured item key logic.
|
|
1089
|
+
*/
|
|
1090
|
+
getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[];
|
|
1091
|
+
/**
|
|
1092
|
+
* Declares which list item refs must resolve before replaying this
|
|
1093
|
+
* operation.
|
|
1094
|
+
*/
|
|
1095
|
+
dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
|
|
1096
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
|
|
1097
|
+
} & ([ItemState | QueryPayload | ItemPayloadUnused] extends [never] ? never : unknown);
|
|
1098
|
+
/**
|
|
1099
|
+
* Builds a list-query offline operations map from a compact operation spec.
|
|
1100
|
+
*
|
|
1101
|
+
* Use this helper to define the full `persistentStorage.offline.operations` contract for a
|
|
1102
|
+
* list-query store while keeping each operation's type declaration short.
|
|
1103
|
+
*
|
|
1104
|
+
* Each operation key is described with {@link DefineOfflineOperation}, and this
|
|
1105
|
+
* helper expands it into the corresponding
|
|
1106
|
+
* {@link ListQueryOfflineOperationDefinition}. The runtime operation object
|
|
1107
|
+
* still needs to provide `getEntityRefs(...)`.
|
|
1108
|
+
*
|
|
1109
|
+
* @typeParam ItemState - List item state type for the owning store.
|
|
1110
|
+
* @typeParam QueryPayload - Query payload type used by the list store.
|
|
1111
|
+
* @typeParam ItemPayload - Item payload type used by the list store.
|
|
1112
|
+
* @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
|
|
1113
|
+
*
|
|
1114
|
+
* @example
|
|
1115
|
+
* ```ts
|
|
1116
|
+
* type Operations = DefineListQueryOfflineOperations<
|
|
1117
|
+
* User,
|
|
1118
|
+
* { tableId: 'users' },
|
|
1119
|
+
* { tableId: 'users'; id: number } | string,
|
|
1120
|
+
* {
|
|
1121
|
+
* renameUser: DefineOfflineOperation<
|
|
1122
|
+
* { id: number; name: string }
|
|
1123
|
+
* >;
|
|
1124
|
+
* createUser: DefineOfflineOperation<
|
|
1125
|
+
* { name: string },
|
|
1126
|
+
* unknown,
|
|
1127
|
+
* { id: number; name: string }
|
|
1128
|
+
* >;
|
|
1129
|
+
* }
|
|
1130
|
+
* >;
|
|
1131
|
+
* ```
|
|
1132
|
+
*/
|
|
1133
|
+
type DefineListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: ListQueryOfflineOperationDefinition<ItemState, QueryPayload, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
|
|
1134
|
+
/**
|
|
1135
|
+
* Extracts operation conflict payload from a registered operation map.
|
|
1136
|
+
*
|
|
1137
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1138
|
+
* @typeParam TName - Operation name whose conflict payload should be extracted.
|
|
1139
|
+
*/
|
|
1140
|
+
type OperationConflict<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
1141
|
+
conflictHandling?: OfflineConflictHandlingConfig<__LEGIT_ANY__, infer TConflict>;
|
|
1142
|
+
} ? TConflict : never;
|
|
1143
|
+
/**
|
|
1144
|
+
* Result returned when decoding a stored offline conflict payload.
|
|
1145
|
+
*
|
|
1146
|
+
* `ok: true` contains the typed conflict payload. `ok: false` contains a
|
|
1147
|
+
* machine-readable parse error describing why decoding was not possible.
|
|
1148
|
+
*/
|
|
1149
|
+
type ParsedOfflineResolutionConflictResultForOperation<TOperations, TName extends keyof TOperations & string> = Result<OperationConflict<TOperations, TName>, OfflineResolutionConflictParseError>;
|
|
1150
|
+
type ParsedOfflineResolutionConflictResultForStore<TOperations> = ParsedOfflineResolutionConflictResultForOperation<TOperations, keyof TOperations & string>;
|
|
1151
|
+
/**
|
|
1152
|
+
* Operation-aware offline resolution record for a specific registered operation.
|
|
1153
|
+
*
|
|
1154
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1155
|
+
* @typeParam TName - Operation name whose stored resolution shape should be extracted.
|
|
1156
|
+
*/
|
|
1157
|
+
type OfflineResolutionRecordForOperation<TOperations, TName extends keyof TOperations & string> = (OfflineConflictResolutionRecord<OperationConflict<TOperations, TName>, OperationInput<TOperations, TName>> & {
|
|
1158
|
+
operation: TName;
|
|
1159
|
+
}) | (OfflineRetryExhaustedResolutionRecord<OperationInput<TOperations, TName>> & {
|
|
1160
|
+
operation: TName;
|
|
1161
|
+
});
|
|
1162
|
+
/**
|
|
1163
|
+
* Union of operation-aware offline resolution records for an operation registry.
|
|
1164
|
+
*
|
|
1165
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1166
|
+
* @typeParam TName - Optional subset of operation names to include.
|
|
1167
|
+
*/
|
|
1168
|
+
type OfflineResolutionRecordForStore<TOperations, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: OfflineResolutionRecordForOperation<TOperations, K> }[TName];
|
|
1169
|
+
type OfflineResolutionConflictParseErrorCode = 'not-conflict' | 'offline-not-configured' | 'operation-not-found' | 'conflict-handling-missing' | 'invalid-conflict-payload';
|
|
1170
|
+
/** Error returned when decoding a stored offline conflict payload fails. */
|
|
1171
|
+
declare class OfflineResolutionConflictParseError extends Error {
|
|
1172
|
+
code: OfflineResolutionConflictParseErrorCode;
|
|
1173
|
+
operation: string;
|
|
1174
|
+
kind?: OfflineResolutionRecord['kind'];
|
|
1175
|
+
rawValue?: unknown;
|
|
1176
|
+
validationError?: SchemaValidationError;
|
|
1177
|
+
constructor(args: {
|
|
1178
|
+
code: OfflineResolutionConflictParseErrorCode;
|
|
1179
|
+
operation: string;
|
|
1180
|
+
kind?: OfflineResolutionRecord['kind'];
|
|
1181
|
+
rawValue?: unknown;
|
|
1182
|
+
validationError?: SchemaValidationError;
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
//#endregion
|
|
1186
|
+
//#region src/persistentStorage/types.d.ts
|
|
1187
|
+
type AsyncStorageNamespaceKind = 'document' | 'collection.item' | 'listQuery.item' | 'listQuery.query' | 'offline.queue' | 'offline.conflict' | 'offline.entity' | '__internal.protected';
|
|
1188
|
+
type AsyncStorageNamespaceScope = {
|
|
1189
|
+
sessionKey: string;
|
|
1190
|
+
storeName: string;
|
|
1191
|
+
kind: AsyncStorageNamespaceKind;
|
|
1192
|
+
};
|
|
1193
|
+
type AsyncStorageTouchMode = 'never' | 'coarse' | 'force';
|
|
1194
|
+
type AsyncStorageReadOptions = {
|
|
1195
|
+
touch?: AsyncStorageTouchMode;
|
|
1196
|
+
};
|
|
1197
|
+
type AsyncStorageMetadataOrder = 'key' | 'lru-asc' | 'lru-desc';
|
|
1198
|
+
type AsyncStorageEntryMetadataBase = {
|
|
1199
|
+
key: string;
|
|
1200
|
+
payloadRef: string;
|
|
1201
|
+
writtenAt: number;
|
|
1202
|
+
lastAccessAt: number; /** Serialized JSON size used for persistence budgeting for this entry. */
|
|
1203
|
+
sizeBytes?: number;
|
|
1204
|
+
version: number;
|
|
1205
|
+
};
|
|
1206
|
+
type AsyncStorageEntryMetadata<TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = AsyncStorageEntryMetadataBase & {
|
|
1207
|
+
customMetadata: TCustomMetadata;
|
|
1208
|
+
};
|
|
1209
|
+
type AsyncStorageNamespaceGetResult<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1210
|
+
value: TValue;
|
|
1211
|
+
metadata: AsyncStorageEntryMetadata<TCustomMetadata>;
|
|
1212
|
+
};
|
|
1213
|
+
type AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1214
|
+
key: string;
|
|
1215
|
+
value: TValue;
|
|
1216
|
+
serializedValue?: string;
|
|
1217
|
+
sizeBytes?: number;
|
|
1218
|
+
version: number;
|
|
1219
|
+
metadata?: TCustomMetadata;
|
|
1220
|
+
};
|
|
1221
|
+
type AsyncStorageNamespaceCommitTouch = {
|
|
1222
|
+
key: string;
|
|
1223
|
+
lastAccessAt?: number;
|
|
1224
|
+
};
|
|
1225
|
+
type AsyncStorageNamespaceStaticPolicy = {
|
|
1226
|
+
maxBytes?: number;
|
|
1227
|
+
pinnedKeys?: string[];
|
|
1228
|
+
};
|
|
1229
|
+
type AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1230
|
+
upserts?: AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata>[];
|
|
1231
|
+
removes?: string[];
|
|
1232
|
+
staticPolicy?: AsyncStorageNamespaceStaticPolicy | null;
|
|
1233
|
+
touches?: AsyncStorageNamespaceCommitTouch[];
|
|
1234
|
+
};
|
|
1235
|
+
type AsyncStorageDriverSetEntry = {
|
|
1236
|
+
key: string;
|
|
1237
|
+
value: unknown;
|
|
1238
|
+
serializedValue?: string;
|
|
1239
|
+
sizeBytes?: number;
|
|
1240
|
+
};
|
|
1241
|
+
type AsyncStorageDiscoveredScope = {
|
|
1242
|
+
/** Known raw record keys for this scope. `null` if keys were not enumerated during discovery. */knownRecordKeys: string[] | null;
|
|
1243
|
+
scope: AsyncStorageNamespaceScope;
|
|
1244
|
+
};
|
|
1245
|
+
/** Low-level async backend contract implemented by custom storage drivers. */
|
|
1246
|
+
type AsyncStorageDriver = {
|
|
1247
|
+
/** Read a single raw record from a logical namespace. */get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
|
|
1248
|
+
set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
|
|
1249
|
+
remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
|
|
1250
|
+
listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
|
|
1251
|
+
clear(scope: AsyncStorageNamespaceScope): Promise<void>; /** Namespace discovery used for cold cleanup, protected-key restore, and session clearing. */
|
|
1252
|
+
listScopes(sessionKey?: string): Promise<AsyncStorageNamespaceScope[]>; /** Returns discovered scopes together with known raw record keys. Used for cleanup. */
|
|
1253
|
+
listScopesWithKnownRecordKeys(sessionKey?: string): Promise<AsyncStorageDiscoveredScope[]>; /** Bulk read for multiple keys in a single call. */
|
|
1254
|
+
getMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<unknown[]>; /** Bulk write for multiple entries in a single call. */
|
|
1255
|
+
setMany(scope: AsyncStorageNamespaceScope, entries: AsyncStorageDriverSetEntry[]): Promise<void>; /** Bulk remove for multiple keys in a single call. */
|
|
1256
|
+
removeMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<void>;
|
|
1257
|
+
};
|
|
1258
|
+
type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1259
|
+
get(key: string, options?: AsyncStorageReadOptions): Promise<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>;
|
|
1260
|
+
getMany(keys: string[], options?: AsyncStorageReadOptions): Promise<Array<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>>;
|
|
1261
|
+
listKeys(): Promise<string[]>;
|
|
1262
|
+
commit(args: AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata>): Promise<void>;
|
|
1263
|
+
listMetadata(args?: {
|
|
1264
|
+
order?: AsyncStorageMetadataOrder;
|
|
1265
|
+
}): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
|
|
1266
|
+
listMetadataByFilter?(args: {
|
|
1267
|
+
filter: {
|
|
1268
|
+
equals: unknown;
|
|
1269
|
+
key: string;
|
|
1270
|
+
};
|
|
1271
|
+
order?: AsyncStorageMetadataOrder;
|
|
1272
|
+
}): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
|
|
1273
|
+
clear(): Promise<void>;
|
|
1274
|
+
};
|
|
1275
|
+
/** Managed async adapter consumed by TSDF persistence internals. */
|
|
1276
|
+
type AsyncStorageAdapter = {
|
|
1277
|
+
/** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
|
|
1278
|
+
openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
|
|
1279
|
+
readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
|
|
1280
|
+
syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
|
|
1281
|
+
clearSession(sessionKey: string): Promise<void>; /** Test-only reset hook used by TSDF internals. */
|
|
1282
|
+
resetForTests?(): void;
|
|
1283
|
+
};
|
|
1284
|
+
/** Injected persistent storage adapter. */
|
|
1285
|
+
type StorageAdapter = 'local-sync' | AsyncStorageAdapter;
|
|
1286
|
+
/** Standard Schema v1 (zod, valibot, arktype, etc.). */
|
|
1287
|
+
type StandardSchemaLike<T> = StandardSchemaV1<unknown, T>;
|
|
1288
|
+
/** Union of supported schema types for persistent storage validation. */
|
|
1289
|
+
type PersistentStorageSchema<T> = RcType<T> | StandardSchemaLike<T>;
|
|
1290
|
+
/**
|
|
1291
|
+
* Converts between the in-memory store data shape and the persisted storage shape.
|
|
1292
|
+
* Use this when the cached representation should differ from the API store format.
|
|
1293
|
+
*/
|
|
1294
|
+
type ConvertedPersistentStorageDataSchema<TFinal, TStorage> = {
|
|
1295
|
+
/** Schema for the final in-memory store data after hydration. */storeSchema: PersistentStorageSchema<TFinal>; /** Schema for the raw persisted storage representation. */
|
|
1296
|
+
storageSchema: PersistentStorageSchema<TStorage>; /** Converts in-memory store data into the persisted storage representation. */
|
|
1297
|
+
convertToStorage: (value: TFinal) => TStorage; /** Converts persisted storage data into the final in-memory store representation. */
|
|
1298
|
+
convertFromStorage: (value: TStorage) => TFinal;
|
|
1299
|
+
};
|
|
1300
|
+
/**
|
|
1301
|
+
* Schema configuration for persisted store data.
|
|
1302
|
+
* Accept either the final store schema directly or a converted storage format.
|
|
1303
|
+
*/
|
|
1304
|
+
type PersistentStorageDataSchema<TFinal, TStorage = unknown> = PersistentStorageSchema<TFinal> | ConvertedPersistentStorageDataSchema<TFinal, TStorage>;
|
|
1305
|
+
/** Result entry returned by explicit persistent-storage preload APIs. */
|
|
1306
|
+
type PersistentStoragePreloadResult<Payload extends ValidPayload = ValidPayload> = {
|
|
1307
|
+
/** Payload loaded from storage or fresh store initialization result. */payload: Payload; /** `true` when payload came from storage cache, `false` when loaded from source. */
|
|
1308
|
+
preloaded: boolean;
|
|
1309
|
+
};
|
|
1310
|
+
type PersistentStorageErrorHandler = (error: unknown) => void;
|
|
1311
|
+
/** Base config shared by all store types. */
|
|
1312
|
+
type PersistentStorageBaseConfig<TFinal, TStorage = unknown> = {
|
|
1313
|
+
/** Unique storage namespace used internally for this store's persisted entries. Must not contain `.`. */storeName: string; /** Injected adapter used to save and restore persistent data. Use `'local-sync'` for built-in localStorage or provide a custom async adapter. */
|
|
1314
|
+
adapter: StorageAdapter; /** Schema used to validate cached data on load and optionally convert persisted data. */
|
|
1315
|
+
schema: PersistentStorageDataSchema<TFinal, TStorage>; /** Optional version number for cache invalidation. When omitted, no version is persisted or checked. */
|
|
1316
|
+
version?: number;
|
|
1317
|
+
/**
|
|
1318
|
+
* Returns a session key scoping storage per org/tenant.
|
|
1319
|
+
* Return `false` to indicate the session is not ready — all storage
|
|
1320
|
+
* operations (load, save, clear) will be skipped until it returns a string.
|
|
1321
|
+
*/
|
|
1322
|
+
getSessionKey: () => string | false;
|
|
1323
|
+
/**
|
|
1324
|
+
* Called when a storage write operation fails (e.g. quota exceeded, OPFS write error).
|
|
1325
|
+
* Use this to log or report persistence failures to your error tracking service.
|
|
1326
|
+
*/
|
|
1327
|
+
onPersistentStorageError?: PersistentStorageErrorHandler | null;
|
|
1328
|
+
};
|
|
1329
|
+
/** Store-level persistent storage config. Session scoping comes from the parent store. */
|
|
1330
|
+
type StorePersistentStorageBaseConfig<TFinal, TStorage = unknown> = Omit<PersistentStorageBaseConfig<TFinal, TStorage>, 'getSessionKey' | 'storeName'>;
|
|
1331
|
+
type InternalDocumentOfflineOperations<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
|
|
1332
|
+
type DocumentOfflineOperationsConfig<State extends ValidStoreState> = InternalDocumentOfflineOperations<State> | null;
|
|
1333
|
+
type PublicStoreOfflineConfig<TOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> = Record<never, never>> = {
|
|
1334
|
+
/** Store-local offline operation definitions. Optional when only session-level offline controls are used. */operations?: TOperations;
|
|
1335
|
+
};
|
|
1336
|
+
type PublicStoreOfflineConfigField<TOfflineOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> | null> = {
|
|
1337
|
+
/** Optional offline sync/replay configuration for mutations. */offline?: TOfflineOperations extends null ? PublicStoreOfflineConfig : PublicStoreOfflineConfig<Exclude<TOfflineOperations, null>>;
|
|
1338
|
+
};
|
|
1339
|
+
/** Persistent storage config for DocumentStore. */
|
|
1340
|
+
type DocumentPersistentStorageConfig<State extends ValidStoreState, StorageState = unknown, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null> = StorePersistentStorageBaseConfig<State, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations>;
|
|
1341
|
+
type InternalCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
|
|
1342
|
+
getEntityRefs: (ctx: {
|
|
1343
|
+
input: __LEGIT_ANY__;
|
|
1344
|
+
}) => CollectionOfflineEntityRef<ItemPayload>[];
|
|
1345
|
+
dependsOn?: (ctx: {
|
|
1346
|
+
input: __LEGIT_ANY__;
|
|
1347
|
+
}) => CollectionOfflineEntityRef<ItemPayload>[];
|
|
1348
|
+
}> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
|
|
1349
|
+
type CollectionOfflineOperationsConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations<ItemState, ItemPayload> | null;
|
|
1350
|
+
type CollectionPersistentStorageFields<ItemPayload extends ValidPayload> = {
|
|
1351
|
+
/** Schema used to validate cached item payloads on load. */payloadSchema: PersistentStorageSchema<ItemPayload>;
|
|
1352
|
+
/**
|
|
1353
|
+
* Maximum serialized JSON size to persist for collection items. Budgeting
|
|
1354
|
+
* uses the serialized string length, not browser quota bytes. Items are
|
|
1355
|
+
* evicted via LRU. Defaults to 64 KB in `local-sync` and 128 KB in async
|
|
1356
|
+
* adapters.
|
|
1357
|
+
*/
|
|
1358
|
+
maxBytes?: number; /** Item payloads that should never be evicted from storage. */
|
|
1359
|
+
pinnedItems?: ItemPayload[];
|
|
1360
|
+
/**
|
|
1361
|
+
* Item payloads that should never be persisted or restored.
|
|
1362
|
+
* Accepts either an explicit payload list or a predicate function.
|
|
1363
|
+
* Takes precedence over `pinnedItems`.
|
|
1364
|
+
*/
|
|
1365
|
+
ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
|
|
1366
|
+
};
|
|
1367
|
+
/** Persistent storage config for CollectionStore. */
|
|
1368
|
+
type CollectionPersistentStorageConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & CollectionPersistentStorageFields<ItemPayload>;
|
|
1369
|
+
type InternalListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
|
|
1370
|
+
getEntityRefs: (ctx: {
|
|
1371
|
+
input: __LEGIT_ANY__;
|
|
1372
|
+
}) => ListQueryOfflineEntityRef<ItemPayload>[];
|
|
1373
|
+
dependsOn?: (ctx: {
|
|
1374
|
+
input: __LEGIT_ANY__;
|
|
1375
|
+
}) => ListQueryOfflineEntityRef<ItemPayload>[];
|
|
1376
|
+
}> & ([ItemState | QueryPayload | ItemPayload] extends [never] ? never : unknown);
|
|
1377
|
+
type ListQueryOfflineOperationsConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = InternalListQueryOfflineOperations<ItemState, QueryPayload, ItemPayload> | null;
|
|
1378
|
+
type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
|
|
1379
|
+
/** Schema used to validate cached item payloads on load. */itemPayloadSchema: PersistentStorageSchema<ItemPayload>; /** Schema used to validate cached query payloads on load. */
|
|
1380
|
+
queryPayloadSchema: PersistentStorageSchema<QueryPayload>;
|
|
1381
|
+
/**
|
|
1382
|
+
* Maximum serialized JSON size to persist for list items. Budgeting uses the
|
|
1383
|
+
* serialized string length, not browser quota bytes. Defaults to 64 KB in
|
|
1384
|
+
* `local-sync` and 128 KB in async adapters.
|
|
1385
|
+
*/
|
|
1386
|
+
maxItemBytes?: number;
|
|
1387
|
+
/**
|
|
1388
|
+
* Maximum serialized JSON size to persist for list queries. Budgeting uses
|
|
1389
|
+
* the serialized string length, not browser quota bytes. Defaults to 32 KB
|
|
1390
|
+
* in `local-sync` and 64 KB in async adapters.
|
|
1391
|
+
*/
|
|
1392
|
+
maxQueryBytes?: number; /** Maximum number of items per query to persist. Defaults to 100. */
|
|
1393
|
+
maxQuerySize?: number; /** Item payloads that should never be evicted from storage. */
|
|
1394
|
+
pinnedItems?: ItemPayload[]; /** Query payloads that should never be evicted from storage. */
|
|
1395
|
+
pinnedQueries?: QueryPayload[];
|
|
1396
|
+
/**
|
|
1397
|
+
* Item payloads that should never be persisted or restored.
|
|
1398
|
+
* Accepts either an explicit payload list or a predicate function.
|
|
1399
|
+
* Takes precedence over `pinnedItems`.
|
|
1400
|
+
*/
|
|
1401
|
+
ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
|
|
1402
|
+
};
|
|
1403
|
+
/** Persistent storage config for ListQueryStore. */
|
|
1404
|
+
type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
|
|
1405
|
+
//#endregion
|
|
1406
|
+
export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, StoreError as At, OfflineEntityMutationKind as B, RequestSchedulerEventData as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, ValidPayload as Ft, OfflineMutationQueueingPolicy as G, OfflineMutationInput as H, ScheduleFetchOptions as Ht, ListQueryOfflineOperationDefinition as I, ValidStoreState as It, OfflineReplayRetryConfig as J, OfflineOperationKind as K, OfflineAccumulationConfig as L, fetchTypePriority as Lt, DocumentOfflineOperationDefinition as M, StoreMutationError as Mt, GlobalOfflineEntity as N, StoreMutationErrorOptions as Nt, DefineCollectionOfflineOperations as O, MutationSkipped as Ot, GlobalOfflineStatus as P, TSDFStatus as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, mutationSkipped as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, ScheduleFetchResults as Ut, OfflineMutationDescriptor as V, RequestSchedulerEvents as Vt, OfflineMutationQueueingConfig as W, OfflineResolutionActionForOperation as X, OfflineResolutionAction as Y, OfflineResolutionConflictParseError as Z, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreFetchError as jt, DefineDocumentOfflineOperations as k, PayloadDebounce as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, FetchType as zt };
|