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