@contello/store 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["mapFile","mapAsset","storeSchema","maybeThen","storeSchema","storeSchema","maybeThen","storeSchema","storeSchema","maybeThen","maybeThen"],"sources":["../src/diagnostics.ts","../src/generated/graphql.ts","../src/utils.ts","../src/assets.ts","../src/dependency-collector.ts","../src/collection.ts","../src/i18n.ts","../src/lru.ts","../src/lazy-assets.ts","../src/lazy-collection.ts","../src/routes-mapping.ts","../src/lazy-routes.ts","../src/model-resolver.ts","../src/routes.ts","../src/singleton.ts","../src/watcher.ts","../src/store.ts"],"sourcesContent":["import dc from 'node:diagnostics_channel';\n\n// ---------------------------------------------------------------------------\n// channel names (exported for subscribers)\n// ---------------------------------------------------------------------------\n\nexport const channels = {\n start: '@contello/store:start',\n end: '@contello/store:end',\n error: '@contello/store:error',\n} as const;\n\n// ---------------------------------------------------------------------------\n// message types (exported for subscribers)\n// ---------------------------------------------------------------------------\n\nexport type OperationStartMessage = {\n name: string;\n};\n\nexport type OperationEndMessage = {\n name: string;\n cached: boolean;\n durationMs: number;\n};\n\nexport type OperationErrorMessage = {\n name: string;\n error: unknown;\n durationMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// internal channels\n// ---------------------------------------------------------------------------\n\nconst onStart = dc.channel(channels.start);\nconst onEnd = dc.channel(channels.end);\nconst onError = dc.channel(channels.error);\n\nfunction hasSubscribers(): boolean {\n return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;\n}\n\n// ---------------------------------------------------------------------------\n// wrap — internal, not exported from hooks entry point\n// ---------------------------------------------------------------------------\n\nexport function wrap<T>(name: string, fn: () => T): T {\n if (!hasSubscribers()) {\n return fn();\n }\n\n const start = performance.now();\n\n onStart.publish({ name } satisfies OperationStartMessage);\n\n let result: T;\n\n try {\n result = fn();\n } catch (error) {\n onError.publish({ name, error, durationMs: performance.now() - start } satisfies OperationErrorMessage);\n\n throw error;\n }\n\n if (result instanceof Promise) {\n return (async () => {\n try {\n const r = await result;\n\n onEnd.publish({ name, cached: false, durationMs: performance.now() - start } satisfies OperationEndMessage);\n\n return r;\n } catch (error) {\n onError.publish({ name, error, durationMs: performance.now() - start } satisfies OperationErrorMessage);\n\n throw error;\n }\n })() as T;\n }\n\n onEnd.publish({ name, cached: true, durationMs: performance.now() - start } satisfies OperationEndMessage);\n\n return result;\n}\n","/* eslint-disable */\n// @ts-nocheck\n/* this file is generated by contello-client — do not edit */\n\nimport type { SourceDef } from '@contello/client';\n\nexport type ContelloAssetKind = 'AUDIO' | 'DOCUMENT' | 'IMAGE' | 'OTHER' | 'VIDEO';\nexport type ContelloAssetRetentionPolicy = 'deleteIfNotUsed' | 'retain';\nexport type ContelloBatchOperationStatus = 'error' | 'success';\nexport type ContelloContentDispositionEnum = 'ATTACHMENT' | 'AUTOMATIC' | 'INLINE';\nexport type ContelloDictionaryType = 'ENTITY' | 'STATIC';\nexport type ContelloMutationType = 'CREATE' | 'DELETE' | 'UPDATE';\nexport type ContelloRouteTargetTypeEnum = 'ENTITY' | 'FILE' | 'REDIRECT' | 'TEXT_RESPONSE';\n\nexport type ContelloAnnotationFilterInput = {\n key?: string | undefined;\n value?: string | undefined;\n};\n\nexport type ContelloAssetAnnotationInput = {\n key: string;\n value: string;\n};\n\nexport type ContelloAssetRequestInput = {\n id?: string | undefined;\n};\n\nexport type ContelloAssetsFilterInput = {\n annotations?: (ContelloAnnotationFilterInput | undefined)[] | undefined;\n collectionReferences?: (string | undefined)[] | undefined;\n ids?: (string | undefined)[] | undefined;\n kinds?: (ContelloAssetKind | undefined)[] | undefined;\n};\n\nexport type ContelloAssetsPaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloAssetUpdateInput = {\n annotations?: ContelloAssetAnnotationInput[] | undefined;\n collectionIds?: string[] | undefined;\n collectionReferenceNames?: string[] | undefined;\n id: string;\n name?: string | undefined;\n retentionPolicy?: ContelloAssetRetentionPolicy | undefined;\n tags?: string[] | undefined;\n};\n\nexport type ContelloEntityRouteInput = {\n path: string;\n};\n\nexport type ContelloI18nMessageInput = {\n description?: string | undefined;\n example?: string | undefined;\n initialTranslations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n token: string;\n translations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n variables?: ContelloI18nMessageVariableInput[] | undefined;\n};\n\nexport type ContelloI18nMessagePaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloI18nMessageTranslationValueInput = {\n language: string;\n message: string;\n};\n\nexport type ContelloI18nMessageVariableInput = {\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloRouteHeaderInput = {\n name: string;\n value: string;\n};\n\nexport type ContelloRouteInput = {\n customHeaders?: (ContelloRouteHeaderInput | undefined)[] | undefined;\n path: string;\n targetEntityConfig?: TargetEntityConfigInput | undefined;\n targetFileConfig?: TargetFileConfig | undefined;\n targetRedirectConfig?: TargetRedirectConfig | undefined;\n targetTextResponseConfig?: TargetTextResponseConfig | undefined;\n targetType: ContelloRouteTargetTypeEnum;\n};\n\nexport type ContelloRouteRequestInput = {\n id?: string | undefined;\n path?: string | undefined;\n};\n\nexport type ContelloRoutesRequestInput = {\n ids?: (string | undefined)[] | undefined;\n paths?: (string | undefined)[] | undefined;\n targetType?: ContelloRouteTargetTypeEnum | undefined;\n};\n\nexport type CreateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id?: string | undefined;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type CreateDummyRequestInput = {\n entity: CreateDummyEntityInput;\n};\n\nexport type DateTimeFilterInput = {\n between?: DateTimeRangeInput | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n greaterThan?: string | undefined;\n greaterThanEqual?: string | undefined;\n lessThan?: string | undefined;\n lessThanEqual?: string | undefined;\n notEqual?: string | undefined;\n};\n\nexport type DateTimeRangeInput = {\n from: string;\n to: string;\n};\n\nexport type DeleteEntityByIdInput = {\n force?: boolean | undefined;\n id: string;\n};\n\nexport type DeleteEntityByIdsInput = {\n ids: string[];\n};\n\nexport type DummiesFilterInput = {\n created?: DateTimeFilterInput | undefined;\n ids?: (string | undefined)[] | undefined;\n name?: StringFilterInput | undefined;\n route?: StringFilterInput | undefined;\n updated?: DateTimeFilterInput | undefined;\n};\n\nexport type DummiesRequestInput = {\n filter?: DummiesFilterInput | undefined;\n pagination?: PaginationInput | undefined;\n};\n\nexport type DummyAttributesInput = {\n dummy?: string | undefined;\n};\n\nexport type GetEntityByIdInput = {\n id: string;\n};\n\nexport type PaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type StringFilterInput = {\n contains?: string | undefined;\n endsWith?: string | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n in?: string[] | undefined;\n notEqual?: string | undefined;\n notIn?: string[] | undefined;\n startsWith?: string | undefined;\n};\n\nexport type TargetEntityConfigInput = {\n entityId: string;\n entityModelId: string;\n};\n\nexport type TargetFileConfig = {\n assetId: string;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type TargetRedirectConfig = {\n location: string;\n responseCode: number;\n};\n\nexport type TargetTextResponseConfig = {\n content: string;\n mimeType: string;\n};\n\nexport type UpdateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id: string;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type UpdateDummyRequestInput = {\n entity: UpdateDummyEntityInput;\n};\n\nexport type ContelloAsset = {\n __typename?: 'ContelloAsset' | undefined;\n annotations: ContelloAssetAnnotation[];\n createdAt: string;\n id: string;\n optimized: ContelloOptimizedFile[];\n original: ContelloFile;\n preview?: ContelloFile | undefined;\n updatedAt: string;\n};\n\nexport type ContelloAssetAnnotation = {\n __typename?: 'ContelloAssetAnnotation' | undefined;\n key: string;\n value: string;\n};\n\nexport type ContelloAssetDeleteResponse = {\n __typename?: 'ContelloAssetDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloBatchOperationResponse = {\n __typename?: 'ContelloBatchOperationResponse' | undefined;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloDictionary = {\n __typename?: 'ContelloDictionary' | undefined;\n createdAt: string;\n description?: string | undefined;\n id: string;\n items?: (string | undefined)[] | undefined;\n name: string;\n referenceName: string;\n type: ContelloDictionaryType;\n updatedAt: string;\n};\n\nexport type ContelloEntityDeleteResponse = {\n __typename?: 'ContelloEntityDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloEntityModel = {\n __typename?: 'ContelloEntityModel' | undefined;\n description: string;\n id: string;\n isRoutable: boolean;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloI18nMessage = {\n __typename?: 'ContelloI18nMessage' | undefined;\n collectionId: string;\n createdAt: string;\n deprecated: boolean;\n description?: string | undefined;\n example?: string | undefined;\n id: string;\n token: string;\n translations: ContelloI18nMessageTranslation[];\n updatedAt: string;\n variables?: ContelloI18nMessageVariable[] | undefined;\n};\n\nexport type ContelloI18nMessagePagination = {\n __typename?: 'ContelloI18nMessagePagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type ContelloI18nMessageRegisterResponse = {\n __typename?: 'ContelloI18nMessageRegisterResponse' | undefined;\n ids: string[];\n};\n\nexport type ContelloI18nMessagesResponse = {\n __typename?: 'ContelloI18nMessagesResponse' | undefined;\n items: ContelloI18nMessage[];\n pagination: ContelloI18nMessagePagination;\n};\n\nexport type ContelloI18nMessageTranslation = {\n __typename?: 'ContelloI18nMessageTranslation' | undefined;\n language: string;\n value: string;\n};\n\nexport type ContelloI18nMessageUpdate = {\n __typename?: 'ContelloI18nMessageUpdate' | undefined;\n message: ContelloI18nMessage;\n mutation: ContelloMutation;\n};\n\nexport type ContelloI18nMessageVariable = {\n __typename?: 'ContelloI18nMessageVariable' | undefined;\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloImageMetadata = {\n __typename?: 'ContelloImageMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloImageOptimizationConfig = {\n __typename?: 'ContelloImageOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type ContelloMutation = {\n __typename?: 'ContelloMutation' | undefined;\n type: ContelloMutationType;\n};\n\nexport type ContelloOptimizedFile = {\n __typename?: 'ContelloOptimizedFile' | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n optimizationConfig?: ContelloOptimizationConfig | undefined;\n uid: string;\n};\n\nexport type ContelloProject = {\n __typename?: 'ContelloProject' | undefined;\n description: string;\n id: string;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloRoute = {\n __typename?: 'ContelloRoute' | undefined;\n createdAt: string;\n customHeaders: ContelloRouteHeader[];\n id: string;\n path: string;\n target: ContelloRouteTarget;\n updatedAt: string;\n};\n\nexport type ContelloRouteHeader = {\n __typename?: 'ContelloRouteHeader' | undefined;\n name: string;\n value: string;\n};\n\nexport type ContelloRouteTargetAsset = {\n __typename?: 'ContelloRouteTargetAsset' | undefined;\n asset: ContelloAsset;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type ContelloRouteTargetEntity = {\n __typename?: 'ContelloRouteTargetEntity' | undefined;\n entity?: ContelloEntityBase | undefined;\n};\n\nexport type ContelloRouteTargetRedirect = {\n __typename?: 'ContelloRouteTargetRedirect' | undefined;\n location: string;\n responseCode: number;\n};\n\nexport type ContelloRouteTargetText = {\n __typename?: 'ContelloRouteTargetText' | undefined;\n content: string;\n mimeType: string;\n};\n\nexport type ContelloRouteUpdate = {\n __typename?: 'ContelloRouteUpdate' | undefined;\n mutation: ContelloMutation;\n route: ContelloRoute;\n};\n\nexport type ContelloUpdateBatch = {\n __typename?: 'ContelloUpdateBatch' | undefined;\n events: ContelloUpdateEvent[];\n};\n\nexport type ContelloUpdateEvent = {\n __typename?: 'ContelloUpdateEvent' | undefined;\n mutation: ContelloMutation;\n prev?: ContelloUpdatePrev | undefined;\n target: ContelloUpdateTarget;\n};\n\nexport type ContelloVideoMetadata = {\n __typename?: 'ContelloVideoMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloVideoOptimizationConfig = {\n __typename?: 'ContelloVideoOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type DummiesResponseCollection = {\n __typename?: 'DummiesResponseCollection' | undefined;\n entities: DummyEntity[];\n pagination: Pagination;\n};\n\nexport type DummyAttributes = {\n __typename?: 'DummyAttributes' | undefined;\n dummy?: string | undefined;\n};\n\nexport type DummyEntity = {\n __typename?: 'DummyEntity' | undefined;\n __model?: 'dummy' | undefined;\n attributes: DummyAttributes;\n createdAt: string;\n id: string;\n internalName: string;\n modelId: string;\n routes: ContelloRoute[];\n updatedAt: string;\n};\n\nexport type DummyEntityUpdate = {\n __typename?: 'DummyEntityUpdate' | undefined;\n entity: DummyEntity;\n mutation: ContelloMutation;\n};\n\nexport type Pagination = {\n __typename?: 'Pagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type PingResult = {\n __typename?: 'PingResult' | undefined;\n response: string;\n};\n\nexport type RootMutation = {\n __typename?: 'RootMutation' | undefined;\n createContelloRoute?: ContelloRoute | undefined;\n createContelloRoutes?: ContelloRoute[] | undefined;\n createDummies?: DummyEntity[] | undefined;\n createDummy?: DummyEntity | undefined;\n deleteContelloAsset: ContelloAssetDeleteResponse;\n deleteContelloRoute: string;\n deleteDummies?: ContelloEntityDeleteResponse[] | undefined;\n deleteDummy: ContelloEntityDeleteResponse;\n registerContelloI18nMessages?: ContelloI18nMessageRegisterResponse | undefined;\n truncateContelloRoutes?: ContelloBatchOperationResponse | undefined;\n truncateDummies?: ContelloBatchOperationResponse | undefined;\n updateContelloAsset?: ContelloAsset | undefined;\n updateContelloRoute?: ContelloRoute | undefined;\n updateDummies?: DummyEntity[] | undefined;\n updateDummy?: DummyEntity | undefined;\n};\n\nexport type RootQuery = {\n __typename?: 'RootQuery' | undefined;\n contelloAsset?: ContelloAsset | undefined;\n contelloAssets?: (ContelloAsset | undefined)[] | undefined;\n contelloDictionaries?: (ContelloDictionary | undefined)[] | undefined;\n contelloEntityModels?: (ContelloEntityModel | undefined)[] | undefined;\n contelloI18nMessages?: ContelloI18nMessagesResponse | undefined;\n contelloPing: PingResult;\n contelloProject?: ContelloProject | undefined;\n contelloRoute?: ContelloRoute | undefined;\n contelloRoutes?: (ContelloRoute | undefined)[] | undefined;\n dummies: DummiesResponseCollection;\n dummy?: DummyEntity | undefined;\n};\n\nexport type RootSubscription = {\n __typename?: 'RootSubscription' | undefined;\n contelloAssets?: ContelloAsset | undefined;\n contelloAssetsBatch: ContelloAsset[];\n contelloI18nMessages?: ContelloI18nMessage | undefined;\n contelloI18nMessagesBatch: ContelloI18nMessage[];\n contelloI18nMessageUpdates?: ContelloI18nMessageUpdate | undefined;\n contelloRoutes?: ContelloRoute | undefined;\n contelloRoutesBatch: ContelloRoute[];\n contelloRouteUpdates?: ContelloRouteUpdate | undefined;\n contelloUpdates?: ContelloUpdateEvent | undefined;\n contelloUpdatesBatch?: ContelloUpdateBatch | undefined;\n dummies?: DummyEntity | undefined;\n dummiesBatch: DummyEntity[];\n dummyUpdates?: DummyEntityUpdate | undefined;\n};\n\nexport type ContelloEntityBase = {\n __typename?: string | undefined;\n createdAt: string;\n id: string;\n updatedAt: string;\n};\n\nexport type ContelloFile = {\n __typename?: string | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n uid: string;\n};\n\nexport type ContelloEntity = DummyEntity;\nexport type ContelloFileMetadata = ContelloImageMetadata | ContelloVideoMetadata;\nexport type ContelloOptimizationConfig = ContelloImageOptimizationConfig | ContelloVideoOptimizationConfig;\nexport type ContelloRouteTarget = ContelloRouteTargetAsset | ContelloRouteTargetEntity | ContelloRouteTargetRedirect | ContelloRouteTargetText;\nexport type ContelloUpdatePrev = ContelloRoute;\nexport type ContelloUpdateTarget = ContelloAsset | ContelloI18nMessage | ContelloRoute | DummyEntity;\n\nexport type MediaFileFragment = {\n uid: string;\n mimeType: string;\n metadata?: {\n __typename: 'ContelloImageMetadata';\n width: number;\n height: number;\n } | {\n __typename: 'ContelloVideoMetadata';\n width: number;\n height: number;\n } | undefined;\n};\n\nexport type MediaAssetFragment = {\n id: string;\n original: MediaFileFragment;\n preview?: MediaFileFragment | undefined;\n optimized: (MediaFileFragment & ({\n __typename: 'ContelloOptimizedFile';\n optimizationConfig?: {\n __typename: 'ContelloImageOptimizationConfig';\n name: string;\n } | undefined;\n }))[];\n};\n\nexport type StoreFileFragment = MediaFileFragment;\n\nexport type StoreAssetFragment = MediaAssetFragment;\n\nexport type StoreI18nMessageFragment = {\n id: string;\n token: string;\n description?: string | undefined;\n example?: string | undefined;\n translations: ({\n language: string;\n value: string;\n })[];\n};\n\nexport type StoreRouteFragment = {\n id: string;\n path: string;\n target: {\n __typename: 'ContelloRouteTargetEntity';\n entity?: {\n __typename: string;\n id: string;\n } | undefined;\n } | {\n __typename: 'ContelloRouteTargetAsset';\n asset: {\n id: string;\n original: {\n uid: string;\n mimeType: string;\n };\n };\n contentDisposition: ContelloContentDispositionEnum;\n } | {\n __typename: 'ContelloRouteTargetRedirect';\n location: string;\n responseCode: number;\n } | {\n __typename: 'ContelloRouteTargetText';\n content: string;\n mimeType: string;\n };\n customHeaders: ({\n name: string;\n value: string;\n })[];\n};\n\nexport type StoreRegisterI18nMessagesMutation = {\n registerContelloI18nMessages?: {\n ids: string[];\n } | undefined;\n};\n\nexport type StoreRegisterI18nMessagesMutationVariables = {\n collection: string;\n messages: ContelloI18nMessageInput[];\n};\n\nexport type StoreWatchUpdatesSubscription = {\n contelloUpdatesBatch?: {\n events: ({\n target: {\n id: string;\n } & ({\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | {\n __typename: 'ContelloAsset';\n id: string;\n } | {\n __typename: 'ContelloI18nMessage';\n id: string;\n token: string;\n });\n prev?: {\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | undefined;\n mutation: {\n type: ContelloMutationType;\n };\n })[];\n } | undefined;\n};\n\nexport type StoreWatchUpdatesSubscriptionVariables = Record<string, never>;\n\nconst MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {\n id\n original {\n ...MediaFile\n }\n preview {\n ...MediaFile\n }\n optimized {\n ...MediaFile\n ... on ContelloOptimizedFile {\n optimizationConfig {\n ... on ContelloImageOptimizationConfig {\n name\n }\n }\n }\n }\n}`;\nconst MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {\n uid\n mimeType\n metadata {\n ... on ContelloImageMetadata {\n width\n height\n }\n ... on ContelloVideoMetadata {\n width\n height\n }\n }\n}`;\nconst StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {\n ...MediaAsset\n}`;\nconst StoreFileFragmentSchema = `fragment StoreFile on ContelloFile {\n ...MediaFile\n}`;\nconst StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {\n id\n token\n description\n example\n translations {\n language\n value\n }\n}`;\nconst StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {\n id\n path\n target {\n __typename\n ... on ContelloRouteTargetEntity {\n entity {\n __typename\n ... on ContelloEntityBase {\n id\n }\n }\n }\n ... on ContelloRouteTargetAsset {\n asset {\n id\n original {\n uid\n mimeType\n }\n }\n contentDisposition\n }\n ... on ContelloRouteTargetRedirect {\n location\n responseCode\n }\n ... on ContelloRouteTargetText {\n content\n mimeType\n }\n }\n customHeaders {\n name\n value\n }\n}`;\n\nexport const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {\n registerContelloI18nMessages(\n collectionReferenceName: $collection\n messages: $messages\n deprecateUnmentioned: true\n ) {\n ids\n }\n}`;\nexport const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}\nsubscription StoreWatchUpdates {\n contelloUpdatesBatch {\n events {\n target {\n __typename\n ... on ContelloEntityBase {\n id\n }\n ... on ContelloRoute {\n ...StoreRoute\n }\n ... on ContelloAsset {\n id\n }\n ... on ContelloI18nMessage {\n id\n token\n }\n }\n prev {\n __typename\n ... on ContelloRoute {\n ...StoreRoute\n }\n }\n mutation {\n type\n }\n }\n }\n}`;\n\nexport type Operations = {\n storeRegisterI18nMessages: {\n document: string;\n kind: 'mutation';\n __result?: StoreRegisterI18nMessagesMutation | undefined;\n __variables?: StoreRegisterI18nMessagesMutationVariables | undefined;\n };\n storeWatchUpdates: {\n document: string;\n kind: 'subscription';\n __result?: StoreWatchUpdatesSubscription | undefined;\n __variables?: StoreWatchUpdatesSubscriptionVariables | undefined;\n };\n};\n\nexport type Sources = {\n storeAsset: SourceDef<'storeAsset', 'asset', StoreAssetFragment>;\n storeI18nMessage: SourceDef<'storeI18nMessage', 'i18nMessage', StoreI18nMessageFragment>;\n storeRoute: SourceDef<'storeRoute', 'route', StoreRouteFragment>;\n};\n\nconst operations: Operations = {\n storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: 'mutation' },\n storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: 'subscription' },\n};\n\nconst sources: Sources = {\n storeAsset: {\n document: `${MediaFileFragmentSchema}\n${MediaAssetFragmentSchema}\n${StoreAssetFragmentSchema}`,\n fragment: 'StoreAsset',\n subscription: 'contelloAssetsBatch',\n __model: 'storeAsset',\n __cardinality: 'asset',\n },\n storeI18nMessage: {\n document: StoreI18nMessageFragmentSchema,\n fragment: 'StoreI18nMessage',\n subscription: 'contelloI18nMessagesBatch',\n __model: 'storeI18nMessage',\n __cardinality: 'i18nMessage',\n },\n storeRoute: {\n document: StoreRouteFragmentSchema,\n fragment: 'StoreRoute',\n subscription: 'contelloRoutesBatch',\n __model: 'storeRoute',\n __cardinality: 'route',\n },\n};\n\nconst models = {\n dummy: 'DummyEntity',\n} as const;\n\nexport const schema = { operations, sources, models };\nexport type Schema = typeof schema;","import { type AsyncIterableSubject, createAsyncIterableSubject, runWithBackoff } from '@contello/client';\n\n/**\n * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)\n * use it as the interval for a periodic full refresh; lazy stores use it as the per-item\n * LRU eviction window. 3 hours.\n */\nexport const DEFAULT_TTL_MS = 3 * 60 * 60 * 1000;\n\n/**\n * default `cache.max` (LRU capacity) for lazy stores — the maximum number of items kept\n * before least-recently-used eviction.\n */\nexport const DEFAULT_LRU_MAX = 1000;\n\n/**\n * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime\n * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.\n */\nexport function resolveTtl(ttl: number | false | undefined): number | undefined {\n if (ttl === undefined) return DEFAULT_TTL_MS;\n if (ttl === false || ttl <= 0) return undefined;\n\n return ttl;\n}\n\n/**\n * creates a coalescing refresh scheduler with exponential-backoff retry on failure.\n *\n * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,\n * it is queued as pending — the queued slot keeps the latest `kind` passed via\n * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh\n * starts, with that latest kind — collapsing any number of intermediate requests into one.\n *\n * on error, retries indefinitely with exponential backoff. the projected value keeps serving\n * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that\n * triggered the just-completed refresh.\n */\nexport function createRefresher<K>(\n fn: () => Promise<unknown>,\n onRefreshed: (kind: K) => void,\n onStart: () => void,\n): (kind: K) => void {\n let refreshing = false;\n let inFlightKind: K | undefined;\n let pendingKind: { kind: K } | undefined;\n\n function scheduleRefresh(kind: K): void {\n if (refreshing) {\n pendingKind = { kind };\n\n return;\n }\n\n refreshing = true;\n inFlightKind = kind;\n onStart?.();\n\n void runWithBackoff(fn).then(() => {\n const finished = inFlightKind as K;\n\n refreshing = false;\n inFlightKind = undefined;\n onRefreshed(finished);\n\n if (pendingKind) {\n const { kind: next } = pendingKind;\n\n pendingKind = undefined;\n scheduleRefresh(next);\n }\n });\n }\n\n return scheduleRefresh;\n}\n\n/**\n * Refresh channel: bundles the `refresh$` multicast stream and the `onRefresh` callback\n * so both fire on every emission. Used by every eager and lazy store that exposes refresh\n * events.\n */\nexport type RefreshChannel<TEvent> = {\n readonly stream$: AsyncIterableSubject<TEvent>;\n emit(event: TEvent): void;\n complete(): void;\n};\n\nexport function createRefreshChannel<TEvent>(\n onRefresh?: ((event: TEvent) => void) | undefined,\n): RefreshChannel<TEvent> {\n const stream$ = createAsyncIterableSubject<TEvent>();\n\n return {\n stream$,\n emit(event) {\n stream$.next(event);\n onRefresh?.(event);\n },\n complete() {\n stream$.complete();\n },\n };\n}\n\n/**\n * TTL orchestrator: owns the safety-net timer for eager stores. Calls into `run` after\n * `ttl` ms have passed since the last `mark()` (or `reset()`); `run` is responsible for\n * actually fetching + re-arming via another `mark()` once it succeeds. `clear()` cancels\n * the timer on destroy. When `ttl` is undefined the orchestrator is a no-op.\n */\nexport type TtlOrchestrator = {\n /** start (or restart) the timer. consumers call this on first successful full fetch and after every later one. */\n mark(): void;\n /** cancel any pending timer; for destroy. */\n clear(): void;\n};\n\nexport function createTtlOrchestrator(options: { ttl: number | undefined; run: () => void }): TtlOrchestrator {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return {\n mark() {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n\n if (options.ttl === undefined) {\n return;\n }\n\n timer = setTimeout(options.run, options.ttl);\n },\n clear() {\n if (timer === undefined) {\n return;\n }\n\n clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n\n/**\n * FIFO queue for ttl-fired refreshes on eager stores.\n * Concurrency is fixed at 1 to avoid DDOSing the server\n */\nexport type RefreshByTtlQueue = {\n enqueue(task: () => Promise<unknown>): void;\n};\n\nexport function createRefreshByTtlQueue(): RefreshByTtlQueue {\n const waiting: (() => Promise<unknown>)[] = [];\n let running = false;\n\n function next(): void {\n if (running) return;\n\n const task = waiting.shift();\n\n if (!task) return;\n\n running = true;\n\n void (async () => {\n try {\n await task();\n } catch {\n // misbehaving task — keep the queue draining\n } finally {\n running = false;\n next();\n }\n })();\n }\n\n return {\n enqueue(task) {\n waiting.push(task);\n next();\n },\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n runWithBackoff,\n} from '@contello/client';\nimport { type MaybePromise, ProjectedMap, type ReadonlyDeep } from 'projected';\n\nimport { wrap } from './diagnostics';\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport type { StoreAsset, StoreFile } from './lazy-assets';\nimport type { CacheOptions, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type AssetsOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type AssetsSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type Assets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreAsset>>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n};\n\nexport type AssetsSync = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreAsset> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreAsset>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createAssetsCollection(\n options: AssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Assets> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await collectAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n const items = rawItems.map((item) => mapAsset(item));\n\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((a) => a.id));\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n runWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void runWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.asset.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.asset) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n projected.clear();\n\n return;\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n const instance: Assets = {\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data, meta, options) {\n return client.upload(data, meta, options);\n },\n\n download(fileId) {\n return client.download(fileId);\n },\n\n proxyHls(path, signal) {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createAssetsSyncCollection(\n options: AssetsSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<AssetsSync> {\n const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n },\n destroy,\n };\n}\n","import type { ModelResolver } from './model-resolver';\nimport type { UpdateEvent } from './watcher';\n\ntype NonEntityTarget = Exclude<UpdateEvent['target'], 'entity'>;\n\n/**\n * passed to `map()` so the mapper can declare which external entities this item depends on.\n * calls are collected during mapping and indexed once the item key is known.\n * designed to be destructurable: `map(raw, { track, trackRoute }) => ...`\n *\n * `track()` inspects `__typename` to auto-detect the dependency type:\n * - `ContelloAsset` → asset dep\n * - `ContelloRoute` → route dep\n * - `*Entity` → entity dep\n * - anything else → throws\n *\n * explicit methods (`trackEntity`, `trackAsset`, `trackRoute`) are available\n * for cases where only an id is known without the full GraphQL object.\n */\nexport type MapperContext<TModels extends string = string> = {\n track(obj: { __typename: string; id: string }): void;\n trackEntity(typename: TModels, id: string): void;\n trackAsset(id: string): void;\n trackRoute(id: string): void;\n};\n\n// shared empty result so the hot path (an event no item depends on) allocates\n// nothing — callers only ever iterate or read `.size`, never mutate.\nconst EMPTY_KEYS: ReadonlySet<never> = new Set();\n\n// dep key for non-entity targets (route, asset) — `${target}\\0${id}`\nfunction createDependencyKey(target: NonEntityTarget, id: string): string {\n return `${target}\\0${id}`;\n}\n\n// dep key for entity deps — prefixed with `entity\\0` to avoid collisions with other targets\n// e.g. a model named 'route' would otherwise collide with ref.route() deps\nfunction createEntityDependencyKey(typename: string, id: string): string {\n return `entity\\0${typename}\\0${id}`;\n}\n\n// key used to register and look up route-target interest deps.\n// separate from createDependencyKey because the value is a compound (typename \\0 id) pair itself.\nfunction createRouteTargetKey(typename: string, id: string): string {\n return `routeTarget\\0${typename}\\0${id}`;\n}\n\n/**\n * bidirectional dependency index for a single collection.\n *\n * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper\n * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes\n * once the item key is known. `register` flushes the collected deps into two maps:\n *\n * forwardIndex: item key -> set of dep keys it declared\n * reverseIndex: dep key -> set of item keys that declared it\n *\n * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`\n * looks up the dep key and returns all item keys that need to be invalidated.\n *\n * lifecycle per map cycle:\n * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)\n * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array\n * 3. fn calls register(key) — real item key is known, deps written into both maps\n */\nexport class DependencyCollector<TKey, TModels extends string = string> {\n /** dep key -> item keys that declared a dependency on it */\n private reverseIndex = new Map<string, Set<TKey>>();\n /** item key -> dep keys it currently declares */\n private forwardIndex = new Map<TKey, Set<string>>();\n\n constructor(\n /** the model name of the owning collection, used to form route-target dep keys */\n private readonly model: string,\n /** resolver for mapping between model names and __typename */\n private readonly resolver: ModelResolver,\n ) {}\n\n private mergeRouteTargetKeys(\n existing: Set<TKey> | undefined,\n entityType: string,\n entityId: string,\n ): Set<TKey> | undefined {\n const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));\n\n if (!items) {\n return existing;\n }\n\n return existing ? existing.union(items) : items;\n }\n\n private warnIfUnknownModel(model: string): void {\n if (!this.resolver.hasModel(model)) {\n console.warn(\n `[contello/store] tracking model \"${model}\" which is not in models — updates for this model will be ignored`,\n );\n }\n }\n\n /**\n * removes all index entries for one item key.\n * cleans up the forward entry and removes the item from every reverse set it appeared in.\n * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.\n */\n private clearItem(key: TKey): void {\n const existingDeps = this.forwardIndex.get(key);\n\n if (!existingDeps) {\n return;\n }\n\n for (const dk of existingDeps) {\n const set = this.reverseIndex.get(dk);\n\n if (set) {\n set.delete(key);\n\n if (set.size === 0) {\n this.reverseIndex.delete(dk);\n }\n }\n }\n\n this.forwardIndex.delete(key);\n }\n\n /**\n * creates a scoped MapperContext for one item and runs `fn` with it.\n * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function\n * that must be called once the item key is known — it writes all declared deps into the index.\n * returns whatever `fn` returns, preserving MaybePromise semantics.\n */\n createContext<T>(fn: (ctx: MapperContext<TModels>, register: (key: TKey) => void) => T): T {\n const deps: string[] = [];\n\n const ctx: MapperContext<TModels> = {\n track: (obj) => {\n if (!obj.id) {\n throw new Error(`track(): object with __typename \"${obj.__typename}\" has no \"id\" field`);\n }\n\n switch (obj.__typename) {\n case 'ContelloAsset': {\n deps.push(createDependencyKey('asset', obj.id));\n break;\n }\n case 'ContelloRoute': {\n deps.push(createDependencyKey('route', obj.id));\n break;\n }\n default: {\n const model = this.resolver.getModel(obj.__typename);\n\n if (!model) {\n throw new Error(\n `track(): unexpected __typename \"${obj.__typename}\" — expected ContelloAsset, ContelloRoute, or a known entity model`,\n );\n }\n\n deps.push(createEntityDependencyKey(model, obj.id));\n }\n }\n },\n trackEntity: (model, id) => {\n this.warnIfUnknownModel(model);\n deps.push(createEntityDependencyKey(model, id));\n },\n trackAsset: (id) => {\n deps.push(createDependencyKey('asset', id));\n },\n trackRoute: (id) => {\n deps.push(createDependencyKey('route', id));\n },\n };\n\n const register = (key: TKey) => {\n this.clearItem(key);\n\n deps.push(createRouteTargetKey(this.model, String(key)));\n\n const fwd = new Set<string>();\n\n for (const dk of deps) {\n fwd.add(dk);\n\n let set = this.reverseIndex.get(dk);\n\n if (!set) {\n set = new Set();\n this.reverseIndex.set(dk, set);\n }\n\n set.add(key);\n }\n\n if (fwd.size > 0) {\n this.forwardIndex.set(key, fwd);\n }\n };\n\n return fn(ctx, register);\n }\n\n /**\n * looks up which item keys are affected by an update event.\n * for route events, checks route-target deps for both the new and previous entity targets.\n */\n getAffectedKeys(event: UpdateEvent): ReadonlySet<TKey> {\n if (event.target === 'entity') {\n return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;\n }\n\n let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));\n\n if (event.target === 'route') {\n if ('after' in event && event.after.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);\n }\n }\n\n return affected ?? EMPTY_KEYS;\n }\n\n /** removes all recorded deps for a single item (called on eviction) */\n removeItem(key: TKey): void {\n this.clearItem(key);\n }\n\n /** drops all recorded deps — used when clearing the entire cache */\n clear(): void {\n this.reverseIndex.clear();\n this.forwardIndex.clear();\n }\n\n /**\n * removes index entries for any item key NOT present in `keys`.\n * called after a full re-fetch to prune refs from items that were deleted upstream.\n */\n retainOnly(keys: Set<TKey>): void {\n for (const key of this.forwardIndex.keys()) {\n if (!keys.has(key)) {\n this.clearItem(key);\n }\n }\n }\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n type SourceDef,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n runWithBackoff,\n} from '@contello/client';\nimport { type MaybePromise, ProjectedMap, type ReadonlyDeep, maybeThen } from 'projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { wrap } from './diagnostics';\nimport type { ModelResolver } from './model-resolver';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n Created,\n ExtractSourceResult,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nfunction fetchCollection<S extends SourceDef<string, 'entity'>>(\n source: S,\n client: ContelloClient<any>,\n ids: string[] | undefined,\n): Promise<ExtractSourceResult<S>[]> {\n return collectAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<S>[] }>(createSourceSubscription(source), { ids }),\n (r) => r.source,\n ),\n );\n}\n\nexport function createCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Collection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const projected = new ProjectedMap<string, TMapped>({\n key: (item) => item.id,\n values: (ids) =>\n wrap(`collection:${_def.name}`, () =>\n maybeThen(fetchCollection(source, client, ids), async (rawItems) => {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const items = await Promise.all(\n rawItems.map((item) =>\n Promise.resolve(\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n );\n\n if (ids === undefined) {\n dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((item) => item.id));\n }\n } else {\n const returnedIds = new Set(items.map((item) => item.id));\n\n for (const id of ids) {\n if (!returnedIds.has(id)) {\n dependencyCollector.removeItem(id);\n }\n }\n }\n\n return items;\n }),\n ),\n sort: opts.sort,\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n runWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void runWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const ownEvents = batch.entity.get(_def.model) ?? [];\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of ownEvents) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n const depAffected = new Set<string>();\n\n for (const event of batch.events) {\n for (const id of dependencyCollector.getAffectedKeys(event)) {\n depAffected.add(id);\n }\n }\n\n if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n for (const id of deleted) {\n dependencyCollector.removeItem(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n const refreshIds = upserted.union(depAffected);\n\n for (const id of deleted) {\n refreshIds.delete(id);\n }\n\n runPartialRefresh([...refreshIds], deleted);\n });\n\n const instance: Collection<TMapped> = {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll(): MaybePromise<ReadonlyArray<ReadonlyDeep<TMapped>>> {\n return projected.getAll();\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createCollectionSync<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<CollectionSync<TMapped>> {\n const { instance: base, destroy } = createCollection<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`collection \"${base.name}\".${method}() is not initialized yet — call collection.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getAll(): ReadonlyArray<ReadonlyDeep<TMapped>> {\n return assertSync(base.getAll(), 'getAll');\n },\n },\n destroy,\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n runWithBackoff,\n} from '@contello/client';\nimport { type MaybePromise, ProjectedMap, type ReadonlyDeep, maybeThen } from 'projected';\nimport { wrap } from './diagnostics';\nimport {\n type ContelloI18nMessageInput,\n type StoreI18nMessageFragment,\n type StoreRegisterI18nMessagesMutation,\n storeRegisterI18nMessagesDocument,\n schema as storeSchema,\n} from './generated/graphql';\nimport type { RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\n\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type I18nTranslation = {\n language: string;\n value: string;\n};\n\nexport type I18nVariableInput = {\n name: string;\n description: string;\n example: string;\n};\n\nexport type I18nInitialTranslation = {\n language: string;\n message: string;\n};\n\nexport type I18nMessageRegistrationDefinition = {\n token: string;\n example?: string | undefined;\n description?: string | undefined;\n variables?: I18nVariableInput[] | undefined;\n /** always overwrites existing translations for this token */\n translations?: I18nInitialTranslation[] | undefined;\n /** only applied when the token is newly registered (existing translations are preserved) */\n initialTranslations?: I18nInitialTranslation[] | undefined;\n};\n\nexport type I18nMessageDef = {\n collection: string;\n cache?: SyncCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type I18nMessage = {\n id: string;\n token: string;\n translations: Map<string, string>;\n};\n\nexport type I18nMessages = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): MaybePromise<ReadonlyDeep<I18nMessage> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n getAll(): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n register(messages: I18nMessageRegistrationDefinition[]): Promise<void>;\n refresh(): void;\n /** Completes refresh$ and detaches from the watcher — called by `Store.destroy()`. */\n destroy(): void;\n};\n\nfunction toGqlMessageInput(msg: I18nMessageRegistrationDefinition): ContelloI18nMessageInput {\n return {\n token: msg.token,\n example: msg.example,\n description: msg.description,\n variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),\n translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),\n initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message })),\n };\n}\n\nexport function createI18nMessagesCollection(\n def: I18nMessageDef,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): I18nMessages {\n const channel = createRefreshChannel<RefreshEvent>(def.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });\n let loaded = false;\n\n const i18nSourceDoc = createSourceSubscription(storeSchema.sources.storeI18nMessage);\n\n const projected = new ProjectedMap<string, I18nMessage>({\n key: (msg) => msg.id,\n values: (ids) =>\n wrap(`i18n:${def.collection}`, async () => {\n const msgs = await collectAsync(\n mapAsync(\n client.subscribe<{ source: StoreI18nMessageFragment[] }>(i18nSourceDoc, {\n collection: def.collection,\n ids,\n }),\n (data) => data.source,\n ),\n );\n const items: I18nMessage[] = msgs.map((msg) => ({\n id: msg.id,\n token: msg.token,\n translations: new Map(msg.translations.map((t) => [t.language, t.value])),\n }));\n\n // start tracking refresh by ttl on first successful full fetch\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function emitWithCurrentIds(kind: RefreshKind): void {\n maybeThen(projected.getAll(), (msgs) => {\n emit(\n msgs.map((m) => m.id),\n kind,\n );\n });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await runWithBackoff(() => projected.refresh());\n emitWithCurrentIds('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emitWithCurrentIds(kind);\n ttl.mark();\n },\n () => {},\n );\n\n function runPartialRefresh(upsertedIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...upsertedIds, ...deletedIds])];\n\n if (changedIds.length === 0) {\n return;\n }\n\n if (upsertedIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void runWithBackoff(async () => {\n await projected.refresh(upsertedIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n if (batch.i18nMessage.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.i18nMessage) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n return {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll() {\n return projected.getAll();\n },\n\n register(messages: I18nMessageRegistrationDefinition[]) {\n return wrap(`i18n-register:${def.collection}`, async () => {\n await client.execute<StoreRegisterI18nMessagesMutation>(storeRegisterI18nMessagesDocument, {\n collection: def.collection,\n messages: messages.map((message) => toGqlMessageInput(message)),\n });\n });\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n","import { LRUCache } from 'lru-cache';\nimport type { ProjectedMapCache } from 'projected';\n\nexport type LruCache<TKey, TValue> = ProjectedMapCache<TKey, TValue> & {\n keys: () => TKey[];\n};\n\nexport function createLruCache<TKey, TValue>(options: {\n max: number;\n ttl: number | undefined;\n onEvict: ((value: TValue, key: TKey) => void) | undefined;\n}): LruCache<TKey, TValue> {\n const { max, ttl, onEvict: dispose } = options;\n\n const lru = new LRUCache<any, any>({\n max,\n ...(ttl !== undefined && { ttl, ttlAutopurge: false }),\n ...(dispose !== undefined && { dispose }),\n });\n\n return {\n has: (key) => lru.has(key),\n get: (key) => lru.get(key),\n set: (key, value) => {\n lru.set(key, value);\n },\n delete: (key) => {\n lru.delete(key);\n },\n clear: () => {\n lru.clear();\n },\n keys: () => lru.keys().toArray(),\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n} from '@contello/client';\nimport { ProjectedLazyMap, type ReadonlyDeep } from 'projected';\nimport { wrap } from './diagnostics';\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport { createLruCache } from './lru';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type StoreFileMetadata = {\n width: number;\n height: number;\n};\n\nexport type StoreFile = {\n uid: string;\n mimeType: string;\n metadata: StoreFileMetadata | undefined;\n};\n\nexport type StoreAsset = {\n id: string;\n original: StoreFile;\n preview: StoreFile | undefined;\n optimized: StoreFile[];\n};\n\nexport type LazyAssetsOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyAssets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreAsset[]>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n clear(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createLazyAssetsCollection(\n def: LazyAssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n): Created<LazyAssets> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createLruCache<string, StoreAsset>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedLazyMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await collectAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n\n return rawItems.map((item) => mapAsset(item));\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (batch.asset.length === 0) return;\n\n for (const event of batch.asset) {\n projected.delete(event.id);\n }\n\n emit(\n batch.asset.map((e) => e.id),\n 'upstream-update',\n );\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return client.upload(data, meta, options);\n },\n\n download(fileId: string): Promise<DownloadResult> {\n return client.download(fileId);\n },\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n type SourceDef,\n collectAsync,\n createAsyncIterableSubject,\n createSourceSubscription,\n mapAsync,\n} from '@contello/client';\nimport { ProjectedLazyMap, maybeThen } from 'projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { wrap } from './diagnostics';\nimport { createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport type {\n Created,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { DEFAULT_LRU_MAX, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createLazyCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: LazyCollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyCollection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n max: opts.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(opts.cache?.ttl),\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const cache = createLruCache<string, TMapped>({\n max: _def.cache.max,\n ttl: _def.cache.ttl,\n onEvict: (_value, key) => dependencyCollector.removeItem(key),\n });\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedLazyMap<string, TMapped>({\n key: (item) => item.id,\n values: (keys) =>\n wrap(`lazy-collection:${_def.name}`, () =>\n maybeThen(\n collectAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource>[] }>(createSourceSubscription(source), {\n ids: keys,\n }),\n (r) => r.source,\n ),\n ),\n (rawItems) =>\n Promise.all(\n rawItems.map((item) =>\n Promise.resolve(\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n ),\n ),\n ),\n cache,\n });\n\n const refresh$ = createAsyncIterableSubject<RefreshEvent>();\n\n function emit(ids: string[], kind: RefreshKind): void {\n const event: RefreshEvent = { ids, kind };\n\n refresh$.next(event);\n opts.onRefresh?.(event);\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted = new Set<string>();\n const ownModelEvents = batch.entity.get(_def.model);\n\n if (ownModelEvents) {\n for (const event of ownModelEvents) {\n evicted.add(event.id);\n }\n }\n\n for (const event of batch.events) {\n for (const key of dependencyCollector.getAffectedKeys(event)) {\n evicted.add(key);\n }\n }\n\n if (evicted.size > 0) {\n for (const key of evicted) {\n dependencyCollector.removeItem(key);\n projected.delete(key);\n }\n\n emit([...evicted], 'upstream-update');\n }\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n dependencyCollector.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n refresh$.complete();\n },\n };\n}\n","import type { StoreRouteFragment } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\n\nexport type StoreRouteCustomHeader = {\n name: string;\n value: string;\n};\n\nexport type StoreRoute = {\n id: string;\n path: string;\n customHeaders: StoreRouteCustomHeader[];\n} & (\n | { type: 'redirect'; location: string; status: number }\n | { type: 'text'; content: string; mimeType: string }\n | { type: 'asset'; assetId: string; fileId: string; contentDisposition: 'inline' | 'attachment'; mimeType: string }\n | { type: 'entity'; model: string; entityType: string; entityId: string }\n);\n\nexport function mapRoute(raw: StoreRouteFragment, resolver: ModelResolver): StoreRoute | undefined {\n const base = {\n id: raw.id,\n path: raw.path,\n customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value })),\n };\n\n switch (raw.target.__typename) {\n case 'ContelloRouteTargetRedirect': {\n return {\n ...base,\n type: 'redirect',\n location: raw.target.location,\n status: raw.target.responseCode,\n };\n }\n\n case 'ContelloRouteTargetText': {\n return {\n ...base,\n type: 'text',\n content: raw.target.content,\n mimeType: raw.target.mimeType,\n };\n }\n\n case 'ContelloRouteTargetAsset': {\n return {\n ...base,\n type: 'asset',\n assetId: raw.target.asset.id,\n fileId: raw.target.asset.original.uid,\n contentDisposition: raw.target.contentDisposition === 'INLINE' ? 'inline' : 'attachment',\n mimeType: raw.target.asset.original.mimeType,\n };\n }\n\n case 'ContelloRouteTargetEntity': {\n if (!raw.target.entity) {\n return undefined;\n }\n\n const entityType = raw.target.entity.__typename;\n\n return {\n ...base,\n type: 'entity',\n model: resolver.resolveModel(entityType),\n entityType,\n entityId: raw.target.entity.id,\n };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n} from '@contello/client';\nimport { ProjectedLazyMap, type ReadonlyDeep } from 'projected';\nimport { wrap } from './diagnostics';\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport { type LruCache, createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type { StoreRoute, StoreRouteCustomHeader } from './routes-mapping';\n\nexport type LazyRoutesOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyRoutes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n getByPath(path: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n refresh(): void;\n clear(): void;\n};\n\n// cache key prefixes — short nullbyte-separated to allow slice(2) extraction without branching\nconst ID_PREFIX = '1\\0';\nconst PATH_PREFIX = '2\\0';\n\n// private symbol used to tag each route with the projected cache key it was requested under,\n// so the key() function can return the right prefixed key for projected to match results back\nconst CACHE_KEY = Symbol('cacheKey');\n\nfunction collectRoutes(\n rawItems: StoreRouteFragment[],\n keyFn: (route: StoreRoute) => string,\n resolver: ModelResolver,\n): StoreRoute[] {\n return rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n (mapped as Record<symbol, string>)[CACHE_KEY] = keyFn(mapped);\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n}\n\n/**\n * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space\n * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.\n *\n * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU\n * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).\n */\nfunction createRoutesCache(max: number, ttl: number | undefined): LruCache<string, StoreRoute> {\n const pathToId = new Map<string, string>();\n // reverse of pathToId, so a route whose path changed can have its previous\n // path entry removed (otherwise getByPath(oldPath) would resolve to the route\n // that no longer lives there)\n const idToPath = new Map<string, string>();\n\n const lru = createLruCache<string, StoreRoute>({\n max,\n ttl,\n onEvict: (route) => {\n pathToId.delete(route.path);\n idToPath.delete(route.id);\n },\n });\n\n function resolveKey(key: string): string {\n if (key.startsWith(PATH_PREFIX)) {\n const id = pathToId.get(key.slice(2));\n\n if (id) {\n return ID_PREFIX + id;\n }\n\n return key; // propagate cache miss if path not found\n }\n\n return key;\n }\n\n return {\n has: (key) => lru.has(resolveKey(key)),\n get: (key) => lru.get(resolveKey(key)),\n\n set: (_key, value) => {\n // always normalise to ID_PREFIX in lru\n // regardless of which key projected passes in\n const previousPath = idToPath.get(value.id);\n\n if (previousPath !== undefined && previousPath !== value.path) {\n pathToId.delete(previousPath);\n }\n\n pathToId.set(value.path, value.id);\n idToPath.set(value.id, value.path);\n lru.set(ID_PREFIX + value.id, value);\n },\n\n delete: (key) => {\n const resolved = resolveKey(key);\n const value = lru.get(resolved);\n\n if (value) {\n pathToId.delete(value.path);\n idToPath.delete(value.id);\n }\n\n lru.delete(resolved);\n },\n\n clear: () => {\n pathToId.clear();\n idToPath.clear();\n lru.clear();\n },\n\n keys: () => lru.keys(),\n };\n}\n\nexport function createLazyRoutesCollection(\n def: LazyRoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyRoutes> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n function fetchRoutes(vars: { ids?: string[]; paths?: string[] }): Promise<StoreRouteFragment[]> {\n return collectAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, vars), (data) => data.source),\n );\n }\n\n const projected = new ProjectedLazyMap<string, StoreRoute>({\n key: (route) => (route as Record<symbol, string>)[CACHE_KEY] ?? ID_PREFIX + route.id,\n values: (prefixedKeys) =>\n wrap('routes', async () => {\n const ids: string[] = [];\n const paths: string[] = [];\n\n for (const key of prefixedKeys) {\n const value = key.slice(2);\n\n if (key.startsWith(ID_PREFIX)) {\n ids.push(value);\n } else {\n paths.push(value);\n }\n }\n\n const [rawByIds, rawByPaths] = await Promise.all([\n ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve<StoreRouteFragment[]>([]),\n paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve<StoreRouteFragment[]>([]),\n ]);\n\n const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);\n const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + r.path, resolver);\n\n return [...byIds, ...byPaths];\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(\n lastRefreshKeys.map((key) => key.slice(2)),\n kind,\n );\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted: string[] = [];\n\n for (const event of batch.route) {\n const idKey = ID_PREFIX + event.id;\n\n if (event.mutation === 'delete') {\n cache.delete(idKey);\n evicted.push(event.id);\n } else {\n if (cache.has(idKey)) {\n cache.set(idKey, event.after);\n }\n\n evicted.push(event.after.path);\n }\n }\n\n if (evicted.length > 0) {\n emit(evicted, 'upstream-update');\n }\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n if (Array.isArray(idOrIds)) {\n return projected.get(idOrIds.map((id) => ID_PREFIX + id));\n }\n\n return projected.get(ID_PREFIX + idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n if (Array.isArray(pathOrPaths)) {\n return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));\n }\n\n return projected.get(PATH_PREFIX + pathOrPaths);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","export class ModelResolver<TModels extends string = string> {\n private _typeNames: ReadonlySet<string> | undefined;\n private _toModel: ReadonlyMap<string, TModels>;\n private _toTypeName: ReadonlyMap<TModels, string>;\n\n constructor(models?: Record<TModels, string> | undefined) {\n const toModel = new Map<string, TModels>();\n const toTypeName = new Map<TModels, string>();\n let typeNames: Set<string> | undefined;\n\n if (models) {\n typeNames = new Set<string>();\n\n for (const [model, typeName] of Object.entries<string>(models)) {\n toModel.set(typeName, model as TModels);\n toTypeName.set(model as TModels, typeName);\n typeNames.add(typeName);\n }\n }\n\n this._typeNames = typeNames;\n this._toModel = toModel;\n this._toTypeName = toTypeName;\n }\n\n hasTypeName(typeName: string): boolean {\n return !this._typeNames || this._typeNames.has(typeName);\n }\n\n getModel(typeName: string): TModels | undefined {\n return this._toModel.get(typeName);\n }\n\n getTypeName(model: TModels): string {\n return this._toTypeName.get(model) ?? model;\n }\n\n hasModel(model: string): boolean {\n return this._toTypeName.size === 0 || this._toTypeName.has(model as TModels);\n }\n\n resolveModel(typeName: string): string {\n return this._toModel.get(typeName) ?? typeName;\n }\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n collectAsync,\n createSourceSubscription,\n mapAsync,\n runWithBackoff,\n} from '@contello/client';\nimport { type MaybePromise, ProjectedMap, type ReadonlyDeep, maybeThen } from 'projected';\n\nimport { wrap } from './diagnostics';\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport type { CacheOptions, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type RoutesOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type RoutesSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type Routes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n getByPath(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n refresh(): void;\n};\n\nexport type RoutesSync = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreRoute> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n getByPath(path: string): ReadonlyDeep<StoreRoute> | undefined;\n getByPath(paths: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n refresh(): void;\n};\n\nexport function createRoutesCollection(\n options: RoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Routes> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n\n // id ↔ path indexes — kept in sync with `projected` by the values callback.\n // any route lookup by path resolves to an id, then the value comes from `projected`.\n const pathById = new Map<string, string>();\n const idByPath = new Map<string, string>();\n let loaded = false;\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n const projected = new ProjectedMap<string, StoreRoute>({\n key: (route) => route.id,\n values: (ids) =>\n wrap('routes', async () => {\n const rawItems = await collectAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, { ids }), (data) => data.source),\n );\n const items = rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n\n if (ids === undefined) {\n pathById.clear();\n idByPath.clear();\n\n for (const r of items) {\n pathById.set(r.id, r.path);\n idByPath.set(r.path, r.id);\n }\n\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((r) => r.id));\n }\n } else {\n const returnedIds = new Set(items.map((r) => r.id));\n\n // requested ids missing from the response = deleted; drop their path entries\n for (const id of ids) {\n if (returnedIds.has(id)) {\n continue;\n }\n\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(oldPath);\n pathById.delete(id);\n }\n }\n\n for (const r of items) {\n const oldPath = pathById.get(r.id);\n\n if (oldPath !== undefined && oldPath !== r.path) {\n idByPath.delete(oldPath);\n }\n\n pathById.set(r.id, r.path);\n idByPath.set(r.path, r.id);\n }\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n runWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void runWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.route.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.route) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n pathById.clear();\n idByPath.clear();\n projected.clear();\n\n return;\n }\n\n for (const id of deleted) {\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(oldPath);\n pathById.delete(id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n function getByIdSingle(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return projected.get(id);\n }\n\n function getByIds(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return projected.get(ids);\n }\n\n function lookupByPathSingle(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return maybeThen(ensureLoaded(), () => {\n const id = idByPath.get(path);\n\n return id === undefined ? undefined : projected.get(id);\n });\n }\n\n function lookupByPaths(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return maybeThen(ensureLoaded(), () => {\n const ids: string[] = [];\n\n for (const p of paths) {\n const id = idByPath.get(p);\n\n if (id !== undefined) {\n ids.push(id);\n }\n }\n\n return projected.get(ids);\n });\n }\n\n function ensureLoaded(): MaybePromise<void> {\n if (loaded) {\n return undefined;\n }\n\n return maybeThen(projected.getAllAsMap(), () => {});\n }\n\n const instance: Routes = {\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return typeof idOrIds === 'string' ? getByIdSingle(idOrIds) : getByIds(idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n return typeof pathOrPaths === 'string' ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createRoutesSyncCollection(\n options: RoutesSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<RoutesSync> {\n const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getByPath(pathOrPaths: string | readonly string[]): any {\n return assertSync(base.getByPath(pathOrPaths as string), 'getByPath');\n },\n },\n destroy,\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n type SourceDef,\n createSourceSubscription,\n firstAsync,\n mapAsync,\n runWithBackoff,\n} from '@contello/client';\nimport { type MaybePromise, ProjectedValue, type ReadonlyDeep, maybeThen } from 'projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { wrap } from './diagnostics';\nimport type { ModelResolver } from './model-resolver';\nimport type {\n Created,\n ExtractSourceResult,\n RefreshKind,\n Singleton,\n SingletonOptions,\n SingletonRefreshEvent,\n SingletonSync,\n SingletonSyncOptions,\n} from './types';\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createSingleton<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Singleton<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const itemKey = `singleton:${_def.name}`;\n const channel = createRefreshChannel<SingletonRefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });\n let loaded = false;\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedValue<TMapped>({\n value: () =>\n wrap(`singleton:${_def.name}`, () =>\n maybeThen(\n firstAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource> }>(createSourceSubscription(source)),\n (r) => r.source,\n ),\n ),\n (raw) =>\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(raw, ref), (mapped) => {\n register(itemKey);\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.();\n }\n\n return mapped;\n }),\n ),\n ),\n ),\n });\n\n function emit(kind: RefreshKind): void {\n channel.emit({ kind });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await runWithBackoff(() => projected.refresh());\n emit('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emit(kind);\n ttl.mark();\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const hasOwnModel = batch.entity.has(_def.model);\n const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);\n\n if (!hasOwnModel && !hasAffectedRefs) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n scheduleRefresh('upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(): MaybePromise<ReadonlyDeep<TMapped>> {\n return projected.get();\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.get();\n }\n },\n },\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createSingletonSync<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<SingletonSync<TMapped>> {\n const { instance: base, destroy } = createSingleton<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n return {\n instance: {\n ...base,\n\n get(): ReadonlyDeep<TMapped> {\n const result = base.get();\n\n if (result instanceof Promise) {\n throw new TypeError(`singleton \"${base.name}\" is not initialized yet — call singleton.load() first`);\n }\n\n return result;\n },\n },\n destroy,\n };\n}\n","import {\n type AsyncIterableSubject,\n type ContelloClient,\n asyncKeepalive,\n createAsyncIterableSubject,\n mapAsync,\n} from '@contello/client';\n\nimport { wrap } from './diagnostics';\nimport {\n type ContelloMutationType,\n type StoreRouteFragment,\n type StoreWatchUpdatesSubscription,\n storeWatchUpdatesDocument,\n} from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\n\nexport type UpdateEvent<TEntityType extends string = string> =\n | { id: string; mutation: 'create'; target: 'route'; after: StoreRoute }\n | { id: string; mutation: 'update'; target: 'route'; after: StoreRoute; before: StoreRoute }\n | { id: string; mutation: 'delete'; target: 'route' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'asset' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'i18nMessage'; token: string }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'entity'; model: TEntityType };\n\nexport type UpdateMutationType = UpdateEvent['mutation'];\n\nexport type UpdateEventFor<T extends UpdateEvent['target']> = Extract<UpdateEvent, { target: T }>;\n\nexport type UpdateBatch = {\n readonly events: UpdateEvent[];\n readonly route: UpdateEventFor<'route'>[];\n readonly asset: UpdateEventFor<'asset'>[];\n readonly i18nMessage: UpdateEventFor<'i18nMessage'>[];\n /** entity events grouped by model typename */\n readonly entity: Map<string, UpdateEventFor<'entity'>[]>;\n /** route events grouped by target entity model (both after and before targets for updates) */\n readonly routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addRouteByModel(\n map: Map<string, UpdateEventFor<'route'>[]>,\n entityType: string,\n event: UpdateEventFor<'route'>,\n): void {\n let list = map.get(entityType);\n\n if (!list) {\n list = [];\n map.set(entityType, list);\n }\n\n list.push(event);\n}\n\ntype MutableBatch = {\n route: UpdateEventFor<'route'>[];\n asset: UpdateEventFor<'asset'>[];\n i18nMessage: UpdateEventFor<'i18nMessage'>[];\n entity: Map<string, UpdateEventFor<'entity'>[]>;\n routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addEventToBatch(batch: MutableBatch, event: UpdateEvent): void {\n switch (event.target) {\n case 'route': {\n batch.route.push(event);\n\n if ('after' in event && event.after.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.after.model, event);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.before.model, event);\n }\n\n break;\n }\n case 'asset': {\n batch.asset.push(event);\n break;\n }\n case 'i18nMessage': {\n batch.i18nMessage.push(event);\n break;\n }\n case 'entity': {\n let list = batch.entity.get(event.model);\n\n if (!list) {\n list = [];\n batch.entity.set(event.model, list);\n }\n\n list.push(event);\n break;\n }\n }\n}\n\nfunction createUpdateBatch(events: UpdateEvent[]): UpdateBatch {\n const batch: MutableBatch = {\n route: [],\n asset: [],\n i18nMessage: [],\n entity: new Map<string, UpdateEventFor<'entity'>[]>(),\n routeByEntityModel: new Map<string, UpdateEventFor<'route'>[]>(),\n };\n\n for (const event of events) {\n addEventToBatch(batch, event);\n }\n\n return {\n events,\n route: batch.route,\n asset: batch.asset,\n i18nMessage: batch.i18nMessage,\n entity: batch.entity,\n routeByEntityModel: batch.routeByEntityModel,\n };\n}\n\ntype RawBatch = NonNullable<StoreWatchUpdatesSubscription['contelloUpdatesBatch']>;\ntype RawEvent = RawBatch['events'][number];\n\nfunction castMutationType(type: ContelloMutationType): UpdateMutationType {\n switch (type) {\n case 'CREATE': {\n return 'create';\n }\n case 'UPDATE': {\n return 'update';\n }\n case 'DELETE': {\n return 'delete';\n }\n }\n}\n\nfunction mapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n const mutation = castMutationType(raw.mutation.type);\n const target = raw.target;\n const { id, __typename } = target;\n\n switch (__typename) {\n case 'ContelloRoute': {\n if (mutation === 'delete') {\n return { id, mutation: 'delete', target: 'route' };\n }\n\n const after = mapRoute(target as StoreRouteFragment, resolver);\n\n if (!after) {\n return undefined;\n }\n\n if (mutation === 'create') {\n return { id, mutation, target: 'route', after };\n }\n\n const before =\n raw.prev?.__typename === 'ContelloRoute'\n ? (mapRoute(raw.prev as StoreRouteFragment, resolver) ?? undefined)\n : undefined;\n\n if (!before) {\n return undefined;\n }\n\n return { id, mutation, target: 'route', after, before };\n }\n\n case 'ContelloAsset': {\n return { id, mutation, target: 'asset' };\n }\n\n case 'ContelloI18nMessage': {\n return { id, mutation, target: 'i18nMessage', token: target.token };\n }\n\n default: {\n if (!__typename || !resolver.hasTypeName(__typename)) {\n return undefined;\n }\n\n return { id, mutation, target: 'entity', model: resolver.resolveModel(__typename) };\n }\n }\n}\n\nfunction safeMapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n try {\n return mapEvent(raw, resolver);\n } catch {\n return undefined;\n }\n}\n\nexport type InternalWatcher = {\n /** Multicast stream of update batches. Internal-only; the public `Store.updates$` is the AsyncIterable view. */\n readonly updates$: AsyncIterableSubject<UpdateBatch>;\n start(): void;\n stop(): void;\n};\n\nexport function createInternalWatcher(client: ContelloClient<any>, resolver: ModelResolver): InternalWatcher {\n const updates$ = createAsyncIterableSubject<UpdateBatch>();\n let controller: AbortController | undefined;\n\n return {\n updates$,\n\n start() {\n if (controller) {\n return;\n }\n\n controller = new AbortController();\n const signal = controller.signal;\n\n wrap('watcher:start', () => {\n void (async () => {\n const source = asyncKeepalive(\n () => client.subscribe<StoreWatchUpdatesSubscription>(storeWatchUpdatesDocument),\n signal,\n );\n\n const events = mapAsync(source, (data) =>\n (data.contelloUpdatesBatch?.events ?? [])\n // a single malformed event must not throw out of the loop and kill\n // the watcher — skip it and keep consuming the stream\n .map((e) => safeMapEvent(e, resolver))\n .filter((e): e is UpdateEvent => e !== undefined),\n );\n\n for await (const list of events) {\n if (signal.aborted) {\n return;\n }\n\n if (list.length === 0) {\n continue;\n }\n\n try {\n updates$.next(createUpdateBatch(list));\n } catch {\n // a subscriber threw — isolate it so it can't tear down the watcher\n }\n }\n })().catch(() => {\n // asyncKeepalive only exits on abort; swallow so a terminal failure\n // never surfaces as an unhandled rejection\n });\n });\n },\n\n stop() {\n controller?.abort();\n controller = undefined;\n updates$.complete();\n },\n };\n}\n","import { type ContelloClient, type Schema, type SourceDef, createContelloClient } from '@contello/client';\n\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n createAssetsCollection,\n createAssetsSyncCollection,\n} from './assets';\nimport { createCollection, createCollectionSync } from './collection';\nimport { wrap } from './diagnostics';\nimport { type I18nMessageDef, type I18nMessages, createI18nMessagesCollection } from './i18n';\nimport { type LazyAssets, type LazyAssetsOptions, createLazyAssetsCollection } from './lazy-assets';\nimport { createLazyCollection } from './lazy-collection';\nimport { type LazyRoutes, type LazyRoutesOptions, createLazyRoutesCollection } from './lazy-routes';\nimport { ModelResolver } from './model-resolver';\nimport {\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n createRoutesCollection,\n createRoutesSyncCollection,\n} from './routes';\nimport { createSingleton, createSingletonSync } from './singleton';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CreateStoreOptions,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n ResolveSource,\n Singleton,\n SingletonOptions,\n SingletonSync,\n SingletonSyncOptions,\n SourceKeysOf,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshByTtlQueue } from './utils';\nimport { type InternalWatcher, type UpdateBatch, createInternalWatcher } from './watcher';\n\n/** Project the model-reference-name union out of a Schema generic, falling back to `string`. */\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\n\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\n\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Store<TSchema extends Schema | undefined = undefined> {\n private _client: ContelloClient<TSchema>;\n private _resolver: ModelResolver;\n private _watcher: InternalWatcher;\n private _schema: TSchema;\n private _cleanups: (() => void)[] = [];\n private _refreshByTtl: RefreshByTtlQueue = createRefreshByTtlQueue();\n\n /**\n * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;\n * each iteration starts an independent fan-out from the shared source.\n */\n public readonly updates$: AsyncIterable<UpdateBatch>;\n\n public ping: () => Promise<void>;\n\n constructor(options: CreateStoreOptions<TSchema>) {\n const { url, project, token, schema } = options;\n\n this._schema = schema as TSchema;\n this._client = createContelloClient<TSchema>({\n url,\n project,\n token,\n schema,\n connections: options.connections,\n onConnected: options.onConnected,\n onReconnecting: options.onReconnecting,\n onError: options.onError,\n connectionEvents: options.connectionEvents,\n });\n\n this._resolver = new ModelResolver(schema?.models);\n this._watcher = createInternalWatcher(this._client, this._resolver);\n this.updates$ = this._watcher.updates$;\n this.ping = () => this._client.ping();\n }\n\n /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */\n private _resolveSource<T extends SourceDef>(sourceOrKey: string | T): T {\n if (typeof sourceOrKey !== 'string') {\n return sourceOrKey;\n }\n\n const sources = (this._schema as Schema | undefined)?.sources;\n const source = sources?.[sourceOrKey];\n\n if (!source) {\n throw new Error(`@contello/store: no source named \"${sourceOrKey}\" in schema.sources`);\n }\n\n return source as T;\n }\n\n public get client(): ContelloClient<TSchema> {\n return this._client;\n }\n\n public async init() {\n await wrap('store:init', () => this._client.init());\n\n this._watcher.start();\n }\n\n public async destroy() {\n // eslint-disable-next-line unicorn/no-unnecessary-splice -- splice(0) is used for its return value (a snapshot of the cleanups) *and* to atomically empty the array; `.length = 0` would drop the returned snapshot we iterate\n for (const fn of this._cleanups.splice(0)) {\n try {\n fn();\n } catch {\n // swallow — destruction is best-effort\n }\n }\n\n this._watcher.stop();\n\n await wrap('store:destroy', () => this._client.destroy());\n }\n\n // --- singleton ---\n\n public defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingleton(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Singleton<TMapped>;\n }\n\n public defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingletonSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as SingletonSync<TMapped>;\n }\n\n // --- collection ---\n\n public defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Collection<TMapped>;\n }\n\n public defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollectionSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as CollectionSync<TMapped>;\n }\n\n // --- lazy collection ---\n\n public defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createLazyCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance as LazyCollection<TMapped>;\n }\n\n // --- assets / routes / i18n (no source — built-ins) ---\n\n // --- assets ---\n\n public defineAssets(options?: AssetsOptions | undefined): Assets {\n const { instance, destroy } = createAssetsCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync {\n const { instance, destroy } = createAssetsSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n // --- routes ---\n\n public defineRoutes(options?: RoutesOptions | undefined): Routes {\n const { instance, destroy } = createRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync {\n const { instance, destroy } = createRoutesSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n const { instance, destroy } = createLazyRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineI18nMessages(def: I18nMessageDef): I18nMessages {\n const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);\n\n this._cleanups.push(result.destroy);\n\n return result;\n }\n}\n\nexport function createStore<TSchema extends Schema | undefined = undefined>(\n options: CreateStoreOptions<TSchema>,\n): Store<TSchema> {\n return new Store(options);\n}\n"],"mappings":";;;;;AAMA,MAAa,WAAW;CACtB,OAAO;CACP,KAAK;CACL,OAAO;AACT;AA0BA,MAAM,UAAU,GAAG,QAAQ,SAAS,KAAK;AACzC,MAAM,QAAQ,GAAG,QAAQ,SAAS,GAAG;AACrC,MAAM,UAAU,GAAG,QAAQ,SAAS,KAAK;AAEzC,SAAS,iBAA0B;CACjC,OAAO,QAAQ,kBAAkB,MAAM,kBAAkB,QAAQ;AACnE;AAMA,SA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YAAY,2BAC5B,SACA,KAAK,SACL,KAAK,SAAS,UACd,KAAK,WACL,KAAK,aACP;EAEA,KAAK,UAAU,KAAK,OAAO;EAE3B,OAAO;CACT;CAEA,iBAAwB,SAAqD;EAC3E,MAAM,EAAE,UAAU,YAAY,2BAC5B,SACA,KAAK,SACL,KAAK,SAAS,UACd,KAAK,SACP;EAEA,KAAK,UAAU,KAAK,OAAO;EAE3B,OAAO;CACT;CAEA,mBAA0B,KAAmC;EAC3D,MAAM,SAAS,6BAA6B,KAAK,KAAK,SAAS,KAAK,SAAS,UAAU,KAAK,aAAa;EAEzG,KAAK,UAAU,KAAK,OAAO,OAAO;EAElC,OAAO;CACT;AACF;AAEA,SAAgB,YACd,SACgB;CAChB,OAAO,IAAI,MAAM,OAAO;AAC1B"}
1
+ {"version":3,"file":"index.js","names":["mapFile","mapAsset","storeSchema","maybeThen","storeSchema","storeSchema","maybeThen","storeSchema","storeSchema","maybeThen","maybeThen"],"sources":["../src/generated/graphql.ts","../src/telemetry.ts","../src/utils.ts","../src/assets.ts","../src/dependency-collector.ts","../src/collection.ts","../src/i18n.ts","../src/lru.ts","../src/lazy-assets.ts","../src/lazy-collection.ts","../src/routes-mapping.ts","../src/lazy-routes.ts","../src/model-resolver.ts","../src/routes.ts","../src/singleton.ts","../src/watcher.ts","../src/store.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n/* this file is generated by contello-client — do not edit */\n\nimport type { SourceDef } from '@contello/client';\n\nexport type ContelloAssetKind = 'AUDIO' | 'DOCUMENT' | 'IMAGE' | 'OTHER' | 'VIDEO';\nexport type ContelloAssetRetentionPolicy = 'deleteIfNotUsed' | 'retain';\nexport type ContelloBatchOperationStatus = 'error' | 'success';\nexport type ContelloContentDispositionEnum = 'ATTACHMENT' | 'AUTOMATIC' | 'INLINE';\nexport type ContelloDictionaryType = 'ENTITY' | 'STATIC';\nexport type ContelloMutationType = 'CREATE' | 'DELETE' | 'UPDATE';\nexport type ContelloRouteTargetTypeEnum = 'ENTITY' | 'FILE' | 'REDIRECT' | 'TEXT_RESPONSE';\n\nexport type ContelloAnnotationFilterInput = {\n key?: string | undefined;\n value?: string | undefined;\n};\n\nexport type ContelloAssetAnnotationInput = {\n key: string;\n value: string;\n};\n\nexport type ContelloAssetRequestInput = {\n id?: string | undefined;\n};\n\nexport type ContelloAssetsFilterInput = {\n annotations?: (ContelloAnnotationFilterInput | undefined)[] | undefined;\n collectionReferences?: (string | undefined)[] | undefined;\n ids?: (string | undefined)[] | undefined;\n kinds?: (ContelloAssetKind | undefined)[] | undefined;\n};\n\nexport type ContelloAssetsPaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloAssetUpdateInput = {\n annotations?: ContelloAssetAnnotationInput[] | undefined;\n collectionIds?: string[] | undefined;\n collectionReferenceNames?: string[] | undefined;\n id: string;\n name?: string | undefined;\n retentionPolicy?: ContelloAssetRetentionPolicy | undefined;\n tags?: string[] | undefined;\n};\n\nexport type ContelloEntityRouteInput = {\n path: string;\n};\n\nexport type ContelloI18nMessageInput = {\n description?: string | undefined;\n example?: string | undefined;\n initialTranslations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n token: string;\n translations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n variables?: ContelloI18nMessageVariableInput[] | undefined;\n};\n\nexport type ContelloI18nMessagePaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloI18nMessageTranslationValueInput = {\n language: string;\n message: string;\n};\n\nexport type ContelloI18nMessageVariableInput = {\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloRouteHeaderInput = {\n name: string;\n value: string;\n};\n\nexport type ContelloRouteInput = {\n customHeaders?: (ContelloRouteHeaderInput | undefined)[] | undefined;\n path: string;\n targetEntityConfig?: TargetEntityConfigInput | undefined;\n targetFileConfig?: TargetFileConfig | undefined;\n targetRedirectConfig?: TargetRedirectConfig | undefined;\n targetTextResponseConfig?: TargetTextResponseConfig | undefined;\n targetType: ContelloRouteTargetTypeEnum;\n};\n\nexport type ContelloRouteRequestInput = {\n id?: string | undefined;\n path?: string | undefined;\n};\n\nexport type ContelloRoutesRequestInput = {\n ids?: (string | undefined)[] | undefined;\n paths?: (string | undefined)[] | undefined;\n targetType?: ContelloRouteTargetTypeEnum | undefined;\n};\n\nexport type CreateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id?: string | undefined;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type CreateDummyRequestInput = {\n entity: CreateDummyEntityInput;\n};\n\nexport type DateTimeFilterInput = {\n between?: DateTimeRangeInput | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n greaterThan?: string | undefined;\n greaterThanEqual?: string | undefined;\n lessThan?: string | undefined;\n lessThanEqual?: string | undefined;\n notEqual?: string | undefined;\n};\n\nexport type DateTimeRangeInput = {\n from: string;\n to: string;\n};\n\nexport type DeleteEntityByIdInput = {\n force?: boolean | undefined;\n id: string;\n};\n\nexport type DeleteEntityByIdsInput = {\n ids: string[];\n};\n\nexport type DummiesFilterInput = {\n created?: DateTimeFilterInput | undefined;\n ids?: (string | undefined)[] | undefined;\n name?: StringFilterInput | undefined;\n route?: StringFilterInput | undefined;\n updated?: DateTimeFilterInput | undefined;\n};\n\nexport type DummiesRequestInput = {\n filter?: DummiesFilterInput | undefined;\n pagination?: PaginationInput | undefined;\n};\n\nexport type DummyAttributesInput = {\n dummy?: string | undefined;\n};\n\nexport type GetEntityByIdInput = {\n id: string;\n};\n\nexport type PaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type StringFilterInput = {\n contains?: string | undefined;\n endsWith?: string | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n in?: string[] | undefined;\n notEqual?: string | undefined;\n notIn?: string[] | undefined;\n startsWith?: string | undefined;\n};\n\nexport type TargetEntityConfigInput = {\n entityId: string;\n entityModelId: string;\n};\n\nexport type TargetFileConfig = {\n assetId: string;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type TargetRedirectConfig = {\n location: string;\n responseCode: number;\n};\n\nexport type TargetTextResponseConfig = {\n content: string;\n mimeType: string;\n};\n\nexport type UpdateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id: string;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type UpdateDummyRequestInput = {\n entity: UpdateDummyEntityInput;\n};\n\nexport type ContelloAsset = {\n __typename?: 'ContelloAsset' | undefined;\n annotations: ContelloAssetAnnotation[];\n createdAt: string;\n id: string;\n optimized: ContelloOptimizedFile[];\n original: ContelloFile;\n preview?: ContelloFile | undefined;\n updatedAt: string;\n};\n\nexport type ContelloAssetAnnotation = {\n __typename?: 'ContelloAssetAnnotation' | undefined;\n key: string;\n value: string;\n};\n\nexport type ContelloAssetDeleteResponse = {\n __typename?: 'ContelloAssetDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloBatchOperationResponse = {\n __typename?: 'ContelloBatchOperationResponse' | undefined;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloDictionary = {\n __typename?: 'ContelloDictionary' | undefined;\n createdAt: string;\n description?: string | undefined;\n id: string;\n items?: (string | undefined)[] | undefined;\n name: string;\n referenceName: string;\n type: ContelloDictionaryType;\n updatedAt: string;\n};\n\nexport type ContelloEntityDeleteResponse = {\n __typename?: 'ContelloEntityDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloEntityModel = {\n __typename?: 'ContelloEntityModel' | undefined;\n description: string;\n id: string;\n isRoutable: boolean;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloI18nMessage = {\n __typename?: 'ContelloI18nMessage' | undefined;\n collectionId: string;\n createdAt: string;\n deprecated: boolean;\n description?: string | undefined;\n example?: string | undefined;\n id: string;\n token: string;\n translations: ContelloI18nMessageTranslation[];\n updatedAt: string;\n variables?: ContelloI18nMessageVariable[] | undefined;\n};\n\nexport type ContelloI18nMessagePagination = {\n __typename?: 'ContelloI18nMessagePagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type ContelloI18nMessageRegisterResponse = {\n __typename?: 'ContelloI18nMessageRegisterResponse' | undefined;\n ids: string[];\n};\n\nexport type ContelloI18nMessagesResponse = {\n __typename?: 'ContelloI18nMessagesResponse' | undefined;\n items: ContelloI18nMessage[];\n pagination: ContelloI18nMessagePagination;\n};\n\nexport type ContelloI18nMessageTranslation = {\n __typename?: 'ContelloI18nMessageTranslation' | undefined;\n language: string;\n value: string;\n};\n\nexport type ContelloI18nMessageUpdate = {\n __typename?: 'ContelloI18nMessageUpdate' | undefined;\n message: ContelloI18nMessage;\n mutation: ContelloMutation;\n};\n\nexport type ContelloI18nMessageVariable = {\n __typename?: 'ContelloI18nMessageVariable' | undefined;\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloImageMetadata = {\n __typename?: 'ContelloImageMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloImageOptimizationConfig = {\n __typename?: 'ContelloImageOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type ContelloMutation = {\n __typename?: 'ContelloMutation' | undefined;\n type: ContelloMutationType;\n};\n\nexport type ContelloOptimizedFile = {\n __typename?: 'ContelloOptimizedFile' | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n optimizationConfig?: ContelloOptimizationConfig | undefined;\n uid: string;\n};\n\nexport type ContelloProject = {\n __typename?: 'ContelloProject' | undefined;\n description: string;\n id: string;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloRoute = {\n __typename?: 'ContelloRoute' | undefined;\n createdAt: string;\n customHeaders: ContelloRouteHeader[];\n id: string;\n path: string;\n target: ContelloRouteTarget;\n updatedAt: string;\n};\n\nexport type ContelloRouteHeader = {\n __typename?: 'ContelloRouteHeader' | undefined;\n name: string;\n value: string;\n};\n\nexport type ContelloRouteTargetAsset = {\n __typename?: 'ContelloRouteTargetAsset' | undefined;\n asset: ContelloAsset;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type ContelloRouteTargetEntity = {\n __typename?: 'ContelloRouteTargetEntity' | undefined;\n entity?: ContelloEntityBase | undefined;\n};\n\nexport type ContelloRouteTargetRedirect = {\n __typename?: 'ContelloRouteTargetRedirect' | undefined;\n location: string;\n responseCode: number;\n};\n\nexport type ContelloRouteTargetText = {\n __typename?: 'ContelloRouteTargetText' | undefined;\n content: string;\n mimeType: string;\n};\n\nexport type ContelloRouteUpdate = {\n __typename?: 'ContelloRouteUpdate' | undefined;\n mutation: ContelloMutation;\n route: ContelloRoute;\n};\n\nexport type ContelloUpdateBatch = {\n __typename?: 'ContelloUpdateBatch' | undefined;\n events: ContelloUpdateEvent[];\n};\n\nexport type ContelloUpdateEvent = {\n __typename?: 'ContelloUpdateEvent' | undefined;\n mutation: ContelloMutation;\n prev?: ContelloUpdatePrev | undefined;\n target: ContelloUpdateTarget;\n};\n\nexport type ContelloVideoMetadata = {\n __typename?: 'ContelloVideoMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloVideoOptimizationConfig = {\n __typename?: 'ContelloVideoOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type DummiesResponseCollection = {\n __typename?: 'DummiesResponseCollection' | undefined;\n entities: DummyEntity[];\n pagination: Pagination;\n};\n\nexport type DummyAttributes = {\n __typename?: 'DummyAttributes' | undefined;\n dummy?: string | undefined;\n};\n\nexport type DummyEntity = {\n __typename?: 'DummyEntity' | undefined;\n __model?: 'dummy' | undefined;\n attributes: DummyAttributes;\n createdAt: string;\n id: string;\n internalName: string;\n modelId: string;\n routes: ContelloRoute[];\n updatedAt: string;\n};\n\nexport type DummyEntityUpdate = {\n __typename?: 'DummyEntityUpdate' | undefined;\n entity: DummyEntity;\n mutation: ContelloMutation;\n};\n\nexport type Pagination = {\n __typename?: 'Pagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type PingResult = {\n __typename?: 'PingResult' | undefined;\n response: string;\n};\n\nexport type RootMutation = {\n __typename?: 'RootMutation' | undefined;\n createContelloRoute?: ContelloRoute | undefined;\n createContelloRoutes?: ContelloRoute[] | undefined;\n createDummies?: DummyEntity[] | undefined;\n createDummy?: DummyEntity | undefined;\n deleteContelloAsset: ContelloAssetDeleteResponse;\n deleteContelloRoute: string;\n deleteDummies?: ContelloEntityDeleteResponse[] | undefined;\n deleteDummy: ContelloEntityDeleteResponse;\n registerContelloI18nMessages?: ContelloI18nMessageRegisterResponse | undefined;\n truncateContelloRoutes?: ContelloBatchOperationResponse | undefined;\n truncateDummies?: ContelloBatchOperationResponse | undefined;\n updateContelloAsset?: ContelloAsset | undefined;\n updateContelloRoute?: ContelloRoute | undefined;\n updateDummies?: DummyEntity[] | undefined;\n updateDummy?: DummyEntity | undefined;\n};\n\nexport type RootQuery = {\n __typename?: 'RootQuery' | undefined;\n contelloAsset?: ContelloAsset | undefined;\n contelloAssets?: (ContelloAsset | undefined)[] | undefined;\n contelloDictionaries?: (ContelloDictionary | undefined)[] | undefined;\n contelloEntityModels?: (ContelloEntityModel | undefined)[] | undefined;\n contelloI18nMessages?: ContelloI18nMessagesResponse | undefined;\n contelloPing: PingResult;\n contelloProject?: ContelloProject | undefined;\n contelloRoute?: ContelloRoute | undefined;\n contelloRoutes?: (ContelloRoute | undefined)[] | undefined;\n dummies: DummiesResponseCollection;\n dummy?: DummyEntity | undefined;\n};\n\nexport type RootSubscription = {\n __typename?: 'RootSubscription' | undefined;\n contelloAssets?: ContelloAsset | undefined;\n contelloAssetsBatch: ContelloAsset[];\n contelloI18nMessages?: ContelloI18nMessage | undefined;\n contelloI18nMessagesBatch: ContelloI18nMessage[];\n contelloI18nMessageUpdates?: ContelloI18nMessageUpdate | undefined;\n contelloRoutes?: ContelloRoute | undefined;\n contelloRoutesBatch: ContelloRoute[];\n contelloRouteUpdates?: ContelloRouteUpdate | undefined;\n contelloUpdates?: ContelloUpdateEvent | undefined;\n contelloUpdatesBatch?: ContelloUpdateBatch | undefined;\n dummies?: DummyEntity | undefined;\n dummiesBatch: DummyEntity[];\n dummyUpdates?: DummyEntityUpdate | undefined;\n};\n\nexport type ContelloEntityBase = {\n __typename?: string | undefined;\n createdAt: string;\n id: string;\n updatedAt: string;\n};\n\nexport type ContelloFile = {\n __typename?: string | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n uid: string;\n};\n\nexport type ContelloEntity = DummyEntity;\nexport type ContelloFileMetadata = ContelloImageMetadata | ContelloVideoMetadata;\nexport type ContelloOptimizationConfig = ContelloImageOptimizationConfig | ContelloVideoOptimizationConfig;\nexport type ContelloRouteTarget = ContelloRouteTargetAsset | ContelloRouteTargetEntity | ContelloRouteTargetRedirect | ContelloRouteTargetText;\nexport type ContelloUpdatePrev = ContelloRoute;\nexport type ContelloUpdateTarget = ContelloAsset | ContelloI18nMessage | ContelloRoute | DummyEntity;\n\nexport type MediaFileFragment = {\n uid: string;\n mimeType: string;\n metadata?: {\n __typename: 'ContelloImageMetadata';\n width: number;\n height: number;\n } | {\n __typename: 'ContelloVideoMetadata';\n width: number;\n height: number;\n } | undefined;\n};\n\nexport type MediaAssetFragment = {\n id: string;\n original: MediaFileFragment;\n preview?: MediaFileFragment | undefined;\n optimized: (MediaFileFragment & ({\n __typename: 'ContelloOptimizedFile';\n optimizationConfig?: {\n __typename: 'ContelloImageOptimizationConfig';\n name: string;\n } | undefined;\n }))[];\n};\n\nexport type StoreFileFragment = MediaFileFragment;\n\nexport type StoreAssetFragment = MediaAssetFragment;\n\nexport type StoreI18nMessageFragment = {\n id: string;\n token: string;\n description?: string | undefined;\n example?: string | undefined;\n translations: ({\n language: string;\n value: string;\n })[];\n};\n\nexport type StoreRouteFragment = {\n id: string;\n path: string;\n target: {\n __typename: 'ContelloRouteTargetEntity';\n entity?: {\n __typename: string;\n id: string;\n } | undefined;\n } | {\n __typename: 'ContelloRouteTargetAsset';\n asset: {\n id: string;\n original: {\n uid: string;\n mimeType: string;\n };\n };\n contentDisposition: ContelloContentDispositionEnum;\n } | {\n __typename: 'ContelloRouteTargetRedirect';\n location: string;\n responseCode: number;\n } | {\n __typename: 'ContelloRouteTargetText';\n content: string;\n mimeType: string;\n };\n customHeaders: ({\n name: string;\n value: string;\n })[];\n};\n\nexport type StoreRegisterI18nMessagesMutation = {\n registerContelloI18nMessages?: {\n ids: string[];\n } | undefined;\n};\n\nexport type StoreRegisterI18nMessagesMutationVariables = {\n collection: string;\n messages: ContelloI18nMessageInput[];\n};\n\nexport type StoreWatchUpdatesSubscription = {\n contelloUpdatesBatch?: {\n events: ({\n target: {\n id: string;\n } & ({\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | {\n __typename: 'ContelloAsset';\n id: string;\n } | {\n __typename: 'ContelloI18nMessage';\n id: string;\n token: string;\n });\n prev?: {\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | undefined;\n mutation: {\n type: ContelloMutationType;\n };\n })[];\n } | undefined;\n};\n\nexport type StoreWatchUpdatesSubscriptionVariables = Record<string, never>;\n\nconst MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {\n id\n original {\n ...MediaFile\n }\n preview {\n ...MediaFile\n }\n optimized {\n ...MediaFile\n ... on ContelloOptimizedFile {\n optimizationConfig {\n ... on ContelloImageOptimizationConfig {\n name\n }\n }\n }\n }\n}`;\nconst MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {\n uid\n mimeType\n metadata {\n ... on ContelloImageMetadata {\n width\n height\n }\n ... on ContelloVideoMetadata {\n width\n height\n }\n }\n}`;\nconst StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {\n ...MediaAsset\n}`;\nconst StoreFileFragmentSchema = `fragment StoreFile on ContelloFile {\n ...MediaFile\n}`;\nconst StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {\n id\n token\n description\n example\n translations {\n language\n value\n }\n}`;\nconst StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {\n id\n path\n target {\n __typename\n ... on ContelloRouteTargetEntity {\n entity {\n __typename\n ... on ContelloEntityBase {\n id\n }\n }\n }\n ... on ContelloRouteTargetAsset {\n asset {\n id\n original {\n uid\n mimeType\n }\n }\n contentDisposition\n }\n ... on ContelloRouteTargetRedirect {\n location\n responseCode\n }\n ... on ContelloRouteTargetText {\n content\n mimeType\n }\n }\n customHeaders {\n name\n value\n }\n}`;\n\nexport const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {\n registerContelloI18nMessages(\n collectionReferenceName: $collection\n messages: $messages\n deprecateUnmentioned: true\n ) {\n ids\n }\n}`;\nexport const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}\nsubscription StoreWatchUpdates {\n contelloUpdatesBatch {\n events {\n target {\n __typename\n ... on ContelloEntityBase {\n id\n }\n ... on ContelloRoute {\n ...StoreRoute\n }\n ... on ContelloAsset {\n id\n }\n ... on ContelloI18nMessage {\n id\n token\n }\n }\n prev {\n __typename\n ... on ContelloRoute {\n ...StoreRoute\n }\n }\n mutation {\n type\n }\n }\n }\n}`;\n\nexport type Operations = {\n storeRegisterI18nMessages: {\n document: string;\n kind: 'mutation';\n __result?: StoreRegisterI18nMessagesMutation | undefined;\n __variables?: StoreRegisterI18nMessagesMutationVariables | undefined;\n };\n storeWatchUpdates: {\n document: string;\n kind: 'subscription';\n __result?: StoreWatchUpdatesSubscription | undefined;\n __variables?: StoreWatchUpdatesSubscriptionVariables | undefined;\n };\n};\n\nexport type Sources = {\n storeAsset: SourceDef<'storeAsset', 'asset', StoreAssetFragment>;\n storeI18nMessage: SourceDef<'storeI18nMessage', 'i18nMessage', StoreI18nMessageFragment>;\n storeRoute: SourceDef<'storeRoute', 'route', StoreRouteFragment>;\n};\n\nconst operations: Operations = {\n storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: 'mutation' },\n storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: 'subscription' },\n};\n\nconst sources: Sources = {\n storeAsset: {\n document: `${MediaFileFragmentSchema}\n${MediaAssetFragmentSchema}\n${StoreAssetFragmentSchema}`,\n fragment: 'StoreAsset',\n subscription: 'contelloAssetsBatch',\n __model: 'storeAsset',\n __cardinality: 'asset',\n },\n storeI18nMessage: {\n document: StoreI18nMessageFragmentSchema,\n fragment: 'StoreI18nMessage',\n subscription: 'contelloI18nMessagesBatch',\n __model: 'storeI18nMessage',\n __cardinality: 'i18nMessage',\n },\n storeRoute: {\n document: StoreRouteFragmentSchema,\n fragment: 'StoreRoute',\n subscription: 'contelloRoutesBatch',\n __model: 'storeRoute',\n __cardinality: 'route',\n },\n};\n\nconst models = {\n dummy: 'DummyEntity',\n} as const;\n\nexport const schema = { operations, sources, models };\nexport type Schema = typeof schema;","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/store');\n","import { type AsyncIterableSubject, createAsyncIterableSubject, retryWithBackoff } from '@entwico/dash/async';\n\n/**\n * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)\n * use it as the interval for a periodic full refresh; lazy stores use it as the per-item\n * LRU eviction window. 3 hours.\n */\nexport const DEFAULT_TTL_MS = 3 * 60 * 60 * 1000;\n\n/**\n * default `cache.max` (LRU capacity) for lazy stores — the maximum number of items kept\n * before least-recently-used eviction.\n */\nexport const DEFAULT_LRU_MAX = 1000;\n\n/**\n * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime\n * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.\n */\nexport function resolveTtl(ttl: number | false | undefined): number | undefined {\n if (ttl === undefined) return DEFAULT_TTL_MS;\n if (ttl === false || ttl <= 0) return undefined;\n\n return ttl;\n}\n\n/**\n * creates a coalescing refresh scheduler with exponential-backoff retry on failure.\n *\n * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,\n * it is queued as pending — the queued slot keeps the latest `kind` passed via\n * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh\n * starts, with that latest kind — collapsing any number of intermediate requests into one.\n *\n * on error, retries indefinitely with exponential backoff. the projected value keeps serving\n * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that\n * triggered the just-completed refresh.\n */\nexport function createRefresher<K>(\n fn: () => Promise<unknown>,\n onRefreshed: (kind: K) => void,\n onStart: () => void,\n): (kind: K) => void {\n let refreshing = false;\n let inFlightKind: K | undefined;\n let pendingKind: { kind: K } | undefined;\n\n function scheduleRefresh(kind: K): void {\n if (refreshing) {\n pendingKind = { kind };\n\n return;\n }\n\n refreshing = true;\n inFlightKind = kind;\n onStart?.();\n\n void retryWithBackoff(fn).then(() => {\n const finished = inFlightKind as K;\n\n refreshing = false;\n inFlightKind = undefined;\n onRefreshed(finished);\n\n if (pendingKind) {\n const { kind: next } = pendingKind;\n\n pendingKind = undefined;\n scheduleRefresh(next);\n }\n });\n }\n\n return scheduleRefresh;\n}\n\n/**\n * Refresh channel: bundles the `refresh$` multicast stream and the `onRefresh` callback\n * so both fire on every emission. Used by every eager and lazy store that exposes refresh\n * events.\n */\nexport type RefreshChannel<TEvent> = {\n readonly stream$: AsyncIterableSubject<TEvent>;\n emit(event: TEvent): void;\n complete(): void;\n};\n\nexport function createRefreshChannel<TEvent>(\n onRefresh?: ((event: TEvent) => void) | undefined,\n): RefreshChannel<TEvent> {\n const stream$ = createAsyncIterableSubject<TEvent>();\n\n return {\n stream$,\n emit(event) {\n stream$.next(event);\n onRefresh?.(event);\n },\n complete() {\n stream$.complete();\n },\n };\n}\n\n/**\n * TTL orchestrator: owns the safety-net timer for eager stores. Calls into `run` after\n * `ttl` ms have passed since the last `mark()` (or `reset()`); `run` is responsible for\n * actually fetching + re-arming via another `mark()` once it succeeds. `clear()` cancels\n * the timer on destroy. When `ttl` is undefined the orchestrator is a no-op.\n */\nexport type TtlOrchestrator = {\n /** start (or restart) the timer. consumers call this on first successful full fetch and after every later one. */\n mark(): void;\n /** cancel any pending timer; for destroy. */\n clear(): void;\n};\n\nexport function createTtlOrchestrator(options: { ttl: number | undefined; run: () => void }): TtlOrchestrator {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return {\n mark() {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n\n if (options.ttl === undefined) {\n return;\n }\n\n timer = setTimeout(options.run, options.ttl);\n },\n clear() {\n if (timer === undefined) {\n return;\n }\n\n clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n\n/**\n * FIFO queue for ttl-fired refreshes on eager stores.\n * Concurrency is fixed at 1 to avoid DDOSing the server\n */\nexport type RefreshByTtlQueue = {\n enqueue(task: () => Promise<unknown>): void;\n};\n\nexport function createRefreshByTtlQueue(): RefreshByTtlQueue {\n const waiting: (() => Promise<unknown>)[] = [];\n let running = false;\n\n function next(): void {\n if (running) return;\n\n const task = waiting.shift();\n\n if (!task) return;\n\n running = true;\n\n void (async () => {\n try {\n await task();\n } catch {\n // misbehaving task — keep the queue draining\n } finally {\n running = false;\n next();\n }\n })();\n }\n\n return {\n enqueue(task) {\n waiting.push(task);\n next();\n },\n };\n}\n","import {\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceSubscription,\n} from '@contello/client';\nimport type { MaybePromise, ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport type { StoreAsset, StoreFile } from './lazy-assets';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type AssetsOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type AssetsSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type Assets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreAsset>>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n};\n\nexport type AssetsSync = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreAsset> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreAsset>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createAssetsCollection(\n options: AssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Assets> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await concatAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n const items = rawItems.map((item) => mapAsset(item));\n\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((a) => a.id));\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.asset.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.asset) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n projected.clear();\n\n return;\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n const instance: Assets = {\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data, meta, options) {\n return client.upload(data, meta, options);\n },\n\n download(fileId) {\n return client.download(fileId);\n },\n\n proxyHls(path, signal) {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createAssetsSyncCollection(\n options: AssetsSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<AssetsSync> {\n const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n },\n destroy,\n };\n}\n","import type { ModelResolver } from './model-resolver';\nimport type { UpdateEvent } from './watcher';\n\ntype NonEntityTarget = Exclude<UpdateEvent['target'], 'entity'>;\n\n/**\n * passed to `map()` so the mapper can declare which external entities this item depends on.\n * calls are collected during mapping and indexed once the item key is known.\n * designed to be destructurable: `map(raw, { track, trackRoute }) => ...`\n *\n * `track()` inspects `__typename` to auto-detect the dependency type:\n * - `ContelloAsset` → asset dep\n * - `ContelloRoute` → route dep\n * - `*Entity` → entity dep\n * - anything else → throws\n *\n * explicit methods (`trackEntity`, `trackAsset`, `trackRoute`) are available\n * for cases where only an id is known without the full GraphQL object.\n */\nexport type MapperContext<TModels extends string = string> = {\n track(obj: { __typename: string; id: string }): void;\n trackEntity(typename: TModels, id: string): void;\n trackAsset(id: string): void;\n trackRoute(id: string): void;\n};\n\n// shared empty result so the hot path (an event no item depends on) allocates\n// nothing — callers only ever iterate or read `.size`, never mutate.\nconst EMPTY_KEYS: ReadonlySet<never> = new Set();\n\n// dep key for non-entity targets (route, asset) — `${target}\\0${id}`\nfunction createDependencyKey(target: NonEntityTarget, id: string): string {\n return `${target}\\0${id}`;\n}\n\n// dep key for entity deps — prefixed with `entity\\0` to avoid collisions with other targets\n// e.g. a model named 'route' would otherwise collide with ref.route() deps\nfunction createEntityDependencyKey(typename: string, id: string): string {\n return `entity\\0${typename}\\0${id}`;\n}\n\n// key used to register and look up route-target interest deps.\n// separate from createDependencyKey because the value is a compound (typename \\0 id) pair itself.\nfunction createRouteTargetKey(typename: string, id: string): string {\n return `routeTarget\\0${typename}\\0${id}`;\n}\n\n/**\n * bidirectional dependency index for a single collection.\n *\n * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper\n * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes\n * once the item key is known. `register` flushes the collected deps into two maps:\n *\n * forwardIndex: item key -> set of dep keys it declared\n * reverseIndex: dep key -> set of item keys that declared it\n *\n * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`\n * looks up the dep key and returns all item keys that need to be invalidated.\n *\n * lifecycle per map cycle:\n * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)\n * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array\n * 3. fn calls register(key) — real item key is known, deps written into both maps\n */\nexport class DependencyCollector<TKey, TModels extends string = string> {\n /** dep key -> item keys that declared a dependency on it */\n private reverseIndex = new Map<string, Set<TKey>>();\n /** item key -> dep keys it currently declares */\n private forwardIndex = new Map<TKey, Set<string>>();\n\n constructor(\n /** the model name of the owning collection, used to form route-target dep keys */\n private readonly model: string,\n /** resolver for mapping between model names and __typename */\n private readonly resolver: ModelResolver,\n ) {}\n\n private mergeRouteTargetKeys(\n existing: Set<TKey> | undefined,\n entityType: string,\n entityId: string,\n ): Set<TKey> | undefined {\n const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));\n\n if (!items) {\n return existing;\n }\n\n return existing ? existing.union(items) : items;\n }\n\n private warnIfUnknownModel(model: string): void {\n if (!this.resolver.hasModel(model)) {\n console.warn(\n `[contello/store] tracking model \"${model}\" which is not in models — updates for this model will be ignored`,\n );\n }\n }\n\n /**\n * removes all index entries for one item key.\n * cleans up the forward entry and removes the item from every reverse set it appeared in.\n * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.\n */\n private clearItem(key: TKey): void {\n const existingDeps = this.forwardIndex.get(key);\n\n if (!existingDeps) {\n return;\n }\n\n for (const dk of existingDeps) {\n const set = this.reverseIndex.get(dk);\n\n if (set) {\n set.delete(key);\n\n if (set.size === 0) {\n this.reverseIndex.delete(dk);\n }\n }\n }\n\n this.forwardIndex.delete(key);\n }\n\n /**\n * creates a scoped MapperContext for one item and runs `fn` with it.\n * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function\n * that must be called once the item key is known — it writes all declared deps into the index.\n * returns whatever `fn` returns, preserving MaybePromise semantics.\n */\n createContext<T>(fn: (ctx: MapperContext<TModels>, register: (key: TKey) => void) => T): T {\n const deps: string[] = [];\n\n const ctx: MapperContext<TModels> = {\n track: (obj) => {\n if (!obj.id) {\n throw new Error(`track(): object with __typename \"${obj.__typename}\" has no \"id\" field`);\n }\n\n switch (obj.__typename) {\n case 'ContelloAsset': {\n deps.push(createDependencyKey('asset', obj.id));\n break;\n }\n case 'ContelloRoute': {\n deps.push(createDependencyKey('route', obj.id));\n break;\n }\n default: {\n const model = this.resolver.getModel(obj.__typename);\n\n if (!model) {\n throw new Error(\n `track(): unexpected __typename \"${obj.__typename}\" — expected ContelloAsset, ContelloRoute, or a known entity model`,\n );\n }\n\n deps.push(createEntityDependencyKey(model, obj.id));\n }\n }\n },\n trackEntity: (model, id) => {\n this.warnIfUnknownModel(model);\n deps.push(createEntityDependencyKey(model, id));\n },\n trackAsset: (id) => {\n deps.push(createDependencyKey('asset', id));\n },\n trackRoute: (id) => {\n deps.push(createDependencyKey('route', id));\n },\n };\n\n const register = (key: TKey) => {\n this.clearItem(key);\n\n deps.push(createRouteTargetKey(this.model, String(key)));\n\n const fwd = new Set<string>();\n\n for (const dk of deps) {\n fwd.add(dk);\n\n let set = this.reverseIndex.get(dk);\n\n if (!set) {\n set = new Set();\n this.reverseIndex.set(dk, set);\n }\n\n set.add(key);\n }\n\n if (fwd.size > 0) {\n this.forwardIndex.set(key, fwd);\n }\n };\n\n return fn(ctx, register);\n }\n\n /**\n * looks up which item keys are affected by an update event.\n * for route events, checks route-target deps for both the new and previous entity targets.\n */\n getAffectedKeys(event: UpdateEvent): ReadonlySet<TKey> {\n if (event.target === 'entity') {\n return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;\n }\n\n let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));\n\n if (event.target === 'route') {\n if ('after' in event && event.after.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);\n }\n }\n\n return affected ?? EMPTY_KEYS;\n }\n\n /** removes all recorded deps for a single item (called on eviction) */\n removeItem(key: TKey): void {\n this.clearItem(key);\n }\n\n /** drops all recorded deps — used when clearing the entire cache */\n clear(): void {\n this.reverseIndex.clear();\n this.forwardIndex.clear();\n }\n\n /**\n * removes index entries for any item key NOT present in `keys`.\n * called after a full re-fetch to prune refs from items that were deleted upstream.\n */\n retainOnly(keys: Set<TKey>): void {\n for (const key of this.forwardIndex.keys()) {\n if (!keys.has(key)) {\n this.clearItem(key);\n }\n }\n }\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n Created,\n ExtractSourceResult,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nfunction fetchCollection<S extends SourceDef<string, 'entity'>>(\n source: S,\n client: ContelloClient<any>,\n ids: string[] | undefined,\n): Promise<ExtractSourceResult<S>[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<S>[] }>(createSourceSubscription(source), { ids }),\n (r) => r.source,\n ),\n );\n}\n\nexport function createCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Collection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const projected = new ProjectedMap<string, TMapped>({\n key: (item) => item.id,\n values: (ids) =>\n wrap(`collection:${_def.name}`, () =>\n maybeThen(fetchCollection(source, client, ids), async (rawItems) => {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const items = await Promise.all(\n rawItems.map((item) =>\n Promise.resolve(\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n );\n\n if (ids === undefined) {\n dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((item) => item.id));\n }\n } else {\n const returnedIds = new Set(items.map((item) => item.id));\n\n for (const id of ids) {\n if (!returnedIds.has(id)) {\n dependencyCollector.removeItem(id);\n }\n }\n }\n\n return items;\n }),\n ),\n sort: opts.sort,\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const ownEvents = batch.entity.get(_def.model) ?? [];\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of ownEvents) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n const depAffected = new Set<string>();\n\n for (const event of batch.events) {\n for (const id of dependencyCollector.getAffectedKeys(event)) {\n depAffected.add(id);\n }\n }\n\n if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n for (const id of deleted) {\n dependencyCollector.removeItem(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n const refreshIds = upserted.union(depAffected);\n\n for (const id of deleted) {\n refreshIds.delete(id);\n }\n\n runPartialRefresh([...refreshIds], deleted);\n });\n\n const instance: Collection<TMapped> = {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll(): MaybePromise<ReadonlyArray<ReadonlyDeep<TMapped>>> {\n return projected.getAll();\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createCollectionSync<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<CollectionSync<TMapped>> {\n const { instance: base, destroy } = createCollection<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`collection \"${base.name}\".${method}() is not initialized yet — call collection.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getAll(): ReadonlyArray<ReadonlyDeep<TMapped>> {\n return assertSync(base.getAll(), 'getAll');\n },\n },\n destroy,\n };\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport {\n type ContelloI18nMessageInput,\n type StoreI18nMessageFragment,\n type StoreRegisterI18nMessagesMutation,\n storeRegisterI18nMessagesDocument,\n schema as storeSchema,\n} from './generated/graphql';\nimport { wrap } from './telemetry';\nimport type { RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\n\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type I18nTranslation = {\n language: string;\n value: string;\n};\n\nexport type I18nVariableInput = {\n name: string;\n description: string;\n example: string;\n};\n\nexport type I18nInitialTranslation = {\n language: string;\n message: string;\n};\n\nexport type I18nMessageRegistrationDefinition = {\n token: string;\n example?: string | undefined;\n description?: string | undefined;\n variables?: I18nVariableInput[] | undefined;\n /** always overwrites existing translations for this token */\n translations?: I18nInitialTranslation[] | undefined;\n /** only applied when the token is newly registered (existing translations are preserved) */\n initialTranslations?: I18nInitialTranslation[] | undefined;\n};\n\nexport type I18nMessageDef = {\n collection: string;\n cache?: SyncCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type I18nMessage = {\n id: string;\n token: string;\n translations: Map<string, string>;\n};\n\nexport type I18nMessages = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): MaybePromise<ReadonlyDeep<I18nMessage> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n getAll(): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n register(messages: I18nMessageRegistrationDefinition[]): Promise<void>;\n refresh(): void;\n /** Completes refresh$ and detaches from the watcher — called by `Store.destroy()`. */\n destroy(): void;\n};\n\nfunction toGqlMessageInput(msg: I18nMessageRegistrationDefinition): ContelloI18nMessageInput {\n return {\n token: msg.token,\n example: msg.example,\n description: msg.description,\n variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),\n translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),\n initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message })),\n };\n}\n\nexport function createI18nMessagesCollection(\n def: I18nMessageDef,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): I18nMessages {\n const channel = createRefreshChannel<RefreshEvent>(def.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });\n let loaded = false;\n\n const i18nSourceDoc = createSourceSubscription(storeSchema.sources.storeI18nMessage);\n\n const projected = new ProjectedMap<string, I18nMessage>({\n key: (msg) => msg.id,\n values: (ids) =>\n wrap(`i18n:${def.collection}`, async () => {\n const msgs = await concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreI18nMessageFragment[] }>(i18nSourceDoc, {\n collection: def.collection,\n ids,\n }),\n (data) => data.source,\n ),\n );\n const items: I18nMessage[] = msgs.map((msg) => ({\n id: msg.id,\n token: msg.token,\n translations: new Map(msg.translations.map((t) => [t.language, t.value])),\n }));\n\n // start tracking refresh by ttl on first successful full fetch\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function emitWithCurrentIds(kind: RefreshKind): void {\n maybeThen(projected.getAll(), (msgs) => {\n emit(\n msgs.map((m) => m.id),\n kind,\n );\n });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await retryWithBackoff(() => projected.refresh());\n emitWithCurrentIds('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emitWithCurrentIds(kind);\n ttl.mark();\n },\n () => {},\n );\n\n function runPartialRefresh(upsertedIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...upsertedIds, ...deletedIds])];\n\n if (changedIds.length === 0) {\n return;\n }\n\n if (upsertedIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retryWithBackoff(async () => {\n await projected.refresh(upsertedIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n if (batch.i18nMessage.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.i18nMessage) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n return {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll() {\n return projected.getAll();\n },\n\n register(messages: I18nMessageRegistrationDefinition[]) {\n return wrap(`i18n-register:${def.collection}`, async () => {\n await client.execute<StoreRegisterI18nMessagesMutation>(storeRegisterI18nMessagesDocument, {\n collection: def.collection,\n messages: messages.map((message) => toGqlMessageInput(message)),\n });\n });\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n","import type { ProjectedMapCache } from '@entwico/projected';\nimport { LRUCache } from 'lru-cache';\n\nexport type LruCache<TKey, TValue> = ProjectedMapCache<TKey, TValue> & {\n keys: () => TKey[];\n};\n\nexport function createLruCache<TKey, TValue>(options: {\n max: number;\n ttl: number | undefined;\n onEvict: ((value: TValue, key: TKey) => void) | undefined;\n}): LruCache<TKey, TValue> {\n const { max, ttl, onEvict: dispose } = options;\n\n const lru = new LRUCache<any, any>({\n max,\n ...(ttl !== undefined && { ttl, ttlAutopurge: false }),\n ...(dispose !== undefined && { dispose }),\n });\n\n return {\n has: (key) => lru.has(key),\n get: (key) => lru.get(key),\n set: (key, value) => {\n lru.set(key, value);\n },\n delete: (key) => {\n lru.delete(key);\n },\n clear: () => {\n lru.clear();\n },\n keys: () => lru.keys().toArray(),\n };\n}\n","import {\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceSubscription,\n} from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport { createLruCache } from './lru';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type StoreFileMetadata = {\n width: number;\n height: number;\n};\n\nexport type StoreFile = {\n uid: string;\n mimeType: string;\n metadata: StoreFileMetadata | undefined;\n};\n\nexport type StoreAsset = {\n id: string;\n original: StoreFile;\n preview: StoreFile | undefined;\n optimized: StoreFile[];\n};\n\nexport type LazyAssetsOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyAssets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreAsset[]>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n clear(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createLazyAssetsCollection(\n def: LazyAssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n): Created<LazyAssets> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createLruCache<string, StoreAsset>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedLazyMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await concatAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n\n return rawItems.map((item) => mapAsset(item));\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (batch.asset.length === 0) return;\n\n for (const event of batch.asset) {\n projected.delete(event.id);\n }\n\n emit(\n batch.asset.map((e) => e.id),\n 'upstream-update',\n );\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return client.upload(data, meta, options);\n },\n\n download(fileId: string): Promise<DownloadResult> {\n return client.download(fileId);\n },\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { maybeThen } from '@entwico/dash';\nimport {\n type AsyncIterableSubject,\n concatAsync,\n createAsyncIterableSubject,\n mapAsync,\n} from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { DEFAULT_LRU_MAX, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createLazyCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: LazyCollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyCollection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n max: opts.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(opts.cache?.ttl),\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const cache = createLruCache<string, TMapped>({\n max: _def.cache.max,\n ttl: _def.cache.ttl,\n onEvict: (_value, key) => dependencyCollector.removeItem(key),\n });\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedLazyMap<string, TMapped>({\n key: (item) => item.id,\n values: (keys) =>\n wrap(`lazy-collection:${_def.name}`, () =>\n maybeThen(\n concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource>[] }>(createSourceSubscription(source), {\n ids: keys,\n }),\n (r) => r.source,\n ),\n ),\n (rawItems) =>\n Promise.all(\n rawItems.map((item) =>\n Promise.resolve(\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n ),\n ),\n ),\n cache,\n });\n\n const refresh$ = createAsyncIterableSubject<RefreshEvent>();\n\n function emit(ids: string[], kind: RefreshKind): void {\n const event: RefreshEvent = { ids, kind };\n\n refresh$.next(event);\n opts.onRefresh?.(event);\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted = new Set<string>();\n const ownModelEvents = batch.entity.get(_def.model);\n\n if (ownModelEvents) {\n for (const event of ownModelEvents) {\n evicted.add(event.id);\n }\n }\n\n for (const event of batch.events) {\n for (const key of dependencyCollector.getAffectedKeys(event)) {\n evicted.add(key);\n }\n }\n\n if (evicted.size > 0) {\n for (const key of evicted) {\n dependencyCollector.removeItem(key);\n projected.delete(key);\n }\n\n emit([...evicted], 'upstream-update');\n }\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n dependencyCollector.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n refresh$.complete();\n },\n };\n}\n","import type { StoreRouteFragment } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\n\nexport type StoreRouteCustomHeader = {\n name: string;\n value: string;\n};\n\nexport type StoreRoute = {\n id: string;\n path: string;\n customHeaders: StoreRouteCustomHeader[];\n} & (\n | { type: 'redirect'; location: string; status: number }\n | { type: 'text'; content: string; mimeType: string }\n | { type: 'asset'; assetId: string; fileId: string; contentDisposition: 'inline' | 'attachment'; mimeType: string }\n | { type: 'entity'; model: string; entityType: string; entityId: string }\n);\n\nexport function mapRoute(raw: StoreRouteFragment, resolver: ModelResolver): StoreRoute | undefined {\n const base = {\n id: raw.id,\n path: raw.path,\n customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value })),\n };\n\n switch (raw.target.__typename) {\n case 'ContelloRouteTargetRedirect': {\n return {\n ...base,\n type: 'redirect',\n location: raw.target.location,\n status: raw.target.responseCode,\n };\n }\n\n case 'ContelloRouteTargetText': {\n return {\n ...base,\n type: 'text',\n content: raw.target.content,\n mimeType: raw.target.mimeType,\n };\n }\n\n case 'ContelloRouteTargetAsset': {\n return {\n ...base,\n type: 'asset',\n assetId: raw.target.asset.id,\n fileId: raw.target.asset.original.uid,\n contentDisposition: raw.target.contentDisposition === 'INLINE' ? 'inline' : 'attachment',\n mimeType: raw.target.asset.original.mimeType,\n };\n }\n\n case 'ContelloRouteTargetEntity': {\n if (!raw.target.entity) {\n return undefined;\n }\n\n const entityType = raw.target.entity.__typename;\n\n return {\n ...base,\n type: 'entity',\n model: resolver.resolveModel(entityType),\n entityType,\n entityId: raw.target.entity.id,\n };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport { type LruCache, createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type { StoreRoute, StoreRouteCustomHeader } from './routes-mapping';\n\nexport type LazyRoutesOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyRoutes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n getByPath(path: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n refresh(): void;\n clear(): void;\n};\n\n// cache key prefixes — short nullbyte-separated to allow slice(2) extraction without branching\nconst ID_PREFIX = '1\\0';\nconst PATH_PREFIX = '2\\0';\n\n// private symbol used to tag each route with the projected cache key it was requested under,\n// so the key() function can return the right prefixed key for projected to match results back\nconst CACHE_KEY = Symbol('cacheKey');\n\nfunction collectRoutes(\n rawItems: StoreRouteFragment[],\n keyFn: (route: StoreRoute) => string,\n resolver: ModelResolver,\n): StoreRoute[] {\n return rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n (mapped as Record<symbol, string>)[CACHE_KEY] = keyFn(mapped);\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n}\n\n/**\n * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space\n * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.\n *\n * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU\n * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).\n */\nfunction createRoutesCache(max: number, ttl: number | undefined): LruCache<string, StoreRoute> {\n const pathToId = new Map<string, string>();\n // reverse of pathToId, so a route whose path changed can have its previous\n // path entry removed (otherwise getByPath(oldPath) would resolve to the route\n // that no longer lives there)\n const idToPath = new Map<string, string>();\n\n const lru = createLruCache<string, StoreRoute>({\n max,\n ttl,\n onEvict: (route) => {\n pathToId.delete(route.path);\n idToPath.delete(route.id);\n },\n });\n\n function resolveKey(key: string): string {\n if (key.startsWith(PATH_PREFIX)) {\n const id = pathToId.get(key.slice(2));\n\n if (id) {\n return ID_PREFIX + id;\n }\n\n return key; // propagate cache miss if path not found\n }\n\n return key;\n }\n\n return {\n has: (key) => lru.has(resolveKey(key)),\n get: (key) => lru.get(resolveKey(key)),\n\n set: (_key, value) => {\n // always normalise to ID_PREFIX in lru\n // regardless of which key projected passes in\n const previousPath = idToPath.get(value.id);\n\n if (previousPath !== undefined && previousPath !== value.path) {\n pathToId.delete(previousPath);\n }\n\n pathToId.set(value.path, value.id);\n idToPath.set(value.id, value.path);\n lru.set(ID_PREFIX + value.id, value);\n },\n\n delete: (key) => {\n const resolved = resolveKey(key);\n const value = lru.get(resolved);\n\n if (value) {\n pathToId.delete(value.path);\n idToPath.delete(value.id);\n }\n\n lru.delete(resolved);\n },\n\n clear: () => {\n pathToId.clear();\n idToPath.clear();\n lru.clear();\n },\n\n keys: () => lru.keys(),\n };\n}\n\nexport function createLazyRoutesCollection(\n def: LazyRoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyRoutes> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n function fetchRoutes(vars: { ids?: string[]; paths?: string[] }): Promise<StoreRouteFragment[]> {\n return concatAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, vars), (data) => data.source),\n );\n }\n\n const projected = new ProjectedLazyMap<string, StoreRoute>({\n key: (route) => (route as Record<symbol, string>)[CACHE_KEY] ?? ID_PREFIX + route.id,\n values: (prefixedKeys) =>\n wrap('routes', async () => {\n const ids: string[] = [];\n const paths: string[] = [];\n\n for (const key of prefixedKeys) {\n const value = key.slice(2);\n\n if (key.startsWith(ID_PREFIX)) {\n ids.push(value);\n } else {\n paths.push(value);\n }\n }\n\n const [rawByIds, rawByPaths] = await Promise.all([\n ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve<StoreRouteFragment[]>([]),\n paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve<StoreRouteFragment[]>([]),\n ]);\n\n const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);\n const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + r.path, resolver);\n\n return [...byIds, ...byPaths];\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(\n lastRefreshKeys.map((key) => key.slice(2)),\n kind,\n );\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted: string[] = [];\n\n for (const event of batch.route) {\n const idKey = ID_PREFIX + event.id;\n\n if (event.mutation === 'delete') {\n cache.delete(idKey);\n evicted.push(event.id);\n } else {\n if (cache.has(idKey)) {\n cache.set(idKey, event.after);\n }\n\n evicted.push(event.after.path);\n }\n }\n\n if (evicted.length > 0) {\n emit(evicted, 'upstream-update');\n }\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n if (Array.isArray(idOrIds)) {\n return projected.get(idOrIds.map((id) => ID_PREFIX + id));\n }\n\n return projected.get(ID_PREFIX + idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n if (Array.isArray(pathOrPaths)) {\n return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));\n }\n\n return projected.get(PATH_PREFIX + pathOrPaths);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","export class ModelResolver<TModels extends string = string> {\n private _typeNames: ReadonlySet<string> | undefined;\n private _toModel: ReadonlyMap<string, TModels>;\n private _toTypeName: ReadonlyMap<TModels, string>;\n\n constructor(models?: Record<TModels, string> | undefined) {\n const toModel = new Map<string, TModels>();\n const toTypeName = new Map<TModels, string>();\n let typeNames: Set<string> | undefined;\n\n if (models) {\n typeNames = new Set<string>();\n\n for (const [model, typeName] of Object.entries<string>(models)) {\n toModel.set(typeName, model as TModels);\n toTypeName.set(model as TModels, typeName);\n typeNames.add(typeName);\n }\n }\n\n this._typeNames = typeNames;\n this._toModel = toModel;\n this._toTypeName = toTypeName;\n }\n\n hasTypeName(typeName: string): boolean {\n return !this._typeNames || this._typeNames.has(typeName);\n }\n\n getModel(typeName: string): TModels | undefined {\n return this._toModel.get(typeName);\n }\n\n getTypeName(model: TModels): string {\n return this._toTypeName.get(model) ?? model;\n }\n\n hasModel(model: string): boolean {\n return this._toTypeName.size === 0 || this._toTypeName.has(model as TModels);\n }\n\n resolveModel(typeName: string): string {\n return this._toModel.get(typeName) ?? typeName;\n }\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type RoutesOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type RoutesSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type Routes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n getByPath(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n refresh(): void;\n};\n\nexport type RoutesSync = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreRoute> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n getByPath(path: string): ReadonlyDeep<StoreRoute> | undefined;\n getByPath(paths: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n refresh(): void;\n};\n\nexport function createRoutesCollection(\n options: RoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Routes> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n\n // id ↔ path indexes — kept in sync with `projected` by the values callback.\n // any route lookup by path resolves to an id, then the value comes from `projected`.\n const pathById = new Map<string, string>();\n const idByPath = new Map<string, string>();\n let loaded = false;\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n const projected = new ProjectedMap<string, StoreRoute>({\n key: (route) => route.id,\n values: (ids) =>\n wrap('routes', async () => {\n const rawItems = await concatAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, { ids }), (data) => data.source),\n );\n const items = rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n\n if (ids === undefined) {\n pathById.clear();\n idByPath.clear();\n\n for (const r of items) {\n pathById.set(r.id, r.path);\n idByPath.set(r.path, r.id);\n }\n\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((r) => r.id));\n }\n } else {\n const returnedIds = new Set(items.map((r) => r.id));\n\n // requested ids missing from the response = deleted; drop their path entries\n for (const id of ids) {\n if (returnedIds.has(id)) {\n continue;\n }\n\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(oldPath);\n pathById.delete(id);\n }\n }\n\n for (const r of items) {\n const oldPath = pathById.get(r.id);\n\n if (oldPath !== undefined && oldPath !== r.path) {\n idByPath.delete(oldPath);\n }\n\n pathById.set(r.id, r.path);\n idByPath.set(r.path, r.id);\n }\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(() =>\n retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.route.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.route) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n pathById.clear();\n idByPath.clear();\n projected.clear();\n\n return;\n }\n\n for (const id of deleted) {\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(oldPath);\n pathById.delete(id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n function getByIdSingle(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return projected.get(id);\n }\n\n function getByIds(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return projected.get(ids);\n }\n\n function lookupByPathSingle(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return maybeThen(ensureLoaded(), () => {\n const id = idByPath.get(path);\n\n return id === undefined ? undefined : projected.get(id);\n });\n }\n\n function lookupByPaths(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return maybeThen(ensureLoaded(), () => {\n const ids: string[] = [];\n\n for (const p of paths) {\n const id = idByPath.get(p);\n\n if (id !== undefined) {\n ids.push(id);\n }\n }\n\n return projected.get(ids);\n });\n }\n\n function ensureLoaded(): MaybePromise<void> {\n if (loaded) {\n return undefined;\n }\n\n return maybeThen(projected.getAllAsMap(), () => {});\n }\n\n const instance: Routes = {\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return typeof idOrIds === 'string' ? getByIdSingle(idOrIds) : getByIds(idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n return typeof pathOrPaths === 'string' ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createRoutesSyncCollection(\n options: RoutesSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<RoutesSync> {\n const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getByPath(pathOrPaths: string | readonly string[]): any {\n return assertSync(base.getByPath(pathOrPaths as string), 'getByPath');\n },\n },\n destroy,\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, firstAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedValue } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n RefreshKind,\n Singleton,\n SingletonOptions,\n SingletonRefreshEvent,\n SingletonSync,\n SingletonSyncOptions,\n} from './types';\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createSingleton<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Singleton<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const itemKey = `singleton:${_def.name}`;\n const channel = createRefreshChannel<SingletonRefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });\n let loaded = false;\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedValue<TMapped>({\n value: () =>\n wrap(`singleton:${_def.name}`, () =>\n maybeThen(\n firstAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource> }>(createSourceSubscription(source)),\n (r) => r.source,\n ),\n ),\n (raw) =>\n dependencyCollector.createContext((ref, register) =>\n maybeThen(mapFn(raw, ref), (mapped) => {\n register(itemKey);\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.();\n }\n\n return mapped;\n }),\n ),\n ),\n ),\n });\n\n function emit(kind: RefreshKind): void {\n channel.emit({ kind });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await retryWithBackoff(() => projected.refresh());\n emit('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emit(kind);\n ttl.mark();\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const hasOwnModel = batch.entity.has(_def.model);\n const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);\n\n if (!hasOwnModel && !hasAffectedRefs) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n scheduleRefresh('upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(): MaybePromise<ReadonlyDeep<TMapped>> {\n return projected.get();\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.get();\n }\n },\n },\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createSingletonSync<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<SingletonSync<TMapped>> {\n const { instance: base, destroy } = createSingleton<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n return {\n instance: {\n ...base,\n\n get(): ReadonlyDeep<TMapped> {\n const result = base.get();\n\n if (result instanceof Promise) {\n throw new TypeError(`singleton \"${base.name}\" is not initialized yet — call singleton.load() first`);\n }\n\n return result;\n },\n },\n destroy,\n };\n}\n","import type { ContelloClient } from '@contello/client';\nimport { type AsyncIterableSubject, createAsyncIterableSubject, keepalive, mapAsync } from '@entwico/dash/async';\n\nimport {\n type ContelloMutationType,\n type StoreRouteFragment,\n type StoreWatchUpdatesSubscription,\n storeWatchUpdatesDocument,\n} from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\n\nexport type UpdateEvent<TEntityType extends string = string> =\n | { id: string; mutation: 'create'; target: 'route'; after: StoreRoute }\n | { id: string; mutation: 'update'; target: 'route'; after: StoreRoute; before: StoreRoute }\n | { id: string; mutation: 'delete'; target: 'route' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'asset' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'i18nMessage'; token: string }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'entity'; model: TEntityType };\n\nexport type UpdateMutationType = UpdateEvent['mutation'];\n\nexport type UpdateEventFor<T extends UpdateEvent['target']> = Extract<UpdateEvent, { target: T }>;\n\nexport type UpdateBatch = {\n readonly events: UpdateEvent[];\n readonly route: UpdateEventFor<'route'>[];\n readonly asset: UpdateEventFor<'asset'>[];\n readonly i18nMessage: UpdateEventFor<'i18nMessage'>[];\n /** entity events grouped by model typename */\n readonly entity: Map<string, UpdateEventFor<'entity'>[]>;\n /** route events grouped by target entity model (both after and before targets for updates) */\n readonly routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addRouteByModel(\n map: Map<string, UpdateEventFor<'route'>[]>,\n entityType: string,\n event: UpdateEventFor<'route'>,\n): void {\n let list = map.get(entityType);\n\n if (!list) {\n list = [];\n map.set(entityType, list);\n }\n\n list.push(event);\n}\n\ntype MutableBatch = {\n route: UpdateEventFor<'route'>[];\n asset: UpdateEventFor<'asset'>[];\n i18nMessage: UpdateEventFor<'i18nMessage'>[];\n entity: Map<string, UpdateEventFor<'entity'>[]>;\n routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addEventToBatch(batch: MutableBatch, event: UpdateEvent): void {\n switch (event.target) {\n case 'route': {\n batch.route.push(event);\n\n if ('after' in event && event.after.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.after.model, event);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.before.model, event);\n }\n\n break;\n }\n case 'asset': {\n batch.asset.push(event);\n break;\n }\n case 'i18nMessage': {\n batch.i18nMessage.push(event);\n break;\n }\n case 'entity': {\n let list = batch.entity.get(event.model);\n\n if (!list) {\n list = [];\n batch.entity.set(event.model, list);\n }\n\n list.push(event);\n break;\n }\n }\n}\n\nfunction createUpdateBatch(events: UpdateEvent[]): UpdateBatch {\n const batch: MutableBatch = {\n route: [],\n asset: [],\n i18nMessage: [],\n entity: new Map<string, UpdateEventFor<'entity'>[]>(),\n routeByEntityModel: new Map<string, UpdateEventFor<'route'>[]>(),\n };\n\n for (const event of events) {\n addEventToBatch(batch, event);\n }\n\n return {\n events,\n route: batch.route,\n asset: batch.asset,\n i18nMessage: batch.i18nMessage,\n entity: batch.entity,\n routeByEntityModel: batch.routeByEntityModel,\n };\n}\n\ntype RawBatch = NonNullable<StoreWatchUpdatesSubscription['contelloUpdatesBatch']>;\ntype RawEvent = RawBatch['events'][number];\n\nfunction castMutationType(type: ContelloMutationType): UpdateMutationType {\n switch (type) {\n case 'CREATE': {\n return 'create';\n }\n case 'UPDATE': {\n return 'update';\n }\n case 'DELETE': {\n return 'delete';\n }\n }\n}\n\nfunction mapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n const mutation = castMutationType(raw.mutation.type);\n const target = raw.target;\n const { id, __typename } = target;\n\n switch (__typename) {\n case 'ContelloRoute': {\n if (mutation === 'delete') {\n return { id, mutation: 'delete', target: 'route' };\n }\n\n const after = mapRoute(target as StoreRouteFragment, resolver);\n\n if (!after) {\n return undefined;\n }\n\n if (mutation === 'create') {\n return { id, mutation, target: 'route', after };\n }\n\n const before =\n raw.prev?.__typename === 'ContelloRoute'\n ? (mapRoute(raw.prev as StoreRouteFragment, resolver) ?? undefined)\n : undefined;\n\n if (!before) {\n return undefined;\n }\n\n return { id, mutation, target: 'route', after, before };\n }\n\n case 'ContelloAsset': {\n return { id, mutation, target: 'asset' };\n }\n\n case 'ContelloI18nMessage': {\n return { id, mutation, target: 'i18nMessage', token: target.token };\n }\n\n default: {\n if (!__typename || !resolver.hasTypeName(__typename)) {\n return undefined;\n }\n\n return { id, mutation, target: 'entity', model: resolver.resolveModel(__typename) };\n }\n }\n}\n\nfunction safeMapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n try {\n return mapEvent(raw, resolver);\n } catch {\n return undefined;\n }\n}\n\nexport type InternalWatcher = {\n /** Multicast stream of update batches. Internal-only; the public `Store.updates$` is the AsyncIterable view. */\n readonly updates$: AsyncIterableSubject<UpdateBatch>;\n start(): void;\n stop(): void;\n};\n\nexport function createInternalWatcher(client: ContelloClient<any>, resolver: ModelResolver): InternalWatcher {\n const updates$ = createAsyncIterableSubject<UpdateBatch>();\n let controller: AbortController | undefined;\n\n return {\n updates$,\n\n start() {\n if (controller) {\n return;\n }\n\n controller = new AbortController();\n const signal = controller.signal;\n\n wrap('watcher:start', () => {\n void (async () => {\n const source = keepalive(\n () => client.subscribe<StoreWatchUpdatesSubscription>(storeWatchUpdatesDocument),\n { signal },\n );\n\n const events = mapAsync(source, (data) =>\n (data.contelloUpdatesBatch?.events ?? [])\n // a single malformed event must not throw out of the loop and kill\n // the watcher — skip it and keep consuming the stream\n .map((e) => safeMapEvent(e, resolver))\n .filter((e): e is UpdateEvent => e !== undefined),\n );\n\n for await (const list of events) {\n if (signal.aborted) {\n return;\n }\n\n if (list.length === 0) {\n continue;\n }\n\n try {\n updates$.next(createUpdateBatch(list));\n } catch {\n // a subscriber threw — isolate it so it can't tear down the watcher\n }\n }\n })().catch(() => {\n // keepalive only exits on abort; swallow so a terminal failure\n // never surfaces as an unhandled rejection\n });\n });\n },\n\n stop() {\n controller?.abort();\n controller = undefined;\n updates$.complete();\n },\n };\n}\n","import { type ContelloClient, type Schema, type SourceDef, createContelloClient } from '@contello/client';\n\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n createAssetsCollection,\n createAssetsSyncCollection,\n} from './assets';\nimport { createCollection, createCollectionSync } from './collection';\nimport { type I18nMessageDef, type I18nMessages, createI18nMessagesCollection } from './i18n';\nimport { type LazyAssets, type LazyAssetsOptions, createLazyAssetsCollection } from './lazy-assets';\nimport { createLazyCollection } from './lazy-collection';\nimport { type LazyRoutes, type LazyRoutesOptions, createLazyRoutesCollection } from './lazy-routes';\nimport { ModelResolver } from './model-resolver';\nimport {\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n createRoutesCollection,\n createRoutesSyncCollection,\n} from './routes';\nimport { createSingleton, createSingletonSync } from './singleton';\nimport { wrap } from './telemetry';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CreateStoreOptions,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n ResolveSource,\n Singleton,\n SingletonOptions,\n SingletonSync,\n SingletonSyncOptions,\n SourceKeysOf,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshByTtlQueue } from './utils';\nimport { type InternalWatcher, type UpdateBatch, createInternalWatcher } from './watcher';\n\n/** Project the model-reference-name union out of a Schema generic, falling back to `string`. */\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\n\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\n\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Store<TSchema extends Schema | undefined = undefined> {\n private _client: ContelloClient<TSchema>;\n private _resolver: ModelResolver;\n private _watcher: InternalWatcher;\n private _schema: TSchema;\n private _cleanups: (() => void)[] = [];\n private _refreshByTtl: RefreshByTtlQueue = createRefreshByTtlQueue();\n\n /**\n * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;\n * each iteration starts an independent fan-out from the shared source.\n */\n public readonly updates$: AsyncIterable<UpdateBatch>;\n\n public ping: () => Promise<void>;\n\n constructor(options: CreateStoreOptions<TSchema>) {\n const { url, project, token, schema } = options;\n\n this._schema = schema as TSchema;\n this._client = createContelloClient<TSchema>({\n url,\n project,\n token,\n schema,\n connections: options.connections,\n onConnected: options.onConnected,\n onReconnecting: options.onReconnecting,\n onError: options.onError,\n connectionEvents: options.connectionEvents,\n });\n\n this._resolver = new ModelResolver(schema?.models);\n this._watcher = createInternalWatcher(this._client, this._resolver);\n this.updates$ = this._watcher.updates$;\n this.ping = () => this._client.ping();\n }\n\n /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */\n private _resolveSource<T extends SourceDef>(sourceOrKey: string | T): T {\n if (typeof sourceOrKey !== 'string') {\n return sourceOrKey;\n }\n\n const sources = (this._schema as Schema | undefined)?.sources;\n const source = sources?.[sourceOrKey];\n\n if (!source) {\n throw new Error(`@contello/store: no source named \"${sourceOrKey}\" in schema.sources`);\n }\n\n return source as T;\n }\n\n public get client(): ContelloClient<TSchema> {\n return this._client;\n }\n\n public async init() {\n await wrap('store:init', () => this._client.init());\n\n this._watcher.start();\n }\n\n public async destroy() {\n // eslint-disable-next-line unicorn/no-unnecessary-splice -- splice(0) is used for its return value (a snapshot of the cleanups) *and* to atomically empty the array; `.length = 0` would drop the returned snapshot we iterate\n for (const fn of this._cleanups.splice(0)) {\n try {\n fn();\n } catch {\n // swallow — destruction is best-effort\n }\n }\n\n this._watcher.stop();\n\n await wrap('store:destroy', () => this._client.destroy());\n }\n\n // --- singleton ---\n\n public defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingleton(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Singleton<TMapped>;\n }\n\n public defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingletonSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as SingletonSync<TMapped>;\n }\n\n // --- collection ---\n\n public defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Collection<TMapped>;\n }\n\n public defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollectionSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as CollectionSync<TMapped>;\n }\n\n // --- lazy collection ---\n\n public defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createLazyCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance as LazyCollection<TMapped>;\n }\n\n // --- assets / routes / i18n (no source — built-ins) ---\n\n // --- assets ---\n\n public defineAssets(options?: AssetsOptions | undefined): Assets {\n const { instance, destroy } = createAssetsCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync {\n const { instance, destroy } = createAssetsSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n // --- routes ---\n\n public defineRoutes(options?: RoutesOptions | undefined): Routes {\n const { instance, destroy } = createRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync {\n const { instance, destroy } = createRoutesSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n const { instance, destroy } = createLazyRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineI18nMessages(def: I18nMessageDef): I18nMessages {\n const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);\n\n this._cleanups.push(result.destroy);\n\n return result;\n }\n}\n\nexport function createStore<TSchema extends Schema | undefined = undefined>(\n options: CreateStoreOptions<TSchema>,\n): Store<TSchema> {\n return new Store(options);\n}\n"],"mappings":";;;;;;;AAsoBA,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;AAmBjC,MAAM,0BAA0B;;;;;;;;;;;;;;AAchC,MAAM,2BAA2B;;;AAMjC,MAAM,iCAAiC;;;;;;;;;;AAUvC,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCjC,MAAa,oCAAoC;;;;;;;;;AASjD,MAAa,4BAA4B,GAAG,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFrE,MAAa,SAAS;CAAE;EAlCtB,2BAA2B;GAAE,UAAU;GAAmC,MAAM;EAAW;EAC3F,mBAAmB;GAAE,UAAU;GAA2B,MAAM;EAAe;CAiCzD;CAAY;EA7BlC,YAAY;GACV,UAAU,GAAG,wBAAwB;EACvC,yBAAyB;EACzB;GACE,UAAU;GACV,cAAc;GACd,SAAS;GACT,eAAe;EACjB;EACA,kBAAkB;GAChB,UAAU;GACV,UAAU;GACV,cAAc;GACd,SAAS;GACT,eAAe;EACjB;EACA,YAAY;GACV,UAAU;GACV,UAAU;GACV,cAAc;GACd,SAAS;GACT,eAAe;EACjB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