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