@xlr-lib/xlr-sdk 0.1.1-next.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.
@@ -0,0 +1,961 @@
1
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/sdk.ts
2
+ import {
3
+ computeEffectiveObject as computeEffectiveObject2,
4
+ resolveConditional as resolveConditional2,
5
+ resolveReferenceNode as resolveReferenceNode2
6
+ } from "@xlr-lib/xlr-utils";
7
+ import { fillInGenerics } from "@xlr-lib/xlr-utils";
8
+ import { TSWriter } from "@xlr-lib/xlr-converters";
9
+ import fs from "fs";
10
+ import path from "path";
11
+ import ts from "typescript";
12
+
13
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/registry/basic-registry.ts
14
+ var BasicXLRRegistry = class {
15
+ typeMap;
16
+ pluginMap;
17
+ infoMap;
18
+ constructor() {
19
+ this.typeMap = /* @__PURE__ */ new Map();
20
+ this.pluginMap = /* @__PURE__ */ new Map();
21
+ this.infoMap = /* @__PURE__ */ new Map();
22
+ }
23
+ /** Returns a copy of the XLR to guard against unexpected type modification */
24
+ get(id) {
25
+ const value = this.typeMap.get(id);
26
+ return value ? JSON.parse(JSON.stringify(value)) : void 0;
27
+ }
28
+ add(type, plugin, capability) {
29
+ this.typeMap.set(type.name, type);
30
+ this.infoMap.set(type.name, { plugin, capability });
31
+ if (!this.pluginMap.has(plugin)) {
32
+ this.pluginMap.set(plugin, /* @__PURE__ */ new Map());
33
+ }
34
+ const pluginsCapabilities = this.pluginMap.get(plugin);
35
+ if (!pluginsCapabilities.has(capability)) {
36
+ pluginsCapabilities.set(capability, []);
37
+ }
38
+ const providedCapabilities = pluginsCapabilities.get(
39
+ capability
40
+ );
41
+ providedCapabilities.push(type.name);
42
+ }
43
+ has(id) {
44
+ return this.typeMap.has(id);
45
+ }
46
+ list(filterArgs) {
47
+ const validTypes = [];
48
+ this.pluginMap.forEach((manifest, pluginName) => {
49
+ if (!filterArgs?.pluginFilter || !pluginName.match(filterArgs.pluginFilter)) {
50
+ manifest.forEach((types, capabilityName) => {
51
+ if (!filterArgs?.capabilityFilter || !capabilityName.match(filterArgs.capabilityFilter)) {
52
+ types.forEach((type) => {
53
+ if (!filterArgs?.typeFilter || !type.match(filterArgs.typeFilter)) {
54
+ validTypes.push(type);
55
+ }
56
+ });
57
+ }
58
+ });
59
+ }
60
+ });
61
+ return validTypes.map((type) => this.get(type));
62
+ }
63
+ info(id) {
64
+ return this.infoMap.get(id);
65
+ }
66
+ };
67
+
68
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/validator.ts
69
+ import {
70
+ makePropertyMap,
71
+ resolveConditional,
72
+ isPrimitiveTypeNode,
73
+ resolveReferenceNode,
74
+ computeEffectiveObject
75
+ } from "@xlr-lib/xlr-utils";
76
+
77
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/types.ts
78
+ var ValidationSeverity = /* @__PURE__ */ ((ValidationSeverity2) => {
79
+ ValidationSeverity2[ValidationSeverity2["Error"] = 1] = "Error";
80
+ ValidationSeverity2[ValidationSeverity2["Warning"] = 2] = "Warning";
81
+ ValidationSeverity2[ValidationSeverity2["Info"] = 3] = "Info";
82
+ ValidationSeverity2[ValidationSeverity2["Trace"] = 4] = "Trace";
83
+ return ValidationSeverity2;
84
+ })(ValidationSeverity || {});
85
+
86
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/validator.ts
87
+ var MAX_VALID_SHOWN = 20;
88
+ var XLRValidator = class {
89
+ config;
90
+ resolveType;
91
+ regexCache;
92
+ constructor(resolveType, config) {
93
+ this.config = config || {};
94
+ this.resolveType = resolveType;
95
+ this.regexCache = /* @__PURE__ */ new Map();
96
+ }
97
+ /** Main entrypoint for validation */
98
+ validateType(rootNode, xlrNode) {
99
+ const validationIssues = new Array();
100
+ if (xlrNode.type === "object") {
101
+ if (rootNode.type === "object") {
102
+ validationIssues.push(...this.validateObject(xlrNode, rootNode));
103
+ } else {
104
+ validationIssues.push({
105
+ type: "type",
106
+ node: rootNode,
107
+ message: `Expected an object but got an "${rootNode.type}"`,
108
+ severity: 1 /* Error */
109
+ });
110
+ }
111
+ } else if (xlrNode.type === "array") {
112
+ if (rootNode.type === "array") {
113
+ validationIssues.push(...this.validateArray(rootNode, xlrNode));
114
+ } else {
115
+ validationIssues.push({
116
+ type: "type",
117
+ node: rootNode,
118
+ message: `Expected an array but got an "${rootNode.type}"`,
119
+ severity: 1 /* Error */
120
+ });
121
+ }
122
+ } else if (xlrNode.type === "template") {
123
+ const error = this.validateTemplate(rootNode, xlrNode);
124
+ if (error) {
125
+ validationIssues.push(error);
126
+ }
127
+ } else if (xlrNode.type === "or") {
128
+ const potentialTypeErrors = [];
129
+ for (const potentialType of xlrNode.or) {
130
+ const potentialErrors = this.validateType(rootNode, potentialType);
131
+ if (potentialErrors.length === 0) {
132
+ return validationIssues;
133
+ }
134
+ potentialTypeErrors.push({
135
+ type: potentialType,
136
+ errors: potentialErrors
137
+ });
138
+ }
139
+ let message;
140
+ const expectedTypes = xlrNode.or.map(
141
+ (node) => isPrimitiveTypeNode(node) ? node.type : node.name ?? node.title ?? node.type ?? "<unnamed type>"
142
+ ).join(" | ");
143
+ if (xlrNode.name) {
144
+ message = `Does not match any of the expected types for type: '${xlrNode.name}'`;
145
+ } else if (xlrNode.title) {
146
+ message = `Does not match any of the expected types for property: '${xlrNode.title}'`;
147
+ } else {
148
+ message = `Does not match any of the types: ${expectedTypes}`;
149
+ }
150
+ const { infoMessage } = this.generateNestedTypesInfo(
151
+ potentialTypeErrors,
152
+ xlrNode,
153
+ rootNode
154
+ );
155
+ validationIssues.push({
156
+ type: "value",
157
+ node: rootNode,
158
+ message: message.trim(),
159
+ severity: 1 /* Error */
160
+ });
161
+ if (infoMessage) {
162
+ validationIssues.push({
163
+ type: "value",
164
+ node: rootNode,
165
+ message: infoMessage,
166
+ severity: 3 /* Info */
167
+ });
168
+ }
169
+ } else if (xlrNode.type === "and") {
170
+ const effectiveType = {
171
+ ...this.computeIntersectionType(xlrNode.and),
172
+ ...xlrNode.name ? { name: xlrNode.name } : {}
173
+ };
174
+ validationIssues.push(...this.validateType(rootNode, effectiveType));
175
+ } else if (xlrNode.type === "record") {
176
+ rootNode.children?.forEach((child) => {
177
+ validationIssues.push(
178
+ ...this.validateType(child.children?.[0], xlrNode.keyType)
179
+ );
180
+ validationIssues.push(
181
+ ...this.validateType(child.children?.[1], xlrNode.valueType)
182
+ );
183
+ });
184
+ } else if (xlrNode.type === "ref") {
185
+ const refType = this.getRefType(xlrNode);
186
+ if (refType === void 0) {
187
+ validationIssues.push({
188
+ type: "unknown",
189
+ node: rootNode,
190
+ message: `Type "${xlrNode.ref}" is not defined in provided bundles`,
191
+ severity: 1 /* Error */
192
+ });
193
+ } else {
194
+ validationIssues.push(
195
+ ...this.validateType(rootNode, refType)
196
+ );
197
+ }
198
+ } else if (isPrimitiveTypeNode(xlrNode)) {
199
+ if (!this.validateLiteralType(xlrNode, rootNode)) {
200
+ if ((xlrNode.type === "string" || xlrNode.type === "number" || xlrNode.type === "boolean") && xlrNode.const) {
201
+ validationIssues.push({
202
+ type: "type",
203
+ node: rootNode.parent,
204
+ message: `Expected "${xlrNode.const}" but got "${rootNode.value}"`,
205
+ expected: xlrNode.const,
206
+ severity: 1 /* Error */
207
+ });
208
+ } else {
209
+ validationIssues.push({
210
+ type: "type",
211
+ node: rootNode.parent,
212
+ message: `Expected type "${xlrNode.type}" but got "${rootNode.type}"`,
213
+ expected: xlrNode.type,
214
+ severity: 1 /* Error */
215
+ });
216
+ }
217
+ }
218
+ } else if (xlrNode.type === "conditional") {
219
+ let { right, left } = xlrNode.check;
220
+ if (right.type === "ref") {
221
+ right = this.getRefType(right);
222
+ }
223
+ if (left.type === "ref") {
224
+ left = this.getRefType(left);
225
+ }
226
+ const resolvedXLRNode = {
227
+ ...xlrNode,
228
+ check: {
229
+ left,
230
+ right
231
+ }
232
+ };
233
+ const resolvedConditional = resolveConditional(resolvedXLRNode);
234
+ if (resolvedConditional === resolvedXLRNode) {
235
+ throw Error(
236
+ `Unable to resolve conditional type at runtime: ${xlrNode.name}`
237
+ );
238
+ }
239
+ validationIssues.push(
240
+ ...this.validateType(rootNode, resolvedConditional)
241
+ );
242
+ } else {
243
+ throw Error(`Unknown type ${xlrNode.type}`);
244
+ }
245
+ return validationIssues;
246
+ }
247
+ generateNestedTypesInfo(potentialTypeErrors, xlrNode, rootNode) {
248
+ const nestedTypes = /* @__PURE__ */ new Set();
249
+ potentialTypeErrors.forEach((typeError) => {
250
+ if (typeError.type.type !== "template") {
251
+ typeError.errors.forEach((error) => {
252
+ if (error.type === "type" && error.expected) {
253
+ String(error.expected).split(" | ").forEach((val) => nestedTypes.add(val.trim()));
254
+ }
255
+ });
256
+ }
257
+ });
258
+ if (nestedTypes.size === 0) {
259
+ xlrNode.or.forEach((type) => {
260
+ const typeName = type.name ?? type.title ?? type.type ?? "<unnamed type>";
261
+ nestedTypes.add(typeName);
262
+ });
263
+ }
264
+ const nestedTypesArray = [...nestedTypes];
265
+ let nestedTypesList = nestedTypesArray.slice(0, MAX_VALID_SHOWN).join(" | ") + (nestedTypesArray.length > MAX_VALID_SHOWN ? ` | +${nestedTypesArray.length - MAX_VALID_SHOWN} ... ${nestedTypesArray.pop()}` : "");
266
+ const docsURL = this.config.urlMapping;
267
+ if (docsURL && xlrNode.name && docsURL[xlrNode.name]) {
268
+ nestedTypesList = docsURL[xlrNode.name];
269
+ }
270
+ let infoMessage;
271
+ if (rootNode.value !== void 0) {
272
+ infoMessage = `Got: ${rootNode.value} and expected: ${nestedTypesList}`;
273
+ } else if (nestedTypesList) {
274
+ infoMessage = `Expected: ${nestedTypesList}`;
275
+ }
276
+ return { nestedTypesList, infoMessage };
277
+ }
278
+ validateTemplate(node, xlrNode) {
279
+ if (node.type !== "string") {
280
+ return {
281
+ type: "type",
282
+ node: node.parent,
283
+ message: `Expected type "${xlrNode.type}" but got "${typeof node}"`,
284
+ expected: xlrNode.type,
285
+ severity: 1 /* Error */
286
+ };
287
+ }
288
+ const regex = this.getRegex(xlrNode.format);
289
+ const valid = regex.exec(node.value);
290
+ if (!valid) {
291
+ return {
292
+ type: "value",
293
+ node: node.parent,
294
+ message: `Does not match expected format: ${xlrNode.format}`,
295
+ expected: xlrNode.format,
296
+ severity: 1 /* Error */
297
+ };
298
+ }
299
+ }
300
+ validateArray(rootNode, xlrNode) {
301
+ const issues = [];
302
+ rootNode.children?.forEach(
303
+ (child) => issues.push(...this.validateType(child, xlrNode.elementType))
304
+ );
305
+ return issues;
306
+ }
307
+ validateObject(xlrNode, node) {
308
+ const issues = [];
309
+ const objectProps = makePropertyMap(node);
310
+ for (const prop in xlrNode.properties) {
311
+ const expectedType = xlrNode.properties[prop];
312
+ const valueNode = objectProps.get(prop);
313
+ if (expectedType.required && valueNode === void 0) {
314
+ issues.push({
315
+ type: "missing",
316
+ node,
317
+ message: `Property "${prop}" missing from type "${xlrNode.name}"`,
318
+ severity: 1 /* Error */
319
+ });
320
+ }
321
+ if (valueNode) {
322
+ issues.push(
323
+ ...this.validateType(valueNode, expectedType.node)
324
+ );
325
+ }
326
+ }
327
+ const extraKeys = Array.from(objectProps.keys()).filter(
328
+ (key) => xlrNode.properties[key] === void 0
329
+ );
330
+ if (xlrNode.additionalProperties === false && extraKeys.length > 0) {
331
+ issues.push({
332
+ type: "value",
333
+ node,
334
+ message: `Unexpected properties on "${xlrNode.name}": ${extraKeys.join(
335
+ ", "
336
+ )}`,
337
+ severity: 1 /* Error */
338
+ });
339
+ } else {
340
+ issues.push(
341
+ ...extraKeys.flatMap(
342
+ (key) => this.validateType(
343
+ objectProps.get(key),
344
+ xlrNode.additionalProperties
345
+ )
346
+ )
347
+ );
348
+ }
349
+ return issues;
350
+ }
351
+ validateLiteralType(expectedType, literalType) {
352
+ switch (expectedType.type) {
353
+ case "boolean":
354
+ if (expectedType.const) {
355
+ return expectedType.const === literalType.value;
356
+ }
357
+ return typeof literalType.value === "boolean";
358
+ case "number":
359
+ if (expectedType.const) {
360
+ return expectedType.const === literalType.value;
361
+ }
362
+ return typeof literalType.value === "number";
363
+ case "string":
364
+ if (expectedType.const) {
365
+ return expectedType.const === literalType.value;
366
+ }
367
+ return typeof literalType.value === "string";
368
+ case "null":
369
+ return literalType.value === null;
370
+ case "never":
371
+ return literalType === void 0;
372
+ case "any":
373
+ return literalType !== void 0;
374
+ case "unknown":
375
+ return literalType !== void 0;
376
+ case "undefined":
377
+ return true;
378
+ default:
379
+ return false;
380
+ }
381
+ }
382
+ getRefType(ref) {
383
+ let refName = ref.ref;
384
+ if (refName.indexOf("<") > 0) {
385
+ [refName] = refName.split("<");
386
+ }
387
+ const actualType = this.resolveType(refName);
388
+ if (!actualType) {
389
+ throw new Error(`Error: can't resolve type reference ${refName}`);
390
+ }
391
+ return resolveReferenceNode(ref, actualType);
392
+ }
393
+ getRegex(expString) {
394
+ if (this.regexCache.has(expString)) {
395
+ return this.regexCache.get(expString);
396
+ }
397
+ const exp = new RegExp(expString);
398
+ this.regexCache.set(expString, exp);
399
+ return exp;
400
+ }
401
+ computeIntersectionType(types) {
402
+ let firstElement = types[0];
403
+ let effectiveType;
404
+ const topLevelTypeName = types[0].name;
405
+ if (firstElement.type === "ref") {
406
+ firstElement = this.getRefType(firstElement);
407
+ }
408
+ if (firstElement.type === "and") {
409
+ effectiveType = this.computeIntersectionType(firstElement.and);
410
+ } else if (firstElement.type === "record") {
411
+ effectiveType = {
412
+ type: "object",
413
+ properties: {},
414
+ additionalProperties: firstElement.valueType
415
+ };
416
+ } else if (firstElement.type !== "or" && firstElement.type !== "object") {
417
+ throw new Error(
418
+ `Can't compute a union with a non-object type ${firstElement.type} (${firstElement.name})`
419
+ );
420
+ } else {
421
+ effectiveType = firstElement;
422
+ }
423
+ types.slice(1).forEach((type) => {
424
+ let typeToApply = type;
425
+ if (typeToApply.type === "record") {
426
+ typeToApply = {
427
+ type: "object",
428
+ properties: {},
429
+ additionalProperties: typeToApply.valueType
430
+ };
431
+ }
432
+ if (type.type === "ref") {
433
+ typeToApply = this.getRefType(type);
434
+ }
435
+ if (typeToApply.type === "and") {
436
+ typeToApply = this.computeIntersectionType([type, effectiveType]);
437
+ }
438
+ if (typeToApply.type === "object") {
439
+ if (effectiveType.type === "object") {
440
+ effectiveType = computeEffectiveObject(effectiveType, typeToApply);
441
+ } else {
442
+ effectiveType = {
443
+ ...effectiveType,
444
+ or: effectiveType.or.map((y) => {
445
+ const intersectedType = this.computeIntersectionType([
446
+ y,
447
+ typeToApply
448
+ ]);
449
+ if (!intersectedType.name && topLevelTypeName) {
450
+ intersectedType.name = topLevelTypeName;
451
+ }
452
+ return intersectedType;
453
+ })
454
+ };
455
+ }
456
+ } else if (typeToApply.type === "or") {
457
+ if (effectiveType.type === "object") {
458
+ effectiveType = {
459
+ ...typeToApply,
460
+ or: typeToApply.or.map((y) => {
461
+ const intersectedType = this.computeIntersectionType([
462
+ y,
463
+ effectiveType
464
+ ]);
465
+ if (!intersectedType.name && topLevelTypeName) {
466
+ intersectedType.name = topLevelTypeName;
467
+ }
468
+ return intersectedType;
469
+ })
470
+ };
471
+ } else {
472
+ throw new Error("unimplemented operation or x or projection");
473
+ }
474
+ } else {
475
+ throw new Error(
476
+ `Can't compute a union with a non-object type ${typeToApply.type} (${typeToApply.name})`
477
+ );
478
+ }
479
+ });
480
+ if (effectiveType.type === "or" && !effectiveType.name && topLevelTypeName) {
481
+ effectiveType.name = topLevelTypeName;
482
+ }
483
+ return effectiveType;
484
+ }
485
+ };
486
+
487
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/utils.ts
488
+ import { isGenericNamedType } from "@xlr-lib/xlr-utils";
489
+ var isMatchingCapability = (capability, capabilitiesToMatch) => {
490
+ if (Array.isArray(capabilitiesToMatch)) {
491
+ return capabilitiesToMatch.includes(capability);
492
+ }
493
+ return capability === capabilitiesToMatch;
494
+ };
495
+ function xlrTransformWalker(transformMap) {
496
+ const walker = (n) => {
497
+ let node = { ...n };
498
+ const transformFunctions = transformMap[node.type];
499
+ for (const transformFn of transformFunctions ?? []) {
500
+ node = transformFn(node);
501
+ }
502
+ if (node.type === "object") {
503
+ const newObjectProperties = {};
504
+ for (const key in node.properties) {
505
+ const value = node.properties[key];
506
+ newObjectProperties[key] = {
507
+ required: value.required,
508
+ node: walker(value.node)
509
+ };
510
+ }
511
+ return {
512
+ ...node,
513
+ properties: { ...newObjectProperties },
514
+ ...isGenericNamedType(node) ? {
515
+ genericTokens: node.genericTokens.map((token) => {
516
+ return {
517
+ ...token,
518
+ constraints: token.constraints ? walker(token.constraints) : void 0,
519
+ default: token.default ? walker(token.default) : void 0
520
+ };
521
+ })
522
+ } : {},
523
+ extends: node.extends ? walker(node.extends) : void 0,
524
+ additionalProperties: node.additionalProperties ? walker(node.additionalProperties) : false
525
+ };
526
+ }
527
+ if (node.type === "array") {
528
+ return {
529
+ ...node,
530
+ elementType: walker(node.elementType)
531
+ };
532
+ }
533
+ if (node.type === "and") {
534
+ return {
535
+ ...node,
536
+ and: node.and.map((element) => walker(element))
537
+ };
538
+ }
539
+ if (node.type === "or") {
540
+ return {
541
+ ...node,
542
+ or: node.or.map((element) => walker(element))
543
+ };
544
+ }
545
+ if (node.type === "ref") {
546
+ return {
547
+ ...node,
548
+ ...node.genericArguments ? {
549
+ genericArguments: node.genericArguments?.map(
550
+ (arg) => walker(arg)
551
+ )
552
+ } : {}
553
+ };
554
+ }
555
+ if (node.type === "tuple") {
556
+ return {
557
+ ...node,
558
+ elementTypes: node.elementTypes.map((element) => {
559
+ return {
560
+ name: element.name,
561
+ type: walker(element.type),
562
+ optional: element.optional
563
+ };
564
+ }),
565
+ additionalItems: node.additionalItems ? walker(node.additionalItems) : false
566
+ };
567
+ }
568
+ if (node.type === "function") {
569
+ return {
570
+ ...node,
571
+ parameters: node.parameters.map((param) => {
572
+ return {
573
+ ...param,
574
+ type: walker(param.type),
575
+ default: param.default ? walker(param.default) : void 0
576
+ };
577
+ }),
578
+ returnType: node.returnType ? walker(node.returnType) : void 0
579
+ };
580
+ }
581
+ if (node.type === "record") {
582
+ return {
583
+ ...node,
584
+ keyType: walker(node.keyType),
585
+ valueType: walker(node.valueType)
586
+ };
587
+ }
588
+ if (node.type === "conditional") {
589
+ return {
590
+ ...node,
591
+ check: {
592
+ left: walker(node.check.left),
593
+ right: walker(node.check.left)
594
+ },
595
+ value: {
596
+ true: walker(node.value.true),
597
+ false: walker(node.value.false)
598
+ }
599
+ };
600
+ }
601
+ return node;
602
+ };
603
+ return walker;
604
+ }
605
+ function simpleTransformGenerator(typeToTransform, capabilityToTransform, functionToRun) {
606
+ return (n, capability) => {
607
+ if (isMatchingCapability(capability, capabilityToTransform)) {
608
+ return xlrTransformWalker({ [typeToTransform]: [functionToRun] })(n);
609
+ }
610
+ return n;
611
+ };
612
+ }
613
+
614
+ // ../../../../../../../../../execroot/_main/bazel-out/k8-fastbuild/bin/sdk/src/sdk.ts
615
+ var XLRSDK = class {
616
+ registry;
617
+ validator;
618
+ tsWriter;
619
+ computedNodeCache;
620
+ externalTransformFunctions;
621
+ constructor(customRegistry) {
622
+ this.registry = customRegistry ?? new BasicXLRRegistry();
623
+ this.validator = new XLRValidator(this.getType.bind(this));
624
+ this.tsWriter = new TSWriter();
625
+ this.computedNodeCache = /* @__PURE__ */ new Map();
626
+ this.externalTransformFunctions = /* @__PURE__ */ new Map();
627
+ }
628
+ /**
629
+ * Loads definitions from a path on the filesystem
630
+ *
631
+ * @param inputPath - path to the directory to load (above the xlr folder)
632
+ * @param filters - Any filters to apply when loading the types (a positive match will omit)
633
+ * @param transforms - any transforms to apply to the types being loaded
634
+ */
635
+ loadDefinitionsFromDisk(inputPath, filters, transforms) {
636
+ this.computedNodeCache.clear();
637
+ const transformsToRun = [
638
+ ...this.externalTransformFunctions.values(),
639
+ ...transforms ?? []
640
+ ];
641
+ const manifest = JSON.parse(
642
+ fs.readFileSync(path.join(inputPath, "xlr", "manifest.json")).toString(),
643
+ (key, value) => {
644
+ if (typeof value === "object" && value !== null) {
645
+ if (key === "capabilities") {
646
+ return new Map(Object.entries(value));
647
+ }
648
+ }
649
+ return value;
650
+ }
651
+ );
652
+ manifest.capabilities?.forEach((capabilityList, capabilityName) => {
653
+ if (filters?.capabilityFilter && capabilityName.match(filters?.capabilityFilter))
654
+ return;
655
+ capabilityList.forEach((extensionName) => {
656
+ if (!filters?.typeFilter || !extensionName.match(filters?.typeFilter)) {
657
+ const cType = JSON.parse(
658
+ fs.readFileSync(
659
+ path.join(inputPath, "xlr", `${extensionName}.json`)
660
+ ).toString()
661
+ );
662
+ const effectiveType = transformsToRun?.reduce(
663
+ (typeAccumulator, transformFn) => transformFn(
664
+ typeAccumulator,
665
+ capabilityName
666
+ ),
667
+ cType
668
+ ) ?? cType;
669
+ this.registry.add(effectiveType, manifest.pluginName, capabilityName);
670
+ }
671
+ });
672
+ });
673
+ }
674
+ /**
675
+ * Load definitions from a js/ts file in memory
676
+ *
677
+ * @param manifest - The imported XLR manifest module
678
+ * @param filters - Any filters to apply when loading the types (a positive match will omit)
679
+ * @param transforms - any transforms to apply to the types being loaded
680
+ */
681
+ async loadDefinitionsFromModule(manifest, filters, transforms) {
682
+ this.computedNodeCache.clear();
683
+ const transformsToRun = [
684
+ ...this.externalTransformFunctions.values(),
685
+ ...transforms ?? []
686
+ ];
687
+ Object.keys(manifest.capabilities)?.forEach((capabilityName) => {
688
+ if (filters?.capabilityFilter && capabilityName.match(filters?.capabilityFilter))
689
+ return;
690
+ const capabilityList = manifest.capabilities[capabilityName];
691
+ capabilityList.forEach((extension) => {
692
+ if (!filters?.typeFilter || !extension.name.match(filters?.typeFilter)) {
693
+ const effectiveType = transformsToRun?.reduce(
694
+ (typeAccumulator, transformFn) => transformFn(
695
+ typeAccumulator,
696
+ capabilityName
697
+ ),
698
+ extension
699
+ ) ?? extension;
700
+ this.registry.add(effectiveType, manifest.pluginName, capabilityName);
701
+ }
702
+ });
703
+ });
704
+ }
705
+ /**
706
+ * Statically load transform function that should be applied to every XLR bundle that is imported
707
+ */
708
+ addTransformFunction(name, fn) {
709
+ this.externalTransformFunctions.set(name, fn);
710
+ }
711
+ /**
712
+ * Remove any transform function loaded via the `addTransformFunction` method by name
713
+ */
714
+ removeTransformFunction(name) {
715
+ this.externalTransformFunctions.delete(name);
716
+ }
717
+ /**
718
+ * Returns a Type that has been previously loaded
719
+ *
720
+ * @param id - Type to retrieve
721
+ * @param options - `GetTypeOptions`
722
+ * @returns `NamedType<NodeType>` | `undefined`
723
+ */
724
+ getType(id, options) {
725
+ let type = this.registry.get(id);
726
+ if (options?.getRawType === true || !type) {
727
+ return type;
728
+ }
729
+ if (this.computedNodeCache.has(id)) {
730
+ return JSON.parse(JSON.stringify(this.computedNodeCache.get(id)));
731
+ }
732
+ type = this.resolveType(type, options?.optimize);
733
+ this.computedNodeCache.set(id, type);
734
+ return type;
735
+ }
736
+ /**
737
+ * Returns if a Type with `id` has been loaded into the DSK
738
+ *
739
+ * @param id - Type to retrieve
740
+ * @returns `boolean`
741
+ */
742
+ hasType(id) {
743
+ return this.registry.has(id);
744
+ }
745
+ /**
746
+ * Lists types that have been loaded into the SDK
747
+ *
748
+ * @param filters - Any filters to apply to the types returned (a positive match will omit)
749
+ * @returns `Array<NamedTypes>`
750
+ */
751
+ listTypes(filters) {
752
+ return this.registry.list(filters);
753
+ }
754
+ /**
755
+ * Returns meta information around a registered type
756
+ *
757
+ * @param id - Name of Type to retrieve
758
+ * @returns `TypeMetaData` | `undefined`
759
+ */
760
+ getTypeInfo(id) {
761
+ return this.registry.info(id);
762
+ }
763
+ /**
764
+ * Validates if a JSONC Node follows the XLR Type registered under the `typeName` specified
765
+ *
766
+ * @param typeName - Registered XLR Type to use for validation
767
+ * @param rootNode - Node to validate
768
+ * @returns `Array<ValidationErrors>`
769
+ */
770
+ validateByName(typeName, rootNode) {
771
+ const xlr = this.getType(typeName);
772
+ if (!xlr) {
773
+ throw new Error(
774
+ `Type ${typeName} does not exist in registry, can't validate`
775
+ );
776
+ }
777
+ return this.validator.validateType(rootNode, xlr);
778
+ }
779
+ /**
780
+ * Validates if a JSONC Node follows the supplied XLR Type
781
+ *
782
+ * @param type - Type to validate against
783
+ * @param rootNode - Node to validate
784
+ * @returns `Array<ValidationErrors>`
785
+ */
786
+ validateByType(type, rootNode) {
787
+ return this.validator.validateType(rootNode, type);
788
+ }
789
+ /**
790
+ * Exports the types loaded into the registry to the specified format
791
+ *
792
+ * @param exportType - what format to export as
793
+ * @param importMap - a map of primitive packages to types exported from that package to add import statements
794
+ * @param filters - filter out plugins/capabilities/types you don't want to export
795
+ * @param transforms - transforms to apply to types before exporting them
796
+ * @returns [filename, content][] - Tuples of filenames and content to write
797
+ */
798
+ exportRegistry(exportType, importMap, filters, transforms) {
799
+ const typesToExport = this.registry.list(filters).map((type) => {
800
+ const effectiveType = transforms?.reduce(
801
+ (typeAccumulator, transformFn) => transformFn(
802
+ typeAccumulator,
803
+ this.registry.info(type.name)?.capability
804
+ ),
805
+ type
806
+ ) ?? type;
807
+ return effectiveType;
808
+ });
809
+ if (exportType === "TypeScript") {
810
+ const outputString = this.exportToTypeScript(typesToExport, importMap);
811
+ return [["out.d.ts", outputString]];
812
+ }
813
+ throw new Error(`Unknown export format ${exportType}`);
814
+ }
815
+ /**
816
+ * Transforms a generated XLR node into its final representation by resolving all `extends` properties.
817
+ * If `optimize` is set to true the following operations are also performed:
818
+ * - Solving any conditional types
819
+ * - Computing the effective types of any union elements
820
+ * - Resolving any ref nodes
821
+ * - filing in any remaining generics with their default value
822
+ */
823
+ resolveType(type, optimize = true) {
824
+ const resolvedObject = fillInGenerics(type);
825
+ let transformMap = {
826
+ object: [(objectNode) => {
827
+ if (objectNode.extends) {
828
+ const refName = objectNode.extends.ref.split("<")[0];
829
+ let extendedType = this.getType(refName, { getRawType: true });
830
+ if (!extendedType) {
831
+ throw new Error(
832
+ `Error resolving ${objectNode.name}: can't find extended type ${refName}`
833
+ );
834
+ }
835
+ extendedType = resolveReferenceNode2(
836
+ objectNode.extends,
837
+ extendedType
838
+ );
839
+ if (extendedType.type === "object") {
840
+ return {
841
+ ...computeEffectiveObject2(
842
+ extendedType,
843
+ objectNode,
844
+ false
845
+ ),
846
+ name: objectNode.name,
847
+ description: objectNode.description
848
+ };
849
+ }
850
+ if (extendedType.type === "or") {
851
+ return {
852
+ ...this.validator.computeIntersectionType(
853
+ [
854
+ objectNode,
855
+ extendedType
856
+ ]
857
+ ),
858
+ name: objectNode.name,
859
+ description: objectNode.description
860
+ };
861
+ }
862
+ return {
863
+ name: objectNode.name,
864
+ type: "and",
865
+ and: [
866
+ {
867
+ ...objectNode,
868
+ extends: void 0
869
+ },
870
+ extendedType
871
+ ]
872
+ };
873
+ }
874
+ return objectNode;
875
+ }]
876
+ };
877
+ if (optimize) {
878
+ transformMap = {
879
+ ...transformMap,
880
+ conditional: [(node) => {
881
+ return resolveConditional2(node);
882
+ }],
883
+ and: [(node) => {
884
+ return {
885
+ ...this.validator.computeIntersectionType(node.and),
886
+ ...node.name ? { name: node.name } : {}
887
+ };
888
+ }],
889
+ ref: [(refNode) => {
890
+ return this.validator.getRefType(refNode);
891
+ }]
892
+ };
893
+ }
894
+ return xlrTransformWalker(transformMap)(resolvedObject);
895
+ }
896
+ exportToTypeScript(typesToExport, importMap) {
897
+ const referencedImports = /* @__PURE__ */ new Set();
898
+ const exportedTypes = /* @__PURE__ */ new Map();
899
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
900
+ let resultFile = ts.createSourceFile(
901
+ "output.d.ts",
902
+ "",
903
+ ts.ScriptTarget.ES2017,
904
+ false,
905
+ // setParentNodes
906
+ ts.ScriptKind.TS
907
+ );
908
+ typesToExport.forEach((typeNode) => {
909
+ const { type, referencedTypes, additionalTypes } = this.tsWriter.convertNamedType(typeNode);
910
+ exportedTypes.set(typeNode.name, type);
911
+ additionalTypes?.forEach(
912
+ (additionalType, name) => exportedTypes.set(name, additionalType)
913
+ );
914
+ referencedTypes?.forEach(
915
+ (referencedType) => referencedImports.add(referencedType)
916
+ );
917
+ });
918
+ const typesToPrint = [];
919
+ exportedTypes.forEach(
920
+ (type) => typesToPrint.push(
921
+ printer.printNode(ts.EmitHint.Unspecified, type, resultFile)
922
+ )
923
+ );
924
+ importMap.forEach((imports, packageName) => {
925
+ const applicableImports = imports.filter((i) => referencedImports.has(i));
926
+ resultFile = ts.factory.updateSourceFile(resultFile, [
927
+ ts.factory.createImportDeclaration(
928
+ /* modifiers */
929
+ void 0,
930
+ ts.factory.createImportClause(
931
+ false,
932
+ void 0,
933
+ ts.factory.createNamedImports(
934
+ applicableImports.map(
935
+ (i) => ts.factory.createImportSpecifier(
936
+ false,
937
+ void 0,
938
+ ts.factory.createIdentifier(i)
939
+ )
940
+ )
941
+ )
942
+ ),
943
+ ts.factory.createStringLiteral(packageName)
944
+ ),
945
+ ...resultFile.statements
946
+ ]);
947
+ });
948
+ const headerText = printer.printFile(resultFile);
949
+ const nodeText = typesToPrint.join("\n");
950
+ return `${headerText}
951
+ ${nodeText}`;
952
+ }
953
+ };
954
+ export {
955
+ BasicXLRRegistry,
956
+ ValidationSeverity,
957
+ XLRSDK,
958
+ simpleTransformGenerator,
959
+ xlrTransformWalker
960
+ };
961
+ //# sourceMappingURL=index.mjs.map