@bgub/fig 1.0.0 → 2.1.0

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/README.md +21 -22
  3. package/dist/{element-9MtOc5qb.d.ts → element-DT9ziqWN.d.ts} +49 -17
  4. package/dist/{element-CssKOG37.js → element-DpXdLgOZ.js} +11 -69
  5. package/dist/element-DpXdLgOZ.js.map +1 -0
  6. package/dist/{hooks-Blgy3bby.d.ts → hooks-GeZ4mX7W.d.ts} +15 -19
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +4 -4
  9. package/dist/internal.d.ts +7 -9
  10. package/dist/internal.js +8 -4
  11. package/dist/internal.js.map +1 -1
  12. package/dist/jsx-runtime.d.ts +1 -1
  13. package/dist/jsx-runtime.js +1 -1
  14. package/dist/payload-format-B9UbNtxo.js.map +1 -1
  15. package/dist/payload.d.ts +1 -1
  16. package/dist/payload.js +2 -2
  17. package/{dist-development/resource-Bt8LOhv4.js → dist/resource-DEDmLSNk.js} +20 -27
  18. package/dist/resource-DEDmLSNk.js.map +1 -0
  19. package/dist/{transition-B7vpLnb1.js → transition-BFLGYE4q.js} +433 -134
  20. package/dist/transition-BFLGYE4q.js.map +1 -0
  21. package/dist-development/{element-CKdh2VTU.js → element-DbzJUf5a.js} +11 -69
  22. package/dist-development/element-DbzJUf5a.js.map +1 -0
  23. package/dist-development/index.js +4 -4
  24. package/dist-development/internal.js +8 -4
  25. package/dist-development/internal.js.map +1 -1
  26. package/dist-development/jsx-runtime.js +1 -1
  27. package/dist-development/payload-format-B9UbNtxo.js.map +1 -1
  28. package/dist-development/payload.js +2 -2
  29. package/{dist/resource-BlZob4k1.js → dist-development/resource-BZOBllE_.js} +20 -27
  30. package/dist-development/resource-BZOBllE_.js.map +1 -0
  31. package/dist-development/{transition-DEVMhyYg.js → transition-CWjp9qRO.js} +430 -133
  32. package/dist-development/transition-CWjp9qRO.js.map +1 -0
  33. package/package.json +1 -1
  34. package/dist/element-CssKOG37.js.map +0 -1
  35. package/dist/resource-BlZob4k1.js.map +0 -1
  36. package/dist/transition-B7vpLnb1.js.map +0 -1
  37. package/dist-development/element-CKdh2VTU.js.map +0 -1
  38. package/dist-development/resource-Bt8LOhv4.js.map +0 -1
  39. package/dist-development/transition-DEVMhyYg.js.map +0 -1
@@ -1,5 +1,4 @@
1
- import { $ as getCurrentDataStore, Q as defineLoadContextCapabilities, Z as dataResourceKeysForError, et as isAttributableError, it as setCurrentDataStore, nt as markDataResourceError, rt as resolveCurrentDataStore } from "./element-CssKOG37.js";
2
- import { y as isThenable$1 } from "./resource-BlZob4k1.js";
1
+ import { y as isThenable$1 } from "./resource-DEDmLSNk.js";
3
2
  //#region src/context.ts
4
3
  /** The Fig context symbol. */
5
4
  const FigContextSymbol = Symbol.for("fig.context");
@@ -15,6 +14,61 @@ function isContext(value) {
15
14
  return typeof value === "function" && "$$typeof" in value && value.$$typeof === FigContextSymbol;
16
15
  }
17
16
  //#endregion
17
+ //#region src/data.ts
18
+ const LoadContextCapabilitiesSymbol = Symbol.for("fig.data-load-context");
19
+ /** Define load context capabilities. */
20
+ function defineLoadContextCapabilities(context, capabilities) {
21
+ Object.defineProperty(context, LoadContextCapabilitiesSymbol, {
22
+ configurable: true,
23
+ enumerable: false,
24
+ value: capabilities
25
+ });
26
+ }
27
+ /** Load context capabilities. */
28
+ function loadContextCapabilities(context) {
29
+ return context[LoadContextCapabilitiesSymbol];
30
+ }
31
+ const objectDataErrors = /* @__PURE__ */ new WeakMap();
32
+ let currentDataStore$1 = null;
33
+ /** Captures an optional data store for synchronous scope re-entry. */
34
+ function getCurrentDataStore() {
35
+ return currentDataStore$1;
36
+ }
37
+ /** Resolves current data store. */
38
+ function resolveCurrentDataStore(message = "Data resource APIs require a Fig data store.") {
39
+ if (currentDataStore$1 === null) throw new Error(message);
40
+ return currentDataStore$1;
41
+ }
42
+ /** Sets current data store. */
43
+ function setCurrentDataStore(store) {
44
+ const previousStore = currentDataStore$1;
45
+ currentDataStore$1 = store;
46
+ return previousStore;
47
+ }
48
+ /** Marks data resource error. */
49
+ function markDataResourceError(error, key) {
50
+ if (!isAttributableError(error)) return;
51
+ let keys = objectDataErrors.get(error);
52
+ if (keys === void 0) {
53
+ keys = [];
54
+ objectDataErrors.set(error, keys);
55
+ }
56
+ if (keys.some((existing) => sameDataResourceKey(existing, key))) return;
57
+ keys.push(key);
58
+ }
59
+ /** Data resource keys for error. */
60
+ function dataResourceKeysForError(error) {
61
+ if (!isAttributableError(error)) return void 0;
62
+ const keys = objectDataErrors.get(error);
63
+ return keys === void 0 || keys.length === 0 ? void 0 : [...keys];
64
+ }
65
+ function sameDataResourceKey(a, b) {
66
+ return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
67
+ }
68
+ function isAttributableError(value) {
69
+ return (typeof value === "object" || typeof value === "function") && value !== null;
70
+ }
71
+ //#endregion
18
72
  //#region src/data-store.ts
