@contello/store 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -32,13 +32,13 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  Store: () => Store,
34
34
  createStore: () => createStore,
35
- maybeCatch: () => import_projected7.maybeCatch,
36
- maybeThen: () => import_projected7.maybeThen
35
+ maybeCatch: () => import_projected9.maybeCatch,
36
+ maybeThen: () => import_projected9.maybeThen
37
37
  });
38
38
  module.exports = __toCommonJS(index_exports);
39
39
 
40
40
  // src/store.ts
41
- var import_client9 = require("@contello/client");
41
+ var import_client11 = require("@contello/client");
42
42
 
43
43
  // src/assets.ts
44
44
  var import_client2 = require("@contello/client");
@@ -170,20 +170,6 @@ var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
170
170
  value
171
171
  }
172
172
  }`;
173
- var storeGetAssetsDocument = `${MediaFileFragmentSchema}
174
- ${MediaAssetFragmentSchema}
175
- ${StoreAssetFragmentSchema}
176
- query StoreGetAssets($filter: ContelloAssetsFilterInput!) {
177
- contelloAssets(filter: $filter) {
178
- ...StoreAsset
179
- }
180
- }`;
181
- var storeGetI18nMessagesDocument = `${StoreI18nMessageFragmentSchema}
182
- subscription StoreGetI18nMessages($collection: String!) {
183
- contelloI18nMessagesBatch(collectionReferenceName: $collection) {
184
- ...StoreI18nMessage
185
- }
186
- }`;
187
173
  var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
188
174
  registerContelloI18nMessages(
189
175
  collectionReferenceName: $collection
@@ -193,12 +179,6 @@ var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($col
193
179
  ids
194
180
  }
195
181
  }`;
196
- var storeGetRoutesDocument = `${StoreRouteFragmentSchema}
197
- query StoreGetRoutes($request: ContelloRoutesRequestInput!) {
198
- contelloRoutes(request: $request) {
199
- ...StoreRoute
200
- }
201
- }`;
202
182
  var storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
203
183
  subscription StoreWatchUpdates {
204
184
  contelloUpdatesBatch {
@@ -231,6 +211,10 @@ subscription StoreWatchUpdates {
231
211
  }
232
212
  }
233
213
  }`;
214
+ var operations = {
215
+ storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: "mutation" },
216
+ storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: "subscription" }
217
+ };
234
218
  var sources = {
235
219
  storeAsset: {
236
220
  document: `${MediaFileFragmentSchema}
