@contello/store 3.0.0 → 3.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.
package/dist/index.js CHANGED
@@ -1,59 +1,9 @@
1
- // src/store.ts
2
- import { createContelloClient } from "@contello/client";
3
-
4
- // src/assets.ts
5
- import {
6
- collectAsync,
7
- createSourceSubscription,
8
- mapAsync,
9
- runWithBackoff as runWithBackoff2
10
- } from "@contello/client";
11
- import { ProjectedMap } from "projected";
12
-
13
- // src/diagnostics.ts
14
- import dc from "diagnostics_channel";
15
- var channels = {
16
- start: "@contello/store:start",
17
- end: "@contello/store:end",
18
- error: "@contello/store:error"
19
- };
20
- var onStart = dc.channel(channels.start);
21
- var onEnd = dc.channel(channels.end);
22
- var onError = dc.channel(channels.error);
23
- function hasSubscribers() {
24
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
25
- }
26
- function wrap(name, fn) {
27
- if (!hasSubscribers()) {
28
- return fn();
29
- }
30
- const start = performance.now();
31
- onStart.publish({ name });
32
- let result;
33
- try {
34
- result = fn();
35
- } catch (error) {
36
- onError.publish({ name, error, durationMs: performance.now() - start });
37
- throw error;
38
- }
39
- if (result instanceof Promise) {
40
- return result.then(
41
- (r) => {
42
- onEnd.publish({ name, cached: false, durationMs: performance.now() - start });
43
- return r;
44
- },
45
- (error) => {
46
- onError.publish({ name, error, durationMs: performance.now() - start });
47
- throw error;
48
- }
49
- );
50
- }
51
- onEnd.publish({ name, cached: true, durationMs: performance.now() - start });
52
- return result;
53
- }
54
-
55
- // src/generated/graphql.ts
56
- var MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
1
+ import { asyncKeepalive, collectAsync, createAsyncIterableSubject, createContelloClient, createSourceSubscription, firstAsync, mapAsync, runWithBackoff } from "@contello/client";
2
+ import { ProjectedLazyMap, ProjectedMap, ProjectedValue, maybeCatch, maybeThen, maybeThen as maybeThen$1 } from "projected";
3
+ import { createOperationTelemetry } from "@contello/opentelemetry";
4
+ import { LRUCache } from "lru-cache";
5
+ //#region src/generated/graphql.ts
6
+ const MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
57
7
  id
58
8
  original {
59
9
  ...MediaFile
@@ -72,7 +22,7 @@ var MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
72
22
  }
73
23
  }
74
24
  }`;
75
- var MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
25
+ const MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
76
26
  uid
77
27
  mimeType
78
28
  metadata {
@@ -86,10 +36,10 @@ var MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
86
36
  }
87
37
  }
88
38
  }`;
89
- var StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {
39
+ const StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {
90
40
  ...MediaAsset
91
41
  }`;
92
- var StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {
42
+ const StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {
93
43
  id
94
44
  token
95
45
  description
@@ -99,7 +49,7 @@ var StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nM
99
49
  value
100
50
  }
101
51
  }`;
102
- var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
52
+ const StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
103
53
  id
104
54
  path
105
55
  target {
@@ -136,7 +86,7 @@ var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
136
86
  value
137
87
  }
138
88
  }`;
139
- var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
89
+ const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
140
90
  registerContelloI18nMessages(
141
91
  collectionReferenceName: $collection
142
92
  messages: $messages
@@ -145,7 +95,7 @@ var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($col
145
95
  ids
146
96
  }
147
97
  }`;
148
- var storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
98
+ const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
149
99
  subscription StoreWatchUpdates {
150
100
  contelloUpdatesBatch {
151
101
  events {
@@ -177,1972 +127,1629 @@ subscription StoreWatchUpdates {
177
127
  }
178
128
  }
179
129
  }`;
180
- var operations = {
181
- storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: "mutation" },
182
- storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: "subscription" }
183
- };
184
- var sources = {
185
- storeAsset: {
186
- document: `${MediaFileFragmentSchema}
130
+ const schema = {
131
+ operations: {
132
+ storeRegisterI18nMessages: {
133
+ document: storeRegisterI18nMessagesDocument,
134
+ kind: "mutation"
135
+ },
136
+ storeWatchUpdates: {
137
+ document: storeWatchUpdatesDocument,
138
+ kind: "subscription"
139
+ }
140
+ },
141
+ sources: {
142
+ storeAsset: {
143
+ document: `${MediaFileFragmentSchema}
187
144
  ${MediaAssetFragmentSchema}
188
145
  ${StoreAssetFragmentSchema}`,
189
- fragment: "StoreAsset",
190
- subscription: "contelloAssetsBatch",
191
- __model: "storeAsset",
192
- __cardinality: "asset"
193
- },
194
- storeI18nMessage: {
195
- document: StoreI18nMessageFragmentSchema,
196
- fragment: "StoreI18nMessage",
197
- subscription: "contelloI18nMessagesBatch",
198
- __model: "storeI18nMessage",
199
- __cardinality: "i18nMessage"
200
- },
201
- storeRoute: {
202
- document: StoreRouteFragmentSchema,
203
- fragment: "StoreRoute",
204
- subscription: "contelloRoutesBatch",
205
- __model: "storeRoute",
206
- __cardinality: "route"
207
- }
146
+ fragment: "StoreAsset",
147
+ subscription: "contelloAssetsBatch",
148
+ __model: "storeAsset",
149
+ __cardinality: "asset"
150
+ },
151
+ storeI18nMessage: {
152
+ document: StoreI18nMessageFragmentSchema,
153
+ fragment: "StoreI18nMessage",
154
+ subscription: "contelloI18nMessagesBatch",
155
+ __model: "storeI18nMessage",
156
+ __cardinality: "i18nMessage"
157
+ },
158
+ storeRoute: {
159
+ document: StoreRouteFragmentSchema,
160
+ fragment: "StoreRoute",
161
+ subscription: "contelloRoutesBatch",
162
+ __model: "storeRoute",
163
+ __cardinality: "route"
164
+ }
165
+ },
166
+ models: { dummy: "DummyEntity" }
208
167
  };
209
- var models = {
210
- dummy: "DummyEntity"
211
- };
212
- var schema = { operations, sources, models };
213
-
214
- // src/utils.ts
215
- import { createAsyncIterableSubject, runWithBackoff } from "@contello/client";
216
- var DEFAULT_TTL_MS = 3 * 60 * 60 * 1e3;
217
- var DEFAULT_LRU_MAX = 1e3;
168
+ //#endregion
169
+ //#region src/telemetry.ts
170
+ const { wrap } = createOperationTelemetry("@contello/store");
171
+ //#endregion
172
+ //#region src/utils.ts
173
+ /**
174
+ * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)
175
+ * use it as the interval for a periodic full refresh; lazy stores use it as the per-item
176
+ * LRU eviction window. 3 hours.
177
+ */
178
+ const DEFAULT_TTL_MS = 10800 * 1e3;
179
+ /**
180
+ * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime
181
+ * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.
182
+ */
218
183
  function resolveTtl(ttl) {
219
- if (ttl === void 0) return DEFAULT_TTL_MS;
220
- if (ttl === false || ttl <= 0) return void 0;
221
- return ttl;
184
+ if (ttl === void 0) return DEFAULT_TTL_MS;
185
+ if (ttl === false || ttl <= 0) return void 0;
186
+ return ttl;
222
187
  }
