import { EntityMap, TranscodeRegistry, ConditionalProperty, Exactify, PropertiesOfType, TranscodableProperties, FlattenEntityMap, Transcodes, MutuallyExclusive, NotNever, DefaultTranscodeRegistry, SortOrder } from '@karmaniverous/entity-tools'; import * as z from 'zod'; import { z as z$1, ZodType } from 'zod'; import { BatchProcessOptions } from '@karmaniverous/batch-process'; /** * Default type parameter for {@link ConfigMap | `ConfigMap`}. * * @category EntityManager */ interface BaseConfigMap { /** Entity map type (entity token -\> entity shape). */ EntityMap: EntityMap; /** Global hash-key property name used by the storage layer. */ HashKey: string; /** Global range-key property name used by the storage layer. */ RangeKey: string; /** Union of sharded generated key tokens (string-valued generated properties). */ ShardedKeys: string; /** Union of unsharded generated key tokens (string-valued generated properties). */ UnshardedKeys: string; /** Union of transcoded property tokens (domain properties mapped in `propertyTranscodes`). */ TranscodedProperties: string; /** Transcode registry mapping transcode names to value types. */ TranscodeRegistry: TranscodeRegistry; } /** * Defines a single time period in an entity sharding strategy. * * @category EntityManager * @protected */ interface ShardBump { /** * The timestamp marking the beginning of the time period. Must be a non-negative integer. * * This value must be unique across all {@link ShardBump | `ShardBumps`} for the entity. */ timestamp: number; /** * The number of bits per character in the bump's shard space. For example, `0` yields a single shard per character, and a value of `2` would yield 4 shards per character. * * This value must be an integer between `1` and `5` inclusive. */ charBits: number; /** * The number of characters used to represent the bump's shard key. * * This value must be an integer between `0` and `40` inclusive. Note that more than a few characters will result in an impossibly large shard space! * * A ShardBump with `chars` of `2` and `charBits` of `3` would yield a two-character shard key with a space of 16 shards. */ chars: number; } /** * Configuration object for an {@link EntityManager | `EntityManager`} instance. * * @typeParam C - {@link ConfigMap | `ConfigMap`} that defines the configuration's {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager */ type Config = ConditionalProperty<'entities', keyof Exactify, { [E in keyof Exactify]: { /** Default max number of items returned by {@link EntityManager.query | `query`} for this entity (across all shards). */ defaultLimit?: number; /** Default per-shard page size used by {@link EntityManager.query | `query`} for this entity. */ defaultPageSize?: number; /** Shard bump schedule for this entity (time-based sharding scale-up). */ shardBumps?: ShardBump[]; /** Property token whose value selects the active shard bump (must be a transcoded numeric property). */ timestampProperty: Extract>, TranscodableProperties>; /** Property token used as the logical unique identifier for this entity (must be a transcoded scalar). */ uniqueProperty: Extract, TranscodableProperties>; }; }> & ConditionalProperty<'generatedProperties', C['ShardedKeys'] | C['UnshardedKeys'], ConditionalProperty<'sharded', C['ShardedKeys'], Record)[]>> & ConditionalProperty<'unsharded', C['UnshardedKeys'], Record)[]>>> & ConditionalProperty<'propertyTranscodes', C['TranscodedProperties'] & TranscodableProperties, { [P in C['TranscodedProperties'] & TranscodableProperties]: PropertiesOfType[P]>; }> & ConditionalProperty<'transcodes', keyof C['TranscodeRegistry'], Transcodes> & { /** Delimiter between generated key elements (default `|`). Must not collide with other delimiters. */ generatedKeyDelimiter?: string; /** Delimiter between a generated property key and its encoded value (default `#`). Must not collide with other delimiters. */ generatedValueDelimiter?: string; /** Global hash key property name. */ hashKey: C['HashKey']; /** * Index token map. Keys are index names; values define the index hash/range key tokens and optional projections. * * @remarks * This is provider-agnostic metadata used for page-key narrowing and (de)hydration; provider adapters map this to platform-specific indexes. */ indexes?: Record); /** Optional list of projected attribute names (validated to exclude key tokens). */ projections?: string[]; }>; /** Global range key property name. */ rangeKey: C['RangeKey']; /** Delimiter between entity token and shard suffix in the global hash key value (default `!`). */ shardKeyDelimiter?: string; /** Maximum number of shard queries to execute concurrently during {@link EntityManager.query | `query`}. */ throttle?: number; }; /** * Validates a type derived from {@link BaseConfigMap | `BaseConfigMap`} to ensure HashKey and RangeKey are both defined and that all sets of special keys are mutually exclusive. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager * @protected */ type ValidateConfigMap = MutuallyExclusive<[ CC['HashKey'], CC['RangeKey'], CC['ShardedKeys'], CC['UnshardedKeys'], keyof FlattenEntityMap ]> extends true ? NotNever extends true ? CC : Exclude, true> : Exclude ]>, true>; /** * Generates & validates the map defining defines an {@link EntityManager | `EntityManager`} configuration's {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. * * Unspecified properties will default to those defined in {@link BaseConfigMap | `BaseConfigMap`}. * * @typeParam M - {@link BaseConfigMap | `BaseConfigMap`} extension. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager */ type ConfigMap = Partial> = ValidateConfigMap<{ /** Entity map type (entity token -\> entity shape). */ EntityMap: 'EntityMap' extends keyof M ? NonNullable : Record; /** Global hash key property name (defaults to `"hashKey"`). */ HashKey: 'HashKey' extends keyof M ? NonNullable : 'hashKey'; /** Global range key property name (defaults to `"rangeKey"`). */ RangeKey: 'RangeKey' extends keyof M ? NonNullable : 'rangeKey'; /** Union of sharded generated key tokens (defaults to `never`). */ ShardedKeys: 'ShardedKeys' extends keyof M ? NonNullable : never; /** Union of unsharded generated key tokens (defaults to `never`). */ UnshardedKeys: 'UnshardedKeys' extends keyof M ? NonNullable : never; /** Union of transcoded property tokens (defaults to `never`). */ TranscodedProperties: 'TranscodedProperties' extends keyof M ? NonNullable : never; /** Transcode registry type (defaults to {@link DefaultTranscodeRegistry | `DefaultTranscodeRegistry`}). */ TranscodeRegistry: 'TranscodeRegistry' extends keyof M ? NonNullable : DefaultTranscodeRegistry; }>; /** * Database-facing record key type from a {@link BaseConfigMap | `ConfigMap`} with required hash & range keys. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityClient * @protected */ type EntityKey = Record; /** * Extracts entity tokens from a {@link ConfigMap | `ConfigMap`}. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager * @protected */ type EntityToken = Extract, string>; /** * Storage-facing partial item type from a {@link BaseConfigMap | `ConfigMap`}. * * Token-agnostic shape used by encoding/decoding, key updates, and * (de)hydration services. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager */ type StorageItem = Partial & Record> & Record; /** * A partial {@link StorageItem | `StorageItem`} restricted to keys defined in `C`. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category QueryBuilder * @protected */ type PageKey = Pick, CC['HashKey'] | CC['RangeKey'] | CC['ShardedKeys'] | CC['UnshardedKeys'] | CC['TranscodedProperties']>; /** * Internal helpers to safely derive index component tokens for an index IT. * * These helpers avoid direct generic indexing into `CF['indexes'][IT]` which can * trigger TS2536. They guard presence and key membership before extracting * literal types when available. */ type IndexHashKeyOf = CF extends { /** Optional values-first index map used for literal narrowing. */ indexes?: infer I; } ? I extends Record ? IT extends keyof I ? I[IT] extends { /** Index hash key token. */ hashKey: infer HK; } ? HK & string : never : never : never : never; /** * Derive the index range-key token for a specific index token. * * When CF carries an `indexes` object and IT is a member key, this extracts the * concrete `rangeKey` token type. */ type IndexRangeKeyOf = CF extends { /** Optional values-first index map used for literal narrowing. */ indexes?: infer I; } ? I extends Record ? IT extends keyof I ? I[IT] extends { /** Index range key token. */ rangeKey: infer RK; } ? RK & string : never : never : never : never; /** * Derive the union of index token names from a values-first config literal. * * When CF carries an `indexes` object with preserved literal keys (prefer `as const`), * this helper captures the index token union. Falls back to `string` if absent. */ type IndexTokensOf = CF extends { /** Optional values-first index map used for index-token narrowing. */ indexes?: infer I; } ? I extends Record ? Extract : string : string; /** * Test whether a values-first config literal CF carries a concrete index IT. * * @remarks * Used to decide whether index-aware narrowing is available. */ type HasIndexFor = CF extends { /** Optional values-first index map used for literal narrowing. */ indexes?: infer I; } ? I extends Record ? IT extends keyof I ? true : false : false : false; /** * Base index component tokens shared by all indexes * (the global hashKey and rangeKey defined in the Config). * * @category QueryBuilder */ type BaseKeyTokens = CC['HashKey'] | CC['RangeKey']; /** * Key set for index component tokens when CF/IT identify a concrete index. * - Always includes base key tokens (global hash/range). * - Conditionally includes index hashKey/rangeKey when they do not collapse * to the base key union. * * @category QueryBuilder */ type PresentIndexTokenSet = Record, true> & { [K in IndexHashKeyOf as K extends BaseKeyTokens ? never : K]: true; } & { [K in IndexRangeKeyOf as K extends BaseKeyTokens ? never : K]: true; }; /** * Key set for index component tokens when CF does not carry an `indexes` map * or IT is unknown. Includes global keys, generated keys, and transcodable * properties. * * @category QueryBuilder */ type FallbackIndexTokenSet = Record; /** * Derive the union of token names that may appear in a page key for a specific index. * * @remarks * If CF carries a concrete `indexes` map and IT is a member key, this narrows to the * exact component-token set for that index. Otherwise, it falls back to the broad key set. */ type IndexComponentTokens = HasIndexFor extends true ? keyof PresentIndexTokenSet : keyof FallbackIndexTokenSet; /** * Page key typed for a specific index token. * * - With CF (values-first config literal) present and carrying `indexes`, the * shape narrows to exactly the component tokens of IT. * - Without CF, falls back to the broad PageKey shape. */ type PageKeyByIndex, IT extends string = string, CF = unknown> = Pick, IndexComponentTokens>; /** * Runtime configuration schema for {@link EntityManager | `EntityManager`}. * * @remarks * This is authoritative at runtime and used internally by the {@link EntityManager | `EntityManager`} constructor. * It is also used by tests. It is not intended as a user-facing TypeDoc artifact. * * @hidden */ declare const configSchema: z$1.ZodObject<{ entities: z$1.ZodDefault>; defaultPageSize: z$1.ZodDefault>; shardBumps: z$1.ZodPipe>>>, z$1.ZodTransform<{ timestamp: number; charBits: number; chars: number; }[], { timestamp: number; charBits: number; chars: number; }[]>>; timestampProperty: z$1.ZodString; uniqueProperty: z$1.ZodString; }, z$1.core.$strict>>>>; generatedProperties: z$1.ZodDefault>>>; unsharded: z$1.ZodDefault>>>; }, z$1.core.$strip>>>; hashKey: z$1.ZodString; indexes: z$1.ZodDefault>; }, z$1.core.$strip>>>>; generatedKeyDelimiter: z$1.ZodDefault>; generatedValueDelimiter: z$1.ZodDefault>; propertyTranscodes: z$1.ZodDefault>>; rangeKey: z$1.ZodString; shardKeyDelimiter: z$1.ZodDefault>; throttle: z$1.ZodDefault>; transcodes: z$1.ZodDefault; decode: z$1.ZodCustom; }, z$1.core.$strict>>>>; }, z$1.core.$strict>; /** * Parsed transcoder entry. * * @remarks * This reflects the runtime contract enforced by Zod for entries in `transcodes`. */ interface ParsedTranscoder { /** Encode a value to a lexicographically sortable string. */ encode: unknown; /** Decode a previously encoded string back to the value type. */ decode: unknown; } /** * Parsed index definition (provider-agnostic). * * @remarks * Provider adapters map these tokens to provider-specific index queries. */ interface ParsedIndexConfig { /** Index hash key token (global hash key or a sharded generated key). */ hashKey: string; /** Index range key token (global range key, an unsharded generated key, or a transcoded scalar). */ rangeKey: string; /** Optional list of projected attribute names (validated to exclude key tokens). */ projections?: string[] | undefined; } /** * Parsed generated properties configuration. */ interface ParsedGeneratedPropertiesConfig { /** Sharded generated property tokens (hash-side); atomic encoding semantics. */ sharded: Record; /** Unsharded generated property tokens (range-side); non-atomic encoding semantics. */ unsharded: Record; } /** * Parsed per-entity configuration. */ interface ParsedEntityConfig { /** Default max items returned by EntityManager.query for this entity (across all shards). */ defaultLimit: number; /** Default per-shard page size used by EntityManager.query for this entity. */ defaultPageSize: number; /** Shard bump schedule for this entity (time-based sharding scale-up). */ shardBumps: ShardBump[]; /** Property token whose value selects the shard bump (typically a timestamp). */ timestampProperty: string; /** Property token used to dedupe and build the global range key. */ uniqueProperty: string; } /** * Simplified runtime configuration shape after parsing/validation. * * @remarks * This is the type exposed by {@link EntityManager.config | `EntityManager.config`}. * It mirrors the validated Zod schema output. * * @category EntityManager */ interface ParsedConfig { /** Entity definitions keyed by entity token. */ entities: Record; /** Generated property token maps. */ generatedProperties: ParsedGeneratedPropertiesConfig; /** Global hash key property name. */ hashKey: string; /** Provider-agnostic index definitions keyed by index token. */ indexes: Record; /** Delimiter between generated key elements (default `|`). */ generatedKeyDelimiter: string; /** Delimiter between generated element name and value (default `#`). */ generatedValueDelimiter: string; /** Map of transcoded property token -\> transcode name. */ propertyTranscodes: Record; /** Global range key property name. */ rangeKey: string; /** Delimiter between entity token and shard suffix in hash key values (default `!`). */ shardKeyDelimiter: string; /** Default max concurrency for shard queries during EntityManager.query. */ throttle: number; /** Transcoder registry used for encoding/decoding values. */ transcodes: Record; } /** EntityOfToken — resolves the concrete entity shape for a specific entity token. */ type EntityOfToken> = Exactify[ET]; /** * EntityItem — domain-facing item narrowed to a specific entity token, plus * optional key/token properties. Required fields per captured entitiesSchema * (when present); no string index signature. */ type EntityItem> = EntityOfToken & Partial>; /** * Normalize literals: string | readonly string[] -\> union of strings. */ type KeysFrom = K extends readonly (infer E)[] ? Extract : K extends string ? K : never; /** * Project item shape by keys; if K is never/unknown, fall back to T. */ type Projected = [KeysFrom] extends [never] ? T : T extends object ? Pick, keyof Exactify>> : T; /** EntityRecord — DB-facing record (keys required), narrowed to a specific entity token. */ type EntityRecord> = Partial> & EntityKey; /** EntityItemPartial — projected/seed domain shape by token. * - If K provided: required projected keys (`Projected, K>`). * - If K omitted: permissive seed (`Partial>`). */ type EntityItemPartial, K = unknown> = [KeysFrom] extends [never] ? Partial> : Projected, K>; /** EntityRecordPartial — projected DB record shape by token. */ type EntityRecordPartial, K = unknown> = Projected, K>; /** * A result returned by a {@link ShardQueryFunction | `ShardQueryFunction`} querying an individual shard. * * @typeParam CC - {@link ConfigMap | `ConfigMap`}. * @typeParam ET - Entity token narrowing the item type. * @typeParam IT - Index token (for page key typing). * @typeParam CF - Optional values-first config literal type for narrowing. * @typeParam K - Optional projection keys; narrows item shape when provided. * * @category EntityManager * @protected */ interface ShardQueryResult, IT extends string, CF = unknown, K = unknown> { /** The number of records returned. */ count: number; /** The returned records. */ items: EntityItemPartial[]; /** The page key for the next query on this shard. */ pageKey?: PageKeyByIndex; } /** * A query function that returns a single page of results from an individual shard. * * This function will typically be composed dynamically to express a specific query index & logic. The arguments to this function will be provided by the {@link EntityManager.query | `EntityManager.query`} method, which assembles many returned pages queried across multiple shards into a single query result. * * @param hashKey - The hash key value of the shard being queried. * @param pageKey - The typed page key for the index being queried. * @param pageSize - The maximum number of items to return from this query. * * @typeParam CC - {@link ConfigMap | `ConfigMap`}. * @typeParam ET - Entity token narrowing the item/record types. * @typeParam IT - Index token (inferred from shardQueryMap keys). * @typeParam CF - Optional values-first config literal type for narrowing. * @typeParam K - Optional projection keys; narrows item shape when provided. * * @category EntityManager * @protected */ type ShardQueryFunction, IT extends string, CF = unknown, K = unknown> = CF extends { /** Optional values-first index map used for index-token narrowing. */ indexes?: infer I; } ? I extends Record ? IT extends Extract ? (hashKey: string, pageKey?: PageKeyByIndex, pageSize?: number) => Promise> : never : (hashKey: string, pageKey?: PageKeyByIndex, pageSize?: number) => Promise> : (hashKey: string, pageKey?: PageKeyByIndex, pageSize?: number) => Promise>; /** * Relates a specific index token to a {@link ShardQueryFunction | `ShardQueryFunction`} to be performed on that index. * * @typeParam CC - {@link ConfigMap | `ConfigMap`}. * @typeParam ET - Entity token narrowing the function item types. * @typeParam ITS - Index token subset (inferred from object keys). * @typeParam CF - Optional values-first config literal type for narrowing. When * provided and it carries an `indexes` object with preserved * literal keys (prefer `as const` at call sites), the map keys * are constrained to that set. Excess keys are rejected by * excess property checks on object literals. * @typeParam K - Optional projection keys; narrows item shape when provided. * * @category EntityManager * @protected */ type ShardQueryMap, ITS extends string, CF = unknown, K = unknown> = CF extends { /** Optional values-first index map used for index-token narrowing. */ indexes?: infer I; } ? I extends Record ? Record>, ShardQueryFunction>, CF, K>> : Record> : Record>; /** * Convenience alias for ShardQueryMap that derives ITS (index token subset) * from a values-first captured config CC (e.g., your config literal type). * * - If CC has `indexes`, ITS becomes the union of its keys. * - Otherwise, ITS defaults to `string`. * * It also passes CC through the CF channel so per-index page-key narrowing * applies consistently. * * This is optional DX sugar; it does not change runtime behavior. */ type ShardQueryMapByCC, CCLit = unknown, K = unknown> = ShardQueryMap, CCLit, K>; /** * Convenience alias for ShardQueryMap that derives ITS (index token subset) * directly from a values-first config literal CF when it carries `indexes`. * * - If CF has `indexes`, ITS becomes the union of its keys. * - Otherwise, ITS defaults to `string`. * * This is optional DX sugar; it does not change runtime behavior. */ type ShardQueryMapByCF, CF = unknown, K = unknown> = ShardQueryMap, CF, K>; /** * Options passed to the {@link EntityManager.query | `EntityManager.query`} method. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam ET - Entity token narrowing the item types. * @typeParam ITS - Index token subset (inferred from shardQueryMap keys). * @typeParam CF - Optional values-first config literal type used for index-aware narrowing. * @typeParam K - Optional projection keys; narrows item/sort shapes when provided. * * @category EntityManager * @protected */ interface QueryOptions = EntityToken, ITS extends string = string, CF = unknown, K = unknown> { /** Identifies the entity to be queried. Key of {@link Config | `Config`} `entities`. */ entityToken: ET; /** * Partial item object sufficiently populated to generate index hash keys. */ item: EntityItemPartial; /** * The target maximum number of records to be returned by the query across * all shards. * * The actual number of records returned will be a product of {@link QueryOptions.pageSize | `pageSize`} and the * number of shards queried, unless limited by available records in a given * shard. */ limit?: number | undefined; /** * {@link QueryResult.pageKeyMap | `pageKeyMap`} returned by the previous iteration of this query. */ pageKeyMap?: string | undefined; /** * The maximum number of records to be returned by each individual query to a * single shard (i.e. {@link ShardQueryFunction | `ShardQueryFunction`} execution). * * Note that, within a given {@link EntityManager.query | `query`} method execution, these queries will be * repeated until either available data is exhausted or the {@link QueryOptions.limit | `limit`} value is * reached. */ pageSize?: number | undefined; /** * Each key in this object is a valid entity index token. Each value is a valid * {@link ShardQueryFunction | 'ShardQueryFunction'} that specifies the query of a single page of data on a * single shard for the mapped index. * * This allows simultaneous queries on multiple sort keys to share a single * page key, e.g. to match the same string against `firstName` and `lastName` * properties without performing a table scan for either. */ shardQueryMap: ShardQueryMap; /** * A {@link SortOrder | `SortOrder`} object specifying the sort order of the result set. Defaults to `[]`. Aligned with the projected item shape when K is provided. */ sortOrder?: SortOrder> | undefined; /** * Lower limit to query shard space. * * Only valid if the query is constrained along the dimension used by the * {@link Config | `EntityManager.config.entities..sharding.timestamptokens.timestamp`} * function to generate `shardKey`. * * @defaultValue `0` */ timestampFrom?: number | undefined; /** * Upper limit to query shard space. * * Only valid if the query is constrained along the dimension used by the * {@link Config | `EntityManager.config.entities..sharding.timestamptokens.timestamp`} * function to generate `shardKey`. * * @defaultValue `Date.now()` */ timestampTo?: number | undefined; /** * The maximum number of shards to query in parallel. Overrides options `throttle`. * * @defaultValue `options.throttle` */ throttle?: number | undefined; } /** * Convenience alias for QueryOptions that derives ITS (index token subset) * directly from a values-first config literal CF when it carries `indexes`. * * - If CF has `indexes`, ITS becomes the union of its keys. * - Otherwise, ITS defaults to `string`. * * This is optional DX sugar; it does not change runtime behavior. */ type QueryOptionsByCF = EntityToken, CF = unknown, K = unknown> = QueryOptions, CF, K>; /** * Convenience alias for QueryOptions that derives ITS (index token subset) * from a values-first captured config CC (e.g., your config literal type). * * - If CC has `indexes`, ITS becomes the union of its keys. * - Otherwise, ITS defaults to `string`. * * It also passes CC through the CF channel so page-key narrowing and other * CF-aware typing applies consistently. * * This is optional DX sugar; it does not change runtime behavior. */ type QueryOptionsByCC = EntityToken, CC = unknown, K = unknown> = QueryOptions, CC, K>; /** * A result returned by a query across multiple shards, where each shard may receive multiple page queries via a dynamically-generated {@link ShardQueryFunction | `ShardQueryFunction`}. * * @typeParam CC - {@link ConfigMap | `ConfigMap`}. * @typeParam ET - Entity token narrowing the result item type. * @typeParam ITS - Index token subset (carried for symmetry; not represented in the shape). * @typeParam K - Optional projection keys; narrows item shape when provided. * * @category EntityManager * @protected */ interface QueryResult, ITS extends string, K = unknown> { /** Total number of records returned across all shards. */ count: number; /** The returned records. */ items: EntityItemPartial[]; /** * A compressed, two-layer map of page keys, used to query the next page of * data for a given sort key on each shard of a given hash key. */ pageKeyMap: string; } /** * The EntityManager class applies a configuration-driven sharded data model & * query strategy to NoSql data. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines the configuration's {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam CF - Values-first config literal type captured at construction * time (phantom generic; type-only). This is used by downstream * adapters to infer index-token unions (ITS) and per-index page * key shapes. * * @remarks * While the {@link EntityManager.query | `query`} method is `public`, normally it should not be called directly. The `query` method is used by a platform-specific {@link BaseQueryBuilder.query | `QueryBuilder.query`} method to provide a fluent query API. * * @category EntityManager */ declare class EntityManager { #private; /** Logger object (defaults to `console`, must support `debug` & `error` methods). */ readonly logger: Pick; /** * Create an EntityManager instance. * * @param config - EntityManager {@link Config | `Config`} object. * @param logger - Logger object (defaults to `console`, must support `debug` & `error` methods). */ constructor(config: Config, logger?: Pick); /** * Get the current EntityManager {@link Config | `Config`} object. * * @returns Current {@link Config | `Config`} object. */ get config(): ParsedConfig; /** * Set the current EntityManager {@link Config | `Config`} object. * * @param value - {@link Config | `Config`} object. */ set config(value: ParsedConfig); /** * Encode a generated property value. Returns a string or undefined if atomicity requirement of sharded properties not met. * * @param property - {@link Config | Config} `generatedProperties` key. * @param item - {@link StorageItem | `StorageItem`} object. * * @returns Encoded generated property value. * * @throws `Error` if `property` is not a {@link Config | Config} `generatedProperties` key. */ encodeGeneratedProperty(property: CC['ShardedKeys'] | CC['UnshardedKeys'], item: StorageItem): string | undefined; /** * Update generated properties, hash key, and range key on an {@link EntityItem | `EntityItem`} object. * * @param entityToken - Entity token (narrows types by token). * @param item - Single item to update with generated keys/properties. * @param overwrite - Overwrite existing keys/properties (default `false`). * * @returns {@link EntityRecord | `EntityRecord`} object with updated properties. * * @throws `Error` if `entityToken` is invalid. * * @overload */ addKeys>(entityToken: ET, item: EntityItemPartial, overwrite?: boolean): EntityRecordPartial; /** * Update generated properties, hash key, and range key on an array of {@link EntityItem | `EntityItem`} objects. * * @param entityToken - Entity token (narrows types by token). * @param item - Items to update with generated keys/properties. * @param overwrite - Overwrite existing keys/properties (default `false`). * * @returns Array of {@link EntityRecord | `EntityRecord`} objects with updated properties. * * @throws `Error` if `entityToken` is invalid. * * @overload */ addKeys>(entityToken: ET, item: EntityItemPartial[], overwrite?: boolean): EntityRecordPartial[]; /** * Convert one or more {@link EntityItem | `EntityItem`} objects into an array of {@link EntityKey | `EntityKey`} values. * * @param entityToken - Entity token (narrows types by token). * @param item - Single item to derive primary keys for. * @param overwrite - Overwrite existing keys on the item before deriving (default `false`). * * @returns Array of {@link EntityKey | `EntityKey`} values derived from `item`. * * @throws `Error` if `entityToken` is invalid. * * @overload */ getPrimaryKey>(entityToken: ET, item: EntityItemPartial, overwrite?: boolean): EntityKey[]; /** * Convert an array of {@link EntityItem | `EntityItem`} objects into {@link EntityKey | `EntityKey`} values. * * @param entityToken - Entity token (narrows types by token). * @param items - Array of items to derive primary keys for. * @param overwrite - Overwrite existing keys on each item before deriving (default `false`). * * @returns Array of {@link EntityKey | `EntityKey`} values derived from all `items`. * * @throws `Error` if `entityToken` is invalid. * * @overload */ getPrimaryKey>(entityToken: ET, items: EntityItemPartial[], overwrite?: boolean): EntityKey[]; /** * Strips generated properties, hash key, and range key from an {@link EntityRecord | `EntityRecord`} object. * * @param entityToken - {@link Config | `Config`} `entities` key. * @param item - {@link EntityRecord | `EntityRecord`} object. * * @returns {@link EntityItem | `EntityItem`} with generated properties, hash key & range key removed. * * @throws `Error` if `entityToken` is invalid. * * Overloads: */ removeKeys>(entityToken: ET, item: EntityRecord): EntityItem; removeKeys, K = unknown>(entityToken: ET, item: EntityRecordPartial): EntityItemPartial; removeKeys>(entityToken: ET, items: EntityRecord[]): EntityItem[]; removeKeys, K = unknown>(entityToken: ET, items: EntityRecordPartial[]): EntityItemPartial[]; /** * Find an index token based on the configured hash and range key tokens. * * @param hashKeyToken - Index hash key token (global hashKey or a sharded generated key). * @param rangeKeyToken - Index range key token (global rangeKey, unsharded generated key, or a transcodable scalar). * @param suppressError - When false (default), throws if no match; when true, returns undefined instead. * * @returns A configured index token (narrowed to the CF.indexes key union) or undefined when allowed. * * @throws `Error` if no match is found and `suppressError` is not `true`. */ findIndexToken(hashKeyToken: CC['HashKey'] | CC['ShardedKeys'], rangeKeyToken: CC['RangeKey'] | CC['UnshardedKeys'] | CC['TranscodedProperties'], suppressError?: false): IndexTokensOf; findIndexToken(hashKeyToken: CC['HashKey'] | CC['ShardedKeys'], rangeKeyToken: CC['RangeKey'] | CC['UnshardedKeys'] | CC['TranscodedProperties'], suppressError: true): IndexTokensOf | undefined; /** * Query a database entity across shards in a provider-generic fashion. * * @remarks * The provided `shardQueryMap` performs the actual query of individual data pages on individual index/shard combinations. * * Individual shard query results will be combined, deduped by {@link Config | `Config`} `uniqueProperty` value, and sorted by {@link QueryOptions.sortOrder | `sortOrder`}. * * In queries on sharded data, expect the leading and trailing edges of returned data pages to interleave somewhat with preceding & following pages. * * Unsharded query results should sort & page as expected. * * **Normally this method should not be called directly!** It is used by a platform-specific {@link BaseQueryBuilder.query | `QueryBuilder.query`} method to provide a fluent query API. * * @param options - {@link QueryOptions | `QueryOptions`} object. * * @returns {@link QueryResult} object. * * @throws Error if `options` {@link QueryOptions.pageKeyMap | `pageKeyMap`} `pageKeyMap` keys do not match {@link QueryOptions.shardQueryMap | `shardQueryMap`} keys. * * @protected */ query, ITS extends string, CF = unknown, K = unknown>(options: QueryOptions): Promise>; } /** * Values-first config input used to capture literal tokens from the provided * configuration value. This does not enforce full Config shape at compile * time; runtime validation still occurs via Zod in the EntityManager. * * Keep this intentionally permissive to maximize inference from `as const`. */ interface ConfigInput { /** Global hash key property name (e.g., `"pk"`). */ hashKey: string; /** Global range key property name (e.g., `"sk"`). */ rangeKey: string; /** * Optional generated property token maps. * * @remarks * - `sharded` keys are hash-side generated property tokens and are encoded atomically. * - `unsharded` keys are range-side generated property tokens. */ generatedProperties?: { /** Sharded generated property tokens (hash-side). */ sharded?: Record; /** Unsharded generated property tokens (range-side). */ unsharded?: Record; }; /** * Optional map of transcodable property token -\> transcode name. * * @remarks * Only properties present here are treated as “transcoded properties”. */ propertyTranscodes?: Record; /** * Optional index token map used for typing and paging-key narrowing. * * @remarks * This is provider-agnostic metadata (not a provider-specific index definition). */ indexes?: Record; /** * Optional per-entity configuration (runtime semantics). * * @remarks * This is intentionally permissive in `ConfigInput`; runtime validation occurs * in the {@link EntityManager | `EntityManager`} constructor via Zod. */ entities?: Record; /** * Optional Zod schemas for per-entity domain shapes (non-generated fields only). * * @remarks * Schemas MUST declare only base (non-generated) properties. Do not include: * - global keys (hashKey/rangeKey), or * - generated property tokens (sharded/unsharded keys). */ entitiesSchema?: Record; /** Optional delimiter between generated key elements (default `|`). */ generatedKeyDelimiter?: string; /** Optional delimiter between a generated element name and its value (default `#`). */ generatedValueDelimiter?: string; /** Optional delimiter between entity token and shard suffix in hash key values (default `!`). */ shardKeyDelimiter?: string; /** Optional transcode registry/value (validated at runtime). */ transcodes?: unknown; /** Optional maximum concurrency for shard queries. */ throttle?: number; } /** Extract the hash key token string literal from a values-first config input type. */ type HashKeyFrom = CC extends { /** Hash key token property name. */ hashKey: infer H; } ? H & string : 'hashKey'; /** Extract the range key token string literal from a values-first config input type. */ type RangeKeyFrom = CC extends { /** Range key token property name. */ rangeKey: infer R; } ? R & string : 'rangeKey'; /** Extract the union of sharded generated key tokens from a values-first config input type. */ type ShardedKeysFrom = CC extends { /** Optional generated properties object containing sharded/unsharded maps. */ generatedProperties?: infer GP; } ? GP extends { /** Sharded generated property token map. */ sharded?: infer S; } ? keyof S & string : never : never; /** Extract the union of unsharded generated key tokens from a values-first config input type. */ type UnshardedKeysFrom = CC extends { /** Optional generated properties object containing sharded/unsharded maps. */ generatedProperties?: infer GP; } ? GP extends { /** Unsharded generated property token map. */ unsharded?: infer U; } ? keyof U & string : never : never; /** Extract the union of transcoded property tokens from a values-first config input type. */ type TranscodedPropertiesFrom = CC extends { /** Optional map of property token -\> transcode name. */ propertyTranscodes?: infer PT; } ? keyof PT & string : never; /** * Derive an EntityMap from CC.entitiesSchema when provided (values-first, no generics). * * Fallback to broad EntityMap if schemas are absent. */ type EntitiesFromSchema = CC extends { /** Optional per-entity Zod schema map used only for type inference. */ entitiesSchema?: infer S; } ? S extends Record ? { [K in Extract]: z.infer; } & EntityMap : EntityMap : EntityMap; /** * Derive the union of index token names from a values-first config input. * * When the provided config literal carries an `indexes` object with preserved * literal keys (prefer `as const` at call sites), this helper captures the * index token union. Falls back to `string` if absent. */ type IndexTokensFrom = CC extends { /** Optional index token map used for index-token inference. */ indexes?: infer I; } ? keyof I & string : string; /** * Captures a BaseConfigMap-compatible type from a literal ConfigInput value * and an EntityMap (defaults to MinimalEntityMapFrom). */ interface CapturedConfigMapFrom extends BaseConfigMap { /** Entity map type (from schemas when provided; otherwise broad). */ EntityMap: EM; /** Hash key token captured from the config literal. */ HashKey: HashKeyFrom; /** Range key token captured from the config literal. */ RangeKey: RangeKeyFrom; /** Sharded generated key token union captured from the config literal. */ ShardedKeys: ShardedKeysFrom; /** Unsharded generated key token union captured from the config literal. */ UnshardedKeys: UnshardedKeysFrom; /** Transcoded property token union captured from the config literal. */ TranscodedProperties: TranscodedPropertiesFrom; /** Transcode registry type (default registry; runtime validation still applies). */ TranscodeRegistry: DefaultTranscodeRegistry; } /** * Values-first factory that captures literal tokens and index names directly * from the provided config value. Runtime config parsing/validation is * unchanged (performed in the EntityManager constructor). * * @typeParam CC - Captured config input (values-first). Prefer `as const` and * `satisfies` at call sites to preserve literal keys. * @typeParam EM - EntityMap for the manager. Defaults to a minimal derived map * from `CC.entitiesSchema` when present; otherwise falls back to EntityMap. * * @returns An {@link EntityManager | `EntityManager`} instance whose type * captures CF from the single values-first config literal ({@link ConfigInput | `ConfigInput`}) * as the second generic parameter (phantom; type-only). */ declare function createEntityManager>(config: CC, logger?: Pick): EntityManager, CC>; /** * Storage-facing record type with required keys. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityManager */ type StorageRecord = StorageItem & EntityKey; /** * Base EntityClient options. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * * @category EntityClient */ interface BaseEntityClientOptions { /** Default batch process options. */ batchProcessOptions?: Omit, 'batchHandler' | 'unprocessedItemExtractor'>; /** {@link EntityManager | `EntityManager`} instance. */ entityManager: EntityManager; /** Injected logger object. Must support `debug` and `error` methods. Default: `console` */ logger?: Pick | undefined; } /** * Base EntityClient class. Integrates {@link EntityManager | `EntityManager`} with injected logging & enhanced batch processing. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s * {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. * If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam CF - Values-first config literal type captured by the manager (phantom; type-only). Propagated so * client-facing calls that return `IndexTokensOf` retain the narrowed union. * * @category EntityClient */ declare abstract class BaseEntityClient { /** Default batch process options. */ readonly batchProcessOptions: NonNullable['batchProcessOptions']>; /** {@link EntityManager | `EntityManager`} instance. */ readonly entityManager: EntityManager; /** Injected logger object. Must support `debug` and `error` methods. Default: `console` */ readonly logger: NonNullable['logger']>; /** * Base EntityClient constructor. * * @param options - {@link BaseEntityClientOptions | `BaseEntityClientOptions`} object. */ constructor(options: BaseEntityClientOptions); } /** * Extract the captured config map type from a {@link BaseEntityClient | `BaseEntityClient`} instance type. * * @typeParam EC - A {@link BaseEntityClient | `BaseEntityClient`} instance type. * * @remarks * This is a pure type-level helper used to derive token-aware types from a client * instance type without requiring callers to restate the config map type. */ type ConfigOfClient = EC extends BaseEntityClient ? CC : never; /** * Map a client instance type + entity token to the storage-facing record type. * * @typeParam EC - A {@link BaseEntityClient | `BaseEntityClient`} instance type. * @typeParam ET - An {@link EntityToken | `EntityToken`} for that client’s config. */ type EntityClientRecordByToken>> = EntityRecord, ET>; /** * Map a client instance type + entity token to the domain-facing item type. * * This is the “item-facing” shape (global keys and generated property tokens are * not required and are typically stripped via {@link EntityManager.removeKeys | `removeKeys`}). * * @typeParam EC - A {@link BaseEntityClient | `BaseEntityClient`} instance type. * @typeParam ET - An {@link EntityToken | `EntityToken`} for that client’s config. */ type EntityClientItemByToken>> = EntityItem, ET>; /** * Constructor options for {@link BaseQueryBuilder | `BaseQueryBuilder`}. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam EntityClient - {@link BaseEntityClient | `BaseEntityClient`} derived class instance. * * @category QueryBuilder */ interface BaseQueryBuilderOptions> { /** {@link BaseEntityClient | `EntityClient`} instance. */ entityClient: EntityClient; /** Entity token. */ entityToken: EntityToken; /** Hash key token. */ hashKeyToken: CC['HashKey'] | CC['ShardedKeys']; /** Dehydrated page key map. */ pageKeyMap?: string | undefined; } /** * Options for {@link BaseQueryBuilder.query | `query`} method on all derived classes. * * Same as {@link QueryOptions | `QueryOptions`} for {@link EntityManager.query | `EntityManager.query`}, excluding `entityToken`, `pageKeyMap`, and `shardQueryMap`. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam ET - Entity token narrowing the item types for options.item. * * @category QueryBuilder */ type QueryBuilderQueryOptions, CF = unknown> = Omit, 'entityToken' | 'pageKeyMap' | 'shardQueryMap'>; /** * Abstract base class supporting a fluent API for building a {@link ShardQueryMap | `ShardQueryMap`} using a database client. * * @typeParam CC - {@link ConfigMap | `ConfigMap`} that defines an {@link Config | `EntityManager configuration`}'s {@link EntityMap | `EntityMap`}, key properties, and {@link TranscodeRegistry | `TranscodeRegistry`}. If omitted, defaults to {@link BaseConfigMap | `BaseConfigMap`}. * @typeParam EntityClient - {@link BaseEntityClient | `BaseEntityClient`} derived class instance. * @typeParam IndexParams - Database platform-specific, index-specific query parameters. * @typeParam CF - Optional values-first config literal type for page key narrowing. * @typeParam K - Optional projection keys; narrows item shape when provided. * * @category QueryBuilder */ declare abstract class BaseQueryBuilder, IndexParams, ET extends EntityToken = EntityToken, ITS extends string = string, CF = unknown, K = unknown> { /** {@link BaseEntityClient | `EntityClient`} instance. */ readonly entityClient: EntityClient; /** Entity token. */ readonly entityToken: EntityToken; /** Hash key token. */ readonly hashKeyToken: CC['HashKey'] | CC['ShardedKeys']; /** Dehydrated page key map. */ readonly pageKeyMap?: string | undefined; /** * Maps `indexToken` values to database platform-specific query parameters. * * @protected */ readonly indexParamsMap: Record; /** BaseQueryBuilder constructor. */ constructor(options: BaseQueryBuilderOptions); /** * Build a shard query function for a specific index token. * * @param indexToken - Index token identifying which index to query. * * @returns A {@link ShardQueryFunction | `ShardQueryFunction`} that queries a single shard for this index. * * @remarks * Implementations are provider-specific (e.g., DynamoDB). The returned function must: * - Query exactly one shard (partition) per invocation using the provided hash key value. * - Respect `pageKey` and `pageSize` for pagination. * - Return `pageKey: undefined` when that shard is exhausted. * * Entity Manager will orchestrate calling these functions across shards and indexes. * * @protected */ protected abstract getShardQueryFunction(indexToken: ITS): ShardQueryFunction; /** * Builds a {@link ShardQueryMap | `ShardQueryMap`} object. * * @returns - The {@link ShardQueryMap | `ShardQueryMap`} object. */ build(): ShardQueryMap; /** * Execute the built query across shards and indexes via {@link EntityManager.query | `EntityManager.query`}. * * @param options - Query options excluding `entityToken`, `pageKeyMap`, and `shardQueryMap`, which are supplied by the builder. * * @returns The merged, de-duplicated, sorted query result, including a compact `pageKeyMap` token for the next page. * * @remarks * This delegates orchestration to Entity Manager; provider-specific behavior lives in {@link getShardQueryFunction | `getShardQueryFunction`}. */ query(options: QueryBuilderQueryOptions): Promise>; } export { BaseEntityClient, BaseQueryBuilder, EntityManager, configSchema, createEntityManager }; export type { BaseConfigMap, BaseEntityClientOptions, BaseKeyTokens, BaseQueryBuilderOptions, CapturedConfigMapFrom, Config, ConfigInput, ConfigMap, ConfigOfClient, EntitiesFromSchema, EntityClientItemByToken, EntityClientRecordByToken, EntityItem, EntityItemPartial, EntityKey, EntityOfToken, EntityRecord, EntityRecordPartial, EntityToken, FallbackIndexTokenSet, HasIndexFor, HashKeyFrom, IndexComponentTokens, IndexHashKeyOf, IndexRangeKeyOf, IndexTokensFrom, IndexTokensOf, KeysFrom, PageKey, PageKeyByIndex, ParsedConfig, ParsedEntityConfig, ParsedGeneratedPropertiesConfig, ParsedIndexConfig, ParsedTranscoder, PresentIndexTokenSet, Projected, QueryBuilderQueryOptions, QueryOptions, QueryOptionsByCC, QueryOptionsByCF, QueryResult, RangeKeyFrom, ShardBump, ShardQueryFunction, ShardQueryMap, ShardQueryMapByCC, ShardQueryMapByCF, ShardQueryResult, ShardedKeysFrom, StorageItem, StorageRecord, TranscodedPropertiesFrom, UnshardedKeysFrom, ValidateConfigMap };