industrial-model 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +178 -1
- package/dist/index.cjs +710 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +139 -5
- package/dist/index.d.ts +139 -5
- package/dist/index.js +709 -6
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
1
3
|
// src/cognite/adapter.ts
|
|
2
4
|
function createCogniteAdapter(client) {
|
|
3
5
|
return new CogniteSdkAdapter(client);
|
|
@@ -24,6 +26,14 @@ var CogniteSdkAdapter = class {
|
|
|
24
26
|
nextCursor: response.nextCursor
|
|
25
27
|
};
|
|
26
28
|
}
|
|
29
|
+
async aggregateInstances(request) {
|
|
30
|
+
const response = await this.client.instances.aggregate(
|
|
31
|
+
request
|
|
32
|
+
);
|
|
33
|
+
return {
|
|
34
|
+
items: response.items
|
|
35
|
+
};
|
|
36
|
+
}
|
|
27
37
|
};
|
|
28
38
|
|
|
29
39
|
// src/constants.ts
|
|
@@ -32,6 +42,8 @@ var EDGE_MARKER = "<EdgeMarker>";
|
|
|
32
42
|
var MAX_LIMIT = 1e4;
|
|
33
43
|
var DEFAULT_LIMIT = 1e3;
|
|
34
44
|
var MAX_DEPENDENCY_DEPTH = 3;
|
|
45
|
+
var AGGREGATE_LIMIT = 1e3;
|
|
46
|
+
var MAX_GROUP_BY = 5;
|
|
35
47
|
|
|
36
48
|
// src/mappers/utils.ts
|
|
37
49
|
var NODE_PROPERTIES = /* @__PURE__ */ new Set([
|
|
@@ -73,6 +85,511 @@ function buildSelect(source, properties) {
|
|
|
73
85
|
if (properties.length === 0) return {};
|
|
74
86
|
return { sources: [{ source, properties }] };
|
|
75
87
|
}
|
|
88
|
+
var GROUPABLE_PROPERTY_TYPES = /* @__PURE__ */ new Set([
|
|
89
|
+
"text",
|
|
90
|
+
"direct",
|
|
91
|
+
"int32",
|
|
92
|
+
"int64",
|
|
93
|
+
"float32",
|
|
94
|
+
"float64",
|
|
95
|
+
"boolean",
|
|
96
|
+
"enum"
|
|
97
|
+
]);
|
|
98
|
+
var NUMERIC_PROPERTY_TYPES = /* @__PURE__ */ new Set(["int32", "int64", "float32", "float64"]);
|
|
99
|
+
function isGroupableProperty(property) {
|
|
100
|
+
if (!isViewPropertyDefinition(property)) return false;
|
|
101
|
+
if (property.type.list === true) return false;
|
|
102
|
+
const type = property.type.type;
|
|
103
|
+
return type != null && GROUPABLE_PROPERTY_TYPES.has(type);
|
|
104
|
+
}
|
|
105
|
+
function isNumericProperty(property) {
|
|
106
|
+
const type = property.type.type;
|
|
107
|
+
return type != null && NUMERIC_PROPERTY_TYPES.has(type);
|
|
108
|
+
}
|
|
109
|
+
function getSelectedGroupByKeys(groupBy) {
|
|
110
|
+
return Object.entries(groupBy).filter((entry) => entry[1] === true).map(([key]) => key);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/validation.ts
|
|
114
|
+
var nodeIdSchema = z.object({
|
|
115
|
+
space: z.string().min(1),
|
|
116
|
+
externalId: z.string().min(1)
|
|
117
|
+
});
|
|
118
|
+
function dateSchema(dateMode) {
|
|
119
|
+
if (dateMode === "coerce") {
|
|
120
|
+
return z.preprocess(
|
|
121
|
+
(value) => typeof value === "string" || typeof value === "number" ? new Date(value) : value,
|
|
122
|
+
z.date()
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return z.union([z.string(), z.date()]);
|
|
126
|
+
}
|
|
127
|
+
function propertyValueSchema(property, options = {}) {
|
|
128
|
+
const type = property.type;
|
|
129
|
+
let schema;
|
|
130
|
+
switch (type.type) {
|
|
131
|
+
case "text":
|
|
132
|
+
case "enum":
|
|
133
|
+
schema = z.string();
|
|
134
|
+
break;
|
|
135
|
+
case "int32":
|
|
136
|
+
case "int64":
|
|
137
|
+
schema = z.number().int();
|
|
138
|
+
break;
|
|
139
|
+
case "float32":
|
|
140
|
+
case "float64":
|
|
141
|
+
schema = z.number();
|
|
142
|
+
break;
|
|
143
|
+
case "boolean":
|
|
144
|
+
schema = z.boolean();
|
|
145
|
+
break;
|
|
146
|
+
case "date":
|
|
147
|
+
case "timestamp":
|
|
148
|
+
schema = dateSchema(options.dateMode);
|
|
149
|
+
break;
|
|
150
|
+
case "direct":
|
|
151
|
+
schema = nodeIdSchema;
|
|
152
|
+
break;
|
|
153
|
+
case "json":
|
|
154
|
+
schema = z.unknown();
|
|
155
|
+
break;
|
|
156
|
+
default:
|
|
157
|
+
schema = z.unknown();
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
return type.list === true ? z.array(schema) : schema;
|
|
161
|
+
}
|
|
162
|
+
function buildViewSchema(view, options = {}) {
|
|
163
|
+
const shape = {};
|
|
164
|
+
for (const [name, property] of Object.entries(view.properties)) {
|
|
165
|
+
if (isViewPropertyDefinition(property)) {
|
|
166
|
+
shape[name] = propertyValueSchema(property, options).optional();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return z.object(shape).strict();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/mappers/query-validator.ts
|
|
173
|
+
var NODE_STRING_PROPERTIES = ["externalId", "space"];
|
|
174
|
+
var NODE_NUMBER_PROPERTIES = ["createdTime", "deletedTime", "lastUpdatedTime"];
|
|
175
|
+
var NODE_PROPERTIES2 = /* @__PURE__ */ new Set([...NODE_STRING_PROPERTIES, ...NODE_NUMBER_PROPERTIES]);
|
|
176
|
+
var SORT_DIRECTION_SCHEMA = z.enum(["ascending", "descending"]);
|
|
177
|
+
var recordSchema = z.record(z.string(), z.unknown());
|
|
178
|
+
var leafOps = /* @__PURE__ */ new Set([
|
|
179
|
+
"eq",
|
|
180
|
+
"in",
|
|
181
|
+
"gt",
|
|
182
|
+
"gte",
|
|
183
|
+
"lt",
|
|
184
|
+
"lte",
|
|
185
|
+
"exists",
|
|
186
|
+
"prefix",
|
|
187
|
+
"containsAny",
|
|
188
|
+
"containsAll"
|
|
189
|
+
]);
|
|
190
|
+
function isRecord(value) {
|
|
191
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
192
|
+
}
|
|
193
|
+
function isLeafFilter(value) {
|
|
194
|
+
return Object.keys(value).some((key) => leafOps.has(key));
|
|
195
|
+
}
|
|
196
|
+
function issuePath(path) {
|
|
197
|
+
return path.length === 0 ? "query" : path.map(String).join(".");
|
|
198
|
+
}
|
|
199
|
+
function formatZodIssues(error, path) {
|
|
200
|
+
return error.issues.map((issue) => `${issuePath([...path, ...issue.path])}: ${issue.message}`);
|
|
201
|
+
}
|
|
202
|
+
function getRelationTarget(property) {
|
|
203
|
+
if (isViewPropertyDefinition(property)) {
|
|
204
|
+
return getDirectRelationSource(property)?.externalId ?? null;
|
|
205
|
+
}
|
|
206
|
+
if (isReverseDirectRelation(property) || isEdgeConnection(property)) {
|
|
207
|
+
return property.source.externalId;
|
|
208
|
+
}
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
function baseValueSchema(property) {
|
|
212
|
+
if (property === "node-string") return z.string();
|
|
213
|
+
if (property === "node-number") return z.number();
|
|
214
|
+
switch (property.type.type) {
|
|
215
|
+
case "text":
|
|
216
|
+
case "enum":
|
|
217
|
+
return z.string();
|
|
218
|
+
case "int32":
|
|
219
|
+
case "int64":
|
|
220
|
+
return z.number().int();
|
|
221
|
+
case "float32":
|
|
222
|
+
case "float64":
|
|
223
|
+
return z.number();
|
|
224
|
+
case "boolean":
|
|
225
|
+
return z.boolean();
|
|
226
|
+
case "date":
|
|
227
|
+
case "timestamp":
|
|
228
|
+
return z.union([z.string(), z.date()]);
|
|
229
|
+
case "direct":
|
|
230
|
+
return nodeIdSchema;
|
|
231
|
+
default:
|
|
232
|
+
return z.union([z.string(), z.number(), z.boolean()]);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function leafFilterSchema(property) {
|
|
236
|
+
const value = baseValueSchema(property);
|
|
237
|
+
const isList = typeof property !== "string" && property.type.list === true;
|
|
238
|
+
if (isList) {
|
|
239
|
+
return z.object({
|
|
240
|
+
containsAny: z.array(value).optional(),
|
|
241
|
+
containsAll: z.array(value).optional(),
|
|
242
|
+
exists: z.boolean().optional()
|
|
243
|
+
}).strict();
|
|
244
|
+
}
|
|
245
|
+
if (property === "node-string" || typeof property !== "string" && property.type.type === "text") {
|
|
246
|
+
return z.object({
|
|
247
|
+
eq: z.string().optional(),
|
|
248
|
+
in: z.array(z.string()).optional(),
|
|
249
|
+
prefix: z.string().optional(),
|
|
250
|
+
exists: z.boolean().optional()
|
|
251
|
+
}).strict();
|
|
252
|
+
}
|
|
253
|
+
if (typeof property !== "string" && property.type.type === "enum") {
|
|
254
|
+
return z.object({
|
|
255
|
+
eq: z.string().optional(),
|
|
256
|
+
in: z.array(z.string()).optional(),
|
|
257
|
+
prefix: z.string().optional(),
|
|
258
|
+
exists: z.boolean().optional()
|
|
259
|
+
}).strict();
|
|
260
|
+
}
|
|
261
|
+
if (property === "node-number" || typeof property !== "string" && ["int32", "int64", "float32", "float64"].includes(property.type.type ?? "")) {
|
|
262
|
+
return z.object({
|
|
263
|
+
eq: value.optional(),
|
|
264
|
+
in: z.array(value).optional(),
|
|
265
|
+
gt: value.optional(),
|
|
266
|
+
gte: value.optional(),
|
|
267
|
+
lt: value.optional(),
|
|
268
|
+
lte: value.optional(),
|
|
269
|
+
exists: z.boolean().optional()
|
|
270
|
+
}).strict();
|
|
271
|
+
}
|
|
272
|
+
if (typeof property !== "string" && ["date", "timestamp"].includes(property.type.type ?? "")) {
|
|
273
|
+
return z.object({
|
|
274
|
+
eq: value.optional(),
|
|
275
|
+
in: z.array(value).optional(),
|
|
276
|
+
gt: value.optional(),
|
|
277
|
+
gte: value.optional(),
|
|
278
|
+
lt: value.optional(),
|
|
279
|
+
lte: value.optional(),
|
|
280
|
+
exists: z.boolean().optional()
|
|
281
|
+
}).strict();
|
|
282
|
+
}
|
|
283
|
+
if (typeof property !== "string" && property.type.type === "boolean") {
|
|
284
|
+
return z.object({
|
|
285
|
+
eq: z.boolean().optional(),
|
|
286
|
+
exists: z.boolean().optional()
|
|
287
|
+
}).strict();
|
|
288
|
+
}
|
|
289
|
+
if (typeof property !== "string" && property.type.type === "direct") {
|
|
290
|
+
return z.object({
|
|
291
|
+
eq: nodeIdSchema.optional(),
|
|
292
|
+
in: z.array(nodeIdSchema).optional(),
|
|
293
|
+
exists: z.boolean().optional()
|
|
294
|
+
}).strict();
|
|
295
|
+
}
|
|
296
|
+
return z.object({
|
|
297
|
+
eq: value.optional(),
|
|
298
|
+
in: z.array(value).optional(),
|
|
299
|
+
exists: z.boolean().optional()
|
|
300
|
+
}).strict();
|
|
301
|
+
}
|
|
302
|
+
var QueryValidator = class {
|
|
303
|
+
constructor(viewMapper) {
|
|
304
|
+
this.viewMapper = viewMapper;
|
|
305
|
+
}
|
|
306
|
+
async validate(options, rootView) {
|
|
307
|
+
const errors = [];
|
|
308
|
+
errors.push(...this.validateOptionsShape(options, rootView));
|
|
309
|
+
if (options.select !== void 0) {
|
|
310
|
+
errors.push(...await this.validateSelect(options.select, rootView, ["select"]));
|
|
311
|
+
}
|
|
312
|
+
if (options.filters !== void 0) {
|
|
313
|
+
errors.push(...await this.validateWhereInput(options.filters, rootView, ["filters"]));
|
|
314
|
+
}
|
|
315
|
+
if (options.sort !== void 0) {
|
|
316
|
+
errors.push(...this.validateSort(options.sort, rootView, ["sort"]));
|
|
317
|
+
}
|
|
318
|
+
if (errors.length > 0) {
|
|
319
|
+
throw new Error(`Invalid query options:
|
|
320
|
+
${errors.map((error) => `- ${error}`).join("\n")}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
validateOptionsShape(options, rootView) {
|
|
324
|
+
const schema = z.object({
|
|
325
|
+
viewExternalId: z.literal(rootView.externalId),
|
|
326
|
+
select: z.unknown().optional(),
|
|
327
|
+
filters: z.unknown().optional(),
|
|
328
|
+
sort: z.unknown().optional(),
|
|
329
|
+
limit: z.union([z.literal(-1), z.number().int().positive().max(MAX_LIMIT)]).optional(),
|
|
330
|
+
cursor: z.string().nullable().optional()
|
|
331
|
+
}).strict();
|
|
332
|
+
const result = schema.safeParse(options);
|
|
333
|
+
return result.success ? [] : formatZodIssues(result.error, []);
|
|
334
|
+
}
|
|
335
|
+
async validateSelect(select, view, path) {
|
|
336
|
+
const shape = {
|
|
337
|
+
_all: z.literal(true).optional()
|
|
338
|
+
};
|
|
339
|
+
for (const property of NODE_PROPERTIES2) {
|
|
340
|
+
shape[property] = z.boolean().optional();
|
|
341
|
+
}
|
|
342
|
+
for (const [name, property] of Object.entries(view.properties)) {
|
|
343
|
+
const target = getRelationTarget(property);
|
|
344
|
+
if (target != null) {
|
|
345
|
+
const nestedSelect = recordSchema;
|
|
346
|
+
shape[name] = isViewPropertyDefinition(property) ? z.union([z.boolean(), nestedSelect]).optional() : nestedSelect.optional();
|
|
347
|
+
} else {
|
|
348
|
+
shape[name] = z.boolean().optional();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const result = z.object(shape).strict().safeParse(select);
|
|
352
|
+
if (!result.success) return formatZodIssues(result.error, path);
|
|
353
|
+
if (!isRecord(select)) return [];
|
|
354
|
+
const errors = [];
|
|
355
|
+
for (const [name, value] of Object.entries(select)) {
|
|
356
|
+
if (name === "_all" || value == null || typeof value !== "object" || Array.isArray(value)) {
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
const property = view.properties[name];
|
|
360
|
+
if (!property) continue;
|
|
361
|
+
const target = getRelationTarget(property);
|
|
362
|
+
if (target == null) {
|
|
363
|
+
errors.push(
|
|
364
|
+
`${issuePath([...path, name])}: property "${name}" does not support nested select`
|
|
365
|
+
);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
const targetView = await this.viewMapper.getView(target);
|
|
369
|
+
errors.push(...await this.validateSelect(value, targetView, [...path, name]));
|
|
370
|
+
}
|
|
371
|
+
return errors;
|
|
372
|
+
}
|
|
373
|
+
async validateWhereInput(filters, view, path) {
|
|
374
|
+
return this.validateFilters(filters, view, path);
|
|
375
|
+
}
|
|
376
|
+
async validateFilters(filters, view, path) {
|
|
377
|
+
const shape = {
|
|
378
|
+
AND: z.union([recordSchema, z.array(recordSchema)]).optional(),
|
|
379
|
+
OR: z.array(recordSchema).optional(),
|
|
380
|
+
NOT: z.union([recordSchema, z.array(recordSchema)]).optional()
|
|
381
|
+
};
|
|
382
|
+
for (const property of NODE_STRING_PROPERTIES) {
|
|
383
|
+
shape[property] = z.unknown().optional();
|
|
384
|
+
}
|
|
385
|
+
for (const property of NODE_NUMBER_PROPERTIES) {
|
|
386
|
+
shape[property] = z.unknown().optional();
|
|
387
|
+
}
|
|
388
|
+
for (const property of Object.keys(view.properties)) {
|
|
389
|
+
shape[property] = z.unknown().optional();
|
|
390
|
+
}
|
|
391
|
+
const result = z.object(shape).strict().safeParse(filters);
|
|
392
|
+
if (!result.success) return formatZodIssues(result.error, path);
|
|
393
|
+
if (!isRecord(filters)) return [];
|
|
394
|
+
const errors = [];
|
|
395
|
+
for (const [name, value] of Object.entries(filters)) {
|
|
396
|
+
if (value == null) continue;
|
|
397
|
+
if (name === "AND" || name === "OR" || name === "NOT") {
|
|
398
|
+
const clauses = Array.isArray(value) ? value : [value];
|
|
399
|
+
for (const [index, clause] of clauses.entries()) {
|
|
400
|
+
errors.push(...await this.validateFilters(clause, view, [...path, name, index]));
|
|
401
|
+
}
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (!isRecord(value)) {
|
|
405
|
+
errors.push(`${issuePath([...path, name])}: Expected object`);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
const nodePropertyType = NODE_STRING_PROPERTIES.includes(
|
|
409
|
+
name
|
|
410
|
+
) ? "node-string" : NODE_NUMBER_PROPERTIES.includes(name) ? "node-number" : null;
|
|
411
|
+
if (nodePropertyType != null) {
|
|
412
|
+
errors.push(...this.validateLeafFilter(value, nodePropertyType, [...path, name]));
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
const property = view.properties[name];
|
|
416
|
+
if (!property) continue;
|
|
417
|
+
if (isViewPropertyDefinition(property)) {
|
|
418
|
+
const target2 = getDirectRelationSource(property);
|
|
419
|
+
if (target2 != null && !isLeafFilter(value)) {
|
|
420
|
+
const targetView = await this.viewMapper.getView(target2.externalId);
|
|
421
|
+
errors.push(...await this.validateFilters(value, targetView, [...path, name]));
|
|
422
|
+
} else {
|
|
423
|
+
errors.push(...this.validateLeafFilter(value, property, [...path, name]));
|
|
424
|
+
}
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
const target = getRelationTarget(property);
|
|
428
|
+
if (target == null) {
|
|
429
|
+
errors.push(`${issuePath([...path, name])}: property "${name}" does not support filters`);
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
errors.push(
|
|
433
|
+
`${issuePath([...path, name])}: filtering through "${name}" is not supported by the query mapper`
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
return errors;
|
|
437
|
+
}
|
|
438
|
+
validateLeafFilter(value, property, path) {
|
|
439
|
+
const result = leafFilterSchema(property).safeParse(value);
|
|
440
|
+
return result.success ? [] : formatZodIssues(result.error, path);
|
|
441
|
+
}
|
|
442
|
+
validateSort(sort, view, path) {
|
|
443
|
+
const shape = {};
|
|
444
|
+
for (const property of NODE_PROPERTIES2) {
|
|
445
|
+
shape[property] = SORT_DIRECTION_SCHEMA.optional();
|
|
446
|
+
}
|
|
447
|
+
for (const [name, property] of Object.entries(view.properties)) {
|
|
448
|
+
if (isViewPropertyDefinition(property) && property.type.list !== true) {
|
|
449
|
+
shape[name] = SORT_DIRECTION_SCHEMA.optional();
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
const result = z.object(shape).strict().safeParse(sort);
|
|
453
|
+
return result.success ? [] : formatZodIssues(result.error, path);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
// src/mappers/aggregate-validator.ts
|
|
458
|
+
var NODE_COUNT_PROPERTIES = /* @__PURE__ */ new Set(["externalId", "space"]);
|
|
459
|
+
function issuePath2(path) {
|
|
460
|
+
return path.length === 0 ? "aggregate" : path.map(String).join(".");
|
|
461
|
+
}
|
|
462
|
+
function formatZodIssues2(error, path) {
|
|
463
|
+
return error.issues.map((issue) => `${issuePath2([...path, ...issue.path])}: ${issue.message}`);
|
|
464
|
+
}
|
|
465
|
+
function isEmptyObject(value) {
|
|
466
|
+
return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
|
|
467
|
+
}
|
|
468
|
+
var AggregateValidator = class {
|
|
469
|
+
constructor(viewMapper) {
|
|
470
|
+
this.queryValidator = new QueryValidator(viewMapper);
|
|
471
|
+
}
|
|
472
|
+
async validate(options, rootView) {
|
|
473
|
+
const errors = [];
|
|
474
|
+
errors.push(...this.validateOptionsShape(options, rootView));
|
|
475
|
+
const selectedGroupBy = options.groupBy ? getSelectedGroupByKeys(options.groupBy) : [];
|
|
476
|
+
if (selectedGroupBy.length === 0 && options.aggregate === void 0) {
|
|
477
|
+
errors.push("aggregate: either groupBy or aggregate must be provided");
|
|
478
|
+
}
|
|
479
|
+
if (options.filters !== void 0) {
|
|
480
|
+
errors.push(
|
|
481
|
+
...await this.queryValidator.validateWhereInput(options.filters, rootView, ["filters"])
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
if (options.groupBy !== void 0) {
|
|
485
|
+
errors.push(...this.validateGroupBy(options.groupBy, rootView, ["groupBy"]));
|
|
486
|
+
}
|
|
487
|
+
if (options.aggregate !== void 0) {
|
|
488
|
+
errors.push(
|
|
489
|
+
...this.validateAggregate(
|
|
490
|
+
options.aggregate,
|
|
491
|
+
rootView,
|
|
492
|
+
["aggregate"]
|
|
493
|
+
)
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
if (errors.length > 0) {
|
|
497
|
+
throw new Error(
|
|
498
|
+
`Invalid aggregate options:
|
|
499
|
+
${errors.map((error) => `- ${error}`).join("\n")}`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
validateOptionsShape(options, rootView) {
|
|
504
|
+
const schema = z.object({
|
|
505
|
+
viewExternalId: z.literal(rootView.externalId),
|
|
506
|
+
filters: z.unknown().optional(),
|
|
507
|
+
groupBy: z.unknown().optional(),
|
|
508
|
+
aggregate: z.unknown().optional()
|
|
509
|
+
}).strict();
|
|
510
|
+
const result = schema.safeParse(options);
|
|
511
|
+
return result.success ? [] : formatZodIssues2(result.error, []);
|
|
512
|
+
}
|
|
513
|
+
validateGroupBy(groupBy, view, path) {
|
|
514
|
+
const shape = {};
|
|
515
|
+
for (const [name, property] of Object.entries(view.properties)) {
|
|
516
|
+
if (isGroupableProperty(property)) {
|
|
517
|
+
shape[name] = z.literal(true).optional();
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const result = z.object(shape).strict().safeParse(groupBy);
|
|
521
|
+
if (!result.success) {
|
|
522
|
+
return formatZodIssues2(result.error, path);
|
|
523
|
+
}
|
|
524
|
+
const selected = getSelectedGroupByKeys(groupBy);
|
|
525
|
+
const errors = [];
|
|
526
|
+
if (selected.length === 0) {
|
|
527
|
+
errors.push(`${issuePath2(path)}: at least one property must be set to true`);
|
|
528
|
+
}
|
|
529
|
+
if (selected.length > MAX_GROUP_BY) {
|
|
530
|
+
errors.push(`${issuePath2(path)}: at most ${MAX_GROUP_BY} properties can be grouped`);
|
|
531
|
+
}
|
|
532
|
+
for (const name of selected) {
|
|
533
|
+
const property = view.properties[name];
|
|
534
|
+
if (!property || !isGroupableProperty(property)) {
|
|
535
|
+
errors.push(`${issuePath2([...path, name])}: property "${name}" cannot be used in groupBy`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return errors;
|
|
539
|
+
}
|
|
540
|
+
validateAggregate(aggregate, view, path) {
|
|
541
|
+
if ("count" in aggregate) {
|
|
542
|
+
const property2 = aggregate.count;
|
|
543
|
+
if (isEmptyObject(property2)) {
|
|
544
|
+
return [];
|
|
545
|
+
}
|
|
546
|
+
if (typeof property2 === "string") {
|
|
547
|
+
if (NODE_COUNT_PROPERTIES.has(property2)) {
|
|
548
|
+
return [];
|
|
549
|
+
}
|
|
550
|
+
const viewProperty = view.properties[property2];
|
|
551
|
+
if (!viewProperty || !isGroupableProperty(viewProperty)) {
|
|
552
|
+
return [`${issuePath2([...path, "count"])}: property "${property2}" cannot be counted`];
|
|
553
|
+
}
|
|
554
|
+
return [];
|
|
555
|
+
}
|
|
556
|
+
return [`${issuePath2([...path, "count"])}: invalid count property`];
|
|
557
|
+
}
|
|
558
|
+
let propertyName;
|
|
559
|
+
let numericOp = null;
|
|
560
|
+
if ("avg" in aggregate) {
|
|
561
|
+
numericOp = "avg";
|
|
562
|
+
propertyName = aggregate.avg;
|
|
563
|
+
} else if ("min" in aggregate) {
|
|
564
|
+
numericOp = "min";
|
|
565
|
+
propertyName = aggregate.min;
|
|
566
|
+
} else if ("max" in aggregate) {
|
|
567
|
+
numericOp = "max";
|
|
568
|
+
propertyName = aggregate.max;
|
|
569
|
+
} else if ("sum" in aggregate) {
|
|
570
|
+
numericOp = "sum";
|
|
571
|
+
propertyName = aggregate.sum;
|
|
572
|
+
}
|
|
573
|
+
if (numericOp == null) {
|
|
574
|
+
return [`${issuePath2(path)}: unknown aggregate operation`];
|
|
575
|
+
}
|
|
576
|
+
if (typeof propertyName !== "string") {
|
|
577
|
+
return [`${issuePath2(path)}: aggregate property must be a string`];
|
|
578
|
+
}
|
|
579
|
+
const property = view.properties[propertyName];
|
|
580
|
+
if (!property || !isViewPropertyDefinition(property) || !isNumericProperty(property)) {
|
|
581
|
+
return [
|
|
582
|
+
`${issuePath2([...path, numericOp])}: property "${propertyName}" must be a numeric view property`
|
|
583
|
+
];
|
|
584
|
+
}
|
|
585
|
+
if (getDirectRelationSource(property) != null) {
|
|
586
|
+
return [
|
|
587
|
+
`${issuePath2([...path, numericOp])}: property "${propertyName}" is a relation and cannot be aggregated`
|
|
588
|
+
];
|
|
589
|
+
}
|
|
590
|
+
return [];
|
|
591
|
+
}
|
|
592
|
+
};
|
|
76
593
|
|
|
77
594
|
// src/mappers/filter-mapper.ts
|
|
78
595
|
var LEAF_OPS = /* @__PURE__ */ new Set([
|
|
@@ -87,7 +604,7 @@ var LEAF_OPS = /* @__PURE__ */ new Set([
|
|
|
87
604
|
"containsAny",
|
|
88
605
|
"containsAll"
|
|
89
606
|
]);
|
|
90
|
-
function
|
|
607
|
+
function isLeafFilter2(value) {
|
|
91
608
|
return Object.keys(value).some((k) => LEAF_OPS.has(k));
|
|
92
609
|
}
|
|
93
610
|
var FilterMapper = class {
|
|
@@ -116,7 +633,7 @@ var FilterMapper = class {
|
|
|
116
633
|
} else {
|
|
117
634
|
const filterValue = value;
|
|
118
635
|
const property = getPropertyRef(key, rootView);
|
|
119
|
-
if (
|
|
636
|
+
if (isLeafFilter2(filterValue)) {
|
|
120
637
|
result.push(...this.leafToFilterDefs(property, filterValue));
|
|
121
638
|
} else {
|
|
122
639
|
const targetView = await this.getNestedTargetView(key, rootView);
|
|
@@ -203,6 +720,85 @@ var FilterMapper = class {
|
|
|
203
720
|
}
|
|
204
721
|
};
|
|
205
722
|
|
|
723
|
+
// src/mappers/aggregate-mapper.ts
|
|
724
|
+
var AggregateMapper = class {
|
|
725
|
+
constructor(viewMapper) {
|
|
726
|
+
this.viewMapper = viewMapper;
|
|
727
|
+
this.filterMapper = new FilterMapper(viewMapper);
|
|
728
|
+
this.validator = new AggregateValidator(viewMapper);
|
|
729
|
+
}
|
|
730
|
+
async map(options) {
|
|
731
|
+
const { viewExternalId, filters, groupBy, aggregate } = options;
|
|
732
|
+
const rootView = await this.viewMapper.getView(viewExternalId);
|
|
733
|
+
await this.validator.validate(options, rootView);
|
|
734
|
+
const filterParts = filters ? await this.filterMapper.map(filters, rootView) : [];
|
|
735
|
+
const filter = filterParts.length === 0 ? void 0 : filterParts.length === 1 ? filterParts[0] : { and: filterParts };
|
|
736
|
+
return {
|
|
737
|
+
view: toViewReference(rootView),
|
|
738
|
+
instanceType: "node",
|
|
739
|
+
limit: AGGREGATE_LIMIT,
|
|
740
|
+
...filter !== void 0 ? { filter } : {},
|
|
741
|
+
...groupBy ? { groupBy: getSelectedGroupByKeys(groupBy) } : {},
|
|
742
|
+
...aggregate ? { aggregates: [mapAggregateDefinition(aggregate)] } : {}
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
function mapAggregateDefinition(aggregate) {
|
|
747
|
+
if ("count" in aggregate) {
|
|
748
|
+
const property = aggregate.count;
|
|
749
|
+
if (property != null && typeof property === "object" && !Array.isArray(property) && Object.keys(property).length === 0) {
|
|
750
|
+
return { count: {} };
|
|
751
|
+
}
|
|
752
|
+
if (typeof property === "string") {
|
|
753
|
+
return { count: { property } };
|
|
754
|
+
}
|
|
755
|
+
return { count: {} };
|
|
756
|
+
}
|
|
757
|
+
if ("avg" in aggregate) {
|
|
758
|
+
return { avg: { property: aggregate.avg } };
|
|
759
|
+
}
|
|
760
|
+
if ("min" in aggregate) {
|
|
761
|
+
return { min: { property: aggregate.min } };
|
|
762
|
+
}
|
|
763
|
+
if ("max" in aggregate) {
|
|
764
|
+
return { max: { property: aggregate.max } };
|
|
765
|
+
}
|
|
766
|
+
if ("sum" in aggregate) {
|
|
767
|
+
return { sum: { property: aggregate.sum } };
|
|
768
|
+
}
|
|
769
|
+
throw new Error("Invalid aggregate definition");
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/mappers/aggregate-result-mapper.ts
|
|
773
|
+
function isNodeId(value) {
|
|
774
|
+
return value != null && typeof value === "object" && "space" in value && "externalId" in value && typeof value.space === "string" && typeof value.externalId === "string";
|
|
775
|
+
}
|
|
776
|
+
var AggregateResultMapper = class {
|
|
777
|
+
map(response, options) {
|
|
778
|
+
const groupByKeys = options.groupBy ? getSelectedGroupByKeys(options.groupBy) : [];
|
|
779
|
+
return response.items.map((item) => {
|
|
780
|
+
let group;
|
|
781
|
+
if (item.group != null && groupByKeys.length > 0) {
|
|
782
|
+
group = {};
|
|
783
|
+
for (const key of groupByKeys) {
|
|
784
|
+
const value = item.group[key];
|
|
785
|
+
if (value === void 0) continue;
|
|
786
|
+
group[key] = isNodeId(value) ? { space: value.space, externalId: value.externalId } : value;
|
|
787
|
+
}
|
|
788
|
+
if (Object.keys(group).length === 0) {
|
|
789
|
+
group = void 0;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
const aggregateValue = item.aggregates[0];
|
|
793
|
+
const aggregate = aggregateValue?.value !== void 0 ? aggregateValue.property != null ? { property: aggregateValue.property, value: aggregateValue.value } : { value: aggregateValue.value } : void 0;
|
|
794
|
+
return {
|
|
795
|
+
...group !== void 0 ? { group } : {},
|
|
796
|
+
...aggregate !== void 0 ? { aggregate } : {}
|
|
797
|
+
};
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
|
|
206
802
|
// src/mappers/sort-mapper.ts
|
|
207
803
|
var SortMapper = class {
|
|
208
804
|
map(sort, rootView) {
|
|
@@ -227,6 +823,7 @@ var QueryMapper = class {
|
|
|
227
823
|
this.viewMapper = viewMapper;
|
|
228
824
|
this.filterMapper = new FilterMapper(viewMapper);
|
|
229
825
|
this.sortMapper = new SortMapper();
|
|
826
|
+
this.validator = new QueryValidator(viewMapper);
|
|
230
827
|
}
|
|
231
828
|
async map(options) {
|
|
232
829
|
const {
|
|
@@ -239,6 +836,7 @@ var QueryMapper = class {
|
|
|
239
836
|
} = options;
|
|
240
837
|
const limit = requestedLimit === -1 ? DEFAULT_LIMIT : requestedLimit;
|
|
241
838
|
const rootView = await this.viewMapper.getView(viewExternalId);
|
|
839
|
+
await this.validator.validate(options, rootView);
|
|
242
840
|
const rootViewRef = toViewReference(rootView);
|
|
243
841
|
const whereFilters = filters ? await this.filterMapper.map(filters, rootView) : [];
|
|
244
842
|
const baseFilters = [{ hasData: [rootViewRef] }, ...whereFilters];
|
|
@@ -529,6 +1127,92 @@ var QueryResultMapper = class {
|
|
|
529
1127
|
return entry;
|
|
530
1128
|
}
|
|
531
1129
|
};
|
|
1130
|
+
var nodeMetadataSchema = {
|
|
1131
|
+
instanceType: z.literal("node").optional(),
|
|
1132
|
+
space: z.string(),
|
|
1133
|
+
externalId: z.string(),
|
|
1134
|
+
version: z.number().optional(),
|
|
1135
|
+
createdTime: z.number().optional(),
|
|
1136
|
+
deletedTime: z.number().optional(),
|
|
1137
|
+
lastUpdatedTime: z.number().optional(),
|
|
1138
|
+
_edges: z.record(z.string(), z.unknown()).optional()
|
|
1139
|
+
};
|
|
1140
|
+
function isListRelation(property) {
|
|
1141
|
+
if (isViewPropertyDefinition(property)) {
|
|
1142
|
+
return isListDirectRelation(property);
|
|
1143
|
+
}
|
|
1144
|
+
if (isReverseDirectRelation(property)) {
|
|
1145
|
+
return property.connectionType === "multi_reverse_direct_relation" || property.targetsList === true;
|
|
1146
|
+
}
|
|
1147
|
+
return isEdgeConnection(property);
|
|
1148
|
+
}
|
|
1149
|
+
function isRecord2(value) {
|
|
1150
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
1151
|
+
}
|
|
1152
|
+
var QueryResultValidator = class {
|
|
1153
|
+
constructor(viewMapper) {
|
|
1154
|
+
this.viewMapper = viewMapper;
|
|
1155
|
+
}
|
|
1156
|
+
async parseItems(rootViewExternalId, items, select) {
|
|
1157
|
+
const rootView = await this.viewMapper.getView(rootViewExternalId);
|
|
1158
|
+
const schema = await this.buildResultSchema(rootView, MAX_DEPENDENCY_DEPTH, select);
|
|
1159
|
+
const result = z.array(schema).safeParse(items);
|
|
1160
|
+
if (!result.success) {
|
|
1161
|
+
throw new Error(
|
|
1162
|
+
`Invalid query result:
|
|
1163
|
+
${result.error.issues.map((issue) => `- ${issue.path.map(String).join(".")}: ${issue.message}`).join("\n")}`
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
return result.data;
|
|
1167
|
+
}
|
|
1168
|
+
async buildResultSchema(view, remainingDepth, select) {
|
|
1169
|
+
const shape = { ...nodeMetadataSchema };
|
|
1170
|
+
const includeAllProperties = select == null || select._all === true;
|
|
1171
|
+
for (const [name, property] of Object.entries(view.properties)) {
|
|
1172
|
+
const isSelected = includeAllProperties || name in select;
|
|
1173
|
+
if (!isSelected) continue;
|
|
1174
|
+
const nestedSelect = isRecord2(select?.[name]) ? select[name] : void 0;
|
|
1175
|
+
if (isViewPropertyDefinition(property)) {
|
|
1176
|
+
const relationSource = getDirectRelationSource(property);
|
|
1177
|
+
if (relationSource) {
|
|
1178
|
+
shape[name] = await this.buildRelationSchema(
|
|
1179
|
+
property,
|
|
1180
|
+
relationSource.externalId,
|
|
1181
|
+
remainingDepth,
|
|
1182
|
+
nestedSelect
|
|
1183
|
+
);
|
|
1184
|
+
} else {
|
|
1185
|
+
shape[name] = propertyValueSchema(property, { dateMode: "coerce" }).optional();
|
|
1186
|
+
}
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
if (isReverseDirectRelation(property) || isEdgeConnection(property)) {
|
|
1190
|
+
shape[name] = await this.buildRelationSchema(
|
|
1191
|
+
property,
|
|
1192
|
+
property.source.externalId,
|
|
1193
|
+
remainingDepth,
|
|
1194
|
+
nestedSelect
|
|
1195
|
+
);
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
const schema = z.object(shape);
|
|
1199
|
+
return includeAllProperties ? schema.strict() : schema;
|
|
1200
|
+
}
|
|
1201
|
+
async buildRelationSchema(property, targetViewExternalId, remainingDepth, select) {
|
|
1202
|
+
const isList = isListRelation(property);
|
|
1203
|
+
const fallbackSchema = isViewPropertyDefinition(property) ? propertyValueSchema(property, { dateMode: "coerce" }) : z.unknown();
|
|
1204
|
+
if (remainingDepth <= 0 || select == null) {
|
|
1205
|
+
return fallbackSchema.optional();
|
|
1206
|
+
}
|
|
1207
|
+
const targetView = await this.viewMapper.getView(targetViewExternalId);
|
|
1208
|
+
const nestedSchema = await this.buildResultSchema(targetView, remainingDepth - 1, select);
|
|
1209
|
+
if (isViewPropertyDefinition(property)) {
|
|
1210
|
+
const nestedRelationSchema = isList ? z.array(nestedSchema) : nestedSchema;
|
|
1211
|
+
return z.union([nestedRelationSchema, fallbackSchema]).optional();
|
|
1212
|
+
}
|
|
1213
|
+
return (isList ? z.array(nestedSchema) : nestedSchema).optional();
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
532
1216
|
|
|
533
1217
|
// src/mappers/view-mapper.ts
|
|
534
1218
|
var ViewMapper = class {
|
|
@@ -679,15 +1363,33 @@ function buildDependenciesQuery(previousQuery, nodesParent, nodesChildren, leafC
|
|
|
679
1363
|
|
|
680
1364
|
// src/client.ts
|
|
681
1365
|
var IndustrialModelClient = class {
|
|
682
|
-
constructor(client, dataModelId) {
|
|
1366
|
+
constructor(client, dataModelId, options = {}) {
|
|
683
1367
|
const cognite = createCogniteAdapter(client);
|
|
684
1368
|
this.cognite = cognite;
|
|
685
1369
|
const viewMapper = new ViewMapper(cognite, dataModelId);
|
|
686
1370
|
this.queryMapper = new QueryMapper(viewMapper);
|
|
1371
|
+
this.aggregateMapper = new AggregateMapper(viewMapper);
|
|
1372
|
+
this.aggregateResultMapper = new AggregateResultMapper();
|
|
687
1373
|
this.resultMapper = new QueryResultMapper(viewMapper);
|
|
1374
|
+
this.resultValidator = new QueryResultValidator(viewMapper);
|
|
1375
|
+
this.validateResults = options.validateResults ?? false;
|
|
688
1376
|
}
|
|
689
1377
|
query() {
|
|
690
|
-
|
|
1378
|
+
const execute = (options) => this.queryInternal(options);
|
|
1379
|
+
return execute;
|
|
1380
|
+
}
|
|
1381
|
+
aggregate() {
|
|
1382
|
+
const execute = (options) => this.aggregateInternal(options);
|
|
1383
|
+
return execute;
|
|
1384
|
+
}
|
|
1385
|
+
async aggregateInternal(options) {
|
|
1386
|
+
const cogniteRequest = await this.aggregateMapper.map(options);
|
|
1387
|
+
const response = await this.cognite.aggregateInstances(cogniteRequest);
|
|
1388
|
+
const items = this.aggregateResultMapper.map(
|
|
1389
|
+
response,
|
|
1390
|
+
options
|
|
1391
|
+
);
|
|
1392
|
+
return { items };
|
|
691
1393
|
}
|
|
692
1394
|
async queryInternal(options) {
|
|
693
1395
|
const { viewExternalId, limit = DEFAULT_LIMIT } = options;
|
|
@@ -705,7 +1407,8 @@ var IndustrialModelClient = class {
|
|
|
705
1407
|
mapNodesAndEdges(queryResult),
|
|
706
1408
|
dependenciesData
|
|
707
1409
|
);
|
|
708
|
-
const
|
|
1410
|
+
const mappedPageResult = await this.resultMapper.mapNodes(viewExternalId, queryResultData);
|
|
1411
|
+
const pageResult = this.validateResults ? await this.resultValidator.parseItems(viewExternalId, mappedPageResult, options.select) : mappedPageResult;
|
|
709
1412
|
const nextCursor = queryResult.nextCursor[viewExternalId] ?? null;
|
|
710
1413
|
const isLastPage = pageResult.length < limit || !nextCursor;
|
|
711
1414
|
const resolvedCursor = isLastPage ? null : nextCursor;
|
|
@@ -736,6 +1439,6 @@ var IndustrialModelClient = class {
|
|
|
736
1439
|
}
|
|
737
1440
|
};
|
|
738
1441
|
|
|
739
|
-
export { IndustrialModelClient };
|
|
1442
|
+
export { IndustrialModelClient, buildViewSchema, nodeIdSchema };
|
|
740
1443
|
//# sourceMappingURL=index.js.map
|
|
741
1444
|
//# sourceMappingURL=index.js.map
|