@contello/store 2.0.1 → 2.1.1

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
@@ -3,9 +3,12 @@ import { createContelloClient } from "@contello/client";
3
3
 
4
4
  // src/assets.ts
5
5
  import {
6
- createAsyncIterableSubject
6
+ collectAsync,
7
+ createSourceSubscription,
8
+ mapAsync,
9
+ runWithBackoff as runWithBackoff2
7
10
  } from "@contello/client";
8
- import { ProjectedLazyMap } from "projected";
11
+ import { ProjectedMap } from "projected";
9
12
 
10
13
  // src/diagnostics.ts
11
14
  import dc from "diagnostics_channel";
@@ -133,20 +136,6 @@ var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
133
136
  value
134
137
  }
135
138
  }`;
136
- var storeGetAssetsDocument = `${MediaFileFragmentSchema}
137
- ${MediaAssetFragmentSchema}
138
- ${StoreAssetFragmentSchema}
139
- query StoreGetAssets($filter: ContelloAssetsFilterInput!) {
140
- contelloAssets(filter: $filter) {
141
- ...StoreAsset
142
- }
143
- }`;
144
- var storeGetI18nMessagesDocument = `${StoreI18nMessageFragmentSchema}
145
- subscription StoreGetI18nMessages($collection: String!) {
146
- contelloI18nMessagesBatch(collectionReferenceName: $collection) {
147
- ...StoreI18nMessage
148
- }
149
- }`;
150
139
  var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
151
140
  registerContelloI18nMessages(
152
141
  collectionReferenceName: $collection
@@ -156,12 +145,6 @@ var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($col
156
145
  ids
157
146
  }
158
147
  }`;
159
- var storeGetRoutesDocument = `${StoreRouteFragmentSchema}
160
- query StoreGetRoutes($request: ContelloRoutesRequestInput!) {
161
- contelloRoutes(request: $request) {
162
- ...StoreRoute
163
- }
164
- }`;
165
148
  var storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
166
149
  subscription StoreWatchUpdates {
167
150
  contelloUpdatesBatch {
@@ -194,6 +177,10 @@ subscription StoreWatchUpdates {
194
177
  }
195
178
  }
196
179
  }`;
180
+ var operations = {
181
+ storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: "mutation" },
182
+ storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: "subscription" }
183
+ };
197
184
  var sources = {
198
185
  storeAsset: {
199
186
  document: `${MediaFileFragmentSchema}