@@ -256,55 +240,100 @@ ${StoreAssetFragmentSchema}`,
256
240
  __cardinality: "route"
257
241
  }
258
242
  };
259
-
260
- // src/lru.ts
261
- var import_lru_cache = require("lru-cache");
262
- function createLruCache(options) {
263
- const { max, ttl, onEvict: dispose } = options;
264
- const lru = new import_lru_cache.LRUCache({
265
- max,
266
- ...ttl !== void 0 && { ttl, ttlAutopurge: false },
267
- ...dispose !== void 0 && { dispose }
268
- });
269
- return {
270
- has: (key) => lru.has(key),
271
- get: (key) => lru.get(key),
272
- set: (key, value) => {
273
- lru.set(key, value);
274
- },
275
- delete: (key) => {
276
- lru.delete(key);
277
- },
278
- clear: () => {
279
- lru.clear();
280
- },
281
- keys: () => [...lru.keys()]
282
- };
283
- }
243
+ var models = {
244
+ dummy: "DummyEntity"
245
+ };
246
+ var schema = { operations, sources, models };
284
247
 
285
248
  // src/utils.ts
286
249
  var import_client = require("@contello/client");
250
+ var DEFAULT_TTL_MS = 3 * 60 * 60 * 1e3;
251
+ function resolveTtl(ttl) {
252
+ if (ttl === void 0) return DEFAULT_TTL_MS;
253
+ if (ttl === false || ttl <= 0) return void 0;
254
+ return ttl;
255
+ }
287
256
  function createRefresher(fn, onRefreshed, onStart2) {
288
257
  let refreshing = false;
289
- let pending = false;
290
- function scheduleRefresh() {
258
+ let inFlightKind;
259
+ let pendingKind;
260
+ function scheduleRefresh(kind) {
291
261
  if (refreshing) {
292
- pending = true;
262
+ pendingKind = { kind };
293
263
  return;
294
264
  }
295
265
  refreshing = true;
266
+ inFlightKind = kind;
296
267
  onStart2?.();
297
268
  void (0, import_client.runWithBackoff)(fn).then(() => {
269
+ const finished = inFlightKind;
298
270
  refreshing = false;
299
- onRefreshed();
300
- if (pending) {
301
- pending = false;
302
- scheduleRefresh();
271
+ inFlightKind = void 0;
272
+ onRefreshed(finished);
273
+ if (pendingKind) {
274
+ const { kind: next } = pendingKind;
275
+ pendingKind = void 0;
276
+ scheduleRefresh(next);
303
277
  }
304
278
  });
305
279
  }
306
280
  return scheduleRefresh;
307
281
  }
282
+ function createRefreshChannel(onRefresh) {
283
+ const stream$ = (0, import_client.createAsyncIterableSubject)();
284
+ return {
285
+ stream$,
286
+ emit(event) {
287
+ stream$.next(event);
288
+ onRefresh?.(event);
289
+ },
290
+ complete() {
291
+ stream$.complete();
292
+ }
293
+ };
294
+ }
295
+ function createTtlOrchestrator(options) {
296
+ let timer;
297
+ return {
298
+ mark() {
299
+ if (timer !== void 0) {
300
+ clearTimeout(timer);
301
+ timer = void 0;
302
+ }
303
+ if (options.ttl === void 0) {
304
+ return;
305
+ }
306
+ timer = setTimeout(options.run, options.ttl);
307
+ },
308
+ clear() {
309
+ if (timer !== void 0) {
310
+ clearTimeout(timer);
311
+ timer = void 0;
312
+ }
313
+ }
314
+ };
315
+ }
316
+ function createRefreshByTtlQueue() {
317
+ const waiting = [];
318
+ let running = false;
319
+ function next() {
320
+ if (running) return;
321
+ const task = waiting.shift();
322
+ if (!task) return;
323
+ running = true;
324
+ Promise.resolve().then(task).catch(() => {
325
+ }).finally(() => {
326
+ running = false;
327
+ next();
328
+ });
329
+ }
330
+ return {
331
+ enqueue(task) {
332
+ waiting.push(task);
333
+ next();
334
+ }
335
+ };
336
+ }
308
337
 
309
338
  // src/assets.ts
310
339
  function mapFile(raw) {
@@ -322,80 +351,128 @@ function mapAsset(raw) {
322
351
  optimized: raw.optimized.map(mapFile)
323
352
  };
324
353
  }
325
- function createAssetsCollection(def, client, updates$) {
326
- const _def = {
327
- cache: {
328
- max: def?.cache?.max ?? 1e3,
329
- ttl: def?.cache?.ttl
330
- }
354
+ function createAssetsCollection(options, client, updates$, refreshByTtl) {
355
+ const opts = options ?? {};
356
+ const cache = {
357
+ ttl: resolveTtl(opts.cache?.ttl),
358
+ eviction: opts.cache?.eviction ?? "refresh"
331
359
  };
332
- const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
333
- const projected = new import_projected.ProjectedLazyMap({
360
+ const channel = createRefreshChannel(opts.onRefresh);
361
+ const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
362
+ let loaded = false;
363
+ const assetsSourceDoc = (0, import_client2.createSourceSubscription)(schema.sources.storeAsset);
364
+ const projected = new import_projected.ProjectedMap({
334
365
  key: (asset) => asset.id,
335
366
  values: (ids) => wrap(
336
367
  "assets",
337
- () => client.execute(storeGetAssetsDocument, { filter: { ids } }).then(
338
- (data) => (data.contelloAssets ?? []).reduce((acc, raw) => {
339
- if (raw) {
340
- acc.push(mapAsset(raw));
341
- }
342
- return acc;
343
- }, [])
368
+ () => (0, import_client2.collectAsync)(
369
+ (0, import_client2.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
370
+ ).then((rawItems) => {
371
+ const items = rawItems.map(mapAsset);
372
+ if (ids === void 0 && !loaded) {
373
+ loaded = true;
374
+ ttl.mark();
375
+ opts.onLoad?.(items.map((a) => a.id));
376
+ }
377
+ return items;
378
+ })
379
+ )
380
+ });
381
+ function emit(ids, kind) {
382
+ channel.emit({ ids, kind });
383
+ }
384
+ function runFullRefresh(kind) {
385
+ refreshByTtl.enqueue(
386
+ () => (0, import_client2.runWithBackoff)(
387
+ () => projected.refresh().then((map) => {
388
+ emit([...map.keys()], kind);
389
+ ttl.mark();
390
+ })
344
391
  )
345
- ),
346
- cache
392
+ );
393
+ }
394
+ function runPartialRefresh(refreshIds, deletedIds) {
395
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
396
+ if (refreshIds.length === 0) {
397
+ emit(changedIds, "upstream-update");
398
+ return;
399
+ }
400
+ void (0, import_client2.runWithBackoff)(
401
+ () => projected.refresh(refreshIds).then(() => {
402
+ emit(changedIds, "upstream-update");
403
+ })
404
+ );
405
+ }
406
+ const unsubUpdates = updates$.subscribe((batch) => {
407
+ if (!loaded || batch.asset.length === 0) {
408
+ return;
409
+ }
410
+ const deleted = [];
411
+ const upserted = /* @__PURE__ */ new Set();
412
+ for (const event of batch.asset) {
413
+ if (event.mutation === "delete") {
414
+ deleted.push(event.id);
415
+ } else {
416
+ upserted.add(event.id);
417
+ }
418
+ }
419
+ if (cache.eviction === "clear") {
420
+ projected.clear();
421
+ return;
422
+ }
423
+ if (deleted.length > 0) {
424
+ projected.delete(deleted);
425
+ }
426
+ runPartialRefresh([...upserted], deleted);
347
427
  });
348
- const refresh$ = (0, import_client2.createAsyncIterableSubject)();
349
- let lastRefreshKeys = [];
350
- const scheduleRefresh = createRefresher(
351
- async () => {
352
- lastRefreshKeys = cache.keys();
353
- if (lastRefreshKeys.length === 0) {
354
- return;
428
+ const instance = {
429
+ refresh$: channel.stream$,
430
+ async load() {
431
+ if (!loaded) {
432
+ await projected.getAllAsMap();
355
433
  }
356
- await projected.refresh(lastRefreshKeys);
357
434
  },
358
- () => {
359
- if (lastRefreshKeys.length > 0) {
360
- refresh$.next(lastRefreshKeys);
361
- }
435
+ get(idOrIds) {
436
+ return projected.get(idOrIds);
362
437
  },
363
- () => {
438
+ upload(data, meta, options2) {
439
+ return client.upload(data, meta, options2);
440
+ },
441
+ download(fileId) {
442
+ return client.download(fileId);
443
+ },
444
+ proxyHls(path, signal) {
445
+ return client.proxyHls(path, signal);
446
+ },
447
+ refresh() {
448
+ runFullRefresh("on-demand");
364
449
  }
365
- );
366
- const unsubUpdates = updates$.subscribe((batch) => {
367
- if (batch.asset.length === 0) return;
368
- for (const event of batch.asset) {
369
- projected.delete(event.id);
450
+ };
451
+ return {
452
+ instance,
453
+ destroy() {
454
+ unsubUpdates();
455
+ ttl.clear();
456
+ channel.complete();
370
457
  }
371
- refresh$.next(batch.asset.map((e) => e.id));
372
- });
458
+ };
459
+ }
460
+ function createAssetsSyncCollection(options, client, updates$, refreshByTtl) {
461
+ const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);
462
+ function assertSync(value, method) {
463
+ if (value instanceof Promise) {
464
+ throw new Error(`assets.${method}() is not initialized yet \u2014 call assets.load() first`);
465
+ }
466
+ return value;
467
+ }
373
468
  return {
374
469
  instance: {
375
- refresh$,
470
+ ...base,
376
471
  get(idOrIds) {
377
- return projected.get(idOrIds);
378
- },
379
- upload(data, meta, options) {
380
- return client.upload(data, meta, options);
381
- },
382
- download(fileId) {
383
- return client.download(fileId);
384
- },
385
- proxyHls(path, signal) {
386
- return client.proxyHls(path, signal);
387
- },
388
- refresh() {
389
- scheduleRefresh();
390
- },
391
- clear() {
392
- projected.clear();
472
+ return assertSync(base.get(idOrIds), "get");
393
473
  }
394
474
  },
395
- destroy() {
396
- unsubUpdates();
397
- refresh$.complete();
398
- }
475
+ destroy
399
476
  };
400
477
  }
401
478
 
@@ -557,26 +634,28 @@ var DependencyCollector = class {
557
634
 
558
635
  // src/collection.ts
559
636
  function fetchCollection(source, client, ids) {
560
- return (0, import_client3.firstAsync)(
637
+ return (0, import_client3.collectAsync)(
561
638
  (0, import_client3.mapAsync)(
562
639
  client.subscribe((0, import_client3.createSourceSubscription)(source), { ids }),
563
640
  (r) => r.source
564
641
  )
565
642
  );
566
643
  }
567
- function createCollection(source, options, client, updates$, resolver) {
644
+ function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
568
645
  const opts = options ?? {};
569
646
  const mapFn = opts.map ?? ((item) => item);
570
647
  const _def = {
571
648
  name: opts.name ?? source.__model,
572
649
  model: source.__model,
573
650
  cache: {
574
- ttl: opts.cache?.ttl,
651
+ ttl: resolveTtl(opts.cache?.ttl),
575
652
  eviction: opts.cache?.eviction ?? "refresh"
576
653
  }
577
654
  };
578
655
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
579
- let ttlTimer;
656
+ const channel = createRefreshChannel(opts.onRefresh);
657
+ const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh("ttl") });
658
+ let loaded = false;
580
659
  const projected = new import_projected2.ProjectedMap({
581
660
  key: (item) => item.id,
582
661
  values: (ids) => wrap(
@@ -595,6 +674,11 @@ function createCollection(source, options, client, updates$, resolver) {
595
674
  ).then((items) => {
596
675
  if (ids === void 0) {
597
676
  dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
677
+ if (!loaded) {
678
+ loaded = true;
679
+ ttl.mark();
680
+ opts.onLoad?.(items.map((item) => item.id));
681
+ }
598
682
  } else {
599
683
  const returnedIds = new Set(items.map((item) => item.id));
600
684
  for (const id of ids) {
@@ -609,38 +693,28 @@ function createCollection(source, options, client, updates$, resolver) {
609
693
  ),
610
694
  sort: opts.sort
611
695
  });
612
- const refresh$ = (0, import_client3.createAsyncIterableSubject)();
613
- let loaded = false;
614
- function scheduleTtl() {
615
- if (_def.cache.ttl === void 0) {
616
- return;
617
- }
618
- clearTimeout(ttlTimer);
619
- ttlTimer = setTimeout(() => {
620
- runFullRefresh();
621
- }, _def.cache.ttl);
696
+ function emit(ids, kind) {
697
+ channel.emit({ ids, kind });
622
698
  }
623
- function runFullRefresh() {
624
- void (0, import_client3.runWithBackoff)(
625
- () => projected.refresh().then((map) => {
626
- const ids = [...map.keys()];
627
- refresh$.next(ids);
628
- opts.onRefresh?.(ids);
629
- scheduleTtl();
630
- })
699
+ function runFullRefresh(kind) {
700
+ refreshByTtl.enqueue(
701
+ () => (0, import_client3.runWithBackoff)(
702
+ () => projected.refresh().then((map) => {
703
+ emit([...map.keys()], kind);
704
+ ttl.mark();
705
+ })
706
+ )
631
707
  );
632
708
  }
633
709
  function runPartialRefresh(refreshIds, deletedIds) {
634
710
  const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
635
711
  if (refreshIds.length === 0) {
636
- refresh$.next(changedIds);
637
- opts.onRefresh?.(changedIds);
712
+ emit(changedIds, "upstream-update");
638
713
  return;
639
714
  }
640
715
  void (0, import_client3.runWithBackoff)(
641
716
  () => projected.refresh(refreshIds).then(() => {
642
- refresh$.next(changedIds);
643
- opts.onRefresh?.(changedIds);
717
+ emit(changedIds, "upstream-update");
644
718
  })
645
719
  );
646
720
  }
@@ -686,7 +760,7 @@ function createCollection(source, options, client, updates$, resolver) {
686
760
  });
687
761
  const instance = {
688
762
  name: _def.name,
689
- refresh$,
763
+ refresh$: channel.stream$,
690
764
  get(idOrIds) {
691
765
  return projected.get(idOrIds);
692
766
  },
@@ -694,31 +768,31 @@ function createCollection(source, options, client, updates$, resolver) {
694
768
  return projected.getAll();
695
769
  },
696
770
  refresh() {
697
- runFullRefresh();
771
+ runFullRefresh("on-demand");
698
772
  },
699
773
  async load() {
700
- const map = await projected.refresh();
701
- loaded = true;
702
- scheduleTtl();
703
- opts.onLoad?.([...map.keys()]);
774
+ if (!loaded) {
775
+ await projected.getAllAsMap();
776
+ }
704
777
  }
705
778
  };
706
779
  return {
707
780
  instance,
708
781
  destroy() {
709
782
  unsubUpdates();
710
- clearTimeout(ttlTimer);
711
- refresh$.complete();
783
+ ttl.clear();
784
+ channel.complete();
712
785
  }
713
786
  };
714
787
  }
715
- function createCollectionSync(source, options, client, updates$, resolver) {
788
+ function createCollectionSync(source, options, client, updates$, resolver, refreshByTtl) {
716
789
  const { instance: base, destroy } = createCollection(
717
790
  source,
718
791
  options,
719
792
  client,
720
793
  updates$,
721
- resolver
794
+ resolver,
795
+ refreshByTtl
722
796
  );
723
797
  function assertSync(value, method) {
724
798
  if (value instanceof Promise) {
@@ -753,45 +827,103 @@ function toGqlMessageInput(msg) {
753
827
  initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message }))
754
828
  };
755
829
  }
756
- function createI18nMessagesCollection(def, client, updates$) {
830
+ function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
831
+ const channel = createRefreshChannel(def.onRefresh);
832
+ const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });
833
+ let loaded = false;
834
+ const i18nSourceDoc = (0, import_client4.createSourceSubscription)(schema.sources.storeI18nMessage);
757
835
  const projected = new import_projected3.ProjectedMap({
758
836
  key: (msg) => msg.id,
759
- values: () => wrap(
837
+ values: (ids) => wrap(
760
838
  `i18n:${def.collection}`,
761
839
  () => (0, import_client4.collectAsync)(
762
840
  (0, import_client4.mapAsync)(
763
- client.subscribe(storeGetI18nMessagesDocument, {
764
- collection: def.collection
841
+ client.subscribe(i18nSourceDoc, {
842
+ collection: def.collection,
843
+ ids
765
844
  }),
766
- (data) => data.contelloI18nMessagesBatch
845
+ (data) => data.source
767
846
  )
768
- ).then(
769
- (msgs) => msgs.map((msg) => ({
847
+ ).then((msgs) => {
848
+ const items = msgs.map((msg) => ({
770
849
  id: msg.id,
771
850
  token: msg.token,
772
851
  translations: new Map(msg.translations.map((t) => [t.language, t.value]))
773
- }))
774
- )
852
+ }));
853
+ if (ids === void 0 && !loaded) {
854
+ loaded = true;
855
+ ttl.mark();
856
+ }
857
+ return items;
858
+ })
775
859
  )
776
860
  });
777
- const refresh$ = (0, import_client4.createAsyncIterableSubject)();
861
+ function emit(ids, kind) {
862
+ channel.emit({ ids, kind });
863
+ }
864
+ function emitWithCurrentIds(kind) {
865
+ (0, import_projected3.maybeThen)(projected.getAll(), (msgs) => {
866
+ emit(
867
+ msgs.map((m) => m.id),
868
+ kind
869
+ );
870
+ });
871
+ }
872
+ function runTtlRefresh() {
873
+ refreshByTtl.enqueue(
874
+ () => (0, import_client4.runWithBackoff)(() => projected.refresh()).then(() => {
875
+ emitWithCurrentIds("ttl");
876
+ ttl.mark();
877
+ })
878
+ );
879
+ }
778
880
  const scheduleRefresh = createRefresher(
779
881
  () => projected.refresh(),
780
- () => {
781
- (0, import_projected3.maybeThen)(projected.getAll(), (msgs) => {
782
- refresh$.next(msgs.map((m) => m.id));
783
- });
882
+ (kind) => {
883
+ emitWithCurrentIds(kind);
884
+ ttl.mark();
784
885
  },
785
886
  () => {
786
887
  }
787
888
  );
889
+ function runPartialRefresh(upsertedIds, deletedIds) {
890
+ const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
891
+ if (changedIds.length === 0) {
892
+ return;
893
+ }
894
+ if (upsertedIds.length === 0) {
895
+ emit(changedIds, "upstream-update");
896
+ return;
897
+ }
898
+ void (0, import_client4.runWithBackoff)(
899
+ () => projected.refresh(upsertedIds).then(() => {
900
+ emit(changedIds, "upstream-update");
901
+ })
902
+ );
903
+ }
788
904
  const unsubUpdates = updates$.subscribe((batch) => {
789
- if (batch.i18nMessage.length > 0) {
790
- scheduleRefresh();
905
+ if (!loaded) {
906
+ return;
907
+ }
908
+ if (batch.i18nMessage.length === 0) {
909
+ return;
910
+ }
911
+ const deleted = [];
912
+ const upserted = /* @__PURE__ */ new Set();
913
+ for (const event of batch.i18nMessage) {
914
+ if (event.mutation === "delete") {
915
+ deleted.push(event.id);
916
+ } else {
917
+ upserted.add(event.id);
918
+ }
919
+ }
920
+ if (deleted.length > 0) {
921
+ projected.delete(deleted);
791
922
  }
923
+ runPartialRefresh([...upserted], deleted);
792
924
  });
793
925
  return {
794
- refresh$,
926
+ refresh$: channel.stream$,
795
927
  get(idOrIds) {
796
928
  return projected.get(idOrIds);
797
929
  },
@@ -808,16 +940,144 @@ function createI18nMessagesCollection(def, client, updates$) {
808
940
  })
809
941
  );
810
942
  },
943
+ refresh() {
944
+ scheduleRefresh("on-demand");
945
+ },
946
+ destroy() {
947
+ unsubUpdates();
948
+ ttl.clear();
949
+ channel.complete();
950
+ }
951
+ };
952
+ }
953
+
954
+ // src/lazy-assets.ts
955
+ var import_client5 = require("@contello/client");
956
+ var import_projected4 = require("projected");
957
+
958
+ // src/lru.ts
959
+ var import_lru_cache = require("lru-cache");
960
+ function createLruCache(options) {
961
+ const { max, ttl, onEvict: dispose } = options;
962
+ const lru = new import_lru_cache.LRUCache({
963
+ max,
964
+ ...ttl !== void 0 && { ttl, ttlAutopurge: false },
965
+ ...dispose !== void 0 && { dispose }
966
+ });
967
+ return {
968
+ has: (key) => lru.has(key),
969
+ get: (key) => lru.get(key),
970
+ set: (key, value) => {
971
+ lru.set(key, value);
972
+ },
973
+ delete: (key) => {
974
+ lru.delete(key);
975
+ },
976
+ clear: () => {
977
+ lru.clear();
978
+ },
979
+ keys: () => [...lru.keys()]
980
+ };
981
+ }
982
+
983
+ // src/lazy-assets.ts
984
+ function mapFile2(raw) {
985
+ return {
986
+ uid: raw.uid,
987
+ mimeType: raw.mimeType,
988
+ metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
989
+ };
990
+ }
991
+ function mapAsset2(raw) {
992
+ return {
993
+ id: raw.id,
994
+ original: mapFile2(raw.original),
995
+ preview: raw.preview ? mapFile2(raw.preview) : void 0,
996
+ optimized: raw.optimized.map(mapFile2)
997
+ };
998
+ }
999
+ function createLazyAssetsCollection(def, client, updates$) {
1000
+ const _def = {
1001
+ cache: {
1002
+ max: def?.cache?.max ?? 1e3,
1003
+ ttl: resolveTtl(def?.cache?.ttl)
1004
+ }
1005
+ };
1006
+ const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
1007
+ const assetsSourceDoc = (0, import_client5.createSourceSubscription)(schema.sources.storeAsset);
1008
+ const projected = new import_projected4.ProjectedLazyMap({
1009
+ key: (asset) => asset.id,
1010
+ values: (ids) => wrap(
1011
+ "assets",
1012
+ () => (0, import_client5.collectAsync)(
1013
+ (0, import_client5.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
1014
+ ).then((rawItems) => rawItems.map(mapAsset2))
1015
+ ),
1016
+ cache
1017
+ });
1018
+ const channel = createRefreshChannel(def?.onRefresh);
1019
+ function emit(ids, kind) {
1020
+ channel.emit({ ids, kind });
1021
+ }
1022
+ let lastRefreshKeys = [];
1023
+ const scheduleRefresh = createRefresher(
1024
+ async () => {
1025
+ lastRefreshKeys = cache.keys();
1026
+ if (lastRefreshKeys.length === 0) {
1027
+ return;
1028
+ }
1029
+ await projected.refresh(lastRefreshKeys);
1030
+ },
1031
+ (kind) => {
1032
+ if (lastRefreshKeys.length > 0) {
1033
+ emit(lastRefreshKeys, kind);
1034
+ }
1035
+ },
1036
+ () => {
1037
+ }
1038
+ );
1039
+ const unsubUpdates = updates$.subscribe((batch) => {
1040
+ if (batch.asset.length === 0) return;
1041
+ for (const event of batch.asset) {
1042
+ projected.delete(event.id);
1043
+ }
1044
+ emit(
1045
+ batch.asset.map((e) => e.id),
1046
+ "upstream-update"
1047
+ );
1048
+ });
1049
+ return {
1050
+ instance: {
1051
+ refresh$: channel.stream$,
1052
+ get(idOrIds) {
1053
+ return projected.get(idOrIds);
1054
+ },
1055
+ upload(data, meta, options) {
1056
+ return client.upload(data, meta, options);
1057
+ },
1058
+ download(fileId) {
1059
+ return client.download(fileId);
1060
+ },
1061
+ proxyHls(path, signal) {
1062
+ return client.proxyHls(path, signal);
1063
+ },
1064
+ refresh() {
1065
+ scheduleRefresh("on-demand");
1066
+ },
1067
+ clear() {
1068
+ projected.clear();
1069
+ }
1070
+ },
811
1071
  destroy() {
812
1072
  unsubUpdates();
813
- refresh$.complete();
1073
+ channel.complete();
814
1074
  }
815
1075
  };
816
1076
  }
817
1077
 
818
1078
  // src/lazy-collection.ts
819
- var import_client5 = require("@contello/client");
820
- var import_projected4 = require("projected");
1079
+ var import_client6 = require("@contello/client");
1080
+ var import_projected5 = require("projected");
821
1081
  function createLazyCollection(source, options, client, updates$, resolver) {
822
1082
  const opts = options ?? {};
823
1083
  const mapFn = opts.map ?? ((item) => item);
@@ -826,7 +1086,7 @@ function createLazyCollection(source, options, client, updates$, resolver) {
826
1086
  model: source.__model,
827
1087
  cache: {
828
1088
  max: opts.cache?.max ?? 1e3,
829
- ttl: opts.cache?.ttl
1089
+ ttl: resolveTtl(opts.cache?.ttl)
830
1090
  }
831
1091
  };
832
1092
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
@@ -835,14 +1095,14 @@ function createLazyCollection(source, options, client, updates$, resolver) {
835
1095
  ttl: _def.cache.ttl,
836
1096
  onEvict: (_value, key) => dependencyCollector.removeItem(key)
837
1097
  });
838
- const projected = new import_projected4.ProjectedLazyMap({
1098
+ const projected = new import_projected5.ProjectedLazyMap({
839
1099
  key: (item) => item.id,
840
1100
  values: (keys) => wrap(
841
1101
  `lazy-collection:${_def.name}`,
842
- () => (0, import_projected4.maybeThen)(
843
- (0, import_client5.firstAsync)(
844
- (0, import_client5.mapAsync)(
845
- client.subscribe((0, import_client5.createSourceSubscription)(source), {
1102
+ () => (0, import_projected5.maybeThen)(
1103
+ (0, import_client6.collectAsync)(
1104
+ (0, import_client6.mapAsync)(
1105
+ client.subscribe((0, import_client6.createSourceSubscription)(source), {
846
1106
  ids: keys
847
1107
  }),
848
1108
  (r) => r.source
@@ -851,7 +1111,7 @@ function createLazyCollection(source, options, client, updates$, resolver) {
851
1111
  (rawItems) => Promise.all(
852
1112
  rawItems.map(
853
1113
  (item) => dependencyCollector.createContext(
854
- (ref, register) => (0, import_projected4.maybeThen)(mapFn(item, ref), (mapped) => {
1114
+ (ref, register) => (0, import_projected5.maybeThen)(mapFn(item, ref), (mapped) => {
855
1115
  register(mapped.id);
856
1116
  return mapped;
857
1117
  })
@@ -862,7 +1122,12 @@ function createLazyCollection(source, options, client, updates$, resolver) {
862
1122
  ),
863
1123
  cache
864
1124
  });
865
- const refresh$ = (0, import_client5.createAsyncIterableSubject)();
1125
+ const refresh$ = (0, import_client6.createAsyncIterableSubject)();
1126
+ function emit(ids, kind) {
1127
+ const event = { ids, kind };
1128
+ refresh$.next(event);
1129
+ opts.onRefresh?.(event);
1130
+ }
866
1131
  let lastRefreshKeys = [];
867
1132
  const scheduleRefresh = createRefresher(
868
1133
  async () => {
@@ -872,10 +1137,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
872
1137
  }
873
1138
  await projected.refresh(lastRefreshKeys);
874
1139
  },
875
- () => {
1140
+ (kind) => {
876
1141
  if (lastRefreshKeys.length > 0) {
877
- refresh$.next(lastRefreshKeys);
878
- opts.onRefresh?.(lastRefreshKeys);
1142
+ emit(lastRefreshKeys, kind);
879
1143
  }
880
1144
  },
881
1145
  () => {
@@ -899,12 +1163,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
899
1163
  dependencyCollector.removeItem(key);
900
1164
  projected.delete(key);
901
1165
  }
902
- const ids = [...evicted];
903
- refresh$.next(ids);
904
- opts.onRefresh?.(ids);
1166
+ emit([...evicted], "upstream-update");
905
1167
  }
906
1168
  });
907
- void scheduleRefresh;
908
1169
  return {
909
1170
  instance: {
910
1171
  name: _def.name,
@@ -913,7 +1174,7 @@ function createLazyCollection(source, options, client, updates$, resolver) {
913
1174
  return projected.get(idOrIds);
914
1175
  },
915
1176
  refresh() {
916
- scheduleRefresh();
1177
+ scheduleRefresh("on-demand");
917
1178
  },
918
1179
  clear() {
919
1180
  dependencyCollector.clear();
@@ -927,47 +1188,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
927
1188
  };
928
1189
  }
929
1190
 
930
- // src/model-resolver.ts
931
- var ModelResolver = class {
932
- _typeNames;
933
- _toModel;
934
- _toTypeName;
935
- constructor(models) {
936
- const toModel = /* @__PURE__ */ new Map();
937
- const toTypeName = /* @__PURE__ */ new Map();
938
- let typeNames;
939
- if (models) {
940
- typeNames = /* @__PURE__ */ new Set();
941
- for (const [model, typeName] of Object.entries(models)) {
942
- toModel.set(typeName, model);
943
- toTypeName.set(model, typeName);
944
- typeNames.add(typeName);
945
- }
946
- }
947
- this._typeNames = typeNames;
948
- this._toModel = toModel;
949
- this._toTypeName = toTypeName;
950
- }
951
- hasTypeName(typeName) {
952
- return !this._typeNames || this._typeNames.has(typeName);
953
- }
954
- getModel(typeName) {
955
- return this._toModel.get(typeName);
956
- }
957
- getTypeName(model) {
958
- return this._toTypeName.get(model) ?? model;
959
- }
960
- hasModel(model) {
961
- return !this._toTypeName.size || this._toTypeName.has(model);
962
- }
963
- resolveModel(typeName) {
964
- return this._toModel.get(typeName) ?? typeName;
965
- }
966
- };
967
-
968
- // src/routes.ts
969
- var import_client6 = require("@contello/client");
970
- var import_projected5 = require("projected");
1191
+ // src/lazy-routes.ts
1192
+ var import_client7 = require("@contello/client");
1193
+ var import_projected6 = require("projected");
971
1194
 
972
1195
  // src/routes-mapping.ts
973
1196
  function mapRoute(raw, resolver) {
@@ -1018,15 +1241,12 @@ function mapRoute(raw, resolver) {
1018
1241
  }
1019
1242
  }
1020
1243
 
1021
- // src/routes.ts
1244
+ // src/lazy-routes.ts
1022
1245
  var ID_PREFIX = "1\0";
1023
1246
  var PATH_PREFIX = "2\0";
1024
1247
  var CACHE_KEY = /* @__PURE__ */ Symbol("cacheKey");
1025
- function collectRoutes(data, keyFn, resolver) {
1026
- return (data.contelloRoutes ?? []).reduce((acc, raw) => {
1027
- if (!raw) {
1028
- return acc;
1029
- }
1248
+ function collectRoutes(rawItems, keyFn, resolver) {
1249
+ return rawItems.reduce((acc, raw) => {
1030
1250
  const mapped = mapRoute(raw, resolver);
1031
1251
  if (mapped) {
1032
1252
  mapped[CACHE_KEY] = keyFn(mapped);
@@ -1076,15 +1296,21 @@ function createRoutesCache(max, ttl) {
1076
1296
  keys: () => lru.keys()
1077
1297
  };
1078
1298
  }
1079
- function createRoutesCollection(def, client, updates$, resolver) {
1299
+ function createLazyRoutesCollection(def, client, updates$, resolver) {
1080
1300
  const _def = {
1081
1301
  cache: {
1082
1302
  max: def?.cache?.max ?? 1e3,
1083
- ttl: def?.cache?.ttl
1303
+ ttl: resolveTtl(def?.cache?.ttl)
1084
1304
  }
1085
1305
  };
1086
1306
  const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1087
- const projected = new import_projected5.ProjectedLazyMap({
1307
+ const routesSourceDoc = (0, import_client7.createSourceSubscription)(schema.sources.storeRoute);
1308
+ function fetchRoutes(vars) {
1309
+ return (0, import_client7.collectAsync)(
1310
+ (0, import_client7.mapAsync)(client.subscribe(routesSourceDoc, vars), (data) => data.source)
1311
+ );
1312
+ }
1313
+ const projected = new import_projected6.ProjectedLazyMap({
1088
1314
  key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1089
1315
  values: (prefixedKeys) => wrap("routes", () => {
1090
1316
  const ids = [];
@@ -1098,13 +1324,16 @@ function createRoutesCollection(def, client, updates$, resolver) {
1098
1324
  }
1099
1325
  }
1100
1326
  return Promise.all([
1101
- ids.length > 0 ? client.execute(storeGetRoutesDocument, { request: { ids } }).then((data) => collectRoutes(data, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1102
- paths.length > 0 ? client.execute(storeGetRoutesDocument, { request: { paths } }).then((data) => collectRoutes(data, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1327
+ ids.length > 0 ? fetchRoutes({ ids }).then((raw) => collectRoutes(raw, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1328
+ paths.length > 0 ? fetchRoutes({ paths }).then((raw) => collectRoutes(raw, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1103
1329
  ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1104
1330
  }),
1105
1331
  cache
1106
1332
  });
1107
- const refresh$ = (0, import_client6.createAsyncIterableSubject)();
1333
+ const channel = createRefreshChannel(def?.onRefresh);
1334
+ function emit(ids, kind) {
1335
+ channel.emit({ ids, kind });
1336
+ }
1108
1337
  let lastRefreshKeys = [];
1109
1338
  const scheduleRefresh = createRefresher(
1110
1339
  async () => {
@@ -1114,9 +1343,12 @@ function createRoutesCollection(def, client, updates$, resolver) {
1114
1343
  }
1115
1344
  await projected.refresh(lastRefreshKeys);
1116
1345
  },
1117
- () => {
1346
+ (kind) => {
1118
1347
  if (lastRefreshKeys.length > 0) {
1119
- refresh$.next(lastRefreshKeys.map((key) => key.slice(2)));
1348
+ emit(
1349
+ lastRefreshKeys.map((key) => key.slice(2)),
1350
+ kind
1351
+ );
1120
1352
  }
1121
1353
  },
1122
1354
  () => {
@@ -1137,12 +1369,12 @@ function createRoutesCollection(def, client, updates$, resolver) {
1137
1369
  }
1138
1370
  }
1139
1371
  if (evicted.length > 0) {
1140
- refresh$.next(evicted);
1372
+ emit(evicted, "upstream-update");
1141
1373
  }
1142
1374
  });
1143
1375
  return {
1144
1376
  instance: {
1145
- refresh$,
1377
+ refresh$: channel.stream$,
1146
1378
  get(idOrIds) {
1147
1379
  if (Array.isArray(idOrIds)) {
1148
1380
  return projected.get(idOrIds.map((id) => ID_PREFIX + id));
@@ -1156,7 +1388,7 @@ function createRoutesCollection(def, client, updates$, resolver) {
1156
1388
  return projected.get(PATH_PREFIX + pathOrPaths);
1157
1389
  },
1158
1390
  refresh() {
1159
- scheduleRefresh();
1391
+ scheduleRefresh("on-demand");
1160
1392
  },
1161
1393
  clear() {
1162
1394
  projected.clear();
@@ -1164,60 +1396,311 @@ function createRoutesCollection(def, client, updates$, resolver) {
1164
1396
  },
1165
1397
  destroy() {
1166
1398
  unsubUpdates();
1167
- refresh$.complete();
1399
+ channel.complete();
1400
+ }
1401
+ };
1402
+ }
1403
+
1404
+ // src/model-resolver.ts
1405
+ var ModelResolver = class {
1406
+ _typeNames;
1407
+ _toModel;
1408
+ _toTypeName;
1409
+ constructor(models2) {
1410
+ const toModel = /* @__PURE__ */ new Map();
1411
+ const toTypeName = /* @__PURE__ */ new Map();
1412
+ let typeNames;
1413
+ if (models2) {
1414
+ typeNames = /* @__PURE__ */ new Set();
1415
+ for (const [model, typeName] of Object.entries(models2)) {
1416
+ toModel.set(typeName, model);
1417
+ toTypeName.set(model, typeName);
1418
+ typeNames.add(typeName);
1419
+ }
1420
+ }
1421
+ this._typeNames = typeNames;
1422
+ this._toModel = toModel;
1423
+ this._toTypeName = toTypeName;
1424
+ }
1425
+ hasTypeName(typeName) {
1426
+ return !this._typeNames || this._typeNames.has(typeName);
1427
+ }
1428
+ getModel(typeName) {
1429
+ return this._toModel.get(typeName);
1430
+ }
1431
+ getTypeName(model) {
1432
+ return this._toTypeName.get(model) ?? model;
1433
+ }
1434
+ hasModel(model) {
1435
+ return !this._toTypeName.size || this._toTypeName.has(model);
1436
+ }
1437
+ resolveModel(typeName) {
1438
+ return this._toModel.get(typeName) ?? typeName;
1439
+ }
1440
+ };
1441
+
1442
+ // src/routes.ts
1443
+ var import_client8 = require("@contello/client");
1444
+ var import_projected7 = require("projected");
1445
+ function createRoutesCollection(options, client, updates$, resolver, refreshByTtl) {
1446
+ const opts = options ?? {};
1447
+ const cache = {
1448
+ ttl: resolveTtl(opts.cache?.ttl),
1449
+ eviction: opts.cache?.eviction ?? "refresh"
1450
+ };
1451
+ const channel = createRefreshChannel(opts.onRefresh);
1452
+ const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
1453
+ const pathById = /* @__PURE__ */ new Map();
1454
+ const idByPath = /* @__PURE__ */ new Map();
1455
+ let loaded = false;
1456
+ const routesSourceDoc = (0, import_client8.createSourceSubscription)(schema.sources.storeRoute);
1457
+ const projected = new import_projected7.ProjectedMap({
1458
+ key: (route) => route.id,
1459
+ values: (ids) => wrap(
1460
+ "routes",
1461
+ () => (0, import_client8.collectAsync)(
1462
+ (0, import_client8.mapAsync)(client.subscribe(routesSourceDoc, { ids }), (data) => data.source)
1463
+ ).then((rawItems) => {
1464
+ const items = rawItems.reduce((acc, raw) => {
1465
+ const mapped = mapRoute(raw, resolver);
1466
+ if (mapped) {
1467
+ acc.push(mapped);
1468
+ }
1469
+ return acc;
1470
+ }, []);
1471
+ if (ids === void 0) {
1472
+ pathById.clear();
1473
+ idByPath.clear();
1474
+ for (const r of items) {
1475
+ pathById.set(r.id, r.path);
1476
+ idByPath.set(r.path, r.id);
1477
+ }
1478
+ if (!loaded) {
1479
+ loaded = true;
1480
+ ttl.mark();
1481
+ opts.onLoad?.(items.map((r) => r.id));
1482
+ }
1483
+ } else {
1484
+ const returnedIds = new Set(items.map((r) => r.id));
1485
+ for (const id of ids) {
1486
+ if (!returnedIds.has(id)) {
1487
+ const oldPath = pathById.get(id);
1488
+ if (oldPath !== void 0) {
1489
+ idByPath.delete(oldPath);
1490
+ pathById.delete(id);
1491
+ }
1492
+ }
1493
+ }
1494
+ for (const r of items) {
1495
+ const oldPath = pathById.get(r.id);
1496
+ if (oldPath !== void 0 && oldPath !== r.path) {
1497
+ idByPath.delete(oldPath);
1498
+ }
1499
+ pathById.set(r.id, r.path);
1500
+ idByPath.set(r.path, r.id);
1501
+ }
1502
+ }
1503
+ return items;
1504
+ })
1505
+ )
1506
+ });
1507
+ function emit(ids, kind) {
1508
+ channel.emit({ ids, kind });
1509
+ }
1510
+ function runFullRefresh(kind) {
1511
+ refreshByTtl.enqueue(
1512
+ () => (0, import_client8.runWithBackoff)(
1513
+ () => projected.refresh().then((map) => {
1514
+ emit([...map.keys()], kind);
1515
+ ttl.mark();
1516
+ })
1517
+ )
1518
+ );
1519
+ }
1520
+ function runPartialRefresh(refreshIds, deletedIds) {
1521
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1522
+ if (refreshIds.length === 0) {
1523
+ emit(changedIds, "upstream-update");
1524
+ return;
1525
+ }
1526
+ void (0, import_client8.runWithBackoff)(
1527
+ () => projected.refresh(refreshIds).then(() => {
1528
+ emit(changedIds, "upstream-update");
1529
+ })
1530
+ );
1531
+ }
1532
+ const unsubUpdates = updates$.subscribe((batch) => {
1533
+ if (!loaded || batch.route.length === 0) {
1534
+ return;
1535
+ }
1536
+ const deleted = [];
1537
+ const upserted = /* @__PURE__ */ new Set();
1538
+ for (const event of batch.route) {
1539
+ if (event.mutation === "delete") {
1540
+ deleted.push(event.id);
1541
+ } else {
1542
+ upserted.add(event.id);
1543
+ }
1544
+ }
1545
+ if (cache.eviction === "clear") {
1546
+ pathById.clear();
1547
+ idByPath.clear();
1548
+ projected.clear();
1549
+ return;
1550
+ }
1551
+ for (const id of deleted) {
1552
+ const oldPath = pathById.get(id);
1553
+ if (oldPath !== void 0) {
1554
+ idByPath.delete(oldPath);
1555
+ pathById.delete(id);
1556
+ }
1557
+ }
1558
+ if (deleted.length > 0) {
1559
+ projected.delete(deleted);
1560
+ }
1561
+ runPartialRefresh([...upserted], deleted);
1562
+ });
1563
+ function getByIdSingle(id) {
1564
+ return projected.get(id);
1565
+ }
1566
+ function getByIds(ids) {
1567
+ return projected.get(ids);
1568
+ }
1569
+ function lookupByPathSingle(path) {
1570
+ return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1571
+ const id = idByPath.get(path);
1572
+ return id === void 0 ? void 0 : projected.get(id);
1573
+ });
1574
+ }
1575
+ function lookupByPaths(paths) {
1576
+ return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1577
+ const ids = [];
1578
+ for (const p of paths) {
1579
+ const id = idByPath.get(p);
1580
+ if (id !== void 0) {
1581
+ ids.push(id);
1582
+ }
1583
+ }
1584
+ return projected.get(ids);
1585
+ });
1586
+ }
1587
+ function ensureLoaded() {
1588
+ if (loaded) {
1589
+ return void 0;
1590
+ }
1591
+ return (0, import_projected7.maybeThen)(projected.getAllAsMap(), () => void 0);
1592
+ }
1593
+ const instance = {
1594
+ refresh$: channel.stream$,
1595
+ async load() {
1596
+ if (!loaded) {
1597
+ await projected.getAllAsMap();
1598
+ }
1599
+ },
1600
+ get(idOrIds) {
1601
+ return Array.isArray(idOrIds) ? getByIds(idOrIds) : getByIdSingle(idOrIds);
1602
+ },
1603
+ getByPath(pathOrPaths) {
1604
+ return Array.isArray(pathOrPaths) ? lookupByPaths(pathOrPaths) : lookupByPathSingle(pathOrPaths);
1605
+ },
1606
+ refresh() {
1607
+ runFullRefresh("on-demand");
1608
+ }
1609
+ };
1610
+ return {
1611
+ instance,
1612
+ destroy() {
1613
+ unsubUpdates();
1614
+ ttl.clear();
1615
+ channel.complete();
1616
+ }
1617
+ };
1618
+ }
1619
+ function createRoutesSyncCollection(options, client, updates$, resolver, refreshByTtl) {
1620
+ const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1621
+ function assertSync(value, method) {
1622
+ if (value instanceof Promise) {
1623
+ throw new Error(`routes.${method}() is not initialized yet \u2014 call routes.load() first`);
1168
1624
  }
1625
+ return value;
1626
+ }
1627
+ return {
1628
+ instance: {
1629
+ ...base,
1630
+ get(idOrIds) {
1631
+ return assertSync(base.get(idOrIds), "get");
1632
+ },
1633
+ getByPath(pathOrPaths) {
1634
+ return assertSync(base.getByPath(pathOrPaths), "getByPath");
1635
+ }
1636
+ },
1637
+ destroy
1169
1638
  };
1170
1639
  }
1171
1640
 
1172
1641
  // src/singleton.ts
1173
- var import_client7 = require("@contello/client");
1174
- var import_projected6 = require("projected");
1175
- function createSingleton(source, options, client, updates$, resolver) {
1642
+ var import_client9 = require("@contello/client");
1643
+ var import_projected8 = require("projected");
1644
+ function createSingleton(source, options, client, updates$, resolver, refreshByTtl) {
1176
1645
  const opts = options ?? {};
1177
1646
  const mapFn = opts.map ?? ((item) => item);
1178
1647
  const _def = {
1179
1648
  name: opts.name ?? source.__model,
1180
1649
  model: source.__model,
1181
1650
  cache: {
1182
- ttl: opts.cache?.ttl,
1651
+ ttl: resolveTtl(opts.cache?.ttl),
1183
1652
  eviction: opts.cache?.eviction ?? "refresh"
1184
1653
  }
1185
1654
  };
1186
1655
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
1187
1656
  const itemKey = `singleton:${_def.name}`;
1188
- let timer;
1189
- const projected = new import_projected6.ProjectedValue({
1657
+ const channel = createRefreshChannel(opts.onRefresh);
1658
+ const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });
1659
+ let loaded = false;
1660
+ const projected = new import_projected8.ProjectedValue({
1190
1661
  value: () => wrap(
1191
1662
  `singleton:${_def.name}`,
1192
- () => (0, import_projected6.maybeThen)(
1193
- (0, import_client7.firstAsync)(
1194
- (0, import_client7.mapAsync)(
1195
- client.subscribe((0, import_client7.createSourceSubscription)(source)),
1663
+ () => (0, import_projected8.maybeThen)(
1664
+ (0, import_client9.firstAsync)(
1665
+ (0, import_client9.mapAsync)(
1666
+ client.subscribe((0, import_client9.createSourceSubscription)(source)),
1196
1667
  (r) => r.source
1197
1668
  )
1198
1669
  ),
1199
1670
  (raw) => dependencyCollector.createContext(
1200
- (ref, register) => (0, import_projected6.maybeThen)(mapFn(raw, ref), (mapped) => {
1671
+ (ref, register) => (0, import_projected8.maybeThen)(mapFn(raw, ref), (mapped) => {
1201
1672
  register(itemKey);
1673
+ if (!loaded) {
1674
+ loaded = true;
1675
+ ttl.mark();
1676
+ opts.onLoad?.();
1677
+ }
1202
1678
  return mapped;
1203
1679
  })
1204
1680
  )
1205
1681
  )
1206
1682
  )
1207
1683
  });
1208
- const refresh$ = (0, import_client7.createAsyncIterableSubject)();
1684
+ function emit(kind) {
1685
+ channel.emit({ kind });
1686
+ }
1687
+ function runTtlRefresh() {
1688
+ refreshByTtl.enqueue(
1689
+ () => (0, import_client9.runWithBackoff)(() => projected.refresh()).then(() => {
1690
+ emit("ttl");
1691
+ ttl.mark();
1692
+ })
1693
+ );
1694
+ }
1209
1695
  const scheduleRefresh = createRefresher(
1210
1696
  () => projected.refresh(),
1211
- () => {
1212
- refresh$.next();
1213
- opts.onRefresh?.();
1214
- if (_def.cache.ttl !== void 0) {
1215
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1216
- }
1697
+ (kind) => {
1698
+ emit(kind);
1699
+ ttl.mark();
1217
1700
  },
1218
- () => clearTimeout(timer)
1701
+ () => {
1702
+ }
1219
1703
  );
1220
- let loaded = false;
1221
1704
  const unsubUpdates = updates$.subscribe((batch) => {
1222
1705
  if (!loaded) {
1223
1706
  return;
@@ -1232,41 +1715,39 @@ function createSingleton(source, options, client, updates$, resolver) {
1232
1715
  projected.clear();
1233
1716
  return;
1234
1717
  }
1235
- scheduleRefresh();
1718
+ scheduleRefresh("upstream-update");
1236
1719
  });
1237
1720
  return {
1238
1721
  instance: {
1239
1722
  name: _def.name,
1240
- refresh$,
1723
+ refresh$: channel.stream$,
1241
1724
  get() {
1242
1725
  return projected.get();
1243
1726
  },
1244
1727
  refresh() {
1245
- scheduleRefresh();
1728
+ scheduleRefresh("on-demand");
1246
1729
  },
1247
1730
  async load() {
1248
- await projected.get();
1249
- loaded = true;
1250
- if (_def.cache.ttl !== void 0) {
1251
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1731
+ if (!loaded) {
1732
+ await projected.get();
1252
1733
  }
1253
- opts.onLoad?.();
1254
1734
  }
1255
1735
  },
1256
1736
  destroy() {
1257
1737
  unsubUpdates();
1258
- clearTimeout(timer);
1259
- refresh$.complete();
1738
+ ttl.clear();
1739
+ channel.complete();
1260
1740
  }
1261
1741
  };
1262
1742
  }
1263
- function createSingletonSync(source, options, client, updates$, resolver) {
1743
+ function createSingletonSync(source, options, client, updates$, resolver, refreshByTtl) {
1264
1744
  const { instance: base, destroy } = createSingleton(
1265
1745
  source,
1266
1746
  options,
1267
1747
  client,
1268
1748
  updates$,
1269
- resolver
1749
+ resolver,
1750
+ refreshByTtl
1270
1751
  );
1271
1752
  return {
1272
1753
  instance: {
@@ -1284,7 +1765,7 @@ function createSingletonSync(source, options, client, updates$, resolver) {
1284
1765
  }
1285
1766
 
1286
1767
  // src/watcher.ts
1287
- var import_client8 = require("@contello/client");
1768
+ var import_client10 = require("@contello/client");
1288
1769
  function addRouteByModel(map, entityType, event) {
1289
1770
  let list = map.get(entityType);
1290
1771
  if (!list) {
@@ -1374,7 +1855,7 @@ function mapEvent(raw, resolver) {
1374
1855
  }
1375
1856
  }
1376
1857
  function createInternalWatcher(client, resolver) {
1377
- const updates$ = (0, import_client8.createAsyncIterableSubject)();
1858
+ const updates$ = (0, import_client10.createAsyncIterableSubject)();
1378
1859
  let controller;
1379
1860
  return {
1380
1861
  updates$,
@@ -1386,11 +1867,11 @@ function createInternalWatcher(client, resolver) {
1386
1867
  const signal = controller.signal;
1387
1868
  wrap("watcher:start", () => {
1388
1869
  void (async () => {
1389
- const source = (0, import_client8.asyncKeepalive)(
1870
+ const source = (0, import_client10.asyncKeepalive)(
1390
1871
  () => client.subscribe(storeWatchUpdatesDocument),
1391
1872
  signal
1392
1873
  );
1393
- const events = (0, import_client8.mapAsync)(
1874
+ const events = (0, import_client10.mapAsync)(
1394
1875
  source,
1395
1876
  (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => mapEvent(e, resolver)).filter((e) => e !== void 0)
1396
1877
  );
@@ -1421,26 +1902,27 @@ var Store = class {
1421
1902
  _watcher;
1422
1903
  _schema;
1423
1904
  _cleanups = [];
1905
+ _refreshByTtl = createRefreshByTtlQueue();
1424
1906
  /**
1425
1907
  * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1426
1908
  * each iteration starts an independent fan-out from the shared source.
1427
1909
  */
1428
1910
  updates$;
1429
1911
  constructor(options) {
1430
- const { url, project, token, schema } = options;
1431
- this._schema = schema;
1432
- this._client = (0, import_client9.createContelloClient)({
1912
+ const { url, project, token, schema: schema2 } = options;
1913
+ this._schema = schema2;
1914
+ this._client = (0, import_client11.createContelloClient)({
1433
1915
  url,
1434
1916
  project,
1435
1917
  token,
1436
- schema,
1918
+ schema: schema2,
1437
1919
  connections: options.connections,
1438
1920
  onConnected: options.onConnected,
1439
1921
  onReconnecting: options.onReconnecting,
1440
1922
  onError: options.onError,
1441
1923
  connectionEvents: options.connectionEvents
1442
1924
  });
1443
- this._resolver = new ModelResolver(schema?.models);
1925
+ this._resolver = new ModelResolver(schema2?.models);
1444
1926
  this._watcher = createInternalWatcher(this._client, this._resolver);
1445
1927
  this.updates$ = this._watcher.updates$;
1446
1928
  this.ping = () => this._client.ping();
@@ -1482,7 +1964,8 @@ var Store = class {
1482
1964
  options,
1483
1965
  this._client,
1484
1966
  this._watcher.updates$,
1485
- this._resolver
1967
+ this._resolver,
1968
+ this._refreshByTtl
1486
1969
  );
1487
1970
  this._cleanups.push(destroy);
1488
1971
  return instance;
@@ -1494,7 +1977,8 @@ var Store = class {
1494
1977
  options,
1495
1978
  this._client,
1496
1979
  this._watcher.updates$,
1497
- this._resolver
1980
+ this._resolver,
1981
+ this._refreshByTtl
1498
1982
  );
1499
1983
  this._cleanups.push(destroy);
1500
1984
  return instance;
@@ -1507,7 +1991,8 @@ var Store = class {
1507
1991
  options,
1508
1992
  this._client,
1509
1993
  this._watcher.updates$,
1510
- this._resolver
1994
+ this._resolver,
1995
+ this._refreshByTtl
1511
1996
  );
1512
1997
  this._cleanups.push(destroy);
1513
1998
  return instance;
@@ -1519,7 +2004,8 @@ var Store = class {
1519
2004
  options,
1520
2005
  this._client,
1521
2006
  this._watcher.updates$,
1522
- this._resolver
2007
+ this._resolver,
2008
+ this._refreshByTtl
1523
2009
  );
1524
2010
  this._cleanups.push(destroy);
1525
2011
  return instance;
@@ -1538,18 +2024,67 @@ var Store = class {
1538
2024
  return instance;
1539
2025
  }
1540
2026
  // --- assets / routes / i18n (no source — built-ins) ---
2027
+ // --- assets ---
1541
2028
  defineAssets(options) {
1542
- const { instance, destroy } = createAssetsCollection(options, this._client, this._watcher.updates$);
2029
+ const { instance, destroy } = createAssetsCollection(
2030
+ options,
2031
+ this._client,
2032
+ this._watcher.updates$,
2033
+ this._refreshByTtl
2034
+ );
2035
+ this._cleanups.push(destroy);
2036
+ return instance;
2037
+ }
2038
+ defineAssetsSync(options) {
2039
+ const { instance, destroy } = createAssetsSyncCollection(
2040
+ options,
2041
+ this._client,
2042
+ this._watcher.updates$,
2043
+ this._refreshByTtl
2044
+ );
2045
+ this._cleanups.push(destroy);
2046
+ return instance;
2047
+ }
2048
+ defineLazyAssets(options) {
2049
+ const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
1543
2050
  this._cleanups.push(destroy);
1544
2051
  return instance;
1545
2052
  }
2053
+ // --- routes ---
1546
2054
  defineRoutes(options) {
1547
- const { instance, destroy } = createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
2055
+ const { instance, destroy } = createRoutesCollection(
2056
+ options,
2057
+ this._client,
2058
+ this._watcher.updates$,
2059
+ this._resolver,
2060
+ this._refreshByTtl
2061
+ );
2062
+ this._cleanups.push(destroy);
2063
+ return instance;
2064
+ }
2065
+ defineRoutesSync(options) {
2066
+ const { instance, destroy } = createRoutesSyncCollection(
2067
+ options,
2068
+ this._client,
2069
+ this._watcher.updates$,
2070
+ this._resolver,
2071
+ this._refreshByTtl
2072
+ );
2073
+ this._cleanups.push(destroy);
2074
+ return instance;
2075
+ }
2076
+ defineLazyRoutes(options) {
2077
+ const { instance, destroy } = createLazyRoutesCollection(
2078
+ options,
2079
+ this._client,
2080
+ this._watcher.updates$,
2081
+ this._resolver
2082
+ );
1548
2083
  this._cleanups.push(destroy);
1549
2084
  return instance;
1550
2085
  }
1551
2086
  defineI18nMessages(def) {
1552
- const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$);
2087
+ const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
1553
2088
  this._cleanups.push(result.destroy);
1554
2089
  return result;
1555
2090
  }
@@ -1560,7 +2095,7 @@ function createStore(options) {
1560
2095
  }
1561
2096
 
1562
2097
  // src/index.ts
1563
- var import_projected7 = require("projected");
2098
+ var import_projected9 = require("projected");
1564
2099
  // Annotate the CommonJS export names for ESM import in node:
1565
2100
  0 && (module.exports = {
1566
2101
  Store,