223
- function createRefresher(fn, onRefreshed, onStart2) {
224
- let refreshing = false;
225
- let inFlightKind;
226
- let pendingKind;
227
- function scheduleRefresh(kind) {
228
- if (refreshing) {
229
- pendingKind = { kind };
230
- return;
231
- }
232
- refreshing = true;
233
- inFlightKind = kind;
234
- onStart2?.();
235
- void runWithBackoff(fn).then(() => {
236
- const finished = inFlightKind;
237
- refreshing = false;
238
- inFlightKind = void 0;
239
- onRefreshed(finished);
240
- if (pendingKind) {
241
- const { kind: next } = pendingKind;
242
- pendingKind = void 0;
243
- scheduleRefresh(next);
244
- }
245
- });
246
- }
247
- return scheduleRefresh;
188
+ /**
189
+ * creates a coalescing refresh scheduler with exponential-backoff retry on failure.
190
+ *
191
+ * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,
192
+ * it is queued as pending — the queued slot keeps the latest `kind` passed via
193
+ * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh
194
+ * starts, with that latest kind — collapsing any number of intermediate requests into one.
195
+ *
196
+ * on error, retries indefinitely with exponential backoff. the projected value keeps serving
197
+ * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that
198
+ * triggered the just-completed refresh.
199
+ */
200
+ function createRefresher(fn, onRefreshed, onStart) {
201
+ let refreshing = false;
202
+ let inFlightKind;
203
+ let pendingKind;
204
+ function scheduleRefresh(kind) {
205
+ if (refreshing) {
206
+ pendingKind = { kind };
207
+ return;
208
+ }
209
+ refreshing = true;
210
+ inFlightKind = kind;
211
+ onStart?.();
212
+ runWithBackoff(fn).then(() => {
213
+ const finished = inFlightKind;
214
+ refreshing = false;
215
+ inFlightKind = void 0;
216
+ onRefreshed(finished);
217
+ if (pendingKind) {
218
+ const { kind: next } = pendingKind;
219
+ pendingKind = void 0;
220
+ scheduleRefresh(next);
221
+ }
222
+ });
223
+ }
224
+ return scheduleRefresh;
248
225
  }
249
226
  function createRefreshChannel(onRefresh) {
250
- const stream$ = createAsyncIterableSubject();
251
- return {
252
- stream$,
253
- emit(event) {
254
- stream$.next(event);
255
- onRefresh?.(event);
256
- },
257
- complete() {
258
- stream$.complete();
259
- }
260
- };
227
+ const stream$ = createAsyncIterableSubject();
228
+ return {
229
+ stream$,
230
+ emit(event) {
231
+ stream$.next(event);
232
+ onRefresh?.(event);
233
+ },
234
+ complete() {
235
+ stream$.complete();
236
+ }
237
+ };
261
238
  }
262
239
  function createTtlOrchestrator(options) {
263
- let timer;
264
- return {
265
- mark() {
266
- if (timer !== void 0) {
267
- clearTimeout(timer);
268
- timer = void 0;
269
- }
270
- if (options.ttl === void 0) {
271
- return;
272
- }
273
- timer = setTimeout(options.run, options.ttl);
274
- },
275
- clear() {
276
- if (timer !== void 0) {
277
- clearTimeout(timer);
278
- timer = void 0;
279
- }
280
- }
281
- };
240
+ let timer;
241
+ return {
242
+ mark() {
243
+ if (timer !== void 0) {
244
+ clearTimeout(timer);
245
+ timer = void 0;
246
+ }
247
+ if (options.ttl === void 0) return;
248
+ timer = setTimeout(options.run, options.ttl);
249
+ },
250
+ clear() {
251
+ if (timer === void 0) return;
252
+ clearTimeout(timer);
253
+ timer = void 0;
254
+ }
255
+ };
282
256
  }
283
257
  function createRefreshByTtlQueue() {
284
- const waiting = [];
285
- let running = false;
286
- function next() {
287
- if (running) return;
288
- const task = waiting.shift();
289
- if (!task) return;
290
- running = true;
291
- Promise.resolve().then(task).catch(() => {
292
- }).finally(() => {
293
- running = false;
294
- next();
295
- });
296
- }
297
- return {
298
- enqueue(task) {
299
- waiting.push(task);
300
- next();
301
- }
302
- };
258
+ const waiting = [];
259
+ let running = false;
260
+ function next() {
261
+ if (running) return;
262
+ const task = waiting.shift();
263
+ if (!task) return;
264
+ running = true;
265
+ (async () => {
266
+ try {
267
+ await task();
268
+ } catch {} finally {
269
+ running = false;
270
+ next();
271
+ }
272
+ })();
273
+ }
274
+ return { enqueue(task) {
275
+ waiting.push(task);
276
+ next();
277
+ } };
303
278
  }
304
-
305
- // src/assets.ts
306
- function mapFile(raw) {
307
- return {
308
- uid: raw.uid,
309
- mimeType: raw.mimeType,
310
- metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
311
- };
279
+ //#endregion
280
+ //#region src/assets.ts
281
+ function mapFile$1(raw) {
282
+ return {
283
+ uid: raw.uid,
284
+ mimeType: raw.mimeType,
285
+ metadata: raw.metadata ? {
286
+ width: raw.metadata.width,
287
+ height: raw.metadata.height
288
+ } : void 0
289
+ };
312
290
  }
313
- function mapAsset(raw) {
314
- return {
315
- id: raw.id,
316
- original: mapFile(raw.original),
317
- preview: raw.preview ? mapFile(raw.preview) : void 0,
318
- optimized: raw.optimized.map((file) => mapFile(file))
319
- };
291
+ function mapAsset$1(raw) {
292
+ return {
293
+ id: raw.id,
294
+ original: mapFile$1(raw.original),
295
+ preview: raw.preview ? mapFile$1(raw.preview) : void 0,
296
+ optimized: raw.optimized.map((file) => mapFile$1(file))
297
+ };
320
298
  }
321
299
  function createAssetsCollection(options, client, updates$, refreshByTtl) {
322
- const opts = options ?? {};
323
- const cache = {
324
- ttl: resolveTtl(opts.cache?.ttl),
325
- eviction: opts.cache?.eviction ?? "refresh"
326
- };
327
- const channel = createRefreshChannel(opts.onRefresh);
328
- const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
329
- let loaded = false;
330
- const assetsSourceDoc = createSourceSubscription(schema.sources.storeAsset);
331
- const projected = new ProjectedMap({
332
- key: (asset) => asset.id,
333
- values: (ids) => wrap(
334
- "assets",
335
- () => collectAsync(
336
- mapAsync(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
337
- ).then((rawItems) => {
338
- const items = rawItems.map((item) => mapAsset(item));
339
- if (ids === void 0 && !loaded) {
340
- loaded = true;
341
- ttl.mark();
342
- opts.onLoad?.(items.map((a) => a.id));
343
- }
344
- return items;
345
- })
346
- )
347
- });
348
- function emit(ids, kind) {
349
- channel.emit({ ids, kind });
350
- }
351
- function runFullRefresh(kind) {
352
- refreshByTtl.enqueue(
353
- () => runWithBackoff2(
354
- () => projected.refresh().then((map) => {
355
- emit([...map.keys()], kind);
356
- ttl.mark();
357
- })
358
- )
359
- );
360
- }
361
- function runPartialRefresh(refreshIds, deletedIds) {
362
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
363
- if (refreshIds.length === 0) {
364
- emit(changedIds, "upstream-update");
365
- return;
366
- }
367
- void runWithBackoff2(
368
- () => projected.refresh(refreshIds).then(() => {
369
- emit(changedIds, "upstream-update");
370
- })
371
- );
372
- }
373
- const unsubUpdates = updates$.subscribe((batch) => {
374
- if (!loaded || batch.asset.length === 0) {
375
- return;
376
- }
377
- const deleted = [];
378
- const upserted = /* @__PURE__ */ new Set();
379
- for (const event of batch.asset) {
380
- if (event.mutation === "delete") {
381
- deleted.push(event.id);
382
- } else {
383
- upserted.add(event.id);
384
- }
385
- }
386
- if (cache.eviction === "clear") {
387
- projected.clear();
388
- return;
389
- }
390
- if (deleted.length > 0) {
391
- projected.delete(deleted);
392
- }
393
- runPartialRefresh([...upserted], deleted);
394
- });
395
- const instance = {
396
- refresh$: channel.stream$,
397
- async load() {
398
- if (!loaded) {
399
- await projected.getAllAsMap();
400
- }
401
- },
402
- get(idOrIds) {
403
- return projected.get(idOrIds);
404
- },
405
- upload(data, meta, options2) {
406
- return client.upload(data, meta, options2);
407
- },
408
- download(fileId) {
409
- return client.download(fileId);
410
- },
411
- proxyHls(path, signal) {
412
- return client.proxyHls(path, signal);
413
- },
414
- refresh() {
415
- runFullRefresh("on-demand");
416
- }
417
- };
418
- return {
419
- instance,
420
- destroy() {
421
- unsubUpdates();
422
- ttl.clear();
423
- channel.complete();
424
- }
425
- };
300
+ const opts = options ?? {};
301
+ const cache = {
302
+ ttl: resolveTtl(opts.cache?.ttl),
303
+ eviction: opts.cache?.eviction ?? "refresh"
304
+ };
305
+ const channel = createRefreshChannel(opts.onRefresh);
306
+ const ttl = createTtlOrchestrator({
307
+ ttl: cache.ttl,
308
+ run: () => runFullRefresh("ttl")
309
+ });
310
+ let loaded = false;
311
+ const assetsSourceDoc = createSourceSubscription(schema.sources.storeAsset);
312
+ const projected = new ProjectedMap({
313
+ key: (asset) => asset.id,
314
+ values: (ids) => wrap("assets", async () => {
315
+ const items = (await collectAsync(mapAsync(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source))).map((item) => mapAsset$1(item));
316
+ if (ids === void 0 && !loaded) {
317
+ loaded = true;
318
+ ttl.mark();
319
+ opts.onLoad?.(items.map((a) => a.id));
320
+ }
321
+ return items;
322
+ })
323
+ });
324
+ function emit(ids, kind) {
325
+ channel.emit({
326
+ ids,
327
+ kind
328
+ });
329
+ }
330
+ function runFullRefresh(kind) {
331
+ refreshByTtl.enqueue(() => runWithBackoff(async () => {
332
+ emit((await projected.refresh()).keys().toArray(), kind);
333
+ ttl.mark();
334
+ }));
335
+ }
336
+ function runPartialRefresh(refreshIds, deletedIds) {
337
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
338
+ if (refreshIds.length === 0) {
339
+ emit(changedIds, "upstream-update");
340
+ return;
341
+ }
342
+ runWithBackoff(async () => {
343
+ await projected.refresh(refreshIds);
344
+ emit(changedIds, "upstream-update");
345
+ });
346
+ }
347
+ const unsubUpdates = updates$.subscribe((batch) => {
348
+ if (!loaded || batch.asset.length === 0) return;
349
+ const deleted = [];
350
+ const upserted = /* @__PURE__ */ new Set();
351
+ for (const event of batch.asset) if (event.mutation === "delete") deleted.push(event.id);
352
+ else upserted.add(event.id);
353
+ if (cache.eviction === "clear") {
354
+ projected.clear();
355
+ return;
356
+ }
357
+ if (deleted.length > 0) projected.delete(deleted);
358
+ runPartialRefresh([...upserted], deleted);
359
+ });
360
+ return {
361
+ instance: {
362
+ refresh$: channel.stream$,
363
+ async load() {
364
+ if (!loaded) await projected.getAllAsMap();
365
+ },
366
+ get(idOrIds) {
367
+ return projected.get(idOrIds);
368
+ },
369
+ upload(data, meta, options) {
370
+ return client.upload(data, meta, options);
371
+ },
372
+ download(fileId) {
373
+ return client.download(fileId);
374
+ },
375
+ proxyHls(path, signal) {
376
+ return client.proxyHls(path, signal);
377
+ },
378
+ refresh() {
379
+ runFullRefresh("on-demand");
380
+ }
381
+ },
382
+ destroy() {
383
+ unsubUpdates();
384
+ ttl.clear();
385
+ channel.complete();
386
+ }
387
+ };
426
388
  }
427
389
  function createAssetsSyncCollection(options, client, updates$, refreshByTtl) {
428
- const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);
429
- function assertSync(value, method) {
430
- if (value instanceof Promise) {
431
- throw new TypeError(`assets.${method}() is not initialized yet \u2014 call assets.load() first`);
432
- }
433
- return value;
434
- }
435
- return {
436
- instance: {
437
- ...base,
438
- get(idOrIds) {
439
- return assertSync(base.get(idOrIds), "get");
440
- }
441
- },
442
- destroy
443
- };
390
+ const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);
391
+ function assertSync(value, method) {
392
+ if (value instanceof Promise) throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);
393
+ return value;
394
+ }
395
+ return {
396
+ instance: {
397
+ ...base,
398
+ get(idOrIds) {
399
+ return assertSync(base.get(idOrIds), "get");
400
+ }
401
+ },
402
+ destroy
403
+ };
444
404
  }
445
-
446
- // src/collection.ts
447
- import {
448
- collectAsync as collectAsync2,
449
- createSourceSubscription as createSourceSubscription2,
450
- mapAsync as mapAsync2,
451
- runWithBackoff as runWithBackoff3
452
- } from "@contello/client";
453
- import { ProjectedMap as ProjectedMap2, maybeThen } from "projected";
454
-
455
- // src/dependency-collector.ts
456
- var EMPTY_KEYS = /* @__PURE__ */ new Set();
405
+ //#endregion
406
+ //#region src/dependency-collector.ts
407
+ const EMPTY_KEYS = /* @__PURE__ */ new Set();
457
408
  function createDependencyKey(target, id) {
458
- return `${target}\0${id}`;
409
+ return `${target}\0${id}`;
459
410
  }
460
411
  function createEntityDependencyKey(typename, id) {
461
- return `entity\0${typename}\0${id}`;
412
+ return `entity\0${typename}\0${id}`;
462
413
  }
463
414
  function createRouteTargetKey(typename, id) {
464
- return `routeTarget\0${typename}\0${id}`;
415
+ return `routeTarget\0${typename}\0${id}`;
465
416
  }
417
+ /**
418
+ * bidirectional dependency index for a single collection.
419
+ *
420
+ * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper
421
+ * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes
422
+ * once the item key is known. `register` flushes the collected deps into two maps:
423
+ *
424
+ * forwardIndex: item key -> set of dep keys it declared
425
+ * reverseIndex: dep key -> set of item keys that declared it
426
+ *
427
+ * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`
428
+ * looks up the dep key and returns all item keys that need to be invalidated.
429
+ *
430
+ * lifecycle per map cycle:
431
+ * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)
432
+ * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array
433
+ * 3. fn calls register(key) — real item key is known, deps written into both maps
434
+ */
466
435
  var DependencyCollector = class {
467
- constructor(model, resolver) {
468
- this.model = model;
469
- this.resolver = resolver;
470
- }
471
- /** dep key -> item keys that declared a dependency on it */
472
- reverseIndex = /* @__PURE__ */ new Map();
473
- /** item key -> dep keys it currently declares */
474
- forwardIndex = /* @__PURE__ */ new Map();
475
- /**
476
- * creates a scoped MapperContext for one item and runs `fn` with it.
477
- * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function
478
- * that must be called once the item key is known — it writes all declared deps into the index.
479
- * returns whatever `fn` returns, preserving MaybePromise semantics.
480
- */
481
- createContext(fn) {
482
- const deps = [];
483
- const ctx = {
484
- track: (obj) => {
485
- if (!obj.id) {
486
- throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
487
- }
488
- switch (obj.__typename) {
489
- case "ContelloAsset": {
490
- deps.push(createDependencyKey("asset", obj.id));
491
- break;
492
- }
493
- case "ContelloRoute": {
494
- deps.push(createDependencyKey("route", obj.id));
495
- break;
496
- }
497
- default: {
498
- const model = this.resolver.getModel(obj.__typename);
499
- if (!model) {
500
- throw new Error(
501
- `track(): unexpected __typename "${obj.__typename}" \u2014 expected ContelloAsset, ContelloRoute, or a known entity model`
502
- );
503
- }
504
- deps.push(createEntityDependencyKey(model, obj.id));
505
- }
506
- }
507
- },
508
- trackEntity: (model, id) => {
509
- this.warnIfUnknownModel(model);
510
- deps.push(createEntityDependencyKey(model, id));
511
- },
512
- trackAsset: (id) => deps.push(createDependencyKey("asset", id)),
513
- trackRoute: (id) => deps.push(createDependencyKey("route", id))
514
- };
515
- const register = (key) => {
516
- this.clearItem(key);
517
- deps.push(createRouteTargetKey(this.model, String(key)));
518
- const fwd = /* @__PURE__ */ new Set();
519
- for (const dk of deps) {
520
- fwd.add(dk);
521
- let set = this.reverseIndex.get(dk);
522
- if (!set) {
523
- set = /* @__PURE__ */ new Set();
524
- this.reverseIndex.set(dk, set);
525
- }
526
- set.add(key);
527
- }
528
- if (fwd.size > 0) {
529
- this.forwardIndex.set(key, fwd);
530
- }
531
- };
532
- return fn(ctx, register);
533
- }
534
- /**
535
- * looks up which item keys are affected by an update event.
536
- * for route events, checks route-target deps for both the new and previous entity targets.
537
- */
538
- getAffectedKeys(event) {
539
- if (event.target === "entity") {
540
- return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;
541
- }
542
- let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));
543
- if (event.target === "route") {
544
- if ("after" in event && event.after.type === "entity") {
545
- affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);
546
- }
547
- if ("before" in event && event.before.type === "entity") {
548
- affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);
549
- }
550
- }
551
- return affected ?? EMPTY_KEYS;
552
- }
553
- mergeRouteTargetKeys(existing, entityType, entityId) {
554
- const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));
555
- if (!items) {
556
- return existing;
557
- }
558
- return existing ? /* @__PURE__ */ new Set([...existing, ...items]) : items;
559
- }
560
- /** removes all recorded deps for a single item (called on eviction) */
561
- removeItem(key) {
562
- this.clearItem(key);
563
- }
564
- /** drops all recorded deps — used when clearing the entire cache */
565
- clear() {
566
- this.reverseIndex.clear();
567
- this.forwardIndex.clear();
568
- }
569
- /**
570
- * removes index entries for any item key NOT present in `keys`.
571
- * called after a full re-fetch to prune refs from items that were deleted upstream.
572
- */
573
- retainOnly(keys) {
574
- for (const key of this.forwardIndex.keys()) {
575
- if (!keys.has(key)) {
576
- this.clearItem(key);
577
- }
578
- }
579
- }
580
- warnIfUnknownModel(model) {
581
- if (!this.resolver.hasModel(model)) {
582
- console.warn(
583
- `[contello/store] tracking model "${model}" which is not in models \u2014 updates for this model will be ignored`
584
- );
585
- }
586
- }
587
- /**
588
- * removes all index entries for one item key.
589
- * cleans up the forward entry and removes the item from every reverse set it appeared in.
590
- * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.
591
- */
592
- clearItem(key) {
593
- const existingDeps = this.forwardIndex.get(key);
594
- if (!existingDeps) {
595
- return;
596
- }
597
- for (const dk of existingDeps) {
598
- const set = this.reverseIndex.get(dk);
599
- if (set) {
600
- set.delete(key);
601
- if (set.size === 0) {
602
- this.reverseIndex.delete(dk);
603
- }
604
- }
605
- }
606
- this.forwardIndex.delete(key);
607
- }
436
+ model;
437
+ resolver;
438
+ /** dep key -> item keys that declared a dependency on it */
439
+ reverseIndex = /* @__PURE__ */ new Map();
440
+ /** item key -> dep keys it currently declares */
441
+ forwardIndex = /* @__PURE__ */ new Map();
442
+ constructor(model, resolver) {
443
+ this.model = model;
444
+ this.resolver = resolver;
445
+ }
446
+ mergeRouteTargetKeys(existing, entityType, entityId) {
447
+ const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));
448
+ if (!items) return existing;
449
+ return existing ? existing.union(items) : items;
450
+ }
451
+ warnIfUnknownModel(model) {
452
+ if (!this.resolver.hasModel(model)) console.warn(`[contello/store] tracking model "${model}" which is not in models — updates for this model will be ignored`);
453
+ }
454
+ /**
455
+ * removes all index entries for one item key.
456
+ * cleans up the forward entry and removes the item from every reverse set it appeared in.
457
+ * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.
458
+ */
459
+ clearItem(key) {
460
+ const existingDeps = this.forwardIndex.get(key);
461
+ if (!existingDeps) return;
462
+ for (const dk of existingDeps) {
463
+ const set = this.reverseIndex.get(dk);
464
+ if (set) {
465
+ set.delete(key);
466
+ if (set.size === 0) this.reverseIndex.delete(dk);
467
+ }
468
+ }
469
+ this.forwardIndex.delete(key);
470
+ }
471
+ /**
472
+ * creates a scoped MapperContext for one item and runs `fn` with it.
473
+ * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function
474
+ * that must be called once the item key is known — it writes all declared deps into the index.
475
+ * returns whatever `fn` returns, preserving MaybePromise semantics.
476
+ */
477
+ createContext(fn) {
478
+ const deps = [];
479
+ const ctx = {
480
+ track: (obj) => {
481
+ if (!obj.id) throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
482
+ switch (obj.__typename) {
483
+ case "ContelloAsset":
484
+ deps.push(createDependencyKey("asset", obj.id));
485
+ break;
486
+ case "ContelloRoute":
487
+ deps.push(createDependencyKey("route", obj.id));
488
+ break;
489
+ default: {
490
+ const model = this.resolver.getModel(obj.__typename);
491
+ if (!model) throw new Error(`track(): unexpected __typename "${obj.__typename}" — expected ContelloAsset, ContelloRoute, or a known entity model`);
492
+ deps.push(createEntityDependencyKey(model, obj.id));
493
+ }
494
+ }
495
+ },
496
+ trackEntity: (model, id) => {
497
+ this.warnIfUnknownModel(model);
498
+ deps.push(createEntityDependencyKey(model, id));
499
+ },
500
+ trackAsset: (id) => {
501
+ deps.push(createDependencyKey("asset", id));
502
+ },
503
+ trackRoute: (id) => {
504
+ deps.push(createDependencyKey("route", id));
505
+ }
506
+ };
507
+ const register = (key) => {
508
+ this.clearItem(key);
509
+ deps.push(createRouteTargetKey(this.model, String(key)));
510
+ const fwd = /* @__PURE__ */ new Set();
511
+ for (const dk of deps) {
512
+ fwd.add(dk);
513
+ let set = this.reverseIndex.get(dk);
514
+ if (!set) {
515
+ set = /* @__PURE__ */ new Set();
516
+ this.reverseIndex.set(dk, set);
517
+ }
518
+ set.add(key);
519
+ }
520
+ if (fwd.size > 0) this.forwardIndex.set(key, fwd);
521
+ };
522
+ return fn(ctx, register);
523
+ }
524
+ /**
525
+ * looks up which item keys are affected by an update event.
526
+ * for route events, checks route-target deps for both the new and previous entity targets.
527
+ */
528
+ getAffectedKeys(event) {
529
+ if (event.target === "entity") return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;
530
+ let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));
531
+ if (event.target === "route") {
532
+ if ("after" in event && event.after.type === "entity") affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);
533
+ if ("before" in event && event.before.type === "entity") affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);
534
+ }
535
+ return affected ?? EMPTY_KEYS;
536
+ }
537
+ /** removes all recorded deps for a single item (called on eviction) */
538
+ removeItem(key) {
539
+ this.clearItem(key);
540
+ }
541
+ /** drops all recorded deps — used when clearing the entire cache */
542
+ clear() {
543
+ this.reverseIndex.clear();
544
+ this.forwardIndex.clear();
545
+ }
546
+ /**
547
+ * removes index entries for any item key NOT present in `keys`.
548
+ * called after a full re-fetch to prune refs from items that were deleted upstream.
549
+ */
550
+ retainOnly(keys) {
551
+ for (const key of this.forwardIndex.keys()) if (!keys.has(key)) this.clearItem(key);
552
+ }
608
553
  };
