import { DataContainer, DcuplInitOptions, ViewDefinition, ListItem, ModelDefinition, RawItem, ChangeDetector, DependencyGraph, AttributeDependencyGraph } from '@dcupl/common'; import { DcuplModel } from './model/model.js'; import { QualityController } from '../quality/quality.controller.js'; import { ChangeTracker } from './change-tracker.js'; import { PartialUpdateMetrics } from './partial-update-metrics.js'; import { DcuplApi } from '../dcupl/dcupl-api.js'; type ModelParserCalculationTimingEntry = { modelName: string; step: string; value: number; }; export declare class ModelParser { cdRef: ChangeDetector; qualityController: QualityController; dcuplInstance: DcuplApi; unprocessedModelDescriptions: Map; protected unprocessedData: DataContainer[]; private keyedContainers; private replacedRowKeys; private uniqueKeyRows; private rowPositions; private foldedInto; private definitionChanges; private autoCreationChanges; defersAutoCreatedPasses: boolean; private releasedReferenceKeys; private orphansRemovedInUpdate; private modelDrops; private droppedModels; dependencyGraph: DependencyGraph; attributeDependencyGraph: AttributeDependencyGraph; changeTracker: ChangeTracker; partialUpdateMetrics: PartialUpdateMetrics; views: Map; models: Map; initOptions: DcuplInitOptions; private calculationTimings; private log; private _sealed; /** True after seal(): the staged log is gone, every write is rejected (#332). Read-only; seal() sets it (#454). */ get sealed(): boolean; constructor(cdRef: ChangeDetector, qualityController: QualityController, dcuplInstance: DcuplApi); /** * Drops the staged raw rows and the change tracker. The built models, indices and quality * errors stay. After this, addData/addModel/reprocessData/init/update throw DcuplSealedError. * The preconditions are checked by DcuplApi.seal(): init() completed, no apply in flight, no pending * loader resource, no unapplied staged changes (rows or model definitions). */ seal(): void; private assertNotSealed; init(): Promise; private prepareModels; /** * Stages dropping `modelKey` (#415): the next `init()` or `update()`, which takes the full path, * removes its definition, its data and the model, as in an instance that never had it: the global * API (`query.*`, `fn.*`) throws for the key, and lists created on it serve no rows. Registering * the key again with `addModel` before that cancels the drop; registering it after rebuilds the * model in the same instance, so those lists follow it. The app loader uses it when a model left * the loader config. */ dropModel(modelKey: string): void; /** Whether the next init or full update drops `modelKey` (see dropModel). */ hasModelDrop(modelKey: string): boolean; private applyModelDrops; /** * Unregisters a model (#420): its stored definition, its instance and its queued data containers, * so the next init does not bring it back. Counts as a definition change, so the next `update()` * rebuilds everything and references to the model resolve as to a missing model. */ removeModel(modelKey: string): void; /** Unregisters a view; takes effect at once (#420). */ removeView(viewKey: string): void; /** * Records that `models.set`/`models.update` changed the definition of `modelKey` (#408): the next * `update()` rebuilds everything, like `init()`. */ markDefinitionChanged(modelKey: string): void; /** The models whose definition changed since the last init (#408). */ getDefinitionChanges(): string[]; private validateModels; /** * initDependencyGraph * The dependencies are only affected by references. Derived properties/references do not count since they * are only possible if references are already present to derive from. Same goes for resolved references. */ private initDependencyGraph; /** * buildAttributeDependencyGraph * Analyzes all models and their attributes to build attribute-level dependencies. * This enables partial updates by tracking which attributes depend on others. */ private buildAttributeDependencyGraph; /** * The processing step of an attribute, as the full path computes it: 1 basic * properties and references, 2 query and resolved references, 3 derived and * grouped references and derived and expression properties, 4 derived * properties and references on a resolved reference (#400). */ private getAttributeProcessingStep; /** * Validates that all expected attributes are present in the attribute dependency graph. * Logs warnings for any missing attributes that might indicate parsing failures. */ private validateAttributeDependencyGraph; /** * Process expression property dependencies * Expression properties depend on all attributes referenced in the template */ private processExpressionProperty; /** * Splits an expression variable path into its segments; bracket indices become segments of * their own: "tags[0].name" -> ["tags", "0", "name"]. */ private getExpressionPathSegments; /** * Process derived property dependencies * Derived properties depend on a local reference and the remote property */ private processDerivedProperty; /** * Process query reference dependencies * Query references depend on properties used in the query template */ private processQueryReference; /** * Process resolved reference dependencies * Resolved references depend on the inverse reference from the remote model */ private processResolvedReference; /** * Process derived reference dependencies * Derived references depend on a local reference */ private processDerivedReference; /** * Process grouped reference dependencies * Grouped references depend on a source reference */ private processGroupedReference; /** * Applies the pending changes, on the partial path when it is possible and worth it, otherwise * as a full rebuild (`init()`). * * @returns The path taken: `'partial'` or `'full'` (dcupl.update() reports it as * `isPartialUpdate` on `dcupl_partial_update`, #383) */ update(): Promise<'partial' | 'full'>; /** * The tracker records the raw columns of the staged rows. A property or reference with * `origin` reads another column, so a changed origin column changes that attribute, as * init() maps it (#605). Without this the partial path never reprocessed it. */ recordOriginColumnChanges(): void; /** * Determines if a partial update is possible and beneficial * @returns object with decision and reason */ private shouldUsePartialUpdate; /** * The query references a partial update recomputes (#429; #367 took the * full path for them), and for which rows of their owner model: * - a model the target model reaches through its references changed, the * target generated a property (it fills rows the update did not touch), * or the query reads a dotted path or pages with an offset * (isMatchSetQuery): every row; * - the target model changed: the owner rows whose result lists one of the * changed, inserted or removed target items, or whose query matches one of * them now; the other rows keep the same matches (step 2 decides); * - the owner model changed: its changed and inserted rows, whose raw values * fill the query templates. * Records each as a changed attribute, so it and its dependents are planned. */ private planQueryReferences; /** * Whether only a changed item the result lists, or one the query matches * now, can alter a query reference's result (#429). Not so for an offset * page (`start`: a match that disappears before the page moves later items * into it). A `count`, a `sort` or a projection keep it: the first N matches * change only through a match that is listed or new. A dotted path is left * to every row as well: query.execute matches it on projected items * (Filter.getProjectionForQuery), the check on the stored ones. */ private isMatchSetQuery; /** * Drops the cached results of the hidden list that `query.execute` uses for * each model the query references of `modelKeys` run over. Query references * are computed through that list while an update runs, but dcupl.update() * invalidates the lists only after it, so a query that ran before the update * served its pre-update result: removed items stayed, changed ones were * missed (#429). Covers the full and the partial path. */ private invalidateQueryReferenceTargetLists; /** * The model itself plus every model it reaches through its references of * any kind, transitively. */ private getModelsReachableFrom; /** * Performs a partial update by only reprocessing changed attributes and their dependents */ private partialUpdate; private partialUpdateSteps; reprocessData(): Promise; protected getSortedCalculationTimings(): ModelParserCalculationTimingEntry[]; /** * Registers a model definition, merged into an earlier one with the same key (`models.update`; * `models.set` drops the earlier one first). The parser keeps its own copy, so later changes to * `model` do not reach this instance, and init does not write into it (#314). Inline `data` is not * part of the stored definition: it is queued through `addData`, like `dcupl.data.set`, so * `models.get` does not return it. */ addModel(model: ModelDefinition): void; private mergeModels; addData(container: DataContainer): void; /** Registers a view definition. The parser keeps its own copy (#314). */ addView(view: ViewDefinition): void; /** * Sets a validation error for a model. * Requires both global quality controller AND model-specific quality to be enabled. * This implements the two-tier validation system. */ private setError; /** * Folds each model's queued containers into the one `set` container that is * processed. A lone `set` container whose rows have unique keys is processed * as is. Every other group goes through mergeContainers(), which applies the * containers in order and dedupes the rows by key: a lone `update`/`remove` * on a model without data changes nothing (#365), and duplicate keys in a * `set` payload keep only the last row (#369). */ private getMergedContainers; /** * `containers` without the update/upsert containers an earlier apply folded * into the `set` container they follow (foldIntoContainer): that apply * failed before it took them out of the queue, and their rows are in the * `set` container already. */ private withoutFoldedContainers; /** * Folds a model's update/upsert/remove containers into its consolidated * container in place (#445), instead of merging all its rows again. The * group is one `set` container whose rows have unique keys, followed only by * update/upsert/remove containers. The result is the container * mergeContainers() returns for the same group, in the same row order: an * update merges a row into the stored row with the same key and ignores * unknown keys, an upsert does the same or appends the row, a remove takes * the rows out and the rows after them move up. * * The parser changes only row arrays it owns: a `set` container without row * positions (the caller's, or one a merge without changes built) is copied * once into a new container, as mergeContainers() would build it. Returns * `undefined` for every other group, which mergeContainers() merges: a later * `set`, an upsert row without a key, or rows without a key in the `set` * container. */ private foldIntoContainer; /** * A copy of a `set` container whose rows have unique keys, with its row * positions, for foldIntoContainer(); `undefined` when its keys are not * known to be unique or a row has no key. Built like mergeContainers() * builds its result from that one container. */ private adoptContainer; /** Takes the rows with the keys of `entries` out of `rows` in place; the rows after them move up. */ private removeRows; /** * Keys of the rows that a later row with the same key replaced in the `set` * payload behind `container`, one entry per replaced row (#369). Empty for * containers without duplicate keys. */ getReplacedRowKeys(container: DataContainer): readonly string[]; /** * A lone container needs no merge when it is a `set` whose rows have unique * keys. A lone `update`/`upsert`/`remove` is merged onto an empty dataset, * so an update or remove on a model without data changes nothing (#365). */ private isProcessableAsIs; /** * Collapse the accumulated container history into the already-merged per-model * result so `unprocessedData` stays bounded (≈ one container per model) instead * of growing with every data mutation — the merged result is identical to * re-merging the full history, so this is behavior-preserving and only affects * how much is re-merged on the next cycle. Runs after processing completes. * * - Only the containers the apply merged (`consumedContainers`) are collapsed. * Every other container stays queued after the merged result, keeping its * relative order: pending (unresolved) placeholders, and placeholders * resolved or containers staged while the apply ran — it yields to the * event loop, and dropping those lost their data. A placeholder that was * already pending therefore folds after containers this apply merged, even * ones staged after it (as before). * - Merged containers are registered as already-keyed so a subsequent * handleAlternativeKey pass does not re-apply a composite keyProperty (#182). */ private consolidateUnprocessedData; /** * Re-records the containers still queued on top of the merged result after * an apply cleared the change tracker. They were staged (or their * placeholder resolved) while the apply ran and are not processed yet: the * next apply must still see them, or its partial path skips their data. * Left out: pending placeholders, which carry no data yet (as before), and * internal `$` models, whose containers the apply stages and builds itself * (quality initData stages the error-tracking models, built at once or on * first read). */ private retrackUnprocessedData; /** * Applies a model's containers in order and returns one `set` container * with one row per key. Keys are compared as strings, the same identity the * model stores, and rows without a key are passed through for the model to * drop as `MissingKey`. * * - `set`: replaces the rows. Rows with the same key are deduped: the last * row wins as a whole and keeps the first row's position; the keys of the * replaced rows are kept for the model's NonUniqueKey errors (#369). * - `upsert`: merges a row into the stored row with the same key (see * mergeRow) or inserts it. * - `update`: merges a row into the stored row with the same key and ignores * unknown keys, also when the model has no rows yet (#365). * - `remove`: deletes the rows with the given keys; unknown keys are ignored. * * The result carries the key settings of the `set` container that supplied * the rows (without one: of the last container that has them), so the * model's errors name the same key attribute. */ private mergeContainers; /** * Folds an update/upsert payload row into the stored row. Every attribute * the payload carries replaces the stored value wholesale: arrays * (Array<…> properties, multi-valued references) and objects (json/any * properties) are never merged element-wise or recursively — change * tracking and the partial path work per attribute, too. Attributes absent * from the payload, or `undefined` in it, keep their stored value (send * `null` to clear one). Returns a new row and mutates neither input: rows * can be caller-owned, and json values are stored by reference. */ private mergeRow; /** * Mirrors mergeContainers() for the loader source-metadata side channel: when * several resources feed one model, their per-resource coercion metadata must * be combined onto the merged container, otherwise the CSV aggregation path in * QualityController loses its side channel (dcupl#197). 'set'/default resets the * effective metadata (the dataset is replaced); 'upsert'/'update' accumulate * columns and failure counts; 'remove' leaves the effective metadata unchanged * (an approximation — removed rows' failures may be over-counted). */ private mergeContainerSourceMetadata; private cloneCoercionSamples; private connectDataWithModels; /** * Performs partial data processing by only reprocessing changed attributes and their dependents * @param containers - Data containers to process */ private connectDataWithModelsPartial; /** Records that `modelKey` gained or lost items a referrer auto-created (#598, #599). */ recordAutoCreationChange(modelKey: string): void; /** * The models that gained or lost items a referrer auto-created during the last update(): the * change tracker does not name them, so their lists are refreshed as well (#599). */ getAutoCreationChanges(): string[]; /** * Runs the queued passes of the auto-created items of every model, the items they auto-create * included (#604). First the basic attributes of every queued item, then the attributes read * from them: a resolved reference of an auto-created item lists an auto-created referrer as * well (#619). Returns whether it ran any. * * @param partial - the partial path: the passes' basic-attribute errors wait for its step 6 */ private processPendingAutoCreatedItems; /** * Records a key that a reference of `modelKey` no longer holds for any item (the indices * controller's onValueReleased, #598): while a partial update runs, an auto-created item of the * reference's model under that key may have lost its last referrer. */ noteReleasedReferenceKey(modelKey: string, attributeKey: string, value: unknown): void; /** * Removes the auto-created items no referrer is left for (#598): init() creates an item of a * `supportsAutoCreation` model only for a reference to it, so once the update removed or * re-pointed the last one, a fresh init would not have the item. The candidates are the keys a * reference's index entry lost its last item for during the update (noteReleasedReferenceKey); a * basic reference's index is kept in step on the partial path, so an item is still referenced * when any basic reference to its model lists it. Removing an item releases the keys its own * references held, so this repeats until nothing goes. */ private removeOrphanedAutoCreatedItems; /** * Removes the errors of the orphans removeOrphanedAutoCreatedItems() took out, the way the * partial path removes those of a deleted row (#598): prepareErrorsForPartialUpdate() drops them * and returns the attributes whose errors must be derived from every row again, a capped group * (its unstored errors cannot be taken out one by one) or a per-attribute aggregate; those are * reprocessed for the model's rows, then finishPartialUpdate() consolidates them and re-derives * them for the auto-created items left, as on init(). */ private finishErrorsOfRemovedOrphans; /** Adds the items this update auto-created to the indices built before it (#599). */ private addAutoCreatedItemsToIndices; /** * Drops the model-level indices derived from the planned attributes (#243): * eager fills only cover index:true properties and references, so lazily * built plain indices (facets/pivot), the context-hashed indices * (aggregate/sections/suggest) and deep indices would keep serving * pre-update values. The next read rebuilds them. */ private resetIndicesForPlan; /** * Step 2 of the partial path for the query references of one model (#429): * runs each planned query reference again for the rows planQueryReferences * chose, from the model's merged raw rows, as init() does. */ private recomputeQueryReferences; /** * The merged rows of the items the pending changes touch, per model: rows of * existing items and rows the update inserts (no stored item yet). Rows * without a key are left out — init() reported them already (MissingKey). */ private splitChangedRows; /** * The rows of `container` that may carry one of the keys, in container * order. A container with row positions (foldIntoContainer) looks the keys * up (#445); any other container returns all its rows. */ private getRowsWithKeys; /** * The items, per model, whose basic reference points at an item that this * update inserts or removes (#368). Records those references as changed, so * they and their dependents are processed again. References within one model * count too: they resolve against every row of the model, whatever its * position (#411). * * An inserted item was missing until now, so only the items whose reference * did not find its key can resolve differently: the model lists them when it * resolves (DcuplModel.takeItemsMissingReferenceKeys), and they are looked up * instead of scanning every row (#425). A removed item can be named by any * row: a reference to a model with removed items scans the rows and matches * the raw reference value (any separator part, array element or object key) * and the stored one, so strict references that dropped a missing key are * found too. */ private getItemsReferencingChangedItems; /** Whether a raw or stored reference value names one of `keys` (a superset match). */ private referencesAnyKey; /** * Scopes step 1 of a partial update to the rows that changed (#368): the * other rows' raw values did not change, so reprocessing them only recorded * their errors again. Rows the update inserts are processed for every basic * attribute, as init() does. With error tracking on, it removes the error * records the update re-derives (QualityController.prepareErrorsForPartialUpdate); * the attributes whose errors need every row are reprocessed for all rows. */ private getPartialRowScopes; /** * Step 1 of the partial path for one model (#368): the changed attributes of * the changed rows, every basic attribute of the inserted rows, and the * attributes of `scope.allRowsAttributes` for every row. */ private addBasicAttributesPartial; /** `container` limited to `rows`, keeping its source metadata (the error `origin`). */ private getContainerWithRows; /** * Computes the processing order for resolved references in step 2 * Resolved references that depend on basic references should be processed before * resolved references that depend on other resolved references * @param processingPlan - The full processing plan * @returns Array of model keys in the correct processing order */ private getResolvedReferenceProcessingOrder; /** * Processes specific attributes for a given step across all affected models * (steps 3 and 4: processDerivedAttributesInDependencyOrder) * @param step - Processing step (1 or 2) * @param processingPlan - Map of modelKey → Map of step → Set of attributeKeys * @param containers - Data containers being processed */ private processAttributesForStep; /** * Steps 3 and 4 of the partial path (#602): derived, grouped and expression * attributes (step 3) and derived attributes on a resolved reference (step 4) * read each other across models: `Product.decor_tool` (step 3) derives from * `Decor.tools`, which derives from the resolved `Decor.prints` (step 4). Run * as two bands, step 3 read the value step 4 had not recomputed yet. Each * planned attribute instead runs after the planned attributes it depends on: * level 0 depends on none of them, level n on one of level n - 1 at most. * Within a level the attributes do not depend on each other, so each model * still takes one pass over its rows per level and step. */ private processDerivedAttributesInDependencyOrder; handleAlternativeKey(containers: DataContainer[]): DataContainer[]; private handleDataContainer; /** * The processing of handleDataContainer without yielding to the event loop, for callers that * cannot wait: the error-tracking models are built on first read, inside a synchronous read (#444). * It emits the same `dcupl_handle_datacontainer` message, when the containers are processed. */ processDataContainersSync(containers: DataContainer[]): void; /** * Steps 1-4 of the data processing. Yields where the async caller gives the event loop a turn * (performance.containerBatchSize decides where, as before). */ private processDataContainers; /** * Called before a read of `modelKey`'s rows from outside the parser: the error-tracking models * are built on first read (#444). */ prepareModelForRead(modelKey: string | undefined): void; _getModelKeys(): string[]; _getViewKeys(options?: { modelKey: string; }): string[]; /** * Gets the total number of items across all models * @returns Total count of items */ getTotalItemCount(): number; } export {};