@cobol-ts/cursor-composition 0.0.0-stage → 0.0.16

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/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @cobol-ts/cursor-composition
2
+
3
+ An entity-driven, master-ordered, streaming merge of prepared file cursors. Child
4
+ projections and parser representations remain borrowed; the composite view is
5
+ created once per pooled lease. Compiled CEL paths resolve numeric slots at
6
+ preparation and delegate directly to the child's reader. Joined collection
7
+ indices select a child lease; remaining indices are copied into reusable
8
+ windows for the child's physical-array reader.
9
+
10
+ `bindAccumulator()` merges a self-describing RDW Protobuf accumulator and uses
11
+ one pooled message allocator for matched persisted rows and missing customer IDs.
12
+ The `acc` root points to that mutable message; `input` remains the composition.
13
+
14
+ Current scope: one sorted master, sorted effective-key secondary streams, one,
15
+ optional, many and many-optional joins. The mapping callback is prepared by the
16
+ caller. Sorting/index creation and YAML plan generation are **not** supplied by
17
+ this module. Non-monotonic mappings fail explicitly instead of producing an
18
+ incorrect merge. A missing optional singular source cannot yet be dereferenced
19
+ from compiled CEL.
20
+
21
+ Run `yarn test` in this package after applying the Laoban templates and linking
22
+ workspace dependencies. See `src/composition.integration.spec.ts` for real
23
+ JSONL cursor + CSV identity-map + schema-first Protobuf usage.
24
+
25
+ ## Quick orientation
26
+
27
+ **Responsibility.** Stream one master-ordered entity at a time across required, optional and many-valued file sources, including mapped keys.
28
+
29
+ **Boundary.** The callback visitor borrows a composite; its physical child leases are closed after the synchronous visit. COBOL, CSV, JSONL and indexed-history batch cursors refill synchronously; other adapters, including Protobuf, may still be asynchronous. Setup and final completion may return Promises.
30
+
31
+ **Public modules.** [composition.ts](./src/composition.ts), [access.ts](./src/access.ts), [accumulator.ts](./src/accumulator.ts), [mapping.ts](./src/mapping.ts).
32
+
33
+ **Tests.** [composition.integration.spec.ts](src/composition.integration.spec.ts), [composition.ownership.spec.ts](src/composition.ownership.spec.ts)
34
+
35
+ **Related packages.** [@cobol-ts/cursor-loader-source](../cursor-loader-source/README.md) · [@cobol-ts/composition-definition](../../config/composition-definition/README.md).
36
+
37
+ ## Hot-path contract
38
+
39
+ `createComposition()` creates property getters and one stable projected-array
40
+ proxy per collection slot when the composite pool expands. Every subsequent
41
+ entity rebinds the same slot arrays and wrapper. The composite CEL compiler
42
+ compiles each logical path once to a numeric slot and the corresponding source
43
+ reader. A joined occurrence selects a child lease; remaining physical-array
44
+ indices are copied into a retained window (not allocated or sliced per read).
45
+ `viaMapping()` streams its mapping file in lockstep with the source and emits
46
+ no wrapper per row.
47
+
48
+ Neither a zero-allocation entire pipeline nor a throughput target has been
49
+ claimed: JSONL parsing, Protobuf strings and asynchronous adapter refills,
50
+ synchronous file reads, pool growth and output materialisation can allocate. Measure warmed field access separately from
51
+ parsing and merge throughput before accepting any optimization.
52
+
53
+
54
+ ## Callback scan contract
55
+
56
+ `composition.scan(visitor)` is the graph execution path: one synchronous callback
57
+ per composed entity and one `Promise<void>` for scan completion. The composite
58
+ lease is closed immediately when the visitor returns (or throws). Returning
59
+ `false` stops the scan; callbacks must not retain or asynchronously access
60
+ borrowed records.
61
+
62
+ Multi-source and mapped joins use `composition.openCursor()` internally. Its
63
+ For the strict COBOL/CSV/JSONL/indexed batch readers, `take()` returns a
64
+ leased row or EOF synchronously, even across physical-buffer refills. A strict
65
+ batch cursor rejects a parser that unexpectedly returns a Promise instead of
66
+ silently switching to per-record async handling. The generic composition
67
+ contract can also accept asynchronous sources, such as Protobuf, without
68
+ using an `AsyncGenerator` or buffering entire input files. Explicit callers of
69
+ `openCursor()` own each lease and must close it; they must also close the cursor.
70
+ The indexed and Protobuf accumulator joins use the same cursor contract.
71
+
72
+ Compiler/planner construction remains outside the measured pass. The scan
73
+ reopens the physical sources and restores pass-local accumulator state.
74
+
75
+ ## Deliberate limits
76
+
77
+ - This package itself consumes prepared sources rather than parsing YAML.
78
+ `@cobol-ts/composition-definition` now parses `files.yaml` declarations and
79
+ prepares those sources; it delegates the actual merge to this package.
80
+ - If an account-to-customer mapping changes the effective key order, the
81
+ composition fails. An explicit external sort/repartition operation would be
82
+ necessary for that input; no hidden in-memory index is built.
83
+ - CEL dereference of optional singular children is rejected at compilation.
84
+ - Nested chained `[index][index]` indexing and general aggregate projection
85
+ materialisation are not yet supplied. `input.accounts[1].balance`, joined
86
+ `map/filter/reduce/sum`, and traversal into source-local arrays are covered.
87
+ - The main schema-first Protobuf writer remains the separate batch output
88
+ facility; this module binds and mutates working state but does not promote
89
+ a newly written output file.
@@ -0,0 +1,4 @@
1
+ export * from './src/composition';
2
+ export * from './src/access';
3
+ export * from './src/accumulator';
4
+ export * from './src/mapping';
package/dist/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/composition"), exports);
18
+ __exportStar(require("./src/access"), exports);
19
+ __exportStar(require("./src/accumulator"), exports);
20
+ __exportStar(require("./src/mapping"), exports);
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC;AAClC,+CAA6B;AAC7B,oDAAkC;AAClC,gDAA8B"}
@@ -0,0 +1,5 @@
1
+ import type { ScalarAccessCompiler, ArrayAccessCompiler } from '@cobol-ts/cel-access';
2
+ import type { CompositeRecord, PreparedSource } from './composition';
3
+ /** Preparation constructs a single fast selector per path. A record read selects a
4
+ * numeric slot and calls the source accessor; paths are never interpreted at runtime. */
5
+ export declare function compositeAccessCompiler(sources: readonly PreparedSource[]): ScalarAccessCompiler<CompositeRecord, unknown, readonly number[]> & ArrayAccessCompiler<CompositeRecord, unknown, readonly number[]>;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compositeAccessCompiler = compositeAccessCompiler;
4
+ const errors_1 = require("@cobol-ts/errors");
5
+ /** Preparation constructs a single fast selector per path. A record read selects a
6
+ * numeric slot and calls the source accessor; paths are never interpreted at runtime. */
7
+ function compositeAccessCompiler(sources) {
8
+ const slotByName = new Map(sources.map((s, i) => [s.name, i]));
9
+ function resolve(path) {
10
+ if (path.length === 0)
11
+ throw new Error('Empty composite path');
12
+ const slot = slotByName.get(path[0]);
13
+ if (slot === undefined)
14
+ throw new Error(`Unknown composite slot ${path[0]}`);
15
+ return { slot, source: sources[slot], child: path.slice(1) };
16
+ }
17
+ function tail(indices, skip, window) {
18
+ const size = indices.length - skip;
19
+ for (let i = 0; i < size; i++)
20
+ window[i] = indices[i + skip];
21
+ window.length = size;
22
+ return window;
23
+ }
24
+ return {
25
+ compileScalar(path) {
26
+ try {
27
+ const { slot, source, child } = resolve(path);
28
+ if (child.length === 0)
29
+ throw new Error('Expected scalar child path');
30
+ if (source.cardinality === 'optional')
31
+ throw new Error(`Optional source ${source.name} requires presence semantics`);
32
+ const compiled = source.access.compileScalar(child);
33
+ if ((0, errors_1.isErrors)(compiled))
34
+ return compiled;
35
+ const reader = compiled.value;
36
+ const joined = source.cardinality === 'many' || source.cardinality === 'manyOptional';
37
+ const suffix = [];
38
+ const read = (record, indices) => {
39
+ const occurrence = joined ? indices[0] : 0;
40
+ if (occurrence === undefined)
41
+ throw new RangeError(`Missing occurrence index for ${source.name}`);
42
+ const representation = record.entry(slot, occurrence).representation;
43
+ return reader.read(representation, joined ? tail(indices, 1, suffix) : indices);
44
+ };
45
+ return (0, errors_1.value)({ type: reader.type, plan: { slot, child: reader.plan },
46
+ integerStorage: reader.integerStorage, read });
47
+ }
48
+ catch (e) {
49
+ return (0, errors_1.errors)(e instanceof Error ? e.message : String(e));
50
+ }
51
+ },
52
+ compileArray(path) {
53
+ try {
54
+ const { slot, source, child } = resolve(path);
55
+ const joined = source.cardinality === 'many' || source.cardinality === 'manyOptional';
56
+ if (child.length === 0) {
57
+ if (!joined)
58
+ throw new Error(`Source ${source.name} is not a joined array`);
59
+ return (0, errors_1.value)({ plan: { slot }, length: (record) => record.count(slot) });
60
+ }
61
+ if (source.cardinality === 'optional')
62
+ throw new Error(`Optional source ${source.name} requires presence semantics`);
63
+ if (source.access.compileArray === undefined)
64
+ throw new Error(`Source ${source.name} does not support array access`);
65
+ const compiled = source.access.compileArray(child);
66
+ if ((0, errors_1.isErrors)(compiled))
67
+ return compiled;
68
+ const reader = compiled.value;
69
+ const suffix = [];
70
+ return (0, errors_1.value)({ plan: { slot, child: reader.plan }, length: (record, indices) => {
71
+ const occurrence = joined ? indices[0] : 0;
72
+ if (occurrence === undefined)
73
+ throw new RangeError(`Missing occurrence index for ${source.name}`);
74
+ return reader.length(record.entry(slot, occurrence).representation, joined ? tail(indices, 1, suffix) : indices);
75
+ } });
76
+ }
77
+ catch (e) {
78
+ return (0, errors_1.errors)(e instanceof Error ? e.message : String(e));
79
+ }
80
+ }
81
+ };
82
+ }
83
+ //# sourceMappingURL=access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.js","sourceRoot":"","sources":["../../src/access.ts"],"names":[],"mappings":";;AAQA,0DA8DC;AAtED,6CAAqE;AAMrE;yFACyF;AACzF,SAAgB,uBAAuB,CAA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AM,MAAM,GAAU,EAAE,CAAC;gBACzB,OAAO,IAAA,cAAK,EAAC,EAAC,IAAI,EAAC,EAAC,IAAI,EAAC,KAAK,EAAC,MAAM,CAAC,IAAI,EAAC,EAAC,MAAM,EAAC,CAAC,MAAsB,EAAC,OAAyB,EAAC,EAAE;wBACnG,MAAM,UAAU,GAAC,MAAM,CAAA,CAAC,CAAA,OAAO,CAAC,CAAC,CAAC,CAAA,CAAC,CAAA,CAAC,CAAC;wBACrC,IAAG,UAAU,KAAG,SAAS;4BAAC,MAAM,IAAI,UAAU,CAAC,gCAAgC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;wBAC9F,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAC,UAAU,CAAC,CAAC,cAAc,EAAC,MAAM,CAAA,CAAC,CAAA,IAAI,CAAC,OAAO,EAAC,CAAC,EAAC,MAAM,CAAC,CAAA,CAAC,CAAA,OAAO,CAAC,CAAC;oBAC7G,CAAC,EAAC,CAAC,CAAC;YACR,CAAC;YAAC,OAAM,CAAC,EAAC,CAAC;gBAAA,OAAO,IAAA,eAAM,EAAC,CAAC,YAAY,KAAK,CAAA,CAAC,CAAA,CAAC,CAAC,OAAO,CAAA,CAAC,CAAA,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;YAAA,CAAC;QACtE,CAAC;KACJ,CAAC;AACN,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { Message } from '@bufbuild/protobuf';
2
+ import type { MessageAccumulatorPool } from '@cobol-ts/cursor-loader-protobuf';
3
+ import { type AccumulatorSchema } from '@cobol-ts/cursor-loader-protobuf';
4
+ import type { CompositeRecord, PreparedComposition } from './composition';
5
+ import type { CallbackLeaseCursor } from '@cobol-ts/cursor-file';
6
+ export interface EvaluationData<Input, Acc, Variables> {
7
+ readonly input: Input;
8
+ readonly acc: Acc;
9
+ readonly variables: Variables;
10
+ }
11
+ export interface EntityLease<Input, Acc, Variables> {
12
+ readonly result: EvaluationData<Input, Acc, Variables>;
13
+ readonly representation: CompositeRecord;
14
+ readonly closed: boolean;
15
+ close(): void;
16
+ }
17
+ export interface AccumulatorBinding<Input, Acc extends Message, Variables> {
18
+ readonly schema: AccumulatorSchema;
19
+ readonly pool: MessageAccumulatorPool<Acc>;
20
+ openCursor(): Promise<CallbackLeaseCursor<EntityLease<Input, Acc, Variables>>>;
21
+ scan(visit: (row: EntityLease<Input, Acc, Variables>) => boolean | void): Promise<void>;
22
+ }
23
+ /** Prepared once: a real self-describing RDW Protobuf cursor or an empty stream.
24
+ * Unmatched customers acquire messages from the very same pool used for decoding. */
25
+ export declare function bindAccumulator<Input, Acc extends Message, Variables>(composition: PreparedComposition<Input>, schema: AccumulatorSchema, filename: string | undefined, variables: Variables, key: (data: Acc) => bigint, optional?: boolean): AccumulatorBinding<Input, Acc, Variables>;
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bindAccumulator = bindAccumulator;
4
+ const promises_1 = require("node:fs/promises");
5
+ const cursor_loader_protobuf_1 = require("@cobol-ts/cursor-loader-protobuf");
6
+ /** Prepared once: a real self-describing RDW Protobuf cursor or an empty stream.
7
+ * Unmatched customers acquire messages from the very same pool used for decoding. */
8
+ function bindAccumulator(composition, schema, filename, variables, key, optional = true) {
9
+ const pool = (0, cursor_loader_protobuf_1.createMessageAccumulatorPool)(schema.message, (0, cursor_loader_protobuf_1.createScalarAccumulatorCodec)(schema));
10
+ const available = [];
11
+ function take(input, working) {
12
+ const entry = available.pop() ?? make();
13
+ entry.input = input;
14
+ entry.working = working;
15
+ entry.active = true;
16
+ const representation = input.representation;
17
+ representation.acc = working.data;
18
+ representation.variables = variables;
19
+ return entry;
20
+ }
21
+ function make() {
22
+ const entry = { input: undefined, working: undefined, active: false };
23
+ const result = {
24
+ get input() { if (!entry.active)
25
+ throw new Error('Entity is closed'); return entry.input.result; },
26
+ get acc() { if (!entry.active)
27
+ throw new Error('Entity is closed'); return entry.working.data; },
28
+ get variables() { if (!entry.active)
29
+ throw new Error('Entity is closed'); return variables; }
30
+ };
31
+ Object.defineProperties(entry, {
32
+ result: { value: result },
33
+ representation: { get() { if (!entry.active)
34
+ throw new Error('Entity is closed'); return entry.input.representation; } },
35
+ closed: { get() { return !entry.active; } }
36
+ });
37
+ entry.close = () => {
38
+ if (!entry.active)
39
+ throw new Error('Entity already closed');
40
+ entry.active = false;
41
+ const input = entry.input, working = entry.working;
42
+ entry.input = undefined;
43
+ entry.working = undefined;
44
+ let failure;
45
+ try {
46
+ input.close();
47
+ }
48
+ catch (e) {
49
+ failure = e;
50
+ }
51
+ try {
52
+ working.close();
53
+ }
54
+ catch (e) {
55
+ failure ??= e;
56
+ }
57
+ available.push(entry);
58
+ if (failure !== undefined)
59
+ throw failure;
60
+ };
61
+ return entry;
62
+ }
63
+ async function openCursor() {
64
+ let exists = false;
65
+ if (filename !== undefined) {
66
+ try {
67
+ await (0, promises_1.access)(filename);
68
+ exists = true;
69
+ }
70
+ catch (e) {
71
+ if (e.code !== 'ENOENT')
72
+ throw e;
73
+ if (!optional)
74
+ throw new Error(`Required accumulator file does not exist: ${filename}`);
75
+ }
76
+ }
77
+ else if (!optional)
78
+ throw new Error('Required accumulator file not specified');
79
+ const input = await composition.openCursor();
80
+ let read;
81
+ try {
82
+ if (exists)
83
+ read = await (0, cursor_loader_protobuf_1.openAccumulatorFileCursor)(filename, { pool, expectedSchema: schema });
84
+ }
85
+ catch (error) {
86
+ await input.close();
87
+ throw error;
88
+ }
89
+ let pending;
90
+ let previous;
91
+ let primed = false, closed = false;
92
+ function accept(row) {
93
+ pending = row;
94
+ if (row === undefined)
95
+ return;
96
+ let id;
97
+ try {
98
+ id = key(row.data);
99
+ }
100
+ catch (error) {
101
+ pending = undefined;
102
+ row.close();
103
+ throw error;
104
+ }
105
+ if (previous !== undefined && id <= previous) {
106
+ pending = undefined;
107
+ row.close();
108
+ throw new Error('Accumulator rows must be strictly ordered by entity ID');
109
+ }
110
+ previous = id;
111
+ }
112
+ function advance() {
113
+ if (read === undefined) {
114
+ pending = undefined;
115
+ return;
116
+ }
117
+ const row = read.take();
118
+ if (row instanceof Promise)
119
+ return row.then(accept);
120
+ accept(row);
121
+ }
122
+ function merge(row) {
123
+ if (row === undefined) {
124
+ if (pending !== undefined)
125
+ throw new Error(`Orphan accumulator entity ${String(key(pending.data))}`);
126
+ return undefined;
127
+ }
128
+ let working;
129
+ try {
130
+ if (typeof row.representation.key !== 'bigint')
131
+ throw new Error('Accumulator entity key must be bigint');
132
+ const id = row.representation.key;
133
+ if (pending !== undefined && key(pending.data) < id)
134
+ throw new Error(`Orphan accumulator entity ${String(key(pending.data))}`);
135
+ if (pending !== undefined && key(pending.data) === id) {
136
+ working = pending;
137
+ pending = undefined;
138
+ const refill = advance();
139
+ if (refill instanceof Promise) {
140
+ const selected = working;
141
+ return refill.then(() => take(row, selected), error => {
142
+ row.close();
143
+ selected?.close();
144
+ throw error;
145
+ });
146
+ }
147
+ }
148
+ else
149
+ working = pool.acquireEmpty(id);
150
+ return take(row, working);
151
+ }
152
+ catch (error) {
153
+ row.close();
154
+ working?.close();
155
+ throw error;
156
+ }
157
+ }
158
+ function pull() {
159
+ const row = input.take();
160
+ return row instanceof Promise ? row.then(merge) : merge(row);
161
+ }
162
+ return {
163
+ take() {
164
+ if (closed)
165
+ throw new Error('Accumulator cursor already closed');
166
+ if (!primed) {
167
+ primed = true;
168
+ const refill = advance();
169
+ if (refill instanceof Promise)
170
+ return refill.then(pull);
171
+ }
172
+ return pull();
173
+ },
174
+ async close() {
175
+ if (closed)
176
+ return;
177
+ closed = true;
178
+ try {
179
+ pending?.close();
180
+ }
181
+ finally {
182
+ try {
183
+ await read?.close();
184
+ }
185
+ finally {
186
+ await input.close();
187
+ }
188
+ }
189
+ }
190
+ };
191
+ }
192
+ async function scan(visit) {
193
+ const cursor = await openCursor();
194
+ try {
195
+ while (true) {
196
+ const result = cursor.take();
197
+ const row = result instanceof Promise ? await result : result;
198
+ if (row === undefined)
199
+ break;
200
+ let keep;
201
+ try {
202
+ keep = visit(row);
203
+ }
204
+ finally {
205
+ row.close();
206
+ }
207
+ if (keep === false)
208
+ break;
209
+ }
210
+ }
211
+ finally {
212
+ await cursor.close();
213
+ }
214
+ }
215
+ return { schema, pool, scan, openCursor };
216
+ }
217
+ //# sourceMappingURL=accumulator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accumulator.js","sourceRoot":"","sources":["../../src/accumulator.ts"],"names":[],"mappings":";;AA6BA,0CAgJC;AA7KD,+CAAwC;AAGxC,6EAC8F;AAuB9F;qFACqF;AACrF,SAAgB,eAAe,CAC3B,WAAsC,EACtC,MAAwB,EACxB,QAAyB,EACzB,SAAmB,EACnB,GAAsB,EACtB,QAAQ,GAAC,IAAI;IAEb,MAAM,IAAI,GAAC,IAAA,qDAA4B,EAAM,MAAM,CAAC,OAAO,EAAC,IAAA,qDAA4B,EAAM,MAAM,CAAC,CAAC,CAAC;IAMvG,MAAM,SAAS,GAAS,EAAE,CAAC;IAC3B,SAAS,IAAI,CAAC,KAA2B,EAAC,OAAwB;QAC9D,MAAM,KAAK,GAAC,SAAS,CAAC,GAAG,EAAE,IAAE,IAAI,EAAE,CAAC;QACpC,KAAK,CAAC,KAAK,GAAC,KAAK,CAAC;QAClB,KAAK,CAAC,OAAO,GAAC,OAAO,CAAC;QACtB,KAAK,CAAC,MAAM,GAAC,IAAI,CAAC;QAClB,MAAM,cAAc,GAAC,KAAK,CAAC,cAAc,CAAC;QAC1C,cAAc,CAAC,GAAG,GAAC,OAAO,CAAC,IAAI,CAAC;QAChC,cAAc,CAAC,SAAS,GAAC,SAAS,CAAC;QACnC,OAAO,KAAK,CAAC;IACjB,CAAC;IACD,SAAS,IAAI;QACT,MAAM,KAAK,GAAC,EAAC,KAAK,EAAC,SAAS,EAAC,OAAO,EAAC,SAAS,EAAC,MAAM,EAAC,KAAK,EAAU,CAAC;QACtE,MAAM,MAAM,GAAC;YACT,IA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,IAAI,EAAE,CAAC;gBAC3B,MAAM,GAAG,GAAC,MAAM,YAAY,OAAO,CAAA,CAAC,CAAA,MAAM,MAAM,CAAA,CAAC,CAAA,MAAM,CAAC;gBACxD,IAAG,GAAG,KAAG,SAAS;oBAAC,MAAM;gBACzB,IAAI,IAAiB,CAAC;gBACtB,IAAG,CAAC;oBAAA,IAAI,GAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBAAA,CAAC;wBACd,CAAC;oBAAA,GAAG,CAAC,KAAK,EAAE,CAAC;gBAAA,CAAC;gBACrB,IAAG,IAAI,KAAG,KAAK;oBAAC,MAAM;YAC1B,CAAC;QACL,CAAC;gBAAO,CAAC;YAAA,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAAA,CAAC;IACnC,CAAC;IACD,OAAO,EAAC,MAAM,EAAC,IAAI,EAAC,IAAI,EAAC,UAAU,EAAC,CAAC;AACzC,CAAC"}
@@ -0,0 +1,45 @@
1
+ import type { ProjectionAuthoring } from '@cobol-ts/cursor-loader-types';
2
+ import type { ScalarAccessCompiler, ArrayAccessCompiler } from '@cobol-ts/cel-access';
3
+ import type { CallbackLeaseCursor, PreparedFileCursorResult } from '@cobol-ts/cursor-file';
4
+ /** Keys must be normalized into one comparable domain before scanning. */
5
+ export type EntityKey = string | number | bigint;
6
+ export type Cardinality = 'one' | 'optional' | 'many' | 'manyOptional';
7
+ export interface PreparedSource<V = unknown, R = unknown> {
8
+ readonly name: string;
9
+ readonly cardinality: Cardinality;
10
+ readonly projection: ProjectionAuthoring;
11
+ readonly access: ScalarAccessCompiler<R, unknown, readonly number[]> & Partial<ArrayAccessCompiler<R, unknown, readonly number[]>>;
12
+ /** This function is compiled/prepared once. A mapping may supply an effective key. */
13
+ readonly key: (lease: PreparedFileCursorResult<V, R>) => EntityKey;
14
+ /** Leased, resumable cursor. Buffer-resident records need no Promise. */
15
+ openCursor(): Promise<CallbackLeaseCursor<PreparedFileCursorResult<V, R>>>;
16
+ }
17
+ export interface CompositeSlot {
18
+ readonly values: PreparedFileCursorResult<unknown, unknown>[];
19
+ size: number;
20
+ }
21
+ /** Stable record layout. Compiled accessors select numeric slots, not paths. */
22
+ export interface CompositeRecord {
23
+ readonly slots: readonly CompositeSlot[];
24
+ readonly active: boolean;
25
+ readonly key: EntityKey;
26
+ acc?: unknown;
27
+ variables?: unknown;
28
+ entry(slot: number, index: number): PreparedFileCursorResult<unknown, unknown>;
29
+ count(slot: number): number;
30
+ }
31
+ export interface CompositeLease<T> {
32
+ readonly result: T;
33
+ readonly representation: CompositeRecord;
34
+ readonly closed: boolean;
35
+ close(): void;
36
+ }
37
+ export interface PreparedComposition<T> {
38
+ readonly projection: ProjectionAuthoring;
39
+ readonly sources: readonly PreparedSource[];
40
+ openCursor(): Promise<CallbackLeaseCursor<CompositeLease<T>>>;
41
+ /** The visitor borrows one composite for its synchronous invocation. */
42
+ scan(visitor: (row: CompositeRecord) => boolean | void): Promise<void>;
43
+ }
44
+ /** No field name resolution, getter creation, array creation or path parsing during a scan. */
45
+ export declare function createComposition<T>(sources: readonly PreparedSource[], masterName: string): PreparedComposition<T>;
@@ -0,0 +1 @@
1
+ export {};