609
-
610
- // src/collection.ts
554
+ //#endregion
555
+ //#region src/collection.ts
611
556
  function fetchCollection(source, client, ids) {
612
- return collectAsync2(
613
- mapAsync2(
614
- client.subscribe(createSourceSubscription2(source), { ids }),
615
- (r) => r.source
616
- )
617
- );
557
+ return collectAsync(mapAsync(client.subscribe(createSourceSubscription(source), { ids }), (r) => r.source));
618
558
  }
619
559
  function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
620
- const opts = options ?? {};
621
- const mapFn = opts.map ?? ((item) => item);
622
- const _def = {
623
- name: opts.name ?? source.__model,
624
- model: source.__model,
625
- cache: {
626
- ttl: resolveTtl(opts.cache?.ttl),
627
- eviction: opts.cache?.eviction ?? "refresh"
628
- }
629
- };
630
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
631
- const channel = createRefreshChannel(opts.onRefresh);
632
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh("ttl") });
633
- let loaded = false;
634
- const projected = new ProjectedMap2({
635
- key: (item) => item.id,
636
- values: (ids) => wrap(
637
- `collection:${_def.name}`,
638
- () => maybeThen(
639
- fetchCollection(source, client, ids),
640
- (rawItems) => Promise.all(
641
- rawItems.map(
642
- (item) => Promise.resolve(
643
- dependencyCollector.createContext(
644
- (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {
645
- register(mapped.id);
646
- return mapped;
647
- })
648
- )
649
- )
650
- )
651
- ).then((items) => {
652
- if (ids === void 0) {
653
- dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
654
- if (!loaded) {
655
- loaded = true;
656
- ttl.mark();
657
- opts.onLoad?.(items.map((item) => item.id));
658
- }
659
- } else {
660
- const returnedIds = new Set(items.map((item) => item.id));
661
- for (const id of ids) {
662
- if (!returnedIds.has(id)) {
663
- dependencyCollector.removeItem(id);
664
- }
665
- }
666
- }
667
- return items;
668
- })
669
- )
670
- ),
671
- sort: opts.sort
672
- });
673
- function emit(ids, kind) {
674
- channel.emit({ ids, kind });
675
- }
676
- function runFullRefresh(kind) {
677
- refreshByTtl.enqueue(
678
- () => runWithBackoff3(
679
- () => projected.refresh().then((map) => {
680
- emit([...map.keys()], kind);
681
- ttl.mark();
682
- })
683
- )
684
- );
685
- }
686
- function runPartialRefresh(refreshIds, deletedIds) {
687
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
688
- if (refreshIds.length === 0) {
689
- emit(changedIds, "upstream-update");
690
- return;
691
- }
692
- void runWithBackoff3(
693
- () => projected.refresh(refreshIds).then(() => {
694
- emit(changedIds, "upstream-update");
695
- })
696
- );
697
- }
698
- const unsubUpdates = updates$.subscribe((batch) => {
699
- if (!loaded) {
700
- return;
701
- }
702
- const ownEvents = batch.entity.get(_def.model) ?? [];
703
- const deleted = [];
704
- const upserted = /* @__PURE__ */ new Set();
705
- for (const event of ownEvents) {
706
- if (event.mutation === "delete") {
707
- deleted.push(event.id);
708
- } else {
709
- upserted.add(event.id);
710
- }
711
- }
712
- const depAffected = /* @__PURE__ */ new Set();
713
- for (const event of batch.events) {
714
- for (const id of dependencyCollector.getAffectedKeys(event)) {
715
- depAffected.add(id);
716
- }
717
- }
718
- if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {
719
- return;
720
- }
721
- if (_def.cache.eviction === "clear") {
722
- dependencyCollector.clear();
723
- projected.clear();
724
- return;
725
- }
726
- for (const id of deleted) {
727
- dependencyCollector.removeItem(id);
728
- }
729
- if (deleted.length > 0) {
730
- projected.delete(deleted);
731
- }
732
- const refreshIds = /* @__PURE__ */ new Set([...upserted, ...depAffected]);
733
- for (const id of deleted) {
734
- refreshIds.delete(id);
735
- }
736
- runPartialRefresh([...refreshIds], deleted);
737
- });
738
- const instance = {
739
- name: _def.name,
740
- refresh$: channel.stream$,
741
- get(idOrIds) {
742
- return projected.get(idOrIds);
743
- },
744
- getAll() {
745
- return projected.getAll();
746
- },
747
- refresh() {
748
- runFullRefresh("on-demand");
749
- },
750
- async load() {
751
- if (!loaded) {
752
- await projected.getAllAsMap();
753
- }
754
- }
755
- };
756
- return {
757
- instance,
758
- destroy() {
759
- unsubUpdates();
760
- ttl.clear();
761
- channel.complete();
762
- }
763
- };
560
+ const opts = options ?? {};
561
+ const mapFn = opts.map ?? ((item) => item);
562
+ const _def = {
563
+ name: opts.name ?? source.__model,
564
+ model: source.__model,
565
+ cache: {
566
+ ttl: resolveTtl(opts.cache?.ttl),
567
+ eviction: opts.cache?.eviction ?? "refresh"
568
+ }
569
+ };
570
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
571
+ const channel = createRefreshChannel(opts.onRefresh);
572
+ const ttl = createTtlOrchestrator({
573
+ ttl: _def.cache.ttl,
574
+ run: () => runFullRefresh("ttl")
575
+ });
576
+ let loaded = false;
577
+ const projected = new ProjectedMap({
578
+ key: (item) => item.id,
579
+ values: (ids) => wrap(`collection:${_def.name}`, () => maybeThen$1(fetchCollection(source, client, ids), async (rawItems) => {
580
+ const items = await Promise.all(rawItems.map((item) => Promise.resolve(dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(item, ref), (mapped) => {
581
+ register(mapped.id);
582
+ return mapped;
583
+ })))));
584
+ if (ids === void 0) {
585
+ dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
586
+ if (!loaded) {
587
+ loaded = true;
588
+ ttl.mark();
589
+ opts.onLoad?.(items.map((item) => item.id));
590
+ }
591
+ } else {
592
+ const returnedIds = new Set(items.map((item) => item.id));
593
+ for (const id of ids) if (!returnedIds.has(id)) dependencyCollector.removeItem(id);
594
+ }
595
+ return items;
596
+ })),
597
+ sort: opts.sort
598
+ });
599
+ function emit(ids, kind) {
600
+ channel.emit({
601
+ ids,
602
+ kind
603
+ });
604
+ }
605
+ function runFullRefresh(kind) {
606
+ refreshByTtl.enqueue(() => runWithBackoff(async () => {
607
+ emit((await projected.refresh()).keys().toArray(), kind);
608
+ ttl.mark();
609
+ }));
610
+ }
611
+ function runPartialRefresh(refreshIds, deletedIds) {
612
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
613
+ if (refreshIds.length === 0) {
614
+ emit(changedIds, "upstream-update");
615
+ return;
616
+ }
617
+ runWithBackoff(async () => {
618
+ await projected.refresh(refreshIds);
619
+ emit(changedIds, "upstream-update");
620
+ });
621
+ }
622
+ const unsubUpdates = updates$.subscribe((batch) => {
623
+ if (!loaded) return;
624
+ const ownEvents = batch.entity.get(_def.model) ?? [];
625
+ const deleted = [];
626
+ const upserted = /* @__PURE__ */ new Set();
627
+ for (const event of ownEvents) if (event.mutation === "delete") deleted.push(event.id);
628
+ else upserted.add(event.id);
629
+ const depAffected = /* @__PURE__ */ new Set();
630
+ for (const event of batch.events) for (const id of dependencyCollector.getAffectedKeys(event)) depAffected.add(id);
631
+ if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) return;
632
+ if (_def.cache.eviction === "clear") {
633
+ dependencyCollector.clear();
634
+ projected.clear();
635
+ return;
636
+ }
637
+ for (const id of deleted) dependencyCollector.removeItem(id);
638
+ if (deleted.length > 0) projected.delete(deleted);
639
+ const refreshIds = upserted.union(depAffected);
640
+ for (const id of deleted) refreshIds.delete(id);
641
+ runPartialRefresh([...refreshIds], deleted);
642
+ });
643
+ return {
644
+ instance: {
645
+ name: _def.name,
646
+ refresh$: channel.stream$,
647
+ get(idOrIds) {
648
+ return projected.get(idOrIds);
649
+ },
650
+ getAll() {
651
+ return projected.getAll();
652
+ },
653
+ refresh() {
654
+ runFullRefresh("on-demand");
655
+ },
656
+ async load() {
657
+ if (!loaded) await projected.getAllAsMap();
658
+ }
659
+ },
660
+ destroy() {
661
+ unsubUpdates();
662
+ ttl.clear();
663
+ channel.complete();
664
+ }
665
+ };
764
666
  }
765
667
  function createCollectionSync(source, options, client, updates$, resolver, refreshByTtl) {
766
- const { instance: base, destroy } = createCollection(
767
- source,
768
- options,
769
- client,
770
- updates$,
771
- resolver,
772
- refreshByTtl
773
- );
774
- function assertSync(value, method) {
775
- if (value instanceof Promise) {
776
- throw new TypeError(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
777
- }
778
- return value;
779
- }
780
- return {
781
- instance: {
782
- ...base,
783
- get(idOrIds) {
784
- return assertSync(base.get(idOrIds), "get");
785
- },
786
- getAll() {
787
- return assertSync(base.getAll(), "getAll");
788
- }
789
- },
790
- destroy
791
- };
668
+ const { instance: base, destroy } = createCollection(source, options, client, updates$, resolver, refreshByTtl);
669
+ function assertSync(value, method) {
670
+ if (value instanceof Promise) throw new TypeError(`collection "${base.name}".${method}() is not initialized yet — call collection.load() first`);
671
+ return value;
672
+ }
673
+ return {
674
+ instance: {
675
+ ...base,
676
+ get(idOrIds) {
677
+ return assertSync(base.get(idOrIds), "get");
678
+ },
679
+ getAll() {
680
+ return assertSync(base.getAll(), "getAll");
681
+ }
682
+ },
683
+ destroy
684
+ };
792
685
  }
793
-
794
- // src/i18n.ts
795
- import {
796
- collectAsync as collectAsync3,
797
- createSourceSubscription as createSourceSubscription3,
798
- mapAsync as mapAsync3,
799
- runWithBackoff as runWithBackoff4
800
- } from "@contello/client";
801
- import { ProjectedMap as ProjectedMap3, maybeThen as maybeThen2 } from "projected";
686
+ //#endregion
687
+ //#region src/i18n.ts
802
688
  function toGqlMessageInput(msg) {
803
- return {
804
- token: msg.token,
805
- example: msg.example,
806
- description: msg.description,
807
- variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),
808
- translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),
809
- initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message }))
810
- };
689
+ return {
690
+ token: msg.token,
691
+ example: msg.example,
692
+ description: msg.description,
693
+ variables: msg.variables?.map((v) => ({
694
+ name: v.name,
695
+ description: v.description,
696
+ example: v.example
697
+ })),
698
+ translations: msg.translations?.map((t) => ({
699
+ language: t.language,
700
+ message: t.message
701
+ })),
702
+ initialTranslations: msg.initialTranslations?.map((t) => ({
703
+ language: t.language,
704
+ message: t.message
705
+ }))
706
+ };
811
707
  }
812
708
  function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