19
73
  const DataResourceSymbol = Symbol.for("fig.data-resource");
20
74
  const DataStoreFactorySymbol = Symbol.for("fig.data-store-factory");
@@ -28,34 +82,13 @@ function dataResource(options) {
28
82
  $$typeof: DataResourceSymbol,
29
83
  [DataStoreFactorySymbol]: dataStoreFactory,
30
84
  debugArgs: options.debugArgs,
85
+ equals: options.equals,
86
+ inactiveRetentionMs: options.inactiveRetentionMs,
31
87
  key: options.key,
32
- load: options.load
88
+ load: options.load,
89
+ watch: options.watch
33
90
  };
34
91
  }
35
- /** Ensures data. */
36
- function ensureData(resource, ...args) {
37
- return resolveDataMutationStore("ensureData").ensureData(resource, ...args);
38
- }
39
- /** Invalidates data. */
40
- function invalidateData(resource, ...args) {
41
- resolveDataMutationStore("invalidateData").invalidateData(resource, ...args);
42
- }
43
- /** Invalidates data error. */
44
- function invalidateDataError(error) {
45
- return resolveDataMutationStore("invalidateDataError").invalidateDataError(error);
46
- }
47
- /** Invalidates data key. */
48
- function invalidateDataKey(key) {
49
- resolveDataMutationStore("invalidateDataKey").invalidateDataKey(key);
50
- }
51
- /** Invalidates data prefix. */
52
- function invalidateDataPrefix(prefix) {
53
- resolveDataMutationStore("invalidateDataPrefix").invalidateDataPrefix(prefix);
54
- }
55
- /** Refreshes data. */
56
- function refreshData(resource, ...args) {
57
- return resolveDataMutationStore("refreshData").refreshData(resource, ...args);
58
- }
59
92
  /** Reads data store. */
