typed-csv 1.0.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,1979 @@
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
+ // src/csv-loader/webpack.ts
31
+ var webpack_exports = {};
32
+ __export(webpack_exports, {
33
+ default: () => csvLoader
34
+ });
35
+ module.exports = __toCommonJS(webpack_exports);
36
+ var path4 = __toESM(require("path"));
37
+ var fs2 = __toESM(require("fs"));
38
+
39
+ // src/csv-loader/module-gen.ts
40
+ var path3 = __toESM(require("path"));
41
+
42
+ // src/csv-loader/loader.ts
43
+ var import_sync = require("csv-parse/sync");
44
+
45
+ // src/parser.ts
46
+ var ParseError = class extends Error {
47
+ constructor(message, position, schema, value) {
48
+ let fullMessage = message;
49
+ if (position !== void 0) {
50
+ fullMessage += ` at position ${position}`;
51
+ }
52
+ if (schema !== void 0) {
53
+ fullMessage += `. Schema: ${schema}`;
54
+ }
55
+ if (value !== void 0) {
56
+ fullMessage += `. Value: ${value}`;
57
+ }
58
+ super(fullMessage);
59
+ this.position = position;
60
+ this.schema = schema;
61
+ this.value = value;
62
+ this.name = "ParseError";
63
+ }
64
+ };
65
+ var Parser = class {
66
+ constructor(input) {
67
+ this.pos = 0;
68
+ this.input = input;
69
+ }
70
+ peek() {
71
+ return this.input[this.pos] || "";
72
+ }
73
+ consume() {
74
+ return this.input[this.pos++] || "";
75
+ }
76
+ skipWhitespace() {
77
+ while (this.pos < this.input.length && /\s/.test(this.input[this.pos])) {
78
+ this.pos++;
79
+ }
80
+ }
81
+ match(str) {
82
+ return this.input.slice(this.pos, this.pos + str.length) === str;
83
+ }
84
+ consumeStr(str) {
85
+ if (this.match(str)) {
86
+ this.pos += str.length;
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ getPosition() {
92
+ return this.pos;
93
+ }
94
+ getInputLength() {
95
+ return this.input.length;
96
+ }
97
+ parseSchema() {
98
+ this.skipWhitespace();
99
+ let schema = this.parseSchemaInternal();
100
+ this.skipWhitespace();
101
+ if (this.consumeStr("[")) {
102
+ this.skipWhitespace();
103
+ if (!this.consumeStr("]")) {
104
+ throw new ParseError("Expected ]", this.pos);
105
+ }
106
+ schema = { type: "array", element: schema };
107
+ this.skipWhitespace();
108
+ }
109
+ if (this.consumeStr("|")) {
110
+ const members = [schema];
111
+ while (true) {
112
+ this.skipWhitespace();
113
+ const member = this.parseSchemaInternal();
114
+ members.push(member);
115
+ this.skipWhitespace();
116
+ if (!this.consumeStr("|")) {
117
+ break;
118
+ }
119
+ }
120
+ return {
121
+ type: "union",
122
+ members
123
+ };
124
+ }
125
+ return schema;
126
+ }
127
+ parseSchemaInternal() {
128
+ this.skipWhitespace();
129
+ if (this.consumeStr("(")) {
130
+ this.skipWhitespace();
131
+ const schema = this.parseSchema();
132
+ this.skipWhitespace();
133
+ if (!this.consumeStr(")")) {
134
+ throw new ParseError("Expected )", this.pos);
135
+ }
136
+ this.skipWhitespace();
137
+ if (this.consumeStr("[")) {
138
+ this.skipWhitespace();
139
+ if (!this.consumeStr("]")) {
140
+ throw new ParseError("Expected ]", this.pos);
141
+ }
142
+ return { type: "array", element: schema };
143
+ }
144
+ return schema;
145
+ }
146
+ if (this.peek() === '"' || this.peek() === "'") {
147
+ return this.parseStringLiteralSchema();
148
+ }
149
+ if (this.consumeStr("~")) {
150
+ return this.parseReverseReferenceSchema();
151
+ }
152
+ if (this.consumeStr("@")) {
153
+ return this.parseReferenceSchema();
154
+ }
155
+ if (this.consumeStr("string")) {
156
+ if (this.consumeStr("[")) {
157
+ this.skipWhitespace();
158
+ if (!this.consumeStr("]")) {
159
+ throw new ParseError("Expected ]", this.pos);
160
+ }
161
+ return { type: "array", element: { type: "string" } };
162
+ }
163
+ return { type: "string" };
164
+ }
165
+ if (this.consumeStr("number")) {
166
+ if (this.consumeStr("[")) {
167
+ this.skipWhitespace();
168
+ if (!this.consumeStr("]")) {
169
+ throw new ParseError("Expected ]", this.pos);
170
+ }
171
+ return { type: "array", element: { type: "number" } };
172
+ }
173
+ return { type: "number" };
174
+ }
175
+ if (this.consumeStr("int")) {
176
+ if (this.consumeStr("[")) {
177
+ this.skipWhitespace();
178
+ if (!this.consumeStr("]")) {
179
+ throw new ParseError("Expected ]", this.pos);
180
+ }
181
+ return { type: "array", element: { type: "int" } };
182
+ }
183
+ return { type: "int" };
184
+ }
185
+ if (this.consumeStr("float")) {
186
+ if (this.consumeStr("[")) {
187
+ this.skipWhitespace();
188
+ if (!this.consumeStr("]")) {
189
+ throw new ParseError("Expected ]", this.pos);
190
+ }
191
+ return { type: "array", element: { type: "float" } };
192
+ }
193
+ return { type: "float" };
194
+ }
195
+ if (this.consumeStr("boolean")) {
196
+ if (this.consumeStr("[")) {
197
+ this.skipWhitespace();
198
+ if (!this.consumeStr("]")) {
199
+ throw new ParseError("Expected ]", this.pos);
200
+ }
201
+ return { type: "array", element: { type: "boolean" } };
202
+ }
203
+ return { type: "boolean" };
204
+ }
205
+ if (this.consumeStr("[")) {
206
+ const elements = [];
207
+ this.skipWhitespace();
208
+ if (this.peek() === "]") {
209
+ this.consume();
210
+ throw new ParseError("Empty array/tuple not allowed", this.pos);
211
+ }
212
+ elements.push(this.parseNamedSchema());
213
+ this.skipWhitespace();
214
+ if (this.consumeStr(";")) {
215
+ const remainingElements = [];
216
+ while (true) {
217
+ this.skipWhitespace();
218
+ remainingElements.push(this.parseNamedSchema());
219
+ this.skipWhitespace();
220
+ if (!this.consumeStr(";")) {
221
+ break;
222
+ }
223
+ }
224
+ elements.push(...remainingElements);
225
+ }
226
+ this.skipWhitespace();
227
+ if (!this.consumeStr("]")) {
228
+ throw new ParseError("Expected ]", this.pos);
229
+ }
230
+ if (this.consumeStr("[")) {
231
+ this.skipWhitespace();
232
+ if (!this.consumeStr("]")) {
233
+ throw new ParseError("Expected ]", this.pos);
234
+ }
235
+ if (elements.length === 1 && !elements[0].name) {
236
+ return { type: "array", element: elements[0].schema };
237
+ }
238
+ return { type: "array", element: { type: "tuple", elements } };
239
+ }
240
+ if (elements.length === 1 && !elements[0].name) {
241
+ return { type: "array", element: elements[0].schema };
242
+ }
243
+ return { type: "tuple", elements };
244
+ }
245
+ throw new ParseError(
246
+ `Unknown type: ${this.peek() || "end of input"}`,
247
+ this.pos
248
+ );
249
+ }
250
+ parseStringLiteralSchema() {
251
+ const value = this.parseStringLiteral();
252
+ return {
253
+ type: "stringLiteral",
254
+ value
255
+ };
256
+ }
257
+ parseStringLiteral() {
258
+ const quote = this.peek();
259
+ if (quote !== '"' && quote !== "'") {
260
+ throw new ParseError("Expected string literal with quotes", this.pos);
261
+ }
262
+ this.consume();
263
+ let value = "";
264
+ while (this.pos < this.input.length) {
265
+ const char = this.peek();
266
+ if (char === "\\") {
267
+ this.consume();
268
+ const nextChar = this.consume();
269
+ if (nextChar === '"' || nextChar === "'" || nextChar === "\\" || nextChar === "|" || nextChar === ";" || nextChar === "(" || nextChar === ")") {
270
+ value += nextChar;
271
+ } else {
272
+ value += "\\" + nextChar;
273
+ }
274
+ } else if (char === quote) {
275
+ this.consume();
276
+ return value;
277
+ } else {
278
+ value += this.consume();
279
+ }
280
+ }
281
+ throw new ParseError("Unterminated string literal", this.pos);
282
+ }
283
+ parseNamedSchema() {
284
+ this.skipWhitespace();
285
+ const startpos = this.pos;
286
+ let identifier = "";
287
+ while (this.pos < this.input.length && /[a-zA-Z0-9\-_]/.test(this.peek())) {
288
+ identifier += this.consume();
289
+ }
290
+ if (identifier.length === 0) {
291
+ const schema = this.parseSchema();
292
+ return { schema };
293
+ }
294
+ this.skipWhitespace();
295
+ if (this.consumeStr(":")) {
296
+ this.skipWhitespace();
297
+ const name = identifier;
298
+ const schema = this.parseSchema();
299
+ return { name, schema };
300
+ } else {
301
+ this.pos = startpos;
302
+ const schema = this.parseSchema();
303
+ return { schema };
304
+ }
305
+ }
306
+ parseReferenceSchema() {
307
+ let tableName = "";
308
+ while (this.pos < this.input.length && /[a-zA-Z0-9\-_]/.test(this.peek())) {
309
+ tableName += this.consume();
310
+ }
311
+ if (tableName.length === 0) {
312
+ throw new ParseError("Expected table name after @", this.pos);
313
+ }
314
+ this.skipWhitespace();
315
+ if (this.consumeStr("[]")) {
316
+ this.skipWhitespace();
317
+ const isOptional2 = this.consumeStr("?");
318
+ return {
319
+ type: "reference",
320
+ tableName,
321
+ isArray: true,
322
+ isOptional: isOptional2
323
+ };
324
+ }
325
+ const isOptional = this.consumeStr("?");
326
+ return {
327
+ type: "reference",
328
+ tableName,
329
+ isArray: false,
330
+ isOptional
331
+ };
332
+ }
333
+ parseReverseReferenceSchema() {
334
+ let tableName = "";
335
+ while (this.pos < this.input.length && /[a-zA-Z0-9\-_]/.test(this.peek())) {
336
+ tableName += this.consume();
337
+ }
338
+ if (tableName.length === 0) {
339
+ throw new ParseError("Expected table name after ~", this.pos);
340
+ }
341
+ this.skipWhitespace();
342
+ if (!this.consumeStr("(")) {
343
+ throw new ParseError(
344
+ "Expected ( after reverse reference table name",
345
+ this.pos
346
+ );
347
+ }
348
+ this.skipWhitespace();
349
+ let foreignKey = "";
350
+ while (this.pos < this.input.length && /[a-zA-Z0-9\-_]/.test(this.peek())) {
351
+ foreignKey += this.consume();
352
+ }
353
+ if (foreignKey.length === 0) {
354
+ throw new ParseError("Expected foreign key name inside ()", this.pos);
355
+ }
356
+ this.skipWhitespace();
357
+ if (!this.consumeStr(")")) {
358
+ throw new ParseError("Expected ) after foreign key name", this.pos);
359
+ }
360
+ this.skipWhitespace();
361
+ const isOptional = this.consumeStr("?");
362
+ return {
363
+ type: "reverseReference",
364
+ tableName,
365
+ foreignKey,
366
+ isOptional
367
+ };
368
+ }
369
+ };
370
+ function parseSchema(schemaString) {
371
+ const parser = new Parser(schemaString.trim());
372
+ const schema = parser.parseSchema();
373
+ if (parser.getPosition() < parser.getInputLength()) {
374
+ throw new ParseError("Unexpected input after schema", parser.getPosition());
375
+ }
376
+ return schema;
377
+ }
378
+
379
+ // src/type-utils.ts
380
+ function schemaToTypeString(schema, resourceNames) {
381
+ switch (schema.type) {
382
+ case "string":
383
+ return "string";
384
+ case "number":
385
+ case "int":
386
+ case "float":
387
+ return "number";
388
+ case "boolean":
389
+ return "boolean";
390
+ case "stringLiteral":
391
+ return `"${schema.value}"`;
392
+ case "union":
393
+ return schema.members.map((m) => schemaToTypeString(m, resourceNames)).join(" | ");
394
+ case "reference": {
395
+ const typeName = resourceNames?.get(schema.tableName) || schema.tableName.charAt(0).toUpperCase() + schema.tableName.slice(1);
396
+ const baseType = schema.isArray ? `${typeName}[]` : typeName;
397
+ return schema.isOptional ? `${baseType} | null` : baseType;
398
+ }
399
+ case "reverseReference": {
400
+ const typeName = resourceNames?.get(schema.tableName) || schema.tableName.charAt(0).toUpperCase() + schema.tableName.slice(1);
401
+ const baseType = `${typeName}[]`;
402
+ return schema.isOptional ? `${baseType} | null` : baseType;
403
+ }
404
+ case "array":
405
+ if (schema.element.type === "tuple") {
406
+ const tupleElements2 = schema.element.elements.map((el) => {
407
+ const typeStr = schemaToTypeString(el.schema, resourceNames);
408
+ return el.name ? `${el.name}: ${typeStr}` : typeStr;
409
+ });
410
+ return `[${tupleElements2.join(", ")}][]`;
411
+ }
412
+ const elementType = schemaToTypeString(schema.element, resourceNames);
413
+ if (schema.element.type === "union") {
414
+ return `(${elementType})[]`;
415
+ }
416
+ return `${elementType}[]`;
417
+ case "tuple":
418
+ const tupleElements = schema.elements.map((el) => {
419
+ const typeStr = schemaToTypeString(el.schema, resourceNames);
420
+ return el.name ? `${el.name}: ${typeStr}` : typeStr;
421
+ });
422
+ return `[${tupleElements.join(", ")}]`;
423
+ default:
424
+ return "unknown";
425
+ }
426
+ }
427
+ function createValidator(schema) {
428
+ return function validate(value) {
429
+ switch (schema.type) {
430
+ case "string":
431
+ return typeof value === "string";
432
+ case "number":
433
+ return typeof value === "number" && !isNaN(value);
434
+ case "int":
435
+ return typeof value === "number" && !isNaN(value) && Number.isInteger(value);
436
+ case "float":
437
+ return typeof value === "number" && !isNaN(value);
438
+ case "boolean":
439
+ return typeof value === "boolean";
440
+ case "stringLiteral":
441
+ return typeof value === "string" && value === schema.value;
442
+ case "union":
443
+ return schema.members.some((member) => createValidator(member)(value));
444
+ case "tuple":
445
+ if (!Array.isArray(value)) return false;
446
+ if (value.length !== schema.elements.length) return false;
447
+ return schema.elements.every(
448
+ (elementSchema, index) => createValidator(elementSchema.schema)(value[index])
449
+ );
450
+ case "array":
451
+ if (!Array.isArray(value)) return false;
452
+ return value.every((item) => createValidator(schema.element)(item));
453
+ case "reference":
454
+ if (schema.isOptional && value === null) return true;
455
+ if (schema.isArray) {
456
+ return Array.isArray(value) && value.every((id) => typeof id === "string");
457
+ }
458
+ return typeof value === "string" || Array.isArray(value) && value.every((id) => typeof id === "string");
459
+ case "reverseReference":
460
+ if (schema.isOptional && value === null) return true;
461
+ return Array.isArray(value);
462
+ default:
463
+ return false;
464
+ }
465
+ };
466
+ }
467
+
468
+ // src/value-parser.ts
469
+ var ValueParser = class {
470
+ constructor(input, schemaString) {
471
+ this.pos = 0;
472
+ this.input = input;
473
+ this.schemaString = schemaString;
474
+ }
475
+ peek() {
476
+ return this.input[this.pos] || "";
477
+ }
478
+ consume() {
479
+ return this.input[this.pos++] || "";
480
+ }
481
+ skipWhitespace() {
482
+ while (this.pos < this.input.length && /\s/.test(this.input[this.pos])) {
483
+ this.pos++;
484
+ }
485
+ }
486
+ consumeStr(str) {
487
+ if (this.input.slice(this.pos, this.pos + str.length) === str) {
488
+ this.pos += str.length;
489
+ return true;
490
+ }
491
+ return false;
492
+ }
493
+ parseValue(schema, allowOmitBrackets = false) {
494
+ this.skipWhitespace();
495
+ switch (schema.type) {
496
+ case "string":
497
+ return this.parseStringValue();
498
+ case "number":
499
+ return this.parseNumberValue();
500
+ case "int":
501
+ return this.parseIntValue();
502
+ case "float":
503
+ return this.parseFloatValue();
504
+ case "boolean":
505
+ return this.parseBooleanValue();
506
+ case "stringLiteral":
507
+ return this.parseStringLiteralValue(schema);
508
+ case "union":
509
+ return this.parseUnionValue(schema);
510
+ case "tuple":
511
+ return this.parseTupleValue(schema, allowOmitBrackets);
512
+ case "array":
513
+ return this.parseArrayValue(schema, allowOmitBrackets);
514
+ case "reference":
515
+ return this.parseReferenceValue(schema);
516
+ case "reverseReference":
517
+ return null;
518
+ default:
519
+ throw new ParseError(
520
+ `Unknown schema type: ${schema.type}`,
521
+ this.pos,
522
+ this.schemaString,
523
+ this.input
524
+ );
525
+ }
526
+ }
527
+ parseStringValue() {
528
+ let result = "";
529
+ while (this.pos < this.input.length) {
530
+ const char = this.peek();
531
+ if (char === "\\") {
532
+ this.consume();
533
+ const nextChar = this.consume();
534
+ if (nextChar === ";" || nextChar === "[" || nextChar === "]" || nextChar === "\\") {
535
+ result += nextChar;
536
+ } else {
537
+ result += "\\" + nextChar;
538
+ }
539
+ } else if (char === ";" || char === "]") {
540
+ break;
541
+ } else {
542
+ result += this.consume();
543
+ }
544
+ }
545
+ return result.trim();
546
+ }
547
+ parseNumberValue() {
548
+ let numStr = "";
549
+ while (this.pos < this.input.length && /[\d.\-+eE]/.test(this.peek())) {
550
+ numStr += this.consume();
551
+ }
552
+ const num = parseFloat(numStr);
553
+ if (isNaN(num)) {
554
+ throw new ParseError(
555
+ "Invalid number",
556
+ this.pos - numStr.length,
557
+ this.schemaString,
558
+ this.input
559
+ );
560
+ }
561
+ return num;
562
+ }
563
+ parseIntValue() {
564
+ let numStr = "";
565
+ while (this.pos < this.input.length && /[\d.\-+eE]/.test(this.peek())) {
566
+ numStr += this.consume();
567
+ }
568
+ const num = parseFloat(numStr);
569
+ if (isNaN(num)) {
570
+ throw new ParseError(
571
+ "Invalid number",
572
+ this.pos - numStr.length,
573
+ this.schemaString,
574
+ this.input
575
+ );
576
+ }
577
+ if (!Number.isInteger(num)) {
578
+ throw new ParseError(
579
+ "Expected integer value",
580
+ this.pos - numStr.length,
581
+ this.schemaString,
582
+ this.input
583
+ );
584
+ }
585
+ return num;
586
+ }
587
+ parseFloatValue() {
588
+ return this.parseNumberValue();
589
+ }
590
+ parseBooleanValue() {
591
+ if (this.consumeStr("true")) {
592
+ return true;
593
+ }
594
+ if (this.consumeStr("false")) {
595
+ return false;
596
+ }
597
+ throw new ParseError(
598
+ "Expected true or false",
599
+ this.pos,
600
+ this.schemaString,
601
+ this.input
602
+ );
603
+ }
604
+ parseStringLiteralValue(schema) {
605
+ const quote = this.peek();
606
+ if (quote === '"' || quote === "'") {
607
+ this.consume();
608
+ let value = "";
609
+ while (this.pos < this.input.length) {
610
+ const char = this.peek();
611
+ if (char === "\\") {
612
+ this.consume();
613
+ const nextChar = this.consume();
614
+ if (nextChar === '"' || nextChar === "'" || nextChar === "\\" || nextChar === ";") {
615
+ value += nextChar;
616
+ } else {
617
+ value += "\\" + nextChar;
618
+ }
619
+ } else if (char === quote) {
620
+ this.consume();
621
+ if (value !== schema.value) {
622
+ throw new ParseError(
623
+ `Invalid value '"${value}"'. Expected '"${schema.value}"'`,
624
+ this.pos,
625
+ this.schemaString,
626
+ this.input
627
+ );
628
+ }
629
+ return value;
630
+ } else {
631
+ value += this.consume();
632
+ }
633
+ }
634
+ throw new ParseError(
635
+ "Unterminated string literal",
636
+ this.pos,
637
+ this.schemaString,
638
+ this.input
639
+ );
640
+ } else {
641
+ let value = "";
642
+ while (this.pos < this.input.length) {
643
+ const char = this.peek();
644
+ if (char === ";" || char === "]" || char === ")") {
645
+ break;
646
+ }
647
+ value += this.consume();
648
+ }
649
+ value = value.trim();
650
+ if (value !== schema.value) {
651
+ throw new ParseError(
652
+ `Invalid value '${value}'. Expected '${schema.value}'`,
653
+ this.pos - value.length,
654
+ this.schemaString,
655
+ this.input
656
+ );
657
+ }
658
+ return value;
659
+ }
660
+ }
661
+ parseUnionValue(schema) {
662
+ const savedPos = this.pos;
663
+ const errors = [];
664
+ for (let i = 0; i < schema.members.length; i++) {
665
+ this.pos = savedPos;
666
+ try {
667
+ return this.parseValue(schema.members[i], false);
668
+ } catch (e) {
669
+ errors.push(e);
670
+ }
671
+ }
672
+ throw new ParseError(
673
+ `Value does not match any union member. Tried ${schema.members.length} alternatives.`,
674
+ this.pos,
675
+ this.schemaString,
676
+ this.input
677
+ );
678
+ }
679
+ parseTupleValue(schema, allowOmitBrackets) {
680
+ let hasOpenBracket = false;
681
+ if (this.peek() === "[") {
682
+ this.consume();
683
+ hasOpenBracket = true;
684
+ } else if (!allowOmitBrackets) {
685
+ throw new ParseError(
686
+ "Expected [",
687
+ this.pos,
688
+ this.schemaString,
689
+ this.input
690
+ );
691
+ }
692
+ this.skipWhitespace();
693
+ if (this.peek() === "]" && hasOpenBracket) {
694
+ this.consume();
695
+ return [];
696
+ }
697
+ const result = [];
698
+ for (let i = 0; i < schema.elements.length; i++) {
699
+ this.skipWhitespace();
700
+ const elementSchema = schema.elements[i];
701
+ if (elementSchema.name) {
702
+ this.skipWhitespace();
703
+ const savedPos = this.pos;
704
+ if (this.consumeStr(`${elementSchema.name}:`)) {
705
+ this.skipWhitespace();
706
+ } else {
707
+ this.pos = savedPos;
708
+ }
709
+ }
710
+ result.push(this.parseValue(elementSchema.schema, false));
711
+ this.skipWhitespace();
712
+ if (i < schema.elements.length - 1) {
713
+ if (!this.consumeStr(";")) {
714
+ throw new ParseError(
715
+ "Expected ;",
716
+ this.pos,
717
+ this.schemaString,
718
+ this.input
719
+ );
720
+ }
721
+ }
722
+ }
723
+ this.skipWhitespace();
724
+ if (hasOpenBracket) {
725
+ if (!this.consumeStr("]")) {
726
+ throw new ParseError(
727
+ "Expected ]",
728
+ this.pos,
729
+ this.schemaString,
730
+ this.input
731
+ );
732
+ }
733
+ }
734
+ return result;
735
+ }
736
+ parseArrayValue(schema, allowOmitBrackets) {
737
+ let hasOpenBracket = false;
738
+ const elementIsTupleOrArray = schema.element.type === "tuple" || schema.element.type === "array";
739
+ if (this.pos >= this.input.length || !this.input.trim()) {
740
+ return [];
741
+ }
742
+ if (this.peek() === "[") {
743
+ if (!elementIsTupleOrArray) {
744
+ this.consume();
745
+ hasOpenBracket = true;
746
+ } else {
747
+ const savedPos = this.pos;
748
+ this.consume();
749
+ this.skipWhitespace();
750
+ if (this.peek() === "]") {
751
+ this.consume();
752
+ return [];
753
+ } else if (this.peek() === "[") {
754
+ hasOpenBracket = true;
755
+ } else {
756
+ this.pos = savedPos;
757
+ }
758
+ }
759
+ }
760
+ if (!hasOpenBracket && !allowOmitBrackets && !elementIsTupleOrArray) {
761
+ throw new ParseError(
762
+ "Expected [",
763
+ this.pos,
764
+ this.schemaString,
765
+ this.input
766
+ );
767
+ }
768
+ this.skipWhitespace();
769
+ if (this.peek() === "]" && hasOpenBracket) {
770
+ this.consume();
771
+ return [];
772
+ }
773
+ const result = [];
774
+ while (true) {
775
+ this.skipWhitespace();
776
+ result.push(this.parseValue(schema.element, elementIsTupleOrArray));
777
+ this.skipWhitespace();
778
+ if (!this.consumeStr(";")) {
779
+ break;
780
+ }
781
+ }
782
+ this.skipWhitespace();
783
+ if (hasOpenBracket) {
784
+ if (!this.consumeStr("]")) {
785
+ throw new ParseError(
786
+ "Expected ]",
787
+ this.pos,
788
+ this.schemaString,
789
+ this.input
790
+ );
791
+ }
792
+ }
793
+ return result;
794
+ }
795
+ parseReferenceValue(schema) {
796
+ if (schema.isOptional) {
797
+ this.skipWhitespace();
798
+ if (this.pos >= this.input.length) {
799
+ return null;
800
+ }
801
+ }
802
+ if (schema.isArray) {
803
+ let hasOpenBracket = false;
804
+ if (this.peek() === "[") {
805
+ this.consume();
806
+ hasOpenBracket = true;
807
+ }
808
+ this.skipWhitespace();
809
+ if (this.peek() === "]" && hasOpenBracket) {
810
+ this.consume();
811
+ return [];
812
+ }
813
+ const ids = [];
814
+ while (true) {
815
+ this.skipWhitespace();
816
+ let id = "";
817
+ while (this.pos < this.input.length && this.peek() !== ";" && this.peek() !== "]") {
818
+ id += this.consume();
819
+ }
820
+ ids.push(id.trim());
821
+ this.skipWhitespace();
822
+ if (!this.consumeStr(";")) {
823
+ break;
824
+ }
825
+ }
826
+ if (hasOpenBracket) {
827
+ if (!this.consumeStr("]")) {
828
+ throw new ParseError(
829
+ "Expected ]",
830
+ this.pos,
831
+ this.schemaString,
832
+ this.input
833
+ );
834
+ }
835
+ }
836
+ return ids;
837
+ } else {
838
+ let id = "";
839
+ while (this.pos < this.input.length) {
840
+ const char = this.peek();
841
+ if (char === ";" || char === "]" || char === ",") {
842
+ break;
843
+ }
844
+ id += this.consume();
845
+ }
846
+ return id.trim();
847
+ }
848
+ }
849
+ getPosition() {
850
+ return this.pos;
851
+ }
852
+ getInputLength() {
853
+ return this.input.length;
854
+ }
855
+ };
856
+ function parseValue(schema, valueString, schemaString) {
857
+ const sStr = schemaString || schemaToTypeString(schema);
858
+ const parser = new ValueParser(valueString.trim(), sStr);
859
+ const allowOmitBrackets = schema.type === "tuple" || schema.type === "array";
860
+ const value = parser.parseValue(schema, allowOmitBrackets);
861
+ if (parser.getPosition() < parser.getInputLength()) {
862
+ throw new ParseError(
863
+ "Unexpected input after value",
864
+ parser.getPosition(),
865
+ sStr,
866
+ valueString.trim()
867
+ );
868
+ }
869
+ return value;
870
+ }
871
+
872
+ // src/csv-loader/reference-resolver.ts
873
+ var fs = __toESM(require("fs"));
874
+ var path = __toESM(require("path"));
875
+ var referenceTableCache = /* @__PURE__ */ new Map();
876
+ var loadingFiles = /* @__PURE__ */ new Set();
877
+ function hasNestedReferences(schema) {
878
+ switch (schema.type) {
879
+ case "reference":
880
+ case "reverseReference":
881
+ return true;
882
+ case "tuple":
883
+ return schema.elements.some((el) => hasNestedReferences(el.schema));
884
+ case "array":
885
+ return hasNestedReferences(schema.element);
886
+ case "union":
887
+ return schema.members.some((m) => hasNestedReferences(m));
888
+ default:
889
+ return false;
890
+ }
891
+ }
892
+ function loadReferenceTable(schema, refBaseDir, defaultPrimaryKey, currentFilePath) {
893
+ const baseDir = refBaseDir || (currentFilePath ? path.dirname(currentFilePath) : process.cwd());
894
+ const fileName = `${schema.tableName}.csv`;
895
+ const refFilePath = path.isAbsolute(fileName) ? fileName : path.join(baseDir, fileName);
896
+ let refTable;
897
+ if (referenceTableCache.has(refFilePath)) {
898
+ refTable = referenceTableCache.get(refFilePath);
899
+ } else {
900
+ if (loadingFiles.has(refFilePath)) {
901
+ throw new Error(
902
+ `Circular reference detected: table "${schema.tableName}" (${refFilePath}) is already being loaded`
903
+ );
904
+ }
905
+ loadingFiles.add(refFilePath);
906
+ try {
907
+ const refContent = fs.readFileSync(refFilePath, "utf-8");
908
+ const refResult = parseCsv(refContent, {
909
+ currentFilePath: refFilePath,
910
+ emitTypes: false
911
+ });
912
+ refTable = refResult.data;
913
+ referenceTableCache.set(refFilePath, refTable);
914
+ } catch (error) {
915
+ throw new Error(
916
+ `Failed to load referenced table "${schema.tableName}" from ${refFilePath}: ${error instanceof Error ? error.message : String(error)}`
917
+ );
918
+ } finally {
919
+ loadingFiles.delete(refFilePath);
920
+ }
921
+ }
922
+ const lookup = /* @__PURE__ */ new Map();
923
+ refTable.forEach((row) => {
924
+ const pkValue = row[defaultPrimaryKey];
925
+ if (pkValue !== void 0) {
926
+ lookup.set(String(pkValue), row);
927
+ }
928
+ });
929
+ return { lookup, refTable };
930
+ }
931
+ function resolveReferenceId(id, lookup, tableName) {
932
+ const obj = lookup.get(id);
933
+ if (!obj) {
934
+ throw new Error(`Reference to "${tableName}" with id="${id}" not found`);
935
+ }
936
+ return obj;
937
+ }
938
+ function parseReferenceIds(schema, valueString) {
939
+ const trimmed = valueString.trim();
940
+ if (schema.isOptional && trimmed === "") {
941
+ return null;
942
+ }
943
+ return parseValue(schema, trimmed);
944
+ }
945
+ function parseValueWithReferenceIds(valueString, schema) {
946
+ if (!hasNestedReferences(schema)) {
947
+ return parseValue(schema, valueString);
948
+ }
949
+ switch (schema.type) {
950
+ case "reference":
951
+ return parseReferenceIds(schema, valueString);
952
+ case "reverseReference":
953
+ return null;
954
+ case "tuple": {
955
+ const parsed = parseValue(schema, valueString);
956
+ return schema.elements.map(
957
+ (el, i) => hasNestedReferences(el.schema) ? extractNestedReferenceIds(parsed[i], el.schema) : parsed[i]
958
+ );
959
+ }
960
+ case "array": {
961
+ const parsed = parseValue(schema, valueString);
962
+ return parsed.map(
963
+ (item) => hasNestedReferences(schema.element) ? extractNestedReferenceIds(item, schema.element) : item
964
+ );
965
+ }
966
+ case "union": {
967
+ for (const member of schema.members) {
968
+ if (hasNestedReferences(member)) {
969
+ try {
970
+ const parsed = parseValue(member, valueString);
971
+ return extractNestedReferenceIds(parsed, member);
972
+ } catch {
973
+ }
974
+ }
975
+ }
976
+ return parseValue(schema, valueString);
977
+ }
978
+ default:
979
+ return parseValue(schema, valueString);
980
+ }
981
+ }
982
+ function extractNestedReferenceIds(value, schema) {
983
+ switch (schema.type) {
984
+ case "reference":
985
+ if (value === null || value === void 0) return value;
986
+ if (schema.isArray) {
987
+ const ids = Array.isArray(value) ? value : [value];
988
+ return ids.map((id) => String(id));
989
+ }
990
+ return String(value);
991
+ case "reverseReference":
992
+ return null;
993
+ case "tuple": {
994
+ if (!Array.isArray(value)) return value;
995
+ return schema.elements.map(
996
+ (el, i) => hasNestedReferences(el.schema) ? extractNestedReferenceIds(value[i], el.schema) : value[i]
997
+ );
998
+ }
999
+ case "array": {
1000
+ if (!Array.isArray(value)) return value;
1001
+ return value.map(
1002
+ (item) => hasNestedReferences(schema.element) ? extractNestedReferenceIds(item, schema.element) : item
1003
+ );
1004
+ }
1005
+ case "union": {
1006
+ for (const member of schema.members) {
1007
+ if (hasNestedReferences(member)) {
1008
+ try {
1009
+ return extractNestedReferenceIds(value, member);
1010
+ } catch {
1011
+ }
1012
+ }
1013
+ }
1014
+ return value;
1015
+ }
1016
+ default:
1017
+ return value;
1018
+ }
1019
+ }
1020
+ function collectReferenceFields(schema, name) {
1021
+ const fields = [];
1022
+ switch (schema.type) {
1023
+ case "reference":
1024
+ fields.push({
1025
+ name,
1026
+ tableName: schema.tableName,
1027
+ isArray: schema.isArray,
1028
+ schema
1029
+ });
1030
+ break;
1031
+ case "reverseReference":
1032
+ fields.push({
1033
+ name,
1034
+ tableName: schema.tableName,
1035
+ isArray: true,
1036
+ foreignKey: schema.foreignKey,
1037
+ schema
1038
+ });
1039
+ break;
1040
+ case "tuple":
1041
+ for (const el of schema.elements) {
1042
+ fields.push(...collectReferenceFields(el.schema, name));
1043
+ }
1044
+ break;
1045
+ case "array":
1046
+ fields.push(...collectReferenceFields(schema.element, name));
1047
+ break;
1048
+ case "union":
1049
+ for (const member of schema.members) {
1050
+ fields.push(...collectReferenceFields(member, name));
1051
+ }
1052
+ break;
1053
+ }
1054
+ return fields;
1055
+ }
1056
+ function parseValueWithReferences(valueString, schema, refBaseDir, defaultPrimaryKey, currentFilePath, currentRowPk) {
1057
+ if (!hasNestedReferences(schema)) {
1058
+ return parseValue(schema, valueString);
1059
+ }
1060
+ switch (schema.type) {
1061
+ case "reference":
1062
+ return parseReferenceValue(
1063
+ schema,
1064
+ valueString,
1065
+ refBaseDir,
1066
+ defaultPrimaryKey,
1067
+ currentFilePath
1068
+ );
1069
+ case "reverseReference": {
1070
+ if (currentRowPk === void 0) return [];
1071
+ return resolveReverseReference(
1072
+ schema,
1073
+ currentRowPk,
1074
+ refBaseDir,
1075
+ defaultPrimaryKey,
1076
+ currentFilePath
1077
+ );
1078
+ }
1079
+ case "tuple": {
1080
+ const parsed = parseValue(schema, valueString);
1081
+ return schema.elements.map(
1082
+ (el, i) => resolveNestedReferences(
1083
+ parsed[i],
1084
+ el.schema,
1085
+ refBaseDir,
1086
+ defaultPrimaryKey,
1087
+ currentFilePath,
1088
+ currentRowPk
1089
+ )
1090
+ );
1091
+ }
1092
+ case "array": {
1093
+ const parsed = parseValue(schema, valueString);
1094
+ return parsed.map(
1095
+ (item) => resolveNestedReferences(
1096
+ item,
1097
+ schema.element,
1098
+ refBaseDir,
1099
+ defaultPrimaryKey,
1100
+ currentFilePath,
1101
+ currentRowPk
1102
+ )
1103
+ );
1104
+ }
1105
+ case "union": {
1106
+ const errors = [];
1107
+ for (const member of schema.members) {
1108
+ if (hasNestedReferences(member)) {
1109
+ try {
1110
+ const parsed = parseValue(member, valueString);
1111
+ return resolveNestedReferences(
1112
+ parsed,
1113
+ member,
1114
+ refBaseDir,
1115
+ defaultPrimaryKey,
1116
+ currentFilePath,
1117
+ currentRowPk
1118
+ );
1119
+ } catch (e) {
1120
+ errors.push(e instanceof Error ? e : new Error(String(e)));
1121
+ }
1122
+ }
1123
+ }
1124
+ if (errors.length > 0 && errors.every(
1125
+ (e) => /not found|Circular reference|Failed to load/.test(e.message)
1126
+ )) {
1127
+ for (const member of schema.members) {
1128
+ if (!hasNestedReferences(member)) {
1129
+ try {
1130
+ return parseValue(member, valueString);
1131
+ } catch {
1132
+ }
1133
+ }
1134
+ }
1135
+ }
1136
+ return parseValue(schema, valueString);
1137
+ }
1138
+ default:
1139
+ return parseValue(schema, valueString);
1140
+ }
1141
+ }
1142
+ function resolveReverseReference(schema, pkValue, refBaseDir, defaultPrimaryKey, currentFilePath) {
1143
+ const { refTable } = loadReferenceTable(
1144
+ schema,
1145
+ refBaseDir,
1146
+ defaultPrimaryKey,
1147
+ currentFilePath
1148
+ );
1149
+ const pkStr = String(pkValue);
1150
+ return refTable.filter((row) => {
1151
+ const fkValue = row[schema.foreignKey];
1152
+ const fkStr = fkValue !== null && fkValue !== void 0 && typeof fkValue === "object" ? String(fkValue[defaultPrimaryKey]) : String(fkValue);
1153
+ return fkStr === pkStr;
1154
+ });
1155
+ }
1156
+ function resolveNestedReferences(value, schema, refBaseDir, defaultPrimaryKey, currentFilePath, currentRowPk) {
1157
+ switch (schema.type) {
1158
+ case "reference": {
1159
+ if (value === null || value === void 0) return value;
1160
+ const { lookup } = loadReferenceTable(
1161
+ schema,
1162
+ refBaseDir,
1163
+ defaultPrimaryKey,
1164
+ currentFilePath
1165
+ );
1166
+ if (schema.isArray) {
1167
+ const ids = Array.isArray(value) ? value : [value];
1168
+ return ids.map(
1169
+ (id) => resolveReferenceId(String(id), lookup, schema.tableName)
1170
+ );
1171
+ }
1172
+ return resolveReferenceId(String(value), lookup, schema.tableName);
1173
+ }
1174
+ case "reverseReference": {
1175
+ if (currentRowPk === void 0) return [];
1176
+ const results = resolveReverseReference(
1177
+ schema,
1178
+ currentRowPk,
1179
+ refBaseDir,
1180
+ defaultPrimaryKey,
1181
+ currentFilePath
1182
+ );
1183
+ return results;
1184
+ }
1185
+ case "tuple": {
1186
+ if (!Array.isArray(value)) return value;
1187
+ return schema.elements.map(
1188
+ (el, i) => resolveNestedReferences(
1189
+ value[i],
1190
+ el.schema,
1191
+ refBaseDir,
1192
+ defaultPrimaryKey,
1193
+ currentFilePath,
1194
+ currentRowPk
1195
+ )
1196
+ );
1197
+ }
1198
+ case "array": {
1199
+ if (!Array.isArray(value)) return value;
1200
+ return value.map(
1201
+ (item) => resolveNestedReferences(
1202
+ item,
1203
+ schema.element,
1204
+ refBaseDir,
1205
+ defaultPrimaryKey,
1206
+ currentFilePath,
1207
+ currentRowPk
1208
+ )
1209
+ );
1210
+ }
1211
+ case "union": {
1212
+ const errors = [];
1213
+ for (const member of schema.members) {
1214
+ if (hasNestedReferences(member)) {
1215
+ try {
1216
+ return resolveNestedReferences(
1217
+ value,
1218
+ member,
1219
+ refBaseDir,
1220
+ defaultPrimaryKey,
1221
+ currentFilePath,
1222
+ currentRowPk
1223
+ );
1224
+ } catch (e) {
1225
+ errors.push(e instanceof Error ? e : new Error(String(e)));
1226
+ }
1227
+ }
1228
+ }
1229
+ if (errors.length > 0) {
1230
+ throw errors[0];
1231
+ }
1232
+ return value;
1233
+ }
1234
+ default:
1235
+ return value;
1236
+ }
1237
+ }
1238
+ function parseReferenceValue(schema, valueString, refBaseDir, defaultPrimaryKey, currentFilePath) {
1239
+ const trimmed = valueString.trim();
1240
+ if (schema.isOptional && trimmed === "") {
1241
+ return null;
1242
+ }
1243
+ const { lookup } = loadReferenceTable(
1244
+ schema,
1245
+ refBaseDir,
1246
+ defaultPrimaryKey,
1247
+ currentFilePath
1248
+ );
1249
+ const ids = parseValue(schema, trimmed);
1250
+ if (ids === null) return null;
1251
+ if (schema.isArray && Array.isArray(ids)) {
1252
+ return ids.map((id) => resolveReferenceId(id, lookup, schema.tableName));
1253
+ }
1254
+ return resolveReferenceId(ids, lookup, schema.tableName);
1255
+ }
1256
+
1257
+ // src/csv-loader/type-gen.ts
1258
+ var path2 = __toESM(require("path"));
1259
+ function resolveReferencesInSchemaString(schemaString, resourceNames) {
1260
+ return schemaString.replace(/@([a-zA-Z0-9\-_]+)(\[\])?/g, (_match, tableName, arraySuffix) => {
1261
+ const typeName = resourceNames.get(tableName) || tableName.charAt(0).toUpperCase() + tableName.slice(1);
1262
+ return arraySuffix ? `${typeName}[]` : typeName;
1263
+ }).replace(/; ?/g, ", ");
1264
+ }
1265
+ function generateTypeDefinition(resourceName, propertyConfigs, references, currentFilePath, typeDeclarations = []) {
1266
+ const typeName = resourceName ? `${resourceName}Table` : "Table";
1267
+ const currentTableName = currentFilePath ? path2.basename(currentFilePath, path2.extname(currentFilePath)) : void 0;
1268
+ const singularType = resourceName ? resourceName.charAt(0).toUpperCase() + resourceName.slice(1) : `${typeName}[number]`;
1269
+ const imports = [];
1270
+ const resourceNames = /* @__PURE__ */ new Map();
1271
+ references.forEach((tableName) => {
1272
+ if (tableName === currentTableName) {
1273
+ resourceNames.set(tableName, singularType);
1274
+ return;
1275
+ }
1276
+ const typeBase = tableName.charAt(0).toUpperCase() + tableName.slice(1);
1277
+ resourceNames.set(tableName, typeBase);
1278
+ let importPath;
1279
+ if (currentFilePath) {
1280
+ importPath = `./${tableName}.csv`;
1281
+ } else {
1282
+ importPath = `../${tableName}.csv`;
1283
+ }
1284
+ imports.push(`import type { ${typeBase} } from '${importPath}';`);
1285
+ });
1286
+ const importSection = imports.length > 0 ? imports.join("\n") + "\n\n" : "";
1287
+ const typeDeclarationSection = typeDeclarations.length > 0 ? typeDeclarations.map(
1288
+ (decl) => `export type ${decl.name} = ${decl.schemaString ? resolveReferencesInSchemaString(decl.schemaString, resourceNames) : schemaToTypeString(decl.schema, resourceNames)};`
1289
+ ).join("\n") + "\n\n" : "";
1290
+ const properties = propertyConfigs.map((config) => {
1291
+ const typeStr = config.declaredTypeName ? config.declaredTypeName : config.schemaString ? resolveReferencesInSchemaString(config.schemaString, resourceNames) : schemaToTypeString(config.schema, resourceNames);
1292
+ return ` readonly ${config.name}: ${typeStr};`;
1293
+ }).join("\n");
1294
+ let exportAlias = "";
1295
+ if (resourceName) {
1296
+ const singularType2 = resourceName.charAt(0).toUpperCase() + resourceName.slice(1);
1297
+ exportAlias = `
1298
+ export type ${singularType2} = ${typeName}[number];`;
1299
+ }
1300
+ return `${importSection}${typeDeclarationSection}type ${typeName} = readonly {
1301
+ ${properties}
1302
+ }[];
1303
+ ${exportAlias}
1304
+
1305
+ declare function getData(): ${typeName};
1306
+ export default getData;
1307
+ `;
1308
+ }
1309
+
1310
+ // src/csv-loader/type-declarations.ts
1311
+ function parseTypeDeclaration(line, commentChar = "#") {
1312
+ const trimmed = line.trim();
1313
+ if (!trimmed.startsWith(commentChar)) return null;
1314
+ const content = trimmed.slice(commentChar.length).trim();
1315
+ const match = content.match(/^type\s+([A-Z][a-zA-Z0-9]*)\s*=\s*(.+)$/);
1316
+ if (!match) return null;
1317
+ const [, typeName, schemaString] = match;
1318
+ return { typeName, schemaString };
1319
+ }
1320
+ function expandTypeName(schemaString, declaredTypes) {
1321
+ const trimmed = schemaString.trim();
1322
+ if (declaredTypes.has(trimmed)) {
1323
+ return declaredTypes.get(trimmed);
1324
+ }
1325
+ return null;
1326
+ }
1327
+ function expandSchemaString(schemaString, declaredTypes) {
1328
+ let result = schemaString;
1329
+ let prev = "";
1330
+ while (prev !== result) {
1331
+ prev = result;
1332
+ result = expandSchemaInString(result, declaredTypes);
1333
+ }
1334
+ return result;
1335
+ }
1336
+ function expandSchemaInString(schemaString, declaredTypes) {
1337
+ const expanded = expandTypeName(schemaString.trim(), declaredTypes);
1338
+ if (expanded !== null) {
1339
+ return expanded;
1340
+ }
1341
+ const trimmed = schemaString.trim();
1342
+ if (trimmed.endsWith("[]")) {
1343
+ const inner = trimmed.slice(0, -2);
1344
+ const expandedInner = expandSchemaInString(inner, declaredTypes);
1345
+ return `${expandedInner}[]`;
1346
+ }
1347
+ if (schemaString.includes("|")) {
1348
+ const parts = splitByToken(schemaString, "|");
1349
+ if (parts.length > 1) {
1350
+ const expandedParts = parts.map(
1351
+ (part) => expandSchemaInString(part.trim(), declaredTypes)
1352
+ );
1353
+ return expandedParts.join(" | ");
1354
+ }
1355
+ }
1356
+ if (schemaString.startsWith("[") && schemaString.endsWith("]")) {
1357
+ const inner = schemaString.slice(1, -1);
1358
+ if (inner.includes(";")) {
1359
+ const elements = splitByToken(inner, ";");
1360
+ const expandedElements = elements.map(
1361
+ (el) => expandSchemaInString(el.trim(), declaredTypes)
1362
+ );
1363
+ return `[${expandedElements.join("; ")}]`;
1364
+ }
1365
+ return `[${expandSchemaInString(inner, declaredTypes)}]`;
1366
+ }
1367
+ const typeNameMatch = schemaString.trim().match(/^[A-Z][a-zA-Z0-9]*$/);
1368
+ if (typeNameMatch) {
1369
+ const expanded2 = expandTypeName(schemaString.trim(), declaredTypes);
1370
+ if (expanded2 !== null) {
1371
+ return expanded2;
1372
+ }
1373
+ }
1374
+ return schemaString;
1375
+ }
1376
+ function splitByToken(str, token) {
1377
+ const result = [];
1378
+ let current = "";
1379
+ let inQuote = null;
1380
+ for (let i = 0; i < str.length; i++) {
1381
+ const char = str[i];
1382
+ if (inQuote) {
1383
+ if (char === inQuote && str[i - 1] !== "\\") {
1384
+ inQuote = null;
1385
+ }
1386
+ current += char;
1387
+ } else if (char === '"' || char === "'") {
1388
+ inQuote = char;
1389
+ current += char;
1390
+ } else if (char === token && inQuote === null) {
1391
+ result.push(current);
1392
+ current = "";
1393
+ } else {
1394
+ current += char;
1395
+ }
1396
+ }
1397
+ if (current.length > 0 || str.endsWith(token)) {
1398
+ result.push(current);
1399
+ }
1400
+ return result;
1401
+ }
1402
+ function resolveTypeReferences(schema, declaredTypes) {
1403
+ switch (schema.type) {
1404
+ case "union":
1405
+ return {
1406
+ type: "union",
1407
+ members: schema.members.map(
1408
+ (m) => resolveTypeReferences(m, declaredTypes)
1409
+ )
1410
+ };
1411
+ case "tuple":
1412
+ return {
1413
+ type: "tuple",
1414
+ elements: schema.elements.map((el) => ({
1415
+ name: el.name,
1416
+ schema: resolveTypeReferences(el.schema, declaredTypes)
1417
+ }))
1418
+ };
1419
+ case "array":
1420
+ return {
1421
+ type: "array",
1422
+ element: resolveTypeReferences(schema.element, declaredTypes)
1423
+ };
1424
+ case "reference":
1425
+ return schema;
1426
+ default:
1427
+ return schema;
1428
+ }
1429
+ }
1430
+ function parseReverseReferenceDeclaration(line, commentChar = "#") {
1431
+ const trimmed = line.trim();
1432
+ if (!trimmed.startsWith(commentChar)) return null;
1433
+ const content = trimmed.slice(commentChar.length).trim();
1434
+ const match = content.match(/^inject\s+(\w+)\s*=\s*~(\w+)\((\w+)\)(\?)?$/);
1435
+ if (!match) return null;
1436
+ const [, fieldName, tableName, foreignKey, optionalMark] = match;
1437
+ const isOptional = optionalMark === "?";
1438
+ const schema = {
1439
+ type: "reverseReference",
1440
+ tableName,
1441
+ foreignKey,
1442
+ isOptional
1443
+ };
1444
+ return {
1445
+ fieldName,
1446
+ tableName,
1447
+ foreignKey,
1448
+ isOptional,
1449
+ schema
1450
+ };
1451
+ }
1452
+
1453
+ // src/csv-loader/loader.ts
1454
+ function parseCsv(content, options = {}) {
1455
+ const delimiter = options.delimiter ?? ",";
1456
+ const quote = options.quote ?? '"';
1457
+ const escape = options.escape ?? "\\";
1458
+ const bom = options.bom ?? true;
1459
+ const comment = options.comment === false ? void 0 : options.comment ?? "#";
1460
+ const trim = options.trim ?? true;
1461
+ const emitTypes = options.emitTypes ?? true;
1462
+ const refBaseDir = options.refBaseDir;
1463
+ const defaultPrimaryKey = options.defaultPrimaryKey ?? "id";
1464
+ const reverseReferences = [];
1465
+ const typeDeclarationsRaw = [];
1466
+ let filteredContent = content;
1467
+ if (comment) {
1468
+ const lines = content.split(/\r?\n/);
1469
+ const nonCommentLines = [];
1470
+ for (const line of lines) {
1471
+ const trimmed = line.trim();
1472
+ if (trimmed.startsWith(comment)) {
1473
+ const typeDecl = parseTypeDeclaration(trimmed, comment);
1474
+ if (typeDecl) {
1475
+ typeDeclarationsRaw.push(typeDecl);
1476
+ continue;
1477
+ }
1478
+ const decl = parseReverseReferenceDeclaration(trimmed, comment);
1479
+ if (decl) {
1480
+ reverseReferences.push(decl);
1481
+ continue;
1482
+ }
1483
+ continue;
1484
+ }
1485
+ nonCommentLines.push(line);
1486
+ }
1487
+ filteredContent = nonCommentLines.join("\n");
1488
+ }
1489
+ const records = (0, import_sync.parse)(filteredContent, {
1490
+ delimiter,
1491
+ quote,
1492
+ escape,
1493
+ bom,
1494
+ comment: void 0,
1495
+ trim,
1496
+ skip_empty_lines: true,
1497
+ relax_column_count: true
1498
+ });
1499
+ const filteredRecords = records;
1500
+ if (filteredRecords.length < 2) {
1501
+ throw new Error("CSV must have at least 2 rows: headers and schemas");
1502
+ }
1503
+ const headers = filteredRecords[0];
1504
+ const schemas = filteredRecords[1];
1505
+ if (headers.length !== schemas.length) {
1506
+ throw new Error(
1507
+ `Header count (${headers.length}) does not match schema count (${schemas.length})`
1508
+ );
1509
+ }
1510
+ const dataRows = filteredRecords.slice(2);
1511
+ for (let col = 0; col < schemas.length; col++) {
1512
+ const cell = (schemas[col] ?? "").trim();
1513
+ if (comment && cell.startsWith(comment)) {
1514
+ const typeDecl = parseTypeDeclaration(cell, comment);
1515
+ if (typeDecl) {
1516
+ typeDeclarationsRaw.push(typeDecl);
1517
+ continue;
1518
+ }
1519
+ const decl = parseReverseReferenceDeclaration(cell, comment);
1520
+ if (decl) {
1521
+ reverseReferences.push(decl);
1522
+ }
1523
+ }
1524
+ }
1525
+ const declaredTypeNames = /* @__PURE__ */ new Set();
1526
+ for (const decl of typeDeclarationsRaw) {
1527
+ declaredTypeNames.add(decl.typeName);
1528
+ }
1529
+ const declaredSchemaStrings = /* @__PURE__ */ new Map();
1530
+ for (const decl of typeDeclarationsRaw) {
1531
+ declaredSchemaStrings.set(decl.typeName, decl.schemaString);
1532
+ }
1533
+ const typeDeclarationsParsed = [];
1534
+ for (const decl of typeDeclarationsRaw) {
1535
+ const expandedSchema = expandSchemaString(
1536
+ decl.schemaString,
1537
+ declaredSchemaStrings
1538
+ );
1539
+ const schema = parseSchema(expandedSchema.trim());
1540
+ typeDeclarationsParsed.push({
1541
+ name: decl.typeName,
1542
+ schema,
1543
+ schemaString: decl.schemaString
1544
+ });
1545
+ }
1546
+ const declaredTypes = /* @__PURE__ */ new Map();
1547
+ for (const decl of typeDeclarationsParsed) {
1548
+ declaredTypes.set(decl.name, decl.schema);
1549
+ }
1550
+ const typeDeclarations = [];
1551
+ for (const decl of typeDeclarationsParsed) {
1552
+ const resolvedSchema = resolveTypeReferences(decl.schema, declaredTypes);
1553
+ typeDeclarations.push({
1554
+ name: decl.name,
1555
+ schema: resolvedSchema,
1556
+ schemaString: decl.schemaString
1557
+ });
1558
+ }
1559
+ for (const decl of typeDeclarations) {
1560
+ declaredTypes.set(decl.name, decl.schema);
1561
+ }
1562
+ const resolveReferences = options.resolveReferences ?? true;
1563
+ const propertyConfigs = headers.map(
1564
+ (header, index) => {
1565
+ const schemaString = schemas[index];
1566
+ let schema;
1567
+ let declaredTypeName;
1568
+ let columnSchemaString;
1569
+ if (declaredTypes.has(schemaString)) {
1570
+ schema = declaredTypes.get(schemaString);
1571
+ declaredTypeName = schemaString;
1572
+ } else {
1573
+ const expandedSchema = expandSchemaString(
1574
+ schemaString,
1575
+ declaredSchemaStrings
1576
+ );
1577
+ schema = parseSchema(expandedSchema.trim());
1578
+ if (expandedSchema !== schemaString) {
1579
+ columnSchemaString = schemaString;
1580
+ }
1581
+ }
1582
+ const config = {
1583
+ name: header,
1584
+ schema,
1585
+ validator: createValidator(schema),
1586
+ parser: (valueString) => parseValue(schema, valueString),
1587
+ declaredTypeName,
1588
+ schemaString: columnSchemaString
1589
+ };
1590
+ if (schema.type === "reference") {
1591
+ config.isReference = true;
1592
+ config.referenceTableName = schema.tableName;
1593
+ config.referenceIsArray = schema.isArray;
1594
+ if (resolveReferences) {
1595
+ config.parser = (valueString) => {
1596
+ return parseReferenceValue(
1597
+ schema,
1598
+ valueString,
1599
+ refBaseDir,
1600
+ defaultPrimaryKey,
1601
+ options.currentFilePath
1602
+ );
1603
+ };
1604
+ } else {
1605
+ config.parser = (valueString) => {
1606
+ return parseReferenceIds(schema, valueString);
1607
+ };
1608
+ }
1609
+ } else if (hasNestedReferences(schema)) {
1610
+ config.isReference = true;
1611
+ if (resolveReferences) {
1612
+ config.parser = (valueString) => {
1613
+ return parseValueWithReferences(
1614
+ valueString,
1615
+ schema,
1616
+ refBaseDir,
1617
+ defaultPrimaryKey,
1618
+ options.currentFilePath
1619
+ );
1620
+ };
1621
+ } else {
1622
+ config.parser = (valueString) => {
1623
+ return parseValueWithReferenceIds(valueString, schema);
1624
+ };
1625
+ }
1626
+ }
1627
+ return config;
1628
+ }
1629
+ );
1630
+ for (const decl of reverseReferences) {
1631
+ const config = {
1632
+ name: decl.fieldName,
1633
+ schema: decl.schema,
1634
+ validator: createValidator(decl.schema),
1635
+ parser: (_valueString) => {
1636
+ return null;
1637
+ },
1638
+ isReference: true,
1639
+ isReverseReference: true,
1640
+ referenceTableName: decl.tableName,
1641
+ referenceIsArray: true,
1642
+ reverseReferenceForeignKey: decl.foreignKey
1643
+ };
1644
+ propertyConfigs.push(config);
1645
+ }
1646
+ const references = /* @__PURE__ */ new Set();
1647
+ function collectReferences(schema) {
1648
+ if (schema.type === "reference") {
1649
+ references.add(schema.tableName);
1650
+ } else if (schema.type === "reverseReference") {
1651
+ references.add(schema.tableName);
1652
+ } else if (schema.type === "tuple") {
1653
+ schema.elements.forEach((el) => collectReferences(el.schema));
1654
+ } else if (schema.type === "array") {
1655
+ collectReferences(schema.element);
1656
+ } else if (schema.type === "union") {
1657
+ schema.members.forEach((m) => collectReferences(m));
1658
+ }
1659
+ }
1660
+ propertyConfigs.forEach((config) => {
1661
+ if (config.isReference && config.referenceTableName) {
1662
+ references.add(config.referenceTableName);
1663
+ }
1664
+ collectReferences(config.schema);
1665
+ });
1666
+ const objects = dataRows.map((row, rowIndex) => {
1667
+ const obj = {};
1668
+ propertyConfigs.forEach((config, colIndex) => {
1669
+ if (config.isReverseReference) {
1670
+ return;
1671
+ }
1672
+ const rawValue = row[colIndex] ?? "";
1673
+ try {
1674
+ const parsed = config.parser(rawValue);
1675
+ if (!config.isReference && !config.validator(parsed)) {
1676
+ throw new Error(
1677
+ `Validation failed for property "${config.name}" at row ${rowIndex + 3}: ${rawValue}`
1678
+ );
1679
+ }
1680
+ obj[config.name] = parsed;
1681
+ } catch (error) {
1682
+ if (error instanceof Error) {
1683
+ throw new Error(
1684
+ `Failed to parse property "${config.name}" at row ${rowIndex + 3}, column ${colIndex + 1}: ${error.message}`
1685
+ );
1686
+ }
1687
+ throw error;
1688
+ }
1689
+ });
1690
+ return obj;
1691
+ });
1692
+ if (resolveReferences) {
1693
+ for (const decl of reverseReferences) {
1694
+ for (const obj of objects) {
1695
+ const pkValue = obj[defaultPrimaryKey];
1696
+ if (pkValue !== void 0) {
1697
+ const resolved = resolveReverseReference(
1698
+ decl.schema,
1699
+ pkValue,
1700
+ refBaseDir,
1701
+ defaultPrimaryKey,
1702
+ options.currentFilePath
1703
+ );
1704
+ obj[decl.fieldName] = decl.isOptional && resolved.length === 0 ? null : resolved;
1705
+ } else {
1706
+ obj[decl.fieldName] = decl.isOptional ? null : [];
1707
+ }
1708
+ }
1709
+ }
1710
+ }
1711
+ const referenceFields = [];
1712
+ if (!resolveReferences) {
1713
+ for (const config of propertyConfigs) {
1714
+ if (hasNestedReferences(config.schema)) {
1715
+ referenceFields.push(
1716
+ ...collectReferenceFields(config.schema, config.name)
1717
+ );
1718
+ }
1719
+ }
1720
+ }
1721
+ const result = {
1722
+ data: objects,
1723
+ propertyConfigs,
1724
+ references,
1725
+ referenceFields,
1726
+ reverseReferences,
1727
+ typeDeclarations
1728
+ };
1729
+ if (emitTypes) {
1730
+ result.typeDefinition = generateTypeDefinition(
1731
+ options.resourceName || "",
1732
+ propertyConfigs,
1733
+ references,
1734
+ options.currentFilePath,
1735
+ typeDeclarations
1736
+ );
1737
+ }
1738
+ return result;
1739
+ }
1740
+
1741
+ // src/csv-loader/module-gen.ts
1742
+ function generateSchemaResolutionCode(schema, valueExpr, lookupVar, pkField, reverseLookupVar) {
1743
+ switch (schema.type) {
1744
+ case "reference": {
1745
+ const lookup = lookupVar(schema.tableName);
1746
+ if (schema.isOptional) {
1747
+ if (schema.isArray) {
1748
+ return `(${valueExpr} === null || ${valueExpr} === undefined ? ${valueExpr} : (Array.isArray(${valueExpr}) ? ${valueExpr}.map(id => ${lookup}.get(String(id))) : ${lookup}.get(String(${valueExpr}))))`;
1749
+ }
1750
+ return `(${valueExpr} === null || ${valueExpr} === undefined ? ${valueExpr} : ${lookup}.get(String(${valueExpr})))`;
1751
+ }
1752
+ if (schema.isArray) {
1753
+ return `(Array.isArray(${valueExpr}) ? ${valueExpr}.map(id => ${lookup}.get(String(id))) : ${valueExpr})`;
1754
+ }
1755
+ return `${lookup}.get(String(${valueExpr}))`;
1756
+ }
1757
+ case "reverseReference": {
1758
+ if (!reverseLookupVar) return valueExpr;
1759
+ const reverseLookup = reverseLookupVar(
1760
+ schema.tableName,
1761
+ schema.foreignKey
1762
+ );
1763
+ if (schema.isOptional) {
1764
+ return `(${reverseLookup}.get(String(row.${pkField})) || null)`;
1765
+ }
1766
+ return `(${reverseLookup}.get(String(row.${pkField})) || [])`;
1767
+ }
1768
+ case "tuple": {
1769
+ const elementResolvers = schema.elements.map((el, i) => {
1770
+ if (hasNestedReferences(el.schema)) {
1771
+ return generateSchemaResolutionCode(
1772
+ el.schema,
1773
+ `${valueExpr}[${i}]`,
1774
+ lookupVar,
1775
+ pkField,
1776
+ reverseLookupVar
1777
+ );
1778
+ }
1779
+ return `${valueExpr}[${i}]`;
1780
+ });
1781
+ return `[${elementResolvers.join(", ")}]`;
1782
+ }
1783
+ case "array": {
1784
+ if (hasNestedReferences(schema.element)) {
1785
+ const itemResolve = generateSchemaResolutionCode(
1786
+ schema.element,
1787
+ "item",
1788
+ lookupVar,
1789
+ pkField,
1790
+ reverseLookupVar
1791
+ );
1792
+ return `(${valueExpr}).map(item => ${itemResolve})`;
1793
+ }
1794
+ return valueExpr;
1795
+ }
1796
+ case "union": {
1797
+ const refMembers = schema.members.filter((m) => hasNestedReferences(m));
1798
+ const nonRefMembers = schema.members.filter(
1799
+ (m) => !hasNestedReferences(m)
1800
+ );
1801
+ const resolveParts = [];
1802
+ for (const member of refMembers) {
1803
+ const resolveCode = generateSchemaResolutionCode(
1804
+ member,
1805
+ valueExpr,
1806
+ lookupVar,
1807
+ pkField,
1808
+ reverseLookupVar
1809
+ );
1810
+ resolveParts.push(resolveCode);
1811
+ }
1812
+ if (nonRefMembers.length > 0) {
1813
+ resolveParts.push(valueExpr);
1814
+ }
1815
+ if (resolveParts.length === 0) return valueExpr;
1816
+ if (resolveParts.length === 1) return resolveParts[0];
1817
+ return `(${resolveParts.join(" ?? ")})`;
1818
+ }
1819
+ default:
1820
+ return valueExpr;
1821
+ }
1822
+ }
1823
+ function csvToModule(content, options = {}) {
1824
+ const result = parseCsv(content, { ...options, resolveReferences: false });
1825
+ const hasRefs = result.referenceFields.length > 0 || result.reverseReferences.length > 0;
1826
+ const defaultPrimaryKey = options.defaultPrimaryKey ?? "id";
1827
+ const imports = [];
1828
+ const lookupInits = [];
1829
+ const lookupVarMap = /* @__PURE__ */ new Map();
1830
+ const reverseLookupInits = [];
1831
+ const reverseLookupVarMap = /* @__PURE__ */ new Map();
1832
+ const currentTableName = options.currentFilePath ? path3.basename(
1833
+ options.currentFilePath,
1834
+ path3.extname(options.currentFilePath)
1835
+ ) : void 0;
1836
+ const uniqueTables = new Set(result.referenceFields.map((f) => f.tableName));
1837
+ for (const decl of result.reverseReferences) {
1838
+ uniqueTables.add(decl.tableName);
1839
+ }
1840
+ uniqueTables.forEach((tableName) => {
1841
+ const lookupVar2 = `_${tableName}Lookup`;
1842
+ lookupVarMap.set(tableName, lookupVar2);
1843
+ if (tableName === currentTableName) {
1844
+ lookupInits.push(
1845
+ `const ${lookupVar2} = new Map(_raw.map(p => [String(p.${defaultPrimaryKey}), p]));`
1846
+ );
1847
+ } else {
1848
+ const varName = `_${tableName}`;
1849
+ imports.push(`import ${varName} from './${tableName}.csv';`);
1850
+ lookupInits.push(
1851
+ `const ${lookupVar2} = new Map(${varName}().map(p => [String(p.${defaultPrimaryKey}), p]));`
1852
+ );
1853
+ }
1854
+ });
1855
+ for (const decl of result.reverseReferences) {
1856
+ const key = `${decl.tableName}:${decl.foreignKey}`;
1857
+ if (reverseLookupVarMap.has(key)) continue;
1858
+ const revLookupVar = `_${decl.tableName}By_${decl.foreignKey}`;
1859
+ reverseLookupVarMap.set(key, revLookupVar);
1860
+ if (decl.tableName === currentTableName) {
1861
+ reverseLookupInits.push(
1862
+ `const ${revLookupVar} = new Map();`,
1863
+ `for (const r of _raw) {`,
1864
+ ` const kv = r.${decl.foreignKey};`,
1865
+ ` const k = String(typeof kv === "object" && "${defaultPrimaryKey}" in kv ? kv.${defaultPrimaryKey} : kv);`,
1866
+ ` if (!${revLookupVar}.has(k)) ${revLookupVar}.set(k, []);`,
1867
+ ` ${revLookupVar}.get(k).push(r);`,
1868
+ `}`
1869
+ );
1870
+ } else {
1871
+ const varName = `_${decl.tableName}`;
1872
+ reverseLookupInits.push(
1873
+ `const ${revLookupVar} = new Map();`,
1874
+ `for (const r of ${varName}()) {`,
1875
+ ` const kv = r.${decl.foreignKey};`,
1876
+ ` const k = String(typeof kv === "object" && "${defaultPrimaryKey}" in kv ? kv.${defaultPrimaryKey} : kv);`,
1877
+ ` if (!${revLookupVar}.has(k)) ${revLookupVar}.set(k, []);`,
1878
+ ` ${revLookupVar}.get(k).push(r);`,
1879
+ `}`
1880
+ );
1881
+ }
1882
+ }
1883
+ const lookupVar = (tableName) => lookupVarMap.get(tableName);
1884
+ const reverseLookupVar = (tableName, foreignKey) => reverseLookupVarMap.get(`${tableName}:${foreignKey}`);
1885
+ const rowResolvers = [];
1886
+ for (const config of result.propertyConfigs) {
1887
+ if (config.isReverseReference) {
1888
+ const decl = result.reverseReferences.find(
1889
+ (d) => d.fieldName === config.name
1890
+ );
1891
+ if (decl) {
1892
+ const revLookup = reverseLookupVar(decl.tableName, decl.foreignKey);
1893
+ if (decl.isOptional) {
1894
+ rowResolvers.push({
1895
+ name: config.name,
1896
+ code: `(${revLookup}.get(String(row.${defaultPrimaryKey})) || null)`
1897
+ });
1898
+ } else {
1899
+ rowResolvers.push({
1900
+ name: config.name,
1901
+ code: `(${revLookup}.get(String(row.${defaultPrimaryKey})) || [])`
1902
+ });
1903
+ }
1904
+ }
1905
+ } else if (hasNestedReferences(config.schema)) {
1906
+ const resolveCode = generateSchemaResolutionCode(
1907
+ config.schema,
1908
+ `row.${config.name}`,
1909
+ lookupVar,
1910
+ defaultPrimaryKey,
1911
+ reverseLookupVar
1912
+ );
1913
+ rowResolvers.push({ name: config.name, code: resolveCode });
1914
+ }
1915
+ }
1916
+ const rawJson = JSON.stringify(result.data, null, 2);
1917
+ const js = [
1918
+ ...imports,
1919
+ "",
1920
+ `const _raw = ${rawJson};`,
1921
+ "",
1922
+ "let _resolved = null;",
1923
+ "",
1924
+ "export default function getData() {",
1925
+ " if (_resolved) return _resolved;",
1926
+ " _resolved = _raw;",
1927
+ ...lookupInits.map((l) => ` ${l}`),
1928
+ ...reverseLookupInits.map((l) => ` ${l}`),
1929
+ ...rowResolvers.length > 0 ? [
1930
+ " _resolved = _raw.map(row => {",
1931
+ ...rowResolvers.map((r) => ` row.${r.name} = ${r.code};`),
1932
+ " return row;",
1933
+ " });"
1934
+ ] : [],
1935
+ " return _resolved;",
1936
+ "}"
1937
+ ].join("\n");
1938
+ return {
1939
+ js,
1940
+ dts: result.typeDefinition
1941
+ };
1942
+ }
1943
+
1944
+ // src/csv-loader/webpack.ts
1945
+ function csvLoader(content) {
1946
+ const options = this.getOptions();
1947
+ const emitTypes = options?.emitTypes ?? true;
1948
+ const typesOutputDir = options?.typesOutputDir ?? "";
1949
+ const writeToDisk = options?.writeToDisk ?? false;
1950
+ const fileName = path4.basename(this.resourcePath, ".csv").split(".")[0];
1951
+ const resourceName = fileName.replace(/[-_\s]+(.)?/g, (_, char) => char ? char.toUpperCase() : "").replace(/^(.)/, (_, char) => char.toUpperCase());
1952
+ const result = csvToModule(content, {
1953
+ ...options,
1954
+ resourceName,
1955
+ currentFilePath: this.resourcePath
1956
+ });
1957
+ if (emitTypes && result.dts) {
1958
+ const context = this.context || "";
1959
+ let relativePath = this.resourcePath.replace(context, "");
1960
+ if (relativePath.startsWith("\\") || relativePath.startsWith("/")) {
1961
+ relativePath = relativePath.substring(1);
1962
+ }
1963
+ relativePath = relativePath.replace(/\\/g, "/");
1964
+ const dtsFileName = `${relativePath}.d.ts`;
1965
+ const outputPath = typesOutputDir ? path4.join(typesOutputDir, dtsFileName) : dtsFileName;
1966
+ if (writeToDisk) {
1967
+ const absolutePath = path4.join(
1968
+ this.context || process.cwd(),
1969
+ typesOutputDir || "",
1970
+ dtsFileName
1971
+ );
1972
+ fs2.mkdirSync(path4.dirname(absolutePath), { recursive: true });
1973
+ fs2.writeFileSync(absolutePath, result.dts);
1974
+ } else {
1975
+ this.emitFile?.(outputPath, result.dts);
1976
+ }
1977
+ }
1978
+ return result.js;
1979
+ }