813
- const channel = createRefreshChannel(def.onRefresh);
814
- const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });
815
- let loaded = false;
816
- const i18nSourceDoc = createSourceSubscription3(schema.sources.storeI18nMessage);
817
- const projected = new ProjectedMap3({
818
- key: (msg) => msg.id,
819
- values: (ids) => wrap(
820
- `i18n:${def.collection}`,
821
- () => collectAsync3(
822
- mapAsync3(
823
- client.subscribe(i18nSourceDoc, {
824
- collection: def.collection,
825
- ids
826
- }),
827
- (data) => data.source
828
- )
829
- ).then((msgs) => {
830
- const items = msgs.map((msg) => ({
831
- id: msg.id,
832
- token: msg.token,
833
- translations: new Map(msg.translations.map((t) => [t.language, t.value]))
834
- }));
835
- if (ids === void 0 && !loaded) {
836
- loaded = true;
837
- ttl.mark();
838
- }
839
- return items;
840
- })
841
- )
842
- });
843
- function emit(ids, kind) {
844
- channel.emit({ ids, kind });
845
- }
846
- function emitWithCurrentIds(kind) {
847
- maybeThen2(projected.getAll(), (msgs) => {
848
- emit(
849
- msgs.map((m) => m.id),
850
- kind
851
- );
852
- });
853
- }
854
- function runTtlRefresh() {
855
- refreshByTtl.enqueue(
856
- () => runWithBackoff4(() => projected.refresh()).then(() => {
857
- emitWithCurrentIds("ttl");
858
- ttl.mark();
859
- })
860
- );
861
- }
862
- const scheduleRefresh = createRefresher(
863
- () => projected.refresh(),
864
- (kind) => {
865
- emitWithCurrentIds(kind);
866
- ttl.mark();
867
- },
868
- () => {
869
- }
870
- );
871
- function runPartialRefresh(upsertedIds, deletedIds) {
872
- const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
873
- if (changedIds.length === 0) {
874
- return;
875
- }
876
- if (upsertedIds.length === 0) {
877
- emit(changedIds, "upstream-update");
878
- return;
879
- }
880
- void runWithBackoff4(
881
- () => projected.refresh(upsertedIds).then(() => {
882
- emit(changedIds, "upstream-update");
883
- })
884
- );
885
- }
886
- const unsubUpdates = updates$.subscribe((batch) => {
887
- if (!loaded) {
888
- return;
889
- }
890
- if (batch.i18nMessage.length === 0) {
891
- return;
892
- }
893
- const deleted = [];
894
- const upserted = /* @__PURE__ */ new Set();
895
- for (const event of batch.i18nMessage) {
896
- if (event.mutation === "delete") {
897
- deleted.push(event.id);
898
- } else {
899
- upserted.add(event.id);
900
- }
901
- }
902
- if (deleted.length > 0) {
903
- projected.delete(deleted);
904
- }
905
- runPartialRefresh([...upserted], deleted);
906
- });
907
- return {
908
- refresh$: channel.stream$,
909
- get(idOrIds) {
910
- return projected.get(idOrIds);
911
- },
912
- getAll() {
913
- return projected.getAll();
914
- },
915
- register(messages) {
916
- return wrap(
917
- `i18n-register:${def.collection}`,
918
- () => client.execute(storeRegisterI18nMessagesDocument, {
919
- collection: def.collection,
920
- messages: messages.map((message) => toGqlMessageInput(message))
921
- }).then(() => {
922
- })
923
- );
924
- },
925
- refresh() {
926
- scheduleRefresh("on-demand");
927
- },
928
- destroy() {
929
- unsubUpdates();
930
- ttl.clear();
931
- channel.complete();
932
- }
933
- };
709
+ const channel = createRefreshChannel(def.onRefresh);
710
+ const ttl = createTtlOrchestrator({
711
+ ttl: resolveTtl(def.cache?.ttl),
712
+ run: () => runTtlRefresh()
713
+ });
714
+ let loaded = false;
715
+ const i18nSourceDoc = createSourceSubscription(schema.sources.storeI18nMessage);
716
+ const projected = new ProjectedMap({
717
+ key: (msg) => msg.id,
718
+ values: (ids) => wrap(`i18n:${def.collection}`, async () => {
719
+ const items = (await collectAsync(mapAsync(client.subscribe(i18nSourceDoc, {
720
+ collection: def.collection,
721
+ ids
722
+ }), (data) => data.source))).map((msg) => ({
723
+ id: msg.id,
724
+ token: msg.token,
725
+ translations: new Map(msg.translations.map((t) => [t.language, t.value]))
726
+ }));
727
+ if (ids === void 0 && !loaded) {
728
+ loaded = true;
729
+ ttl.mark();
730
+ }
731
+ return items;
732
+ })
733
+ });
734
+ function emit(ids, kind) {
735
+ channel.emit({
736
+ ids,
737
+ kind
738
+ });
739
+ }
740
+ function emitWithCurrentIds(kind) {
741
+ maybeThen$1(projected.getAll(), (msgs) => {
742
+ emit(msgs.map((m) => m.id), kind);
743
+ });
744
+ }
745
+ function runTtlRefresh() {
746
+ refreshByTtl.enqueue(async () => {
747
+ await runWithBackoff(() => projected.refresh());
748
+ emitWithCurrentIds("ttl");
749
+ ttl.mark();
750
+ });
751
+ }
752
+ const scheduleRefresh = createRefresher(() => projected.refresh(), (kind) => {
753
+ emitWithCurrentIds(kind);
754
+ ttl.mark();
755
+ }, () => {});
756
+ function runPartialRefresh(upsertedIds, deletedIds) {
757
+ const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
758
+ if (changedIds.length === 0) return;
759
+ if (upsertedIds.length === 0) {
760
+ emit(changedIds, "upstream-update");
761
+ return;
762
+ }
763
+ runWithBackoff(async () => {
764
+ await projected.refresh(upsertedIds);
765
+ emit(changedIds, "upstream-update");
766
+ });
767
+ }
768
+ const unsubUpdates = updates$.subscribe((batch) => {
769
+ if (!loaded) return;
770
+ if (batch.i18nMessage.length === 0) return;
771
+ const deleted = [];
772
+ const upserted = /* @__PURE__ */ new Set();
773
+ for (const event of batch.i18nMessage) if (event.mutation === "delete") deleted.push(event.id);
774
+ else upserted.add(event.id);
775
+ if (deleted.length > 0) projected.delete(deleted);
776
+ runPartialRefresh([...upserted], deleted);
777
+ });
778
+ return {
779
+ refresh$: channel.stream$,
780
+ get(idOrIds) {
781
+ return projected.get(idOrIds);
782
+ },
783
+ getAll() {
784
+ return projected.getAll();
785
+ },
786
+ register(messages) {
787
+ return wrap(`i18n-register:${def.collection}`, async () => {
788
+ await client.execute(storeRegisterI18nMessagesDocument, {
789
+ collection: def.collection,
790
+ messages: messages.map((message) => toGqlMessageInput(message))
791
+ });
792
+ });
793
+ },
794
+ refresh() {
795
+ scheduleRefresh("on-demand");
796
+ },
797
+ destroy() {
798
+ unsubUpdates();
799
+ ttl.clear();
800
+ channel.complete();
801
+ }
802
+ };
934
803
  }
935
-
936
- // src/lazy-assets.ts
937
- import {
938
- collectAsync as collectAsync4,
939
- createSourceSubscription as createSourceSubscription4,
940
- mapAsync as mapAsync4
941
- } from "@contello/client";
942
- import { ProjectedLazyMap } from "projected";
943
-
944
- // src/lru.ts
945
- import { LRUCache } from "lru-cache";
804
+ //#endregion
805
+ //#region src/lru.ts
946
806
  function createLruCache(options) {
947
- const { max, ttl, onEvict: dispose } = options;
948
- const lru = new LRUCache({
949
- max,
950
- ...ttl !== void 0 && { ttl, ttlAutopurge: false },
951
- ...dispose !== void 0 && { dispose }
952
- });
953
- return {
954
- has: (key) => lru.has(key),
955
- get: (key) => lru.get(key),
956
- set: (key, value) => {
957
- lru.set(key, value);
958
- },
959
- delete: (key) => {
960
- lru.delete(key);
961
- },
962
- clear: () => {
963
- lru.clear();
964
- },
965
- keys: () => [...lru.keys()]
966
- };
807
+ const { max, ttl, onEvict: dispose } = options;
808
+ const lru = new LRUCache({
809
+ max,
810
+ ...ttl !== void 0 && {
811
+ ttl,
812
+ ttlAutopurge: false
813
+ },
814
+ ...dispose !== void 0 && { dispose }
815
+ });
816
+ return {
817
+ has: (key) => lru.has(key),
818
+ get: (key) => lru.get(key),
819
+ set: (key, value) => {
820
+ lru.set(key, value);
821
+ },
822
+ delete: (key) => {
823
+ lru.delete(key);
824
+ },
825
+ clear: () => {
826
+ lru.clear();
827
+ },
828
+ keys: () => lru.keys().toArray()
829
+ };
967
830
  }
968
-
969
- // src/lazy-assets.ts
970
- function mapFile2(raw) {
971
- return {
972
- uid: raw.uid,
973
- mimeType: raw.mimeType,
974
- metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
975
- };
831
+ //#endregion
832
+ //#region src/lazy-assets.ts
833
+ function mapFile(raw) {
834
+ return {
835
+ uid: raw.uid,
836
+ mimeType: raw.mimeType,
837
+ metadata: raw.metadata ? {
838
+ width: raw.metadata.width,
839
+ height: raw.metadata.height
840
+ } : void 0
841
+ };
976
842
  }
977
- function mapAsset2(raw) {
978
- return {
979
- id: raw.id,
980
- original: mapFile2(raw.original),
981
- preview: raw.preview ? mapFile2(raw.preview) : void 0,
982
- optimized: raw.optimized.map((file) => mapFile2(file))
983
- };
843
+ function mapAsset(raw) {
844
+ return {
845
+ id: raw.id,
846
+ original: mapFile(raw.original),
847
+ preview: raw.preview ? mapFile(raw.preview) : void 0,
848
+ optimized: raw.optimized.map((file) => mapFile(file))
849
+ };
984
850
  }
985
851
  function createLazyAssetsCollection(def, client, updates$) {
986
- const _def = {
987
- cache: {
988
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
989
- ttl: resolveTtl(def?.cache?.ttl)
990
- }
991
- };
992
- const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
993
- const assetsSourceDoc = createSourceSubscription4(schema.sources.storeAsset);
994
- const projected = new ProjectedLazyMap({
995
- key: (asset) => asset.id,
996
- values: (ids) => wrap(
997
- "assets",
998
- () => collectAsync4(
999
- mapAsync4(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
1000
- ).then((rawItems) => rawItems.map((item) => mapAsset2(item)))
1001
- ),
1002
- cache
1003
- });
1004
- const channel = createRefreshChannel(def?.onRefresh);
1005
- function emit(ids, kind) {
1006
- channel.emit({ ids, kind });
1007
- }
1008
- let lastRefreshKeys = [];
1009
- const scheduleRefresh = createRefresher(
1010
- async () => {
1011
- lastRefreshKeys = cache.keys();
1012
- if (lastRefreshKeys.length === 0) {
1013
- return;
1014
- }
1015
- await projected.refresh(lastRefreshKeys);
1016
- },
1017
- (kind) => {
1018
- if (lastRefreshKeys.length > 0) {
1019
- emit(lastRefreshKeys, kind);
1020
- }
1021
- },
1022
- () => {
1023
- }
1024
- );
1025
- const unsubUpdates = updates$.subscribe((batch) => {
1026
- if (batch.asset.length === 0) return;
1027
- for (const event of batch.asset) {
1028
- projected.delete(event.id);
1029
- }
1030
- emit(
1031
- batch.asset.map((e) => e.id),
1032
- "upstream-update"
1033
- );
1034
- });
1035
- return {
1036
- instance: {
1037
- refresh$: channel.stream$,
1038
- get(idOrIds) {
1039
- return projected.get(idOrIds);
1040
- },
1041
- upload(data, meta, options) {
1042
- return client.upload(data, meta, options);
1043
- },
1044
- download(fileId) {
1045
- return client.download(fileId);
1046
- },
1047
- proxyHls(path, signal) {
1048
- return client.proxyHls(path, signal);
1049
- },
1050
- refresh() {
1051
- scheduleRefresh("on-demand");
1052
- },
1053
- clear() {
1054
- projected.clear();
1055
- }
1056
- },
1057
- destroy() {
1058
- unsubUpdates();
1059
- channel.complete();
1060
- }
1061
- };
852
+ const _def = { cache: {
853
+ max: def?.cache?.max ?? 1e3,
854
+ ttl: resolveTtl(def?.cache?.ttl)
855
+ } };
856
+ const cache = createLruCache({
857
+ max: _def.cache.max,
858
+ ttl: _def.cache.ttl,
859
+ onEvict: void 0
860
+ });
861
+ const assetsSourceDoc = createSourceSubscription(schema.sources.storeAsset);
862
+ const projected = new ProjectedLazyMap({
863
+ key: (asset) => asset.id,
864
+ values: (ids) => wrap("assets", async () => {
865
+ return (await collectAsync(mapAsync(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source))).map((item) => mapAsset(item));
866
+ }),
867
+ cache
868
+ });
869
+ const channel = createRefreshChannel(def?.onRefresh);
870
+ function emit(ids, kind) {
871
+ channel.emit({
872
+ ids,
873
+ kind
874
+ });
875
+ }
876
+ let lastRefreshKeys = [];
877
+ const scheduleRefresh = createRefresher(async () => {
878
+ lastRefreshKeys = cache.keys();
879
+ if (lastRefreshKeys.length === 0) return;
880
+ await projected.refresh(lastRefreshKeys);
881
+ }, (kind) => {
882
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys, kind);
883
+ }, () => {});
884
+ const unsubUpdates = updates$.subscribe((batch) => {
885
+ if (batch.asset.length === 0) return;
886
+ for (const event of batch.asset) projected.delete(event.id);
887
+ emit(batch.asset.map((e) => e.id), "upstream-update");
888
+ });
889
+ return {
890
+ instance: {
891
+ refresh$: channel.stream$,
892
+ get(idOrIds) {
893
+ return projected.get(idOrIds);
894
+ },
895
+ upload(data, meta, options) {
896
+ return client.upload(data, meta, options);
897
+ },
898
+ download(fileId) {
899
+ return client.download(fileId);
900
+ },
901
+ proxyHls(path, signal) {
902
+ return client.proxyHls(path, signal);
903
+ },
904
+ refresh() {
905
+ scheduleRefresh("on-demand");
906
+ },
907
+ clear() {
908
+ projected.clear();
909
+ }
910
+ },
911
+ destroy() {
912
+ unsubUpdates();
913
+ channel.complete();
914
+ }
915
+ };
1062
916
  }
1063
-
1064
- // src/lazy-collection.ts
1065
- import {
1066
- collectAsync as collectAsync5,
1067
- createAsyncIterableSubject as createAsyncIterableSubject2,
1068
- createSourceSubscription as createSourceSubscription5,
1069
- mapAsync as mapAsync5
1070
- } from "@contello/client";
1071
- import { ProjectedLazyMap as ProjectedLazyMap2, maybeThen as maybeThen3 } from "projected";
917
+ //#endregion
918
+ //#region src/lazy-collection.ts
1072
919
  function createLazyCollection(source, options, client, updates$, resolver) {
1073
- const opts = options ?? {};
1074
- const mapFn = opts.map ?? ((item) => item);
1075
- const _def = {
1076
- name: opts.name ?? source.__model,
1077
- model: source.__model,
1078
- cache: {
1079
- max: opts.cache?.max ?? DEFAULT_LRU_MAX,
1080
- ttl: resolveTtl(opts.cache?.ttl)
1081
- }
1082
- };
1083
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1084
- const cache = createLruCache({
1085
- max: _def.cache.max,
1086
- ttl: _def.cache.ttl,
1087
- onEvict: (_value, key) => dependencyCollector.removeItem(key)
1088
- });
1089
- const projected = new ProjectedLazyMap2({
1090
- key: (item) => item.id,
1091
- values: (keys) => wrap(
1092
- `lazy-collection:${_def.name}`,
1093
- () => maybeThen3(
1094
- collectAsync5(
1095
- mapAsync5(
1096
- client.subscribe(createSourceSubscription5(source), {
1097
- ids: keys
1098
- }),
1099
- (r) => r.source
1100
- )
1101
- ),
1102
- (rawItems) => Promise.all(
1103
- rawItems.map(
1104
- (item) => Promise.resolve(
1105
- dependencyCollector.createContext(
1106
- (ref, register) => maybeThen3(mapFn(item, ref), (mapped) => {
1107
- register(mapped.id);
1108
- return mapped;
1109
- })
1110
- )
1111
- )
1112
- )
1113
- )
1114
- )
1115
- ),
1116
- cache
1117
- });
1118
- const refresh$ = createAsyncIterableSubject2();
1119
- function emit(ids, kind) {
1120
- const event = { ids, kind };
1121
- refresh$.next(event);
1122
- opts.onRefresh?.(event);
1123
- }
1124
- let lastRefreshKeys = [];
1125
- const scheduleRefresh = createRefresher(
1126
- async () => {
1127
- lastRefreshKeys = cache.keys();
1128
- if (lastRefreshKeys.length === 0) {
1129
- return;
1130
- }
1131
- await projected.refresh(lastRefreshKeys);
1132
- },
1133
- (kind) => {
1134
- if (lastRefreshKeys.length > 0) {
1135
- emit(lastRefreshKeys, kind);
1136
- }
1137
- },
1138
- () => {
1139
- }
1140
- );
1141
- const unsubUpdates = updates$.subscribe((batch) => {
1142
- const evicted = /* @__PURE__ */ new Set();
1143
- const ownModelEvents = batch.entity.get(_def.model);
1144
- if (ownModelEvents) {
1145
- for (const event of ownModelEvents) {
1146
- evicted.add(event.id);
1147
- }
1148
- }
1149
- for (const event of batch.events) {
1150
- for (const key of dependencyCollector.getAffectedKeys(event)) {
1151
- evicted.add(key);
1152
- }
1153
- }
1154
- if (evicted.size > 0) {
1155
- for (const key of evicted) {
1156
- dependencyCollector.removeItem(key);
1157
- projected.delete(key);
1158
- }
1159
- emit([...evicted], "upstream-update");
1160
- }
1161
- });
1162
- return {
1163
- instance: {
1164
- name: _def.name,
1165
- refresh$,
1166
- get(idOrIds) {
1167
- return projected.get(idOrIds);
1168
- },
1169
- refresh() {
1170
- scheduleRefresh("on-demand");
1171
- },
1172
- clear() {
1173
- dependencyCollector.clear();
1174
- projected.clear();
1175
- }
1176
- },
1177
- destroy() {
1178
- unsubUpdates();
1179
- refresh$.complete();
1180
- }
1181
- };
920
+ const opts = options ?? {};
921
+ const mapFn = opts.map ?? ((item) => item);
922
+ const _def = {
923
+ name: opts.name ?? source.__model,
924
+ model: source.__model,
925
+ cache: {
926
+ max: opts.cache?.max ?? 1e3,
927
+ ttl: resolveTtl(opts.cache?.ttl)
928
+ }
929
+ };
930
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
931
+ const cache = createLruCache({
932
+ max: _def.cache.max,
933
+ ttl: _def.cache.ttl,
934
+ onEvict: (_value, key) => dependencyCollector.removeItem(key)
935
+ });
936
+ const projected = new ProjectedLazyMap({
937
+ key: (item) => item.id,
938
+ values: (keys) => wrap(`lazy-collection:${_def.name}`, () => maybeThen$1(collectAsync(mapAsync(client.subscribe(createSourceSubscription(source), { ids: keys }), (r) => r.source)), (rawItems) => Promise.all(rawItems.map((item) => Promise.resolve(dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(item, ref), (mapped) => {
939
+ register(mapped.id);
940
+ return mapped;
941
+ }))))))),
942
+ cache
943
+ });
944
+ const refresh$ = createAsyncIterableSubject();
945
+ function emit(ids, kind) {
946
+ const event = {
947
+ ids,
948
+ kind
949
+ };
950
+ refresh$.next(event);
951
+ opts.onRefresh?.(event);
952
+ }
953
+ let lastRefreshKeys = [];
954
+ const scheduleRefresh = createRefresher(async () => {
955
+ lastRefreshKeys = cache.keys();
956
+ if (lastRefreshKeys.length === 0) return;
957
+ await projected.refresh(lastRefreshKeys);
958
+ }, (kind) => {
959
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys, kind);
960
+ }, () => {});
961
+ const unsubUpdates = updates$.subscribe((batch) => {
962
+ const evicted = /* @__PURE__ */ new Set();
963
+ const ownModelEvents = batch.entity.get(_def.model);
964
+ if (ownModelEvents) for (const event of ownModelEvents) evicted.add(event.id);
965
+ for (const event of batch.events) for (const key of dependencyCollector.getAffectedKeys(event)) evicted.add(key);
966
+ if (evicted.size > 0) {
967
+ for (const key of evicted) {
968
+ dependencyCollector.removeItem(key);
969
+ projected.delete(key);
970
+ }
971
+ emit([...evicted], "upstream-update");
972
+ }
973
+ });
974
+ return {
975
+ instance: {
976
+ name: _def.name,
977
+ refresh$,
978
+ get(idOrIds) {
979
+ return projected.get(idOrIds);
980
+ },
981
+ refresh() {
982
+ scheduleRefresh("on-demand");
983
+ },
984
+ clear() {
985
+ dependencyCollector.clear();
986
+ projected.clear();
987
+ }
988
+ },
989
+ destroy() {
990
+ unsubUpdates();
991
+ refresh$.complete();
992
+ }
993
+ };
1182
994
  }