60
93
  function readDataStore() {
61
94
  return resolveCurrentDataStore("readDataStore() must be called synchronously while Fig is executing — during render, an event handler, an action, or an effect. Capture the handle there and use it after awaits.");
@@ -65,8 +98,10 @@ function createDataStore(options = {}) {
65
98
  const state = { host: null };
66
99
  const store = createRendererDataStore({
67
100
  getLane: () => state.host === null ? null : state.host.getLane(),
68
- partition: options.partition,
69
- schedule: (owner, lane) => state.host?.schedule(owner, lane)
101
+ schedule: (owner, lane) => state.host?.schedule(owner, lane),
102
+ get watchSources() {
103
+ return state.host?.watchSources === true;
104
+ }
70
105
  });
71
106
  Object.defineProperty(store, DataStoreControllerSymbol, { value: state });
72
107
  if (options.initialData !== void 0) store.hydrate(options.initialData);
@@ -78,16 +113,13 @@ function isDataStoreController(value) {
78
113
  }
79
114
  /** Attach data store. */
80
115
  function attachDataStore(controller, host, initialData) {
81
- if (host.partition !== void 0 || initialData !== void 0) throw new Error("Pass partition and initialData to createDataStore(), not the renderer, when adopting a data store.");
116
+ if (initialData !== void 0) throw new Error("Pass initialData to createDataStore(), not the renderer, when adopting a data store.");
82
117
  const state = controller[DataStoreControllerSymbol];
83
118
  if (state === void 0) throw new Error("dataStore must be created with createDataStore().");
84
119
  if (state.host !== null) throw new Error("A data store can only be adopted by one Fig renderer.");
85
120
  state.host = host;
86
121
  return controller;
87
122
  }
88
- function resolveDataMutationStore(name) {
89
- return resolveCurrentDataStore(`${name}() must be called synchronously while Fig is executing — during render, an event handler, an action, or an effect. Capture readDataStore() (or root.data) synchronously and call the handle instead.`);
90
- }
91
123
  /** Creates renderer data store. */
92
124
  function createRendererDataStore(host) {
93
125
  return new DefaultDataStore(host);
@@ -101,22 +133,27 @@ var DefaultDataStore = class {
101
133
  entries = /* @__PURE__ */ new Map();
102
134
  inactiveRetentionMs;
103
135
  ownerKeys = /* @__PURE__ */ new WeakMap();
104
- pendingOwnerKeys = /* @__PURE__ */ new WeakMap();
105
- partitionKey;
106
136
  preloadRetentionMs;
107
137
  disposed = false;
138
+ pendingWatchReconciles = null;
108
139
  constructor(host) {
109
140
  this.host = host;
110
141
  this.inactiveRetentionMs = host.inactiveRetentionMs ?? DEFAULT_INACTIVE_RETENTION_MS;
111
- this.partitionKey = host.partition === void 0 ? "" : encodeValue(host.partition, createEncodePath("partition"));
112
142
  this.preloadRetentionMs = host.preloadRetentionMs ?? DEFAULT_PRELOAD_RETENTION_MS;
113
143
  }
114
- commitDataDependencies(owner, previousOwner) {
115
- const nextKeys = this.pendingOwnerKeys.get(owner) ?? null;
144
+ areDataDependenciesConsistent(reads) {
145
+ for (const [key, snapshot] of reads) {
146
+ if (snapshot === void 0) continue;
147
+ const entry = this.entries.get(key);
148
+ if (entry === void 0 || !entryHasValue(entry) || !Object.is(snapshot.value, entry.value)) return false;
149
+ }
150
+ return true;
151
+ }
152
+ commitDataDependencies(owner, previousOwner, reads) {
153
+ const nextKeys = reads === void 0 ? null : new Set(reads.keys());
116
154
  const ownerKeys = this.ownerKeys.get(owner) ?? null;
117
155
  const previousOwnerKeys = previousOwner === null ? null : this.ownerKeys.get(previousOwner) ?? null;
118
- this.pendingOwnerKeys.delete(owner);
119
- if ((nextKeys === null || nextKeys.size === 0) && ownerKeys === null && previousOwnerKeys === null) return;
156
+ if ((nextKeys === null || nextKeys.size === 0) && ownerKeys === null && previousOwnerKeys === null) return true;
120
157
  let orphanCandidates = null;
121
158
  orphanCandidates = this.collectSubscribedEntries(ownerKeys, orphanCandidates);
122
159
  orphanCandidates = this.collectSubscribedEntries(previousOwnerKeys, orphanCandidates);
@@ -129,22 +166,26 @@ var DefaultDataStore = class {
129
166
  if (entry !== void 0) {
130
167
  this.clearInactiveTimer(entry);
131
168
  entry.subscribers.add(owner);
169
+ if (reads !== void 0) entry.retainers?.delete(reads);
132
170
  this.notifyEntryChange(entry);
133
171
  }
134
172
  }
135
173
  }
136
174
  if (orphanCandidates !== null) for (const entry of orphanCandidates) this.abortOrphanedLoad(entry);
175
+ if (nextKeys !== null) for (const key of nextKeys) {
176
+ const entry = this.entries.get(key);
177
+ if (entry !== void 0) this.scheduleWatchReconcile(entry);
178
+ }
179
+ const consistent = reads === void 0 || this.areDataDependenciesConsistent(reads);
180
+ reads?.clear();
181
+ return consistent;
137
182
  }
138
183
  releaseDataOwner(owner) {
139
184
  const orphanCandidates = this.collectSubscribedEntries(this.ownerKeys.get(owner) ?? null, null);
140
185
  this.deleteDataOwner(owner);
141
186
  if (orphanCandidates !== null) for (const entry of orphanCandidates) this.abortOrphanedLoad(entry);
142
187
  }
143
- resetDataDependencies(owner) {
144
- this.pendingOwnerKeys.delete(owner);
145
- }
146
188
  deleteDataOwner(owner, retainedKeys = null) {
147
- this.pendingOwnerKeys.delete(owner);
148
189
  const keys = this.ownerKeys.get(owner);
149
190
  if (keys === void 0) return;
150
191
  this.ownerKeys.delete(owner);
@@ -153,7 +194,10 @@ var DefaultDataStore = class {
153
194
  if (entry === void 0) continue;
154
195
  entry.subscribers.delete(owner);
155
196
  this.notifyEntryChange(entry);
156
- if (retainedKeys?.has(key) !== true) this.scheduleInactiveCleanup(entry);
197
+ if (retainedKeys?.has(key) !== true) {
198
+ this.scheduleInactiveCleanup(entry);
199
+ this.scheduleWatchReconcile(entry);
200
+ }
157
201
  }
158
202
  }
159
203
  collectSubscribedEntries(keys, into) {
@@ -168,8 +212,8 @@ var DefaultDataStore = class {
168
212
  return into;
169
213
  }
170
214
  abortOrphanedLoad(entry) {
171
- if (this.entries.get(entry.storeKey) !== entry) return;
172
- if (entry.subscribers.size > 0 || entry.preloadTimer !== null || entry.ensureRetainers > 0 || entry.pending === null || entryHasValue(entry)) return;
215
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
216
+ if (isHeld(entry) || entry.preloadTimer !== null || entry.pending === null || entryHasValue(entry)) return;
173
217
  this.evictEntry(entry, "evicted");
174
218
  }
175
219
  dispose() {
@@ -182,27 +226,39 @@ var DefaultDataStore = class {
182
226
  }
183
227
  }
184
228
  hydrate(entries) {
229
+ this.hydrateEntries(entries, true);
230
+ }
231
+ hydrateMissing(entries) {
232
+ this.hydrateEntries(entries, false);
233
+ }
234
+ hydrateEntries(entries, replaceValues) {
185
235
  if (this.disposed) return;
186
236
  for (const hydrated of entries) {
237
+ if (this.disposed) return;
187
238
  const normalized = normalizeKey(hydrated.key);
188
- const storeKey = this.storeKey(normalized.canonical);
239
+ const storeKey = normalized.canonical;
189
240
  const current = this.entries.get(storeKey);
190
241
  if (current !== void 0) {
191
- this.hydrateEntry(current, normalized.key, hydrated.value);
192
- this.publish(current);
242
+ if (replaceValues || !entryHasValue(current)) this.hydrateEntry(current, normalized.key, hydrated.value);
193
243
  continue;
194
244
  }
195
- const entry = this.createEntry(normalized, storeKey, null, null, "fulfilled", hydrated.value);
245
+ const entry = this.createEntry(normalized, null, null, "fulfilled", hydrated.value);
196
246
  this.entries.set(storeKey, entry);
197
247
  this.notifyEntryChange(entry);
198
248
  }
199
249
  }
200
250
  snapshot() {
251
+ return this.snapshotKeys(this.entries.keys());
252
+ }
253
+ snapshotKeys(canonicalKeys) {
201
254
  const entries = [];
202
- for (const entry of this.entries.values()) if (entryHasValue(entry)) entries.push({
203
- key: entry.key,
204
- value: entry.value
205
- });
255
+ for (const key of canonicalKeys) {
256
+ const entry = this.entries.get(key);
257
+ if (entry !== void 0 && entryHasValue(entry)) entries.push({
258
+ key: entry.key,
259
+ value: entry.value
260
+ });
261
+ }
206
262
  return entries;
207
263
  }
208
264
  inspectDataEntries() {
@@ -242,8 +298,12 @@ var DefaultDataStore = class {
242
298
  for (const entry of this.entries.values()) if (canonicalKeyStartsWith(entry.canonicalKey, prefixCanonical)) entries.push(entry);
243
299
  this.invalidateEntries(entries);
244
300
  }
245
- async ensureData(resource, ...args) {
301
+ ensureData(resource, ...args) {
302
+ return this.ensureDataUntil(resource, args, void 0);
303
+ }
304
+ async ensureDataUntil(resource, args, until) {
246
305
  for (;;) {
306
+ if (until?.aborted === true) throw until.reason;
247
307
  if (this.disposed) throw new Error("ensureData() requires a live data store; this store was disposed.");
248
308
  const entry = this.entryFor(resource, args, true);
249
309
  this.clearInactiveTimer(entry);
@@ -253,16 +313,24 @@ var DefaultDataStore = class {
253
313
  return entry.value;
254
314
  }
255
315
  if (entry.status === "rejected") throwDataResourceError(entry);
256
- entry.ensureRetainers += 1;
316
+ const retainer = {};
317
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(retainer);
257
318
  try {
258
- if (entry.pending !== null) await entry.pending.promise;
259
- else await this.startLoad(entry, resource, args, {
319
+ this.recordWatchSource(entry, resource, args);
320
+ let settled;
321
+ if (entry.pending !== null) settled = entry.pending.promise;
322
+ else if (this.waitsOnWatch(resource)) settled = this.beginWatchPending(entry).promise;
323
+ else settled = this.startLoad(entry, resource, args, {
260
324
  lane: this.host.getLane(),
261
325
  refresh: false
262
326
  });
327
+ await (until === void 0 ? settled : untilAborted(settled, until));
263
328
  } finally {
264
- entry.ensureRetainers -= 1;
265
- if (this.entries.get(entry.storeKey) === entry) this.retainPreload(entry);
329
+ entry.retainers?.delete(retainer);
330
+ if (this.entries.get(entry.canonicalKey) === entry) {
331
+ this.retainPreload(entry);
332
+ this.scheduleWatchReconcile(entry);
333
+ }
266
334
  }
267
335
  }
268
336
  }
@@ -278,17 +346,24 @@ var DefaultDataStore = class {
278
346
  refresh: entry.status === "fulfilled"
279
347
  });
280
348
  }
281
- readData(resource, args, owner) {
349
+ readData(resource, args, reads) {
282
350
  const entry = this.entryFor(resource, args, true);
283
351
  this.clearInactiveTimer(entry);
284
352
  this.clearPreloadTimer(entry);
285
- this.addOwnerKey(owner, entry.storeKey);
353
+ if (reads !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
354
+ if (reads !== void 0 && !reads.has(entry.canonicalKey)) reads.set(entry.canonicalKey, void 0);
355
+ this.recordWatchSource(entry, resource, args);
286
356
  this.revalidateIfStale(entry, resource, args);
287
- if (entry.status === "pending" && entry.pending === null) this.startLoad(entry, resource, args, {
288
- lane: this.host.getLane(),
289
- refresh: false
290
- });
291
- return this.readCurrentValue(entry);
357
+ if (entry.status === "pending" && entry.pending === null) {
358
+ if (this.waitsOnWatch(resource)) this.beginWatchPending(entry);
359
+ else this.startLoad(entry, resource, args, {
360
+ lane: this.host.getLane(),
361
+ refresh: false
362
+ });
363
+ }
364
+ const value = this.readCurrentValue(entry);
365
+ if (reads !== void 0 && reads.get(entry.canonicalKey) === void 0) reads.set(entry.canonicalKey, { value });
366
+ return value;
292
367
  }
293
368
  refreshData(resource, ...args) {
294
369
  if (this.disposed) return Promise.resolve({
@@ -318,29 +393,25 @@ var DefaultDataStore = class {
318
393
  setCurrentDataStore(previousStore);
319
394
  }
320
395
  }
321
- addOwnerKey(owner, key) {
322
- let keys = this.pendingOwnerKeys.get(owner);
323
- if (keys === void 0) {
324
- keys = /* @__PURE__ */ new Set();
325
- this.pendingOwnerKeys.set(owner, keys);
326
- }
327
- keys.add(key);
328
- }
329
396
  entryFor(resource, args, create) {
330
397
  const normalized = normalizeKey(resource.key(...args));
331
398
  const fingerprint = null;
332
- const key = this.storeKey(normalized.canonical);
399
+ const key = normalized.canonical;
333
400
  const current = this.entries.get(key);
334
- if (current !== void 0) return current;
401
+ if (current !== void 0) {
402
+ if (resource.inactiveRetentionMs !== void 0) current.inactiveRetentionMs = resource.inactiveRetentionMs;
403
+ return current;
404
+ }
335
405
  if (!create) return null;
336
- const entry = this.createEntry(normalized, key, resource, fingerprint, "pending", void 0);
406
+ const entry = this.createEntry(normalized, resource, fingerprint, "pending", void 0);
407
+ entry.inactiveRetentionMs = resource.inactiveRetentionMs;
337
408
  if (this.disposed) return entry;
338
409
  this.entries.set(key, entry);
339
410
  this.notifyEntryChange(entry);
340
411
  return entry;
341
412
  }
342
413
  revalidateIfStale(entry, resource, args) {
343
- if (entry.status !== "fulfilled" || !entry.stale || entry.pending !== null || entry.refreshError !== void 0 || resource.load === void 0) return;
414
+ if (entry.status !== "fulfilled" || !entry.stale || entry.pending !== null || entry.refreshFailed || resource.load === void 0) return;
344
415
  this.startLoad(entry, resource, args, {
345
416
  lane: this.host.getLane(),
346
417
  refresh: true
@@ -348,49 +419,230 @@ var DefaultDataStore = class {
348
419
  }
349
420
  entryForKey(key) {
350
421
  const normalized = normalizeKey(key);
351
- return this.entries.get(this.storeKey(normalized.canonical)) ?? null;
422
+ return this.entries.get(normalized.canonical) ?? null;
352
423
  }
353
- createEntry(normalized, storeKey, resource, fingerprint, status, value) {
424
+ createEntry(normalized, resource, fingerprint, status, value) {
354
425
  return {
355
426
  canonicalKey: normalized.canonical,
356
- controller: null,
357
- ensureRetainers: 0,
427
+ retainers: null,
358
428
  error: void 0,
359
429
  fingerprint,
360
- generation: 0,
361
430
  invalidationVersion: 0,
431
+ inactiveRetentionMs: void 0,
362
432
  inactiveTimer: null,
363
433
  key: normalized.key,
364
434
  lane: null,
365
435
  pending: null,
366
436
  preloadTimer: null,
367
437
  refreshError: void 0,
438
+ refreshFailed: false,
368
439
  resource,
369
440
  stale: false,
370
441
  status,
371
- storeKey,
372
442
  subscribers: /* @__PURE__ */ new Set(),
373
443
  value,
374
444
  valueController: null,
375
- valueErrors: /* @__PURE__ */ new WeakSet()
445
+ valueErrors: /* @__PURE__ */ new WeakSet(),
446
+ watchController: null,
447
+ watchSource: null
448
+ };
449
+ }
450
+ recordWatchSource(entry, resource, args) {
451
+ if (resource.watch === void 0 || entry.watchSource !== null) return;
452
+ entry.watchSource = {
453
+ args,
454
+ resource
455
+ };
456
+ }
457
+ waitsOnWatch(resource) {
458
+ return resource.load === void 0 && resource.watch !== void 0 && this.host.watchSources === true;
459
+ }
460
+ beginWatchPending(entry) {
461
+ if (entry.pending !== null) return entry.pending;
462
+ const pending = createPendingLoad(new AbortController());
463
+ pending.watch = true;
464
+ entry.pending = pending;
465
+ entry.status = "pending";
466
+ this.notifyEntryChange(entry);
467
+ this.scheduleWatchReconcile(entry);
468
+ return pending;
469
+ }
470
+ dependentHandle(signal) {
471
+ const retain = (entry) => {
472
+ if (signal.aborted || entry.retainers?.has(signal)) return;
473
+ (entry.retainers ??= /* @__PURE__ */ new Set()).add(signal);
474
+ this.clearInactiveTimer(entry);
475
+ signal.addEventListener("abort", () => this.releaseRetainer(entry, signal), { once: true });
476
+ };
477
+ return {
478
+ ensureData: (resource, ...args) => {
479
+ if (signal.aborted) return Promise.reject(signal.reason);
480
+ if (!this.disposed) {
481
+ const entry = this.entryFor(resource, args, true);
482
+ this.recordWatchSource(entry, resource, args);
483
+ retain(entry);
484
+ this.scheduleWatchReconcile(entry);
485
+ }
486
+ return this.ensureDataUntil(resource, args, signal);
487
+ },
488
+ hydrate: (entries) => this.hydrate(entries),
489
+ invalidateData: (resource, ...args) => this.invalidateData(resource, ...args),
490
+ invalidateDataError: (error) => this.invalidateDataError(error),
491
+ invalidateDataKey: (key) => this.invalidateDataKey(key),
492
+ invalidateDataPrefix: (prefix) => this.invalidateDataPrefix(prefix),
493
+ preloadData: (resource, ...args) => this.preloadData(resource, ...args),
494
+ refreshData: (resource, ...args) => this.refreshData(resource, ...args),
495
+ run: (callback) => this.run(callback)
496
+ };
497
+ }
498
+ keepEqualValue(entry, stale) {
499
+ entry.error = void 0;
500
+ entry.pending = null;
501
+ entry.refreshError = void 0;
502
+ entry.refreshFailed = false;
503
+ entry.stale = stale;
504
+ entry.status = "fulfilled";
505
+ this.notifyEntryChange(entry);
506
+ this.scheduleInactiveCleanup(entry);
507
+ }
508
+ scheduleWatchReconcile(entry) {
509
+ if (entry.watchSource === null && entry.watchController === null) return;
510
+ if (this.pendingWatchReconciles !== null) {
511
+ this.pendingWatchReconciles.add(entry);
512
+ return;
513
+ }
514
+ const entries = /* @__PURE__ */ new Set([entry]);
515
+ this.pendingWatchReconciles = entries;
516
+ queueMicrotask(() => {
517
+ this.pendingWatchReconciles = null;
518
+ for (const pending of entries) this.reconcileWatch(pending);
519
+ });
520
+ }
521
+ wantsWatch(entry) {
522
+ const source = entry.watchSource;
523
+ if (source === null || this.disposed || this.host.watchSources !== true || this.entries.get(entry.canonicalKey) !== entry) return false;
524
+ if (entry.subscribers.size > 0) return true;
525
+ return source.resource.load === void 0 && isHeld(entry);
526
+ }
527
+ reconcileWatch(entry) {
528
+ const wanted = this.wantsWatch(entry);
529
+ if (wanted && entry.watchController === null) this.startWatch(entry);
530
+ else if (!wanted && entry.watchController !== null) this.stopWatch(entry, "released");
531
+ if (!wanted && entry.pending?.watch === true && !isHeld(entry)) this.evictEntry(entry, "evicted");
532
+ }
533
+ holdDataRead(reads, canonicalKey) {
534
+ if (!reads.has(canonicalKey)) reads.set(canonicalKey, void 0);
535
+ const entry = this.entries.get(canonicalKey);
536
+ if (entry !== void 0) (entry.retainers ??= /* @__PURE__ */ new Set()).add(reads);
537
+ }
538
+ releaseDataReads(reads) {
539
+ for (const key of reads.keys()) {
540
+ const entry = this.entries.get(key);
541
+ if (entry !== void 0) this.releaseRetainer(entry, reads);
542
+ }
543
+ }
544
+ releaseRetainer(entry, owner) {
545
+ if (!entry.retainers?.delete(owner) || this.entries.get(entry.canonicalKey) !== entry) return;
546
+ this.scheduleInactiveCleanup(entry);
547
+ this.scheduleWatchReconcile(entry);
548
+ }
549
+ startWatch(entry) {
550
+ const source = entry.watchSource;
551
+ const watch = source?.resource.watch;
552
+ if (source === null || watch === void 0) return;
553
+ const controller = new AbortController();
554
+ entry.watchController = controller;
555
+ this.notifyEntryChange(entry);
556
+ const context = this.createWatchContext(entry, source, controller);
557
+ try {
558
+ watch(...source.args, context);
559
+ } catch (error) {
560
+ context.fail(error);
561
+ }
562
+ }
563
+ stopWatch(entry, reason) {
564
+ const controller = entry.watchController;
565
+ if (controller === null) return;
566
+ entry.watchController = null;
567
+ if (reason === "released" && entryHasValue(entry)) entry.stale = true;
568
+ this.notifyEntryChange(entry);
569
+ controller.abort(reason);
570
+ }
571
+ createWatchContext(entry, source, controller) {
572
+ const live = () => !this.disposed && !controller.signal.aborted && this.entries.get(entry.canonicalKey) === entry;
573
+ return {
574
+ data: this.dependentHandle(controller.signal),
575
+ signal: controller.signal,
576
+ publish: (value) => {
577
+ if (!live()) return;
578
+ const equals = source.resource.equals ?? Object.is;
579
+ if (entryHasValue(entry) && equals(entry.value, value)) {
580
+ const pending = entry.pending;
581
+ entry.invalidationVersion = 0;
582
+ entry.lane = null;
583
+ this.keepEqualValue(entry, false);
584
+ pending?.resolve(abortedRefreshResult(entry, "superseded"));
585
+ pending?.controller.abort("superseded");
586
+ return;
587
+ }
588
+ this.hydrateEntry(entry, entry.key, value);
589
+ this.scheduleWatchReconcile(entry);
590
+ },
591
+ fail: (error) => {
592
+ if (!live()) return;
593
+ this.failWatchedEntry(entry, error);
594
+ },
595
+ refresh: () => {
596
+ if (live()) return this.refreshData(source.resource, ...source.args);
597
+ const reason = this.disposed ? "store-disposed" : controller.signal.reason === "released" ? "released" : "evicted";
598
+ return Promise.resolve(abortedRefreshResult(entry, reason));
599
+ },
600
+ invalidate: () => {
601
+ if (!live()) return;
602
+ this.invalidateEntry(entry, this.host.getLane());
603
+ }
376
604
  };
377
605
  }
606
+ failWatchedEntry(entry, error) {
607
+ if (entryHasValue(entry)) {
608
+ entry.refreshError = error;
609
+ entry.refreshFailed = true;
610
+ entry.stale = true;
611
+ this.publish(entry);
612
+ return;
613
+ }
614
+ const pending = entry.pending;
615
+ entry.pending = null;
616
+ entry.error = error;
617
+ entry.status = "rejected";
618
+ markDataResourceError(error, entry.key);
619
+ pending?.resolve({
620
+ error,
621
+ status: "rejected"
622
+ });
623
+ this.publish(entry);
624
+ pending?.controller.abort(error);
625
+ }
378
626
  hydrateEntry(entry, key, value) {
379
627
  this.clearInactiveTimer(entry);
380
- this.abortEntryGenerations(entry, "superseded");
628
+ const valueController = entry.valueController;
629
+ const pending = entry.pending;
630
+ entry.valueController = null;
631
+ entry.pending = null;
381
632
  entry.error = void 0;
382
- entry.generation += 1;
383
633
  entry.valueErrors = /* @__PURE__ */ new WeakSet();
384
634
  entry.invalidationVersion = 0;
385
635
  entry.key = key;
386
636
  entry.lane = null;
387
637
  entry.refreshError = void 0;
638
+ entry.refreshFailed = false;
388
639
  entry.stale = false;
389
640
  entry.status = "fulfilled";
390
641
  entry.value = value;
391
- }
392
- storeKey(canonicalKey) {
393
- return this.partitionKey === "" ? canonicalKey : `${this.partitionKey}:${canonicalKey}`;
642
+ pending?.resolve(abortedRefreshResult(entry, "superseded"));
643
+ this.publish(entry);
644
+ pending?.controller.abort("superseded");
645
+ valueController?.abort("superseded");
394
646
  }
395
647
  startLoad(entry, resource, args, options) {
396
648
  const hadValue = entryHasValue(entry);
@@ -404,18 +656,18 @@ var DefaultDataStore = class {
404
656
  this.notifyEntryChange(entry);
405
657
  return Promise.resolve(unsupportedRefreshResult(entry));
406
658
  }
407
- this.abortPendingLoad(entry, "superseded");
659
+ const previousPending = entry.pending;
408
660
  const controller = new AbortController();
409
661
  const valueErrors = /* @__PURE__ */ new WeakSet();
410
- const generation = entry.generation + 1;
411
662
  const invalidationVersion = entry.invalidationVersion;
412
- const pending = createPendingResult();
413
- entry.controller = controller;
414
- entry.generation = generation;
663
+ const pending = createPendingLoad(controller);
415
664
  entry.lane = options.lane;
416
665
  entry.pending = pending;
417
666
  entry.status = options.refresh && hadValue ? "refreshing" : "pending";
667
+ previousPending?.resolve(abortedRefreshResult(entry, "superseded"));
668
+ previousPending?.controller.abort("superseded");
418
669
  this.notifyEntryChange(entry);
670
+ if (controller.signal.aborted) return pending.promise;
419
671
  let loaded;
420
672
  try {
421
673
  loaded = load(...args, this.createLoadContext(entry, controller, valueErrors));
@@ -428,64 +680,89 @@ var DefaultDataStore = class {
428
680
  return result;
429
681
  };
430
682
  const fulfill = (value) => {
431
- if (entry.generation !== generation || controller.signal.aborted) return settleAborted();
683
+ if (entry.pending !== pending || controller.signal.aborted) return settleAborted();
684
+ const equals = resource.equals ?? Object.is;
685
+ let equal;
686
+ try {
687
+ equal = entryHasValue(entry) && equals(entry.value, value);
688
+ } catch (error) {
689
+ return reject(error);
690
+ }
691
+ if (equal) {
692
+ this.keepEqualValue(entry, entry.invalidationVersion !== invalidationVersion);
693
+ const result = {
694
+ status: "fulfilled",
695
+ value: entry.value
696
+ };
697
+ pending.resolve(result);
698
+ controller.abort("superseded");
699
+ return result;
700
+ }
432
701
  const superseded = entry.valueController;
433
- entry.controller = null;
434
702
  entry.valueController = controller;
435
703
  entry.valueErrors = valueErrors;
436
704
  entry.error = void 0;
437
705
  entry.pending = null;
438
706
  entry.refreshError = void 0;
707
+ entry.refreshFailed = false;
439
708
  entry.stale = entry.invalidationVersion !== invalidationVersion;
440
709
  entry.status = "fulfilled";
441
710
  entry.value = value;
442
- this.publish(entry);
443
- superseded?.abort("superseded");
444
711
  const result = {
445
712
  status: "fulfilled",
446
713
  value
447
714
  };
448
715
  pending.resolve(result);
716
+ this.publish(entry);
717
+ superseded?.abort("superseded");
449
718
  return result;
450
719
  };
451
720
  const reject = (error) => {
452
- if (entry.generation !== generation || controller.signal.aborted) return settleAborted();
453
- entry.controller = null;
454
- controller.abort(error);
721
+ if (entry.pending !== pending || controller.signal.aborted) return settleAborted();
455
722
  entry.pending = null;
456
723
  if (hadValue && entryHasValue(entry)) {
457
724
  entry.refreshError = error;
725
+ entry.refreshFailed = true;
458
726
  entry.stale = true;
459
727
  entry.status = "fulfilled";
460
- this.publish(entry);
461
728
  const result = {
462
729
  error,
463
730
  staleValue: entry.value,
464
731
  status: "rejected"
465
732
  };
466
733
  pending.resolve(result);
734
+ this.publish(entry);
735
+ controller.abort(error);
467
736
  return result;
468
737
  }
469
738
  entry.error = error;
470
739
  entry.status = "rejected";
471
740
  markDataResourceError(error, entry.key);
472
- this.publish(entry);
473
741
  const result = {
474
742
  error,
475
743
  status: "rejected"
476
744
  };
477
745
  pending.resolve(result);
746
+ this.publish(entry);
747
+ controller.abort(error);
478
748
  return result;
479
749
  };
480
- if (!isThenable(loaded)) {
481
- fulfill(loaded);
750
+ let thenable;
751
+ try {
752
+ thenable = isThenable(loaded);
753
+ } catch (error) {
754
+ reject(error);
482
755
  return pending.promise;
483
756
  }
484
- Promise.resolve(loaded).then(fulfill, reject);
757
+ if (thenable) Promise.resolve(loaded).then(fulfill, reject);
758
+ else fulfill(loaded);
485
759
  return pending.promise;
486
760
  }
487
761
  createLoadContext(entry, controller, valueErrors) {
488
- const context = { signal: controller.signal };
762
+ const context = {
763
+ data: this.dependentHandle(controller.signal),
764
+ signal: controller.signal
765
+ };
489
766
  defineLoadContextCapabilities(context, {
490
767
  key: entry.key,
491
768
  attributeError: (error) => {
@@ -495,8 +772,11 @@ var DefaultDataStore = class {
495
772
  },
496
773
  hydrate: (entries) => {
497
774
  if (this.disposed || controller.signal.aborted) return;
498
- const foreign = entries.filter((hydrated) => this.storeKey(normalizeKey(hydrated.key).canonical) !== entry.storeKey);
499
- if (foreign.length > 0) this.hydrate(foreign);
775
+ const foreign = entries.filter((hydrated) => normalizeKey(hydrated.key).canonical !== entry.canonicalKey);
776
+ for (const hydrated of foreign) {
777
+ if (controller.signal.aborted) return;
778
+ this.hydrate([hydrated]);
779
+ }
500
780
  }
501
781
  });
502
782
  return context;
@@ -509,25 +789,22 @@ var DefaultDataStore = class {
509
789
  scheduleSubscribers(entry, lane) {
510
790
  for (const subscriber of entry.subscribers) this.host.schedule(subscriber, lane);
511
791
  }
512
- abortPendingLoad(entry, reason) {
513
- entry.controller?.abort(reason);
514
- entry.controller = null;
515
- const pending = entry.pending;
516
- if (pending === null) return;
517
- entry.pending = null;
518
- pending.resolve(abortedRefreshResult(entry, reason));
519
- }
520
792
  abortEntryGenerations(entry, reason) {
521
- this.abortPendingLoad(entry, reason);
522
- entry.valueController?.abort(reason);
793
+ const valueController = entry.valueController;
794
+ const pending = entry.pending;
523
795
  entry.valueController = null;
796
+ entry.pending = null;
797
+ pending?.resolve(abortedRefreshResult(entry, reason));
798
+ pending?.controller.abort(reason);
799
+ valueController?.abort(reason);
800
+ this.stopWatch(entry, reason);
524
801
  }
525
802
  retainPreload(entry) {
526
803
  this.clearPreloadTimer(entry);
527
804
  if (this.disposed || !Number.isFinite(this.preloadRetentionMs)) return;
528
805
  entry.preloadTimer = scheduleStoreTimer(() => {
529
806
  entry.preloadTimer = null;
530
- if (entry.subscribers.size === 0 && entry.ensureRetainers === 0 && entry.pending !== null && !entryHasValue(entry)) {
807
+ if (!isHeld(entry) && entry.pending !== null && !entryHasValue(entry)) {
531
808
  this.evictEntry(entry, "evicted");
532
809
  return;
533
810
  }
@@ -535,20 +812,21 @@ var DefaultDataStore = class {
535
812
  }, Math.max(0, this.preloadRetentionMs));
536
813
  }
537
814
  scheduleInactiveCleanup(entry) {
538
- if (this.disposed || entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0 || !Number.isFinite(this.inactiveRetentionMs)) return;
815
+ const retention = entry.inactiveRetentionMs ?? this.inactiveRetentionMs;
816
+ if (this.disposed || isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null || !Number.isFinite(retention)) return;
539
817
  this.clearInactiveTimer(entry);
540
818
  entry.inactiveTimer = scheduleStoreTimer(() => {
541
819
  entry.inactiveTimer = null;
542
- if (entry.subscribers.size > 0 || entry.pending !== null || entry.preloadTimer !== null || entry.ensureRetainers > 0) return;
820
+ if (isHeld(entry) || entry.pending !== null || entry.preloadTimer !== null) return;
543
821
  this.evictEntry(entry, "evicted");
544
- }, Math.max(0, this.inactiveRetentionMs));
822
+ }, Math.max(0, retention));
545
823
  }
546
824
  evictEntry(entry, reason) {
547
- if (this.entries.get(entry.storeKey) !== entry) return;
825
+ if (this.entries.get(entry.canonicalKey) !== entry) return;
548
826
  this.clearInactiveTimer(entry);
549
827
  this.clearPreloadTimer(entry);
828
+ this.entries.delete(entry.canonicalKey);
550
829
  this.abortEntryGenerations(entry, reason);
551
- this.entries.delete(entry.storeKey);
552
830
  this.host.onEntryEvict?.(this.snapshotEntry(entry));
553
831
  }
554
832
  clearInactiveTimer(entry) {
@@ -576,7 +854,8 @@ var DefaultDataStore = class {
576
854
  stale: entry.stale,
577
855
  status: entry.status,
578
856
  subscriberCount: entry.subscribers.size,
579
- value: hasValue ? entry.value : void 0
857
+ value: hasValue ? entry.value : void 0,
858
+ ...entry.watchController === null ? {} : { watching: true }
580
859
  };
581
860
  }
582
861
  readCurrentValue(entry) {
@@ -589,8 +868,10 @@ var DefaultDataStore = class {
589
868
  entry.invalidationVersion += 1;
590
869
  entry.stale = true;
591
870
  entry.refreshError = void 0;
871
+ entry.refreshFailed = false;
872
+ let retiredController = null;
592
873
  if (isAttributableError(attributedError) && entry.valueErrors.has(attributedError)) {
593
- entry.valueController?.abort(attributedError);
874
+ retiredController = entry.valueController;
594
875
  entry.valueController = null;
595
876
  entry.valueErrors = /* @__PURE__ */ new WeakSet();
596
877
  entry.value = void 0;
@@ -601,8 +882,8 @@ var DefaultDataStore = class {
601
882
  entry.status = "pending";
602
883
  }
603
884
  this.notifyEntryChange(entry);
604
- if (entry.subscribers.size === 0) return;
605
885
  this.scheduleSubscribers(entry, lane);
886
+ retiredController?.abort(attributedError);
606
887
  }
607
888
  invalidateEntries(entries, attributedError) {
608
889
  if (entries.length === 0) return;
@@ -622,6 +903,9 @@ function canonicalKeyStartsWith(key, prefix) {
622
903
  const arrayPrefix = prefix.slice(0, -1);
623
904
  return key.startsWith(arrayPrefix) && key[arrayPrefix.length] === ",";
624
905
  }
906
+ function isHeld(entry) {
907
+ return entry.subscribers.size > 0 || (entry.retainers?.size ?? 0) > 0;
908
+ }
625
909
  function entryHasValue(entry) {
626
910
  return entry.status === "fulfilled" || entry.status === "refreshing";
627
911
  }
@@ -696,9 +980,24 @@ function encodeValue(value, path) {
696
980
  function isThenable(value) {
697
981
  return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
698
982
  }
699
- function createPendingResult() {
983
+ function untilAborted(promise, signal) {
984
+ if (signal.aborted) return Promise.reject(signal.reason);
985
+ return new Promise((resolve, reject) => {
986
+ const abort = () => reject(signal.reason);
987
+ signal.addEventListener("abort", abort, { once: true });
988
+ promise.then((value) => {
989
+ signal.removeEventListener("abort", abort);
990
+ resolve(value);
991
+ }, (error) => {
992
+ signal.removeEventListener("abort", abort);
993
+ reject(error);
994
+ });
995
+ });
996
+ }
997
+ function createPendingLoad(controller) {
700
998
  let resolve = () => void 0;
701
999
  return {
1000
+ controller,
702
1001
  promise: new Promise((settle) => {
703
1002
  resolve = settle;
704
1003
  }),
@@ -767,6 +1066,6 @@ function setTransitionHandler(handler) {
767
1066
  return previous;
768
1067
  }
769
1068
  //#endregion
770
- export { refreshData as _, createDataStore as a, createContext as b, dataResource as c, invalidateDataError as d, invalidateDataKey as f, readDataStore as g, normalizeDataResourceKey as h, attachDataStore as i, ensureData as l, isDataStoreController as m, setTransitionHandler as n, createRendererDataStore as o, invalidateDataPrefix as p, transition as r, currentDataStore as s, runTransitionScope as t, invalidateData as u, runWithDataStore as v, isContext as x, FigContextSymbol as y };
1069
+ export { resolveCurrentDataStore as _, createDataStore as a, createContext as b, dataResource as c, readDataStore as d, runWithDataStore as f, markDataResourceError as g, loadContextCapabilities as h, attachDataStore as i, isDataStoreController as l, defineLoadContextCapabilities as m, setTransitionHandler as n, createRendererDataStore as o, dataResourceKeysForError as p, transition as r, currentDataStore as s, runTransitionScope as t, normalizeDataResourceKey as u, setCurrentDataStore as v, isContext as x, FigContextSymbol as y };
771
1070
 
772
- //# sourceMappingURL=transition-B7vpLnb1.js.map
1071
+ //# sourceMappingURL=transition-BFLGYE4q.js.map