@type-bridge/node 1.5.6 → 1.5.7

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.
@@ -0,0 +1,566 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.materializeValidatedOne = materializeValidatedOne;
4
+ exports.materializeValidatedRows = materializeValidatedRows;
5
+ exports.materializeValidatedPage = materializeValidatedPage;
6
+ exports.materializeValidatedCount = materializeValidatedCount;
7
+ exports.materializeValidatedExists = materializeValidatedExists;
8
+ const codec_js_1 = require("../codec.js");
9
+ const iid_js_1 = require("../iid.js");
10
+ const model_js_1 = require("../model.js");
11
+ const page_js_1 = require("./page.js");
12
+ const references_js_1 = require("./references.js");
13
+ /** @internal Materialize exactly one scalar/tuple/named row from a native proof. */
14
+ function materializeValidatedOne(query, result, models) {
15
+ const rows = materializeValidatedRows(query, result, models);
16
+ if (rows.length !== 1) {
17
+ throw resultDecode("validated_one_row_count_mismatch", "exactly-one execution did not expose exactly one validated row");
18
+ }
19
+ return rows[0];
20
+ }
21
+ /** @internal Materialize frozen scalar/tuple/named rows from one native proof. */
22
+ function materializeValidatedRows(query, result, models) {
23
+ const rowCount = requireCount((0, references_js_1.nativeCall)(() => result.rowCount(query)), "invalid_result_row_count", "validated result exposed an invalid row count");
24
+ const output = preflightOutputShape(query, result);
25
+ if (output.collections.some(Boolean)) {
26
+ throw resultDecode("collection_in_fetch_rows_result", "FetchRows materialization cannot consume a collected output slot");
27
+ }
28
+ const slotCounts = [];
29
+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex += 1) {
30
+ const slotCount = requireCount((0, references_js_1.nativeCall)(() => result.slotCount(query, rowIndex)), "invalid_result_slot_count", "validated result exposed an invalid slot count");
31
+ if (slotCount !== output.collections.length) {
32
+ throw resultDecode("result_slot_count_mismatch", "validated row does not match its exact native output shape");
33
+ }
34
+ slotCounts.push(slotCount);
35
+ }
36
+ // Inspect every opaque slot and nested role player before invoking any user
37
+ // constructor. A hostile token, shape, descriptor, or hydration graph can
38
+ // therefore never cause partial model construction.
39
+ const plans = [];
40
+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex += 1) {
41
+ const row = [];
42
+ const slotCount = slotCounts[rowIndex];
43
+ for (let slotIndex = 0; slotIndex < slotCount; slotIndex += 1) {
44
+ const thing = (0, references_js_1.nativeCall)(() => result.slotThing(query, rowIndex, slotIndex));
45
+ row.push(preflightThing(thing, models, "selected"));
46
+ }
47
+ plans.push(row);
48
+ }
49
+ const rows = [];
50
+ for (const rowPlans of plans) {
51
+ const slots = rowPlans.map(materializeThingPlan);
52
+ if (output.names !== null) {
53
+ rows.push(frozenNamedOutput(output.names, slots));
54
+ }
55
+ else if (slots.length === 1) {
56
+ rows.push(slots[0]);
57
+ }
58
+ else {
59
+ rows.push(Object.freeze(slots));
60
+ }
61
+ }
62
+ return Object.freeze(rows);
63
+ }
64
+ /** @internal Materialize one immutable distinct-root page from a native proof. */
65
+ function materializeValidatedPage(query, result, models, expectedOffset, expectedLimit, includeTotal) {
66
+ const entryCount = requireCount((0, references_js_1.nativeCall)(() => result.pageEntryCount(query)), "invalid_result_page_entry_count", "validated page exposed an invalid entry count");
67
+ const offset = requireU64BigInt((0, references_js_1.nativeCall)(() => result.pageOffset(query)), "invalid_result_page_offset", "validated page exposed an invalid offset");
68
+ const limit = requireU64BigInt((0, references_js_1.nativeCall)(() => result.pageLimit(query)), "invalid_result_page_limit", "validated page exposed an invalid limit", false);
69
+ if (offset !== expectedOffset || limit !== expectedLimit) {
70
+ throw resultDecode("result_page_window_mismatch", "validated page window differs from the exact terminal invocation");
71
+ }
72
+ if (BigInt(entryCount) > limit) {
73
+ throw resultDecode("result_page_entry_count_mismatch", "validated page contains more entries than its exact limit");
74
+ }
75
+ const rawTotal = (0, references_js_1.nativeCall)(() => result.pageTotal(query));
76
+ const total = rawTotal === null
77
+ ? undefined
78
+ : requireU64BigInt(rawTotal, "invalid_result_page_total", "validated page exposed an invalid total");
79
+ if ((includeTotal && total === undefined) || (!includeTotal && total !== undefined)) {
80
+ throw resultDecode("result_page_total_presence_mismatch", "validated page total presence differs from the exact terminal invocation");
81
+ }
82
+ if (total !== undefined) {
83
+ const remaining = total > offset ? total - offset : 0n;
84
+ const expectedEntries = remaining < limit ? remaining : limit;
85
+ if (BigInt(entryCount) !== expectedEntries) {
86
+ throw resultDecode("result_page_total_mismatch", "validated page length is inconsistent with its same-snapshot total and window");
87
+ }
88
+ }
89
+ const output = preflightOutputShape(query, result);
90
+ if (output.collections.filter((collection) => !collection).length !== 1) {
91
+ throw resultDecode("invalid_page_output_shape", "validated page output must contain exactly one singular root slot");
92
+ }
93
+ const valueCounts = [];
94
+ for (let entryIndex = 0; entryIndex < entryCount; entryIndex += 1) {
95
+ const slotCount = requireCount((0, references_js_1.nativeCall)(() => result.pageSlotCount(query, entryIndex)), "invalid_result_slot_count", "validated page exposed an invalid slot count");
96
+ if (slotCount !== output.collections.length) {
97
+ throw resultDecode("result_slot_count_mismatch", "validated page row does not match its exact native output shape");
98
+ }
99
+ const rowCounts = [];
100
+ for (let slotIndex = 0; slotIndex < slotCount; slotIndex += 1) {
101
+ const count = requireCount((0, references_js_1.nativeCall)(() => result.pageSlotValueCount(query, entryIndex, slotIndex)), "invalid_result_slot_value_count", "validated page slot exposed an invalid value count");
102
+ if (!output.collections[slotIndex] && count !== 1) {
103
+ throw resultDecode("singular_page_slot_cardinality_mismatch", "validated singular page slot did not expose exactly one value");
104
+ }
105
+ rowCounts.push(count);
106
+ }
107
+ valueCounts.push(rowCounts);
108
+ }
109
+ // As with FetchRows, complete the opaque graph proof before constructing a
110
+ // single generated model or attribute instance.
111
+ const plans = [];
112
+ for (let entryIndex = 0; entryIndex < entryCount; entryIndex += 1) {
113
+ const row = [];
114
+ for (let slotIndex = 0; slotIndex < output.collections.length; slotIndex += 1) {
115
+ const slot = [];
116
+ const count = valueCounts[entryIndex][slotIndex];
117
+ for (let valueIndex = 0; valueIndex < count; valueIndex += 1) {
118
+ const thing = (0, references_js_1.nativeCall)(() => result.pageSlotThing(query, entryIndex, slotIndex, valueIndex));
119
+ slot.push(preflightThing(thing, models, "selected"));
120
+ }
121
+ row.push(slot);
122
+ }
123
+ plans.push(row);
124
+ }
125
+ const items = [];
126
+ for (const rowPlans of plans) {
127
+ const slots = rowPlans.map((slotPlans, slotIndex) => {
128
+ const values = slotPlans.map(materializeThingPlan);
129
+ return output.collections[slotIndex]
130
+ ? Object.freeze(values)
131
+ : values[0];
132
+ });
133
+ if (output.names !== null) {
134
+ items.push(frozenNamedOutput(output.names, slots));
135
+ }
136
+ else if (slots.length === 1) {
137
+ items.push(slots[0]);
138
+ }
139
+ else {
140
+ items.push(Object.freeze(slots));
141
+ }
142
+ }
143
+ return (0, page_js_1.pageFromValidatedResult)(items, offset, limit, total);
144
+ }
145
+ function frozenNamedOutput(names, values) {
146
+ const named = {};
147
+ for (let index = 0; index < names.length; index += 1) {
148
+ Object.defineProperty(named, names[index], {
149
+ value: values[index],
150
+ writable: false,
151
+ enumerable: true,
152
+ configurable: false,
153
+ });
154
+ }
155
+ return Object.freeze(named);
156
+ }
157
+ /** @internal Preserve one lossless distinct-root count. */
158
+ function materializeValidatedCount(query, result) {
159
+ return requireU64BigInt((0, references_js_1.nativeCall)(() => result.countValue(query)), "invalid_result_count", "validated count exposed an invalid lossless value");
160
+ }
161
+ /** @internal Preserve one distinct-root existence proof. */
162
+ function materializeValidatedExists(query, result) {
163
+ const value = (0, references_js_1.nativeCall)(() => result.existsValue(query));
164
+ if (typeof value !== "boolean") {
165
+ throw resultDecode("invalid_result_exists", "validated existence result did not expose a boolean");
166
+ }
167
+ return value;
168
+ }
169
+ function preflightOutputShape(query, result) {
170
+ const slotCount = requireCount((0, references_js_1.nativeCall)(() => result.outputSlotCount(query)), "invalid_result_slot_count", "validated result exposed an invalid native output slot count");
171
+ if (slotCount === 0 || slotCount > 16) {
172
+ throw resultDecode("invalid_result_slot_count", "validated output must contain between one and sixteen slots");
173
+ }
174
+ const rawNames = (0, references_js_1.nativeCall)(() => result.outputNames(query));
175
+ const names = rawNames === null
176
+ ? null
177
+ : requireNames(rawNames, "output", "invalid_result_output_names");
178
+ if (names !== null && names.length !== slotCount) {
179
+ throw resultDecode("named_result_slot_count_mismatch", "validated named output does not match its exact slot count");
180
+ }
181
+ const collections = [];
182
+ for (let slotIndex = 0; slotIndex < slotCount; slotIndex += 1) {
183
+ const collection = (0, references_js_1.nativeCall)(() => result.outputSlotIsCollection(query, slotIndex));
184
+ if (typeof collection !== "boolean") {
185
+ throw resultDecode("invalid_result_slot_kind", "validated output exposed an invalid slot kind");
186
+ }
187
+ collections.push(collection);
188
+ }
189
+ return Object.freeze({
190
+ names,
191
+ collections: Object.freeze(collections),
192
+ });
193
+ }
194
+ function preflightThing(thing, models, position) {
195
+ const concreteDescriptor = (0, references_js_1.nativeCall)(() => thing.concreteDescriptor());
196
+ const actualKind = (0, references_js_1.nativeCall)(() => thing.thingKind());
197
+ if (typeof concreteDescriptor !== "string") {
198
+ throw resultDecode("invalid_result_descriptor", "validated thing did not expose a concrete descriptor identity");
199
+ }
200
+ const prefix = `${actualKind}:`;
201
+ if (!concreteDescriptor.startsWith(prefix) || concreteDescriptor.length === prefix.length) {
202
+ throw resultDecode("invalid_result_descriptor", "validated thing carries a malformed concrete descriptor identity");
203
+ }
204
+ const typeName = concreteDescriptor.slice(prefix.length);
205
+ if (typeName.includes(":")) {
206
+ throw resultDecode("invalid_result_descriptor", "validated thing carries a non-canonical concrete descriptor identity");
207
+ }
208
+ // Exact concrete lookup is intentional: never substitute a declared base
209
+ // constructor for a subtype returned by the provider.
210
+ const registered = models.get(typeName);
211
+ if (registered === undefined) {
212
+ throw resultDecode("unregistered_result_model", `validated concrete result type '${typeName}' has no registered model constructor`);
213
+ }
214
+ const model = registered;
215
+ const descriptor = modelDescriptor(model, typeName);
216
+ const expectedKind = isRelationDescriptor(descriptor) ? "relation" : "entity";
217
+ if (model.typeName !== typeName ||
218
+ descriptor.type_name !== typeName ||
219
+ actualKind !== expectedKind ||
220
+ concreteDescriptor !== `${expectedKind}:${descriptor.type_name}`) {
221
+ throw resultDecode("result_model_descriptor_mismatch", `validated concrete descriptor '${concreteDescriptor}' does not match its exact model constructor`);
222
+ }
223
+ const iid = (0, references_js_1.nativeCall)(() => thing.iid());
224
+ if (typeof iid !== "string" || iid.length === 0) {
225
+ throw resultDecode("invalid_result_iid", `validated result type '${typeName}' did not expose a non-empty IID`);
226
+ }
227
+ const fields = preflightFields(thing, model, descriptor.owned_attributes);
228
+ const roles = isRelationDescriptor(descriptor)
229
+ ? position === "selected"
230
+ ? preflightRoles(thing, model, descriptor.roles, models)
231
+ : []
232
+ : preflightEntityRoles(thing, typeName);
233
+ return Object.freeze({
234
+ typeName,
235
+ kind: actualKind,
236
+ parentType: descriptor.parent_type,
237
+ model,
238
+ iid,
239
+ fields: Object.freeze(fields),
240
+ roles: Object.freeze(roles),
241
+ });
242
+ }
243
+ function preflightFields(thing, model, descriptors) {
244
+ const typeName = model.typeName;
245
+ const nativeNames = requireNames((0, references_js_1.nativeCall)(() => thing.fieldNames()), "field", "invalid_result_field_names");
246
+ const nativeNameSet = new Set(nativeNames);
247
+ const descriptorByName = uniqueDescriptors(descriptors, (descriptor) => descriptor.field_name, "duplicate_result_model_field", `model constructor '${typeName}' has duplicate descriptor fields`);
248
+ for (const fieldName of nativeNames) {
249
+ if (!descriptorByName.has(fieldName)) {
250
+ throw resultDecode("unknown_result_field", `validated concrete result exposes unknown field '${typeName}.${fieldName}'`);
251
+ }
252
+ }
253
+ for (const [fieldName, spec] of Object.entries(model.schema)) {
254
+ if ((spec instanceof model_js_1.FieldSpec || spec instanceof model_js_1.ListFieldSpec) && !descriptorByName.has(fieldName)) {
255
+ throw resultDecode("result_model_descriptor_mismatch", `model field '${typeName}.${fieldName}' is absent from its concrete descriptor`);
256
+ }
257
+ }
258
+ const plans = [];
259
+ for (const descriptor of descriptors) {
260
+ const fieldName = descriptor.field_name;
261
+ const spec = model.schema[fieldName];
262
+ if (!(spec instanceof model_js_1.FieldSpec || spec instanceof model_js_1.ListFieldSpec)) {
263
+ throw resultDecode("missing_result_model_field", `concrete descriptor field '${typeName}.${fieldName}' has no model field constructor`);
264
+ }
265
+ if (spec.attrType.attrName !== descriptor.attr_name ||
266
+ spec.attrType.valueType !== descriptor.value_type) {
267
+ throw resultDecode("result_model_field_type_mismatch", `model field '${typeName}.${fieldName}' does not match its validated descriptor type`);
268
+ }
269
+ const present = nativeNameSet.has(fieldName);
270
+ if (!present) {
271
+ if (minimumFieldCardinality(spec) > 0) {
272
+ throw resultDecode("missing_result_field", `validated result is missing required field '${typeName}.${fieldName}'`);
273
+ }
274
+ continue;
275
+ }
276
+ const encoded = (0, references_js_1.nativeCall)(() => thing.fieldValuesJson(fieldName));
277
+ if (encoded === null) {
278
+ throw resultDecode("missing_result_field_payload", `validated result listed field '${typeName}.${fieldName}' without its values`);
279
+ }
280
+ const values = decodeFieldValues(encoded, descriptor.value_type, `${typeName}.${fieldName}`);
281
+ requireFieldCardinality(spec, values.length, typeName, fieldName);
282
+ if (spec instanceof model_js_1.FieldSpec && values.length === 0) {
283
+ continue;
284
+ }
285
+ plans.push(Object.freeze({ fieldName, spec, values }));
286
+ }
287
+ return plans;
288
+ }
289
+ function preflightEntityRoles(thing, typeName) {
290
+ const nativeNames = requireNames((0, references_js_1.nativeCall)(() => thing.roleNames()), "role", "invalid_result_role_names");
291
+ if (nativeNames.length !== 0) {
292
+ throw resultDecode("entity_result_has_roles", `validated entity result '${typeName}' unexpectedly exposes relation roles`);
293
+ }
294
+ return [];
295
+ }
296
+ function preflightRoles(thing, model, descriptors, models) {
297
+ const typeName = model.typeName;
298
+ if ((0, references_js_1.nativeCall)(() => thing.roleDataComplete()) !== true) {
299
+ throw resultDecode("incomplete_relation_role_data", `validated relation result '${typeName}' does not carry complete root-role hydration`);
300
+ }
301
+ const nativeNames = requireNames((0, references_js_1.nativeCall)(() => thing.roleNames()), "role", "invalid_result_role_names");
302
+ const nativeNameSet = new Set(nativeNames);
303
+ const descriptorByName = uniqueDescriptors(descriptors, (descriptor) => descriptor.role_name, "duplicate_result_model_role", `model constructor '${typeName}' has duplicate descriptor roles`);
304
+ for (const roleName of nativeNames) {
305
+ if (!descriptorByName.has(roleName)) {
306
+ throw resultDecode("unknown_result_role", `validated relation result exposes unknown role '${typeName}.${roleName}'`);
307
+ }
308
+ }
309
+ const plans = [];
310
+ for (const descriptor of descriptors) {
311
+ const fieldName = descriptor.role_name;
312
+ const spec = model.schema[fieldName];
313
+ if (!(spec instanceof model_js_1.RoleSpec)) {
314
+ throw resultDecode("missing_result_model_role", `concrete descriptor role '${typeName}.${fieldName}' has no model role field`);
315
+ }
316
+ requireRoleDescriptor(spec, descriptor, typeName);
317
+ const count = requireCount((0, references_js_1.nativeCall)(() => thing.rolePlayerCount(fieldName)), "invalid_result_role_player_count", `validated role '${typeName}.${fieldName}' exposed an invalid player count`);
318
+ if (!nativeNameSet.has(fieldName) && count !== 0) {
319
+ throw resultDecode("missing_result_role_payload", `validated relation omitted role '${typeName}.${fieldName}' while exposing players`);
320
+ }
321
+ const [minimum, maximum] = descriptor.cardinality ?? [0, null];
322
+ if (count < minimum || (maximum !== null && count > maximum)) {
323
+ throw resultDecode("result_role_cardinality_mismatch", `validated role '${typeName}.${fieldName}' violates its concrete descriptor cardinality`);
324
+ }
325
+ const players = [];
326
+ for (let index = 0; index < count; index += 1) {
327
+ const player = (0, references_js_1.nativeCall)(() => thing.rolePlayer(fieldName, index));
328
+ const playerPlan = preflightThing(player, models, "role-player");
329
+ if (!isAllowedRolePlayer(playerPlan, descriptor.player_type_names, models)) {
330
+ throw resultDecode("result_role_player_type_mismatch", `validated role '${typeName}.${fieldName}' contains an incompatible concrete player`);
331
+ }
332
+ players.push(playerPlan);
333
+ }
334
+ const multiple = descriptor.cardinality !== null &&
335
+ (descriptor.cardinality[1] === null || descriptor.cardinality[1] > 1);
336
+ plans.push(Object.freeze({
337
+ fieldName,
338
+ multiple,
339
+ players: Object.freeze(players),
340
+ }));
341
+ }
342
+ return plans;
343
+ }
344
+ function isAllowedRolePlayer(player, allowedTypes, models) {
345
+ let current = player;
346
+ const visited = new Set();
347
+ while (current !== null) {
348
+ if (allowedTypes.includes(current.typeName)) {
349
+ return true;
350
+ }
351
+ const parentType = current.parentType;
352
+ if (parentType === null || visited.has(parentType)) {
353
+ return false;
354
+ }
355
+ visited.add(parentType);
356
+ const parent = models.get(parentType);
357
+ if (parent === undefined) {
358
+ return false;
359
+ }
360
+ const descriptor = modelDescriptor(parent, parentType);
361
+ const kind = isRelationDescriptor(descriptor) ? "relation" : "entity";
362
+ if (kind !== player.kind || descriptor.type_name !== parentType) {
363
+ return false;
364
+ }
365
+ current = {
366
+ ...player,
367
+ typeName: parentType,
368
+ parentType: descriptor.parent_type,
369
+ kind,
370
+ model: parent,
371
+ };
372
+ }
373
+ return false;
374
+ }
375
+ function requireRoleDescriptor(spec, descriptor, typeName) {
376
+ const players = spec.players.map((player) => typeof player === "string" ? player : player.typeName);
377
+ if (players.length !== descriptor.player_type_names.length ||
378
+ players.some((player, index) => player !== descriptor.player_type_names[index]) ||
379
+ !equalCardinality(spec.cardinality, descriptor.cardinality)) {
380
+ throw resultDecode("result_model_role_type_mismatch", `model role '${typeName}.${descriptor.role_name}' does not match its validated descriptor`);
381
+ }
382
+ }
383
+ function materializeThingPlan(plan) {
384
+ const values = {};
385
+ for (const field of plan.fields) {
386
+ if (field.spec instanceof model_js_1.ListFieldSpec && field.values.length === 0) {
387
+ values[field.fieldName] = Object.freeze([]);
388
+ continue;
389
+ }
390
+ let hydrated;
391
+ try {
392
+ const entries = field.values.map((value) => [field.spec.attrType.attrName, value]);
393
+ hydrated = (0, codec_js_1.hydrateAttributeEntries)(entries, plan.model.schema)[field.fieldName];
394
+ }
395
+ catch {
396
+ throw resultDecode("result_attribute_construction_failed", `validated field '${plan.typeName}.${field.fieldName}' could not be materialized`);
397
+ }
398
+ if (hydrated === undefined) {
399
+ throw resultDecode("result_field_hydration_failed", `validated field '${plan.typeName}.${field.fieldName}' could not be hydrated`);
400
+ }
401
+ if (Array.isArray(hydrated)) {
402
+ for (const attribute of hydrated)
403
+ Object.freeze(attribute);
404
+ values[field.fieldName] = Object.freeze(hydrated);
405
+ }
406
+ else {
407
+ values[field.fieldName] = Object.freeze(hydrated);
408
+ }
409
+ }
410
+ for (const role of plan.roles) {
411
+ const players = role.players.map(materializeThingPlan);
412
+ if (players.length === 0) {
413
+ if (role.multiple)
414
+ values[role.fieldName] = Object.freeze([]);
415
+ }
416
+ else {
417
+ values[role.fieldName] = role.multiple || players.length > 1
418
+ ? Object.freeze(players)
419
+ : players[0];
420
+ }
421
+ }
422
+ try {
423
+ const instance = (0, iid_js_1.setIid)(new plan.model(Object.freeze(values)), plan.iid);
424
+ if (!(instance instanceof plan.model) || instance._iid !== plan.iid) {
425
+ throw new TypeError("model constructor did not preserve its concrete identity");
426
+ }
427
+ return Object.freeze(instance);
428
+ }
429
+ catch {
430
+ throw resultDecode("result_model_construction_failed", `validated concrete result '${plan.typeName}' could not be constructed`);
431
+ }
432
+ }
433
+ function decodeFieldValues(encoded, valueType, fieldName) {
434
+ let decoded;
435
+ try {
436
+ decoded = JSON.parse(encoded);
437
+ }
438
+ catch {
439
+ throw resultDecode("invalid_result_field_encoding", `validated field '${fieldName}' did not contain valid native JSON`);
440
+ }
441
+ if (!Array.isArray(decoded)) {
442
+ throw resultDecode("invalid_result_field_encoding", `validated field '${fieldName}' did not contain an array of values`);
443
+ }
444
+ try {
445
+ return Object.freeze(decoded.map((value) => {
446
+ requireExactValueTag(value, valueType);
447
+ return (0, codec_js_1.runtimeAttributeValueFromUnknown)(value, valueType);
448
+ }));
449
+ }
450
+ catch {
451
+ throw resultDecode("invalid_result_attribute_value", `validated field '${fieldName}' did not match its concrete descriptor value type`);
452
+ }
453
+ }
454
+ const VALUE_TAGS = Object.freeze({
455
+ string: "String",
456
+ long: "Long",
457
+ double: "Double",
458
+ boolean: "Boolean",
459
+ date: "Date",
460
+ datetime: "DateTime",
461
+ "datetime-tz": "DateTimeTZ",
462
+ decimal: "Decimal",
463
+ duration: "Duration",
464
+ });
465
+ function requireExactValueTag(value, valueType) {
466
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
467
+ throw new TypeError("result attribute value is not tagged");
468
+ }
469
+ const record = value;
470
+ const tag = VALUE_TAGS[valueType];
471
+ const keys = Object.keys(record);
472
+ if (keys.length !== 1 || keys[0] !== tag) {
473
+ throw new TypeError("result attribute value tag does not match its descriptor");
474
+ }
475
+ const raw = record[tag];
476
+ if ((valueType === "double" && (typeof raw !== "number" || !Number.isFinite(raw))) ||
477
+ (valueType === "boolean" && typeof raw !== "boolean") ||
478
+ (!matchesSpecialPrimitive(valueType) && typeof raw !== "string")) {
479
+ throw new TypeError("result attribute value payload has the wrong primitive type");
480
+ }
481
+ if (valueType === "long") {
482
+ if (typeof raw !== "string" || !/^-?(0|[1-9][0-9]*)$/.test(raw)) {
483
+ throw new TypeError("result long value is not canonical");
484
+ }
485
+ BigInt(raw);
486
+ }
487
+ }
488
+ function matchesSpecialPrimitive(valueType) {
489
+ return valueType === "double" || valueType === "boolean";
490
+ }
491
+ function requireFieldCardinality(spec, actual, typeName, fieldName) {
492
+ const [minimum, maximum] = modelFieldCardinality(spec);
493
+ if (actual < minimum || (maximum !== null && actual > maximum)) {
494
+ throw resultDecode("result_field_cardinality_mismatch", `validated field '${typeName}.${fieldName}' violates its model cardinality`);
495
+ }
496
+ }
497
+ function minimumFieldCardinality(spec) {
498
+ return modelFieldCardinality(spec)[0];
499
+ }
500
+ function modelFieldCardinality(spec) {
501
+ if (spec instanceof model_js_1.ListFieldSpec) {
502
+ return spec.card ?? [spec.isOptional ? 0 : 1, null];
503
+ }
504
+ return [spec.isOptional ? 0 : 1, 1];
505
+ }
506
+ function modelDescriptor(model, typeName) {
507
+ try {
508
+ return model.descriptor();
509
+ }
510
+ catch {
511
+ throw resultDecode("result_model_descriptor_failed", `registered result model '${typeName}' could not expose its descriptor`);
512
+ }
513
+ }
514
+ function isRelationDescriptor(descriptor) {
515
+ return "roles" in descriptor;
516
+ }
517
+ function requireCount(value, code, message) {
518
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
519
+ throw resultDecode(code, message);
520
+ }
521
+ return value;
522
+ }
523
+ const MAX_U64 = 18446744073709551615n;
524
+ function requireU64BigInt(value, code, message, allowZero = true) {
525
+ if (typeof value !== "bigint" ||
526
+ value < 0n ||
527
+ value > MAX_U64 ||
528
+ (!allowZero && value === 0n)) {
529
+ throw resultDecode(code, message);
530
+ }
531
+ return value;
532
+ }
533
+ function requireNames(value, kind, code) {
534
+ if (!Array.isArray(value)) {
535
+ throw resultDecode(code, `validated ${kind} names were not an array`);
536
+ }
537
+ const names = [];
538
+ const seen = new Set();
539
+ for (const name of value) {
540
+ if (typeof name !== "string" || name.length === 0 || seen.has(name)) {
541
+ throw resultDecode(code, `validated ${kind} names were empty, duplicated, or malformed`);
542
+ }
543
+ seen.add(name);
544
+ names.push(name);
545
+ }
546
+ return Object.freeze(names);
547
+ }
548
+ function uniqueDescriptors(descriptors, name, code, message) {
549
+ const result = new Map();
550
+ for (const descriptor of descriptors) {
551
+ const descriptorName = name(descriptor);
552
+ if (descriptorName.length === 0 || result.has(descriptorName)) {
553
+ throw resultDecode(code, message);
554
+ }
555
+ result.set(descriptorName, descriptor);
556
+ }
557
+ return result;
558
+ }
559
+ function equalCardinality(left, right) {
560
+ return left === null
561
+ ? right === null
562
+ : right !== null && left[0] === right[0] && left[1] === right[1];
563
+ }
564
+ function resultDecode(code, message) {
565
+ return new references_js_1.TypedMatchError("result_decode", code, message, Object.freeze([{ kind: "result" }]), Object.freeze({}));
566
+ }
@@ -0,0 +1,11 @@
1
+ import type { NativeRustDatabase, NativeRustTransactionContext, RustDatabase, RustTransactionContext } from "../index.js";
2
+ /** @internal Reject structurally forged public execution connections. */
3
+ export declare function isRegisteredRustConnection(connection: unknown): connection is RustDatabase | RustTransactionContext;
4
+ /** @internal Retain an opaque native database without making it a root export. */
5
+ export declare function registerRustDatabaseHandle(database: RustDatabase, native: NativeRustDatabase): void;
6
+ /** @internal Retain an opaque borrowed transaction without making it public. */
7
+ export declare function registerRustTransactionHandle(transaction: RustTransactionContext, native: NativeRustTransactionContext): void;
8
+ /** @internal Resolve database ownership for the typed match executor. */
9
+ export declare function rustDatabaseHandle(connection: RustDatabase | RustTransactionContext): NativeRustDatabase | undefined;
10
+ /** @internal Resolve borrowed transaction ownership for the typed match executor. */
11
+ export declare function rustTransactionHandle(connection: RustDatabase | RustTransactionContext): NativeRustTransactionContext | undefined;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRegisteredRustConnection = isRegisteredRustConnection;
4
+ exports.registerRustDatabaseHandle = registerRustDatabaseHandle;
5
+ exports.registerRustTransactionHandle = registerRustTransactionHandle;
6
+ exports.rustDatabaseHandle = rustDatabaseHandle;
7
+ exports.rustTransactionHandle = rustTransactionHandle;
8
+ const databaseHandles = new WeakMap();
9
+ const transactionHandles = new WeakMap();
10
+ /** @internal Reject structurally forged public execution connections. */
11
+ function isRegisteredRustConnection(connection) {
12
+ if (connection === null ||
13
+ (typeof connection !== "object" && typeof connection !== "function")) {
14
+ return false;
15
+ }
16
+ return databaseHandles.has(connection) || transactionHandles.has(connection);
17
+ }
18
+ /** @internal Retain an opaque native database without making it a root export. */
19
+ function registerRustDatabaseHandle(database, native) {
20
+ databaseHandles.set(database, native);
21
+ }
22
+ /** @internal Retain an opaque borrowed transaction without making it public. */
23
+ function registerRustTransactionHandle(transaction, native) {
24
+ transactionHandles.set(transaction, native);
25
+ }
26
+ /** @internal Resolve database ownership for the typed match executor. */
27
+ function rustDatabaseHandle(connection) {
28
+ return databaseHandles.get(connection);
29
+ }
30
+ /** @internal Resolve borrowed transaction ownership for the typed match executor. */
31
+ function rustTransactionHandle(connection) {
32
+ return transactionHandles.get(connection);
33
+ }
@@ -0,0 +1,33 @@
1
+ import { loadNative } from "../native.js";
2
+ import { type NamedQueryRow, type NamedSelectionInput, type Query, type QueryConnection, type QuerySelections, type SelectedOutputs } from "./query.js";
3
+ import { type BoundVar, type QueryModelClass } from "./references.js";
4
+ type NativeModule = ReturnType<typeof loadNative>;
5
+ type NativeSession = InstanceType<NativeModule["NodeMatchSessionHandle"]>;
6
+ export type MatchMode = "exact" | "subtypes";
7
+ /**
8
+ * Owner of one native reference-construction session.
9
+ *
10
+ * Models are registered lazily from their canonical descriptors. Repeated
11
+ * calls for the same model deliberately return distinct native variables.
12
+ */
13
+ export declare class QuerySession {
14
+ #private;
15
+ constructor(connection: QueryConnection);
16
+ /**
17
+ * Register concrete constructors that JavaScript cannot discover through
18
+ * reverse class reflection. This is session-local metadata only; it does not
19
+ * create a query binding. Register subtype and relation-player descendants
20
+ * here before selecting a declared base with `"subtypes"`.
21
+ */
22
+ registerModels<const Models extends readonly [QueryModelClass, ...QueryModelClass[]]>(...models: Models): this;
23
+ var<Model extends QueryModelClass>(model: Model, matchMode?: MatchMode): BoundVar<InstanceType<Model>>;
24
+ query<const Selections extends QuerySelections>(...selections: Selections): Query<SelectedOutputs<Selections>>;
25
+ queryNamed<const Shape extends object>(selections: NamedSelectionInput<Shape>): Query<readonly [NamedQueryRow<Shape>]>;
26
+ }
27
+ /** @internal Construct a source-test session that can exercise planning without execution. */
28
+ export declare function diagnosticQuerySession(): QuerySession;
29
+ /** @internal Extract the opaque native session for the future Query facade. */
30
+ export declare function nativeSessionHandle(session: QuerySession): NativeSession;
31
+ /** @internal Inspect exact constructor registration in focused binding tests. */
32
+ export declare function registeredModelConstructors(session: QuerySession): ReadonlyMap<string, QueryModelClass>;
33
+ export {};