1183
-
1184
- // src/lazy-routes.ts
1185
- import {
1186
- collectAsync as collectAsync6,
1187
- createSourceSubscription as createSourceSubscription6,
1188
- mapAsync as mapAsync6
1189
- } from "@contello/client";
1190
- import { ProjectedLazyMap as ProjectedLazyMap3 } from "projected";
1191
-
1192
- // src/routes-mapping.ts
995
+ //#endregion
996
+ //#region src/routes-mapping.ts
1193
997
  function mapRoute(raw, resolver) {
1194
- const base = {
1195
- id: raw.id,
1196
- path: raw.path,
1197
- customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value }))
1198
- };
1199
- switch (raw.target.__typename) {
1200
- case "ContelloRouteTargetRedirect": {
1201
- return {
1202
- ...base,
1203
- type: "redirect",
1204
- location: raw.target.location,
1205
- status: raw.target.responseCode
1206
- };
1207
- }
1208
- case "ContelloRouteTargetText": {
1209
- return {
1210
- ...base,
1211
- type: "text",
1212
- content: raw.target.content,
1213
- mimeType: raw.target.mimeType
1214
- };
1215
- }
1216
- case "ContelloRouteTargetAsset": {
1217
- return {
1218
- ...base,
1219
- type: "asset",
1220
- assetId: raw.target.asset.id,
1221
- fileId: raw.target.asset.original.uid,
1222
- contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
1223
- mimeType: raw.target.asset.original.mimeType
1224
- };
1225
- }
1226
- case "ContelloRouteTargetEntity": {
1227
- if (!raw.target.entity) {
1228
- return void 0;
1229
- }
1230
- const entityType = raw.target.entity.__typename;
1231
- return {
1232
- ...base,
1233
- type: "entity",
1234
- model: resolver.resolveModel(entityType),
1235
- entityType,
1236
- entityId: raw.target.entity.id
1237
- };
1238
- }
1239
- default: {
1240
- return void 0;
1241
- }
1242
- }
998
+ const base = {
999
+ id: raw.id,
1000
+ path: raw.path,
1001
+ customHeaders: raw.customHeaders.map((h) => ({
1002
+ name: h.name,
1003
+ value: h.value
1004
+ }))
1005
+ };
1006
+ switch (raw.target.__typename) {
1007
+ case "ContelloRouteTargetRedirect": return {
1008
+ ...base,
1009
+ type: "redirect",
1010
+ location: raw.target.location,
1011
+ status: raw.target.responseCode
1012
+ };
1013
+ case "ContelloRouteTargetText": return {
1014
+ ...base,
1015
+ type: "text",
1016
+ content: raw.target.content,
1017
+ mimeType: raw.target.mimeType
1018
+ };
1019
+ case "ContelloRouteTargetAsset": return {
1020
+ ...base,
1021
+ type: "asset",
1022
+ assetId: raw.target.asset.id,
1023
+ fileId: raw.target.asset.original.uid,
1024
+ contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
1025
+ mimeType: raw.target.asset.original.mimeType
1026
+ };
1027
+ case "ContelloRouteTargetEntity": {
1028
+ if (!raw.target.entity) return;
1029
+ const entityType = raw.target.entity.__typename;
1030
+ return {
1031
+ ...base,
1032
+ type: "entity",
1033
+ model: resolver.resolveModel(entityType),
1034
+ entityType,
1035
+ entityId: raw.target.entity.id
1036
+ };
1037
+ }
1038
+ default: return;
1039
+ }
1243
1040
  }
1244
-
1245
- // src/lazy-routes.ts
1246
- var ID_PREFIX = "1\0";
1247
- var PATH_PREFIX = "2\0";
1248
- var CACHE_KEY = /* @__PURE__ */ Symbol("cacheKey");
1041
+ //#endregion
1042
+ //#region src/lazy-routes.ts
1043
+ const ID_PREFIX = "1\0";
1044
+ const PATH_PREFIX = "2\0";
1045
+ const CACHE_KEY = Symbol("cacheKey");
1249
1046
  function collectRoutes(rawItems, keyFn, resolver) {
1250
- return rawItems.reduce((acc, raw) => {
1251
- const mapped = mapRoute(raw, resolver);
1252
- if (mapped) {
1253
- mapped[CACHE_KEY] = keyFn(mapped);
1254
- acc.push(mapped);
1255
- }
1256
- return acc;
1257
- }, []);
1047
+ return rawItems.reduce((acc, raw) => {
1048
+ const mapped = mapRoute(raw, resolver);
1049
+ if (mapped) {
1050
+ mapped[CACHE_KEY] = keyFn(mapped);
1051
+ acc.push(mapped);
1052
+ }
1053
+ return acc;
1054
+ }, []);
1258
1055
  }
1056
+ /**
1057
+ * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space
1058
+ * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.
1059
+ *
1060
+ * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU
1061
+ * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).
1062
+ */
1259
1063
  function createRoutesCache(max, ttl) {
1260
- const pathToId = /* @__PURE__ */ new Map();
1261
- const idToPath = /* @__PURE__ */ new Map();
1262
- const lru = createLruCache({
1263
- max,
1264
- ttl,
1265
- onEvict: (route) => {
1266
- pathToId.delete(route.path);
1267
- idToPath.delete(route.id);
1268
- }
1269
- });
1270
- function resolveKey(key) {
1271
- if (key.startsWith(PATH_PREFIX)) {
1272
- const id = pathToId.get(key.slice(2));
1273
- if (id) {
1274
- return ID_PREFIX + id;
1275
- }
1276
- return key;
1277
- }
1278
- return key;
1279
- }
1280
- return {
1281
- has: (key) => lru.has(resolveKey(key)),
1282
- get: (key) => lru.get(resolveKey(key)),
1283
- set: (_key, value) => {
1284
- const previousPath = idToPath.get(value.id);
1285
- if (previousPath !== void 0 && previousPath !== value.path) {
1286
- pathToId.delete(previousPath);
1287
- }
1288
- pathToId.set(value.path, value.id);
1289
- idToPath.set(value.id, value.path);
1290
- lru.set(ID_PREFIX + value.id, value);
1291
- },
1292
- delete: (key) => {
1293
- const resolved = resolveKey(key);
1294
- const value = lru.get(resolved);
1295
- if (value) {
1296
- pathToId.delete(value.path);
1297
- idToPath.delete(value.id);
1298
- }
1299
- lru.delete(resolved);
1300
- },
1301
- clear: () => {
1302
- pathToId.clear();
1303
- idToPath.clear();
1304
- lru.clear();
1305
- },
1306
- keys: () => lru.keys()
1307
- };
1064
+ const pathToId = /* @__PURE__ */ new Map();
1065
+ const idToPath = /* @__PURE__ */ new Map();
1066
+ const lru = createLruCache({
1067
+ max,
1068
+ ttl,
1069
+ onEvict: (route) => {
1070
+ pathToId.delete(route.path);
1071
+ idToPath.delete(route.id);
1072
+ }
1073
+ });
1074
+ function resolveKey(key) {
1075
+ if (key.startsWith(PATH_PREFIX)) {
1076
+ const id = pathToId.get(key.slice(2));
1077
+ if (id) return ID_PREFIX + id;
1078
+ return key;
1079
+ }
1080
+ return key;
1081
+ }
1082
+ return {
1083
+ has: (key) => lru.has(resolveKey(key)),
1084
+ get: (key) => lru.get(resolveKey(key)),
1085
+ set: (_key, value) => {
1086
+ const previousPath = idToPath.get(value.id);
1087
+ if (previousPath !== void 0 && previousPath !== value.path) pathToId.delete(previousPath);
1088
+ pathToId.set(value.path, value.id);
1089
+ idToPath.set(value.id, value.path);
1090
+ lru.set(ID_PREFIX + value.id, value);
1091
+ },
1092
+ delete: (key) => {
1093
+ const resolved = resolveKey(key);
1094
+ const value = lru.get(resolved);
1095
+ if (value) {
1096
+ pathToId.delete(value.path);
1097
+ idToPath.delete(value.id);
1098
+ }
1099
+ lru.delete(resolved);
1100
+ },
1101
+ clear: () => {
1102
+ pathToId.clear();
1103
+ idToPath.clear();
1104
+ lru.clear();
1105
+ },
1106
+ keys: () => lru.keys()
1107
+ };
1308
1108
  }
