@x12i/reportic-datasets 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1840 @@
1
+ // packages/reportic-datasets/src/contracts.ts
2
+ var DatasetAdapterRegistry = class {
3
+ adapters = /* @__PURE__ */ new Map();
4
+ constructor(adapters = []) {
5
+ adapters.forEach((adapter) => this.register(adapter));
6
+ }
7
+ register(adapter) {
8
+ if (this.adapters.has(adapter.protocol)) throw new Error("The dataset protocol is already registered.");
9
+ this.adapters.set(adapter.protocol, adapter);
10
+ }
11
+ get(protocol) {
12
+ const adapter = this.adapters.get(protocol);
13
+ if (!adapter) throw datasetError("ADAPTER_UNAVAILABLE", "connection", "The requested adapter is not configured.");
14
+ return adapter;
15
+ }
16
+ list() {
17
+ return [...this.adapters.values()].map(({ protocol, capabilities }) => ({ protocol, capabilities }));
18
+ }
19
+ };
20
+ var DatasetError = class extends Error {
21
+ constructor(diagnostic, status = 422, retryAfterMs, upstreamStatus) {
22
+ super(diagnostic.message);
23
+ this.diagnostic = diagnostic;
24
+ this.status = status;
25
+ this.retryAfterMs = retryAfterMs;
26
+ this.upstreamStatus = upstreamStatus;
27
+ this.name = "DatasetError";
28
+ }
29
+ diagnostic;
30
+ status;
31
+ retryAfterMs;
32
+ upstreamStatus;
33
+ };
34
+ function datasetError(code, phase, message, path) {
35
+ return new DatasetError({ code, phase, message, path });
36
+ }
37
+ var protocols = ["rest", "graphql", "grpc", "postgrest", "mongo"];
38
+
39
+ // packages/reportic-datasets/src/expressions.ts
40
+ import { isObject, safeInput } from "@x12i/reportic-catalog/schema";
41
+ var reserved = /* @__PURE__ */ new Set(["constructor", "prototype", "__proto__"]);
42
+ var identifier = /^[A-Za-z_][A-Za-z0-9_-]{0,79}$/;
43
+ var missing = /* @__PURE__ */ Symbol("missing dataset value");
44
+ var conversions = ["string", "number", "integer", "decimalString", "boolean", "dateTime"];
45
+ function checkJson(value, bytes = 2e6) {
46
+ try {
47
+ safeInput(value);
48
+ const serialized = JSON.stringify(value, (_key, item) => {
49
+ if (typeof item === "number" && (!Number.isFinite(item) || Number.isInteger(item) && !Number.isSafeInteger(item))) {
50
+ throw datasetError("NUMERIC_PRECISION_LIMIT", "mapping", "Use a decimal string for numbers that exceed safe JSON precision.");
51
+ }
52
+ return item;
53
+ });
54
+ if (Buffer.byteLength(serialized ?? "") > bytes) throw new Error();
55
+ } catch (error) {
56
+ if (error instanceof DatasetError) throw error;
57
+ throw datasetError("DATA_LIMIT", "plan", "The value exceeds its JSON limit or contains an unsafe key.");
58
+ }
59
+ }
60
+ function pointerParts(pointer) {
61
+ if (!pointer) return [];
62
+ if (!pointer.startsWith("/") || /~(?![01])/u.test(pointer)) {
63
+ throw datasetError("INVALID_POINTER", "plan", "Use a valid JSON Pointer.", pointer);
64
+ }
65
+ const parts = pointer.slice(1).split("/").map((key) => key.replace(/~1/g, "/").replace(/~0/g, "~"));
66
+ if (parts.length > 32 || parts.some((key) => reserved.has(key))) {
67
+ throw datasetError("INVALID_POINTER", "plan", "The mapping path contains a restricted key.", pointer);
68
+ }
69
+ return parts;
70
+ }
71
+ function readPointer(value, pointer) {
72
+ for (const key of pointerParts(pointer)) {
73
+ if (!Array.isArray(value) && !isObject(value) || !Object.hasOwn(value, key)) return missing;
74
+ if (Array.isArray(value) && !/^(?:0|[1-9]\d*)$/.test(key)) return missing;
75
+ value = value[key];
76
+ }
77
+ return value === void 0 ? missing : value;
78
+ }
79
+ function mappedSchema(expression2, schemas, path) {
80
+ if (!isObject(expression2) || typeof expression2.$get !== "string") return void 0;
81
+ const separator = expression2.$get.indexOf("#");
82
+ let schema = schemas?.[expression2.$get.slice(0, separator)];
83
+ for (const key of pointerParts(expression2.$get.slice(separator + 1))) {
84
+ if (!isObject(schema) || schema.$ref || schema.anyOf || schema.oneOf || schema.allOf) return void 0;
85
+ if (schema.type === "array" && /^(0|[1-9]\d*)$/.test(key)) schema = schema.items;
86
+ else if (isObject(schema.properties) && Object.hasOwn(schema.properties, key)) schema = schema.properties[key];
87
+ else if (schema.additionalProperties === false) {
88
+ throw datasetError("MAPPING_PATH_UNAVAILABLE", "plan", "The approved response schema does not contain this mapping path.", path);
89
+ } else return void 0;
90
+ }
91
+ return schema;
92
+ }
93
+ function itemSchemaFor(expression2, schemas, path) {
94
+ const schema = mappedSchema(expression2, schemas, path);
95
+ return isObject(schema) ? schema.items : void 0;
96
+ }
97
+ function checkExpression(value, scope, path, depth = 0) {
98
+ if (depth > 32) throw datasetError("INVALID_MAPPING", "plan", "This projection is nested too deeply.", path);
99
+ if (Array.isArray(value)) {
100
+ value.forEach((item, index) => checkExpression(item, scope, path + "/" + index, depth + 1));
101
+ return;
102
+ }
103
+ if (!isObject(value)) return;
104
+ const operator = Object.keys(value).find((key) => key.startsWith("$"));
105
+ if (!operator) {
106
+ for (const [key, child] of Object.entries(value)) checkExpression(child, scope, path + "/" + key, depth + 1);
107
+ return;
108
+ }
109
+ if (!["$param", "$page", "$get", "$map"].includes(operator) || Object.keys(value).some((key) => ![operator, "omitIfMissing", "default", "convert"].includes(key)) || value.omitIfMissing !== void 0 && typeof value.omitIfMissing !== "boolean" || value.convert !== void 0 && !conversions.includes(value.convert)) {
110
+ throw datasetError("INVALID_EXPRESSION", "plan", "Use one approved expression with an optional default, omission or checked conversion.", path);
111
+ }
112
+ if (value.omitIfMissing && Object.hasOwn(value, "default")) {
113
+ throw datasetError("INVALID_EXPRESSION", "plan", "Choose either omission or a default for a missing value.", path);
114
+ }
115
+ if (operator === "$param" && !scope.parameters.has(value.$param)) {
116
+ throw datasetError("INVALID_REQUEST_BINDING", "plan", "The parameter is not declared in this phase.", path);
117
+ }
118
+ if (operator === "$page" && !scope.pageFields?.has(value.$page)) {
119
+ throw datasetError("INVALID_REQUEST_BINDING", "plan", "The selected pagination strategy does not provide this value.", path);
120
+ }
121
+ if (operator === "$get") {
122
+ const expression2 = value.$get;
123
+ if (typeof expression2 !== "string" || !expression2.includes("#")) {
124
+ throw datasetError("INVALID_MAPPING", "plan", "Use context#/path to read a value.", path);
125
+ }
126
+ const separator = expression2.indexOf("#");
127
+ const root = expression2.slice(0, separator);
128
+ const parts = pointerParts(expression2.slice(separator + 1));
129
+ if (!scope.contexts.has(root) || root === "results" && !(scope.dependencies ?? scope.results)?.has(parts[0]) || root === "reductions" && !scope.reductions?.has(parts[0])) {
130
+ throw datasetError("INVALID_MAPPING_CONTEXT", "plan", "The referenced context or operation is unavailable here.", path);
131
+ }
132
+ mappedSchema(value, scope.schemas, path);
133
+ }
134
+ if (operator === "$map") {
135
+ const mapping = value.$map;
136
+ if (!isObject(mapping) || !Object.hasOwn(mapping, "items") || !Object.hasOwn(mapping, "item") || Object.keys(mapping).some((key) => !["items", "item"].includes(key))) {
137
+ throw datasetError("INVALID_MAPPING", "plan", "Array mapping needs an items expression and an item projection.", path);
138
+ }
139
+ checkExpression(mapping.items, scope, path + "/items", depth + 1);
140
+ checkExpression(mapping.item, {
141
+ ...scope,
142
+ contexts: /* @__PURE__ */ new Set([...scope.contexts, "item"]),
143
+ schemas: { ...scope.schemas, item: itemSchemaFor(mapping.items, scope.schemas, path + "/items") }
144
+ }, path + "/item", depth + 1);
145
+ }
146
+ }
147
+ function convert(value, conversion, path) {
148
+ if (conversion === "string" && ["string", "boolean", "number"].includes(typeof value)) return String(value);
149
+ if (conversion === "boolean" && (value === "true" || value === "false" || typeof value === "boolean")) {
150
+ return value === true || value === "true";
151
+ }
152
+ const decimal = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;
153
+ if (conversion === "decimalString" && typeof value === "string" && decimal.test(value) && value.length <= 128) return value;
154
+ if (conversion === "decimalString" && typeof value === "number" && Number.isSafeInteger(value)) return String(value);
155
+ if (conversion === "number" || conversion === "integer") {
156
+ const number = typeof value === "string" && decimal.test(value) && value.length <= 128 ? Number(value) : value;
157
+ if (typeof number === "number" && Number.isFinite(number) && (conversion === "integer" ? Number.isSafeInteger(number) : !Number.isInteger(number) || Number.isSafeInteger(number))) {
158
+ return number;
159
+ }
160
+ }
161
+ if (conversion === "dateTime" && typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/i.test(value) && Number.isFinite(Date.parse(value))) {
162
+ return new Date(value).toISOString();
163
+ }
164
+ throw datasetError("MAPPING_TYPE_MISMATCH", "mapping", "The value cannot be converted to " + conversion + ".", path);
165
+ }
166
+ function evaluateExpression(expression2, context, path) {
167
+ if (Array.isArray(expression2)) {
168
+ return expression2.map((value2, index) => evaluateExpression(value2, context, path + "/" + index)).filter((value2) => value2 !== missing);
169
+ }
170
+ if (!isObject(expression2)) return expression2;
171
+ let value;
172
+ if (Object.hasOwn(expression2, "$param")) value = readPointer(context.parameters, "/" + expression2.$param);
173
+ else if (Object.hasOwn(expression2, "$page")) value = readPointer(context.page, "/" + expression2.$page);
174
+ else if (Object.hasOwn(expression2, "$get")) {
175
+ const separator = expression2.$get.indexOf("#");
176
+ value = readPointer(context[expression2.$get.slice(0, separator)], expression2.$get.slice(separator + 1));
177
+ } else if (Object.hasOwn(expression2, "$map")) {
178
+ const items = evaluateExpression(expression2.$map.items, context, path + "/items");
179
+ if (!Array.isArray(items) || items.length > 1e4) {
180
+ throw datasetError("MAPPING_TYPE_MISMATCH", "mapping", "This projection needs a bounded array.", path);
181
+ }
182
+ value = items.map((item, index) => evaluateExpression(expression2.$map.item, { ...context, item }, path + "/" + index)).filter((item) => item !== missing);
183
+ } else {
184
+ return Object.fromEntries(Object.entries(expression2).flatMap(([key, child]) => {
185
+ const mapped = evaluateExpression(child, context, path + "/" + key);
186
+ return mapped === missing ? [] : [[key, mapped]];
187
+ }));
188
+ }
189
+ if (value === missing) {
190
+ if (Object.hasOwn(expression2, "default")) value = expression2.default;
191
+ else if (expression2.omitIfMissing) return missing;
192
+ else throw datasetError("MAPPING_VALUE_MISSING", "mapping", "A required mapping path is missing.", path);
193
+ }
194
+ return expression2.convert ? convert(value, expression2.convert, path) : value;
195
+ }
196
+
197
+ // packages/reportic-datasets/src/plan.ts
198
+ import { z } from "zod";
199
+ import { parseAuthoringYaml } from "@x12i/reportic-core/authoring";
200
+ import { createSchemaValidator, validateSchemaDocument } from "@x12i/reportic-catalog";
201
+ import { isObject as isObject2 } from "@x12i/reportic-catalog/schema";
202
+ var ref = z.string().min(1).max(200);
203
+ var name = z.string().regex(identifier);
204
+ var expression = z.unknown();
205
+ var object = z.record(expression);
206
+ var positive = (max) => z.number().int().min(1).max(max);
207
+ var paginationSchema = z.object({
208
+ mode: z.enum(["cursor", "page", "offset", "range", "nextLink", "keyset", "stream"]),
209
+ size: positive(1e4).default(200),
210
+ start: z.number().int().min(0).max(1e8).optional(),
211
+ initial: z.union([z.string(), z.number(), z.array(z.union([z.string(), z.number()]))]).optional(),
212
+ next: expression,
213
+ hasMore: expression,
214
+ end: z.enum(["missingOrNull", "hasMore", "shortPage", "emptyPage", "range"]).optional()
215
+ }).strict();
216
+ var countSchema = z.object({
217
+ value: expression,
218
+ source: z.enum(["mapping", "adapter"]).default("mapping"),
219
+ precision: z.enum(["exact", "estimated", "unknown"]),
220
+ scope: ref
221
+ }).strict();
222
+ var resultSchema = z.object({
223
+ mode: z.enum(["collection", "object", "scalar"]),
224
+ items: expression,
225
+ item: expression,
226
+ fields: object.optional(),
227
+ value: expression,
228
+ count: countSchema.optional()
229
+ }).strict();
230
+ var operationSchema = z.object({
231
+ sourceRef: ref.optional(),
232
+ operationRef: name,
233
+ dependsOn: z.array(name).max(24).default([]),
234
+ request: z.record(object).default({}),
235
+ result: resultSchema,
236
+ pagination: paginationSchema.optional(),
237
+ businessLimit: positive(1e4).optional(),
238
+ duplicates: z.object({ key: ref, mode: z.enum(["report", "fail", "deduplicate"]) }).strict().optional()
239
+ }).strict();
240
+ var metricSchema = z.object({
241
+ op: z.enum(["count", "countDistinct", "sum", "avg", "min", "max"]),
242
+ field: ref.optional(),
243
+ nulls: z.enum(["skip", "zero", "fail"]).default("skip"),
244
+ missing: z.enum(["skip", "zero", "fail"]).default("fail"),
245
+ empty: z.enum(["null", "zero", "fail"]).default("null"),
246
+ decimals: z.number().int().min(0).max(12).optional()
247
+ }).strict();
248
+ var reductionSchema = metricSchema.extend({
249
+ op: z.enum(["count", "countDistinct", "sum", "avg", "min", "max", "groupBy"]),
250
+ input: name,
251
+ coverage: z.enum(["complete", "declared", "partial"]).default("complete"),
252
+ scope: ref.optional(),
253
+ group: z.object({
254
+ field: ref,
255
+ bucket: z.enum(["day", "month"]).optional(),
256
+ timezone: z.string().min(1).max(100).optional(),
257
+ metrics: z.record(name, metricSchema)
258
+ }).strict().optional()
259
+ }).strict();
260
+ var policySchema = z.object({
261
+ completeness: z.enum(["complete", "allowPartial"]).default("complete"),
262
+ consistency: z.enum(["bestEffort", "snapshotRequired"]).default("bestEffort"),
263
+ maxCalls: positive(200).default(25),
264
+ maxPages: positive(200).default(20),
265
+ maxRows: positive(1e4).default(2e3),
266
+ maxBytes: positive(2e7).default(2e6),
267
+ timeoutMs: positive(12e4).default(15e3),
268
+ concurrency: positive(4).default(2),
269
+ retries: z.number().int().min(0).max(3).default(1),
270
+ partialField: name.optional()
271
+ }).strict();
272
+ var datasetPlanSchema = z.object({
273
+ planVersion: z.literal("1"),
274
+ datasetId: ref,
275
+ outputSchemaRef: ref,
276
+ sourceRef: ref,
277
+ parametersSchema: object.default({ type: "object", additionalProperties: false }),
278
+ defaults: object.default({}),
279
+ dateRanges: z.array(z.object({ from: name, to: name }).strict()).max(8).default([]),
280
+ operations: z.record(name, operationSchema),
281
+ reductions: z.record(name, reductionSchema).default({}),
282
+ output: object,
283
+ policy: policySchema.default({})
284
+ }).strict();
285
+ function parseDatasetPlan(sourceText) {
286
+ if (typeof sourceText !== "string" || Buffer.byteLength(sourceText) > 3e5) {
287
+ throw datasetError("PLAN_SIZE_LIMIT", "plan", "Use a YAML or JSON plan under 300 KB.");
288
+ }
289
+ let input;
290
+ try {
291
+ input = parseAuthoringYaml(sourceText).toJS({ maxAliasCount: 0 });
292
+ } catch {
293
+ throw datasetError("INVALID_PLAN_SOURCE", "plan", "The plan contains invalid or unsupported YAML.");
294
+ }
295
+ checkJson(input, 3e5);
296
+ const result = datasetPlanSchema.safeParse(input);
297
+ if (!result.success) {
298
+ const issue = result.error.issues[0];
299
+ throw datasetError("INVALID_PLAN", "plan", issue.message, "/" + issue.path.join("/"));
300
+ }
301
+ return result.data;
302
+ }
303
+ function scopesFor(pagination) {
304
+ switch (pagination?.mode) {
305
+ case "cursor":
306
+ return /* @__PURE__ */ new Set(["cursor", "limit"]);
307
+ case "keyset":
308
+ return /* @__PURE__ */ new Set(["key", "limit"]);
309
+ case "page":
310
+ return /* @__PURE__ */ new Set(["page", "limit"]);
311
+ case "offset":
312
+ case "range":
313
+ return /* @__PURE__ */ new Set(["offset", "limit"]);
314
+ default:
315
+ return /* @__PURE__ */ new Set();
316
+ }
317
+ }
318
+ function checkPagination(operation, scope, prefix) {
319
+ const { pagination, result, duplicates, businessLimit } = operation.plan;
320
+ if ((pagination || duplicates || businessLimit) && result.mode !== "collection") {
321
+ throw datasetError("INVALID_PAGINATION", "plan", "Page, duplicate and row limits apply to collections.", prefix);
322
+ }
323
+ if (!pagination) return;
324
+ const { mode, end } = pagination;
325
+ operation.adapter.validatePagination?.(operation.approved, mode);
326
+ if (["offset", "range", "keyset", "page"].includes(mode) && !operation.approved.stableOrder) {
327
+ throw datasetError("UNSTABLE_PAGINATION", "plan", "This paging strategy requires an approved stable order with a unique tie breaker.", prefix);
328
+ }
329
+ if (mode === "stream") {
330
+ if (end || pagination.next || pagination.hasMore) throw datasetError("INVALID_PAGINATION", "plan", "A stream ends with a successful terminal status.", prefix);
331
+ return;
332
+ }
333
+ if (!end || end === "range" && mode !== "range" || end === "missingOrNull" && !["cursor", "keyset", "nextLink"].includes(mode)) {
334
+ throw datasetError("INVALID_PAGINATION", "plan", "Choose a termination rule supported by this pagination strategy.", prefix);
335
+ }
336
+ if (end === "hasMore" && pagination.hasMore === void 0) throw datasetError("INVALID_PAGINATION", "plan", "Provide the documented has-more expression.", prefix);
337
+ if (["cursor", "keyset", "nextLink"].includes(mode) && pagination.next === void 0) {
338
+ throw datasetError("INVALID_PAGINATION", "plan", "Provide the next cursor, link or key expression.", prefix);
339
+ }
340
+ checkExpression(pagination.next, { ...scope, contexts: /* @__PURE__ */ new Set([...scope.contexts, ...mode === "keyset" ? ["item"] : []]) }, prefix + "/pagination/next");
341
+ checkExpression(pagination.hasMore, scope, prefix + "/pagination/hasMore");
342
+ }
343
+ function sortOperations(operations) {
344
+ const remaining = new Map(operations.map((operation) => [operation.name, operation]));
345
+ const sorted = [];
346
+ const added = /* @__PURE__ */ new Set();
347
+ while (remaining.size) {
348
+ const ready = [...remaining.values()].filter((operation) => operation.plan.dependsOn.every((name2) => added.has(name2)));
349
+ if (!ready.length) throw datasetError("OPERATION_CYCLE", "plan", "Operation dependencies must be acyclic.");
350
+ for (const operation of ready) {
351
+ remaining.delete(operation.name);
352
+ added.add(operation.name);
353
+ sorted.push(operation);
354
+ }
355
+ }
356
+ return sorted;
357
+ }
358
+ function compileDatasetPlan(sourceText, environment) {
359
+ const plan = parseDatasetPlan(sourceText);
360
+ if (plan.datasetId !== environment.datasetId) throw datasetError("DATASET_PIN_MISMATCH", "plan", "The plan must name its own catalog dataset.");
361
+ const schema = plan.outputSchemaRef === "draft" ? environment.draftSchema : environment.schemas[plan.outputSchemaRef];
362
+ const outputSchemaRef = plan.outputSchemaRef === "draft" ? environment.draftSchemaRef : plan.outputSchemaRef;
363
+ if (schema === void 0 || !outputSchemaRef) throw datasetError("SCHEMA_UNAVAILABLE", "plan", "Choose an authorized output schema version or a reviewed schema draft.");
364
+ for (const [path, definition] of [["/parametersSchema", plan.parametersSchema], ["/outputSchemaRef", schema]]) {
365
+ const errors = validateSchemaDocument(definition, environment.schemas);
366
+ if (errors.length) throw datasetError("INVALID_SCHEMA", "plan", errors[0].message, path);
367
+ }
368
+ const parameterProperties = isObject2(plan.parametersSchema.properties) ? plan.parametersSchema.properties : {};
369
+ const parameters = new Set(Object.keys(parameterProperties));
370
+ const resultNames = new Set(Object.keys(plan.operations));
371
+ if (!resultNames.size || resultNames.size > 24 || Object.keys(plan.reductions).length > 24) {
372
+ throw datasetError("PLAN_LIMIT", "plan", "A plan needs one to 24 operations and at most 24 local reductions.");
373
+ }
374
+ const validateParameters = createSchemaValidator(plan.parametersSchema, environment.schemas).validate;
375
+ for (const [key, value] of Object.entries(plan.defaults)) {
376
+ if (!parameters.has(key) || !createSchemaValidator(parameterProperties[key], environment.schemas).validate(value)) {
377
+ throw datasetError("INVALID_PARAMETER_DEFAULT", "plan", "A configured default does not match its declared parameter.", "/defaults/" + key);
378
+ }
379
+ }
380
+ for (const { from, to } of plan.dateRanges) {
381
+ if (![from, to].every((key) => parameterProperties[key]?.format === "date-time" || parameterProperties[key]?.format === "date")) {
382
+ throw datasetError("INVALID_DATE_RANGE", "plan", "An ordered date range needs two date or date-time parameters.");
383
+ }
384
+ }
385
+ const operations = Object.entries(plan.operations).map(([key, definition]) => {
386
+ const prefix = "/operations/" + key;
387
+ if (definition.dependsOn.some((dependency) => !resultNames.has(dependency))) {
388
+ throw datasetError("UNKNOWN_DEPENDENCY", "plan", "The operation depends on an unknown step.", prefix);
389
+ }
390
+ const source = environment.sources.find((item) => item.id === (definition.sourceRef ?? plan.sourceRef));
391
+ const approved = source && Object.hasOwn(source.operations, definition.operationRef) ? source.operations[definition.operationRef] : void 0;
392
+ if (!source || !approved) throw datasetError("UNAUTHORIZED_SOURCE", "plan", "The pinned source revision or operation is unavailable.", prefix);
393
+ const adapter = environment.registry.get(source.protocol);
394
+ adapter.validateOperation(approved, environment.connectionFor(source));
395
+ const requestValidators = /* @__PURE__ */ new Map();
396
+ const requestScope = { parameters, contexts: /* @__PURE__ */ new Set(["results"]), dependencies: new Set(definition.dependsOn), pageFields: scopesFor(definition.pagination) };
397
+ const responseScope = {
398
+ parameters,
399
+ contexts: /* @__PURE__ */ new Set(["body", "headers", "trailers", "meta", "results"]),
400
+ dependencies: requestScope.dependencies,
401
+ schemas: { body: approved.responseSchema }
402
+ };
403
+ for (const slot of approved.slots) {
404
+ const slotPath = slot.section + "/" + slot.name;
405
+ requestValidators.set(slotPath, { validate: createSchemaValidator(slot.schema).validate, required: Boolean(slot.required) });
406
+ if (slot.required && !Object.hasOwn(definition.request[slot.section] ?? {}, slot.name)) {
407
+ throw datasetError("REQUIRED_REQUEST_SLOT", "plan", "This approved operation requires a request input.", prefix + "/request/" + slotPath);
408
+ }
409
+ }
410
+ for (const [section, inputs] of Object.entries(definition.request)) {
411
+ for (const [field, input] of Object.entries(inputs)) {
412
+ const slotPath = section + "/" + field;
413
+ const path = prefix + "/request/" + slotPath;
414
+ const validator = requestValidators.get(slotPath);
415
+ if (!validator) throw datasetError("INVALID_REQUEST_BINDING", "plan", "This request destination has not been approved.", path);
416
+ checkExpression(input, requestScope, path);
417
+ if (!JSON.stringify(input).includes('"$') && !validator.validate(input)) {
418
+ throw datasetError("INVALID_REQUEST_BINDING", "plan", "The literal does not match the approved request type.", path);
419
+ }
420
+ }
421
+ }
422
+ const { result } = definition;
423
+ if (result.mode === "collection" && (result.items === void 0 || result.item === void 0) || result.mode === "object" && !result.fields || result.mode === "scalar" && result.value === void 0) {
424
+ throw datasetError("INVALID_RESULT_MAPPING", "plan", "Add the required selector and projection for this result mode.", prefix);
425
+ }
426
+ checkExpression(result.items, responseScope, prefix + "/result/items");
427
+ checkExpression(result.item, {
428
+ ...responseScope,
429
+ contexts: /* @__PURE__ */ new Set([...responseScope.contexts, "item"]),
430
+ schemas: { ...responseScope.schemas, item: itemSchemaFor(result.items, responseScope.schemas, prefix + "/result/items") }
431
+ }, prefix + "/result/item");
432
+ checkExpression(result.fields ?? result.value, responseScope, prefix + "/result");
433
+ if (result.count?.source === "mapping" && result.count.value === void 0) throw datasetError("INVALID_COUNT", "plan", "Select a count value.", prefix);
434
+ checkExpression(result.count?.value, responseScope, prefix + "/result/count");
435
+ if (definition.duplicates && !definition.duplicates.key.startsWith("/")) throw datasetError("INVALID_DUPLICATE_KEY", "plan", "Use a JSON Pointer to the mapped row identity.", prefix);
436
+ const operation = {
437
+ name: key,
438
+ plan: definition,
439
+ source,
440
+ approved,
441
+ adapter,
442
+ requestValidators,
443
+ responseValidator: approved.responseSchema ? createSchemaValidator(approved.responseSchema).validate : void 0
444
+ };
445
+ checkPagination(operation, responseScope, prefix);
446
+ return operation;
447
+ });
448
+ for (const [key, reduction] of Object.entries(plan.reductions)) {
449
+ const path = "/reductions/" + key;
450
+ if (plan.operations[reduction.input]?.result.mode !== "collection") throw datasetError("INVALID_REDUCTION", "plan", "Select a normalized collection for this reduction.", path);
451
+ if (reduction.op === "groupBy" && (!reduction.group || !Object.keys(reduction.group.metrics).length)) {
452
+ throw datasetError("INVALID_REDUCTION", "plan", "Grouping requires a field and at least one measure.", path);
453
+ }
454
+ const measures = reduction.group ? Object.values(reduction.group.metrics) : [reduction];
455
+ if (measures.some((metric) => metric.op !== "count" && !metric.field?.startsWith("/"))) {
456
+ throw datasetError("INVALID_REDUCTION", "plan", "Select each measure with an exact JSON Pointer.", path);
457
+ }
458
+ if (reduction.group?.bucket) {
459
+ try {
460
+ new Intl.DateTimeFormat("en", { timeZone: reduction.group.timezone ?? "UTC" });
461
+ } catch {
462
+ throw datasetError("INVALID_REDUCTION", "plan", "The date bucket timezone is invalid.", path);
463
+ }
464
+ }
465
+ }
466
+ checkExpression(plan.output, {
467
+ parameters: /* @__PURE__ */ new Set(),
468
+ contexts: /* @__PURE__ */ new Set(["results", "reductions", "run"]),
469
+ results: resultNames,
470
+ reductions: new Set(Object.keys(plan.reductions))
471
+ }, "/output");
472
+ if (plan.policy.completeness === "allowPartial" && (!plan.policy.partialField || !isObject2(plan.output[plan.policy.partialField]) || plan.output[plan.policy.partialField].$get !== "run#/completeness")) {
473
+ throw datasetError("PARTIAL_DISCLOSURE_REQUIRED", "plan", "Map the run completeness into the declared disclosure field.", "/policy/partialField");
474
+ }
475
+ if (plan.policy.consistency === "snapshotRequired") {
476
+ const first = operations[0];
477
+ if (!first.adapter.openSnapshot || !environment.connectionFor(first.source)?.snapshot || operations.some((operation) => operation.source.id !== first.source.id)) {
478
+ throw datasetError("SNAPSHOT_UNAVAILABLE", "plan", "All steps need one approved source with a shared snapshot capability.");
479
+ }
480
+ operations.forEach((operation) => operation.adapter.validateSnapshot?.(operation.approved));
481
+ }
482
+ return {
483
+ plan,
484
+ operations: sortOperations(operations),
485
+ validateParameters,
486
+ outputSchemaRef,
487
+ validateOutput: createSchemaValidator(schema, environment.schemas).validate
488
+ };
489
+ }
490
+ function validateDatasetPlan(sourceText, environment) {
491
+ try {
492
+ const { plan, operations, outputSchemaRef } = compileDatasetPlan(sourceText, environment);
493
+ return { valid: true, plan, schemaRef: outputSchemaRef, operations: operations.map(({ name: name2, source }) => ({ name: name2, protocol: source.protocol, sourceRef: source.id })), diagnostics: [] };
494
+ } catch (error) {
495
+ const diagnostic = error instanceof DatasetError ? error.diagnostic : {
496
+ code: "INVALID_PLAN",
497
+ phase: "plan",
498
+ message: "The plan or its selected contracts could not be compiled."
499
+ };
500
+ return { valid: false, diagnostics: [diagnostic] };
501
+ }
502
+ }
503
+
504
+ // packages/reportic-datasets/src/engine.ts
505
+ import { setTimeout as sleep } from "timers/promises";
506
+ import { digest } from "@x12i/reportic-catalog";
507
+ import { isObject as isObject3 } from "@x12i/reportic-catalog/schema";
508
+
509
+ // packages/reportic-datasets/src/reductions.ts
510
+ function valuesFor(rows, metric, path) {
511
+ return rows.flatMap((row) => {
512
+ const value = readPointer(row, metric.field ?? "");
513
+ if (value !== missing && value !== null) return [value];
514
+ const policy = value === missing ? metric.missing : metric.nulls;
515
+ if (policy === "fail") throw datasetError("REDUCTION_VALUE_MISSING", "reduction", "A reduction input is null or missing.", path);
516
+ return policy === "zero" ? [0] : [];
517
+ });
518
+ }
519
+ function measure(rows, metric, path) {
520
+ if (metric.op === "count" && !metric.field) return rows.length;
521
+ const values = valuesFor(rows, metric, path);
522
+ if (metric.op === "count") return values.length;
523
+ if (metric.op === "countDistinct") {
524
+ if (values.some((value) => !["string", "number", "boolean"].includes(typeof value))) {
525
+ throw datasetError("REDUCTION_TYPE_MISMATCH", "reduction", "Distinct measures require scalar values.", path);
526
+ }
527
+ return new Set(values).size;
528
+ }
529
+ if (!values.length) {
530
+ if (metric.empty === "fail") throw datasetError("REDUCTION_EMPTY", "reduction", "The measure has no input values.", path);
531
+ return metric.empty === "zero" ? 0 : null;
532
+ }
533
+ if (!values.every((value) => typeof value === "number" && Number.isFinite(value) && (!Number.isInteger(value) || Number.isSafeInteger(value)))) {
534
+ throw datasetError("REDUCTION_TYPE_MISMATCH", "reduction", "Use finite, safely represented numbers in this measure.", path);
535
+ }
536
+ let answer;
537
+ if (metric.op === "min") answer = Math.min(...values);
538
+ else if (metric.op === "max") answer = Math.max(...values);
539
+ else {
540
+ const sum = values.reduce((total, value) => total + value, 0);
541
+ answer = metric.op === "avg" ? sum / values.length : sum;
542
+ }
543
+ if (!Number.isFinite(answer) || Number.isInteger(answer) && !Number.isSafeInteger(answer)) {
544
+ throw datasetError("REDUCTION_PRECISION_LIMIT", "reduction", "The result exceeds safe numeric precision. Use a source-side decimal aggregate.", path);
545
+ }
546
+ return metric.decimals === void 0 ? answer : Number(answer.toFixed(metric.decimals));
547
+ }
548
+ function reduceRows(rows, definition, coverage, path) {
549
+ if (definition.coverage === "complete" && coverage !== "complete" || definition.coverage === "declared" && !["complete", "limitedByDesign"].includes(coverage)) {
550
+ throw datasetError("REDUCTION_COVERAGE_MISMATCH", "reduction", "The collection did not cover the scope required by this reduction.", path);
551
+ }
552
+ if (definition.op !== "groupBy") return measure(rows, definition, path);
553
+ const group = definition.group;
554
+ const groups = /* @__PURE__ */ new Map();
555
+ const formatter = group.bucket ? new Intl.DateTimeFormat("en-CA", {
556
+ timeZone: group.timezone ?? "UTC",
557
+ year: "numeric",
558
+ month: "2-digit",
559
+ day: "2-digit"
560
+ }) : void 0;
561
+ for (const row of rows) {
562
+ let key = valuesFor([row], { ...definition, field: group.field }, path)[0];
563
+ if (key === void 0) continue;
564
+ if (formatter) {
565
+ if (typeof key !== "string" || !/^\d{4}-\d\d-\d\d(?:T.*(?:Z|[+-]\d\d:\d\d))?$/.test(key) || !Number.isFinite(Date.parse(key))) {
566
+ throw datasetError("REDUCTION_TYPE_MISMATCH", "reduction", "Date buckets require ISO dates or timestamp values.", path);
567
+ }
568
+ const parts = Object.fromEntries(formatter.formatToParts(new Date(key)).map((part) => [part.type, part.value]));
569
+ key = parts.year + "-" + parts.month + (group.bucket === "day" ? "-" + parts.day : "");
570
+ }
571
+ if (typeof key !== "string" && typeof key !== "number" && typeof key !== "boolean") {
572
+ throw datasetError("REDUCTION_TYPE_MISMATCH", "reduction", "Grouping needs scalar keys.", path);
573
+ }
574
+ const bucket = groups.get(key) ?? [];
575
+ bucket.push(row);
576
+ groups.set(key, bucket);
577
+ }
578
+ return [...groups].map(([key, bucket]) => ({
579
+ key,
580
+ measures: Object.fromEntries(Object.entries(group.metrics).map(([name2, metric]) => [
581
+ name2,
582
+ measure(bucket, metric, path + "/metrics/" + name2)
583
+ ]))
584
+ }));
585
+ }
586
+
587
+ // packages/reportic-datasets/src/engine.ts
588
+ var DatasetExecutionError = class extends DatasetError {
589
+ constructor(error, metadata) {
590
+ super(error.diagnostic, error.status, error.retryAfterMs, error.upstreamStatus);
591
+ this.metadata = metadata;
592
+ }
593
+ metadata;
594
+ };
595
+ function buildParameters(compiled, input = {}) {
596
+ if (!isObject3(input)) throw datasetError("PARAMETER_SCHEMA_MISMATCH", "request", "Run parameters must be an object.");
597
+ checkJson(input, 1e5);
598
+ const parameters = { ...compiled.plan.defaults, ...input };
599
+ if (!compiled.validateParameters(parameters)) {
600
+ const error = compiled.validateParameters.errors?.[0];
601
+ throw datasetError("PARAMETER_SCHEMA_MISMATCH", "request", "Run parameters " + (error?.message ?? "do not match their schema.") + ".", error?.instancePath);
602
+ }
603
+ for (const { from, to } of compiled.plan.dateRanges) {
604
+ if (parameters[from] !== void 0 && parameters[to] !== void 0 && Date.parse(String(parameters[from])) > Date.parse(String(parameters[to]))) {
605
+ throw datasetError("INVALID_DATE_RANGE", "request", "The start date must be on or before the end date.", "/" + from);
606
+ }
607
+ }
608
+ return parameters;
609
+ }
610
+ function mappedCount(value, precision, scope, path) {
611
+ if (value === null || value === missing || precision === "unknown") return { value: null, precision: "unknown", scope };
612
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 || typeof value === "string" && /^\d{1,40}$/.test(value)) {
613
+ return { value, precision, scope };
614
+ }
615
+ throw datasetError("INVALID_COUNT", "mapping", "Expected a nonnegative integer or exact decimal integer string.", path);
616
+ }
617
+ function requestFor(operation, context) {
618
+ const request = evaluateExpression(operation.plan.request, context, "/operations/" + operation.name + "/request");
619
+ if (!isObject3(request)) throw datasetError("INVALID_REQUEST_BINDING", "request", "The resolved request must be an object.");
620
+ for (const [path, slot] of operation.requestValidators) {
621
+ const value = readPointer(request, "/" + path);
622
+ if (value === missing && !slot.required) continue;
623
+ if (value === missing || !slot.validate(value)) {
624
+ throw datasetError("INVALID_REQUEST_BINDING", "request", "A resolved request input does not satisfy its approved type.", "/request/" + path);
625
+ }
626
+ }
627
+ checkJson(request, 25e4);
628
+ return request;
629
+ }
630
+ function endOfPage(operation, page, reply, items, context) {
631
+ const pagination = operation.plan.pagination;
632
+ if (!pagination) {
633
+ if (reply.exhausted === false) throw datasetError("STREAM_INCOMPLETE", "page", "The source did not reach a successful terminal status.");
634
+ return { done: true };
635
+ }
636
+ if (pagination.mode === "stream") {
637
+ if (reply.exhausted !== true) throw datasetError("STREAM_INCOMPLETE", "page", "The stream did not reach a successful terminal status.");
638
+ return { done: true };
639
+ }
640
+ const path = "/operations/" + operation.name + "/pagination";
641
+ let done;
642
+ let next = missing;
643
+ if (pagination.next !== void 0) {
644
+ const expression2 = pagination.end === "missingOrNull" && isObject3(pagination.next) && Object.hasOwn(pagination.next, "$get") && !Object.hasOwn(pagination.next, "default") ? { ...pagination.next, omitIfMissing: true } : pagination.next;
645
+ next = evaluateExpression(expression2, { ...context, item: items.at(-1) }, path + "/next");
646
+ }
647
+ const nextMissing = next === missing || next === null;
648
+ switch (pagination.end) {
649
+ case "hasMore": {
650
+ const indicator = evaluateExpression(pagination.hasMore, context, path + "/hasMore");
651
+ if (typeof indicator !== "boolean") throw datasetError("INVALID_PAGE_INDICATOR", "page", "The has-more field must be a boolean.", path);
652
+ done = !indicator;
653
+ break;
654
+ }
655
+ case "shortPage":
656
+ done = items.length < page.limit;
657
+ break;
658
+ case "emptyPage":
659
+ done = items.length === 0;
660
+ break;
661
+ case "missingOrNull":
662
+ done = nextMissing;
663
+ break;
664
+ case "range": {
665
+ if (items.length && (!reply.range || reply.range.start !== page.offset || reply.range.end - reply.range.start + 1 !== items.length)) {
666
+ throw datasetError("INVALID_CONTENT_RANGE", "page", "The returned range disagrees with the requested offset or row count.", path);
667
+ }
668
+ if (reply.count?.precision !== "exact" || reply.count.value === null) {
669
+ throw datasetError("COUNT_PRECISION_MISMATCH", "page", "This range terminator requires an exact count.", path);
670
+ }
671
+ const total = BigInt(reply.count.value);
672
+ if (items.length && BigInt(page.offset + items.length) > total) {
673
+ throw datasetError("INVALID_CONTENT_RANGE", "page", "The returned range exceeds its exact count.", path);
674
+ }
675
+ done = BigInt(page.offset + items.length) >= total;
676
+ break;
677
+ }
678
+ default:
679
+ throw datasetError("INVALID_PAGINATION", "page", "This pagination strategy needs a termination rule.", path);
680
+ }
681
+ if (done && !nextMissing && ["shortPage", "emptyPage"].includes(pagination.end)) {
682
+ throw datasetError("PAGE_INDICATOR_CONFLICT", "page", "The stop rule conflicts with the next-page indicator.", path);
683
+ }
684
+ if (done) return { done };
685
+ if (["cursor", "keyset", "nextLink"].includes(pagination.mode)) {
686
+ const scalar = (value) => typeof value === "string" && value.length > 0 && value.length <= 8192 || typeof value === "number" && Number.isSafeInteger(value);
687
+ if (nextMissing || (pagination.mode === "nextLink" ? typeof next !== "string" || !scalar(next) : !scalar(next) && !(pagination.mode === "keyset" && Array.isArray(next) && next.length <= 8 && next.every(scalar)))) {
688
+ throw datasetError("INVALID_NEXT_PAGE", "page", "The source did not provide a usable next-page state.", path);
689
+ }
690
+ return { done, next };
691
+ }
692
+ if (!items.length) throw datasetError("PAGE_STALLED", "page", "An empty page did not satisfy the approved stop rule.", path);
693
+ return { done, next: pagination.mode === "page" ? page.page + 1 : page.offset + items.length };
694
+ }
695
+ function safeFailure(error, signal) {
696
+ if (error instanceof DatasetError) return error;
697
+ if (signal.aborted && signal.reason instanceof DatasetError) return signal.reason;
698
+ return datasetError("SOURCE_REQUEST_FAILED", "request", "The approved source request did not complete.");
699
+ }
700
+ function combinedCoverage(coverage) {
701
+ if (Object.values(coverage).includes("partial")) return "partial";
702
+ return Object.values(coverage).includes("limitedByDesign") ? "limitedByDesign" : "complete";
703
+ }
704
+ async function runDataset(compiled, options) {
705
+ const parameters = buildParameters(compiled, options.parameters);
706
+ const { plan } = compiled;
707
+ const policy = { ...plan.policy };
708
+ if (options.test) {
709
+ policy.maxRows = Math.min(policy.maxRows, 500);
710
+ policy.maxCalls = Math.min(policy.maxCalls, 20);
711
+ policy.maxPages = Math.min(policy.maxPages, 12);
712
+ policy.maxBytes = Math.min(policy.maxBytes, 1e6);
713
+ policy.timeoutMs = Math.min(policy.timeoutMs, 12e3);
714
+ }
715
+ const started = Date.now();
716
+ const deadline = started + policy.timeoutMs;
717
+ const controller = new AbortController();
718
+ const { signal } = controller;
719
+ const onAbort = () => controller.abort(datasetError("DATASET_CANCELLED", "run", "The dataset run was cancelled."));
720
+ if (options.signal?.aborted) onAbort();
721
+ else options.signal?.addEventListener("abort", onAbort, { once: true });
722
+ const timer = setTimeout(() => controller.abort(datasetError("DATASET_TIMEOUT", "run", "The dataset deadline was reached.")), policy.timeoutMs);
723
+ timer.unref();
724
+ const results = {};
725
+ const raw = {};
726
+ const secrets = /* @__PURE__ */ new Map();
727
+ const metadata = {
728
+ schemaRef: compiled.outputSchemaRef,
729
+ planRevision: options.planRevision,
730
+ sourceRefs: [...new Set(compiled.operations.map((operation) => operation.source.id))],
731
+ startedAt: new Date(started).toISOString(),
732
+ finishedAt: "",
733
+ durationMs: 0,
734
+ calls: 0,
735
+ pages: 0,
736
+ rows: 0,
737
+ bytes: 0,
738
+ retries: 0,
739
+ completeness: "complete",
740
+ consistency: "bestEffort",
741
+ counts: {},
742
+ operationCoverage: {},
743
+ reductions: {},
744
+ trace: [],
745
+ diagnostics: []
746
+ };
747
+ let snapshot;
748
+ let pageSlots = 0;
749
+ const finish = () => {
750
+ metadata.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
751
+ metadata.durationMs = Date.now() - started;
752
+ };
753
+ const limit = (name2) => datasetError("SOURCE_LIMIT_REACHED", "page", "The protective " + name2 + " limit stopped this run.");
754
+ const requireLiveProfile = (operation) => {
755
+ const profile = options.connectionFor(operation.source);
756
+ if (operation.source.fixtureOnly || !profile) throw datasetError("UNAUTHORIZED_SOURCE", "connection", "The pinned connection is unavailable for live execution.");
757
+ return profile;
758
+ };
759
+ const secretFor = (operation) => {
760
+ if (options.fixtures) return Promise.resolve(void 0);
761
+ const profile = requireLiveProfile(operation);
762
+ if (!secrets.has(operation.source.id)) {
763
+ const promise = (async () => {
764
+ if (!profile.secretRef) return;
765
+ if (!options.resolveSecret) throw datasetError("SOURCE_CREDENTIAL_UNAVAILABLE", "connection", "The source credential is unavailable.");
766
+ try {
767
+ return await options.resolveSecret(profile.secretRef, {
768
+ workspaceId: operation.source.workspaceId,
769
+ agentId: operation.source.agentId,
770
+ actor: options.actor.id,
771
+ connectionRef: profile.ref,
772
+ signal
773
+ });
774
+ } catch {
775
+ throw datasetError("SOURCE_CREDENTIAL_UNAVAILABLE", "connection", "The source credential could not be resolved.");
776
+ }
777
+ })();
778
+ secrets.set(operation.source.id, promise);
779
+ }
780
+ return secrets.get(operation.source.id);
781
+ };
782
+ const contextFor = async (operation, page) => {
783
+ const profile = options.fixtures ? void 0 : requireLiveProfile(operation);
784
+ return {
785
+ signal,
786
+ deadline: Math.min(deadline, Date.now() + (profile?.timeoutMs ?? policy.timeoutMs)),
787
+ maxBytes: Math.min(policy.maxBytes - metadata.bytes, profile?.maxBytes ?? policy.maxBytes),
788
+ maxRows: policy.maxRows - metadata.rows,
789
+ profile,
790
+ secret: await secretFor(operation),
791
+ page,
792
+ snapshot: snapshot?.value,
793
+ businessLimit: operation.plan.businessLimit
794
+ };
795
+ };
796
+ async function executeOperation(operation) {
797
+ const { name: name2, plan: definition, source, approved, adapter } = operation;
798
+ const prefix = "/operations/" + name2;
799
+ const paging = definition.pagination;
800
+ const page = {
801
+ page: paging?.mode === "page" ? paging.start ?? 1 : 1,
802
+ offset: ["range", "offset"].includes(paging?.mode ?? "") ? paging?.start ?? 0 : 0,
803
+ limit: paging?.size ?? 200,
804
+ mode: paging?.mode,
805
+ cursor: paging?.mode === "cursor" ? paging.initial : void 0,
806
+ key: paging?.mode === "keyset" ? paging.initial : void 0
807
+ };
808
+ const rows = [];
809
+ const seenStates = /* @__PURE__ */ new Set();
810
+ if (paging?.initial !== void 0) seenStates.add(digest(paging.initial));
811
+ const seenRows = /* @__PURE__ */ new Set();
812
+ const dependencies = Object.fromEntries(definition.dependsOn.map((key) => [key, results[key]]));
813
+ let coverage = "complete";
814
+ let fixtureIndex = 0;
815
+ let pageNumber = 0;
816
+ try {
817
+ for (; ; ) {
818
+ signal.throwIfAborted();
819
+ if (pageSlots >= policy.maxPages) throw limit("page");
820
+ pageSlots++;
821
+ if (metadata.rows >= policy.maxRows && definition.result.mode === "collection") throw limit("row");
822
+ const request = requestFor(operation, { parameters, page, results: dependencies });
823
+ const slots = Object.entries(request).flatMap(([section, value]) => Object.keys(value).map((key2) => section + "/" + key2)).slice(0, 40);
824
+ let reply;
825
+ let trace;
826
+ for (let attempt = 1; !reply; attempt++) {
827
+ await options.beforeCall?.(source);
828
+ signal.throwIfAborted();
829
+ if (metadata.calls >= policy.maxCalls) throw limit("call");
830
+ if (metadata.bytes >= policy.maxBytes) throw limit("byte");
831
+ const context2 = await contextFor(operation, page);
832
+ signal.throwIfAborted();
833
+ if (metadata.calls >= policy.maxCalls) throw limit("call");
834
+ metadata.calls++;
835
+ const time = Date.now();
836
+ trace = { operation: name2, protocol: source.protocol, page: pageNumber + 1, attempt, outcome: "accepted", rows: 0, bytes: 0, durationMs: 0, slots };
837
+ try {
838
+ const sample = options.fixtures?.[name2]?.[fixtureIndex++];
839
+ if (options.fixtures && !sample) throw datasetError("FIXTURE_PAGE_MISSING", "request", "The fixture has no response for this request.");
840
+ const response = options.fixtures ? structuredClone(sample) : await adapter.execute(approved, request, context2);
841
+ signal.throwIfAborted();
842
+ trace.bytes = response.bytes ?? Buffer.byteLength(JSON.stringify(response.body) ?? "");
843
+ trace.status = response.status;
844
+ if (trace.bytes < 0 || trace.bytes > context2.maxBytes || metadata.bytes + trace.bytes > policy.maxBytes) throw limit("byte");
845
+ metadata.bytes += trace.bytes;
846
+ checkJson(response.body, policy.maxBytes);
847
+ const normalized = adapter.normalize ? adapter.normalize(approved, response, context2) : response;
848
+ if (operation.responseValidator && !operation.responseValidator(normalized.body)) {
849
+ throw datasetError("SOURCE_SCHEMA_MISMATCH", "mapping", "The source response no longer matches its approved contract.", operation.responseValidator.errors?.[0]?.instancePath);
850
+ }
851
+ reply = normalized;
852
+ } catch (error) {
853
+ const failure = safeFailure(error, signal);
854
+ trace.status ??= failure.upstreamStatus;
855
+ const delay = Math.max(failure.retryAfterMs ?? 0, 100 * 2 ** (attempt - 1) + Math.floor(Math.random() * 55));
856
+ const canRetry = approved.safeToRetry && failure.diagnostic.retryable && attempt <= policy.retries && !signal.aborted && Date.now() + delay < context2.deadline;
857
+ trace.outcome = canRetry ? "retry" : "failed";
858
+ if (!canRetry) throw failure;
859
+ metadata.retries++;
860
+ await sleep(delay, void 0, { signal });
861
+ } finally {
862
+ trace.durationMs = Date.now() - time;
863
+ metadata.trace.push(trace);
864
+ }
865
+ }
866
+ metadata.pages++;
867
+ pageNumber++;
868
+ const context = {
869
+ parameters,
870
+ body: reply.body,
871
+ headers: reply.headers ?? {},
872
+ trailers: reply.trailers ?? {},
873
+ meta: { count: reply.count, range: reply.range, status: reply.status },
874
+ results: dependencies
875
+ };
876
+ if (reply.partial) {
877
+ if (policy.completeness !== "allowPartial") throw datasetError("PARTIAL_DATASET", "page", "The source returned partial results.");
878
+ coverage = "partial";
879
+ metadata.diagnostics.push({ code: "PARTIAL_DATASET", phase: "page", operation: name2, message: "The source returned approved partial values." });
880
+ }
881
+ if (options.includeRaw && approved.rawPreviewPaths?.length) {
882
+ const selected = {};
883
+ for (const path of approved.rawPreviewPaths) {
884
+ const value = readPointer(reply.body, path);
885
+ if (value !== missing) selected[path] = value;
886
+ }
887
+ (raw[name2] ??= []).push(selected);
888
+ }
889
+ const count = definition.result.count;
890
+ if (count) {
891
+ if (count.source === "adapter" && reply.count && count.precision !== reply.count.precision) {
892
+ throw datasetError("COUNT_PRECISION_MISMATCH", "mapping", "The source count does not have the declared precision.", prefix + "/result/count");
893
+ }
894
+ const value = count.source === "adapter" ? reply.count?.value ?? null : evaluateExpression(count.value, context, prefix + "/result/count");
895
+ const observed = mappedCount(value, count.precision, count.scope, prefix + "/result/count");
896
+ const previous = metadata.counts[name2];
897
+ if (previous?.precision === "exact" && observed.precision === "exact" && String(previous.value) !== String(observed.value)) {
898
+ if (snapshot) throw datasetError("COUNT_CHANGED", "page", "The exact total changed inside the shared snapshot.");
899
+ metadata.diagnostics.push({ code: "COUNT_CHANGED", phase: "page", operation: name2, message: "The exact total changed between best-effort reads." });
900
+ }
901
+ metadata.counts[name2] = observed;
902
+ } else if (reply.count) metadata.counts[name2] = reply.count;
903
+ if (definition.result.mode !== "collection") {
904
+ results[name2] = evaluateExpression(definition.result.mode === "object" ? definition.result.fields : definition.result.value, context, prefix + "/result");
905
+ break;
906
+ }
907
+ const items = evaluateExpression(definition.result.items, context, prefix + "/result/items");
908
+ if (!Array.isArray(items)) throw datasetError("INVALID_PAGE_SHAPE", "mapping", "The collection selector did not return an array.", prefix + "/result/items");
909
+ const state = endOfPage(operation, page, reply, items, context);
910
+ if (trace) trace.rows = items.length;
911
+ const available = policy.maxRows - metadata.rows;
912
+ if (items.length > available && policy.completeness !== "allowPartial") throw limit("row");
913
+ metadata.rows += Math.min(items.length, available);
914
+ const duplicate = definition.duplicates;
915
+ let duplicates = 0;
916
+ let clippedByDesign = false;
917
+ for (const item of items.slice(0, available)) {
918
+ if (definition.businessLimit && rows.length >= definition.businessLimit) {
919
+ clippedByDesign = true;
920
+ break;
921
+ }
922
+ const mapped = evaluateExpression(definition.result.item, { ...context, item }, prefix + "/result/item");
923
+ if (mapped === missing) continue;
924
+ if (duplicate) {
925
+ const key2 = readPointer(mapped, duplicate.key);
926
+ if (key2 === missing || key2 === null || !["string", "number", "boolean"].includes(typeof key2)) {
927
+ throw datasetError("INVALID_DUPLICATE_KEY", "mapping", "The mapped row identity is missing or is not scalar.", prefix);
928
+ }
929
+ const hash = digest([key2]);
930
+ if (seenRows.has(hash)) {
931
+ duplicates++;
932
+ if (duplicate.mode === "fail") throw datasetError("DUPLICATE_ROW", "mapping", "A repeated row identity was found.", prefix);
933
+ if (duplicate.mode === "deduplicate") continue;
934
+ }
935
+ seenRows.add(hash);
936
+ }
937
+ rows.push(mapped);
938
+ }
939
+ if (duplicates) metadata.diagnostics.push({
940
+ code: "DUPLICATE_ROWS",
941
+ phase: "mapping",
942
+ operation: name2,
943
+ message: duplicates + " repeated identities " + (duplicate?.mode === "deduplicate" ? "were removed." : "were retained.")
944
+ });
945
+ if (items.length > available) throw limit("row");
946
+ if (definition.businessLimit && rows.length >= definition.businessLimit && (!state.done || clippedByDesign)) {
947
+ if (coverage !== "partial") coverage = "limitedByDesign";
948
+ break;
949
+ }
950
+ if (state.done) break;
951
+ const key = digest([state.next]);
952
+ if (seenStates.has(key) || paging?.initial !== void 0 && digest(state.next) === digest(paging.initial)) {
953
+ throw datasetError("PAGE_STALLED", "page", "The source repeated a cursor, key or page link.", prefix + "/pagination");
954
+ }
955
+ seenStates.add(key);
956
+ if (paging?.mode === "cursor") page.cursor = state.next;
957
+ else if (paging?.mode === "nextLink") page.link = String(state.next);
958
+ else if (paging?.mode === "keyset") page.key = state.next;
959
+ else if (paging?.mode === "page") page.page = Number(state.next);
960
+ else page.offset = Number(state.next);
961
+ }
962
+ } catch (error) {
963
+ const failure = safeFailure(error, signal);
964
+ failure.diagnostic.operation ??= name2;
965
+ if (failure.diagnostic.code === "SOURCE_LIMIT_REACHED" && policy.completeness === "allowPartial" && definition.result.mode === "collection" && rows.length) {
966
+ coverage = "partial";
967
+ metadata.diagnostics.push({ ...failure.diagnostic, code: "PARTIAL_DATASET" });
968
+ } else throw failure;
969
+ }
970
+ if (definition.result.mode === "collection") results[name2] = rows;
971
+ metadata.operationCoverage[name2] = coverage;
972
+ }
973
+ try {
974
+ signal.throwIfAborted();
975
+ if (!options.fixtures) for (const operation of compiled.operations) requireLiveProfile(operation);
976
+ if (policy.consistency === "snapshotRequired") {
977
+ const first = compiled.operations[0];
978
+ if (options.fixtures) throw datasetError("SNAPSHOT_UNAVAILABLE", "connection", "A fixture cannot verify a shared live snapshot.");
979
+ await options.beforeCall?.(first.source);
980
+ snapshot = await first.adapter.openSnapshot(await contextFor(first, { page: 1, offset: 0, limit: 200 }));
981
+ metadata.consistency = "snapshot";
982
+ }
983
+ const pending = new Set(compiled.operations);
984
+ while (pending.size) {
985
+ const ready = [...pending].filter((operation) => operation.plan.dependsOn.every((key) => Object.hasOwn(results, key))).slice(0, snapshot ? 1 : policy.concurrency);
986
+ let failure;
987
+ await Promise.allSettled(ready.map(async (operation) => {
988
+ try {
989
+ await executeOperation(operation);
990
+ } catch (error) {
991
+ failure ??= safeFailure(error, signal);
992
+ controller.abort(failure);
993
+ }
994
+ }));
995
+ if (failure) throw failure;
996
+ ready.forEach((operation) => pending.delete(operation));
997
+ }
998
+ const reductions = {};
999
+ for (const [name2, definition] of Object.entries(plan.reductions)) {
1000
+ const rows = results[definition.input];
1001
+ const coverage = metadata.operationCoverage[definition.input];
1002
+ reductions[name2] = reduceRows(rows, definition, coverage, "/reductions/" + name2);
1003
+ metadata.reductions[name2] = { coverage, rows: rows.length };
1004
+ if (definition.op === "count" && typeof reductions[name2] === "number") {
1005
+ metadata.counts[name2] = mappedCount(reductions[name2], coverage === "partial" ? "estimated" : "exact", definition.scope ?? "mappedCollection", "/reductions/" + name2);
1006
+ }
1007
+ }
1008
+ metadata.completeness = combinedCoverage(metadata.operationCoverage);
1009
+ const data = evaluateExpression(plan.output, { results, reductions, run: { completeness: metadata.completeness, counts: metadata.counts } }, "/output");
1010
+ if (!isObject3(data) || !compiled.validateOutput(data)) {
1011
+ const error = compiled.validateOutput.errors?.[0];
1012
+ throw datasetError("OUTPUT_SCHEMA_MISMATCH", "output", "Normalized output " + (error?.message ?? "must be an object matching the published schema."), error?.instancePath);
1013
+ }
1014
+ checkJson(data, policy.maxBytes);
1015
+ signal.throwIfAborted();
1016
+ finish();
1017
+ return { data, metadata, ...options.includeRaw ? { raw } : {} };
1018
+ } catch (error) {
1019
+ const failure = safeFailure(error, signal);
1020
+ metadata.completeness = "failed";
1021
+ metadata.diagnostics.push(failure.diagnostic);
1022
+ finish();
1023
+ throw new DatasetExecutionError(failure, metadata);
1024
+ } finally {
1025
+ clearTimeout(timer);
1026
+ options.signal?.removeEventListener("abort", onAbort);
1027
+ await snapshot?.close().catch(() => {
1028
+ });
1029
+ }
1030
+ }
1031
+
1032
+ // packages/reportic-datasets/src/service.ts
1033
+ import { randomUUID } from "crypto";
1034
+ import { setTimeout as sleep2 } from "timers/promises";
1035
+ import { z as z2 } from "zod";
1036
+ import { parseAuthoringYaml as parseAuthoringYaml2, indexSource } from "@x12i/reportic-core/authoring";
1037
+ import {
1038
+ audit,
1039
+ CatalogError,
1040
+ createSchemaValidator as createSchemaValidator2,
1041
+ digest as digest2,
1042
+ publishDatasetSchema,
1043
+ scopeMatch
1044
+ } from "@x12i/reportic-catalog";
1045
+ import { isObject as isObject4 } from "@x12i/reportic-catalog/schema";
1046
+ var restrictedKeys = /^(?:authorization|cookie|set-cookie|password|api[-_]?key|access[-_]?token|client[-_]?secret|connection[-_]?string|secret[-_]?value)$/i;
1047
+ var unavailable = () => new CatalogError("RESOURCE_UNAVAILABLE", "Resource not found or unavailable.", 404);
1048
+ var conflict = () => new CatalogError("REVISION_CONFLICT", "A newer revision was saved. Review it before applying your change.", 409);
1049
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
1050
+ var newId = (prefix) => prefix + "_" + randomUUID().replaceAll("-", "");
1051
+ var sourceInput = z2.object({
1052
+ name: z2.string().trim().min(1).max(150),
1053
+ protocol: z2.enum(protocols),
1054
+ connectionRef: z2.string().min(1).max(150).optional(),
1055
+ sourceId: z2.string().max(100).optional(),
1056
+ expectedRevision: z2.number().int().optional(),
1057
+ operations: z2.record(z2.string().regex(identifier), z2.object({
1058
+ label: z2.string().min(1).max(150),
1059
+ slots: z2.array(z2.object({
1060
+ section: z2.enum(["path", "query", "body", "variables", "message", "operands"]),
1061
+ name: z2.string().regex(/^[A-Za-z_][\w.-]{0,79}$/),
1062
+ schema: z2.record(z2.unknown()),
1063
+ required: z2.boolean().optional()
1064
+ }).strict()).max(40),
1065
+ configuration: z2.record(z2.unknown()),
1066
+ responseSchema: z2.record(z2.unknown()).optional(),
1067
+ safeToRetry: z2.boolean().optional(),
1068
+ stableOrder: z2.boolean().optional(),
1069
+ rawPreviewPaths: z2.array(z2.string().max(200)).max(20).optional()
1070
+ }).strict())
1071
+ }).strict();
1072
+ var replyInput = z2.object({
1073
+ body: z2.unknown(),
1074
+ status: z2.number().int().min(0).max(599).optional(),
1075
+ headers: z2.record(z2.string().max(16384)).optional(),
1076
+ trailers: z2.record(z2.string().max(16384)).optional(),
1077
+ exhausted: z2.boolean().optional(),
1078
+ count: z2.object({
1079
+ value: z2.union([z2.number().int().nonnegative().safe(), z2.string().regex(/^\d{1,40}$/), z2.null()]),
1080
+ precision: z2.enum(["exact", "estimated", "unknown"]),
1081
+ scope: z2.string().max(100)
1082
+ }).strict().optional()
1083
+ }).strict();
1084
+ var fixtureInput = z2.record(z2.string().regex(identifier), z2.array(replyInput).min(1).max(25));
1085
+ function checkNoCredentials(value) {
1086
+ if (typeof value === "string" && /\bBearer\s+[\w./+=-]{12,}|\b[a-z][a-z0-9+.-]*:\/\/[^\s/@]+:[^\s/@]+@/i.test(value)) {
1087
+ throw datasetError("INLINE_CREDENTIAL_FORBIDDEN", "plan", "Credentials must come from a host-managed secret reference.");
1088
+ }
1089
+ if (Array.isArray(value)) value.forEach(checkNoCredentials);
1090
+ else if (isObject4(value)) for (const [key, child] of Object.entries(value)) {
1091
+ if (restrictedKeys.test(key)) throw datasetError("INLINE_CREDENTIAL_FORBIDDEN", "plan", "Credentials must come from a host-managed secret reference.");
1092
+ checkNoCredentials(child);
1093
+ }
1094
+ }
1095
+ function withoutValues(run) {
1096
+ const { data, requestDigest, idempotencyKey, workerPid, cancelRequested, ...summary } = run;
1097
+ return { ...summary, resultAvailable: data !== void 0 && Date.parse(run.expiresAt) > Date.now() };
1098
+ }
1099
+ function fixtureSummary(fixture) {
1100
+ const { parameters, responses, ...summary } = fixture;
1101
+ return { ...summary, operations: Object.keys(responses) };
1102
+ }
1103
+ var DatasetService = class {
1104
+ constructor(catalog, options) {
1105
+ this.catalog = catalog;
1106
+ this.options = options;
1107
+ this.concurrency = Math.max(1, Math.min(8, options.concurrency ?? 2));
1108
+ this.resultTtlMs = options.resultTtlMs ?? 36e5;
1109
+ this.runRetentionMs = options.runRetentionMs ?? 864e5;
1110
+ this.maxResultBytes = Math.min(2e6, Math.max(1024, options.maxResultBytes ?? 1e6));
1111
+ this.sweep = setInterval(() => {
1112
+ void this.recoverAndExpire().catch(() => {
1113
+ });
1114
+ }, 6e4);
1115
+ this.sweep.unref();
1116
+ }
1117
+ catalog;
1118
+ options;
1119
+ controllers = /* @__PURE__ */ new Map();
1120
+ queue = [];
1121
+ active = 0;
1122
+ closed = false;
1123
+ sweep;
1124
+ concurrency;
1125
+ resultTtlMs;
1126
+ runRetentionMs;
1127
+ maxResultBytes;
1128
+ dispose() {
1129
+ this.closed = true;
1130
+ clearInterval(this.sweep);
1131
+ for (const controller of this.controllers.values()) controller.abort();
1132
+ this.drain();
1133
+ }
1134
+ async recoverAndExpire() {
1135
+ const snapshot = await this.catalog.storage.read();
1136
+ if (!snapshot.datasetResponseFixtures?.some((fixture) => Date.parse(fixture.expiresAt) <= Date.now()) && !snapshot.datasetRuns?.some((run) => this.isInterrupted(run) || run.data !== void 0 && Date.parse(run.expiresAt) <= Date.now() || Date.parse(run.createdAt) + this.runRetentionMs <= Date.now())) return;
1137
+ await this.catalog.storage.transaction((state) => {
1138
+ const time = Date.now();
1139
+ state.datasetResponseFixtures = (state.datasetResponseFixtures ?? []).filter((fixture) => Date.parse(fixture.expiresAt) > time);
1140
+ state.datasetRuns = (state.datasetRuns ?? []).filter((run) => Date.parse(run.createdAt) + this.runRetentionMs > time);
1141
+ for (const run of state.datasetRuns) {
1142
+ if (Date.parse(run.expiresAt) <= time) delete run.data;
1143
+ if (this.isInterrupted(run)) {
1144
+ run.state = "failed";
1145
+ run.diagnostics = [{ code: "RUN_INTERRUPTED", phase: "run", message: "The worker exited before validating the result. Submit a new run." }];
1146
+ }
1147
+ }
1148
+ });
1149
+ }
1150
+ isInterrupted(run) {
1151
+ if (!["queued", "running"].includes(run.state) || run.workerPid === process.pid) return false;
1152
+ try {
1153
+ process.kill(run.workerPid, 0);
1154
+ return false;
1155
+ } catch (error) {
1156
+ return error.code === "ESRCH";
1157
+ }
1158
+ }
1159
+ async permitted(actor, agentId, action) {
1160
+ try {
1161
+ await this.catalog.authorize(actor, agentId, action);
1162
+ return true;
1163
+ } catch {
1164
+ return false;
1165
+ }
1166
+ }
1167
+ profiles(actor, agentId) {
1168
+ const definitions = typeof this.options.connections === "function" ? this.options.connections(actor.workspaceId, agentId) : this.options.connections ?? [];
1169
+ return definitions.filter((profile) => scopeMatch(profile, actor, agentId));
1170
+ }
1171
+ profileFor(source) {
1172
+ if (source.fixtureOnly) return void 0;
1173
+ const { workspaceId, agentId } = source;
1174
+ const definitions = typeof this.options.connections === "function" ? this.options.connections(workspaceId, agentId) : this.options.connections ?? [];
1175
+ return definitions.find((profile) => profile.workspaceId === workspaceId && profile.agentId === agentId && profile.protocol === source.protocol && profile.ref === source.connectionRef && profile.revision === source.connectionRevision);
1176
+ }
1177
+ async inspectSource(actor, agentId) {
1178
+ await this.catalog.authorize(actor, agentId, "sources.read");
1179
+ const state = await this.catalog.storage.read();
1180
+ return {
1181
+ adapters: this.options.registry.list(),
1182
+ connections: this.profiles(actor, agentId).map(({ ref: ref2, revision, label, protocol, effectiveRole, operationRules, verification }) => ({
1183
+ ref: ref2,
1184
+ revision,
1185
+ label,
1186
+ protocol,
1187
+ effectiveRole,
1188
+ operationRules,
1189
+ verification
1190
+ })),
1191
+ sources: (state.datasetSources ?? []).filter((source) => scopeMatch(source, actor, agentId))
1192
+ };
1193
+ }
1194
+ async approveSource(actor, agentId, input) {
1195
+ await this.catalog.authorize(actor, agentId, "sources.manage");
1196
+ checkJson(input, 1e6);
1197
+ checkNoCredentials(input);
1198
+ const parsed = sourceInput.safeParse(input);
1199
+ if (!parsed.success) throw datasetError("INVALID_SOURCE", "plan", "Enter a source name and approved operation definitions.", "/" + parsed.error.issues[0].path.join("/"));
1200
+ const { protocol, connectionRef, operations, name: name2 } = parsed.data;
1201
+ const profile = connectionRef ? this.profiles(actor, agentId).find((item) => item.ref === connectionRef && item.protocol === protocol) : void 0;
1202
+ if (connectionRef && !profile) throw unavailable();
1203
+ if (Object.keys(operations).length < 1 || Object.keys(operations).length > 24) {
1204
+ throw datasetError("SOURCE_OPERATION_LIMIT", "plan", "Approve one to 24 operations per source revision.");
1205
+ }
1206
+ const adapter = this.options.registry.get(protocol);
1207
+ for (const operation of Object.values(operations)) {
1208
+ const slots = /* @__PURE__ */ new Set();
1209
+ for (const slot of operation.slots) {
1210
+ const key = slot.section + "/" + slot.name;
1211
+ if (slots.has(key) || restrictedKeys.test(slot.name)) throw datasetError("INVALID_REQUEST_SLOT", "plan", "Request slots must be unique and cannot carry credentials.");
1212
+ slots.add(key);
1213
+ try {
1214
+ createSchemaValidator2(slot.schema);
1215
+ } catch {
1216
+ throw datasetError("INVALID_REQUEST_SLOT", "plan", "An approved request slot has an invalid JSON Schema.");
1217
+ }
1218
+ }
1219
+ operation.rawPreviewPaths?.forEach((path) => {
1220
+ if (!pointerParts(path).length) throw datasetError("RAW_SCOPE_REQUIRED", "plan", "Approve specific response fields for raw preview.");
1221
+ });
1222
+ if (operation.responseSchema) {
1223
+ try {
1224
+ createSchemaValidator2(operation.responseSchema);
1225
+ } catch {
1226
+ throw datasetError("INVALID_RESPONSE_SCHEMA", "plan", "The response schema must validate without fetching references.");
1227
+ }
1228
+ }
1229
+ adapter.validateOperation(operation, profile);
1230
+ }
1231
+ return this.catalog.storage.transaction((state) => {
1232
+ const sources = state.datasetSources ??= [];
1233
+ let source = parsed.data.sourceId ? sources.find((item) => item.id === parsed.data.sourceId && scopeMatch(item, actor, agentId)) : void 0;
1234
+ if (parsed.data.sourceId && !source) throw unavailable();
1235
+ if (source && (source.revision !== parsed.data.expectedRevision || source.status === "revoked")) throw conflict();
1236
+ if (!source) {
1237
+ source = { id: newId("source"), name: name2, workspaceId: actor.workspaceId, agentId, status: "active", revision: 0, versions: [] };
1238
+ sources.push(source);
1239
+ }
1240
+ if (source.versions.length >= 50) throw datasetError("SOURCE_VERSION_LIMIT", "plan", "This source reached the retained revision limit.");
1241
+ const revision = {
1242
+ id: newId("src"),
1243
+ sourceId: source.id,
1244
+ revision: (source.versions.at(-1)?.revision ?? 0) + 1,
1245
+ workspaceId: actor.workspaceId,
1246
+ agentId,
1247
+ protocol,
1248
+ connectionRef: connectionRef ?? "fixture",
1249
+ connectionRevision: profile?.revision,
1250
+ fixtureOnly: !profile,
1251
+ operations,
1252
+ publishedAt: now(),
1253
+ publishedBy: actor.id,
1254
+ digest: digest2({ protocol, connectionRef, revision: profile?.revision, operations })
1255
+ };
1256
+ source.name = name2;
1257
+ source.revision++;
1258
+ source.versions.push(revision);
1259
+ audit(state, actor, agentId, "source.approved", source.id, { sourceRef: revision.id, protocol, revision: revision.revision });
1260
+ return { source, revision };
1261
+ });
1262
+ }
1263
+ async setSourceStatus(actor, agentId, sourceId, status, revision) {
1264
+ await this.catalog.authorize(actor, agentId, "sources.manage");
1265
+ if (status !== "active" && status !== "deprecated" && status !== "revoked") throw datasetError("INVALID_SOURCE_STATUS", "plan", "Select active, deprecated or revoked.");
1266
+ return this.catalog.storage.transaction((state) => {
1267
+ const source = state.datasetSources?.find((item) => item.id === sourceId && scopeMatch(item, actor, agentId));
1268
+ if (!source) throw unavailable();
1269
+ if (source.revision !== revision || source.status === "revoked" && status !== "revoked") throw conflict();
1270
+ source.status = status;
1271
+ source.revision++;
1272
+ audit(state, actor, agentId, "source." + status, source.id);
1273
+ return source;
1274
+ });
1275
+ }
1276
+ async testConnection(actor, agentId, sourceRef, signal) {
1277
+ await this.catalog.authorize(actor, agentId, "sources.connect");
1278
+ const state = await this.catalog.storage.read();
1279
+ const source = this.sources(state, actor, agentId).find((item) => item.id === sourceRef);
1280
+ const profile = source && this.profileFor(source);
1281
+ if (!source || !profile) throw unavailable();
1282
+ const adapter = this.options.registry.get(source.protocol);
1283
+ if (!adapter.testConnection) throw datasetError("CONNECTION_TEST_UNAVAILABLE", "connection", "This adapter does not expose a separate connectivity test.");
1284
+ const start = Date.now();
1285
+ const timeout = Math.min(profile.timeoutMs ?? 5e3, 5e3);
1286
+ const bounded = AbortSignal.any([AbortSignal.timeout(timeout), ...signal ? [signal] : []]);
1287
+ return this.withTestSlot(async () => {
1288
+ const secret = profile.secretRef ? await this.options.resolveSecret?.(profile.secretRef, {
1289
+ workspaceId: actor.workspaceId,
1290
+ agentId,
1291
+ actor: actor.id,
1292
+ connectionRef: profile.ref,
1293
+ signal: bounded
1294
+ }) : void 0;
1295
+ if (profile.secretRef && !secret) throw datasetError("SOURCE_CREDENTIAL_UNAVAILABLE", "connection", "The source credential could not be resolved.");
1296
+ await adapter.testConnection({
1297
+ profile,
1298
+ secret,
1299
+ signal: bounded,
1300
+ deadline: start + timeout,
1301
+ maxRows: 1,
1302
+ maxBytes: 8192,
1303
+ page: { page: 1, offset: 0, limit: 1 }
1304
+ });
1305
+ return { connected: true, sourceRef, durationMs: Date.now() - start, effectiveRole: profile.effectiveRole };
1306
+ });
1307
+ }
1308
+ sources(state, actor, agentId) {
1309
+ return (state.datasetSources ?? []).filter((source) => source.status !== "revoked" && scopeMatch(source, actor, agentId)).flatMap((source) => source.versions);
1310
+ }
1311
+ dataset(state, actor, agentId, datasetId) {
1312
+ const dataset = state.datasets.find((item) => item.id === datasetId && item.kind === "dataset" && scopeMatch(item, actor, agentId));
1313
+ if (!dataset) throw unavailable();
1314
+ return dataset;
1315
+ }
1316
+ record(state, actor, agentId, datasetId) {
1317
+ return state.datasetPlans?.find((plan) => plan.datasetId === datasetId && scopeMatch(plan, actor, agentId));
1318
+ }
1319
+ async getPlan(actor, agentId, datasetId) {
1320
+ const dataset = await this.catalog.getDataset(actor, agentId, datasetId);
1321
+ await this.catalog.authorize(actor, agentId, "sources.read");
1322
+ const state = await this.catalog.storage.read();
1323
+ const plan = this.record(state, actor, agentId, datasetId);
1324
+ const templates = await this.permitted(actor, agentId, "templates.read") ? state.templates.filter((template) => scopeMatch(template, actor, agentId) && [template.manifest, ...template.publishedRevisions.map((revision) => revision.manifest)].some((manifest) => Object.values(manifest.dataSetMappings).some((mapping) => mapping.datasetId === datasetId))).map(({ id, name: name2, revision }) => ({ id, name: name2, revision })) : [];
1325
+ return { dataset, plan, templates };
1326
+ }
1327
+ async saveDraft(actor, agentId, datasetId, sourceText, expectedRevision) {
1328
+ await this.catalog.authorize(actor, agentId, "datasets.plan.edit");
1329
+ if (typeof sourceText !== "string" || Buffer.byteLength(sourceText) > 3e5) throw datasetError("PLAN_SIZE_LIMIT", "plan", "Use a YAML or JSON plan under 300 KB.");
1330
+ checkNoCredentials(sourceText);
1331
+ try {
1332
+ checkNoCredentials(parseAuthoringYaml2(sourceText).toJS({ maxAliasCount: 0 }));
1333
+ } catch (error) {
1334
+ if (error instanceof DatasetError) throw error;
1335
+ }
1336
+ return this.catalog.storage.transaction((state) => {
1337
+ this.dataset(state, actor, agentId, datasetId);
1338
+ let record = this.record(state, actor, agentId, datasetId);
1339
+ if ((record?.draft.revision ?? 0) !== expectedRevision) throw conflict();
1340
+ if (!record) {
1341
+ record = { workspaceId: actor.workspaceId, agentId, datasetId, draft: { revision: 0, sourceText: "", updatedAt: now() }, versions: [] };
1342
+ (state.datasetPlans ??= []).push(record);
1343
+ }
1344
+ if (record.draft.sourceText !== sourceText) record.draft = { sourceText, revision: expectedRevision + 1, updatedAt: now() };
1345
+ return record;
1346
+ });
1347
+ }
1348
+ environment(state, actor, agentId, dataset, sourceText) {
1349
+ const plan = parseDatasetPlan(sourceText);
1350
+ checkNoCredentials(plan);
1351
+ const schemas = this.catalog.registryFrom(state, actor, agentId);
1352
+ let draftSchema;
1353
+ if (plan.outputSchemaRef === "draft") {
1354
+ try {
1355
+ draftSchema = JSON.parse(dataset.draftSchemaText);
1356
+ } catch {
1357
+ throw datasetError("INVALID_SCHEMA_JSON", "plan", "Fix the catalog schema draft before testing or publishing.");
1358
+ }
1359
+ } else if (!dataset.versions.some((version) => version.schemaRef === plan.outputSchemaRef)) {
1360
+ throw datasetError("SCHEMA_PIN_MISMATCH", "plan", "The output schema must belong to this dataset.");
1361
+ }
1362
+ const draftSchemaRef = "reportic.dataset." + dataset.id + ".v" + ((dataset.versions.at(-1)?.version ?? 0) + 1);
1363
+ return {
1364
+ registry: this.options.registry,
1365
+ sources: this.sources(state, actor, agentId),
1366
+ schemas,
1367
+ draftSchema,
1368
+ draftSchemaRef,
1369
+ datasetId: dataset.id,
1370
+ connectionFor: (source) => this.profileFor(source)
1371
+ };
1372
+ }
1373
+ async validateDatasetPlan(actor, agentId, datasetId, sourceText) {
1374
+ await this.catalog.authorize(actor, agentId, "datasets.plan.edit");
1375
+ const state = await this.catalog.storage.read();
1376
+ try {
1377
+ const dataset = this.dataset(state, actor, agentId, datasetId);
1378
+ return validateDatasetPlan(sourceText, this.environment(state, actor, agentId, dataset, sourceText));
1379
+ } catch (error) {
1380
+ if (error instanceof DatasetError) return { valid: false, diagnostics: [error.diagnostic] };
1381
+ throw error;
1382
+ }
1383
+ }
1384
+ verifiedDigest(sourceText, state, actor, agentId, dataset) {
1385
+ const environment = this.environment(state, actor, agentId, dataset, sourceText);
1386
+ const compiled = compileDatasetPlan(sourceText, environment);
1387
+ const schema = compiled.plan.outputSchemaRef === "draft" ? environment.draftSchema : environment.schemas[compiled.outputSchemaRef];
1388
+ return { compiled, fingerprint: digest2({ sourceText, schema, schemaRef: compiled.outputSchemaRef, sources: compiled.operations.map((operation) => operation.source.digest) }) };
1389
+ }
1390
+ async withTestSlot(work) {
1391
+ if (this.closed || this.active >= this.concurrency) throw new CatalogError("RUN_CAPACITY", "Execution capacity is busy. Try again shortly.", 429);
1392
+ this.active++;
1393
+ try {
1394
+ return await work();
1395
+ } finally {
1396
+ this.active--;
1397
+ this.drain();
1398
+ }
1399
+ }
1400
+ async testDatasetPlan(actor, agentId, datasetId, input, signal) {
1401
+ await this.catalog.authorize(actor, agentId, "datasets.test");
1402
+ if (input.includeRaw) await this.catalog.authorize(actor, agentId, "datasets.raw");
1403
+ const canView = await this.permitted(actor, agentId, "datasets.results");
1404
+ const state = await this.catalog.storage.read();
1405
+ const dataset = this.dataset(state, actor, agentId, datasetId);
1406
+ const record = this.record(state, actor, agentId, datasetId);
1407
+ if (!record || record.draft.revision !== input.expectedRevision) throw conflict();
1408
+ if (input.mode !== "fixture" && input.mode !== "live") throw datasetError("TEST_MODE_REQUIRED", "run", "Choose a fixture test or an explicit live sample.");
1409
+ let fixtures;
1410
+ let parameters = input.parameters;
1411
+ if (input.mode === "fixture") {
1412
+ const saved = input.fixtureId ? this.findResponseFixture(state, actor, agentId, datasetId, input.fixtureId) : void 0;
1413
+ if (saved) parameters = { ...saved.parameters, ...input.parameters };
1414
+ const responses = saved?.responses ?? input.fixtures;
1415
+ checkJson(responses, 15e5);
1416
+ const parsed = fixtureInput.safeParse(responses);
1417
+ if (!parsed.success) throw datasetError("INVALID_RESPONSE_FIXTURE", "run", "Provide bounded fixture response arrays keyed by plan operation.");
1418
+ fixtures = parsed.data;
1419
+ }
1420
+ const { compiled, fingerprint } = this.verifiedDigest(record.draft.sourceText, state, actor, agentId, dataset);
1421
+ const result = await this.withTestSlot(() => runDataset(compiled, {
1422
+ actor,
1423
+ signal,
1424
+ fixtures,
1425
+ parameters,
1426
+ includeRaw: input.includeRaw,
1427
+ test: true,
1428
+ connectionFor: (source) => this.profileFor(source),
1429
+ resolveSecret: this.options.resolveSecret,
1430
+ beforeCall: (source) => this.checkSource(actor, agentId, source, "datasets.test", input.mode === "live")
1431
+ }));
1432
+ const verification = result.metadata.completeness === "partial" ? void 0 : { digest: fingerprint, mode: input.mode, at: now() };
1433
+ await this.catalog.storage.transaction((current) => {
1434
+ const fresh = this.record(current, actor, agentId, datasetId);
1435
+ if (fresh?.draft.revision === record.draft.revision) fresh.draft.verification = verification;
1436
+ audit(current, actor, agentId, "dataset.plan.tested", datasetId, {
1437
+ mode: input.mode,
1438
+ schemaRef: compiled.outputSchemaRef,
1439
+ calls: result.metadata.calls,
1440
+ completeness: result.metadata.completeness
1441
+ });
1442
+ });
1443
+ return { metadata: result.metadata, data: canView ? result.data : void 0, raw: result.raw, verification };
1444
+ }
1445
+ findResponseFixture(state, actor, agentId, datasetId, fixtureId) {
1446
+ const fixture = state.datasetResponseFixtures?.find((item) => item.id === fixtureId && item.datasetId === datasetId && scopeMatch(item, actor, agentId) && Date.parse(item.expiresAt) > Date.now());
1447
+ if (!fixture) throw unavailable();
1448
+ return fixture;
1449
+ }
1450
+ async listResponseFixtures(actor, agentId, datasetId) {
1451
+ await this.catalog.authorize(actor, agentId, "datasets.test");
1452
+ const state = await this.catalog.storage.read();
1453
+ this.dataset(state, actor, agentId, datasetId);
1454
+ return (state.datasetResponseFixtures ?? []).filter((fixture) => fixture.datasetId === datasetId && scopeMatch(fixture, actor, agentId) && Date.parse(fixture.expiresAt) > Date.now()).map(fixtureSummary);
1455
+ }
1456
+ async getResponseFixture(actor, agentId, datasetId, fixtureId) {
1457
+ await this.catalog.authorize(actor, agentId, "datasets.raw");
1458
+ const state = await this.catalog.storage.read();
1459
+ return this.findResponseFixture(state, actor, agentId, datasetId, fixtureId);
1460
+ }
1461
+ async saveResponseFixture(actor, agentId, datasetId, input) {
1462
+ await this.catalog.authorize(actor, agentId, "datasets.test");
1463
+ await this.catalog.authorize(actor, agentId, "datasets.raw");
1464
+ checkJson(input, 75e4);
1465
+ checkNoCredentials(input);
1466
+ const parsed = fixtureInput.safeParse(input.responses);
1467
+ if (!parsed.success || !Object.keys(parsed.data).length || typeof input.name !== "string" || !input.name.trim() || input.parameters !== void 0 && !isObject4(input.parameters)) {
1468
+ throw datasetError("INVALID_RESPONSE_FIXTURE", "run", "Name the fixture and provide response arrays keyed by operation.");
1469
+ }
1470
+ return this.catalog.storage.transaction((state) => {
1471
+ this.dataset(state, actor, agentId, datasetId);
1472
+ const fixtures = state.datasetResponseFixtures ??= [];
1473
+ if (fixtures.length >= 30 || fixtures.filter((fixture2) => scopeMatch(fixture2, actor, agentId)).length >= 15) {
1474
+ throw new CatalogError("FIXTURE_LIMIT", "Saved response fixtures reached the retention limit.", 429);
1475
+ }
1476
+ const fixture = {
1477
+ id: newId("response"),
1478
+ datasetId,
1479
+ workspaceId: actor.workspaceId,
1480
+ agentId,
1481
+ owner: actor.id,
1482
+ name: input.name.trim().slice(0, 150),
1483
+ createdAt: now(),
1484
+ expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(),
1485
+ parameters: input.parameters ?? {},
1486
+ responses: parsed.data
1487
+ };
1488
+ fixtures.push(fixture);
1489
+ audit(state, actor, agentId, "dataset.response_fixture.saved", datasetId, { fixtureId: fixture.id });
1490
+ return fixtureSummary(fixture);
1491
+ });
1492
+ }
1493
+ async publishDatasetPlan(actor, agentId, datasetId, input) {
1494
+ await this.catalog.authorize(actor, agentId, "datasets.publish");
1495
+ await this.catalog.authorize(actor, agentId, "catalog.publish");
1496
+ return this.catalog.storage.transaction((state) => {
1497
+ const dataset = this.dataset(state, actor, agentId, datasetId);
1498
+ const record = this.record(state, actor, agentId, datasetId);
1499
+ if (!record || record.draft.revision !== input.expectedRevision || dataset.revision !== input.expectedDatasetRevision) throw conflict();
1500
+ if (dataset.status === "archived") throw datasetError("DATASET_ARCHIVED", "plan", "Activate the dataset before publishing an execution plan.");
1501
+ const { compiled, fingerprint } = this.verifiedDigest(record.draft.sourceText, state, actor, agentId, dataset);
1502
+ const verification = record.draft.verification;
1503
+ if (!verification || verification.digest !== fingerprint) throw datasetError("PLAN_VERIFICATION_REQUIRED", "plan", "Test this exact draft with its selected sources and schema before publishing.");
1504
+ if (verification.mode === "fixture") {
1505
+ if (compiled.operations.some((operation) => this.profileFor(operation.source)?.verification === "live")) {
1506
+ throw datasetError("LIVE_VERIFICATION_REQUIRED", "plan", "The host requires a successful live verification for this source.");
1507
+ }
1508
+ if (!input.approveFixture) throw datasetError("FIXTURE_APPROVAL_REQUIRED", "plan", "Review and approve the passing fixture before publishing.");
1509
+ }
1510
+ if (compiled.operations.some((operation) => !operation.source.fixtureOnly && !this.profileFor(operation.source))) {
1511
+ throw datasetError("UNAUTHORIZED_SOURCE", "plan", "A pinned connection revision is no longer approved.");
1512
+ }
1513
+ if (record.versions.length >= 50) throw datasetError("PLAN_VERSION_LIMIT", "plan", "This dataset reached the retained plan limit.");
1514
+ let sourceText = record.draft.sourceText;
1515
+ if (compiled.plan.outputSchemaRef === "draft") {
1516
+ if (dataset.versions.length && !input.approveImpact) throw datasetError("IMPACT_REVIEW_REQUIRED", "plan", "Review downstream usage before publishing a new output schema.");
1517
+ const schema = publishDatasetSchema(state, actor, dataset, input.expectedDatasetRevision, this.catalog.registryFrom(state, actor, agentId));
1518
+ const range = parseAuthoringYaml2(sourceText).getIn(["outputSchemaRef"], true)?.range;
1519
+ if (!range) throw datasetError("INVALID_PLAN_SOURCE", "plan", "The schema reference must be a literal value in the plan.");
1520
+ sourceText = sourceText.slice(0, range[0]) + JSON.stringify(schema.schemaRef) + sourceText.slice(range[1]);
1521
+ }
1522
+ const revision = {
1523
+ revision: (record.versions.at(-1)?.revision ?? 0) + 1,
1524
+ schemaRef: compiled.outputSchemaRef,
1525
+ digest: digest2(sourceText),
1526
+ sourceText,
1527
+ sourceRefs: [...new Set(compiled.operations.map((operation) => operation.source.id))],
1528
+ publishedAt: now(),
1529
+ publishedBy: actor.id,
1530
+ verification
1531
+ };
1532
+ record.versions.push(revision);
1533
+ const { revision: number, schemaRef, digest: hash, publishedAt } = revision;
1534
+ dataset.execution = { activeRevision: number, versions: [...dataset.execution?.versions ?? [], { revision: number, schemaRef, digest: hash, publishedAt }] };
1535
+ if (compiled.plan.outputSchemaRef !== "draft") dataset.revision++;
1536
+ dataset.updatedAt = publishedAt;
1537
+ record.draft = { sourceText, revision: record.draft.revision + 1, updatedAt: publishedAt };
1538
+ audit(state, actor, agentId, "dataset.plan.published", datasetId, { revision: number, schemaRef, sourceRefs: revision.sourceRefs });
1539
+ return { dataset, record, version: revision };
1540
+ });
1541
+ }
1542
+ async activatePlan(actor, agentId, datasetId, revision, expectedDatasetRevision) {
1543
+ await this.catalog.authorize(actor, agentId, "datasets.publish");
1544
+ return this.catalog.storage.transaction((state) => {
1545
+ const dataset = this.dataset(state, actor, agentId, datasetId);
1546
+ if (dataset.revision !== expectedDatasetRevision) throw conflict();
1547
+ const version = this.record(state, actor, agentId, datasetId)?.versions.find((plan) => plan.revision === revision);
1548
+ if (!version || !dataset.execution) throw unavailable();
1549
+ const { compiled } = this.verifiedDigest(version.sourceText, state, actor, agentId, dataset);
1550
+ if (compiled.operations.some((operation) => !operation.source.fixtureOnly && !this.profileFor(operation.source))) throw unavailable();
1551
+ dataset.execution.activeRevision = revision;
1552
+ dataset.revision++;
1553
+ dataset.updatedAt = now();
1554
+ audit(state, actor, agentId, "dataset.plan.activated", datasetId, { revision });
1555
+ return dataset;
1556
+ });
1557
+ }
1558
+ async checkSource(actor, agentId, source, action, live) {
1559
+ await this.catalog.authorize(actor, agentId, action);
1560
+ const state = await this.catalog.storage.read();
1561
+ if (!this.sources(state, actor, agentId).some((item) => item.id === source.id) || live && !this.profileFor(source)) {
1562
+ throw datasetError("UNAUTHORIZED_SOURCE", "connection", "The pinned source or its connection grant has been revoked.");
1563
+ }
1564
+ }
1565
+ drain() {
1566
+ while (this.active < this.concurrency && this.queue.length) {
1567
+ const execute = this.queue.shift();
1568
+ this.active++;
1569
+ void execute().catch(() => {
1570
+ }).finally(() => {
1571
+ this.active--;
1572
+ this.drain();
1573
+ });
1574
+ }
1575
+ }
1576
+ async submitRun(actor, agentId, datasetId, input, idempotencyKey) {
1577
+ await this.catalog.authorize(actor, agentId, "datasets.execute");
1578
+ if (this.closed) throw new CatalogError("RUN_CAPACITY", "The execution service is shutting down.", 503);
1579
+ if (idempotencyKey && !/^[A-Za-z0-9_.:-]{1,160}$/.test(idempotencyKey)) throw datasetError("INVALID_IDEMPOTENCY_KEY", "run", "Use an idempotency key up to 160 characters.");
1580
+ await this.recoverAndExpire();
1581
+ const state = await this.catalog.storage.read();
1582
+ const dataset = this.dataset(state, actor, agentId, datasetId);
1583
+ const version = this.record(state, actor, agentId, datasetId)?.versions.find((plan) => plan.revision === input.planRevision);
1584
+ if (!version) throw unavailable();
1585
+ const { compiled } = this.verifiedDigest(version.sourceText, state, actor, agentId, dataset);
1586
+ if (compiled.operations.some((operation) => operation.source.fixtureOnly || !this.profileFor(operation.source))) {
1587
+ throw datasetError("UNAUTHORIZED_SOURCE", "connection", "This plan needs an approved live connection for every operation.");
1588
+ }
1589
+ const parameters = buildParameters(compiled, input.parameters);
1590
+ const requestDigest = digest2({ planRevision: version.revision, parameters });
1591
+ compiled.plan.policy.maxBytes = Math.min(compiled.plan.policy.maxBytes, this.maxResultBytes);
1592
+ const submitted = await this.catalog.storage.transaction((current) => {
1593
+ const runs = current.datasetRuns ??= [];
1594
+ const existing = idempotencyKey && runs.find((run3) => run3.datasetId === datasetId && run3.actor === actor.id && scopeMatch(run3, actor, agentId) && run3.idempotencyKey === idempotencyKey);
1595
+ if (existing) {
1596
+ if (existing.requestDigest !== requestDigest) throw new CatalogError("IDEMPOTENCY_CONFLICT", "This key is already attached to another request.", 409);
1597
+ return { run: existing, created: false };
1598
+ }
1599
+ if (runs.filter((run3) => ["queued", "running"].includes(run3.state)).length >= 24 || runs.length >= 120) {
1600
+ throw new CatalogError("RUN_CAPACITY", "Run history or the execution queue reached its retention limit.", 429);
1601
+ }
1602
+ const run2 = {
1603
+ id: newId("run"),
1604
+ datasetId,
1605
+ workspaceId: actor.workspaceId,
1606
+ agentId,
1607
+ actor: actor.id,
1608
+ planRevision: version.revision,
1609
+ schemaRef: version.schemaRef,
1610
+ sourceRefs: version.sourceRefs,
1611
+ state: "queued",
1612
+ createdAt: now(),
1613
+ expiresAt: new Date(Date.now() + this.resultTtlMs).toISOString(),
1614
+ workerPid: process.pid,
1615
+ idempotencyKey,
1616
+ requestDigest,
1617
+ diagnostics: []
1618
+ };
1619
+ runs.push(run2);
1620
+ audit(current, actor, agentId, "dataset.run.queued", datasetId, { runId: run2.id, planRevision: version.revision, schemaRef: version.schemaRef });
1621
+ return { run: run2, created: true };
1622
+ });
1623
+ const { run } = submitted;
1624
+ if (submitted.created) {
1625
+ const controller = new AbortController();
1626
+ this.controllers.set(run.id, controller);
1627
+ this.queue.push(async () => {
1628
+ try {
1629
+ const started = await this.catalog.storage.transaction((state2) => {
1630
+ const job = state2.datasetRuns?.find((job2) => job2.id === run.id);
1631
+ if (!job || job.state !== "queued") return false;
1632
+ job.state = controller.signal.aborted || job.cancelRequested ? "cancelled" : "running";
1633
+ return job.state === "running";
1634
+ });
1635
+ if (!started) return;
1636
+ const result = await runDataset(compiled, {
1637
+ actor,
1638
+ signal: controller.signal,
1639
+ parameters,
1640
+ planRevision: version.revision,
1641
+ connectionFor: (source) => this.profileFor(source),
1642
+ resolveSecret: this.options.resolveSecret,
1643
+ beforeCall: async (source) => {
1644
+ await this.checkSource(actor, agentId, source, "datasets.execute", true);
1645
+ if ((await this.catalog.storage.read()).datasetRuns?.find((job) => job.id === run.id)?.cancelRequested) controller.abort();
1646
+ }
1647
+ });
1648
+ await this.finishRun(run.id, actor, agentId, controller.signal.aborted ? "cancelled" : "succeeded", result.metadata, result.data);
1649
+ } catch (error) {
1650
+ const failure = error instanceof DatasetError ? error.diagnostic : { code: "DATASET_RUN_FAILED", phase: "run", message: "The authorized dataset run could not complete." };
1651
+ await this.finishRun(
1652
+ run.id,
1653
+ actor,
1654
+ agentId,
1655
+ controller.signal.aborted ? "cancelled" : "failed",
1656
+ error instanceof DatasetExecutionError ? error.metadata : void 0,
1657
+ void 0,
1658
+ [failure]
1659
+ );
1660
+ } finally {
1661
+ this.controllers.delete(run.id);
1662
+ }
1663
+ });
1664
+ this.drain();
1665
+ }
1666
+ return withoutValues(run);
1667
+ }
1668
+ async finishRun(id, actor, agentId, outcome, metadata, data, diagnostics = metadata?.diagnostics ?? []) {
1669
+ await this.catalog.storage.transaction((state) => {
1670
+ const run = state.datasetRuns?.find((job) => job.id === id && scopeMatch(job, actor, agentId));
1671
+ if (!run) return;
1672
+ run.state = run.cancelRequested ? "cancelled" : outcome;
1673
+ run.metadata = metadata;
1674
+ run.diagnostics = diagnostics;
1675
+ run.expiresAt = new Date(Date.now() + this.resultTtlMs).toISOString();
1676
+ if (run.state === "succeeded") run.data = data;
1677
+ audit(state, actor, agentId, "dataset.run." + run.state, run.datasetId, {
1678
+ runId: run.id,
1679
+ planRevision: run.planRevision,
1680
+ calls: metadata?.calls,
1681
+ completeness: metadata?.completeness
1682
+ });
1683
+ });
1684
+ }
1685
+ async findRun(actor, agentId, datasetId, runId, action) {
1686
+ await this.catalog.authorize(actor, agentId, action);
1687
+ const state = await this.catalog.storage.read();
1688
+ const run = state.datasetRuns?.find((job) => job.id === runId && job.datasetId === datasetId && job.actor === actor.id && scopeMatch(job, actor, agentId));
1689
+ if (!run) throw unavailable();
1690
+ return run;
1691
+ }
1692
+ async listRuns(actor, agentId, datasetId) {
1693
+ await this.catalog.authorize(actor, agentId, "datasets.execute");
1694
+ const state = await this.catalog.storage.read();
1695
+ this.dataset(state, actor, agentId, datasetId);
1696
+ return (state.datasetRuns ?? []).filter((run) => run.datasetId === datasetId && run.actor === actor.id && scopeMatch(run, actor, agentId)).slice(-40).reverse().map(withoutValues);
1697
+ }
1698
+ async getRun(actor, agentId, datasetId, runId) {
1699
+ return withoutValues(await this.findRun(actor, agentId, datasetId, runId, "datasets.execute"));
1700
+ }
1701
+ async getResult(actor, agentId, datasetId, runId) {
1702
+ const run = await this.findRun(actor, agentId, datasetId, runId, "datasets.results");
1703
+ if (Date.parse(run.expiresAt) <= Date.now()) throw new CatalogError("RESULT_EXPIRED", "The run result expired.", 410);
1704
+ if (run.state !== "succeeded" || run.data === void 0) throw new CatalogError("RESULT_NOT_READY", "A validated run result is unavailable.", 409);
1705
+ return { data: run.data, metadata: run.metadata, schemaRef: run.schemaRef, planRevision: run.planRevision, expiresAt: run.expiresAt };
1706
+ }
1707
+ async cancelRun(actor, agentId, datasetId, runId) {
1708
+ await this.findRun(actor, agentId, datasetId, runId, "datasets.execute");
1709
+ const updated = await this.catalog.storage.transaction((state) => {
1710
+ const run = state.datasetRuns?.find((job) => job.id === runId && job.actor === actor.id && scopeMatch(job, actor, agentId));
1711
+ if (!run) throw unavailable();
1712
+ if (run.state === "queued" || run.state === "running") {
1713
+ run.cancelRequested = true;
1714
+ run.state = "cancelled";
1715
+ run.diagnostics = [{ code: "DATASET_CANCELLED", phase: "run", message: "The dataset run was cancelled." }];
1716
+ }
1717
+ return run;
1718
+ });
1719
+ this.controllers.get(runId)?.abort();
1720
+ return withoutValues(updated);
1721
+ }
1722
+ async resultFixture(actor, agentId, datasetId, runId, input) {
1723
+ const result = await this.getResult(actor, agentId, datasetId, runId);
1724
+ const dataset = await this.catalog.getDataset(actor, agentId, datasetId);
1725
+ const alias = input.alias ?? dataset.name;
1726
+ if (!identifier.test(alias) || ["constructor", "prototype", "__proto__"].includes(alias)) throw datasetError("INVALID_DATASET_ALIAS", "run", "Choose a safe dataset alias.");
1727
+ return this.catalog.createFixture(actor, agentId, {
1728
+ name: input.name ?? dataset.displayName + " run sample",
1729
+ dataSets: [{ name: alias, data: result.data }],
1730
+ variables: {},
1731
+ schemaPins: { [alias]: result.schemaRef },
1732
+ retentionDays: input.retentionDays ?? 7,
1733
+ sample: true
1734
+ });
1735
+ }
1736
+ async acquireReportData(actor, agentId, templateId, input, signal) {
1737
+ await this.catalog.authorize(actor, agentId, "datasets.execute");
1738
+ await this.catalog.authorize(actor, agentId, "datasets.results");
1739
+ const template = await this.catalog.getTemplate(actor, agentId, templateId);
1740
+ const published = input.publishedRevision === void 0 ? void 0 : template.publishedRevisions.find((item) => item.number === input.publishedRevision);
1741
+ if (input.publishedRevision !== void 0 ? !published : input.revision !== template.revision) throw conflict();
1742
+ const manifest = published?.manifest ?? template.manifest;
1743
+ const source = published?.source ?? template.source;
1744
+ const dataSets = [...input.dataSets ?? []];
1745
+ checkJson(dataSets, 1e6);
1746
+ checkJson(input.parameters, 1e5);
1747
+ const aliasSet = /* @__PURE__ */ new Set();
1748
+ for (const dataset of dataSets) {
1749
+ if (!identifier.test(dataset?.name ?? "") || !isObject4(dataset?.data) || aliasSet.has(dataset.name)) {
1750
+ throw datasetError("DATASET_ALIAS_COLLISION", "run", "Manual inputs must have unique aliases and object values.");
1751
+ }
1752
+ aliasSet.add(dataset.name);
1753
+ }
1754
+ const metadata = indexSource(source).metadata;
1755
+ const pinned = Object.entries(manifest.dataSetMappings).filter(([, mapping]) => mapping.acquisition);
1756
+ if (!pinned.length || pinned.length > 8) throw datasetError("ACQUISITION_PLAN_REQUIRED", "run", "Pin one to eight published execution plans for explicit acquisition.");
1757
+ const snapshot = await this.catalog.storage.read();
1758
+ const resolved = pinned.map(([alias, mapping]) => {
1759
+ if (aliasSet.has(alias)) throw datasetError("DATASET_ALIAS_COLLISION", "run", "An acquired dataset alias also appears in manual inputs.");
1760
+ const version = this.record(snapshot, actor, agentId, mapping.datasetId)?.versions.find((plan) => plan.revision === mapping.acquisition.planRevision);
1761
+ if (version?.schemaRef !== mapping.schemaRef || metadata.dataSets?.[alias]?.schema !== mapping.schemaRef) {
1762
+ throw datasetError("ACQUISITION_PIN_MISMATCH", "plan", "A pinned execution plan does not match the report dataset schema.");
1763
+ }
1764
+ const parameters = {};
1765
+ for (const [name2, binding] of Object.entries(mapping.acquisition?.parameters ?? {})) {
1766
+ if (isObject4(binding) && Object.keys(binding).length === 1 && typeof binding.$input === "string") {
1767
+ if (!identifier.test(binding.$input)) throw datasetError("INVALID_PARAMETER_MAPPING", "plan", "Map a declared run input by exact name.");
1768
+ if (Object.hasOwn(input.parameters ?? {}, binding.$input)) parameters[name2] = input.parameters[binding.$input];
1769
+ } else parameters[name2] = binding;
1770
+ }
1771
+ return { alias, mapping, version, parameters };
1772
+ });
1773
+ const runs = [];
1774
+ const diagnostics = [];
1775
+ for (const { alias, mapping, version, parameters } of resolved) {
1776
+ signal?.throwIfAborted();
1777
+ let runId;
1778
+ try {
1779
+ let run = await this.submitRun(actor, agentId, mapping.datasetId, { planRevision: version.revision, parameters });
1780
+ runId = run.id;
1781
+ while (run.state === "queued" || run.state === "running") {
1782
+ await sleep2(90, void 0, { signal });
1783
+ run = await this.getRun(actor, agentId, mapping.datasetId, run.id);
1784
+ }
1785
+ if (run.state !== "succeeded") throw new CatalogError("ACQUISITION_FAILED", "The acquired dataset did not complete.", 422, { diagnostics: run.diagnostics });
1786
+ const result = await this.getResult(actor, agentId, mapping.datasetId, run.id);
1787
+ if (result.metadata.completeness === "partial") {
1788
+ throw datasetError("PARTIAL_DATASET", "run", "Report acquisition requires complete coverage of the plan\u2019s declared scope.");
1789
+ }
1790
+ dataSets.push({ name: alias, data: result.data });
1791
+ runs.push({ alias, id: run.id, metadata: result.metadata });
1792
+ diagnostics.push(...result.metadata.diagnostics);
1793
+ } catch (error) {
1794
+ if (signal?.aborted) {
1795
+ if (runId) await this.cancelRun(actor, agentId, mapping.datasetId, runId).catch(() => {
1796
+ });
1797
+ throw error;
1798
+ }
1799
+ if (metadata.dataSets?.[alias]?.required !== false) throw error;
1800
+ diagnostics.push({ code: "OPTIONAL_DATASET_OMITTED", phase: "run", message: "Optional acquisition for " + alias + " could not complete." });
1801
+ }
1802
+ }
1803
+ return { dataSets, runs, diagnostics, revision: published?.number ?? template.revision, ...published ? { published: true } : {} };
1804
+ }
1805
+ };
1806
+ function checkAcquisitionPins(manifest, datasets) {
1807
+ const diagnostics = [];
1808
+ for (const [alias, pin] of Object.entries(manifest.dataSetMappings ?? {})) {
1809
+ if (!pin.acquisition) continue;
1810
+ const dataset = datasets.find((dataset2) => dataset2.id === pin.datasetId);
1811
+ if (!dataset?.execution?.versions.some((version) => version.revision === pin.acquisition?.planRevision && version.schemaRef === pin.schemaRef)) {
1812
+ diagnostics.push({ code: "ACQUISITION_PIN_MISMATCH", phase: "plan", message: "The execution plan pinned for " + alias + " does not match its schema version.", path: alias });
1813
+ }
1814
+ }
1815
+ return diagnostics;
1816
+ }
1817
+ export {
1818
+ DatasetAdapterRegistry,
1819
+ DatasetError,
1820
+ DatasetExecutionError,
1821
+ DatasetService,
1822
+ buildParameters,
1823
+ checkAcquisitionPins,
1824
+ checkExpression,
1825
+ checkJson,
1826
+ compileDatasetPlan,
1827
+ datasetError,
1828
+ datasetPlanSchema,
1829
+ evaluateExpression,
1830
+ identifier,
1831
+ itemSchemaFor,
1832
+ missing,
1833
+ parseDatasetPlan,
1834
+ pointerParts,
1835
+ protocols,
1836
+ readPointer,
1837
+ runDataset,
1838
+ validateDatasetPlan
1839
+ };
1840
+ //# sourceMappingURL=index.js.map