@@ -219,55 +206,101 @@ ${StoreAssetFragmentSchema}`,
219
206
  __cardinality: "route"
220
207
  }
221
208
  };
222
-
223
- // src/lru.ts
224
- import { LRUCache } from "lru-cache";
225
- function createLruCache(options) {
226
- const { max, ttl, onEvict: dispose } = options;
227
- const lru = new LRUCache({
228
- max,
229
- ...ttl !== void 0 && { ttl, ttlAutopurge: false },
230
- ...dispose !== void 0 && { dispose }
231
- });
232
- return {
233
- has: (key) => lru.has(key),
234
- get: (key) => lru.get(key),
235
- set: (key, value) => {
236
- lru.set(key, value);
237
- },
238
- delete: (key) => {
239
- lru.delete(key);
240
- },
241
- clear: () => {
242
- lru.clear();
243
- },
244
- keys: () => [...lru.keys()]
245
- };
246
- }
209
+ var models = {
210
+ dummy: "DummyEntity"
211
+ };
212
+ var schema = { operations, sources, models };
247
213
 
248
214
  // src/utils.ts
249
- import { runWithBackoff } from "@contello/client";
215
+ import { createAsyncIterableSubject, runWithBackoff } from "@contello/client";
216
+ var DEFAULT_TTL_MS = 3 * 60 * 60 * 1e3;
217
+ var DEFAULT_LRU_MAX = 1e3;
218
+ function resolveTtl(ttl) {
219
+ if (ttl === void 0) return DEFAULT_TTL_MS;
220
+ if (ttl === false || ttl <= 0) return void 0;
221
+ return ttl;
222
+ }
250
223
  function createRefresher(fn, onRefreshed, onStart2) {
251
224
  let refreshing = false;
252
- let pending = false;
253
- function scheduleRefresh() {
225
+ let inFlightKind;
226
+ let pendingKind;
227
+ function scheduleRefresh(kind) {
254
228
  if (refreshing) {
255
- pending = true;
229
+ pendingKind = { kind };
256
230
  return;
257
231
  }
258
232
  refreshing = true;
233
+ inFlightKind = kind;
259
234
  onStart2?.();
260
235
  void runWithBackoff(fn).then(() => {
236
+ const finished = inFlightKind;
261
237
  refreshing = false;
262
- onRefreshed();
263
- if (pending) {
264
- pending = false;
265
- scheduleRefresh();
238
+ inFlightKind = void 0;
239
+ onRefreshed(finished);
240
+ if (pendingKind) {
241
+ const { kind: next } = pendingKind;
242
+ pendingKind = void 0;
243
+ scheduleRefresh(next);
266
244
  }
267
245
  });
268
246
  }
269
247
  return scheduleRefresh;
270
248
  }
249
+ 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
+ };
261
+ }
262
+ 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
+ };
282
+ }
283
+ 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
+ };
303
+ }
271
304
 
272
305
  // src/assets.ts
273
306
  function mapFile(raw) {
@@ -282,95 +315,142 @@ function mapAsset(raw) {
282
315
  id: raw.id,
283
316
  original: mapFile(raw.original),
284
317
  preview: raw.preview ? mapFile(raw.preview) : void 0,
285
- optimized: raw.optimized.map(mapFile)
318
+ optimized: raw.optimized.map((file) => mapFile(file))
286
319
  };
287
320
  }
288
- function createAssetsCollection(def, client, updates$) {
289
- const _def = {
290
- cache: {
291
- max: def?.cache?.max ?? 1e3,
292
- ttl: def?.cache?.ttl
293
- }
321
+ 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"
294
326
  };
295
- const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
296
- const projected = new ProjectedLazyMap({
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({
297
332
  key: (asset) => asset.id,
298
333
  values: (ids) => wrap(
299
334
  "assets",
300
- () => client.execute(storeGetAssetsDocument, { filter: { ids } }).then(
301
- (data) => (data.contelloAssets ?? []).reduce((acc, raw) => {
302
- if (raw) {
303
- acc.push(mapAsset(raw));
304
- }
305
- return acc;
306
- }, [])
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
+ })
307
358
  )
308
- ),
309
- cache
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);
310
394
  });
311
- const refresh$ = createAsyncIterableSubject();
312
- let lastRefreshKeys = [];
313
- const scheduleRefresh = createRefresher(
314
- async () => {
315
- lastRefreshKeys = cache.keys();
316
- if (lastRefreshKeys.length === 0) {
317
- return;
395
+ const instance = {
396
+ refresh$: channel.stream$,
397
+ async load() {
398
+ if (!loaded) {
399
+ await projected.getAllAsMap();
318
400
  }
319
- await projected.refresh(lastRefreshKeys);
320
401
  },
321
- () => {
322
- if (lastRefreshKeys.length > 0) {
323
- refresh$.next(lastRefreshKeys);
324
- }
402
+ get(idOrIds) {
403
+ return projected.get(idOrIds);
325
404
  },
326
- () => {
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");
327
416
  }
328
- );
329
- const unsubUpdates = updates$.subscribe((batch) => {
330
- if (batch.asset.length === 0) return;
331
- for (const event of batch.asset) {
332
- projected.delete(event.id);
417
+ };
418
+ return {
419
+ instance,
420
+ destroy() {
421
+ unsubUpdates();
422
+ ttl.clear();
423
+ channel.complete();
333
424
  }
334
- refresh$.next(batch.asset.map((e) => e.id));
335
- });
425
+ };
426
+ }
427
+ 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
+ }
336
435
  return {
337
436
  instance: {
338
- refresh$,
437
+ ...base,
339
438
  get(idOrIds) {
340
- return projected.get(idOrIds);
341
- },
342
- upload(data, meta, options) {
343
- return client.upload(data, meta, options);
344
- },
345
- download(fileId) {
346
- return client.download(fileId);
347
- },
348
- proxyHls(path, signal) {
349
- return client.proxyHls(path, signal);
350
- },
351
- refresh() {
352
- scheduleRefresh();
353
- },
354
- clear() {
355
- projected.clear();
439
+ return assertSync(base.get(idOrIds), "get");
356
440
  }
357
441
  },
358
- destroy() {
359
- unsubUpdates();
360
- refresh$.complete();
361
- }
442
+ destroy
362
443
  };
363
444
  }
364
445
 
365
446
  // src/collection.ts
366
447
  import {
367
- collectAsync,
368
- createAsyncIterableSubject as createAsyncIterableSubject2,
369
- createSourceSubscription,
370
- mapAsync,
371
- runWithBackoff as runWithBackoff2
448
+ collectAsync as collectAsync2,
449
+ createSourceSubscription as createSourceSubscription2,
450
+ mapAsync as mapAsync2,
451
+ runWithBackoff as runWithBackoff3
372
452
  } from "@contello/client";
373
- import { ProjectedMap, maybeThen } from "projected";
453
+ import { ProjectedMap as ProjectedMap2, maybeThen } from "projected";
374
454
 
375
455
  // src/dependency-collector.ts
376
456
  function createDependencyKey(target, id) {
@@ -405,12 +485,14 @@ var DependencyCollector = class {
405
485
  throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
406
486
  }
407
487
  switch (obj.__typename) {
408
- case "ContelloAsset":
488
+ case "ContelloAsset": {
409
489
  deps.push(createDependencyKey("asset", obj.id));
410
490
  break;
411
- case "ContelloRoute":
491
+ }
492
+ case "ContelloRoute": {
412
493
  deps.push(createDependencyKey("route", obj.id));
413
494
  break;
495
+ }
414
496
  default: {
415
497
  const model = this.resolver.getModel(obj.__typename);
416
498
  if (!model) {
@@ -526,27 +608,29 @@ var DependencyCollector = class {
526
608
 
527
609
  // src/collection.ts
528
610
  function fetchCollection(source, client, ids) {
529
- return collectAsync(
530
- mapAsync(
531
- client.subscribe(createSourceSubscription(source), { ids }),
611
+ return collectAsync2(
612
+ mapAsync2(
613
+ client.subscribe(createSourceSubscription2(source), { ids }),
532
614
  (r) => r.source
533
615
  )
534
616
  );
535
617
  }
536
- function createCollection(source, options, client, updates$, resolver) {
618
+ function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
537
619
  const opts = options ?? {};
538
620
  const mapFn = opts.map ?? ((item) => item);
539
621
  const _def = {
540
622
  name: opts.name ?? source.__model,
541
623
  model: source.__model,
542
624
  cache: {
543
- ttl: opts.cache?.ttl,
625
+ ttl: resolveTtl(opts.cache?.ttl),
544
626
  eviction: opts.cache?.eviction ?? "refresh"
545
627
  }
546
628
  };
547
629
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
548
- let ttlTimer;
549
- const projected = new ProjectedMap({
630
+ const channel = createRefreshChannel(opts.onRefresh);
631
+ const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh("ttl") });
632
+ let loaded = false;
633
+ const projected = new ProjectedMap2({
550
634
  key: (item) => item.id,
551
635
  values: (ids) => wrap(
552
636
  `collection:${_def.name}`,
@@ -554,16 +638,23 @@ function createCollection(source, options, client, updates$, resolver) {
554
638
  fetchCollection(source, client, ids),
555
639
  (rawItems) => Promise.all(
556
640
  rawItems.map(
557
- (item) => dependencyCollector.createContext(
558
- (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {
559
- register(mapped.id);
560
- return mapped;
561
- })
641
+ (item) => Promise.resolve(
642
+ dependencyCollector.createContext(
643
+ (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {
644
+ register(mapped.id);
645
+ return mapped;
646
+ })
647
+ )
562
648
  )
563
649
  )
564
650
  ).then((items) => {
565
651
  if (ids === void 0) {
566
652
  dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
653
+ if (!loaded) {
654
+ loaded = true;
655
+ ttl.mark();
656
+ opts.onLoad?.(items.map((item) => item.id));
657
+ }
567
658
  } else {
568
659
  const returnedIds = new Set(items.map((item) => item.id));
569
660
  for (const id of ids) {
@@ -578,38 +669,28 @@ function createCollection(source, options, client, updates$, resolver) {
578
669
  ),
579
670
  sort: opts.sort
580
671
  });
581
- const refresh$ = createAsyncIterableSubject2();
582
- let loaded = false;
583
- function scheduleTtl() {
584
- if (_def.cache.ttl === void 0) {
585
- return;
586
- }
587
- clearTimeout(ttlTimer);
588
- ttlTimer = setTimeout(() => {
589
- runFullRefresh();
590
- }, _def.cache.ttl);
672
+ function emit(ids, kind) {
673
+ channel.emit({ ids, kind });
591
674
  }
592
- function runFullRefresh() {
593
- void runWithBackoff2(
594
- () => projected.refresh().then((map) => {
595
- const ids = [...map.keys()];
596
- refresh$.next(ids);
597
- opts.onRefresh?.(ids);
598
- scheduleTtl();
599
- })
675
+ function runFullRefresh(kind) {
676
+ refreshByTtl.enqueue(
677
+ () => runWithBackoff3(
678
+ () => projected.refresh().then((map) => {
679
+ emit([...map.keys()], kind);
680
+ ttl.mark();
681
+ })
682
+ )
600
683
  );
601
684
  }
602
685
  function runPartialRefresh(refreshIds, deletedIds) {
603
686
  const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
604
687
  if (refreshIds.length === 0) {
605
- refresh$.next(changedIds);
606
- opts.onRefresh?.(changedIds);
688
+ emit(changedIds, "upstream-update");
607
689
  return;
608
690
  }
609
- void runWithBackoff2(
691
+ void runWithBackoff3(
610
692
  () => projected.refresh(refreshIds).then(() => {
611
- refresh$.next(changedIds);
612
- opts.onRefresh?.(changedIds);
693
+ emit(changedIds, "upstream-update");
613
694
  })
614
695
  );
615
696
  }
@@ -655,7 +736,7 @@ function createCollection(source, options, client, updates$, resolver) {
655
736
  });
656
737
  const instance = {
657
738
  name: _def.name,
658
- refresh$,
739
+ refresh$: channel.stream$,
659
740
  get(idOrIds) {
660
741
  return projected.get(idOrIds);
661
742
  },
@@ -663,35 +744,35 @@ function createCollection(source, options, client, updates$, resolver) {
663
744
  return projected.getAll();
664
745
  },
665
746
  refresh() {
666
- runFullRefresh();
747
+ runFullRefresh("on-demand");
667
748
  },
668
749
  async load() {
669
- const map = await projected.refresh();
670
- loaded = true;
671
- scheduleTtl();
672
- opts.onLoad?.([...map.keys()]);
750
+ if (!loaded) {
751
+ await projected.getAllAsMap();
752
+ }
673
753
  }
674
754
  };
675
755
  return {
676
756
  instance,
677
757
  destroy() {
678
758
  unsubUpdates();
679
- clearTimeout(ttlTimer);
680
- refresh$.complete();
759
+ ttl.clear();
760
+ channel.complete();
681
761
  }
682
762
  };
683
763
  }
684
- function createCollectionSync(source, options, client, updates$, resolver) {
764
+ function createCollectionSync(source, options, client, updates$, resolver, refreshByTtl) {
685
765
  const { instance: base, destroy } = createCollection(
686
766
  source,
687
767
  options,
688
768
  client,
689
769
  updates$,
690
- resolver
770
+ resolver,
771
+ refreshByTtl
691
772
  );
692
773
  function assertSync(value, method) {
693
774
  if (value instanceof Promise) {
694
- throw new Error(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
775
+ throw new TypeError(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
695
776
  }
696
777
  return value;
697
778
  }
@@ -711,11 +792,12 @@ function createCollectionSync(source, options, client, updates$, resolver) {
711
792
 
712
793
  // src/i18n.ts
713
794
  import {
714
- collectAsync as collectAsync2,
715
- createAsyncIterableSubject as createAsyncIterableSubject3,
716
- mapAsync as mapAsync2
795
+ collectAsync as collectAsync3,
796
+ createSourceSubscription as createSourceSubscription3,
797
+ mapAsync as mapAsync3,
798
+ runWithBackoff as runWithBackoff4
717
799
  } from "@contello/client";
718
- import { ProjectedMap as ProjectedMap2, maybeThen as maybeThen2 } from "projected";
800
+ import { ProjectedMap as ProjectedMap3, maybeThen as maybeThen2 } from "projected";
719
801
  function toGqlMessageInput(msg) {
720
802
  return {
721
803
  token: msg.token,
@@ -726,45 +808,103 @@ function toGqlMessageInput(msg) {
726
808
  initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message }))
727
809
  };
728
810
  }
729
- function createI18nMessagesCollection(def, client, updates$) {
730
- const projected = new ProjectedMap2({
811
+ function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
812
+ const channel = createRefreshChannel(def.onRefresh);
813
+ const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });
814
+ let loaded = false;
815
+ const i18nSourceDoc = createSourceSubscription3(schema.sources.storeI18nMessage);
816
+ const projected = new ProjectedMap3({
731
817
  key: (msg) => msg.id,
732
- values: () => wrap(
818
+ values: (ids) => wrap(
733
819
  `i18n:${def.collection}`,
734
- () => collectAsync2(
735
- mapAsync2(
736
- client.subscribe(storeGetI18nMessagesDocument, {
737
- collection: def.collection
820
+ () => collectAsync3(
821
+ mapAsync3(
822
+ client.subscribe(i18nSourceDoc, {
823
+ collection: def.collection,
824
+ ids
738
825
  }),
739
- (data) => data.contelloI18nMessagesBatch
826
+ (data) => data.source
740
827
  )
741
- ).then(
742
- (msgs) => msgs.map((msg) => ({
828
+ ).then((msgs) => {
829
+ const items = msgs.map((msg) => ({
743
830
  id: msg.id,
744
831
  token: msg.token,
745
832
  translations: new Map(msg.translations.map((t) => [t.language, t.value]))
746
- }))
747
- )
833
+ }));
834
+ if (ids === void 0 && !loaded) {
835
+ loaded = true;
836
+ ttl.mark();
837
+ }
838
+ return items;
839
+ })
748
840
  )
749
841
  });
750
- const refresh$ = createAsyncIterableSubject3();
842
+ function emit(ids, kind) {
843
+ channel.emit({ ids, kind });
844
+ }
845
+ function emitWithCurrentIds(kind) {
846
+ maybeThen2(projected.getAll(), (msgs) => {
847
+ emit(
848
+ msgs.map((m) => m.id),
849
+ kind
850
+ );
851
+ });
852
+ }
853
+ function runTtlRefresh() {
854
+ refreshByTtl.enqueue(
855
+ () => runWithBackoff4(() => projected.refresh()).then(() => {
856
+ emitWithCurrentIds("ttl");
857
+ ttl.mark();
858
+ })
859
+ );
860
+ }
751
861
  const scheduleRefresh = createRefresher(
752
862
  () => projected.refresh(),
753
- () => {
754
- maybeThen2(projected.getAll(), (msgs) => {
755
- refresh$.next(msgs.map((m) => m.id));
756
- });
863
+ (kind) => {
864
+ emitWithCurrentIds(kind);
865
+ ttl.mark();
757
866
  },
758
867
  () => {
759
868
  }
760
869
  );
870
+ function runPartialRefresh(upsertedIds, deletedIds) {
871
+ const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
872
+ if (changedIds.length === 0) {
873
+ return;
874
+ }
875
+ if (upsertedIds.length === 0) {
876
+ emit(changedIds, "upstream-update");
877
+ return;
878
+ }
879
+ void runWithBackoff4(
880
+ () => projected.refresh(upsertedIds).then(() => {
881
+ emit(changedIds, "upstream-update");
882
+ })
883
+ );
884
+ }
761
885
  const unsubUpdates = updates$.subscribe((batch) => {
762
- if (batch.i18nMessage.length > 0) {
763
- scheduleRefresh();
886
+ if (!loaded) {
887
+ return;
888
+ }
889
+ if (batch.i18nMessage.length === 0) {
890
+ return;
764
891
  }
892
+ const deleted = [];
893
+ const upserted = /* @__PURE__ */ new Set();
894
+ for (const event of batch.i18nMessage) {
895
+ if (event.mutation === "delete") {
896
+ deleted.push(event.id);
897
+ } else {
898
+ upserted.add(event.id);
899
+ }
900
+ }
901
+ if (deleted.length > 0) {
902
+ projected.delete(deleted);
903
+ }
904
+ runPartialRefresh([...upserted], deleted);
765
905
  });
766
906
  return {
767
- refresh$,
907
+ refresh$: channel.stream$,
768
908
  get(idOrIds) {
769
909
  return projected.get(idOrIds);
770
910
  },
@@ -776,24 +916,156 @@ function createI18nMessagesCollection(def, client, updates$) {
776
916
  `i18n-register:${def.collection}`,
777
917
  () => client.execute(storeRegisterI18nMessagesDocument, {
778
918
  collection: def.collection,
779
- messages: messages.map(toGqlMessageInput)
919
+ messages: messages.map((message) => toGqlMessageInput(message))
780
920
  }).then(() => {
781
921
  })
782
922
  );
783
923
  },
924
+ refresh() {
925
+ scheduleRefresh("on-demand");
926
+ },
784
927
  destroy() {
785
928
  unsubUpdates();
786
- refresh$.complete();
929
+ ttl.clear();
930
+ channel.complete();
931
+ }
932
+ };
933
+ }
934
+
935
+ // src/lazy-assets.ts
936
+ import {
937
+ collectAsync as collectAsync4,
938
+ createSourceSubscription as createSourceSubscription4,
939
+ mapAsync as mapAsync4
940
+ } from "@contello/client";
941
+ import { ProjectedLazyMap } from "projected";
942
+
943
+ // src/lru.ts
944
+ import { LRUCache } from "lru-cache";
945
+ function createLruCache(options) {
946
+ const { max, ttl, onEvict: dispose } = options;
947
+ const lru = new LRUCache({
948
+ max,
949
+ ...ttl !== void 0 && { ttl, ttlAutopurge: false },
950
+ ...dispose !== void 0 && { dispose }
951
+ });
952
+ return {
953
+ has: (key) => lru.has(key),
954
+ get: (key) => lru.get(key),
955
+ set: (key, value) => {
956
+ lru.set(key, value);
957
+ },
958
+ delete: (key) => {
959
+ lru.delete(key);
960
+ },
961
+ clear: () => {
962
+ lru.clear();
963
+ },
964
+ keys: () => [...lru.keys()]
965
+ };
966
+ }
967
+
968
+ // src/lazy-assets.ts
969
+ function mapFile2(raw) {
970
+ return {
971
+ uid: raw.uid,
972
+ mimeType: raw.mimeType,
973
+ metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
974
+ };
975
+ }
976
+ function mapAsset2(raw) {
977
+ return {
978
+ id: raw.id,
979
+ original: mapFile2(raw.original),
980
+ preview: raw.preview ? mapFile2(raw.preview) : void 0,
981
+ optimized: raw.optimized.map((file) => mapFile2(file))
982
+ };
983
+ }
984
+ function createLazyAssetsCollection(def, client, updates$) {
985
+ const _def = {
986
+ cache: {
987
+ max: def?.cache?.max ?? DEFAULT_LRU_MAX,
988
+ ttl: resolveTtl(def?.cache?.ttl)
989
+ }
990
+ };
991
+ const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
992
+ const assetsSourceDoc = createSourceSubscription4(schema.sources.storeAsset);
993
+ const projected = new ProjectedLazyMap({
994
+ key: (asset) => asset.id,
995
+ values: (ids) => wrap(
996
+ "assets",
997
+ () => collectAsync4(
998
+ mapAsync4(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
999
+ ).then((rawItems) => rawItems.map((item) => mapAsset2(item)))
1000
+ ),
1001
+ cache
1002
+ });
1003
+ const channel = createRefreshChannel(def?.onRefresh);
1004
+ function emit(ids, kind) {
1005
+ channel.emit({ ids, kind });
1006
+ }
1007
+ let lastRefreshKeys = [];
1008
+ const scheduleRefresh = createRefresher(
1009
+ async () => {
1010
+ lastRefreshKeys = cache.keys();
1011
+ if (lastRefreshKeys.length === 0) {
1012
+ return;
1013
+ }
1014
+ await projected.refresh(lastRefreshKeys);
1015
+ },
1016
+ (kind) => {
1017
+ if (lastRefreshKeys.length > 0) {
1018
+ emit(lastRefreshKeys, kind);
1019
+ }
1020
+ },
1021
+ () => {
1022
+ }
1023
+ );
1024
+ const unsubUpdates = updates$.subscribe((batch) => {
1025
+ if (batch.asset.length === 0) return;
1026
+ for (const event of batch.asset) {
1027
+ projected.delete(event.id);
1028
+ }
1029
+ emit(
1030
+ batch.asset.map((e) => e.id),
1031
+ "upstream-update"
1032
+ );
1033
+ });
1034
+ return {
1035
+ instance: {
1036
+ refresh$: channel.stream$,
1037
+ get(idOrIds) {
1038
+ return projected.get(idOrIds);
1039
+ },
1040
+ upload(data, meta, options) {
1041
+ return client.upload(data, meta, options);
1042
+ },
1043
+ download(fileId) {
1044
+ return client.download(fileId);
1045
+ },
1046
+ proxyHls(path, signal) {
1047
+ return client.proxyHls(path, signal);
1048
+ },
1049
+ refresh() {
1050
+ scheduleRefresh("on-demand");
1051
+ },
1052
+ clear() {
1053
+ projected.clear();
1054
+ }
1055
+ },
1056
+ destroy() {
1057
+ unsubUpdates();
1058
+ channel.complete();
787
1059
  }
788
1060
  };
789
1061
  }
790
1062
 
791
1063
  // src/lazy-collection.ts
792
1064
  import {
793
- collectAsync as collectAsync3,
794
- createAsyncIterableSubject as createAsyncIterableSubject4,
795
- createSourceSubscription as createSourceSubscription2,
796
- mapAsync as mapAsync3
1065
+ collectAsync as collectAsync5,
1066
+ createAsyncIterableSubject as createAsyncIterableSubject2,
1067
+ createSourceSubscription as createSourceSubscription5,
1068
+ mapAsync as mapAsync5
797
1069
  } from "@contello/client";
798
1070
  import { ProjectedLazyMap as ProjectedLazyMap2, maybeThen as maybeThen3 } from "projected";
799
1071
  function createLazyCollection(source, options, client, updates$, resolver) {
@@ -803,8 +1075,8 @@ function createLazyCollection(source, options, client, updates$, resolver) {
803
1075
  name: opts.name ?? source.__model,
804
1076
  model: source.__model,
805
1077
  cache: {
806
- max: opts.cache?.max ?? 1e3,
807
- ttl: opts.cache?.ttl
1078
+ max: opts.cache?.max ?? DEFAULT_LRU_MAX,
1079
+ ttl: resolveTtl(opts.cache?.ttl)
808
1080
  }
809
1081
  };
810
1082
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
@@ -818,9 +1090,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
818
1090
  values: (keys) => wrap(
819
1091
  `lazy-collection:${_def.name}`,
820
1092
  () => maybeThen3(
821
- collectAsync3(
822
- mapAsync3(
823
- client.subscribe(createSourceSubscription2(source), {
1093
+ collectAsync5(
1094
+ mapAsync5(
1095
+ client.subscribe(createSourceSubscription5(source), {
824
1096
  ids: keys
825
1097
  }),
826
1098
  (r) => r.source
@@ -828,11 +1100,13 @@ function createLazyCollection(source, options, client, updates$, resolver) {
828
1100
  ),
829
1101
  (rawItems) => Promise.all(
830
1102
  rawItems.map(
831
- (item) => dependencyCollector.createContext(
832
- (ref, register) => maybeThen3(mapFn(item, ref), (mapped) => {
833
- register(mapped.id);
834
- return mapped;
835
- })
1103
+ (item) => Promise.resolve(
1104
+ dependencyCollector.createContext(
1105
+ (ref, register) => maybeThen3(mapFn(item, ref), (mapped) => {
1106
+ register(mapped.id);
1107
+ return mapped;
1108
+ })
1109
+ )
836
1110
  )
837
1111
  )
838
1112
  )
@@ -840,7 +1114,12 @@ function createLazyCollection(source, options, client, updates$, resolver) {
840
1114
  ),
841
1115
  cache
842
1116
  });
843
- const refresh$ = createAsyncIterableSubject4();
1117
+ const refresh$ = createAsyncIterableSubject2();
1118
+ function emit(ids, kind) {
1119
+ const event = { ids, kind };
1120
+ refresh$.next(event);
1121
+ opts.onRefresh?.(event);
1122
+ }
844
1123
  let lastRefreshKeys = [];
845
1124
  const scheduleRefresh = createRefresher(
846
1125
  async () => {
@@ -850,10 +1129,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
850
1129
  }
851
1130
  await projected.refresh(lastRefreshKeys);
852
1131
  },
853
- () => {
1132
+ (kind) => {
854
1133
  if (lastRefreshKeys.length > 0) {
855
- refresh$.next(lastRefreshKeys);
856
- opts.onRefresh?.(lastRefreshKeys);
1134
+ emit(lastRefreshKeys, kind);
857
1135
  }
858
1136
  },
859
1137
  () => {
@@ -877,12 +1155,9 @@ function createLazyCollection(source, options, client, updates$, resolver) {
877
1155
  dependencyCollector.removeItem(key);
878
1156
  projected.delete(key);
879
1157
  }
880
- const ids = [...evicted];
881
- refresh$.next(ids);
882
- opts.onRefresh?.(ids);
1158
+ emit([...evicted], "upstream-update");
883
1159
  }
884
1160
  });
885
- void scheduleRefresh;
886
1161
  return {
887
1162
  instance: {
888
1163
  name: _def.name,
@@ -891,7 +1166,7 @@ function createLazyCollection(source, options, client, updates$, resolver) {
891
1166
  return projected.get(idOrIds);
892
1167
  },
893
1168
  refresh() {
894
- scheduleRefresh();
1169
+ scheduleRefresh("on-demand");
895
1170
  },
896
1171
  clear() {
897
1172
  dependencyCollector.clear();
@@ -905,46 +1180,12 @@ function createLazyCollection(source, options, client, updates$, resolver) {
905
1180
  };
906
1181
  }
907
1182
 
908
- // src/model-resolver.ts
909
- var ModelResolver = class {
910
- _typeNames;
911
- _toModel;
912
- _toTypeName;
913
- constructor(models) {
914
- const toModel = /* @__PURE__ */ new Map();
915
- const toTypeName = /* @__PURE__ */ new Map();
916
- let typeNames;
917
- if (models) {
918
- typeNames = /* @__PURE__ */ new Set();
919
- for (const [model, typeName] of Object.entries(models)) {
920
- toModel.set(typeName, model);
921
- toTypeName.set(model, typeName);
922
- typeNames.add(typeName);
923
- }
924
- }
925
- this._typeNames = typeNames;
926
- this._toModel = toModel;
927
- this._toTypeName = toTypeName;
928
- }
929
- hasTypeName(typeName) {
930
- return !this._typeNames || this._typeNames.has(typeName);
931
- }
932
- getModel(typeName) {
933
- return this._toModel.get(typeName);
934
- }
935
- getTypeName(model) {
936
- return this._toTypeName.get(model) ?? model;
937
- }
938
- hasModel(model) {
939
- return !this._toTypeName.size || this._toTypeName.has(model);
940
- }
941
- resolveModel(typeName) {
942
- return this._toModel.get(typeName) ?? typeName;
943
- }
944
- };
945
-
946
- // src/routes.ts
947
- import { createAsyncIterableSubject as createAsyncIterableSubject5 } from "@contello/client";
1183
+ // src/lazy-routes.ts
1184
+ import {
1185
+ collectAsync as collectAsync6,
1186
+ createSourceSubscription as createSourceSubscription6,
1187
+ mapAsync as mapAsync6
1188
+ } from "@contello/client";
948
1189
  import { ProjectedLazyMap as ProjectedLazyMap3 } from "projected";
949
1190
 
950
1191
  // src/routes-mapping.ts
@@ -955,21 +1196,23 @@ function mapRoute(raw, resolver) {
955
1196
  customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value }))
956
1197
  };
957
1198
  switch (raw.target.__typename) {
958
- case "ContelloRouteTargetRedirect":
1199
+ case "ContelloRouteTargetRedirect": {
959
1200
  return {
960
1201
  ...base,
961
1202
  type: "redirect",
962
1203
  location: raw.target.location,
963
1204
  status: raw.target.responseCode
964
1205
  };
965
- case "ContelloRouteTargetText":
1206
+ }
1207
+ case "ContelloRouteTargetText": {
966
1208
  return {
967
1209
  ...base,
968
1210
  type: "text",
969
1211
  content: raw.target.content,
970
1212
  mimeType: raw.target.mimeType
971
1213
  };
972
- case "ContelloRouteTargetAsset":
1214
+ }
1215
+ case "ContelloRouteTargetAsset": {
973
1216
  return {
974
1217
  ...base,
975
1218
  type: "asset",
@@ -978,6 +1221,7 @@ function mapRoute(raw, resolver) {
978
1221
  contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
979
1222
  mimeType: raw.target.asset.original.mimeType
980
1223
  };
1224
+ }
981
1225
  case "ContelloRouteTargetEntity": {
982
1226
  if (!raw.target.entity) {
983
1227
  return void 0;
@@ -991,20 +1235,18 @@ function mapRoute(raw, resolver) {
991
1235
  entityId: raw.target.entity.id
992
1236
  };
993
1237
  }
994
- default:
1238
+ default: {
995
1239
  return void 0;
1240
+ }
996
1241
  }
997
1242
  }
998
1243
 
999
- // src/routes.ts
1244
+ // src/lazy-routes.ts
1000
1245
  var ID_PREFIX = "1\0";
1001
1246
  var PATH_PREFIX = "2\0";
1002
1247
  var CACHE_KEY = /* @__PURE__ */ Symbol("cacheKey");
1003
- function collectRoutes(data, keyFn, resolver) {
1004
- return (data.contelloRoutes ?? []).reduce((acc, raw) => {
1005
- if (!raw) {
1006
- return acc;
1007
- }
1248
+ function collectRoutes(rawItems, keyFn, resolver) {
1249
+ return rawItems.reduce((acc, raw) => {
1008
1250
  const mapped = mapRoute(raw, resolver);
1009
1251
  if (mapped) {
1010
1252
  mapped[CACHE_KEY] = keyFn(mapped);
@@ -1054,14 +1296,20 @@ function createRoutesCache(max, ttl) {
1054
1296
  keys: () => lru.keys()
1055
1297
  };
1056
1298
  }
1057
- function createRoutesCollection(def, client, updates$, resolver) {
1299
+ function createLazyRoutesCollection(def, client, updates$, resolver) {
1058
1300
  const _def = {
1059
1301
  cache: {
1060
- max: def?.cache?.max ?? 1e3,
1061
- ttl: def?.cache?.ttl
1302
+ max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1303
+ ttl: resolveTtl(def?.cache?.ttl)
1062
1304
  }
1063
1305
  };
1064
1306
  const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1307
+ const routesSourceDoc = createSourceSubscription6(schema.sources.storeRoute);
1308
+ function fetchRoutes(vars) {
1309
+ return collectAsync6(
1310
+ mapAsync6(client.subscribe(routesSourceDoc, vars), (data) => data.source)
1311
+ );
1312
+ }
1065
1313
  const projected = new ProjectedLazyMap3({
1066
1314
  key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1067
1315
  values: (prefixedKeys) => wrap("routes", () => {
@@ -1076,13 +1324,16 @@ function createRoutesCollection(def, client, updates$, resolver) {
1076
1324
  }
1077
1325
  }
1078
1326
  return Promise.all([
1079
- ids.length > 0 ? client.execute(storeGetRoutesDocument, { request: { ids } }).then((data) => collectRoutes(data, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1080
- 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([])
1081
1329
  ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1082
1330
  }),
1083
1331
  cache
1084
1332
  });
1085
- const refresh$ = createAsyncIterableSubject5();
1333
+ const channel = createRefreshChannel(def?.onRefresh);
1334
+ function emit(ids, kind) {
1335
+ channel.emit({ ids, kind });
1336
+ }
1086
1337
  let lastRefreshKeys = [];
1087
1338
  const scheduleRefresh = createRefresher(
1088
1339
  async () => {
@@ -1092,9 +1343,12 @@ function createRoutesCollection(def, client, updates$, resolver) {
1092
1343
  }
1093
1344
  await projected.refresh(lastRefreshKeys);
1094
1345
  },
1095
- () => {
1346
+ (kind) => {
1096
1347
  if (lastRefreshKeys.length > 0) {
1097
- refresh$.next(lastRefreshKeys.map((key) => key.slice(2)));
1348
+ emit(
1349
+ lastRefreshKeys.map((key) => key.slice(2)),
1350
+ kind
1351
+ );
1098
1352
  }
1099
1353
  },
1100
1354
  () => {
@@ -1115,12 +1369,12 @@ function createRoutesCollection(def, client, updates$, resolver) {
1115
1369
  }
1116
1370
  }
1117
1371
  if (evicted.length > 0) {
1118
- refresh$.next(evicted);
1372
+ emit(evicted, "upstream-update");
1119
1373
  }
1120
1374
  });
1121
1375
  return {
1122
1376
  instance: {
1123
- refresh$,
1377
+ refresh$: channel.stream$,
1124
1378
  get(idOrIds) {
1125
1379
  if (Array.isArray(idOrIds)) {
1126
1380
  return projected.get(idOrIds.map((id) => ID_PREFIX + id));
@@ -1134,7 +1388,7 @@ function createRoutesCollection(def, client, updates$, resolver) {
1134
1388
  return projected.get(PATH_PREFIX + pathOrPaths);
1135
1389
  },
1136
1390
  refresh() {
1137
- scheduleRefresh();
1391
+ scheduleRefresh("on-demand");
1138
1392
  },
1139
1393
  clear() {
1140
1394
  projected.clear();
@@ -1142,65 +1396,322 @@ function createRoutesCollection(def, client, updates$, resolver) {
1142
1396
  },
1143
1397
  destroy() {
1144
1398
  unsubUpdates();
1145
- 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 === 0 || this._toTypeName.has(model);
1436
+ }
1437
+ resolveModel(typeName) {
1438
+ return this._toModel.get(typeName) ?? typeName;
1439
+ }
1440
+ };
1441
+
1442
+ // src/routes.ts
1443
+ import {
1444
+ collectAsync as collectAsync7,
1445
+ createSourceSubscription as createSourceSubscription7,
1446
+ mapAsync as mapAsync7,
1447
+ runWithBackoff as runWithBackoff5
1448
+ } from "@contello/client";
1449
+ import { ProjectedMap as ProjectedMap4, maybeThen as maybeThen4 } from "projected";
1450
+ function createRoutesCollection(options, client, updates$, resolver, refreshByTtl) {
1451
+ const opts = options ?? {};
1452
+ const cache = {
1453
+ ttl: resolveTtl(opts.cache?.ttl),
1454
+ eviction: opts.cache?.eviction ?? "refresh"
1455
+ };
1456
+ const channel = createRefreshChannel(opts.onRefresh);
1457
+ const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
1458
+ const pathById = /* @__PURE__ */ new Map();
1459
+ const idByPath = /* @__PURE__ */ new Map();
1460
+ let loaded = false;
1461
+ const routesSourceDoc = createSourceSubscription7(schema.sources.storeRoute);
1462
+ const projected = new ProjectedMap4({
1463
+ key: (route) => route.id,
1464
+ values: (ids) => wrap(
1465
+ "routes",
1466
+ () => collectAsync7(
1467
+ mapAsync7(client.subscribe(routesSourceDoc, { ids }), (data) => data.source)
1468
+ ).then((rawItems) => {
1469
+ const items = rawItems.reduce((acc, raw) => {
1470
+ const mapped = mapRoute(raw, resolver);
1471
+ if (mapped) {
1472
+ acc.push(mapped);
1473
+ }
1474
+ return acc;
1475
+ }, []);
1476
+ if (ids === void 0) {
1477
+ pathById.clear();
1478
+ idByPath.clear();
1479
+ for (const r of items) {
1480
+ pathById.set(r.id, r.path);
1481
+ idByPath.set(r.path, r.id);
1482
+ }
1483
+ if (!loaded) {
1484
+ loaded = true;
1485
+ ttl.mark();
1486
+ opts.onLoad?.(items.map((r) => r.id));
1487
+ }
1488
+ } else {
1489
+ const returnedIds = new Set(items.map((r) => r.id));
1490
+ for (const id of ids) {
1491
+ if (!returnedIds.has(id)) {
1492
+ const oldPath = pathById.get(id);
1493
+ if (oldPath !== void 0) {
1494
+ idByPath.delete(oldPath);
1495
+ pathById.delete(id);
1496
+ }
1497
+ }
1498
+ }
1499
+ for (const r of items) {
1500
+ const oldPath = pathById.get(r.id);
1501
+ if (oldPath !== void 0 && oldPath !== r.path) {
1502
+ idByPath.delete(oldPath);
1503
+ }
1504
+ pathById.set(r.id, r.path);
1505
+ idByPath.set(r.path, r.id);
1506
+ }
1507
+ }
1508
+ return items;
1509
+ })
1510
+ )
1511
+ });
1512
+ function emit(ids, kind) {
1513
+ channel.emit({ ids, kind });
1514
+ }
1515
+ function runFullRefresh(kind) {
1516
+ refreshByTtl.enqueue(
1517
+ () => runWithBackoff5(
1518
+ () => projected.refresh().then((map) => {
1519
+ emit([...map.keys()], kind);
1520
+ ttl.mark();
1521
+ })
1522
+ )
1523
+ );
1524
+ }
1525
+ function runPartialRefresh(refreshIds, deletedIds) {
1526
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1527
+ if (refreshIds.length === 0) {
1528
+ emit(changedIds, "upstream-update");
1529
+ return;
1530
+ }
1531
+ void runWithBackoff5(
1532
+ () => projected.refresh(refreshIds).then(() => {
1533
+ emit(changedIds, "upstream-update");
1534
+ })
1535
+ );
1536
+ }
1537
+ const unsubUpdates = updates$.subscribe((batch) => {
1538
+ if (!loaded || batch.route.length === 0) {
1539
+ return;
1540
+ }
1541
+ const deleted = [];
1542
+ const upserted = /* @__PURE__ */ new Set();
1543
+ for (const event of batch.route) {
1544
+ if (event.mutation === "delete") {
1545
+ deleted.push(event.id);
1546
+ } else {
1547
+ upserted.add(event.id);
1548
+ }
1549
+ }
1550
+ if (cache.eviction === "clear") {
1551
+ pathById.clear();
1552
+ idByPath.clear();
1553
+ projected.clear();
1554
+ return;
1555
+ }
1556
+ for (const id of deleted) {
1557
+ const oldPath = pathById.get(id);
1558
+ if (oldPath !== void 0) {
1559
+ idByPath.delete(oldPath);
1560
+ pathById.delete(id);
1561
+ }
1562
+ }
1563
+ if (deleted.length > 0) {
1564
+ projected.delete(deleted);
1565
+ }
1566
+ runPartialRefresh([...upserted], deleted);
1567
+ });
1568
+ function getByIdSingle(id) {
1569
+ return projected.get(id);
1570
+ }
1571
+ function getByIds(ids) {
1572
+ return projected.get(ids);
1573
+ }
1574
+ function lookupByPathSingle(path) {
1575
+ return maybeThen4(ensureLoaded(), () => {
1576
+ const id = idByPath.get(path);
1577
+ return id === void 0 ? void 0 : projected.get(id);
1578
+ });
1579
+ }
1580
+ function lookupByPaths(paths) {
1581
+ return maybeThen4(ensureLoaded(), () => {
1582
+ const ids = [];
1583
+ for (const p of paths) {
1584
+ const id = idByPath.get(p);
1585
+ if (id !== void 0) {
1586
+ ids.push(id);
1587
+ }
1588
+ }
1589
+ return projected.get(ids);
1590
+ });
1591
+ }
1592
+ function ensureLoaded() {
1593
+ if (loaded) {
1594
+ return void 0;
1595
+ }
1596
+ return maybeThen4(projected.getAllAsMap(), () => {
1597
+ });
1598
+ }
1599
+ const instance = {
1600
+ refresh$: channel.stream$,
1601
+ async load() {
1602
+ if (!loaded) {
1603
+ await projected.getAllAsMap();
1604
+ }
1605
+ },
1606
+ get(idOrIds) {
1607
+ return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1608
+ },
1609
+ getByPath(pathOrPaths) {
1610
+ return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1611
+ },
1612
+ refresh() {
1613
+ runFullRefresh("on-demand");
1614
+ }
1615
+ };
1616
+ return {
1617
+ instance,
1618
+ destroy() {
1619
+ unsubUpdates();
1620
+ ttl.clear();
1621
+ channel.complete();
1146
1622
  }
1147
1623
  };
1148
1624
  }
1625
+ function createRoutesSyncCollection(options, client, updates$, resolver, refreshByTtl) {
1626
+ const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1627
+ function assertSync(value, method) {
1628
+ if (value instanceof Promise) {
1629
+ throw new TypeError(`routes.${method}() is not initialized yet \u2014 call routes.load() first`);
1630
+ }
1631
+ return value;
1632
+ }
1633
+ return {
1634
+ instance: {
1635
+ ...base,
1636
+ get(idOrIds) {
1637
+ return assertSync(base.get(idOrIds), "get");
1638
+ },
1639
+ getByPath(pathOrPaths) {
1640
+ return assertSync(base.getByPath(pathOrPaths), "getByPath");
1641
+ }
1642
+ },
1643
+ destroy
1644
+ };
1645
+ }
1149
1646
 
1150
1647
  // src/singleton.ts
1151
1648
  import {
1152
- createAsyncIterableSubject as createAsyncIterableSubject6,
1153
- createSourceSubscription as createSourceSubscription3,
1649
+ createSourceSubscription as createSourceSubscription8,
1154
1650
  firstAsync,
1155
- mapAsync as mapAsync4
1651
+ mapAsync as mapAsync8,
1652
+ runWithBackoff as runWithBackoff6
1156
1653
  } from "@contello/client";
1157
- import { ProjectedValue, maybeThen as maybeThen4 } from "projected";
1158
- function createSingleton(source, options, client, updates$, resolver) {
1654
+ import { ProjectedValue, maybeThen as maybeThen5 } from "projected";
1655
+ function createSingleton(source, options, client, updates$, resolver, refreshByTtl) {
1159
1656
  const opts = options ?? {};
1160
1657
  const mapFn = opts.map ?? ((item) => item);
1161
1658
  const _def = {
1162
1659
  name: opts.name ?? source.__model,
1163
1660
  model: source.__model,
1164
1661
  cache: {
1165
- ttl: opts.cache?.ttl,
1662
+ ttl: resolveTtl(opts.cache?.ttl),
1166
1663
  eviction: opts.cache?.eviction ?? "refresh"
1167
1664
  }
1168
1665
  };
1169
1666
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
1170
1667
  const itemKey = `singleton:${_def.name}`;
1171
- let timer;
1668
+ const channel = createRefreshChannel(opts.onRefresh);
1669
+ const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });
1670
+ let loaded = false;
1172
1671
  const projected = new ProjectedValue({
1173
1672
  value: () => wrap(
1174
1673
  `singleton:${_def.name}`,
1175
- () => maybeThen4(
1674
+ () => maybeThen5(
1176
1675
  firstAsync(
1177
- mapAsync4(
1178
- client.subscribe(createSourceSubscription3(source)),
1676
+ mapAsync8(
1677
+ client.subscribe(createSourceSubscription8(source)),
1179
1678
  (r) => r.source
1180
1679
  )
1181
1680
  ),
1182
1681
  (raw) => dependencyCollector.createContext(
1183
- (ref, register) => maybeThen4(mapFn(raw, ref), (mapped) => {
1682
+ (ref, register) => maybeThen5(mapFn(raw, ref), (mapped) => {
1184
1683
  register(itemKey);
1684
+ if (!loaded) {
1685
+ loaded = true;
1686
+ ttl.mark();
1687
+ opts.onLoad?.();
1688
+ }
1185
1689
  return mapped;
1186
1690
  })
1187
1691
  )
1188
1692
  )
1189
1693
  )
1190
1694
  });
1191
- const refresh$ = createAsyncIterableSubject6();
1695
+ function emit(kind) {
1696
+ channel.emit({ kind });
1697
+ }
1698
+ function runTtlRefresh() {
1699
+ refreshByTtl.enqueue(
1700
+ () => runWithBackoff6(() => projected.refresh()).then(() => {
1701
+ emit("ttl");
1702
+ ttl.mark();
1703
+ })
1704
+ );
1705
+ }
1192
1706
  const scheduleRefresh = createRefresher(
1193
1707
  () => projected.refresh(),
1194
- () => {
1195
- refresh$.next();
1196
- opts.onRefresh?.();
1197
- if (_def.cache.ttl !== void 0) {
1198
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1199
- }
1708
+ (kind) => {
1709
+ emit(kind);
1710
+ ttl.mark();
1200
1711
  },
1201
- () => clearTimeout(timer)
1712
+ () => {
1713
+ }
1202
1714
  );
1203
- let loaded = false;
1204
1715
  const unsubUpdates = updates$.subscribe((batch) => {
1205
1716
  if (!loaded) {
1206
1717
  return;
@@ -1215,41 +1726,39 @@ function createSingleton(source, options, client, updates$, resolver) {
1215
1726
  projected.clear();
1216
1727
  return;
1217
1728
  }
1218
- scheduleRefresh();
1729
+ scheduleRefresh("upstream-update");
1219
1730
  });
1220
1731
  return {
1221
1732
  instance: {
1222
1733
  name: _def.name,
1223
- refresh$,
1734
+ refresh$: channel.stream$,
1224
1735
  get() {
1225
1736
  return projected.get();
1226
1737
  },
1227
1738
  refresh() {
1228
- scheduleRefresh();
1739
+ scheduleRefresh("on-demand");
1229
1740
  },
1230
1741
  async load() {
1231
- await projected.get();
1232
- loaded = true;
1233
- if (_def.cache.ttl !== void 0) {
1234
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1742
+ if (!loaded) {
1743
+ await projected.get();
1235
1744
  }
1236
- opts.onLoad?.();
1237
1745
  }
1238
1746
  },
1239
1747
  destroy() {
1240
1748
  unsubUpdates();
1241
- clearTimeout(timer);
1242
- refresh$.complete();
1749
+ ttl.clear();
1750
+ channel.complete();
1243
1751
  }
1244
1752
  };
1245
1753
  }
1246
- function createSingletonSync(source, options, client, updates$, resolver) {
1754
+ function createSingletonSync(source, options, client, updates$, resolver, refreshByTtl) {
1247
1755
  const { instance: base, destroy } = createSingleton(
1248
1756
  source,
1249
1757
  options,
1250
1758
  client,
1251
1759
  updates$,
1252
- resolver
1760
+ resolver,
1761
+ refreshByTtl
1253
1762
  );
1254
1763
  return {
1255
1764
  instance: {
@@ -1257,7 +1766,7 @@ function createSingletonSync(source, options, client, updates$, resolver) {
1257
1766
  get() {
1258
1767
  const result = base.get();
1259
1768
  if (result instanceof Promise) {
1260
- throw new Error(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1769
+ throw new TypeError(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1261
1770
  }
1262
1771
  return result;
1263
1772
  }
@@ -1269,8 +1778,8 @@ function createSingletonSync(source, options, client, updates$, resolver) {
1269
1778
  // src/watcher.ts
1270
1779
  import {
1271
1780
  asyncKeepalive,
1272
- createAsyncIterableSubject as createAsyncIterableSubject7,
1273
- mapAsync as mapAsync5
1781
+ createAsyncIterableSubject as createAsyncIterableSubject3,
1782
+ mapAsync as mapAsync9
1274
1783
  } from "@contello/client";
1275
1784
  function addRouteByModel(map, entityType, event) {
1276
1785
  let list = map.get(entityType);
@@ -1288,7 +1797,7 @@ function createUpdateBatch(events) {
1288
1797
  const routeByEntityModel = /* @__PURE__ */ new Map();
1289
1798
  for (const event of events) {
1290
1799
  switch (event.target) {
1291
- case "route":
1800
+ case "route": {
1292
1801
  route.push(event);
1293
1802
  if ("after" in event && event.after.type === "entity") {
1294
1803
  addRouteByModel(routeByEntityModel, event.after.model, event);
@@ -1297,12 +1806,15 @@ function createUpdateBatch(events) {
1297
1806
  addRouteByModel(routeByEntityModel, event.before.model, event);
1298
1807
  }
1299
1808
  break;
1300
- case "asset":
1809
+ }
1810
+ case "asset": {
1301
1811
  asset.push(event);
1302
1812
  break;
1303
- case "i18nMessage":
1813
+ }
1814
+ case "i18nMessage": {
1304
1815
  i18nMessage.push(event);
1305
1816
  break;
1817
+ }
1306
1818
  case "entity": {
1307
1819
  let list = entity.get(event.model);
1308
1820
  if (!list) {
@@ -1318,12 +1830,15 @@ function createUpdateBatch(events) {
1318
1830
  }
1319
1831
  function castMutationType(type) {
1320
1832
  switch (type) {
1321
- case "CREATE":
1833
+ case "CREATE": {
1322
1834
  return "create";
1323
- case "UPDATE":
1835
+ }
1836
+ case "UPDATE": {
1324
1837
  return "update";
1325
- case "DELETE":
1838
+ }
1839
+ case "DELETE": {
1326
1840
  return "delete";
1841
+ }
1327
1842
  }
1328
1843
  }
1329
1844
  function mapEvent(raw, resolver) {
@@ -1348,10 +1863,12 @@ function mapEvent(raw, resolver) {
1348
1863
  }
1349
1864
  return { id, mutation, target: "route", after, before };
1350
1865
  }
1351
- case "ContelloAsset":
1866
+ case "ContelloAsset": {
1352
1867
  return { id, mutation, target: "asset" };
1353
- case "ContelloI18nMessage":
1868
+ }
1869
+ case "ContelloI18nMessage": {
1354
1870
  return { id, mutation, target: "i18nMessage", token: target.token };
1871
+ }
1355
1872
  default: {
1356
1873
  if (!__typename || !resolver.hasTypeName(__typename)) {
1357
1874
  return void 0;
@@ -1361,7 +1878,7 @@ function mapEvent(raw, resolver) {
1361
1878
  }
1362
1879
  }
1363
1880
  function createInternalWatcher(client, resolver) {
1364
- const updates$ = createAsyncIterableSubject7();
1881
+ const updates$ = createAsyncIterableSubject3();
1365
1882
  let controller;
1366
1883
  return {
1367
1884
  updates$,
@@ -1377,7 +1894,7 @@ function createInternalWatcher(client, resolver) {
1377
1894
  () => client.subscribe(storeWatchUpdatesDocument),
1378
1895
  signal
1379
1896
  );
1380
- const events = mapAsync5(
1897
+ const events = mapAsync9(
1381
1898
  source,
1382
1899
  (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => mapEvent(e, resolver)).filter((e) => e !== void 0)
1383
1900
  );
@@ -1408,26 +1925,27 @@ var Store = class {
1408
1925
  _watcher;
1409
1926
  _schema;
1410
1927
  _cleanups = [];
1928
+ _refreshByTtl = createRefreshByTtlQueue();
1411
1929
  /**
1412
1930
  * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1413
1931
  * each iteration starts an independent fan-out from the shared source.
1414
1932
  */
1415
1933
  updates$;
1416
1934
  constructor(options) {
1417
- const { url, project, token, schema } = options;
1418
- this._schema = schema;
1935
+ const { url, project, token, schema: schema2 } = options;
1936
+ this._schema = schema2;
1419
1937
  this._client = createContelloClient({
1420
1938
  url,
1421
1939
  project,
1422
1940
  token,
1423
- schema,
1941
+ schema: schema2,
1424
1942
  connections: options.connections,
1425
1943
  onConnected: options.onConnected,
1426
1944
  onReconnecting: options.onReconnecting,
1427
1945
  onError: options.onError,
1428
1946
  connectionEvents: options.connectionEvents
1429
1947
  });
1430
- this._resolver = new ModelResolver(schema?.models);
1948
+ this._resolver = new ModelResolver(schema2?.models);
1431
1949
  this._watcher = createInternalWatcher(this._client, this._resolver);
1432
1950
  this.updates$ = this._watcher.updates$;
1433
1951
  this.ping = () => this._client.ping();
@@ -1469,7 +1987,8 @@ var Store = class {
1469
1987
  options,
1470
1988
  this._client,
1471
1989
  this._watcher.updates$,
1472
- this._resolver
1990
+ this._resolver,
1991
+ this._refreshByTtl
1473
1992
  );
1474
1993
  this._cleanups.push(destroy);
1475
1994
  return instance;
@@ -1481,7 +2000,8 @@ var Store = class {
1481
2000
  options,
1482
2001
  this._client,
1483
2002
  this._watcher.updates$,
1484
- this._resolver
2003
+ this._resolver,
2004
+ this._refreshByTtl
1485
2005
  );
1486
2006
  this._cleanups.push(destroy);
1487
2007
  return instance;
@@ -1494,7 +2014,8 @@ var Store = class {
1494
2014
  options,
1495
2015
  this._client,
1496
2016
  this._watcher.updates$,
1497
- this._resolver
2017
+ this._resolver,
2018
+ this._refreshByTtl
1498
2019
  );
1499
2020
  this._cleanups.push(destroy);
1500
2021
  return instance;
@@ -1506,7 +2027,8 @@ var Store = class {
1506
2027
  options,
1507
2028
  this._client,
1508
2029
  this._watcher.updates$,
1509
- this._resolver
2030
+ this._resolver,
2031
+ this._refreshByTtl
1510
2032
  );
1511
2033
  this._cleanups.push(destroy);
1512
2034
  return instance;
@@ -1525,18 +2047,67 @@ var Store = class {
1525
2047
  return instance;
1526
2048
  }
1527
2049
  // --- assets / routes / i18n (no source — built-ins) ---
2050
+ // --- assets ---
1528
2051
  defineAssets(options) {
1529
- const { instance, destroy } = createAssetsCollection(options, this._client, this._watcher.updates$);
2052
+ const { instance, destroy } = createAssetsCollection(
2053
+ options,
2054
+ this._client,
2055
+ this._watcher.updates$,
2056
+ this._refreshByTtl
2057
+ );
2058
+ this._cleanups.push(destroy);
2059
+ return instance;
2060
+ }
2061
+ defineAssetsSync(options) {
2062
+ const { instance, destroy } = createAssetsSyncCollection(
2063
+ options,
2064
+ this._client,
2065
+ this._watcher.updates$,
2066
+ this._refreshByTtl
2067
+ );
2068
+ this._cleanups.push(destroy);
2069
+ return instance;
2070
+ }
2071
+ defineLazyAssets(options) {
2072
+ const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
1530
2073
  this._cleanups.push(destroy);
1531
2074
  return instance;
1532
2075
  }
2076
+ // --- routes ---
1533
2077
  defineRoutes(options) {
1534
- const { instance, destroy } = createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
2078
+ const { instance, destroy } = createRoutesCollection(
2079
+ options,
2080
+ this._client,
2081
+ this._watcher.updates$,
2082
+ this._resolver,
2083
+ this._refreshByTtl
2084
+ );
2085
+ this._cleanups.push(destroy);
2086
+ return instance;
2087
+ }
2088
+ defineRoutesSync(options) {
2089
+ const { instance, destroy } = createRoutesSyncCollection(
2090
+ options,
2091
+ this._client,
2092
+ this._watcher.updates$,
2093
+ this._resolver,
2094
+ this._refreshByTtl
2095
+ );
2096
+ this._cleanups.push(destroy);
2097
+ return instance;
2098
+ }
2099
+ defineLazyRoutes(options) {
2100
+ const { instance, destroy } = createLazyRoutesCollection(
2101
+ options,
2102
+ this._client,
2103
+ this._watcher.updates$,
2104
+ this._resolver
2105
+ );
1535
2106
  this._cleanups.push(destroy);
1536
2107
  return instance;
1537
2108
  }
1538
2109
  defineI18nMessages(def) {
1539
- const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$);
2110
+ const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
1540
2111
  this._cleanups.push(result.destroy);
1541
2112
  return result;
1542
2113
  }
@@ -1547,10 +2118,10 @@ function createStore(options) {
1547
2118
  }
1548
2119
 
1549
2120
  // src/index.ts
1550
- import { maybeThen as maybeThen5, maybeCatch } from "projected";
2121
+ import { maybeThen as maybeThen6, maybeCatch } from "projected";
1551
2122
  export {
1552
2123
  Store,
1553
2124
  createStore,
1554
2125
  maybeCatch,
1555
- maybeThen5 as maybeThen
2126
+ maybeThen6 as maybeThen
1556
2127
  };