1309
1109
  function createLazyRoutesCollection(def, client, updates$, resolver) {
1310
- const _def = {
1311
- cache: {
1312
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1313
- ttl: resolveTtl(def?.cache?.ttl)
1314
- }
1315
- };
1316
- const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1317
- const routesSourceDoc = createSourceSubscription6(schema.sources.storeRoute);
1318
- function fetchRoutes(vars) {
1319
- return collectAsync6(
1320
- mapAsync6(client.subscribe(routesSourceDoc, vars), (data) => data.source)
1321
- );
1322
- }
1323
- const projected = new ProjectedLazyMap3({
1324
- key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1325
- values: (prefixedKeys) => wrap("routes", () => {
1326
- const ids = [];
1327
- const paths = [];
1328
- for (const key of prefixedKeys) {
1329
- const value = key.slice(2);
1330
- if (key.startsWith(ID_PREFIX)) {
1331
- ids.push(value);
1332
- } else {
1333
- paths.push(value);
1334
- }
1335
- }
1336
- return Promise.all([
1337
- ids.length > 0 ? fetchRoutes({ ids }).then((raw) => collectRoutes(raw, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1338
- paths.length > 0 ? fetchRoutes({ paths }).then((raw) => collectRoutes(raw, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1339
- ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1340
- }),
1341
- cache
1342
- });
1343
- const channel = createRefreshChannel(def?.onRefresh);
1344
- function emit(ids, kind) {
1345
- channel.emit({ ids, kind });
1346
- }
1347
- let lastRefreshKeys = [];
1348
- const scheduleRefresh = createRefresher(
1349
- async () => {
1350
- lastRefreshKeys = cache.keys();
1351
- if (lastRefreshKeys.length === 0) {
1352
- return;
1353
- }
1354
- await projected.refresh(lastRefreshKeys);
1355
- },
1356
- (kind) => {
1357
- if (lastRefreshKeys.length > 0) {
1358
- emit(
1359
- lastRefreshKeys.map((key) => key.slice(2)),
1360
- kind
1361
- );
1362
- }
1363
- },
1364
- () => {
1365
- }
1366
- );
1367
- const unsubUpdates = updates$.subscribe((batch) => {
1368
- const evicted = [];
1369
- for (const event of batch.route) {
1370
- const idKey = ID_PREFIX + event.id;
1371
- if (event.mutation === "delete") {
1372
- cache.delete(idKey);
1373
- evicted.push(event.id);
1374
- } else {
1375
- if (cache.has(idKey)) {
1376
- cache.set(idKey, event.after);
1377
- }
1378
- evicted.push(event.after.path);
1379
- }
1380
- }
1381
- if (evicted.length > 0) {
1382
- emit(evicted, "upstream-update");
1383
- }
1384
- });
1385
- return {
1386
- instance: {
1387
- refresh$: channel.stream$,
1388
- get(idOrIds) {
1389
- if (Array.isArray(idOrIds)) {
1390
- return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1391
- }
1392
- return projected.get(ID_PREFIX + idOrIds);
1393
- },
1394
- getByPath(pathOrPaths) {
1395
- if (Array.isArray(pathOrPaths)) {
1396
- return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1397
- }
1398
- return projected.get(PATH_PREFIX + pathOrPaths);
1399
- },
1400
- refresh() {
1401
- scheduleRefresh("on-demand");
1402
- },
1403
- clear() {
1404
- projected.clear();
1405
- }
1406
- },
1407
- destroy() {
1408
- unsubUpdates();
1409
- channel.complete();
1410
- }
1411
- };
1110
+ const _def = { cache: {
1111
+ max: def?.cache?.max ?? 1e3,
1112
+ ttl: resolveTtl(def?.cache?.ttl)
1113
+ } };
1114
+ const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1115
+ const routesSourceDoc = createSourceSubscription(schema.sources.storeRoute);
1116
+ function fetchRoutes(vars) {
1117
+ return collectAsync(mapAsync(client.subscribe(routesSourceDoc, vars), (data) => data.source));
1118
+ }
1119
+ const projected = new ProjectedLazyMap({
1120
+ key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1121
+ values: (prefixedKeys) => wrap("routes", async () => {
1122
+ const ids = [];
1123
+ const paths = [];
1124
+ for (const key of prefixedKeys) {
1125
+ const value = key.slice(2);
1126
+ if (key.startsWith(ID_PREFIX)) ids.push(value);
1127
+ else paths.push(value);
1128
+ }
1129
+ const [rawByIds, rawByPaths] = await Promise.all([ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve([]), paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve([])]);
1130
+ const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);
1131
+ const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + r.path, resolver);
1132
+ return [...byIds, ...byPaths];
1133
+ }),
1134
+ cache
1135
+ });
1136
+ const channel = createRefreshChannel(def?.onRefresh);
1137
+ function emit(ids, kind) {
1138
+ channel.emit({
1139
+ ids,
1140
+ kind
1141
+ });
1142
+ }
1143
+ let lastRefreshKeys = [];
1144
+ const scheduleRefresh = createRefresher(async () => {
1145
+ lastRefreshKeys = cache.keys();
1146
+ if (lastRefreshKeys.length === 0) return;
1147
+ await projected.refresh(lastRefreshKeys);
1148
+ }, (kind) => {
1149
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys.map((key) => key.slice(2)), kind);
1150
+ }, () => {});
1151
+ const unsubUpdates = updates$.subscribe((batch) => {
1152
+ const evicted = [];
1153
+ for (const event of batch.route) {
1154
+ const idKey = ID_PREFIX + event.id;
1155
+ if (event.mutation === "delete") {
1156
+ cache.delete(idKey);
1157
+ evicted.push(event.id);
1158
+ } else {
1159
+ if (cache.has(idKey)) cache.set(idKey, event.after);
1160
+ evicted.push(event.after.path);
1161
+ }
1162
+ }
1163
+ if (evicted.length > 0) emit(evicted, "upstream-update");
1164
+ });
1165
+ return {
1166
+ instance: {
1167
+ refresh$: channel.stream$,
1168
+ get(idOrIds) {
1169
+ if (Array.isArray(idOrIds)) return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1170
+ return projected.get(ID_PREFIX + idOrIds);
1171
+ },
1172
+ getByPath(pathOrPaths) {
1173
+ if (Array.isArray(pathOrPaths)) return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1174
+ return projected.get(PATH_PREFIX + pathOrPaths);
1175
+ },
1176
+ refresh() {
1177
+ scheduleRefresh("on-demand");
1178
+ },
1179
+ clear() {
1180
+ projected.clear();
1181
+ }
1182
+ },
1183
+ destroy() {
1184
+ unsubUpdates();
1185
+ channel.complete();
1186
+ }
1187
+ };
1412
1188
  }
1413
-
1414
- // src/model-resolver.ts
1189
+ //#endregion
1190
+ //#region src/model-resolver.ts
1415
1191
  var ModelResolver = class {
1416
- _typeNames;
1417
- _toModel;
1418
- _toTypeName;
1419
- constructor(models2) {
1420
- const toModel = /* @__PURE__ */ new Map();
1421
- const toTypeName = /* @__PURE__ */ new Map();
1422
- let typeNames;
1423
- if (models2) {
1424
- typeNames = /* @__PURE__ */ new Set();
1425
- for (const [model, typeName] of Object.entries(models2)) {
1426
- toModel.set(typeName, model);
1427
- toTypeName.set(model, typeName);
1428
- typeNames.add(typeName);
1429
- }
1430
- }
1431
- this._typeNames = typeNames;
1432
- this._toModel = toModel;
1433
- this._toTypeName = toTypeName;
1434
- }
1435
- hasTypeName(typeName) {
1436
- return !this._typeNames || this._typeNames.has(typeName);
1437
- }
1438
- getModel(typeName) {
1439
- return this._toModel.get(typeName);
1440
- }
1441
- getTypeName(model) {
1442
- return this._toTypeName.get(model) ?? model;
1443
- }
1444
- hasModel(model) {
1445
- return this._toTypeName.size === 0 || this._toTypeName.has(model);
1446
- }
1447
- resolveModel(typeName) {
1448
- return this._toModel.get(typeName) ?? typeName;
1449
- }
1192
+ _typeNames;
1193
+ _toModel;
1194
+ _toTypeName;
1195
+ constructor(models) {
1196
+ const toModel = /* @__PURE__ */ new Map();
1197
+ const toTypeName = /* @__PURE__ */ new Map();
1198
+ let typeNames;
1199
+ if (models) {
1200
+ typeNames = /* @__PURE__ */ new Set();
1201
+ for (const [model, typeName] of Object.entries(models)) {
1202
+ toModel.set(typeName, model);
1203
+ toTypeName.set(model, typeName);
1204
+ typeNames.add(typeName);
1205
+ }
1206
+ }
1207
+ this._typeNames = typeNames;
1208
+ this._toModel = toModel;
1209
+ this._toTypeName = toTypeName;
1210
+ }
1211
+ hasTypeName(typeName) {
1212
+ return !this._typeNames || this._typeNames.has(typeName);
1213
+ }
1214
+ getModel(typeName) {
1215
+ return this._toModel.get(typeName);
1216
+ }
1217
+ getTypeName(model) {
1218
+ return this._toTypeName.get(model) ?? model;
1219
+ }
1220
+ hasModel(model) {
1221
+ return this._toTypeName.size === 0 || this._toTypeName.has(model);
1222
+ }
1223
+ resolveModel(typeName) {
1224
+ return this._toModel.get(typeName) ?? typeName;
1225
+ }
1450
1226
  };
1451
-
1452
- // src/routes.ts
1453
- import {
1454
- collectAsync as collectAsync7,
1455
- createSourceSubscription as createSourceSubscription7,
1456
- mapAsync as mapAsync7,
1457
- runWithBackoff as runWithBackoff5
1458
- } from "@contello/client";
1459
- import { ProjectedMap as ProjectedMap4, maybeThen as maybeThen4 } from "projected";
1227
+ //#endregion
1228
+ //#region src/routes.ts
1460
1229
  function createRoutesCollection(options, client, updates$, resolver, refreshByTtl) {
1461
- const opts = options ?? {};
1462
- const cache = {
1463
- ttl: resolveTtl(opts.cache?.ttl),
1464
- eviction: opts.cache?.eviction ?? "refresh"
1465
- };
1466
- const channel = createRefreshChannel(opts.onRefresh);
1467
- const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
1468
- const pathById = /* @__PURE__ */ new Map();
1469
- const idByPath = /* @__PURE__ */ new Map();
1470
- let loaded = false;
1471
- const routesSourceDoc = createSourceSubscription7(schema.sources.storeRoute);
1472
- const projected = new ProjectedMap4({
1473
- key: (route) => route.id,
1474
- values: (ids) => wrap(
1475
- "routes",
1476
- () => collectAsync7(
1477
- mapAsync7(client.subscribe(routesSourceDoc, { ids }), (data) => data.source)
1478
- ).then((rawItems) => {
1479
- const items = rawItems.reduce((acc, raw) => {
1480
- const mapped = mapRoute(raw, resolver);
1481
- if (mapped) {
1482
- acc.push(mapped);
1483
- }
1484
- return acc;
1485
- }, []);
1486
- if (ids === void 0) {
1487
- pathById.clear();
1488
- idByPath.clear();
1489
- for (const r of items) {
1490
- pathById.set(r.id, r.path);
1491
- idByPath.set(r.path, r.id);
1492
- }
1493
- if (!loaded) {
1494
- loaded = true;
1495
- ttl.mark();
1496
- opts.onLoad?.(items.map((r) => r.id));
1497
- }
1498
- } else {
1499
- const returnedIds = new Set(items.map((r) => r.id));
1500
- for (const id of ids) {
1501
- if (!returnedIds.has(id)) {
1502
- const oldPath = pathById.get(id);
1503
- if (oldPath !== void 0) {
1504
- idByPath.delete(oldPath);
1505
- pathById.delete(id);
1506
- }
1507
- }
1508
- }
1509
- for (const r of items) {
1510
- const oldPath = pathById.get(r.id);
1511
- if (oldPath !== void 0 && oldPath !== r.path) {
1512
- idByPath.delete(oldPath);
1513
- }
1514
- pathById.set(r.id, r.path);
1515
- idByPath.set(r.path, r.id);
1516
- }
1517
- }
1518
- return items;
1519
- })
1520
- )
1521
- });
1522
- function emit(ids, kind) {
1523
- channel.emit({ ids, kind });
1524
- }
1525
- function runFullRefresh(kind) {
1526
- refreshByTtl.enqueue(
1527
- () => runWithBackoff5(
1528
- () => projected.refresh().then((map) => {
1529
- emit([...map.keys()], kind);
1530
- ttl.mark();
1531
- })
1532
- )
1533
- );
1534
- }
1535
- function runPartialRefresh(refreshIds, deletedIds) {
1536
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1537
- if (refreshIds.length === 0) {
1538
- emit(changedIds, "upstream-update");
1539
- return;
1540
- }
1541
- void runWithBackoff5(
1542
- () => projected.refresh(refreshIds).then(() => {
1543
- emit(changedIds, "upstream-update");
1544
- })
1545
- );
1546
- }
1547
- const unsubUpdates = updates$.subscribe((batch) => {
1548
- if (!loaded || batch.route.length === 0) {
1549
- return;
1550
- }
1551
- const deleted = [];
1552
- const upserted = /* @__PURE__ */ new Set();
1553
- for (const event of batch.route) {
1554
- if (event.mutation === "delete") {
1555
- deleted.push(event.id);
1556
- } else {
1557
- upserted.add(event.id);
1558
- }
1559
- }
1560
- if (cache.eviction === "clear") {
1561
- pathById.clear();
1562
- idByPath.clear();
1563
- projected.clear();
1564
- return;
1565
- }
1566
- for (const id of deleted) {
1567
- const oldPath = pathById.get(id);
1568
- if (oldPath !== void 0) {
1569
- idByPath.delete(oldPath);
1570
- pathById.delete(id);
1571
- }
1572
- }
1573
- if (deleted.length > 0) {
1574
- projected.delete(deleted);
1575
- }
1576
- runPartialRefresh([...upserted], deleted);
1577
- });
1578
- function getByIdSingle(id) {
1579
- return projected.get(id);
1580
- }
1581
- function getByIds(ids) {
1582
- return projected.get(ids);
1583
- }
1584
- function lookupByPathSingle(path) {
1585
- return maybeThen4(ensureLoaded(), () => {
1586
- const id = idByPath.get(path);
1587
- return id === void 0 ? void 0 : projected.get(id);
1588
- });
1589
- }
1590
- function lookupByPaths(paths) {
1591
- return maybeThen4(ensureLoaded(), () => {
1592
- const ids = [];
1593
- for (const p of paths) {
1594
- const id = idByPath.get(p);
1595
- if (id !== void 0) {
1596
- ids.push(id);
1597
- }
1598
- }
1599
- return projected.get(ids);
1600
- });
1601
- }
1602
- function ensureLoaded() {
1603
- if (loaded) {
1604
- return void 0;
1605
- }
1606
- return maybeThen4(projected.getAllAsMap(), () => {
1607
- });
1608
- }
1609
- const instance = {
1610
- refresh$: channel.stream$,
1611
- async load() {
1612
- if (!loaded) {
1613
- await projected.getAllAsMap();
1614
- }
1615
- },
1616
- get(idOrIds) {
1617
- return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1618
- },
1619
- getByPath(pathOrPaths) {
1620
- return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1621
- },
1622
- refresh() {
1623
- runFullRefresh("on-demand");
1624
- }
1625
- };
1626
- return {
1627
- instance,
1628
- destroy() {
1629
- unsubUpdates();
1630
- ttl.clear();
1631
- channel.complete();
1632
- }
1633
- };
1230
+ const opts = options ?? {};
1231
+ const cache = {
1232
+ ttl: resolveTtl(opts.cache?.ttl),
1233
+ eviction: opts.cache?.eviction ?? "refresh"
1234
+ };
1235
+ const channel = createRefreshChannel(opts.onRefresh);
1236
+ const ttl = createTtlOrchestrator({
1237
+ ttl: cache.ttl,
1238
+ run: () => runFullRefresh("ttl")
1239
+ });
1240
+ const pathById = /* @__PURE__ */ new Map();
1241
+ const idByPath = /* @__PURE__ */ new Map();
1242
+ let loaded = false;
1243
+ const routesSourceDoc = createSourceSubscription(schema.sources.storeRoute);
1244
+ const projected = new ProjectedMap({
1245
+ key: (route) => route.id,
1246
+ values: (ids) => wrap("routes", async () => {
1247
+ const items = (await collectAsync(mapAsync(client.subscribe(routesSourceDoc, { ids }), (data) => data.source))).reduce((acc, raw) => {
1248
+ const mapped = mapRoute(raw, resolver);
1249
+ if (mapped) acc.push(mapped);
1250
+ return acc;
1251
+ }, []);
1252
+ if (ids === void 0) {
1253
+ pathById.clear();
1254
+ idByPath.clear();
1255
+ for (const r of items) {
1256
+ pathById.set(r.id, r.path);
1257
+ idByPath.set(r.path, r.id);
1258
+ }
1259
+ if (!loaded) {
1260
+ loaded = true;
1261
+ ttl.mark();
1262
+ opts.onLoad?.(items.map((r) => r.id));
1263
+ }
1264
+ } else {
1265
+ const returnedIds = new Set(items.map((r) => r.id));
1266
+ for (const id of ids) {
1267
+ if (returnedIds.has(id)) continue;
1268
+ const oldPath = pathById.get(id);
1269
+ if (oldPath !== void 0) {
1270
+ idByPath.delete(oldPath);
1271
+ pathById.delete(id);
1272
+ }
1273
+ }
1274
+ for (const r of items) {
1275
+ const oldPath = pathById.get(r.id);
1276
+ if (oldPath !== void 0 && oldPath !== r.path) idByPath.delete(oldPath);
1277
+ pathById.set(r.id, r.path);
1278
+ idByPath.set(r.path, r.id);
1279
+ }
1280
+ }
1281
+ return items;
1282
+ })
1283
+ });
1284
+ function emit(ids, kind) {
1285
+ channel.emit({
1286
+ ids,
1287
+ kind
1288
+ });
1289
+ }
1290
+ function runFullRefresh(kind) {
1291
+ refreshByTtl.enqueue(() => runWithBackoff(async () => {
1292
+ emit((await projected.refresh()).keys().toArray(), kind);
1293
+ ttl.mark();
1294
+ }));
1295
+ }
1296
+ function runPartialRefresh(refreshIds, deletedIds) {
1297
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1298
+ if (refreshIds.length === 0) {
1299
+ emit(changedIds, "upstream-update");
1300
+ return;
1301
+ }
1302
+ runWithBackoff(async () => {
1303
+ await projected.refresh(refreshIds);
1304
+ emit(changedIds, "upstream-update");
1305
+ });
1306
+ }
1307
+ const unsubUpdates = updates$.subscribe((batch) => {
1308
+ if (!loaded || batch.route.length === 0) return;
1309
+ const deleted = [];
1310
+ const upserted = /* @__PURE__ */ new Set();
1311
+ for (const event of batch.route) if (event.mutation === "delete") deleted.push(event.id);
1312
+ else upserted.add(event.id);
1313
+ if (cache.eviction === "clear") {
1314
+ pathById.clear();
1315
+ idByPath.clear();
1316
+ projected.clear();
1317
+ return;
1318
+ }
1319
+ for (const id of deleted) {
1320
+ const oldPath = pathById.get(id);
1321
+ if (oldPath !== void 0) {
1322
+ idByPath.delete(oldPath);
1323
+ pathById.delete(id);
1324
+ }
1325
+ }
1326
+ if (deleted.length > 0) projected.delete(deleted);
1327
+ runPartialRefresh([...upserted], deleted);
1328
+ });
1329
+ function getByIdSingle(id) {
1330
+ return projected.get(id);
1331
+ }
1332
+ function getByIds(ids) {
1333
+ return projected.get(ids);
1334
+ }
1335
+ function lookupByPathSingle(path) {
1336
+ return maybeThen$1(ensureLoaded(), () => {
1337
+ const id = idByPath.get(path);
1338
+ return id === void 0 ? void 0 : projected.get(id);
1339
+ });
1340
+ }
1341
+ function lookupByPaths(paths) {
1342
+ return maybeThen$1(ensureLoaded(), () => {
1343
+ const ids = [];
1344
+ for (const p of paths) {
1345
+ const id = idByPath.get(p);
1346
+ if (id !== void 0) ids.push(id);
1347
+ }
1348
+ return projected.get(ids);
1349
+ });
1350
+ }
1351
+ function ensureLoaded() {
1352
+ if (loaded) return;
1353
+ return maybeThen$1(projected.getAllAsMap(), () => {});
1354
+ }
1355
+ return {
1356
+ instance: {
1357
+ refresh$: channel.stream$,
1358
+ async load() {
1359
+ if (!loaded) await projected.getAllAsMap();
1360
+ },
1361
+ get(idOrIds) {
1362
+ return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1363
+ },
1364
+ getByPath(pathOrPaths) {
1365
+ return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1366
+ },
1367
+ refresh() {
1368
+ runFullRefresh("on-demand");
1369
+ }
1370
+ },
1371
+ destroy() {
1372
+ unsubUpdates();
1373
+ ttl.clear();
1374
+ channel.complete();
1375
+ }
1376
+ };
1634
1377
  }
1635
1378
  function createRoutesSyncCollection(options, client, updates$, resolver, refreshByTtl) {
1636
- const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1637
- function assertSync(value, method) {
1638
- if (value instanceof Promise) {
1639
- throw new TypeError(`routes.${method}() is not initialized yet \u2014 call routes.load() first`);
1640
- }
1641
- return value;
1642
- }
1643
- return {
1644
- instance: {
1645
- ...base,
1646
- get(idOrIds) {
1647
- return assertSync(base.get(idOrIds), "get");
1648
- },
1649
- getByPath(pathOrPaths) {
1650
- return assertSync(base.getByPath(pathOrPaths), "getByPath");
1651
- }
1652
- },
1653
- destroy
1654
- };
1379
+ const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1380
+ function assertSync(value, method) {
1381
+ if (value instanceof Promise) throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);
1382
+ return value;
1383
+ }
1384
+ return {
1385
+ instance: {
1386
+ ...base,
1387
+ get(idOrIds) {
1388
+ return assertSync(base.get(idOrIds), "get");
1389
+ },
1390
+ getByPath(pathOrPaths) {
1391
+ return assertSync(base.getByPath(pathOrPaths), "getByPath");
1392
+ }
1393
+ },
1394
+ destroy
1395
+ };
1655
1396
  }
1656
-
1657
- // src/singleton.ts
1658
- import {
1659
- createSourceSubscription as createSourceSubscription8,
1660
- firstAsync,
1661
- mapAsync as mapAsync8,
1662
- runWithBackoff as runWithBackoff6
1663
- } from "@contello/client";
1664
- import { ProjectedValue, maybeThen as maybeThen5 } from "projected";
1397
+ //#endregion
1398
+ //#region src/singleton.ts
1665
1399
  function createSingleton(source, options, client, updates$, resolver, refreshByTtl) {
1666
- const opts = options ?? {};
1667
- const mapFn = opts.map ?? ((item) => item);
1668
- const _def = {
1669
- name: opts.name ?? source.__model,
1670
- model: source.__model,
1671
- cache: {
1672
- ttl: resolveTtl(opts.cache?.ttl),
1673
- eviction: opts.cache?.eviction ?? "refresh"
1674
- }
1675
- };
1676
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1677
- const itemKey = `singleton:${_def.name}`;
1678
- const channel = createRefreshChannel(opts.onRefresh);
1679
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });
1680
- let loaded = false;
1681
- const projected = new ProjectedValue({
1682
- value: () => wrap(
1683
- `singleton:${_def.name}`,
1684
- () => maybeThen5(
1685
- firstAsync(
1686
- mapAsync8(
1687
- client.subscribe(createSourceSubscription8(source)),
1688
- (r) => r.source
1689
- )
1690
- ),
1691
- (raw) => dependencyCollector.createContext(
1692
- (ref, register) => maybeThen5(mapFn(raw, ref), (mapped) => {
1693
- register(itemKey);
1694
- if (!loaded) {
1695
- loaded = true;
1696
- ttl.mark();
1697
- opts.onLoad?.();
1698
- }
1699
- return mapped;
1700
- })
1701
- )
1702
- )
1703
- )
1704
- });
1705
- function emit(kind) {
1706
- channel.emit({ kind });
1707
- }
1708
- function runTtlRefresh() {
1709
- refreshByTtl.enqueue(
1710
- () => runWithBackoff6(() => projected.refresh()).then(() => {
1711
- emit("ttl");
1712
- ttl.mark();
1713
- })
1714
- );
1715
- }
1716
- const scheduleRefresh = createRefresher(
1717
- () => projected.refresh(),
1718
- (kind) => {
1719
- emit(kind);
1720
- ttl.mark();
1721
- },
1722
- () => {
1723
- }
1724
- );
1725
- const unsubUpdates = updates$.subscribe((batch) => {
1726
- if (!loaded) {
1727
- return;
1728
- }
1729
- const hasOwnModel = batch.entity.has(_def.model);
1730
- const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
1731
- if (!hasOwnModel && !hasAffectedRefs) {
1732
- return;
1733
- }
1734
- if (_def.cache.eviction === "clear") {
1735
- dependencyCollector.clear();
1736
- projected.clear();
1737
- return;
1738
- }
1739
- scheduleRefresh("upstream-update");
1740
- });
1741
- return {
1742
- instance: {
1743
- name: _def.name,
1744
- refresh$: channel.stream$,
1745
- get() {
1746
- return projected.get();
1747
- },
1748
- refresh() {
1749
- scheduleRefresh("on-demand");
1750
- },
1751
- async load() {
1752
- if (!loaded) {
1753
- await projected.get();
1754
- }
1755
- }
1756
- },
1757
- destroy() {
1758
- unsubUpdates();
1759
- ttl.clear();
1760
- channel.complete();
1761
- }
1762
- };
1400
+ const opts = options ?? {};
1401
+ const mapFn = opts.map ?? ((item) => item);
1402
+ const _def = {
1403
+ name: opts.name ?? source.__model,
1404
+ model: source.__model,
1405
+ cache: {
1406
+ ttl: resolveTtl(opts.cache?.ttl),
1407
+ eviction: opts.cache?.eviction ?? "refresh"
1408
+ }
1409
+ };
1410
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
1411
+ const itemKey = `singleton:${_def.name}`;
1412
+ const channel = createRefreshChannel(opts.onRefresh);
1413
+ const ttl = createTtlOrchestrator({
1414
+ ttl: _def.cache.ttl,
1415
+ run: () => runTtlRefresh()
1416
+ });
1417
+ let loaded = false;
1418
+ const projected = new ProjectedValue({ value: () => wrap(`singleton:${_def.name}`, () => maybeThen$1(firstAsync(mapAsync(client.subscribe(createSourceSubscription(source)), (r) => r.source)), (raw) => dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(raw, ref), (mapped) => {
1419
+ register(itemKey);
1420
+ if (!loaded) {
1421
+ loaded = true;
1422
+ ttl.mark();
1423
+ opts.onLoad?.();
1424
+ }
1425
+ return mapped;
1426
+ })))) });
1427
+ function emit(kind) {
1428
+ channel.emit({ kind });
1429
+ }
1430
+ function runTtlRefresh() {
1431
+ refreshByTtl.enqueue(async () => {
1432
+ await runWithBackoff(() => projected.refresh());
1433
+ emit("ttl");
1434
+ ttl.mark();
1435
+ });
1436
+ }
1437
+ const scheduleRefresh = createRefresher(() => projected.refresh(), (kind) => {
1438
+ emit(kind);
1439
+ ttl.mark();
1440
+ }, () => {});
1441
+ const unsubUpdates = updates$.subscribe((batch) => {
1442
+ if (!loaded) return;
1443
+ const hasOwnModel = batch.entity.has(_def.model);
1444
+ const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
1445
+ if (!hasOwnModel && !hasAffectedRefs) return;
1446
+ if (_def.cache.eviction === "clear") {
1447
+ dependencyCollector.clear();
1448
+ projected.clear();
1449
+ return;
1450
+ }
1451
+ scheduleRefresh("upstream-update");
1452
+ });
1453
+ return {
1454
+ instance: {
1455
+ name: _def.name,
1456
+ refresh$: channel.stream$,
1457
+ get() {
1458
+ return projected.get();
1459
+ },
1460
+ refresh() {
1461
+ scheduleRefresh("on-demand");
1462
+ },
1463
+ async load() {
1464
+ if (!loaded) await projected.get();
1465
+ }
1466
+ },
1467
+ destroy() {
1468
+ unsubUpdates();
1469
+ ttl.clear();
1470
+ channel.complete();
1471
+ }
1472
+ };
1763
1473
  }
