@sdk-it/core 0.19.0 → 0.20.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/dist/index.js CHANGED
@@ -1,920 +1,12 @@
1
- // packages/core/src/index.ts
2
1
  import {
3
2
  pascalcase as _pascalcase,
4
3
  snakecase as _snakecase,
5
4
  spinalcase as _spinalcase
6
5
  } from "stringcase";
7
-
8
- // packages/core/src/lib/deriver.ts
9
- import ts, { TypeFlags, symbolName } from "typescript";
10
- var deriveSymbol = Symbol.for("serialize");
11
- var $types = Symbol.for("types");
12
- var defaults = {
13
- Readable: "any",
14
- ReadableStream: "any",
15
- DateConstructor: "string",
16
- ArrayBufferConstructor: "any",
17
- SharedArrayBufferConstructor: "any",
18
- Int8ArrayConstructor: "any",
19
- Uint8Array: "any"
20
- };
21
- var TypeDeriver = class {
22
- collector = {};
23
- checker;
24
- constructor(checker) {
25
- this.checker = checker;
26
- }
27
- serializeType(type) {
28
- const indexType = type.getStringIndexType();
29
- if (indexType) {
30
- return {
31
- [deriveSymbol]: true,
32
- kind: "record",
33
- optional: false,
34
- [$types]: [this.serializeType(indexType)]
35
- };
36
- }
37
- if (type.flags & TypeFlags.Any) {
38
- return {
39
- [deriveSymbol]: true,
40
- optional: false,
41
- [$types]: []
42
- };
43
- }
44
- if (type.flags & TypeFlags.Unknown) {
45
- return {
46
- [deriveSymbol]: true,
47
- optional: false,
48
- [$types]: []
49
- };
50
- }
51
- if (type.isStringLiteral()) {
52
- return {
53
- [deriveSymbol]: true,
54
- optional: false,
55
- kind: "literal",
56
- value: type.value,
57
- [$types]: ["string"]
58
- };
59
- }
60
- if (type.isNumberLiteral()) {
61
- return {
62
- [deriveSymbol]: true,
63
- optional: false,
64
- kind: "literal",
65
- value: type.value,
66
- [$types]: ["number"]
67
- };
68
- }
69
- if (type.flags & TypeFlags.BooleanLiteral) {
70
- return {
71
- [deriveSymbol]: true,
72
- optional: false,
73
- [$types]: ["boolean"]
74
- };
75
- }
76
- if (type.flags & TypeFlags.TemplateLiteral) {
77
- return {
78
- [deriveSymbol]: true,
79
- optional: false,
80
- [$types]: ["string"]
81
- };
82
- }
83
- if (type.flags & TypeFlags.String) {
84
- return {
85
- [deriveSymbol]: true,
86
- optional: false,
87
- [$types]: ["string"]
88
- };
89
- }
90
- if (type.flags & TypeFlags.Number) {
91
- return {
92
- [deriveSymbol]: true,
93
- optional: false,
94
- [$types]: ["number"]
95
- };
96
- }
97
- if (type.flags & ts.TypeFlags.Boolean) {
98
- return {
99
- [deriveSymbol]: true,
100
- optional: false,
101
- [$types]: ["boolean"]
102
- };
103
- }
104
- if (type.flags & TypeFlags.Null) {
105
- return {
106
- [deriveSymbol]: true,
107
- optional: true,
108
- [$types]: ["null"]
109
- };
110
- }
111
- if (type.isIntersection()) {
112
- let optional;
113
- const types = [];
114
- for (const unionType of type.types) {
115
- if (optional === void 0) {
116
- optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;
117
- if (optional) {
118
- continue;
119
- }
120
- }
121
- types.push(this.serializeType(unionType));
122
- }
123
- return {
124
- [deriveSymbol]: true,
125
- kind: "intersection",
126
- optional,
127
- [$types]: types
128
- };
129
- }
130
- if (type.isUnion()) {
131
- let optional;
132
- const types = [];
133
- for (const unionType of type.types) {
134
- if (optional === void 0) {
135
- optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;
136
- if (optional) {
137
- continue;
138
- }
139
- }
140
- types.push(this.serializeType(unionType));
141
- }
142
- return {
143
- [deriveSymbol]: true,
144
- kind: "union",
145
- optional,
146
- [$types]: types
147
- };
148
- }
149
- if (this.checker.isArrayLikeType(type)) {
150
- const [argType] = this.checker.getTypeArguments(type);
151
- if (!argType) {
152
- const typeName = type.symbol?.getName() || "<unknown>";
153
- console.warn(
154
- `Could not find generic type argument for array type ${typeName}`
155
- );
156
- return {
157
- [deriveSymbol]: true,
158
- optional: false,
159
- kind: "array",
160
- [$types]: ["any"]
161
- };
162
- }
163
- const typeSymbol = argType.getSymbol();
164
- if (!typeSymbol) {
165
- return {
166
- [deriveSymbol]: true,
167
- optional: false,
168
- kind: "array",
169
- [$types]: [this.serializeType(argType)]
170
- };
171
- }
172
- if (typeSymbol.valueDeclaration) {
173
- return {
174
- kind: "array",
175
- [deriveSymbol]: true,
176
- [$types]: [this.serializeNode(typeSymbol.valueDeclaration)]
177
- };
178
- }
179
- const maybeDeclaration = typeSymbol.declarations?.[0];
180
- if (maybeDeclaration) {
181
- if (ts.isMappedTypeNode(maybeDeclaration)) {
182
- const resolvedType = this.checker.getPropertiesOfType(argType).reduce((acc, prop) => {
183
- const propType = this.checker.getTypeOfSymbol(prop);
184
- acc[prop.name] = this.serializeType(propType);
185
- return acc;
186
- }, {});
187
- return {
188
- kind: "array",
189
- optional: false,
190
- [deriveSymbol]: true,
191
- [$types]: [resolvedType]
192
- };
193
- } else {
194
- return {
195
- kind: "array",
196
- ...this.serializeNode(maybeDeclaration)
197
- };
198
- }
199
- }
200
- return {
201
- kind: "array",
202
- optional: false,
203
- [deriveSymbol]: true,
204
- [$types]: ["any"]
205
- };
206
- }
207
- if (type.isClass()) {
208
- const declaration = type.symbol?.valueDeclaration;
209
- if (!declaration) {
210
- return {
211
- [deriveSymbol]: true,
212
- optional: false,
213
- [$types]: [type.symbol.getName()]
214
- };
215
- }
216
- return this.serializeNode(declaration);
217
- }
218
- if (isInterfaceType(type)) {
219
- const valueDeclaration = type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];
220
- if (!valueDeclaration) {
221
- return {
222
- [deriveSymbol]: true,
223
- optional: false,
224
- [$types]: [type.symbol.getName()]
225
- };
226
- }
227
- return this.serializeNode(valueDeclaration);
228
- }
229
- if (type.flags & TypeFlags.Object) {
230
- if (defaults[symbolName(type.symbol)]) {
231
- return {
232
- [deriveSymbol]: true,
233
- optional: false,
234
- [$types]: [defaults[type.symbol.name]]
235
- };
236
- }
237
- const properties = this.checker.getPropertiesOfType(type);
238
- if (properties.length > 0) {
239
- const serializedProps = {};
240
- for (const prop of properties) {
241
- const propAssingment = (prop.getDeclarations() ?? []).find(
242
- (it) => ts.isPropertyAssignment(it)
243
- );
244
- if (propAssingment) {
245
- const type2 = this.checker.getTypeAtLocation(
246
- propAssingment.initializer
247
- );
248
- serializedProps[prop.name] = this.serializeType(type2);
249
- }
250
- if ((prop.getDeclarations() ?? []).find(
251
- (it) => ts.isPropertySignature(it)
252
- )) {
253
- const propType = this.checker.getTypeOfSymbol(prop);
254
- serializedProps[prop.name] = this.serializeType(propType);
255
- }
256
- }
257
- return {
258
- [deriveSymbol]: true,
259
- kind: "object",
260
- optional: false,
261
- [$types]: [serializedProps]
262
- };
263
- }
264
- const declaration = type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];
265
- if (!declaration) {
266
- return {
267
- [deriveSymbol]: true,
268
- optional: false,
269
- [$types]: [type.symbol.getName()]
270
- };
271
- }
272
- return this.serializeNode(declaration);
273
- }
274
- console.warn(`Unhandled type: ${type.flags} ${ts.TypeFlags[type.flags]}`);
275
- return {
276
- [deriveSymbol]: true,
277
- optional: false,
278
- [$types]: [
279
- this.checker.typeToString(
280
- type,
281
- void 0,
282
- ts.TypeFormatFlags.NoTruncation
283
- )
284
- ]
285
- };
286
- }
287
- serializeNode(node) {
288
- if (ts.isObjectLiteralExpression(node)) {
289
- const symbolType = this.checker.getTypeAtLocation(node);
290
- const props = {};
291
- for (const symbol of symbolType.getProperties()) {
292
- const type = this.checker.getTypeOfSymbol(symbol);
293
- props[symbol.name] = this.serializeType(type);
294
- }
295
- for (const prop of node.properties) {
296
- if (ts.isPropertyAssignment(prop)) {
297
- const type = this.checker.getTypeAtLocation(prop.initializer);
298
- props[prop.name.getText()] = this.serializeType(type);
299
- }
300
- }
301
- return props;
302
- }
303
- if (ts.isPropertyAccessExpression(node)) {
304
- const symbol = this.checker.getSymbolAtLocation(node.name);
305
- if (!symbol) {
306
- console.warn(`No symbol found for ${node.name.getText()}`);
307
- return null;
308
- }
309
- const type = this.checker.getTypeOfSymbol(symbol);
310
- return this.serializeType(type);
311
- }
312
- if (ts.isPropertySignature(node)) {
313
- const symbol = this.checker.getSymbolAtLocation(node.name);
314
- if (!symbol) {
315
- console.warn(`No symbol found for ${node.name.getText()}`);
316
- return null;
317
- }
318
- const type = this.checker.getTypeOfSymbol(symbol);
319
- return this.serializeType(type);
320
- }
321
- if (ts.isPropertyDeclaration(node)) {
322
- const symbol = this.checker.getSymbolAtLocation(node.name);
323
- if (!symbol) {
324
- console.warn(`No symbol found for ${node.name.getText()}`);
325
- return null;
326
- }
327
- const type = this.checker.getTypeOfSymbol(symbol);
328
- return this.serializeType(type);
329
- }
330
- if (ts.isInterfaceDeclaration(node)) {
331
- if (!node.name?.text) {
332
- throw new Error("Interface has no name");
333
- }
334
- if (defaults[node.name.text]) {
335
- return {
336
- [deriveSymbol]: true,
337
- optional: false,
338
- [$types]: [defaults[node.name.text]]
339
- };
340
- }
341
- if (!this.collector[node.name.text]) {
342
- this.collector[node.name.text] = {};
343
- const members = {};
344
- for (const member of node.members.filter(ts.isPropertySignature)) {
345
- members[member.name.getText()] = this.serializeNode(member);
346
- }
347
- this.collector[node.name.text] = members;
348
- }
349
- return {
350
- [deriveSymbol]: true,
351
- optional: false,
352
- [$types]: [`#/components/schemas/${node.name.text}`]
353
- };
354
- }
355
- if (ts.isClassDeclaration(node)) {
356
- if (!node.name?.text) {
357
- throw new Error("Class has no name");
358
- }
359
- if (defaults[node.name.text]) {
360
- return {
361
- [deriveSymbol]: true,
362
- optional: false,
363
- [$types]: [defaults[node.name.text]]
364
- };
365
- }
366
- if (!this.collector[node.name.text]) {
367
- this.collector[node.name.text] = {};
368
- const members = {};
369
- for (const member of node.members.filter(ts.isPropertyDeclaration)) {
370
- members[member.name.getText()] = this.serializeNode(member);
371
- }
372
- this.collector[node.name.text] = members;
373
- }
374
- return {
375
- [deriveSymbol]: true,
376
- optional: false,
377
- [$types]: [`#/components/schemas/${node.name.text}`],
378
- $ref: `#/components/schemas/${node.name.text}`
379
- };
380
- }
381
- if (ts.isVariableDeclaration(node)) {
382
- const symbol = this.checker.getSymbolAtLocation(node.name);
383
- if (!symbol) {
384
- console.warn(`No symbol found for ${node.name.getText()}`);
385
- return null;
386
- }
387
- if (!node.type) {
388
- console.warn(`No type found for ${node.name.getText()}`);
389
- return "any";
390
- }
391
- const type = this.checker.getTypeFromTypeNode(node.type);
392
- return this.serializeType(type);
393
- }
394
- if (ts.isIdentifier(node)) {
395
- const symbol = this.checker.getSymbolAtLocation(node);
396
- if (!symbol) {
397
- console.warn(`Identifer: No symbol found for ${node.getText()}`);
398
- return null;
399
- }
400
- const type = this.checker.getTypeAtLocation(node);
401
- return this.serializeType(type);
402
- }
403
- if (ts.isAwaitExpression(node)) {
404
- const type = this.checker.getTypeAtLocation(node);
405
- return this.serializeType(type);
406
- }
407
- if (ts.isCallExpression(node)) {
408
- const type = this.checker.getTypeAtLocation(node);
409
- return this.serializeType(type);
410
- }
411
- if (ts.isAsExpression(node)) {
412
- const type = this.checker.getTypeAtLocation(node);
413
- return this.serializeType(type);
414
- }
415
- if (ts.isTypeLiteralNode(node)) {
416
- const symbolType = this.checker.getTypeAtLocation(node);
417
- const props = {};
418
- for (const symbol of symbolType.getProperties()) {
419
- const type = this.checker.getTypeOfSymbol(symbol);
420
- props[symbol.name] = this.serializeType(type);
421
- }
422
- return {
423
- [deriveSymbol]: true,
424
- optional: false,
425
- [$types]: [props]
426
- };
427
- }
428
- if (node.kind === ts.SyntaxKind.NullKeyword) {
429
- return {
430
- [deriveSymbol]: true,
431
- optional: true,
432
- [$types]: ["null"]
433
- };
434
- }
435
- if (node.kind === ts.SyntaxKind.BooleanKeyword) {
436
- return {
437
- [deriveSymbol]: true,
438
- optional: false,
439
- [$types]: ["boolean"]
440
- };
441
- }
442
- if (node.kind === ts.SyntaxKind.TrueKeyword) {
443
- return {
444
- [deriveSymbol]: true,
445
- optional: false,
446
- kind: "literal",
447
- value: true,
448
- [$types]: ["boolean"]
449
- };
450
- }
451
- if (node.kind === ts.SyntaxKind.FalseKeyword) {
452
- return {
453
- [deriveSymbol]: true,
454
- optional: false,
455
- kind: "literal",
456
- value: false,
457
- [$types]: ["boolean"]
458
- };
459
- }
460
- if (ts.isArrayLiteralExpression(node)) {
461
- const type = this.checker.getTypeAtLocation(node);
462
- return this.serializeType(type);
463
- }
464
- console.warn(`Unhandled node: ${ts.SyntaxKind[node.kind]} ${node.flags}`);
465
- return {
466
- [deriveSymbol]: true,
467
- optional: false,
468
- [$types]: ["any"]
469
- };
470
- }
471
- };
472
- function isInterfaceType(type) {
473
- if (type.isClassOrInterface()) {
474
- return !!(type.symbol.flags & ts.SymbolFlags.Interface);
475
- }
476
- return false;
477
- }
478
-
479
- // packages/core/src/lib/file-system.ts
480
- import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
481
- import { dirname, extname, isAbsolute, join } from "node:path";
482
- async function getFile(filePath) {
483
- if (await exist(filePath)) {
484
- return readFile(filePath, "utf-8");
485
- }
486
- return null;
487
- }
488
- async function exist(file) {
489
- return stat(file).then(() => true).catch(() => false);
490
- }
491
- async function readFolder(path) {
492
- if (await exist(path)) {
493
- return readdir(path);
494
- }
495
- return [];
496
- }
497
- async function writeFiles(dir, contents) {
498
- await Promise.all(
499
- Object.entries(contents).map(async ([file, content]) => {
500
- if (content === null) {
501
- return;
502
- }
503
- const filePath = isAbsolute(file) ? file : join(dir, file);
504
- await mkdir(dirname(filePath), { recursive: true });
505
- if (typeof content === "string") {
506
- await writeFile(filePath, content, "utf-8");
507
- } else {
508
- if (content.ignoreIfExists) {
509
- if (!await exist(filePath)) {
510
- await writeFile(filePath, content.content, "utf-8");
511
- }
512
- } else {
513
- await writeFile(filePath, content.content, "utf-8");
514
- }
515
- }
516
- })
517
- );
518
- }
519
- async function getFolderExports(folder, includeExtension = true, extensions = ["ts"], ignore = () => false) {
520
- const files = await readdir(folder, { withFileTypes: true });
521
- const exports = [];
522
- for (const file of files) {
523
- if (ignore(file)) {
524
- continue;
525
- }
526
- if (file.isDirectory()) {
527
- if (await exist(`${file.parentPath}/${file.name}/index.ts`)) {
528
- exports.push(
529
- `export * from './${file.name}/index${includeExtension ? ".ts" : ""}';`
530
- );
531
- }
532
- } else if (file.name !== "index.ts" && extensions.includes(getExt(file.name))) {
533
- exports.push(
534
- `export * from './${includeExtension ? file.name : file.name.replace(extname(file.name), "")}';`
535
- );
536
- }
537
- }
538
- return exports.join("\n");
539
- }
540
- async function getFolderExportsV2(folder, options = {
541
- extensions: "ts",
542
- ignore: () => false,
543
- includeExtension: true,
544
- exportSyntax: "export * from "
545
- }) {
546
- options.includeExtension ??= true;
547
- if (!await exist(folder)) {
548
- return "";
549
- }
550
- const files = await readdir(folder, { withFileTypes: true });
551
- const exports = [];
552
- for (const file of files) {
553
- if (options.ignore?.(file)) {
554
- continue;
555
- }
556
- if (file.isDirectory()) {
557
- if (await exist(
558
- `${file.parentPath}/${file.name}/index.${options.extensions}`
559
- )) {
560
- exports.push(
561
- `${options.exportSyntax} './${file.name}/index${options.includeExtension ? `.${options.extensions}` : ""}';`
562
- );
563
- }
564
- } else if (file.name !== `index.${options.extensions}` && options.extensions.includes(getExt(file.name))) {
565
- exports.push(
566
- `${options.exportSyntax} './${options.includeExtension ? file.name : file.name.replace(extname(file.name), "")}';`
567
- );
568
- }
569
- }
570
- return exports.join("\n");
571
- }
572
- var getExt = (fileName) => {
573
- if (!fileName) {
574
- return "";
575
- }
576
- const lastDot = fileName.lastIndexOf(".");
577
- if (lastDot === -1) {
578
- return "";
579
- }
580
- const ext = fileName.slice(lastDot + 1).split("/").filter(Boolean).join("");
581
- if (ext === fileName) {
582
- return "";
583
- }
584
- return ext || "txt";
585
- };
586
-
587
- // packages/core/src/lib/paths.ts
588
- var methods = [
589
- "get",
590
- "post",
591
- "put",
592
- "patch",
593
- "delete",
594
- "trace",
595
- "head"
596
- ];
597
- var semanticSourceToOpenAPI = {
598
- queries: "query",
599
- query: "query",
600
- headers: "header",
601
- params: "path"
602
- };
603
- var Paths = class {
604
- #commonZodImport;
605
- #onOperation;
606
- #operations = [];
607
- constructor(config) {
608
- this.#commonZodImport = config.commonZodImport;
609
- this.#onOperation = config.onOperation;
610
- }
611
- addPath(name, path, method, contentType, selectors, responses, sourceFile, tags, description) {
612
- const responsesObject = this.#responseItemToResponses(responses);
613
- this.#operations.push({
614
- name,
615
- path: this.#tunePath(path),
616
- sourceFile,
617
- contentType,
618
- method,
619
- selectors,
620
- responses: responsesObject,
621
- tags,
622
- description
623
- });
624
- return this;
625
- }
626
- #responseItemToResponses(responses) {
627
- const responsesObject = {};
628
- for (const item of responses) {
629
- const ct = item.contentType;
630
- const schema = item.response ? toSchema(item.response) : {};
631
- if (!responsesObject[item.statusCode]) {
632
- responsesObject[item.statusCode] = {
633
- description: `Response for ${item.statusCode}`,
634
- content: ct !== "empty" ? {
635
- [ct]: ct === "application/octet-stream" ? { schema: { type: "string", format: "binary" } } : { schema }
636
- } : void 0,
637
- headers: item.headers.length ? item.headers.reduce((acc, current) => {
638
- const headers = typeof current === "string" ? { [current]: [] } : current;
639
- return Object.entries(headers).reduce(
640
- (subAcc, [key, value]) => {
641
- const header = {
642
- [key]: {
643
- schema: {
644
- type: "string",
645
- enum: value.length ? value : void 0
646
- }
647
- }
648
- };
649
- return { ...subAcc, ...header };
650
- },
651
- acc
652
- );
653
- }, {}) : void 0
654
- };
655
- } else {
656
- if (!responsesObject[item.statusCode].content[ct]) {
657
- responsesObject[item.statusCode].content[ct] = { schema };
658
- } else {
659
- const existing = responsesObject[item.statusCode].content[ct].schema;
660
- if (existing.oneOf) {
661
- if (!existing.oneOf.find(
662
- (it) => JSON.stringify(it) === JSON.stringify(schema)
663
- )) {
664
- existing.oneOf.push(schema);
665
- }
666
- } else if (JSON.stringify(existing) !== JSON.stringify(schema)) {
667
- responsesObject[item.statusCode].content[ct].schema = {
668
- oneOf: [existing, schema]
669
- };
670
- }
671
- }
672
- }
673
- }
674
- return responsesObject;
675
- }
676
- async #selectosToParameters(selectors) {
677
- const parameters = [];
678
- const bodySchemaProps = {};
679
- for (const selector of selectors) {
680
- if (selector.source === "body") {
681
- bodySchemaProps[selector.name] = {
682
- required: selector.required,
683
- schema: await evalZod(selector.against, this.#commonZodImport)
684
- };
685
- continue;
686
- }
687
- const parameter = {
688
- in: semanticSourceToOpenAPI[selector.source],
689
- name: selector.name,
690
- required: selector.required,
691
- schema: await evalZod(selector.against, this.#commonZodImport)
692
- };
693
- parameters.push(parameter);
694
- }
695
- return { parameters, bodySchemaProps };
696
- }
697
- async getPaths() {
698
- const operations = {};
699
- for (const operation of this.#operations) {
700
- const { path, method, selectors } = operation;
701
- const { parameters, bodySchemaProps } = await this.#selectosToParameters(selectors);
702
- const bodySchema = {};
703
- const required = [];
704
- for (const [key, value] of Object.entries(bodySchemaProps)) {
705
- if (value.required) {
706
- required.push(key);
707
- }
708
- bodySchema[key] = value.schema;
709
- }
710
- const operationObject = {
711
- operationId: operation.name,
712
- parameters,
713
- tags: operation.tags,
714
- description: operation.description,
715
- requestBody: Object.keys(bodySchema).length ? {
716
- required: required.length ? true : false,
717
- content: {
718
- [operation.contentType || "application/json"]: {
719
- schema: {
720
- required: required.length ? required : void 0,
721
- type: "object",
722
- properties: bodySchema
723
- }
724
- }
725
- }
726
- } : void 0,
727
- responses: Object.keys(operation.responses).length === 0 ? void 0 : operation.responses
728
- };
729
- if (!operations[path]) {
730
- operations[path] = {};
731
- }
732
- operations[path][method] = operationObject;
733
- if (this.#onOperation) {
734
- const paths = this.#onOperation?.(
735
- operation.sourceFile,
736
- method,
737
- path,
738
- operationObject
739
- );
740
- Object.assign(operations, paths ?? {});
741
- }
742
- }
743
- return operations;
744
- }
745
- /**
746
- * Converts Express/Node.js style path parameters (/path/:param) to OpenAPI style (/path/{param})
747
- */
748
- #tunePath(path) {
749
- return path.replace(/:([^/]+)/g, "{$1}");
750
- }
751
- };
752
- async function evalZod(schema, commonZodImport) {
753
- const lines = [
754
- `import { createRequire } from "node:module";`,
755
- `const filename = "${import.meta.url}";`,
756
- `const require = createRequire(filename);`,
757
- `const z = require("zod");`,
758
- commonZodImport ? `const commonZod = require('${commonZodImport}');` : "",
759
- `const {zodToJsonSchema} = require('zod-to-json-schema');`,
760
- `const schema = ${schema.replace(".optional()", "").replaceAll("instanceof(File)", "string().base64()")};`,
761
- `const jsonSchema = zodToJsonSchema(schema, {
762
- $refStrategy: 'root',
763
- basePath: ['#', 'components', 'schemas'],
764
- target: 'jsonSchema7',
765
- base64Strategy: 'format:binary',
766
- });`,
767
- `export default jsonSchema;`
768
- ];
769
- const base64 = Buffer.from(lines.join("\n")).toString("base64");
770
- return import(`data:text/javascript;base64,${base64}`).then((mod) => mod.default).then(({ $schema, ...result }) => result);
771
- }
772
- function toSchema(data) {
773
- if (data === null || data === void 0) {
774
- return { type: "any" };
775
- } else if (typeof data === "string") {
776
- const isRef2 = data.startsWith("#");
777
- if (isRef2) {
778
- return { $ref: data };
779
- }
780
- return { type: data };
781
- } else if (data.kind === "literal") {
782
- return { enum: [data.value], type: data[$types][0] };
783
- } else if (data.kind === "record") {
784
- return {
785
- type: "object",
786
- additionalProperties: toSchema(data[$types][0])
787
- };
788
- } else if (data.kind === "array") {
789
- const items = data[$types].map(toSchema);
790
- return { type: "array", items: data[$types].length ? items[0] : {} };
791
- } else if (data.kind === "union") {
792
- return { anyOf: data[$types].map(toSchema) };
793
- } else if (data.kind === "intersection") {
794
- return { allOf: data[$types].map(toSchema) };
795
- } else if ($types in data) {
796
- return data[$types].map(toSchema)[0] ?? {};
797
- } else {
798
- const props = {};
799
- const required = [];
800
- for (const [key, value] of Object.entries(data)) {
801
- props[key] = toSchema(value);
802
- if (!value.optional) {
803
- required.push(key);
804
- }
805
- }
806
- return {
807
- type: "object",
808
- properties: props,
809
- required,
810
- additionalProperties: false
811
- };
812
- }
813
- }
814
- function isHttpMethod(name) {
815
- return ["get", "post", "put", "delete", "patch"].includes(name);
816
- }
817
-
818
- // packages/core/src/lib/program.ts
819
- import debug from "debug";
820
- import { dirname as dirname2, join as join2 } from "node:path";
821
- import ts2 from "typescript";
822
- var logger = debug("january:client");
823
- function parseTsConfig(tsconfigPath) {
824
- logger(`Using TypeScript version: ${ts2.version}`);
825
- const configContent = ts2.readConfigFile(tsconfigPath, ts2.sys.readFile);
826
- if (configContent.error) {
827
- console.error(
828
- `Failed to read tsconfig file:`,
829
- ts2.formatDiagnosticsWithColorAndContext([configContent.error], {
830
- getCanonicalFileName: (path) => path,
831
- getCurrentDirectory: ts2.sys.getCurrentDirectory,
832
- getNewLine: () => ts2.sys.newLine
833
- })
834
- );
835
- throw new Error("Failed to parse tsconfig.json");
836
- }
837
- const parsed = ts2.parseJsonConfigFileContent(
838
- configContent.config,
839
- ts2.sys,
840
- dirname2(tsconfigPath)
841
- );
842
- if (parsed.errors.length > 0) {
843
- console.error(
844
- `Errors found in tsconfig.json:`,
845
- ts2.formatDiagnosticsWithColorAndContext(parsed.errors, {
846
- getCanonicalFileName: (path) => path,
847
- getCurrentDirectory: ts2.sys.getCurrentDirectory,
848
- getNewLine: () => ts2.sys.newLine
849
- })
850
- );
851
- throw new Error("Failed to parse tsconfig.json");
852
- }
853
- return parsed;
854
- }
855
- function getProgram(tsconfigPath) {
856
- const tsConfigParseResult = parseTsConfig(tsconfigPath);
857
- logger(`Parsing tsconfig`);
858
- return ts2.createProgram({
859
- options: {
860
- ...tsConfigParseResult.options,
861
- noEmit: true,
862
- incremental: true,
863
- tsBuildInfoFile: join2(dirname2(tsconfigPath), "./.tsbuildinfo")
864
- // not working atm
865
- },
866
- rootNames: tsConfigParseResult.fileNames,
867
- projectReferences: tsConfigParseResult.projectReferences,
868
- configFileParsingDiagnostics: tsConfigParseResult.errors
869
- });
870
- }
871
- function getPropertyAssignment(node, name) {
872
- if (ts2.isObjectLiteralExpression(node)) {
873
- return node.properties.filter((prop) => ts2.isPropertyAssignment(prop)).find((prop) => prop.name.getText() === name);
874
- }
875
- return void 0;
876
- }
877
- function isCallExpression(node, name) {
878
- return ts2.isCallExpression(node) && node.expression && ts2.isIdentifier(node.expression) && node.expression.text === name;
879
- }
880
- function isInterfaceType2(type) {
881
- if (type.isClassOrInterface()) {
882
- return !!(type.symbol.flags & ts2.SymbolFlags.Interface);
883
- }
884
- return false;
885
- }
886
-
887
- // packages/core/src/lib/ref.ts
888
- import { get } from "lodash-es";
889
- function isRef(obj) {
890
- return obj && "$ref" in obj;
891
- }
892
- function notRef(obj) {
893
- return !isRef(obj);
894
- }
895
- function cleanRef(ref) {
896
- return ref.replace(/^#\//, "");
897
- }
898
- function parseRef(ref) {
899
- const parts = ref.split("/");
900
- const [model] = parts.splice(-1);
901
- const [namespace] = parts.splice(-1);
902
- return {
903
- model,
904
- namespace,
905
- path: cleanRef(parts.join("/"))
906
- };
907
- }
908
- function followRef(spec, ref) {
909
- const pathParts = cleanRef(ref).split("/");
910
- const entry = get(spec, pathParts);
911
- if (entry && "$ref" in entry) {
912
- return followRef(spec, entry.$ref);
913
- }
914
- return entry;
915
- }
916
-
917
- // packages/core/src/index.ts
6
+ export * from "./lib/deriver.js";
7
+ export * from "./lib/paths.js";
8
+ export * from "./lib/program.js";
9
+ export * from "./lib/ref.js";
918
10
  function removeDuplicates(data, accessor = (item) => item) {
919
11
  return [...new Map(data.map((x) => [accessor(x), x])).values()];
920
12
  }
@@ -943,35 +35,11 @@ function snakecase(value) {
943
35
  return _snakecase(value.split("/").join(" "));
944
36
  }
945
37
  export {
946
- $types,
947
- Paths,
948
- TypeDeriver,
949
- cleanRef,
950
- deriveSymbol,
951
- exist,
952
- followRef,
953
- getExt,
954
- getFile,
955
- getFolderExports,
956
- getFolderExportsV2,
957
- getProgram,
958
- getPropertyAssignment,
959
- isCallExpression,
960
38
  isEmpty,
961
- isHttpMethod,
962
- isInterfaceType2 as isInterfaceType,
963
- isRef,
964
- methods,
965
- notRef,
966
- parseRef,
967
- parseTsConfig,
968
39
  pascalcase,
969
- readFolder,
970
40
  removeDuplicates,
971
41
  snakecase,
972
42
  spinalcase,
973
- toLitObject,
974
- toSchema,
975
- writeFiles
43
+ toLitObject
976
44
  };
977
45
  //# sourceMappingURL=index.js.map