1764
1474
  function createSingletonSync(source, options, client, updates$, resolver, refreshByTtl) {
1765
- const { instance: base, destroy } = createSingleton(
1766
- source,
1767
- options,
1768
- client,
1769
- updates$,
1770
- resolver,
1771
- refreshByTtl
1772
- );
1773
- return {
1774
- instance: {
1775
- ...base,
1776
- get() {
1777
- const result = base.get();
1778
- if (result instanceof Promise) {
1779
- throw new TypeError(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1780
- }
1781
- return result;
1782
- }
1783
- },
1784
- destroy
1785
- };
1475
+ const { instance: base, destroy } = createSingleton(source, options, client, updates$, resolver, refreshByTtl);
1476
+ return {
1477
+ instance: {
1478
+ ...base,
1479
+ get() {
1480
+ const result = base.get();
1481
+ if (result instanceof Promise) throw new TypeError(`singleton "${base.name}" is not initialized yet — call singleton.load() first`);
1482
+ return result;
1483
+ }
1484
+ },
1485
+ destroy
1486
+ };
1786
1487
  }
1787
-
1788
- // src/watcher.ts
1789
- import {
1790
- asyncKeepalive,
1791
- createAsyncIterableSubject as createAsyncIterableSubject3,
1792
- mapAsync as mapAsync9
1793
- } from "@contello/client";
1488
+ //#endregion
1489
+ //#region src/watcher.ts
1794
1490
  function addRouteByModel(map, entityType, event) {
1795
- let list = map.get(entityType);
1796
- if (!list) {
1797
- list = [];
1798
- map.set(entityType, list);
1799
- }
1800
- list.push(event);
1491
+ let list = map.get(entityType);
1492
+ if (!list) {
1493
+ list = [];
1494
+ map.set(entityType, list);
1495
+ }
1496
+ list.push(event);
1497
+ }
1498
+ function addEventToBatch(batch, event) {
1499
+ switch (event.target) {
1500
+ case "route":
1501
+ batch.route.push(event);
1502
+ if ("after" in event && event.after.type === "entity") addRouteByModel(batch.routeByEntityModel, event.after.model, event);
1503
+ if ("before" in event && event.before.type === "entity") addRouteByModel(batch.routeByEntityModel, event.before.model, event);
1504
+ break;
1505
+ case "asset":
1506
+ batch.asset.push(event);
1507
+ break;
1508
+ case "i18nMessage":
1509
+ batch.i18nMessage.push(event);
1510
+ break;
1511
+ case "entity": {
1512
+ let list = batch.entity.get(event.model);
1513
+ if (!list) {
1514
+ list = [];
1515
+ batch.entity.set(event.model, list);
1516
+ }
1517
+ list.push(event);
1518
+ break;
1519
+ }
1520
+ }
1801
1521
  }
1802
1522
  function createUpdateBatch(events) {
1803
- const route = [];
1804
- const asset = [];
1805
- const i18nMessage = [];
1806
- const entity = /* @__PURE__ */ new Map();
1807
- const routeByEntityModel = /* @__PURE__ */ new Map();
1808
- for (const event of events) {
1809
- switch (event.target) {
1810
- case "route": {
1811
- route.push(event);
1812
- if ("after" in event && event.after.type === "entity") {
1813
- addRouteByModel(routeByEntityModel, event.after.model, event);
1814
- }
1815
- if ("before" in event && event.before.type === "entity") {
1816
- addRouteByModel(routeByEntityModel, event.before.model, event);
1817
- }
1818
- break;
1819
- }
1820
- case "asset": {
1821
- asset.push(event);
1822
- break;
1823
- }
1824
- case "i18nMessage": {
1825
- i18nMessage.push(event);
1826
- break;
1827
- }
1828
- case "entity": {
1829
- let list = entity.get(event.model);
1830
- if (!list) {
1831
- list = [];
1832
- entity.set(event.model, list);
1833
- }
1834
- list.push(event);
1835
- break;
1836
- }
1837
- }
1838
- }
1839
- return { events, route, asset, i18nMessage, entity, routeByEntityModel };
1523
+ const batch = {
1524
+ route: [],
1525
+ asset: [],
1526
+ i18nMessage: [],
1527
+ entity: /* @__PURE__ */ new Map(),
1528
+ routeByEntityModel: /* @__PURE__ */ new Map()
1529
+ };
1530
+ for (const event of events) addEventToBatch(batch, event);
1531
+ return {
1532
+ events,
1533
+ route: batch.route,
1534
+ asset: batch.asset,
1535
+ i18nMessage: batch.i18nMessage,
1536
+ entity: batch.entity,
1537
+ routeByEntityModel: batch.routeByEntityModel
1538
+ };
1840
1539
  }
1841
1540
  function castMutationType(type) {
1842
- switch (type) {
1843
- case "CREATE": {
1844
- return "create";
1845
- }
1846
- case "UPDATE": {
1847
- return "update";
1848
- }
1849
- case "DELETE": {
1850
- return "delete";
1851
- }
1852
- }
1541
+ switch (type) {
1542
+ case "CREATE": return "create";
1543
+ case "UPDATE": return "update";
1544
+ case "DELETE": return "delete";
1545
+ }
1853
1546
  }
1854
1547
  function mapEvent(raw, resolver) {
1855
- const mutation = castMutationType(raw.mutation.type);
1856
- const target = raw.target;
1857
- const { id, __typename } = target;
1858
- switch (__typename) {
1859
- case "ContelloRoute": {
1860
- if (mutation === "delete") {
1861
- return { id, mutation: "delete", target: "route" };
1862
- }
1863
- const after = mapRoute(target, resolver);
1864
- if (!after) {
1865
- return void 0;
1866
- }
1867
- if (mutation === "create") {
1868
- return { id, mutation, target: "route", after };
1869
- }
1870
- const before = raw.prev?.__typename === "ContelloRoute" ? mapRoute(raw.prev, resolver) ?? void 0 : void 0;
1871
- if (!before) {
1872
- return void 0;
1873
- }
1874
- return { id, mutation, target: "route", after, before };
1875
- }
1876
- case "ContelloAsset": {
1877
- return { id, mutation, target: "asset" };
1878
- }
1879
- case "ContelloI18nMessage": {
1880
- return { id, mutation, target: "i18nMessage", token: target.token };
1881
- }
1882
- default: {
1883
- if (!__typename || !resolver.hasTypeName(__typename)) {
1884
- return void 0;
1885
- }
1886
- return { id, mutation, target: "entity", model: resolver.resolveModel(__typename) };
1887
- }
1888
- }
1548
+ const mutation = castMutationType(raw.mutation.type);
1549
+ const target = raw.target;
1550
+ const { id, __typename } = target;
1551
+ switch (__typename) {
1552
+ case "ContelloRoute": {
1553
+ if (mutation === "delete") return {
1554
+ id,
1555
+ mutation: "delete",
1556
+ target: "route"
1557
+ };
1558
+ const after = mapRoute(target, resolver);
1559
+ if (!after) return;
1560
+ if (mutation === "create") return {
1561
+ id,
1562
+ mutation,
1563
+ target: "route",
1564
+ after
1565
+ };
1566
+ const before = raw.prev?.__typename === "ContelloRoute" ? mapRoute(raw.prev, resolver) ?? void 0 : void 0;
1567
+ if (!before) return;
1568
+ return {
1569
+ id,
1570
+ mutation,
1571
+ target: "route",
1572
+ after,
1573
+ before
1574
+ };
1575
+ }
1576
+ case "ContelloAsset": return {
1577
+ id,
1578
+ mutation,
1579
+ target: "asset"
1580
+ };
1581
+ case "ContelloI18nMessage": return {
1582
+ id,
1583
+ mutation,
1584
+ target: "i18nMessage",
1585
+ token: target.token
1586
+ };
1587
+ default:
1588
+ if (!__typename || !resolver.hasTypeName(__typename)) return;
1589
+ return {
1590
+ id,
1591
+ mutation,
1592
+ target: "entity",
1593
+ model: resolver.resolveModel(__typename)
1594
+ };
1595
+ }
1889
1596
  }
1890
1597
  function safeMapEvent(raw, resolver) {
1891
- try {
1892
- return mapEvent(raw, resolver);
1893
- } catch {
1894
- return void 0;
1895
- }
1598
+ try {
1599
+ return mapEvent(raw, resolver);
1600
+ } catch {
1601
+ return;
1602
+ }
1896
1603
  }
1897
1604
  function createInternalWatcher(client, resolver) {
1898
- const updates$ = createAsyncIterableSubject3();
1899
- let controller;
1900
- return {
1901
- updates$,
1902
- start() {
1903
- if (controller) {
1904
- return;
1905
- }
1906
- controller = new AbortController();
1907
- const signal = controller.signal;
1908
- wrap("watcher:start", () => {
1909
- void (async () => {
1910
- const source = asyncKeepalive(
1911
- () => client.subscribe(storeWatchUpdatesDocument),
1912
- signal
1913
- );
1914
- const events = mapAsync9(
1915
- source,
1916
- (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => safeMapEvent(e, resolver)).filter((e) => e !== void 0)
1917
- );
1918
- for await (const list of events) {
1919
- if (signal.aborted) {
1920
- return;
1921
- }
1922
- if (list.length === 0) {
1923
- continue;
1924
- }
1925
- try {
1926
- updates$.next(createUpdateBatch(list));
1927
- } catch {
1928
- }
1929
- }
1930
- })().catch(() => {
1931
- });
1932
- });
1933
- },
1934
- stop() {
1935
- controller?.abort();
1936
- controller = void 0;
1937
- updates$.complete();
1938
- }
1939
- };
1605
+ const updates$ = createAsyncIterableSubject();
1606
+ let controller;
1607
+ return {
1608
+ updates$,
1609
+ start() {
1610
+ if (controller) return;
1611
+ controller = new AbortController();
1612
+ const signal = controller.signal;
1613
+ wrap("watcher:start", () => {
1614
+ (async () => {
1615
+ const events = mapAsync(asyncKeepalive(() => client.subscribe(storeWatchUpdatesDocument), signal), (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => safeMapEvent(e, resolver)).filter((e) => e !== void 0));
1616
+ for await (const list of events) {
1617
+ if (signal.aborted) return;
1618
+ if (list.length === 0) continue;
1619
+ try {
1620
+ updates$.next(createUpdateBatch(list));
1621
+ } catch {}
1622
+ }
1623
+ })().catch(() => {});
1624
+ });
1625
+ },
1626
+ stop() {
1627
+ controller?.abort();
1628
+ controller = void 0;
1629
+ updates$.complete();
1630
+ }
1631
+ };
1940
1632
  }
1941
-
1942
- // src/store.ts
1633
+ //#endregion
1634
+ //#region src/store.ts
1943
1635
  var Store = class {
1944
- _client;
1945
- _resolver;
1946
- _watcher;
1947
- _schema;
1948
- _cleanups = [];
1949
- _refreshByTtl = createRefreshByTtlQueue();
1950
- /**
1951
- * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1952
- * each iteration starts an independent fan-out from the shared source.
1953
- */
1954
- updates$;
1955
- constructor(options) {
1956
- const { url, project, token, schema: schema2 } = options;
1957
- this._schema = schema2;
1958
- this._client = createContelloClient({
1959
- url,
1960
- project,
1961
- token,
1962
- schema: schema2,
1963
- connections: options.connections,
1964
- onConnected: options.onConnected,
1965
- onReconnecting: options.onReconnecting,
1966
- onError: options.onError,
1967
- connectionEvents: options.connectionEvents
1968
- });
1969
- this._resolver = new ModelResolver(schema2?.models);
1970
- this._watcher = createInternalWatcher(this._client, this._resolver);
1971
- this.updates$ = this._watcher.updates$;
1972
- this.ping = () => this._client.ping();
1973
- }
1974
- get client() {
1975
- return this._client;
1976
- }
1977
- async init() {
1978
- await wrap("store:init", () => this._client.init());
1979
- this._watcher.start();
1980
- }
1981
- async destroy() {
1982
- for (const fn of this._cleanups.splice(0)) {
1983
- try {
1984
- fn();
1985
- } catch {
1986
- }
1987
- }
1988
- this._watcher.stop();
1989
- await wrap("store:destroy", () => this._client.destroy());
1990
- }
1991
- /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1992
- _resolveSource(sourceOrKey) {
1993
- if (typeof sourceOrKey !== "string") {
1994
- return sourceOrKey;
1995
- }
1996
- const sources2 = this._schema?.sources;
1997
- const source = sources2?.[sourceOrKey];
1998
- if (!source) {
1999
- throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
2000
- }
2001
- return source;
2002
- }
2003
- // --- singleton ---
2004
- defineSingleton(sourceOrKey, options) {
2005
- const source = this._resolveSource(sourceOrKey);
2006
- const { instance, destroy } = createSingleton(
2007
- source,
2008
- options,
2009
- this._client,
2010
- this._watcher.updates$,
2011
- this._resolver,
2012
- this._refreshByTtl
2013
- );
2014
- this._cleanups.push(destroy);
2015
- return instance;
2016
- }
2017
- defineSingletonSync(sourceOrKey, options) {
2018
- const source = this._resolveSource(sourceOrKey);
2019
- const { instance, destroy } = createSingletonSync(
2020
- source,
2021
- options,
2022
- this._client,
2023
- this._watcher.updates$,
2024
- this._resolver,
2025
- this._refreshByTtl
2026
- );
2027
- this._cleanups.push(destroy);
2028
- return instance;
2029
- }
2030
- // --- collection ---
2031
- defineCollection(sourceOrKey, options) {
2032
- const source = this._resolveSource(sourceOrKey);
2033
- const { instance, destroy } = createCollection(
2034
- source,
2035
- options,
2036
- this._client,
2037
- this._watcher.updates$,
2038
- this._resolver,
2039
- this._refreshByTtl
2040
- );
2041
- this._cleanups.push(destroy);
2042
- return instance;
2043
- }
2044
- defineCollectionSync(sourceOrKey, options) {
2045
- const source = this._resolveSource(sourceOrKey);
2046
- const { instance, destroy } = createCollectionSync(
2047
- source,
2048
- options,
2049
- this._client,
2050
- this._watcher.updates$,
2051
- this._resolver,
2052
- this._refreshByTtl
2053
- );
2054
- this._cleanups.push(destroy);
2055
- return instance;
2056
- }
2057
- // --- lazy collection ---
2058
- defineLazyCollection(sourceOrKey, options) {
2059
- const source = this._resolveSource(sourceOrKey);
2060
- const { instance, destroy } = createLazyCollection(
2061
- source,
2062
- options,
2063
- this._client,
2064
- this._watcher.updates$,
2065
- this._resolver
2066
- );
2067
- this._cleanups.push(destroy);
2068
- return instance;
2069
- }
2070
- // --- assets / routes / i18n (no source — built-ins) ---
2071
- // --- assets ---
2072
- defineAssets(options) {
2073
- const { instance, destroy } = createAssetsCollection(
2074
- options,
2075
- this._client,
2076
- this._watcher.updates$,
2077
- this._refreshByTtl
2078
- );
2079
- this._cleanups.push(destroy);
2080
- return instance;
2081
- }
2082
- defineAssetsSync(options) {
2083
- const { instance, destroy } = createAssetsSyncCollection(
2084
- options,
2085
- this._client,
2086
- this._watcher.updates$,
2087
- this._refreshByTtl
2088
- );
2089
- this._cleanups.push(destroy);
2090
- return instance;
2091
- }
2092
- defineLazyAssets(options) {
2093
- const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
2094
- this._cleanups.push(destroy);
2095
- return instance;
2096
- }
2097
- // --- routes ---
2098
- defineRoutes(options) {
2099
- const { instance, destroy } = createRoutesCollection(
2100
- options,
2101
- this._client,
2102
- this._watcher.updates$,
2103
- this._resolver,
2104
- this._refreshByTtl
2105
- );
2106
- this._cleanups.push(destroy);
2107
- return instance;
2108
- }
2109
- defineRoutesSync(options) {
2110
- const { instance, destroy } = createRoutesSyncCollection(
2111
- options,
2112
- this._client,
2113
- this._watcher.updates$,
2114
- this._resolver,
2115
- this._refreshByTtl
2116
- );
2117
- this._cleanups.push(destroy);
2118
- return instance;
2119
- }
2120
- defineLazyRoutes(options) {
2121
- const { instance, destroy } = createLazyRoutesCollection(
2122
- options,
2123
- this._client,
2124
- this._watcher.updates$,
2125
- this._resolver
2126
- );
2127
- this._cleanups.push(destroy);
2128
- return instance;
2129
- }
2130
- defineI18nMessages(def) {
2131
- const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
2132
- this._cleanups.push(result.destroy);
2133
- return result;
2134
- }
2135
- ping;
1636
+ _client;
1637
+ _resolver;
1638
+ _watcher;
1639
+ _schema;
1640
+ _cleanups = [];
1641
+ _refreshByTtl = createRefreshByTtlQueue();
1642
+ /**
1643
+ * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1644
+ * each iteration starts an independent fan-out from the shared source.
1645
+ */
1646
+ updates$;
1647
+ ping;
1648
+ constructor(options) {
1649
+ const { url, project, token, schema } = options;
1650
+ this._schema = schema;
1651
+ this._client = createContelloClient({
1652
+ url,
1653
+ project,
1654
+ token,
1655
+ schema,
1656
+ connections: options.connections,
1657
+ onConnected: options.onConnected,
1658
+ onReconnecting: options.onReconnecting,
1659
+ onError: options.onError,
1660
+ connectionEvents: options.connectionEvents
1661
+ });
1662
+ this._resolver = new ModelResolver(schema?.models);
1663
+ this._watcher = createInternalWatcher(this._client, this._resolver);
1664
+ this.updates$ = this._watcher.updates$;
1665
+ this.ping = () => this._client.ping();
1666
+ }
1667
+ /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1668
+ _resolveSource(sourceOrKey) {
1669
+ if (typeof sourceOrKey !== "string") return sourceOrKey;
1670
+ const source = (this._schema?.sources)?.[sourceOrKey];
1671
+ if (!source) throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
1672
+ return source;
1673
+ }
1674
+ get client() {
1675
+ return this._client;
1676
+ }
1677
+ async init() {
1678
+ await wrap("store:init", () => this._client.init());
1679
+ this._watcher.start();
1680
+ }
1681
+ async destroy() {
1682
+ for (const fn of this._cleanups.splice(0)) try {
1683
+ fn();
1684
+ } catch {}
1685
+ this._watcher.stop();
1686
+ await wrap("store:destroy", () => this._client.destroy());
1687
+ }
1688
+ defineSingleton(sourceOrKey, options) {
1689
+ const { instance, destroy } = createSingleton(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1690
+ this._cleanups.push(destroy);
1691
+ return instance;
1692
+ }
1693
+ defineSingletonSync(sourceOrKey, options) {
1694
+ const { instance, destroy } = createSingletonSync(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1695
+ this._cleanups.push(destroy);
1696
+ return instance;
1697
+ }
1698
+ defineCollection(sourceOrKey, options) {
1699
+ const { instance, destroy } = createCollection(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1700
+ this._cleanups.push(destroy);
1701
+ return instance;
1702
+ }
1703
+ defineCollectionSync(sourceOrKey, options) {
1704
+ const { instance, destroy } = createCollectionSync(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1705
+ this._cleanups.push(destroy);
1706
+ return instance;
1707
+ }
1708
+ defineLazyCollection(sourceOrKey, options) {
1709
+ const { instance, destroy } = createLazyCollection(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver);
1710
+ this._cleanups.push(destroy);
1711
+ return instance;
1712
+ }
1713
+ defineAssets(options) {
1714
+ const { instance, destroy } = createAssetsCollection(options, this._client, this._watcher.updates$, this._refreshByTtl);
1715
+ this._cleanups.push(destroy);
1716
+ return instance;
1717
+ }
1718
+ defineAssetsSync(options) {
1719
+ const { instance, destroy } = createAssetsSyncCollection(options, this._client, this._watcher.updates$, this._refreshByTtl);
1720
+ this._cleanups.push(destroy);
1721
+ return instance;
1722
+ }
1723
+ defineLazyAssets(options) {
1724
+ const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
1725
+ this._cleanups.push(destroy);
1726
+ return instance;
1727
+ }
1728
+ defineRoutes(options) {
1729
+ const { instance, destroy } = createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1730
+ this._cleanups.push(destroy);
1731
+ return instance;
1732
+ }
1733
+ defineRoutesSync(options) {
1734
+ const { instance, destroy } = createRoutesSyncCollection(options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1735
+ this._cleanups.push(destroy);
1736
+ return instance;
1737
+ }
1738
+ defineLazyRoutes(options) {
1739
+ const { instance, destroy } = createLazyRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
1740
+ this._cleanups.push(destroy);
1741
+ return instance;
1742
+ }
1743
+ defineI18nMessages(def) {
1744
+ const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
1745
+ this._cleanups.push(result.destroy);
1746
+ return result;
1747
+ }
2136
1748
  };
2137
1749
  function createStore(options) {
2138
- return new Store(options);
1750
+ return new Store(options);
2139
1751
  }
1752
+ //#endregion
1753
+ export { Store, createStore, maybeCatch, maybeThen };
2140
1754
 
2141
- // src/index.ts
2142
- import { maybeThen as maybeThen6, maybeCatch } from "projected";
2143
- export {
2144
- Store,
2145
- createStore,
2146
- maybeCatch,
2147
- maybeThen6 as maybeThen
2148
- };
1755
+ //# sourceMappingURL=index.js.map