sasat 0.21.21 → 0.22.1

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,4165 @@
1
+ //#region \0rolldown/runtime.js
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let node_fs = require("node:fs");
24
+ node_fs = __toESM(node_fs, 1);
25
+ let node_path = require("node:path");
26
+ node_path = __toESM(node_path, 1);
27
+ let node_fs_promises = require("node:fs/promises");
28
+ let js_yaml = require("js-yaml");
29
+ js_yaml = __toESM(js_yaml, 1);
30
+ require("pluralize");
31
+ let typescript = require("typescript");
32
+ typescript = __toESM(typescript, 1);
33
+ let chalk = require("chalk");
34
+ chalk = __toESM(chalk, 1);
35
+ let sqlstring = require("sqlstring");
36
+ sqlstring = __toESM(sqlstring, 1);
37
+ let mysql2_promise = require("mysql2/promise");
38
+ let esbuild = require("esbuild");
39
+ //#region src/util/assignDeep.ts
40
+ const assignDeep = (base, ...objects) => {
41
+ const assign = (target, key, value) => {
42
+ if (key === "__proto__" || key === "constructor") return;
43
+ if (Array.isArray(target[key]) && Array.isArray(value)) target[key] = [...target[key], ...value];
44
+ else if (typeof target[key] === "object" && typeof value === "object") assignDeep(target[key], value);
45
+ else target[key] = value;
46
+ };
47
+ objects.forEach((obj) => {
48
+ if (typeof obj === "object") Object.entries(obj).forEach(([key, value]) => {
49
+ assign(base, key, value);
50
+ });
51
+ });
52
+ return base;
53
+ };
54
+ //#endregion
55
+ //#region src/util/fsUtil.ts
56
+ const readYmlFile = (filepath) => js_yaml.default.load((0, node_fs.readFileSync)(filepath, "utf8"));
57
+ const mkDirIfNotExist = (path) => {
58
+ if (!(0, node_fs.existsSync)(path)) (0, node_fs.mkdirSync)(path);
59
+ };
60
+ const writeFileIfNotExist = (path, data) => {
61
+ if ((0, node_fs.existsSync)(path)) return Promise.resolve();
62
+ return (0, node_fs_promises.writeFile)(path, data);
63
+ };
64
+ const writeYmlFile = (path, fileName, obj) => {
65
+ mkDirIfNotExist(path);
66
+ (0, node_fs.writeFileSync)((0, node_path.join)(path, fileName), js_yaml.default.dump(obj, {
67
+ skipInvalid: true,
68
+ noRefs: true,
69
+ sortKeys: (a, b) => {
70
+ if (b === "tableName") return 1;
71
+ if (a === "tableName") return -1;
72
+ if (a > b) return 1;
73
+ if (a < b) return -1;
74
+ return 0;
75
+ }
76
+ }));
77
+ };
78
+ const readInitialSchema = () => {
79
+ return readYmlFile((0, node_path.join)(config().migration.dir, "initialSchema.yml"));
80
+ };
81
+ const writeCurrentSchema = (schema) => {
82
+ writeYmlFile(config().migration.dir, "currentSchema.yml", schema);
83
+ };
84
+ //#endregion
85
+ //#region src/config/loader.ts
86
+ var SasatConfigLoader = class SasatConfigLoader {
87
+ static loadConfig() {
88
+ const filepath = node_path.default.join(process.cwd(), "sasat.yml");
89
+ if (!(0, node_fs.existsSync)(filepath)) return defaultConf;
90
+ return readYmlFile(filepath);
91
+ }
92
+ constructor() {
93
+ const conf = this.readValue({
94
+ ...defaultConf,
95
+ ...SasatConfigLoader.loadConfig()
96
+ });
97
+ this.conf = { ...conf };
98
+ }
99
+ getConfig() {
100
+ return this.conf;
101
+ }
102
+ readValue(value) {
103
+ if (!value) return value;
104
+ if (Array.isArray(value)) return value.map((it) => this.readValue(it));
105
+ if (typeof value === "string" && value.startsWith("$")) return process.env[value.slice(1)];
106
+ if (typeof value === "object") {
107
+ for (const key in value) if (Object.hasOwn(value, key)) value[key] = this.readValue(value[key]);
108
+ return value;
109
+ }
110
+ return value;
111
+ }
112
+ };
113
+ const defaultConf = {
114
+ db: {
115
+ host: "127.0.0.1",
116
+ port: 3306,
117
+ user: "root",
118
+ database: "sasat",
119
+ password: ""
120
+ },
121
+ migration: {
122
+ table: "__migrate__",
123
+ dir: "migrations",
124
+ out: "sasat"
125
+ },
126
+ generator: {
127
+ addJsExtToImportStatement: false,
128
+ gql: { subscription: true }
129
+ }
130
+ };
131
+ let conf;
132
+ const config = () => {
133
+ if (conf === void 0) conf = new SasatConfigLoader().getConfig();
134
+ return conf;
135
+ };
136
+ function setConfig(update) {
137
+ conf = assignDeep(config(), update);
138
+ return conf;
139
+ }
140
+ //#endregion
141
+ //#region src/generatorv2/fs/emptyDir.ts
142
+ async function emptyDir(dir) {
143
+ let items;
144
+ try {
145
+ items = await (0, node_fs_promises.readdir)(dir);
146
+ } catch {
147
+ return (0, node_fs_promises.mkdir)(dir, { mode: 511 });
148
+ }
149
+ return Promise.all(items.map((item) => (0, node_fs_promises.rm)(node_path.default.join(dir, item), {
150
+ recursive: true,
151
+ force: true
152
+ })));
153
+ }
154
+ //#endregion
155
+ //#region src/generatorv2/codegen/ts/tsFileNames.ts
156
+ const tsFileNames = {
157
+ encoder: "idEncoder",
158
+ conditions: "conditions",
159
+ middleware: "middlewares"
160
+ };
161
+ //#endregion
162
+ //#region src/migration/column/columnTypes.ts
163
+ let DBColumnTypes = /* @__PURE__ */ function(DBColumnTypes) {
164
+ DBColumnTypes["char"] = "char";
165
+ DBColumnTypes["varchar"] = "varchar";
166
+ DBColumnTypes["text"] = "text";
167
+ DBColumnTypes["tinyInt"] = "tinyint";
168
+ DBColumnTypes["smallInt"] = "smallint";
169
+ DBColumnTypes["mediumInt"] = "mediumint";
170
+ DBColumnTypes["int"] = "int";
171
+ DBColumnTypes["bigInt"] = "bigint";
172
+ DBColumnTypes["float"] = "float";
173
+ DBColumnTypes["double"] = "double";
174
+ DBColumnTypes["decimal"] = "decimal";
175
+ DBColumnTypes["year"] = "year";
176
+ DBColumnTypes["date"] = "date";
177
+ DBColumnTypes["time"] = "time";
178
+ DBColumnTypes["dateTime"] = "datetime";
179
+ DBColumnTypes["timestamp"] = "timestamp";
180
+ DBColumnTypes["boolean"] = "boolean";
181
+ return DBColumnTypes;
182
+ }({});
183
+ const columnTypeToTsType = (type) => {
184
+ switch (type) {
185
+ case "tinyint":
186
+ case "smallint":
187
+ case "mediumint":
188
+ case "int":
189
+ case "bigint":
190
+ case "float":
191
+ case "double":
192
+ case "decimal":
193
+ case "year": return "number";
194
+ case "char":
195
+ case "varchar":
196
+ case "text":
197
+ case "time":
198
+ case "date":
199
+ case "datetime":
200
+ case "timestamp": return "string";
201
+ case "boolean": return "boolean";
202
+ }
203
+ };
204
+ //#endregion
205
+ //#region src/tsg/importDeclaration.ts
206
+ var ImportDeclaration = class {
207
+ constructor(types, module) {
208
+ this.types = types;
209
+ this.module = module;
210
+ }
211
+ toString() {
212
+ const addJsExt = config().generator.addJsExtToImportStatement && this.module.startsWith(".");
213
+ return `import {${this.types.join(",")}} from "${addJsExt ? this.module + ".js" : this.module}";`;
214
+ }
215
+ };
216
+ //#endregion
217
+ //#region src/tsg/abstruct/tsCode.ts
218
+ var TsCode = class {
219
+ constructor() {
220
+ this.importDeclarations = [];
221
+ }
222
+ addImport(types, module) {
223
+ this.importDeclarations.push(new ImportDeclaration(types, module));
224
+ return this;
225
+ }
226
+ toString() {
227
+ return this.codePrefix() + this.toTsString();
228
+ }
229
+ codePrefix() {
230
+ return "";
231
+ }
232
+ mergeImport(...code) {
233
+ code.forEach((it) => {
234
+ if (it) this.importDeclarations.push(...it.importDeclarations);
235
+ });
236
+ }
237
+ };
238
+ //#endregion
239
+ //#region src/tsg/abstruct/statement.ts
240
+ var TsStatement = class extends TsCode {
241
+ constructor(..._args) {
242
+ super(..._args);
243
+ this.codeType = "statement";
244
+ }
245
+ };
246
+ //#endregion
247
+ //#region src/tsg/node/block.ts
248
+ const notNull = (v) => {
249
+ return v !== null;
250
+ };
251
+ var Block = class extends TsStatement {
252
+ constructor(...statements) {
253
+ super();
254
+ const sts = statements.filter(notNull);
255
+ this.mergeImport(...sts);
256
+ this.statements = sts;
257
+ }
258
+ toTsString() {
259
+ return `{${this.statements.map((it) => it.toString()).join("\n")}}`;
260
+ }
261
+ };
262
+ //#endregion
263
+ //#region src/tsg/abstruct/exportableDeclaration.ts
264
+ var ExportableDeclaration = class extends TsStatement {
265
+ constructor(..._args) {
266
+ super(..._args);
267
+ this.isExported = false;
268
+ }
269
+ codePrefix() {
270
+ return this.isExported ? "export " : "";
271
+ }
272
+ export() {
273
+ this.isExported = true;
274
+ return this;
275
+ }
276
+ };
277
+ //#endregion
278
+ //#region src/tsg/node/class.ts
279
+ var Class = class extends ExportableDeclaration {
280
+ constructor(name) {
281
+ super();
282
+ this.name = name;
283
+ this.properties = [];
284
+ this.methods = [];
285
+ this.isAbstract = false;
286
+ }
287
+ abstract() {
288
+ this.isAbstract = true;
289
+ return this;
290
+ }
291
+ extends(value) {
292
+ this._extends = value;
293
+ this.mergeImport(value);
294
+ return this;
295
+ }
296
+ implements(value) {
297
+ this._implements = value;
298
+ this.mergeImport(value);
299
+ return this;
300
+ }
301
+ addProperty(...properties) {
302
+ this.properties.push(...properties);
303
+ this.mergeImport(...properties);
304
+ return this;
305
+ }
306
+ addMethod(...methods) {
307
+ this.methods.push(...methods);
308
+ this.mergeImport(...methods);
309
+ return this;
310
+ }
311
+ toTsString() {
312
+ const properties = this.properties.map((it) => it.toString()).join("");
313
+ const methods = this.methods.map((it) => it.toString()).join("");
314
+ const implement = this._implements ? this._implements.toString() + " " : "";
315
+ const extend = this._extends ? this._extends.toString() + "" : "";
316
+ return (this.isAbstract ? "abstract " : "") + `class ${this.name} ${implement}${extend}{${properties}${methods}}`;
317
+ }
318
+ };
319
+ //#endregion
320
+ //#region src/tsg/node/enumDeclaration.ts
321
+ var EnumDeclaration = class extends ExportableDeclaration {
322
+ constructor(identifier, members) {
323
+ super();
324
+ this.identifier = identifier;
325
+ this.members = members;
326
+ this.mergeImport(identifier, ...members);
327
+ }
328
+ addMembers(...members) {
329
+ this.members.push(...members);
330
+ this.mergeImport(...members);
331
+ return this;
332
+ }
333
+ toTsString() {
334
+ return `enum ${this.identifier}{${this.members.map((it) => it.toString() + ",").join("")}}`;
335
+ }
336
+ };
337
+ //#endregion
338
+ //#region src/tsg/node/enumMember.ts
339
+ var EnumMember = class extends TsCode {
340
+ constructor(identifier, value) {
341
+ super();
342
+ this.identifier = identifier;
343
+ this.value = value;
344
+ this.mergeImport(identifier);
345
+ if (value) this.mergeImport(value);
346
+ }
347
+ toTsString() {
348
+ if (!this.value) return this.identifier.toString();
349
+ return this.identifier + "=" + this.value;
350
+ }
351
+ };
352
+ //#endregion
353
+ //#region src/tsg/node/expressionStatement.ts
354
+ var ExpressionStatement = class extends TsStatement {
355
+ constructor(expression) {
356
+ super();
357
+ this.expression = expression;
358
+ this.mergeImport(expression);
359
+ }
360
+ toTsString() {
361
+ return this.expression.toString() + ";";
362
+ }
363
+ };
364
+ //#endregion
365
+ //#region src/tsg/tsValueString.ts
366
+ const tsValueString = (value) => {
367
+ if (value === null) return "null";
368
+ if (value === void 0) return "undefined";
369
+ if (typeof value === "number") return "" + value;
370
+ if (typeof value === "boolean") return "" + value;
371
+ if (typeof value === "string") return `'${value.replaceAll("'", "\\'")}'`;
372
+ if (typeof value === "bigint") return "" + value;
373
+ if (typeof value === "function") return value.toString();
374
+ if (Array.isArray(value)) return `[${value.map(tsValueString).join(",")}]`;
375
+ if (typeof value === "object") return `{${Object.entries(value).map(([key, value]) => [key, tsValueString(value)]).map(([key, value]) => `${key}: ${value}`).join(",")}}`;
376
+ throw new TypeError(`tsValueString::unsupported data type ${typeof value}`);
377
+ };
378
+ //#endregion
379
+ //#region src/tsg/node/parameter.ts
380
+ var Parameter = class extends TsCode {
381
+ constructor(paramName, type) {
382
+ super();
383
+ this.paramName = paramName;
384
+ this.type = type;
385
+ this.mergeImport(type);
386
+ }
387
+ toTsString() {
388
+ if (!this.type) return this.paramName;
389
+ return `${this.paramName}: ${this.type.toString()}`;
390
+ }
391
+ static arrayToString(params) {
392
+ return params.map((it) => it.toString()).join(",");
393
+ }
394
+ };
395
+ //#endregion
396
+ //#region src/tsg/node/expressions.ts
397
+ var TsExpression = class extends TsCode {
398
+ constructor(..._args) {
399
+ super(..._args);
400
+ this._codeType = "expression";
401
+ }
402
+ toStatement() {
403
+ return new ExpressionStatement(this);
404
+ }
405
+ call(...args) {
406
+ return new CallExpression(this, ...args);
407
+ }
408
+ nonNull() {
409
+ return new NonNullExpression(this);
410
+ }
411
+ property(propertyName) {
412
+ return new PropertyAccessExpression(this, propertyName);
413
+ }
414
+ as(type) {
415
+ return new AsExpression(this, type);
416
+ }
417
+ };
418
+ var CallExpression = class extends TsExpression {
419
+ constructor(identifier, ...args) {
420
+ super();
421
+ this.identifier = identifier;
422
+ this._typeArgs = [];
423
+ this.mergeImport(identifier, ...args);
424
+ this.args = args;
425
+ }
426
+ typeArgs(...typeArgs) {
427
+ this._typeArgs = typeArgs;
428
+ this.mergeImport(...typeArgs);
429
+ return this;
430
+ }
431
+ toTsString() {
432
+ return this.identifier.toString() + (this._typeArgs.length !== 0 ? `<${this._typeArgs.map((it) => it.toString()).join(",")}>` : "") + `(${this.args.map((it) => it.toString()).join(",")})`;
433
+ }
434
+ };
435
+ var Literal = class extends TsExpression {};
436
+ var StringLiteral = class extends Literal {
437
+ constructor(value) {
438
+ super();
439
+ this.value = value;
440
+ }
441
+ toTsString() {
442
+ return tsValueString(this.value);
443
+ }
444
+ };
445
+ var NumericLiteral = class extends Literal {
446
+ constructor(value) {
447
+ super();
448
+ this.value = value;
449
+ }
450
+ toTsString() {
451
+ return this.value.toString();
452
+ }
453
+ };
454
+ var Boolean = class extends Literal {
455
+ constructor(value) {
456
+ super();
457
+ this.value = value;
458
+ }
459
+ toTsString() {
460
+ return this.value.toString();
461
+ }
462
+ };
463
+ var ArrayLiteral = class extends Literal {
464
+ constructor(literals) {
465
+ super();
466
+ this.literals = literals;
467
+ this.mergeImport(...literals);
468
+ }
469
+ toTsString() {
470
+ return `[${this.literals.map((it) => it.toString()).join(",")}]`;
471
+ }
472
+ };
473
+ var ObjectLiteral = class extends Literal {
474
+ constructor(...properties) {
475
+ super();
476
+ this.properties = [];
477
+ this.addProperties(...properties);
478
+ }
479
+ addProperties(...properties) {
480
+ this.properties.push(...properties);
481
+ this.mergeImport(...properties);
482
+ return this;
483
+ }
484
+ toTsString() {
485
+ return `{${this.properties.map((it) => it.toString()).join(",")}}`;
486
+ }
487
+ };
488
+ var ArrowFunction = class extends Literal {
489
+ constructor(params, returnType, body) {
490
+ super();
491
+ this.params = params;
492
+ this.returnType = returnType;
493
+ this.body = body;
494
+ this.mergeImport(...params, body, returnType);
495
+ }
496
+ toTsString() {
497
+ const returnType = this.returnType ? `: ${this.returnType}` : "";
498
+ return `(${Parameter.arrayToString(this.params)})${returnType} => ${this.body.toString()}`;
499
+ }
500
+ toAsync() {
501
+ return new AsyncExpression(this);
502
+ }
503
+ };
504
+ var AsyncExpression = class extends TsExpression {
505
+ constructor(expression) {
506
+ super();
507
+ this.expression = expression;
508
+ this.mergeImport(expression);
509
+ }
510
+ toTsString() {
511
+ return "async " + this.expression.toString();
512
+ }
513
+ };
514
+ var AwaitExpression = class extends TsExpression {
515
+ constructor(expression) {
516
+ super();
517
+ this.expression = expression;
518
+ this.mergeImport(expression);
519
+ }
520
+ toTsString() {
521
+ return "await " + this.expression.toString();
522
+ }
523
+ };
524
+ var BinaryExpression = class extends TsExpression {
525
+ constructor(left, operator, right) {
526
+ super();
527
+ this.left = left;
528
+ this.operator = operator;
529
+ this.right = right;
530
+ this.mergeImport(left, right);
531
+ }
532
+ toTsString() {
533
+ return this.left + this.operator + this.right;
534
+ }
535
+ };
536
+ var Identifier = class extends TsExpression {
537
+ constructor(name) {
538
+ super();
539
+ this.name = name;
540
+ }
541
+ toTsString() {
542
+ return this.name;
543
+ }
544
+ importFrom(path) {
545
+ this.addImport([this.name], path);
546
+ return this;
547
+ }
548
+ };
549
+ var NewExpression = class extends CallExpression {
550
+ toTsString() {
551
+ return "new " + super.toTsString();
552
+ }
553
+ };
554
+ var ParenthesizedExpression = class extends TsExpression {
555
+ constructor(expression) {
556
+ super();
557
+ this.expression = expression;
558
+ this.mergeImport(expression);
559
+ }
560
+ toTsString() {
561
+ return `(${this.expression})`;
562
+ }
563
+ };
564
+ var NonNullExpression = class extends TsExpression {
565
+ constructor(expression) {
566
+ super();
567
+ this.expression = expression;
568
+ this.mergeImport(expression);
569
+ }
570
+ toTsString() {
571
+ return `${this.expression}!`;
572
+ }
573
+ };
574
+ var PropertyAccessExpression = class extends TsExpression {
575
+ constructor(expression, propertyName) {
576
+ super();
577
+ this.expression = expression;
578
+ this.propertyName = propertyName;
579
+ this.mergeImport(expression);
580
+ }
581
+ toTsString() {
582
+ return `${this.expression.toString()}.${this.propertyName}`;
583
+ }
584
+ };
585
+ var AsExpression = class extends TsExpression {
586
+ constructor(expression, asType) {
587
+ super();
588
+ this.expression = expression;
589
+ this.asType = asType;
590
+ this.mergeImport(expression, asType);
591
+ }
592
+ toTsString() {
593
+ return this.expression.toString() + " as " + this.asType.toString();
594
+ }
595
+ };
596
+ var TernaryExpression = class extends TsExpression {
597
+ constructor(condition, left, right) {
598
+ super();
599
+ this.condition = condition;
600
+ this.left = left;
601
+ this.right = right;
602
+ this.mergeImport(condition, left, right);
603
+ }
604
+ toTsString() {
605
+ return `(${this.condition})?${this.left}:${this.right}`;
606
+ }
607
+ };
608
+ var SpreadElement = class extends TsExpression {
609
+ constructor(expression) {
610
+ super();
611
+ this.expression = expression;
612
+ this.mergeImport(expression);
613
+ }
614
+ toTsString() {
615
+ return `...${this.expression}`;
616
+ }
617
+ };
618
+ //#endregion
619
+ //#region src/tsg/node/extendsClause.ts
620
+ var ExtendsClause = class extends TsCode {
621
+ constructor(type) {
622
+ super();
623
+ this.type = type;
624
+ this.mergeImport(type);
625
+ }
626
+ toTsString() {
627
+ return `extends ${this.type}`;
628
+ }
629
+ };
630
+ //#endregion
631
+ //#region src/tsg/node/ifStatement.ts
632
+ var IfStatement = class extends TsStatement {
633
+ constructor(condition, statement) {
634
+ super();
635
+ this.condition = condition;
636
+ this.statement = statement;
637
+ this.mergeImport(condition, statement);
638
+ }
639
+ toTsString() {
640
+ return `if(${this.condition})${this.statement}`;
641
+ }
642
+ };
643
+ //#endregion
644
+ //#region src/tsg/node/implementsClause.ts
645
+ var ImplementsClause = class extends TsCode {
646
+ constructor(...types) {
647
+ super();
648
+ this.types = types;
649
+ this.mergeImport(...types);
650
+ }
651
+ toTsString() {
652
+ return `implements ${this.types.join(",")}`;
653
+ }
654
+ };
655
+ //#endregion
656
+ //#region src/tsg/tsUtil.ts
657
+ const TsUtil = {
658
+ readonly: (isReadonly) => isReadonly ? "readonly " : "",
659
+ questionToken: (isOptional) => isOptional ? "?" : ""
660
+ };
661
+ //#endregion
662
+ //#region src/tsg/node/propertySignature.ts
663
+ var PropertySignature = class extends TsCode {
664
+ constructor(propertyName, type, isOptional = false, isReadOnly = false) {
665
+ super();
666
+ this.propertyName = propertyName;
667
+ this.type = type;
668
+ this.isOptional = isOptional;
669
+ this.isReadOnly = isReadOnly;
670
+ this.mergeImport(type);
671
+ }
672
+ codePrefix() {
673
+ return TsUtil.readonly(this.isReadOnly);
674
+ }
675
+ toTsString() {
676
+ return `${this.propertyName}${TsUtil.questionToken(this.isOptional)}: ${this.type}`;
677
+ }
678
+ };
679
+ //#endregion
680
+ //#region src/tsg/node/interface.ts
681
+ var TsInterface = class extends ExportableDeclaration {
682
+ constructor(name) {
683
+ super();
684
+ this.name = name;
685
+ this.properties = [];
686
+ }
687
+ addProperty(propertyName, type, isOptional = false, isReadOnly = false) {
688
+ this.properties.push(new PropertySignature(propertyName, type, isOptional, isReadOnly));
689
+ return this;
690
+ }
691
+ addProperties(properties) {
692
+ this.properties.push(...properties);
693
+ this.mergeImport(...properties);
694
+ return this;
695
+ }
696
+ extends(value) {
697
+ this._extends = value;
698
+ this.mergeImport(value);
699
+ return this;
700
+ }
701
+ toTsString() {
702
+ const extend = this._extends ? this._extends.toString() + " " : "";
703
+ return `interface ${this.name} ${extend}{${this.properties.map((it) => it.toString()).join(";")}}`;
704
+ }
705
+ };
706
+ //#endregion
707
+ //#region src/tsg/node/modifier/modifiers.ts
708
+ var Modifiers = class extends TsCode {
709
+ constructor(..._args) {
710
+ super(..._args);
711
+ this._accessor = "";
712
+ this.isReadOnly = false;
713
+ this.isStatic = false;
714
+ this.isAbstract = false;
715
+ this.isAsync = false;
716
+ }
717
+ accessor(accessor) {
718
+ this._accessor = accessor;
719
+ return this;
720
+ }
721
+ private() {
722
+ return this.accessor("private");
723
+ }
724
+ protected() {
725
+ return this.accessor("protected ");
726
+ }
727
+ abstract() {
728
+ this.isAbstract = true;
729
+ return this;
730
+ }
731
+ readonly() {
732
+ this.isReadOnly = true;
733
+ return this;
734
+ }
735
+ static() {
736
+ this.isStatic = true;
737
+ return this;
738
+ }
739
+ async() {
740
+ this.isAsync = true;
741
+ return this;
742
+ }
743
+ toTsString() {
744
+ const optional = (bool, string) => bool ? string : "";
745
+ return this._accessor + " " + optional(this.isAbstract, "abstract ") + optional(this.isStatic, "static ") + optional(this.isReadOnly, "readonly ") + optional(this.isAsync, "async ");
746
+ }
747
+ };
748
+ //#endregion
749
+ //#region src/tsg/node/modifier/methodModifiers.ts
750
+ var MethodModifiers = class extends Modifiers {
751
+ private() {
752
+ return super.private();
753
+ }
754
+ protected() {
755
+ return super.protected();
756
+ }
757
+ abstract() {
758
+ return super.abstract();
759
+ }
760
+ static() {
761
+ return super.static();
762
+ }
763
+ async() {
764
+ return super.async();
765
+ }
766
+ };
767
+ //#endregion
768
+ //#region src/tsg/node/type/type.ts
769
+ const isCode = (t) => t instanceof TsCode;
770
+ const pickCode = (types) => types.filter((it) => it instanceof TsCode);
771
+ //#endregion
772
+ //#region src/tsg/node/methodDeclaration.ts
773
+ var MethodDeclaration = class extends TsCode {
774
+ constructor(methodName, params, returnType, body) {
775
+ super();
776
+ this.methodName = methodName;
777
+ this.params = params;
778
+ this.returnType = returnType;
779
+ this.body = body;
780
+ this._modifiers = new MethodModifiers();
781
+ this.mergeImport(...params, ...body);
782
+ if (isCode(returnType)) this.mergeImport(returnType);
783
+ }
784
+ modifiers(modifiers) {
785
+ this._modifiers = modifiers;
786
+ return this;
787
+ }
788
+ importFrom(from) {
789
+ this.addImport([this.methodName], from);
790
+ return this;
791
+ }
792
+ toTsString() {
793
+ const params = this.params.map((it) => it.toString()).join(",");
794
+ return this._modifiers.toString() + `${this.methodName}(${params}): ${this.returnType}{${this.body.map((it) => it.toString()).join("")}}\n`;
795
+ }
796
+ };
797
+ //#endregion
798
+ //#region src/tsg/node/modifier/propertyModifiers.ts
799
+ var PropertyModifiers = class extends Modifiers {
800
+ accessor(accessor) {
801
+ return super.accessor(accessor);
802
+ }
803
+ private() {
804
+ return super.private();
805
+ }
806
+ protected() {
807
+ return super.protected();
808
+ }
809
+ abstract() {
810
+ return super.abstract();
811
+ }
812
+ readonly() {
813
+ return super.readonly();
814
+ }
815
+ static() {
816
+ return super.static();
817
+ }
818
+ };
819
+ //#endregion
820
+ //#region src/tsg/node/propertyAssignment.ts
821
+ var PropertyAssignment = class extends TsCode {
822
+ constructor(key, value) {
823
+ super();
824
+ this.key = key;
825
+ this.value = value;
826
+ this.mergeImport(value);
827
+ }
828
+ toTsString() {
829
+ if (!this.value) return this.key;
830
+ return `${this.key}: ${this.value.toString()}`;
831
+ }
832
+ };
833
+ //#endregion
834
+ //#region src/tsg/node/propertyDeclaration.ts
835
+ var PropertyDeclaration = class extends TsCode {
836
+ constructor(propertyName, type, optional = false) {
837
+ super();
838
+ this.propertyName = propertyName;
839
+ this.type = type;
840
+ this.optional = optional;
841
+ this._modifiers = new PropertyModifiers();
842
+ this._initializer = void 0;
843
+ if (isCode(type)) this.mergeImport(type);
844
+ }
845
+ modifiers(modifiers) {
846
+ this._modifiers = modifiers;
847
+ return this;
848
+ }
849
+ initializer(initializer) {
850
+ this._initializer = initializer;
851
+ this.mergeImport(initializer);
852
+ return this;
853
+ }
854
+ toTsString() {
855
+ const initializer = this._initializer ? ` = ${this._initializer.toString()}` : "";
856
+ return this._modifiers.toString() + `${this.propertyName}${TsUtil.questionToken(this.optional)}: ${this.type}` + initializer + ";";
857
+ }
858
+ };
859
+ //#endregion
860
+ //#region src/tsg/node/returnStatement.ts
861
+ var ReturnStatement = class extends TsStatement {
862
+ constructor(expression) {
863
+ super();
864
+ this.expression = expression;
865
+ this.mergeImport(expression);
866
+ }
867
+ toTsString() {
868
+ return `return ${this.expression.toString()};`;
869
+ }
870
+ };
871
+ //#endregion
872
+ //#region src/tsg/node/spreadAssignment.ts
873
+ var SpreadAssignment = class extends TsCode {
874
+ constructor(identifier) {
875
+ super();
876
+ this.identifier = identifier;
877
+ this.mergeImport(identifier);
878
+ }
879
+ toTsString() {
880
+ return `...${this.identifier.toString()}`;
881
+ }
882
+ };
883
+ //#endregion
884
+ //#region src/tsg/node/throwStatement.ts
885
+ var ThrowStatement = class extends TsStatement {
886
+ constructor(expression) {
887
+ super();
888
+ this.expression = expression;
889
+ this.mergeImport(expression);
890
+ }
891
+ toTsString() {
892
+ return "throw " + this.expression.toString() + ";";
893
+ }
894
+ };
895
+ //#endregion
896
+ //#region src/tsg/node/type/arrayType.ts
897
+ var ArrayType = class extends TsCode {
898
+ constructor(type) {
899
+ super();
900
+ this.type = type;
901
+ if (isCode(type)) this.mergeImport(type);
902
+ }
903
+ toTsString() {
904
+ return `Array<${this.type.toString()}>`;
905
+ }
906
+ };
907
+ //#endregion
908
+ //#region src/tsg/node/type/intersectionType.ts
909
+ var IntersectionType = class extends TsCode {
910
+ constructor(...types) {
911
+ super();
912
+ this.types = types;
913
+ this.mergeImport(...types);
914
+ }
915
+ toTsString() {
916
+ return this.types.map((it) => it.toString()).join(" & ");
917
+ }
918
+ };
919
+ //#endregion
920
+ //#region src/tsg/node/type/typeAliasDeclaration.ts
921
+ var TypeAliasDeclaration = class extends ExportableDeclaration {
922
+ constructor(alias, type) {
923
+ super();
924
+ this.alias = alias;
925
+ this.type = type;
926
+ if (isCode(type)) this.mergeImport(type);
927
+ }
928
+ toTsString() {
929
+ return `type ${this.alias} = ${this.type.toString()}`;
930
+ }
931
+ };
932
+ //#endregion
933
+ //#region src/tsg/node/type/typeLiteral.ts
934
+ var TypeLiteral = class extends TsCode {
935
+ constructor(properties = []) {
936
+ super();
937
+ this.properties = properties;
938
+ this.mergeImport(...properties);
939
+ }
940
+ addProperty(propertyName, type, isOptional = false, isReadOnly = false) {
941
+ this.properties.push(new PropertySignature(propertyName, type, isOptional, isReadOnly));
942
+ return this;
943
+ }
944
+ toTsString() {
945
+ return `{${this.properties.map((it) => it.toString()).join(";")}}`;
946
+ }
947
+ };
948
+ //#endregion
949
+ //#region src/tsg/node/type/typeReference.ts
950
+ var TypeReference = class TypeReference extends TsCode {
951
+ constructor(typeName, typeArguments = []) {
952
+ super();
953
+ this.typeName = typeName;
954
+ this.typeArguments = typeArguments;
955
+ this.mergeImport(...pickCode(typeArguments));
956
+ }
957
+ importFrom(path) {
958
+ this.addImport([this.typeName], path);
959
+ return this;
960
+ }
961
+ partial() {
962
+ return new TypeReference("Partial", [this]);
963
+ }
964
+ pick(...properties) {
965
+ return new TypeReference("Pick", [this, new Identifier(properties.map((it) => `'${it}'`).join("|"))]);
966
+ }
967
+ toTsString() {
968
+ const typeArgs = this.typeArguments.length === 0 ? "" : `<${this.typeArguments.join(",")}>`;
969
+ return `${this.typeName}${typeArgs}`;
970
+ }
971
+ };
972
+ //#endregion
973
+ //#region src/tsg/node/type/unionType.ts
974
+ var UnionType = class extends TsCode {
975
+ constructor(...types) {
976
+ super();
977
+ this.types = types;
978
+ const codeTypes = types.filter((it) => isCode(it));
979
+ this.mergeImport(...codeTypes);
980
+ }
981
+ toTsString() {
982
+ return this.types.map((it) => it.toString()).join(" | ");
983
+ }
984
+ };
985
+ //#endregion
986
+ //#region src/tsg/node/variableDeclaration.ts
987
+ var VariableDeclaration = class extends ExportableDeclaration {
988
+ constructor(flag, variableName, expression, type) {
989
+ super();
990
+ this.flag = flag;
991
+ this.expression = expression;
992
+ this.type = type;
993
+ this.variableName = typeof variableName === "string" ? new Identifier(variableName) : variableName;
994
+ this.mergeImport(expression, this.variableName, type);
995
+ }
996
+ toTsString() {
997
+ const type = this.type ? ": " + this.type.toString() : "";
998
+ return `${this.flag} ${this.variableName}${type} = ${this.expression.toString()};`;
999
+ }
1000
+ };
1001
+ //#endregion
1002
+ //#region src/tsg/factory.ts
1003
+ const createFactory = (Constructor) => {
1004
+ return (...args) => new Constructor(...args);
1005
+ };
1006
+ const expressions = {
1007
+ arrowFunc: createFactory(ArrowFunction),
1008
+ async: createFactory(AsyncExpression),
1009
+ await: createFactory(AwaitExpression),
1010
+ binary: createFactory(BinaryExpression),
1011
+ call: createFactory(CallExpression),
1012
+ identifier: createFactory(Identifier),
1013
+ new: createFactory(NewExpression),
1014
+ nonNull: createFactory(NonNullExpression),
1015
+ parenthesis: createFactory(ParenthesizedExpression),
1016
+ propertyAccess: createFactory(PropertyAccessExpression),
1017
+ string: createFactory(StringLiteral),
1018
+ number: createFactory(NumericLiteral),
1019
+ boolean: createFactory(Boolean),
1020
+ array: createFactory(ArrayLiteral),
1021
+ object: createFactory(ObjectLiteral),
1022
+ as: createFactory(AsExpression),
1023
+ ternary: createFactory(TernaryExpression)
1024
+ };
1025
+ const types = {
1026
+ arrayType: createFactory(ArrayType),
1027
+ intersectionType: createFactory(IntersectionType),
1028
+ unionType: createFactory(UnionType),
1029
+ typeAlias: createFactory(TypeAliasDeclaration),
1030
+ typeLiteral: createFactory(TypeLiteral),
1031
+ typeRef: createFactory(TypeReference)
1032
+ };
1033
+ const others = {
1034
+ block: createFactory(Block),
1035
+ class: createFactory(Class),
1036
+ enum: createFactory(EnumDeclaration),
1037
+ enumMember: createFactory(EnumMember),
1038
+ ExpStatement: createFactory(ExpressionStatement),
1039
+ extends: createFactory(ExtendsClause),
1040
+ if: createFactory(IfStatement),
1041
+ implements: createFactory(ImplementsClause),
1042
+ interface: createFactory(TsInterface),
1043
+ method: createFactory(MethodDeclaration),
1044
+ parameter: createFactory(Parameter),
1045
+ propertyAssign: createFactory(PropertyAssignment),
1046
+ propertyDeclaration: createFactory(PropertyDeclaration),
1047
+ propertySignature: createFactory(PropertySignature),
1048
+ return: createFactory(ReturnStatement),
1049
+ spreadAssign: createFactory(SpreadAssignment),
1050
+ variable: createFactory(VariableDeclaration),
1051
+ methodModifiers: createFactory(MethodModifiers),
1052
+ propertyModifiers: createFactory(PropertyModifiers),
1053
+ throw: createFactory(ThrowStatement),
1054
+ spread: createFactory(SpreadElement)
1055
+ };
1056
+ const tsg = {
1057
+ ...expressions,
1058
+ ...types,
1059
+ ...others
1060
+ };
1061
+ //#endregion
1062
+ //#region src/tsg/file.ts
1063
+ var TsFile = class extends TsCode {
1064
+ constructor(...statements) {
1065
+ super();
1066
+ this.esLintDisabled = false;
1067
+ this.mergeImport(...statements);
1068
+ this.statements = statements;
1069
+ }
1070
+ toTsString() {
1071
+ const string = [...this.resolveImport(this.importDeclarations), ...this.statements].map((it) => it.toString()).join("\n");
1072
+ return (this.esLintDisabled ? "/* eslint-disable */\n" : "") + string;
1073
+ }
1074
+ resolveImport(imports) {
1075
+ const map = {};
1076
+ imports.forEach((it) => {
1077
+ if (!map[it.module]) map[it.module] = it.types;
1078
+ else map[it.module] = [...map[it.module], ...it.types];
1079
+ });
1080
+ return Object.entries(map).map(([module, types]) => new ImportDeclaration([...new Set(types)], module));
1081
+ }
1082
+ disableEsLint() {
1083
+ this.esLintDisabled = true;
1084
+ return this;
1085
+ }
1086
+ enableEsLint() {
1087
+ this.esLintDisabled = false;
1088
+ return this;
1089
+ }
1090
+ async generate() {
1091
+ return this.toString();
1092
+ }
1093
+ };
1094
+ //#endregion
1095
+ //#region src/tsg/node/type/typeKeyword.ts
1096
+ const KeywordTypeNode = {
1097
+ any: new TypeReference("any"),
1098
+ unknown: new TypeReference("unknown"),
1099
+ number: new TypeReference("number"),
1100
+ bigInt: new TypeReference("BigInt"),
1101
+ boolean: new TypeReference("boolean"),
1102
+ string: new TypeReference("string"),
1103
+ symbol: new TypeReference("Symbol"),
1104
+ this: new TypeReference("this"),
1105
+ void: new TypeReference("void"),
1106
+ undefined: new TypeReference("undefined"),
1107
+ null: new TypeReference("null"),
1108
+ never: new TypeReference("never")
1109
+ };
1110
+ //#endregion
1111
+ //#region src/generatorv2/directory.ts
1112
+ const GeneratedDirName = "__generated__";
1113
+ const EntityDirName = "entities";
1114
+ const DataSourceDirName = "dataSources";
1115
+ const relative = (from, to) => {
1116
+ const result = node_path.posix.relative(from, to);
1117
+ if (result.startsWith("../")) return result;
1118
+ return "./" + result;
1119
+ };
1120
+ const GENERATED_PATH = `/${GeneratedDirName}/`;
1121
+ const paths = {
1122
+ BASE: "/",
1123
+ GENERATED: GENERATED_PATH,
1124
+ ENTITIES: `${GENERATED_PATH}${EntityDirName}/`,
1125
+ DATA_SOURCES: `/${DataSourceDirName}/db/`,
1126
+ GENERATED_DS: `${GENERATED_PATH}${DataSourceDirName}/db/`
1127
+ };
1128
+ const resolve = (from, source, fileName) => {
1129
+ return relative(paths[from], paths[source] + fileName);
1130
+ };
1131
+ const Directory = {
1132
+ paths,
1133
+ resolve
1134
+ };
1135
+ //#endregion
1136
+ //#region src/generatorv2/codegen/ts/scripts/getEntityTypeRefs.ts
1137
+ const typeRefs = {
1138
+ entity: {
1139
+ name: (entity) => entity.name,
1140
+ dir: "ENTITIES",
1141
+ file: (entity) => entity.name
1142
+ },
1143
+ creatable: {
1144
+ name: (entity) => entity.creatableInterface(),
1145
+ dir: "ENTITIES",
1146
+ file: (entity) => entity.name
1147
+ },
1148
+ updatable: {
1149
+ name: (entity) => entity.updatable(),
1150
+ dir: "ENTITIES",
1151
+ file: (entity) => entity.name
1152
+ },
1153
+ identifiable: {
1154
+ name: (entity) => entity.identifiableInterfaceName(),
1155
+ dir: "ENTITIES",
1156
+ file: (entity) => entity.name
1157
+ },
1158
+ fields: {
1159
+ name: (entity) => entity.fieldsTypeName(),
1160
+ dir: "GENERATED",
1161
+ file: () => "fields"
1162
+ },
1163
+ withRelation: {
1164
+ name: (entity) => entity.entityWithRelationTypeName(),
1165
+ dir: "GENERATED",
1166
+ file: () => "relationMap"
1167
+ },
1168
+ result: {
1169
+ name: (entity) => entity.resultType(),
1170
+ dir: "GENERATED",
1171
+ file: () => "relationMap"
1172
+ }
1173
+ };
1174
+ const makeTypeRef = (entity, type, importFrom) => {
1175
+ const info = typeRefs[type];
1176
+ return tsg.typeRef(info.name(entity)).importFrom(Directory.resolve(importFrom, info.dir, info.file(entity)));
1177
+ };
1178
+ const makeContextTypeRef = (importFrom) => {
1179
+ return tsg.typeRef("GQLContext").importFrom(Directory.resolve(importFrom, "BASE", "context"));
1180
+ };
1181
+ //#endregion
1182
+ //#region src/generatorv2/codegen/ts/scripts/sqlValueToTsExpression.ts
1183
+ const sqlValueToTsExpression = (value) => {
1184
+ if (typeof value === "string") return tsg.string(value);
1185
+ if (typeof value === "number") return tsg.number(value);
1186
+ return tsg.identifier("null");
1187
+ };
1188
+ //#endregion
1189
+ //#region src/generatorv2/codegen/ts/generateAutoGeneratedDatasource.ts
1190
+ const DIR$2 = "GENERATED_DS";
1191
+ const generateAutoGeneratedDatasource = (node) => {
1192
+ return new TsFile(tsg.typeAlias("QueryResult", tsg.intersectionType(makeTypeRef(node.name, "withRelation", DIR$2).partial(), makeTypeRef(node.name, "identifiable", DIR$2))), tsg.class(node.name.generatedDataSourceName()).export().abstract().extends(tsg.extends(tsg.typeRef("BaseDBDataSource", [
1193
+ makeTypeRef(node.name, "entity", DIR$2),
1194
+ makeTypeRef(node.name, "identifiable", DIR$2),
1195
+ makeTypeRef(node.name, "creatable", DIR$2),
1196
+ makeTypeRef(node.name, "updatable", DIR$2),
1197
+ makeTypeRef(node.name, "fields", DIR$2),
1198
+ tsg.typeRef("QueryResult")
1199
+ ])).addImport(["BaseDBDataSource"], Directory.resolve(DIR$2, "BASE", "baseDBDataSource"))).addProperty(...makeClassProperties(node)).addMethod(makeDefaultValueMethod(node), ...makeFindMethods(node))).disableEsLint();
1200
+ };
1201
+ const makeClassProperties = (node) => {
1202
+ const ai = node.fields.find((it) => it.isAutoIncrement);
1203
+ return [
1204
+ tsg.propertyDeclaration("tableName", KeywordTypeNode.string, false).modifiers(tsg.propertyModifiers().readonly()).initializer(tsg.string(node.tableName)),
1205
+ tsg.propertyDeclaration("fields", tsg.arrayType(KeywordTypeNode.string), false).modifiers(tsg.propertyModifiers().readonly()).initializer(tsg.array(node.fields.map((it) => tsg.string(it.fieldName)))),
1206
+ tsg.propertyDeclaration("primaryKeys", tsg.arrayType(KeywordTypeNode.string), false).modifiers(tsg.propertyModifiers().readonly().protected()).initializer(tsg.array(node.identifyKeys.map((it) => tsg.string(it)))),
1207
+ tsg.propertyDeclaration("identifyFields", tsg.arrayType(KeywordTypeNode.string), false).modifiers(tsg.propertyModifiers().readonly().protected()).initializer(tsg.array(node.identifyKeys.map((it) => node.fields.find((f) => it === f.columnName).fieldName).map(tsg.string))),
1208
+ tsg.propertyDeclaration("autoIncrementColumn", tsg.unionType(KeywordTypeNode.string, KeywordTypeNode.undefined), true).modifiers(tsg.propertyModifiers().readonly().protected()).initializer(ai ? tsg.string(ai.fieldName) : tsg.identifier("undefined"))
1209
+ ];
1210
+ };
1211
+ const fieldToExpression = (node) => {
1212
+ if (node.column.defaultCurrentTimeStamp) return tsg.identifier("getCurrentDateTimeString").addImport(["getCurrentDateTimeString"], "sasat").call();
1213
+ return sqlValueToTsExpression(node.column.default);
1214
+ };
1215
+ const makeDefaultValueMethod = (node) => {
1216
+ const columns = node.fields.filter((it) => it.column.defaultCurrentTimeStamp || it.column.default !== void 0);
1217
+ const properties = columns.map((it) => {
1218
+ return tsg.propertyAssign(it.fieldName, fieldToExpression(it));
1219
+ });
1220
+ const body = tsg.return(tsg.object(...properties));
1221
+ return tsg.method("getDefaultValueString", [], columns.length !== 0 ? tsg.typeRef(node.name.name).pick(...columns.map((it) => it.fieldName)) : tsg.typeRef(node.name.name).partial(), [body]).modifiers(tsg.methodModifiers().protected());
1222
+ };
1223
+ const makeFindMethods = (node) => {
1224
+ const qExpr = tsg.identifier("qe").importFrom("sasat");
1225
+ return node.findMethods.map((it) => {
1226
+ const bve = it.params.flatMap((it) => {
1227
+ if (!it.entity) return qExpr.property("eq").call(qExpr.property("field").call(tsg.identifier("tableName"), tsg.string(it.columnName.toString())), qExpr.property("value").call(tsg.identifier(it.fieldName.toString())));
1228
+ return it.fields.map((field) => {
1229
+ return qExpr.property("eq").call(qExpr.property("field").call(tsg.identifier("tableName"), tsg.string(field.columnName)), qExpr.property("value").call(tsg.identifier(it.name).property(field.fieldName)));
1230
+ });
1231
+ });
1232
+ const body = [tsg.variable("const", "tableName", tsg.identifier("fields?.tableAlias || \"t0\"")), tsg.return(tsg.identifier(it.isArray ? "this.find" : "this.first").call(tsg.identifier("fields"), tsg.object().addProperties(tsg.spreadAssign(tsg.identifier("options")), tsg.propertyAssign("where", qExpr.property("and").call(...bve, tsg.identifier("options?").property("where")))), tsg.identifier("context")))];
1233
+ const returnType = tsg.typeRef("QueryResult");
1234
+ return tsg.method(it.name, [
1235
+ ...it.params.map((it) => tsg.parameter(it.entity ? it.name.toString() : it.fieldName, it.entity ? makeTypeRef(it.entityName, "identifiable", "GENERATED_DS") : tsg.typeRef(columnTypeToTsType(it.dbtype)))),
1236
+ tsg.parameter(`fields?`, makeTypeRef(node.name, "fields", DIR$2)),
1237
+ tsg.parameter("options?", it.isArray ? tsg.typeRef("QueryOptions").importFrom("sasat") : tsg.typeRef("Omit", [tsg.typeRef("QueryOptions").importFrom("sasat"), tsg.typeRef("\"offset\" | \"limit\" | \"sort\"")])),
1238
+ tsg.parameter("context?", makeContextTypeRef(DIR$2))
1239
+ ], tsg.typeRef("Promise", [it.isArray ? tsg.arrayType(returnType) : tsg.unionType(returnType, tsg.typeRef("null"))]), body);
1240
+ });
1241
+ };
1242
+ //#endregion
1243
+ //#region src/generatorv2/codegen/ts/generateContext.ts
1244
+ const generateContext = (root) => {
1245
+ return new TsFile(tsg.interface("BaseGQLContext").addProperties(root.contexts.map((it) => tsg.propertySignature(it.name, tsg.typeRef(columnTypeToTsType(it.dbtype))))).export()).disableEsLint();
1246
+ };
1247
+ //#endregion
1248
+ //#region src/generatorv2/codegen/ts/generateDatasource.ts
1249
+ const generateDatasource = (node) => {
1250
+ return new TsFile(tsg.class(node.name.dataSourceName()).extends(tsg.extends(tsg.typeRef(node.name.generatedDataSourceName()).importFrom(Directory.resolve("DATA_SOURCES", "GENERATED_DS", node.name.name)))).export());
1251
+ };
1252
+ //#endregion
1253
+ //#region src/generatorv2/codegen/ts/scripts/fieldToProperty.ts
1254
+ const fieldToPropertySignature = (field) => {
1255
+ const type = tsg.typeRef(columnTypeToTsType(field.dbType));
1256
+ return tsg.propertySignature(field.fieldName, field.isNullable ? tsg.unionType(type, KeywordTypeNode.null) : type, field.isNullable, true);
1257
+ };
1258
+ //#endregion
1259
+ //#region src/generatorv2/codegen/ts/generateEntity.ts
1260
+ const generateEntityFile = (node) => {
1261
+ return new TsFile(generateEntity(node), generateCreatable(node), generateUpdatable(node), generateIdentifiable(node)).disableEsLint();
1262
+ };
1263
+ const generateEntity = (node) => {
1264
+ return tsg.typeAlias(node.name.name, tsg.typeLiteral(node.fields.map(fieldToPropertySignature))).export();
1265
+ };
1266
+ const generateCreatable = (node) => {
1267
+ return tsg.typeAlias(node.name.creatableInterface(), node.creatable.fields.length === 0 ? tsg.typeRef("Record<string, never>") : tsg.typeLiteral(node.creatable.fields.map(fieldToPropertySignature))).export();
1268
+ };
1269
+ const generateUpdatable = (node) => {
1270
+ return tsg.typeAlias(node.name.updatable(), node.updateInput.fields.length === 0 ? tsg.typeRef("Record<string, never>") : tsg.typeLiteral(node.updateInput.fields.map(fieldToPropertySignature))).export();
1271
+ };
1272
+ const generateIdentifiable = (node) => {
1273
+ return tsg.typeAlias(node.name.identifiableInterfaceName(), tsg.typeLiteral(node.fields.filter((it) => it.isPrimary).map(fieldToPropertySignature))).export();
1274
+ };
1275
+ //#endregion
1276
+ //#region src/util/stringUtil.ts
1277
+ const capitalizeFirstLetter = (str) => str.slice(0, 1).toUpperCase() + str.slice(1);
1278
+ const lowercaseFirstLetter = (str) => str.slice(0, 1).toLowerCase() + str.slice(1);
1279
+ const camelize = (str) => str.replace(/(?:^\w|[A-Z]|_\w|\b\w)/g, (word, index) => index === 0 ? word.toLowerCase() : word.toUpperCase()).replace(/\s|_|-+/g, "");
1280
+ //#endregion
1281
+ //#region src/generatorv2/nodes/entityName.ts
1282
+ var EntityName = class EntityName {
1283
+ static fromTableName(tableName) {
1284
+ return new EntityName(capitalizeFirstLetter(camelize(tableName)));
1285
+ }
1286
+ constructor(name) {
1287
+ this.name = name;
1288
+ }
1289
+ toString() {
1290
+ return this.name;
1291
+ }
1292
+ creatableInterface() {
1293
+ return `${this.name}Creatable`;
1294
+ }
1295
+ updatable() {
1296
+ return `${this.name}Updatable`;
1297
+ }
1298
+ identifiableInterfaceName() {
1299
+ return `${this.name}Identifiable`;
1300
+ }
1301
+ relationTypeName() {
1302
+ return this.name + "Relations";
1303
+ }
1304
+ entityWithRelationTypeName() {
1305
+ return this.name + "WithRelations";
1306
+ }
1307
+ resultType() {
1308
+ return this.name + "Result";
1309
+ }
1310
+ fieldsTypeName() {
1311
+ return this.name + "Fields";
1312
+ }
1313
+ dataSourceName() {
1314
+ return `${this.name}DBDataSource`;
1315
+ }
1316
+ generatedDataSourceName() {
1317
+ return `Generated${this.name}DBDataSource`;
1318
+ }
1319
+ lowerCase() {
1320
+ return lowercaseFirstLetter(this.name);
1321
+ }
1322
+ createInputName() {
1323
+ return this.name + "CreateInput";
1324
+ }
1325
+ updateInputName() {
1326
+ return this.name + "UpdateInput";
1327
+ }
1328
+ identifyInputName() {
1329
+ return `${this.name}IdentifyInput`;
1330
+ }
1331
+ IDEncoderName() {
1332
+ return `${this.name}HashId`;
1333
+ }
1334
+ };
1335
+ //#endregion
1336
+ //#region src/generatorv2/codegen/ts/generateFields.ts
1337
+ const generateFields = (root) => {
1338
+ return new TsFile(...root.entities.map((it) => tsg.typeAlias(it.name.fieldsTypeName(), tsg.typeRef("Fields", [makeTypeRef(it.name, "entity", "GENERATED"), makeTypeLiteral(it)]).importFrom("sasat")).export())).disableEsLint();
1339
+ };
1340
+ const makeTypeLiteral = (entity) => {
1341
+ return tsg.typeLiteral([...entity.references.map((it) => tsg.propertySignature(`${it.fieldName}?`, tsg.typeRef(EntityName.fromTableName(it.parentTableName).fieldsTypeName()))), ...entity.referencedBy.map((it) => tsg.propertySignature(`${it.fieldName}?`, tsg.typeRef(EntityName.fromTableName(it.childTable).fieldsTypeName())))]);
1342
+ };
1343
+ //#endregion
1344
+ //#region src/runtime/util.ts
1345
+ const pick = (target, keys) => Object.fromEntries(keys.map((key) => [key, target[key]]));
1346
+ const unique = (array) => {
1347
+ const result = [];
1348
+ for (let i = 0, l = array.length; i < l; i += 1) if (!result.includes(array[i])) result.push(array[i]);
1349
+ return result;
1350
+ };
1351
+ const nonNullable = (value) => value != null;
1352
+ //#endregion
1353
+ //#region src/generatorv2/codegen/ts/scripts/ast/getExportedVariables.ts
1354
+ const { SyntaxKind: SyntaxKind$1 } = typescript.default;
1355
+ const getExportedVariables = (sourceFile) => {
1356
+ return sourceFile.statements.filter((it) => it.kind === SyntaxKind$1.VariableStatement && it.modifiers?.some((it) => it.kind === SyntaxKind$1.ExportKeyword));
1357
+ };
1358
+ //#endregion
1359
+ //#region src/generatorv2/codegen/ts/scripts/ast/isImported.ts
1360
+ const { SyntaxKind } = typescript.default;
1361
+ const isImported = (sourceFile, type, paths) => {
1362
+ return sourceFile.statements.filter((it) => it.kind === SyntaxKind.ImportDeclaration).some((it) => {
1363
+ if (!paths.some((path) => {
1364
+ const text = it.moduleSpecifier.getText(sourceFile);
1365
+ return `'${path}'` === text || `"${path}"` === text;
1366
+ })) return false;
1367
+ const binding = it.importClause?.namedBindings;
1368
+ if (it.importClause?.name?.getText(sourceFile) === type) return true;
1369
+ if (binding?.kind !== SyntaxKind.NamedImports) return false;
1370
+ return binding.elements.some((it) => {
1371
+ return it.name.text.trim() === type;
1372
+ });
1373
+ });
1374
+ };
1375
+ //#endregion
1376
+ //#region src/generatorv2/codegen/ts/generateIDEncoder.ts
1377
+ const { createSourceFile: createSourceFile$2, ScriptTarget: ScriptTarget$2 } = typescript.default;
1378
+ const hashIds = "HashIds";
1379
+ const generateIDEncoder = (root, content) => {
1380
+ const fields = root.entities.map((it) => it.fields.find((it) => it.column.option.autoIncrementHashId)).filter(nonNullable);
1381
+ if (fields.length === 0) return null;
1382
+ const sourceFile = createSourceFile$2(tsFileNames.encoder + ".ts", content, ScriptTarget$2.ESNext);
1383
+ sourceFile.getChildren().map((it) => it);
1384
+ const exportedVariables = getExportedVariables(sourceFile);
1385
+ const hashIdImported = isImported(sourceFile, hashIds, ["hashids"]);
1386
+ const statements = [];
1387
+ fields.forEach((field) => {
1388
+ const name = field.entity.name.IDEncoderName();
1389
+ if (exportedVariables.some((it) => {
1390
+ return it.declarationList.declarations[0].name.getText(sourceFile) === name;
1391
+ })) return;
1392
+ statements.push(tsg.variable("const", name, tsg.identifier("makeNumberIdEncoder").call(tsg.new(tsg.identifier(hashIds), tsg.string(field.column.option.hashSalt || field.entity.name.name)))).export());
1393
+ });
1394
+ const imports = hashIdImported ? "" : "import HashIds from \"hashids\";\n";
1395
+ const makeEncoder = isImported(sourceFile, "makeNumberIdEncoder", ["sasat"]) ? "" : new ImportDeclaration(["makeNumberIdEncoder"], "sasat").toString();
1396
+ const addition = statements.length === 0 ? "" : "\n" + new TsFile(...statements).toString();
1397
+ return imports + makeEncoder + content + addition;
1398
+ };
1399
+ //#endregion
1400
+ //#region src/generatorv2/codegen/ts/generateMiddlewares.ts
1401
+ const { createSourceFile: createSourceFile$1, ScriptTarget: ScriptTarget$1 } = typescript.default;
1402
+ const generateMiddlewares = (root, content) => {
1403
+ const middlewares = unique(root.entities.flatMap((it) => [...it.queries.flatMap((it) => it.middlewares), ...it.mutations.flatMap((it) => it.middlewares)]));
1404
+ if (middlewares.length === 0) return null;
1405
+ const sourceFile = createSourceFile$1(tsFileNames.middleware + ".ts", content, ScriptTarget$1.ESNext);
1406
+ const exportedVariables = getExportedVariables(sourceFile);
1407
+ const statements = [];
1408
+ middlewares.forEach((middleware) => {
1409
+ if (exportedVariables.some((it) => {
1410
+ return it.declarationList.declarations[0].name.getText(sourceFile) === middleware;
1411
+ })) return;
1412
+ statements.push(tsg.variable("const", middleware, tsg.arrowFunc([tsg.parameter("args")], void 0, tsg.block(tsg.throw(tsg.new(tsg.identifier("Error"), tsg.string("TODO: Not implemented"))), tsg.return(tsg.identifier("args")))), tsg.typeRef("ResolverMiddleware", [tsg.typeRef("GQLContext")])).export());
1413
+ });
1414
+ const contextImported = isImported(sourceFile, "GQLContext", ["./context", "./context.js"]);
1415
+ const resolverMiddlewareImported = isImported(sourceFile, "ResolverMiddleware", ["sasat"]);
1416
+ const imports = [contextImported ? "" : new ImportDeclaration(["GQLContext"], "./context").toString() + "\n", resolverMiddlewareImported ? "" : new ImportDeclaration(["ResolverMiddleware"], "sasat").toString() + "\n"].join("");
1417
+ const addition = statements.length === 0 ? "" : "\n" + new TsFile(...statements).toString();
1418
+ return imports + content + addition;
1419
+ };
1420
+ //#endregion
1421
+ //#region src/generatorv2/codegen/names.ts
1422
+ const map = {
1423
+ create: "Created",
1424
+ update: "Updated",
1425
+ delete: "Deleted"
1426
+ };
1427
+ const publishFunctionName = (entityName, type) => {
1428
+ return `publish${entityName}${map[type]}`;
1429
+ };
1430
+ const makeFindQueryName = (keys) => "findBy" + keys.map(capitalizeFirstLetter).join("And");
1431
+ //#endregion
1432
+ //#region src/generatorv2/codegen/ts/mutation/makeMutationInputDecoder.ts
1433
+ const DIR$1 = "GENERATED";
1434
+ const makeMutationMiddlewareAndTypes = (entity) => {
1435
+ return entity.mutations.map((node) => makeMutationResolverMiddleware(entity, node));
1436
+ };
1437
+ const makeParamType = (node) => {
1438
+ if (node.mutationType === "create") return makeTypeRef(node.entityName, "creatable", "GENERATED");
1439
+ if (node.mutationType === "update") return tsg.intersectionType(makeTypeRef(node.entityName, "identifiable", "GENERATED"), makeTypeRef(node.entityName, "updatable", "GENERATED"));
1440
+ return makeTypeRef(node.entityName, "identifiable", "GENERATED");
1441
+ };
1442
+ const makeEncoder = (name) => tsg.identifier(name).importFrom(Directory.resolve(DIR$1, "BASE", tsFileNames.encoder));
1443
+ const makeIdDecodeMiddleware = (fields, node) => {
1444
+ const params = tsg.identifier("args[1]");
1445
+ const entityName = node.entity.name.lowerCase();
1446
+ return tsg.arrowFunc([tsg.parameter("args")], void 0, tsg.block(tsg.binary(params, "=", tsg.object(tsg.spreadAssign(params), tsg.propertyAssign(entityName, tsg.object(tsg.spreadAssign(params.property(entityName)), ...fields.filter((it) => it.hashId).map((it) => tsg.propertyAssign(it.fieldName, makeEncoder(it.hashId.encoder).property("decode").call(params.property(entityName).property(it.fieldName).as(tsg.typeRef("string"))))))))).toStatement(), tsg.return(tsg.identifier("args"))));
1447
+ };
1448
+ const makeResolverMiddleware = (typeName, entity, fields, node) => {
1449
+ const sig = fields.map((it) => tsg.propertySignature(it.fieldName, tsg.typeRef(it.hashId ? "string" : columnTypeToTsType(it.dbType))));
1450
+ const requiredType = tsg.typeAlias(typeName, tsg.typeLiteral([tsg.propertySignature(entity.name.lowerCase(), makeParamType(node))]));
1451
+ const middlewareName = node.mutationName + "Middleware";
1452
+ if (!node.requireIdDecodeMiddleware) return [requiredType, tsg.variable("const", middlewareName, tsg.array(node.middlewares.map((it) => tsg.identifier(it).importFrom("../" + tsFileNames.middleware))), tsg.arrayType(tsg.typeRef("ResolverMiddleware", [makeContextTypeRef(DIR$1), tsg.identifier(typeName)]).importFrom("sasat")))];
1453
+ return [
1454
+ tsg.typeAlias("GQL" + typeName, tsg.typeLiteral([tsg.propertySignature(entity.name.lowerCase(), tsg.typeLiteral(sig))])),
1455
+ requiredType,
1456
+ tsg.variable("const", node.mutationName + "Middleware", tsg.array([makeIdDecodeMiddleware(fields, node), ...node.middlewares.map((it) => tsg.identifier(it).importFrom("../" + tsFileNames.middleware))]), tsg.arrayType(tsg.typeRef("ResolverMiddleware", [
1457
+ makeContextTypeRef(DIR$1),
1458
+ tsg.identifier(typeName),
1459
+ tsg.identifier("GQL" + typeName)
1460
+ ]).importFrom("sasat")))
1461
+ ];
1462
+ };
1463
+ const makeMutationResolverMiddleware = (entity, node) => {
1464
+ switch (node.mutationType) {
1465
+ case "create": return makeResolverMiddleware(entity.name.createInputName(), entity, entity.creatable.fields, node);
1466
+ case "update": return makeResolverMiddleware(entity.name.updateInputName(), entity, entity.updateInput.fields, node);
1467
+ case "delete": return makeResolverMiddleware(entity.name.identifyInputName(), entity, entity.identifyFields(), node);
1468
+ }
1469
+ };
1470
+ //#endregion
1471
+ //#region src/generatorv2/codegen/ts/scripts/makeDatasource.ts
1472
+ const makeDatasource = (entity, importFrom, args) => {
1473
+ return tsg.new(tsg.identifier(entity.dataSourceName()).importFrom(Directory.resolve(importFrom, "DATA_SOURCES", entity.name)), ...args || []);
1474
+ };
1475
+ //#endregion
1476
+ //#region src/generatorv2/codegen/ts/generateMutationResolver.ts
1477
+ const generateMutationResolver = (root) => {
1478
+ return new TsFile(...root.entities.flatMap(makeMutationMiddlewareAndTypes).flat(), tsg.variable("const", "mutation", tsg.object(...root.entities.flatMap((it) => it.mutations).map(makeMutation$1))).export()).disableEsLint();
1479
+ };
1480
+ const result = tsg.identifier("result");
1481
+ const refetched = tsg.identifier("fetched");
1482
+ const ds = tsg.identifier("ds");
1483
+ const ident = tsg.identifier("identifiable");
1484
+ const makeMutation$1 = (node) => {
1485
+ return tsg.propertyAssign(node.mutationName, makeResolver$1.call(tsg.arrowFunc(makeResolverArgs(node), void 0, makeMutationBody(node)).toAsync(), tsg.identifier(node.mutationName + "Middleware")).typeArgs(...[
1486
+ context,
1487
+ tsg.typeRef(node.inputName),
1488
+ node.requireIdDecodeMiddleware ? tsg.typeRef("GQL" + node.inputName) : null
1489
+ ].filter(nonNullable)));
1490
+ };
1491
+ const makeMutationBody = (node) => {
1492
+ if (node.mutationType === "create") return makeCreateMutationBody(node);
1493
+ if (node.mutationType === "update") return makeUpdateMutationBody(node);
1494
+ return makeDeleteMutationBody(node);
1495
+ };
1496
+ const makeResolver$1 = tsg.identifier("makeResolver").importFrom("sasat");
1497
+ const context = tsg.typeRef("GQLContext").importFrom(Directory.resolve("GENERATED", "BASE", "context"));
1498
+ const makeResolverArgs = (node) => [
1499
+ tsg.parameter("_"),
1500
+ tsg.parameter(`{${node.entityName.lowerCase()}}`),
1501
+ node.contextFields.length === 0 ? null : tsg.parameter("context")
1502
+ ].filter(nonNullable);
1503
+ const makeCreateMutationBody = (node) => {
1504
+ const entity = tsg.identifier(node.entityName.lowerCase());
1505
+ const dsVariable = tsg.variable("const", ds, makeDatasource(node.entityName, "GENERATED"));
1506
+ const createCall = ds.property("create").call(entity);
1507
+ if (!node.subscription && !node.refetch) return tsg.block(dsVariable, tsg.return(createCall));
1508
+ if (!node.refetch) return tsg.block(dsVariable, tsg.variable("const", result, tsg.await(createCall)), node.subscription ? makePublishCall(node, result) : null, tsg.return(result));
1509
+ return tsg.block(dsVariable, tsg.variable("const", result, tsg.await(createCall)), ...makeRefetched(node), node.subscription ? makePublishCall(node, refetched) : null, tsg.return(refetched));
1510
+ };
1511
+ const makeRefetched = (node) => {
1512
+ return [tsg.variable("const", ident, tsg.identifier("pick").importFrom("sasat").call(node.mutationType === "create" ? result : tsg.identifier(node.entityName.lowerCase()), tsg.array(node.identifyFields.map(tsg.string))).as(tsg.typeRef("unknown")).as(makeTypeRef(node.entityName, "identifiable", "GENERATED"))), tsg.variable("const", refetched, tsg.await(ds.property(makeFindQueryName(node.identifyFields)).call(...node.identifyFields.map((it) => ident.property(it)))))];
1513
+ };
1514
+ const makePublishCall = (node, identifier) => {
1515
+ return tsg.await(tsg.identifier(publishFunctionName(node.entityName, node.mutationType)).importFrom("./subscription").call(identifier.as(makeTypeRef(node.entityName, "entity", "GENERATED")))).toStatement();
1516
+ };
1517
+ const makeDatasourceParam = (entity, contextParams) => {
1518
+ if (contextParams.length === 0) return entity;
1519
+ return tsg.object(tsg.spreadAssign(entity), ...contextParams.map((it) => tsg.propertyAssign(it.fieldName, tsg.identifier(`context.${it.contextName}`))));
1520
+ };
1521
+ const makeUpdateMutationBody = (node) => {
1522
+ const entity = tsg.identifier(node.entityName.lowerCase());
1523
+ const statements = [tsg.variable("const", ds, makeDatasource(node.entityName, "GENERATED")), tsg.variable("const", result, tsg.await(ds.property("update").call(makeDatasourceParam(entity, node.contextFields)).property("then").call(tsg.arrowFunc([tsg.parameter("it", tsg.typeRef("CommandResponse").importFrom("sasat"))], KeywordTypeNode.boolean, tsg.binary(tsg.identifier("it.changedRows"), "===", tsg.number(1))))))];
1524
+ if (!node.refetch && !node.subscription) return tsg.block(...statements, tsg.return(result));
1525
+ return tsg.block(...statements, ...makeRefetched(node), node.subscription ? makePublishCall(node, refetched) : null, tsg.return(node.refetch ? refetched : result));
1526
+ };
1527
+ const makeDeleteMutationBody = (node) => {
1528
+ const entity = tsg.identifier(node.entityName.lowerCase());
1529
+ const dsV = tsg.variable("const", ds, makeDatasource(node.entityName, "GENERATED"));
1530
+ const deleteCall = ds.property("delete").call(entity).property("then").call(tsg.arrowFunc([tsg.parameter("it", tsg.typeRef("CommandResponse").importFrom("sasat"))], KeywordTypeNode.boolean, tsg.binary(tsg.identifier("it.affectedRows"), "===", new NumericLiteral(1))));
1531
+ return tsg.block(dsV, tsg.variable("const", result, tsg.await(deleteCall)), node.subscription ? tsg.if(result, tsg.block(makePublishCall(node, entity))) : null, tsg.return(result));
1532
+ };
1533
+ //#endregion
1534
+ //#region src/cli/console.ts
1535
+ const Console = {
1536
+ success: (msg) => {
1537
+ console.log(chalk.default.green(msg));
1538
+ },
1539
+ error: (msg) => {
1540
+ console.error(chalk.default.bold.red(msg));
1541
+ },
1542
+ log: (msg) => {
1543
+ console.log(msg);
1544
+ },
1545
+ debug: (msg) => {
1546
+ console.debug("debug:: " + msg);
1547
+ }
1548
+ };
1549
+ //#endregion
1550
+ //#region src/migration/data/GQLOption.ts
1551
+ const defaultGQLOption = () => ({
1552
+ enabled: false,
1553
+ queries: [],
1554
+ mutations: []
1555
+ });
1556
+ const getArgs = (query, entity) => {
1557
+ if (query.type === "primary") return entity.fields.filter((it) => it.isPrimary).map((it) => ({
1558
+ kind: "arg",
1559
+ name: it.fieldName,
1560
+ type: it.gqlType
1561
+ }));
1562
+ const r = [];
1563
+ if (query.type === "list-paging") r.push({
1564
+ kind: "arg",
1565
+ name: "option",
1566
+ type: "PagingOption"
1567
+ });
1568
+ query.conditions.forEach((it) => {
1569
+ if (it.left.kind === "arg") r.push(it.left);
1570
+ if (it.kind === "between") {
1571
+ if (it.begin.kind === "arg") r.push(it.begin);
1572
+ if (it.end.kind === "arg") r.push(it.end);
1573
+ } else if (it.right.kind === "arg") r.push(it.right);
1574
+ });
1575
+ return r;
1576
+ };
1577
+ //#endregion
1578
+ //#region src/tsg/node/rawCodeStatement.ts
1579
+ var RawCodeStatement = class extends TsStatement {
1580
+ constructor(code) {
1581
+ super();
1582
+ this.code = code;
1583
+ }
1584
+ toTsString() {
1585
+ return this.code;
1586
+ }
1587
+ };
1588
+ //#endregion
1589
+ //#region src/generatorv2/scripts/gqlTypes.ts
1590
+ const toTsType = (type) => {
1591
+ switch (type) {
1592
+ case "Int":
1593
+ case "Float": return "number";
1594
+ case "ID":
1595
+ case "String": return "string";
1596
+ case "Boolean": return "boolean";
1597
+ default: return type;
1598
+ }
1599
+ };
1600
+ //#endregion
1601
+ //#region src/generatorv2/codegen/ts/scripts/makeConditonValueExpr.ts
1602
+ const qExpr$3 = tsg.identifier("qe").importFrom("sasat");
1603
+ const makeConditionValueRaw = (cv) => {
1604
+ const context = tsg.identifier("arg").property("context?");
1605
+ switch (cv.kind) {
1606
+ case "context": {
1607
+ const value = context.property(cv.field);
1608
+ if (cv.onNotDefined.action !== "defaultValue") return value;
1609
+ return tsg.binary(context.property(cv.field), "||", typeof cv.onNotDefined.value === "string" ? tsg.string(cv.onNotDefined.value) : tsg.number(cv.onNotDefined.value));
1610
+ }
1611
+ case "fixed": return typeof cv.value === "string" ? tsg.string(cv.value) : tsg.number(cv.value);
1612
+ case "today": return tsg.identifier(cv.type === "datetime" ? "getTodayDateTimeString" : "getTodayDateString").importFrom("sasat").call();
1613
+ case "now": return tsg.identifier("dateString").importFrom("sasat").call(tsg.new(tsg.identifier("Date")));
1614
+ default: throw Error(`not implemented: makeConditionValue.${cv.kind}`);
1615
+ }
1616
+ };
1617
+ const makeConditionValueQExpr = (cv) => {
1618
+ const context = tsg.identifier("arg").property("context?");
1619
+ switch (cv.kind) {
1620
+ case "context": {
1621
+ const value = context.property(cv.field);
1622
+ if (cv.onNotDefined.action !== "defaultValue") return qExpr$3.property("value").call(value);
1623
+ return qExpr$3.property("value").call(tsg.binary(context.property(cv.field), "||", typeof cv.onNotDefined.value === "string" ? tsg.string(cv.onNotDefined.value) : tsg.number(cv.onNotDefined.value)));
1624
+ }
1625
+ case "fixed": return qExpr$3.property("value").call(typeof cv.value === "string" ? tsg.string(cv.value) : tsg.number(cv.value));
1626
+ case "today": return qExpr$3.property("value").call(tsg.identifier(cv.type === "datetime" ? "getTodayDateTimeString" : "getTodayDateString").importFrom("sasat").call());
1627
+ case "now": return qExpr$3.property("value").call(tsg.identifier("dateString").importFrom("sasat").call(tsg.new(tsg.identifier("Date"))));
1628
+ case "arg": return qExpr$3.property("value").call(tsg.identifier(cv.name));
1629
+ case "field": return qExpr$3.property("field").call(tsg.string("t0"), tsg.string(cv.column));
1630
+ }
1631
+ };
1632
+ //#endregion
1633
+ //#region src/generatorv2/codegen/ts/scripts/makeQueryConditionExpr.ts
1634
+ const qExpr$2 = tsg.identifier("qe").importFrom("sasat");
1635
+ const makeQueryConditionExpr = (condition) => {
1636
+ if (condition.kind === "between") return qExpr$2.property("between").call(makeConditionValueQExpr(condition.left), makeConditionValueQExpr(condition.begin), makeConditionValueQExpr(condition.end));
1637
+ return qExpr$2.property("comparison").call(makeConditionValueQExpr(condition.left), tsg.string(condition.operator), makeConditionValueQExpr(condition.right));
1638
+ };
1639
+ //#endregion
1640
+ //#region src/generatorv2/codegen/ts/generateQueryResolver.ts
1641
+ const DIR = "GENERATED";
1642
+ const generateQueryResolver = (root) => {
1643
+ return new TsFile(tsg.variable("const", "query", tsg.object(...root.entities.flatMap((entity) => entity.queries.map((query) => makeGQLQuery(entity, query))).filter(nonNullable))).export()).disableEsLint();
1644
+ };
1645
+ const makeResolver = () => tsg.identifier("makeResolver").importFrom("sasat");
1646
+ const makeGQLQuery = (entity, query) => {
1647
+ if (!entity.gqlEnabled) {
1648
+ Console.log(`Query.${query.name || entity.name.lowerCase()} generation skipped. Reason: Entity:${entity.name.name} is not Open to GQL.`);
1649
+ return null;
1650
+ }
1651
+ const args = getArgs(query, entity);
1652
+ return tsg.propertyAssign(query.type === "primary" ? entity.name.lowerCase() : query.name, makeResolver().call(...[tsg.arrowFunc([
1653
+ tsg.parameter("_"),
1654
+ tsg.parameter(`{${args.map((it) => it.name).join(",")}}`),
1655
+ tsg.parameter("context"),
1656
+ tsg.parameter("info")
1657
+ ], void 0, makeGQLQueryBody(entity, query)).toAsync(), makeMiddlewares(entity, query)].filter(nonNullable)).typeArgs(...makeTypeArgs(args)));
1658
+ };
1659
+ const getHashIdArgs = (entity, query) => {
1660
+ if (query.type === "primary") {
1661
+ const hashIDs = entity.identifyFields().filter((it) => it.option.autoIncrementHashId);
1662
+ if (hashIDs.length === 0) return null;
1663
+ return hashIDs.map((it) => ({
1664
+ encoder: it.hashId.encoder,
1665
+ name: it.fieldName
1666
+ }));
1667
+ }
1668
+ const getHashIdArg = (arg, field) => {
1669
+ const columnName = field.column;
1670
+ const hashIdOpt = entity.fields.find((e) => e.columnName === columnName)?.hashId;
1671
+ if (!hashIdOpt) return null;
1672
+ return {
1673
+ name: arg.name,
1674
+ encoder: hashIdOpt.encoder
1675
+ };
1676
+ };
1677
+ return query.conditions.map((it) => {
1678
+ if (it.kind === "comparison") {
1679
+ if (it.left.kind === "arg") {
1680
+ if (it.right.kind === "field") return getHashIdArg(it.left, it.right);
1681
+ }
1682
+ if (it.right.kind === "arg") {
1683
+ if (it.left.kind === "field") return getHashIdArg(it.right, it.left);
1684
+ }
1685
+ }
1686
+ return null;
1687
+ }).filter(nonNullable);
1688
+ };
1689
+ const makeHashIdMiddleware = (entity, query) => {
1690
+ const args = getHashIdArgs(entity, query);
1691
+ if (!args || args?.length === 0) return null;
1692
+ return tsg.arrowFunc([tsg.parameter("args")], void 0, tsg.block(new RawCodeStatement(`args[1] = {...args[1], ${args.map((it) => `${it.name}: ${it.encoder}.decode(args[1].${it.name} as string),`).join("")}};`).addImport(args.map((it) => it.encoder), Directory.resolve(DIR, "BASE", tsFileNames.encoder)), tsg.return(tsg.identifier("args"))));
1693
+ };
1694
+ const makeMiddlewares = (entity, query) => {
1695
+ const hashId = makeHashIdMiddleware(entity, query);
1696
+ if (!hashId && query.middlewares.length === 0) return null;
1697
+ if (query.middlewares.length === 0) return tsg.array([hashId]);
1698
+ const middlewares = query.middlewares.map((it) => tsg.identifier(it).importFrom("../" + tsFileNames.middleware));
1699
+ if (!hashId) return tsg.array(middlewares);
1700
+ return tsg.array([hashId, ...middlewares]);
1701
+ };
1702
+ const makeTypeArgs = (args) => {
1703
+ let hashIds = false;
1704
+ const getType = (arg, checkHashId) => {
1705
+ if (arg.type === "PagingOption") return tsg.typeRef(arg.type).importFrom("sasat");
1706
+ if (checkHashId && arg.type === "ID") {
1707
+ hashIds = true;
1708
+ return tsg.typeRef("number");
1709
+ }
1710
+ return tsg.typeRef(toTsType(arg.type));
1711
+ };
1712
+ const params = tsg.typeLiteral(args.map((it) => tsg.propertySignature(it.name, getType(it, true))));
1713
+ if (!hashIds) return [makeContextTypeRef("GENERATED"), params];
1714
+ return [
1715
+ makeContextTypeRef("GENERATED"),
1716
+ params,
1717
+ tsg.typeLiteral(args.map((it) => tsg.propertySignature(it.name, getType(it, false))))
1718
+ ];
1719
+ };
1720
+ const qExpr$1 = tsg.identifier("qe").importFrom("sasat");
1721
+ const makeGQLQueryBody = (entity, query) => {
1722
+ const fields = tsg.variable("const", "fields", tsg.identifier("gqlResolveInfoToField").importFrom("sasat").call(tsg.identifier("info")).as(makeTypeRef(entity.name, "fields", "GENERATED")));
1723
+ const where = query.conditions && query.conditions.length !== 0 ? tsg.variable("const", "where", qExpr$1.property("and").call(...(query.conditions || []).map(makeQueryConditionExpr))) : null;
1724
+ const method = {
1725
+ single: "first",
1726
+ primary: entity.primaryQueryName(),
1727
+ "list-all": "find",
1728
+ "list-paging": "findPageable"
1729
+ };
1730
+ const queryArgs = getArgs(query, entity);
1731
+ const args = [
1732
+ ...query.type === "primary" ? queryArgs.map((it) => tsg.identifier(it.name)) : [],
1733
+ query.type === "list-paging" ? tsg.identifier("pagingOption").importFrom("sasat").call(tsg.identifier("option")) : null,
1734
+ tsg.identifier("fields"),
1735
+ tsg.identifier(where ? "{ where }" : "undefined"),
1736
+ tsg.identifier("context")
1737
+ ].filter(nonNullable);
1738
+ const result = makeDatasource(entity.name, DIR).property(method[query.type]).call(...args);
1739
+ return tsg.block(fields, where, tsg.return(result));
1740
+ };
1741
+ //#endregion
1742
+ //#region src/generatorv2/codegen/ts/generateResolver.ts
1743
+ const generateResolver = (root) => {
1744
+ const hasSubscription = root.subscriptions.some((it) => it.gqlEnabled);
1745
+ const properties = [tsg.propertyAssign("Query", tsg.identifier("query").importFrom("./query")), tsg.propertyAssign("Mutation", tsg.identifier("mutation").importFrom("./mutation"))];
1746
+ if (hasSubscription) properties.push(tsg.propertyAssign("Subscription", tsg.identifier("subscription").importFrom("./subscription")));
1747
+ return new TsFile(tsg.variable("const", tsg.identifier("resolvers"), tsg.object(...properties, tsg.spreadAssign(tsg.object(...root.entities.filter((it) => it.gqlEnabled).map(makeEntityResolver))))).export()).disableEsLint();
1748
+ };
1749
+ const makeEntityResolver = (node) => {
1750
+ return tsg.propertyAssign(node.name.name, tsg.object(...node.fields.filter((it) => it.hashId).map(makeHashIdProperty).filter(nonNullable), ...node.references.filter((it) => it.isGQLOpen).map((ref) => makeRelationProperty(ref)), ...node.referencedBy.filter((it) => it.isGQLOpen).map((ref) => makeReferencedByProperty(ref))));
1751
+ };
1752
+ const makeHashIdProperty = (field) => {
1753
+ if (!field.hashId) return null;
1754
+ const paramName = field.entity.name.lowerCase();
1755
+ return tsg.propertyAssign(field.fieldName, tsg.arrowFunc([tsg.parameter(paramName, makeTypeRef(field.entity.name, "result", "GENERATED"))], void 0, tsg.binary(tsg.identifier(paramName).property(field.fieldName), "&&", tsg.identifier(field.hashId.encoder).importFrom(Directory.resolve("GENERATED", "BASE", tsFileNames.encoder)).property("encode").call(tsg.identifier(paramName).property(field.fieldName)))));
1756
+ };
1757
+ const makeRelationProperty = (ref) => {
1758
+ const paramName = ref.entity.name.lowerCase();
1759
+ return tsg.propertyAssign(ref.fieldName, tsg.arrowFunc([tsg.parameter(paramName, makeTypeRef(ref.entity.name, "result", "GENERATED")), tsg.parameter("context", makeContextTypeRef("GENERATED"))], void 0, tsg.block(tsg.if(tsg.binary(tsg.identifier(paramName).property(ref.fieldName), "!==", tsg.identifier("undefined")), tsg.return(tsg.identifier(paramName).property(ref.fieldName))), tsg.variable("const", "ds", makeDatasource(EntityName.fromTableName(ref.parentTableName), "GENERATED")), tsg.variable("const", "where", tsg.identifier("ds").property("getRelationMap").call().property(ref.fieldName).property("condition").call(tsg.object(tsg.propertyAssign("parent", tsg.identifier(paramName)), tsg.propertyAssign("childTableAlias", tsg.string("t0")), tsg.propertyAssign("context")))), tsg.return(tsg.identifier("ds").property("first").call(tsg.identifier("undefined"), tsg.object(tsg.propertyAssign("where")))))));
1760
+ };
1761
+ const makeReferencedByProperty = (ref) => {
1762
+ const paramName = ref.entity.name.lowerCase();
1763
+ const propertyName = ref.fieldName;
1764
+ return tsg.propertyAssign(propertyName, tsg.arrowFunc([tsg.parameter(paramName, makeTypeRef(ref.entity.name, "result", "GENERATED")), tsg.parameter("context", makeContextTypeRef("GENERATED"))], void 0, tsg.block(tsg.if(tsg.binary(tsg.identifier(paramName).property(propertyName), "!==", tsg.identifier("undefined")), tsg.return(tsg.identifier(paramName).property(propertyName))), tsg.variable("const", "ds", makeDatasource(EntityName.fromTableName(ref.childTable), "GENERATED")), tsg.variable("const", "where", tsg.identifier("ds").property("getRelationMap").call().property(propertyName).property("condition").call(tsg.object(tsg.propertyAssign("parent", tsg.identifier(paramName)), tsg.propertyAssign("childTableAlias", tsg.string("t0")), tsg.propertyAssign("context")))), tsg.return(tsg.identifier("ds").property(ref.isArray ? "find" : "first").call(tsg.identifier("undefined"), tsg.object(tsg.propertyAssign("where")))))));
1765
+ };
1766
+ //#endregion
1767
+ //#region src/generatorv2/codegen/ts/generateSubscription.ts
1768
+ const generateSubscription = (root) => {
1769
+ const subscriptionEnum = tsg.enum(tsg.identifier("SubscriptionName"), []).export();
1770
+ const subscriptions = tsg.object();
1771
+ const publishFunctions = [];
1772
+ root.subscriptions.forEach((it) => {
1773
+ subscriptionEnum.addMembers(tsg.enumMember(tsg.identifier(it.subscriptionName), tsg.string(it.subscriptionName)));
1774
+ if (it.gqlEnabled) {
1775
+ const fn = it.filters.length === 0 ? makeAsyncIteratorCall(it.subscriptionName) : makeWithFilter(it.subscriptionName, it.filters);
1776
+ subscriptions.addProperties(tsg.propertyAssign(it.subscriptionName, tsg.object(tsg.propertyAssign("subscribe", fn))));
1777
+ }
1778
+ publishFunctions.push(tsg.variable("const", tsg.identifier(it.publishFunctionName), tsg.arrowFunc([tsg.parameter("entity", makeTypeRef(it.entity, it.mutationType === "delete" ? "identifiable" : "entity", "GENERATED"))], tsg.typeRef("Promise", [KeywordTypeNode.void]), tsg.identifier("pubsub.publish").call(tsg.identifier(`SubscriptionName.${it.subscriptionName}`), tsg.object(tsg.propertyAssign(it.subscriptionName, tsg.identifier("entity")))))).export());
1779
+ });
1780
+ return new TsFile(subscriptionEnum, tsg.variable("const", tsg.identifier("subscription"), subscriptions).export(), ...publishFunctions).disableEsLint();
1781
+ };
1782
+ const makeAsyncIteratorCall = (event) => {
1783
+ return tsg.arrowFunc([], void 0, tsg.identifier("pubsub").importFrom("../pubsub").property("asyncIterator").call(tsg.array([tsg.identifier(`SubscriptionName.${event}`)])));
1784
+ };
1785
+ const makeWithFilter = (event, filters) => {
1786
+ const binaryExpressions = filters.map((it) => tsg.binary(tsg.identifier(`result.${it.field}`), "===", tsg.identifier(`variables.${it.field}`))).reduce((previousValue, currentValue) => tsg.binary(previousValue, "&&", currentValue));
1787
+ return tsg.identifier("withFilter").importFrom("graphql-subscriptions").call(makeAsyncIteratorCall(event), tsg.arrowFunc([tsg.parameter("payload", KeywordTypeNode.any), tsg.parameter("variables", KeywordTypeNode.any)], tsg.typeRef("Promise", [KeywordTypeNode.boolean]), tsg.block(tsg.variable("const", tsg.identifier("result"), tsg.await(tsg.identifier(`payload.${event}`))), tsg.return(binaryExpressions))).toAsync());
1788
+ };
1789
+ //#endregion
1790
+ //#region src/generatorv2/codegen/ts/scripts/gqlString.ts
1791
+ const GQLString = {
1792
+ args: (args) => {
1793
+ if (args.length === 0) return "";
1794
+ return `(${args.map((arg) => `${arg.name}: ${GQLString.type(arg.type)}`).join(",")})`;
1795
+ },
1796
+ field: (field) => {
1797
+ return `${field.fieldName}: ${fieldGqlType(field)}`;
1798
+ },
1799
+ referenceField: (ref) => {
1800
+ return `${ref.fieldName}: ${makeGQLType(EntityName.fromTableName(ref.parentTableName).name, ref.isNullable, ref.isArray)}`;
1801
+ },
1802
+ referencedField: (ref) => {
1803
+ return `${ref.fieldName}: ${makeGQLType(EntityName.fromTableName(ref.childTable).name, ref.isNullable, ref.isArray)}`;
1804
+ },
1805
+ query: (node) => {
1806
+ return `${node.queryName}${GQLString.args(node.args)}: ${GQLString.type(node.returnType)}`;
1807
+ },
1808
+ mutation: (node) => {
1809
+ return `${node.mutationName}${GQLString.args(node.args)}: ${GQLString.type(node.returnType)}`;
1810
+ },
1811
+ subscription: (node) => {
1812
+ return `${node.subscriptionName}${GQLString.args(node.args)}: ${GQLString.type(node.returnType)}`;
1813
+ },
1814
+ type: (node) => {
1815
+ const type = node.nullable ? node.typeName : node.typeName + "!";
1816
+ if (node.array) return `[${type}]!`;
1817
+ return type;
1818
+ }
1819
+ };
1820
+ const fieldGqlType = (field) => {
1821
+ return makeGQLType(field.gqlType, field.isNullable, field.isArray);
1822
+ };
1823
+ const makeGQLType = (typeName, isNullable, isArray) => {
1824
+ const type = isNullable ? typeName : typeName + "!";
1825
+ if (isArray) return `[${type}]!`;
1826
+ return type;
1827
+ };
1828
+ //#endregion
1829
+ //#region src/generatorv2/codegen/ts/scripts/typeDefinition.ts
1830
+ const typeFieldDefinitionToTsg = (def) => {
1831
+ const properties = [tsg.propertyAssign("return", tsg.string(def.return)), def.args ? tsg.propertyAssign("args", tsg.array(def.args.map((it) => {
1832
+ return tsg.object(tsg.propertyAssign("name", tsg.string(it.name)), tsg.propertyAssign("type", tsg.string(it.type)));
1833
+ }))) : null];
1834
+ return tsg.object(...properties.filter(nonNullable));
1835
+ };
1836
+ //#endregion
1837
+ //#region src/generatorv2/codegen/ts/generateTypeDefs.ts
1838
+ const generateTypeDefs = (root) => {
1839
+ const types = [
1840
+ ...root.entities.map(makeEntityType),
1841
+ makeQuery(root),
1842
+ makeMutation(root.entities.flatMap((it) => it.mutations)),
1843
+ makeSubscription(root.subscriptions.filter((it) => it.gqlEnabled))
1844
+ ].filter(nonNullable);
1845
+ const inputs = [
1846
+ tsg.propertyAssign("PagingOption", tsg.object(tsg.propertyAssign("numberOfItem", typeFieldDefinitionToTsg({ return: "Int!" })), tsg.propertyAssign("offset", typeFieldDefinitionToTsg({ return: "Int" })), tsg.propertyAssign("order", typeFieldDefinitionToTsg({ return: "String" })), tsg.propertyAssign("asc", typeFieldDefinitionToTsg({ return: "Boolean" })))),
1847
+ ...root.entities.map(makeCreateInput),
1848
+ ...root.entities.map(makeUpdateInput),
1849
+ ...root.entities.map(makeIdentifyInput)
1850
+ ].filter(nonNullable);
1851
+ return new TsFile(tsg.variable("const", tsg.identifier("typeDefs"), tsg.object(...types)).export(), tsg.variable("const", tsg.identifier("inputs"), tsg.object(...inputs)).export()).disableEsLint();
1852
+ };
1853
+ const makeEntityType = (node) => {
1854
+ if (!node.gqlEnabled) return null;
1855
+ return tsg.propertyAssign(node.name.name, tsg.object(...node.fields.filter((it) => it.isGQLOpen).map((it) => {
1856
+ return tsg.propertyAssign(it.fieldName, typeFieldDefinitionToTsg({ return: makeGQLType(it.gqlType, it.isNullable, it.isArray) }));
1857
+ }), ...node.references.filter((it) => it.isGQLOpen).map((it) => {
1858
+ return tsg.propertyAssign(it.fieldName, typeFieldDefinitionToTsg({ return: makeGQLType(EntityName.fromTableName(it.parentTableName).name, it.isNullable, it.isArray) }));
1859
+ }), ...node.referencedBy.filter((it) => it.isGQLOpen).map((it) => {
1860
+ return tsg.propertyAssign(it.fieldName, typeFieldDefinitionToTsg({ return: makeGQLType(EntityName.fromTableName(it.childTable).name, it.isNullable, it.isArray) }));
1861
+ })));
1862
+ };
1863
+ const makeInput = (inputName, fields) => {
1864
+ return tsg.propertyAssign(inputName, tsg.object(...fields.filter((it) => it.isGQLOpen).map((it) => tsg.propertyAssign(it.fieldName, typeFieldDefinitionToTsg({ return: makeGQLType(it.gqlType, it.isNullable, it.isArray) })))));
1865
+ };
1866
+ const makeCreateInput = (node) => {
1867
+ if (!node.gqlEnabled || !node.creatable.gqlEnabled) return null;
1868
+ return makeInput(node.name.createInputName(), node.creatable.fields);
1869
+ };
1870
+ const makeUpdateInput = (node) => {
1871
+ if (!node.gqlEnabled || !node.updateInput.gqlEnabled) return null;
1872
+ return makeInput(node.name.updateInputName(), node.updateInput.fields);
1873
+ };
1874
+ const makeIdentifyInput = (node) => {
1875
+ if (!node.gqlEnabled || !node.mutations.find((it) => it.mutationType === "delete")) return null;
1876
+ return makeInput(node.name.identifyInputName(), node.fields.filter((it) => it.isPrimary));
1877
+ };
1878
+ const makeQueryTypeDef = (entity, query) => {
1879
+ const args = getArgs(query, entity);
1880
+ return tsg.propertyAssign(query.type === "primary" ? entity.name.lowerCase() : query.name, typeFieldDefinitionToTsg({
1881
+ return: GQLString.type({
1882
+ typeName: entity.name.name,
1883
+ entity: true,
1884
+ array: query.type === "list-paging" || query.type === "list-all",
1885
+ nullable: query.type !== "list-paging" && query.type !== "list-all"
1886
+ }),
1887
+ args: args.map((it) => ({
1888
+ name: it.name,
1889
+ type: it.type + "!"
1890
+ }))
1891
+ }));
1892
+ };
1893
+ const makeQueryProperties = (root) => {
1894
+ return root.entities.filter((it) => it.gqlEnabled).flatMap((entity) => entity.queries.map((it) => makeQueryTypeDef(entity, it)));
1895
+ };
1896
+ const makeQuery = (root) => {
1897
+ const properties = makeQueryProperties(root);
1898
+ if (properties.length === 0) return null;
1899
+ return tsg.propertyAssign("Query", tsg.object(...properties));
1900
+ };
1901
+ const makeMutation = (mutations) => {
1902
+ if (mutations.length === 0) return null;
1903
+ return tsg.propertyAssign("Mutation", tsg.object(...mutations.map((mutation) => {
1904
+ return tsg.propertyAssign(mutation.mutationName, typeFieldDefinitionToTsg({
1905
+ return: GQLString.type(mutation.returnType),
1906
+ args: mutation.args.map((arg) => ({
1907
+ name: arg.name,
1908
+ type: GQLString.type(arg.type)
1909
+ }))
1910
+ }));
1911
+ })));
1912
+ };
1913
+ const makeSubscription = (subscriptions) => {
1914
+ if (subscriptions.length === 0) return null;
1915
+ return tsg.propertyAssign("Subscription", tsg.object(...subscriptions.map((subscription) => {
1916
+ return tsg.propertyAssign(subscription.subscriptionName, typeFieldDefinitionToTsg({
1917
+ return: GQLString.type(subscription.returnType),
1918
+ args: subscription.args.map((arg) => ({
1919
+ name: arg.name,
1920
+ type: GQLString.type(arg.type)
1921
+ }))
1922
+ }));
1923
+ })));
1924
+ };
1925
+ //#endregion
1926
+ //#region src/generatorv2/codegen/ts/generateUserDefinedCondition.ts
1927
+ const { createSourceFile, ScriptTarget } = typescript.default;
1928
+ const generateUserDefinedCondition = (root, content) => {
1929
+ const customConditionNames = unique(root.entities.flatMap((it) => [...it.references.flatMap((it) => it.joinCondition.filter((it) => it.kind === "custom").map((it) => it.conditionName)), ...it.referencedBy.flatMap((it) => it.joinCondition.filter((it) => it.kind === "custom").map((it) => it.conditionName))]));
1930
+ if (customConditionNames.length === 0) return null;
1931
+ const sourceFile = createSourceFile(tsFileNames.conditions + ".ts", content, ScriptTarget.ESNext);
1932
+ const exportedVariables = getExportedVariables(sourceFile);
1933
+ const contextImported = isImported(sourceFile, "GQLContext", ["./context", "./context.js"]);
1934
+ const customConditionImported = isImported(sourceFile, "CustomCondition", ["sasat"]);
1935
+ const statements = [];
1936
+ customConditionNames.forEach((conditionName) => {
1937
+ if (!exportedVariables.some((it) => {
1938
+ return it.declarationList.declarations[0].name.getText(sourceFile) === conditionName;
1939
+ })) statements.push(tsg.variable("const", conditionName, tsg.arrowFunc([], void 0, tsg.block(tsg.throw(tsg.new(tsg.identifier("Error"), tsg.string("TODO: Not Implemented"))))), tsg.typeRef("CustomCondition", [tsg.typeRef("GQLContext")])).export());
1940
+ });
1941
+ const context = contextImported ? "" : new ImportDeclaration(["GQLContext"], "./context").toString() + "\n";
1942
+ const condition = customConditionImported ? "" : new ImportDeclaration(["CustomCondition"], "sasat").toString() + "\n";
1943
+ const addition = statements.length === 0 ? "" : "\n" + new TsFile(...statements).toString();
1944
+ return context + condition + content + addition;
1945
+ };
1946
+ //#endregion
1947
+ //#region src/generatorv2/codegen/ts/relationMap/getRequiredColumnNames.ts
1948
+ const getChildConditionValue = (cv) => {
1949
+ if (cv.kind === "child") return cv.field;
1950
+ return null;
1951
+ };
1952
+ const getConditionChildColumnNames = (getConditionValue) => (c) => {
1953
+ if (c.kind === "custom") return c.childRequiredFields || [];
1954
+ if (c.kind === "isNull") return [];
1955
+ const result = [getConditionValue(c.left)];
1956
+ if (c.operator === "IN") {
1957
+ result.push(getConditionValue(c.left));
1958
+ c.right.forEach((it) => {
1959
+ result.push(getConditionValue(it));
1960
+ });
1961
+ }
1962
+ if (c.operator !== "BETWEEN") result.push(getConditionValue(c.right));
1963
+ else if (c.right.kind === "range") result.push(getConditionValue(c.right.begin), getConditionValue(c.right.end));
1964
+ return result;
1965
+ };
1966
+ const getChildRequiredNames = (ref) => {
1967
+ const getNames = getConditionChildColumnNames(getChildConditionValue);
1968
+ return ref.joinCondition.flatMap(getNames).filter(nonNullable);
1969
+ };
1970
+ //#endregion
1971
+ //#region src/generatorv2/codegen/ts/relationMap/makeNoContexError.ts
1972
+ const makeJoinRangeConditionThrowExpressions = (cv) => {
1973
+ if (cv.kind === "range") {
1974
+ const result = [];
1975
+ if (cv.begin.kind === "context") result.push(makeJoinConditionThrowExpressions(cv.begin));
1976
+ if (cv.end.kind === "context") result.push(makeJoinConditionThrowExpressions(cv.end));
1977
+ return result;
1978
+ }
1979
+ return [];
1980
+ };
1981
+ const makeJoinConditionThrowExpressions = (cv) => {
1982
+ if (cv.kind !== "context") return null;
1983
+ if (cv.onNotDefined.action !== "error") return null;
1984
+ return tsg.if(tsg.binary(tsg.identifier("!arg.context"), "||", tsg.binary(tsg.identifier("arg.context").property(cv.field), "===", tsg.identifier("undefined"))), tsg.throw(tsg.new(tsg.identifier("Error"), tsg.string(cv.onNotDefined.message))));
1985
+ };
1986
+ const makeThrowExpressions = (condition) => {
1987
+ if (condition.kind === "custom") return [];
1988
+ if (condition.kind === "isNull") return [makeJoinConditionThrowExpressions(condition.value)];
1989
+ if (condition.operator === "BETWEEN") return [makeJoinConditionThrowExpressions(condition.left), ...condition.right.kind === "range" ? makeJoinRangeConditionThrowExpressions(condition.right) : []];
1990
+ if (condition.operator === "IN") return [makeJoinConditionThrowExpressions(condition.left), ...condition.right.map(makeJoinConditionThrowExpressions)];
1991
+ return [makeJoinConditionThrowExpressions(condition.left), makeJoinConditionThrowExpressions(condition.right)];
1992
+ };
1993
+ //#endregion
1994
+ //#region src/generatorv2/codegen/ts/relationMap/makeJoinConditionValue.ts
1995
+ const qExpr = tsg.identifier("qe").importFrom("sasat");
1996
+ const parentTableAlias = "parentTableAlias";
1997
+ const childTableAlias = "childTableAlias";
1998
+ const makeJoinConditionValueQExpr = (node, cv) => {
1999
+ const arg = tsg.identifier("arg");
2000
+ switch (cv.kind) {
2001
+ case "parent": {
2002
+ const columnName = node.fields.find((it) => it.fieldName === cv.field)?.columnName || cv.field;
2003
+ return qExpr.property("field").call(arg.property(childTableAlias), tsg.string(columnName));
2004
+ }
2005
+ case "child": {
2006
+ const columnName = node.fields.find((it) => it.fieldName === cv.field)?.columnName || cv.field;
2007
+ return tsg.ternary(arg.property(parentTableAlias), qExpr.property("field").call(arg.property(parentTableAlias), tsg.string(columnName)), qExpr.property("value").call(arg.property("parent?").property(cv.field)));
2008
+ }
2009
+ default: return makeConditionValueQExpr(cv);
2010
+ }
2011
+ };
2012
+ const makeRangeCondition = (entity, range) => {
2013
+ if (range.kind === "range") return [makeJoinConditionValueQExpr(entity, range.begin), makeJoinConditionValueQExpr(entity, range.end)];
2014
+ return [tsg.spread(tsg.identifier("getDayRangeQExpr").importFrom("sasat").call(tsg.new(tsg.identifier("Date")), range.thresholdHour ? tsg.number(range.thresholdHour) : tsg.identifier("undefined")))];
2015
+ };
2016
+ const makeConditionExpr = (entity, condition) => {
2017
+ if (condition.kind === "custom") return tsg.identifier(condition.conditionName).importFrom("../conditions").call(tsg.identifier("arg"));
2018
+ if (condition.kind === "isNull") return qExpr.property(condition.not ? "isNotNull" : "isNull").call(makeJoinConditionValueQExpr(entity, condition.value));
2019
+ if (condition.operator === "BETWEEN") return qExpr.property("between").call(makeJoinConditionValueQExpr(entity, condition.left), ...makeRangeCondition(entity, condition.right));
2020
+ if (condition.operator === "IN") return qExpr.property("in").call(makeJoinConditionValueQExpr(entity, condition.left), tsg.array(condition.right.map((it) => makeConditionValueRaw(it))));
2021
+ return qExpr.property("comparison").call(makeJoinConditionValueQExpr(entity, condition.left), tsg.string(condition.operator), makeJoinConditionValueQExpr(entity, condition.right));
2022
+ };
2023
+ const makeJoinConditionValue = (node, ref) => {
2024
+ const arg = tsg.identifier("arg");
2025
+ return tsg.propertyAssign("condition", tsg.arrowFunc([tsg.parameter(arg.toString())], tsg.typeRef("BooleanValueExpression").importFrom("sasat"), tsg.block(...ref.joinCondition.flatMap((it) => makeThrowExpressions(it)).filter(nonNullable), tsg.return(qExpr.property("and").call(...ref.joinCondition.map((it) => makeConditionExpr(node, it)))))));
2026
+ };
2027
+ //#endregion
2028
+ //#region src/generatorv2/codegen/ts/relationMap/index.ts
2029
+ const generateRelationMap = (root) => {
2030
+ return new TsFile(makeRelationMap(root), makeTableInfo(root), ...root.entities.flatMap(entityRelationType)).disableEsLint();
2031
+ };
2032
+ const makeRelationMap = (root) => {
2033
+ return tsg.variable("const", tsg.identifier("relationMap"), tsg.object(...root.entities.map((it) => makeEntityRelationMap(it))), tsg.typeRef("RelationMap", [makeContextTypeRef("GENERATED")]).importFrom("sasat")).export();
2034
+ };
2035
+ const fieldNameToColumnNameAndFilterPrimary = (node) => (field) => {
2036
+ const column = node.fields.find((it) => it.fieldName === field || it.columnName === field);
2037
+ if (!column) throw new Error(`${node.name.name}.${field} Not Found`);
2038
+ if (column.isPrimary) return null;
2039
+ return column.columnName;
2040
+ };
2041
+ const makeEntityRelationMap = (node) => {
2042
+ return tsg.propertyAssign(node.tableName, tsg.object(...node.references.map((ref) => {
2043
+ const toColumnName = fieldNameToColumnNameAndFilterPrimary(ref.entity);
2044
+ return tsg.propertyAssign(ref.fieldName, tsg.object(tsg.propertyAssign("table", tsg.string(ref.parentTableName)), makeJoinConditionValue(node, ref), tsg.propertyAssign("array", tsg.boolean(ref.isArray)), tsg.propertyAssign("nullable", tsg.boolean(ref.isNullable)), tsg.propertyAssign("requiredColumns", tsg.array(getChildRequiredNames(ref).map(toColumnName).filter(nonNullable).map(tsg.string)))));
2045
+ }), ...node.referencedBy.map((rel) => {
2046
+ const toColumnName = fieldNameToColumnNameAndFilterPrimary(rel.entity);
2047
+ return tsg.propertyAssign(rel.fieldName, tsg.object(tsg.propertyAssign("table", tsg.string(rel.childTable)), makeJoinConditionValue(node, rel), tsg.propertyAssign("array", tsg.boolean(rel.isArray)), tsg.propertyAssign("nullable", tsg.boolean(rel.isNullable)), tsg.propertyAssign("requiredColumns", tsg.array(getChildRequiredNames(rel).map(toColumnName).filter(nonNullable).map(tsg.string)))));
2048
+ })));
2049
+ };
2050
+ const makeTableInfo = (root) => {
2051
+ const columnMap = (entity) => tsg.propertyAssign("columnMap", tsg.object(...entity.fields.map((field) => tsg.propertyAssign(field.fieldName, tsg.string(field.columnName)))));
2052
+ return tsg.variable("const", "tableInfo", tsg.object(...root.entities.map((entity) => tsg.propertyAssign(entity.tableName, tsg.object(tsg.propertyAssign("identifiableKeys", tsg.array(entity.identifyKeys.map(tsg.string))), tsg.propertyAssign("identifiableFields", tsg.array(entity.fields.filter((it) => it.isPrimary).map((it) => it.fieldName).map(tsg.string))), columnMap(entity))))), tsg.typeRef("TableInfo").importFrom("sasat")).export();
2053
+ };
2054
+ const referenceRelationType = (ref) => {
2055
+ const parentEntityName = EntityName.fromTableName(ref.parentTableName);
2056
+ const type = tsg.typeRef("EntityResult", [tsg.typeRef(parentEntityName.entityWithRelationTypeName()), tsg.typeRef(parentEntityName.relationTypeName())]).importFrom("sasat");
2057
+ return tsg.propertySignature(ref.fieldName, ref.isArray ? tsg.arrayType(type) : type);
2058
+ };
2059
+ const referencedRelationType = (node) => {
2060
+ const child = EntityName.fromTableName(node.childTable);
2061
+ const type = tsg.typeRef("EntityResult", [tsg.typeRef(child.entityWithRelationTypeName()), makeTypeRef(child, "identifiable", "GENERATED")]).importFrom("sasat");
2062
+ return tsg.propertySignature(node.fieldName, node.isArray ? tsg.arrayType(type) : type);
2063
+ };
2064
+ const entityRelationType = (node) => {
2065
+ const typeProperties = [...node.references.map(referenceRelationType), ...node.referencedBy.map(referencedRelationType)];
2066
+ return [
2067
+ tsg.typeAlias(node.name.relationTypeName(), typeProperties.length !== 0 ? tsg.typeLiteral(typeProperties) : tsg.typeRef("Record<never, never>")).export(),
2068
+ tsg.typeAlias(node.name.entityWithRelationTypeName(), tsg.intersectionType(makeTypeRef(node.name, "entity", "GENERATED"), tsg.typeRef(node.name.relationTypeName()))).export(),
2069
+ tsg.typeAlias(node.name.resultType(), tsg.typeRef("EntityResult", [tsg.typeRef(node.name.entityWithRelationTypeName()), makeTypeRef(node.name, "identifiable", "GENERATED")]).importFrom("sasat")).export()
2070
+ ];
2071
+ };
2072
+ //#endregion
2073
+ //#region src/generatorv2/codegen/ts/staticFiles.ts
2074
+ const contextFile = `\
2075
+ ${new ImportDeclaration(["BaseGQLContext"], "./__generated__/context").toString()}
2076
+ export type GQLContext = BaseGQLContext & Record<string, never>;
2077
+ `;
2078
+ const pubsubFile = `\
2079
+ ${new ImportDeclaration(["PubSub", "PubSubEngine"], "graphql-subscriptions").toString()}
2080
+
2081
+ export const pubsub: PubSubEngine = new PubSub();
2082
+ `;
2083
+ const schemaFile = `\
2084
+ ${new ImportDeclaration(["assignDeep", "createTypeDef"], "sasat").toString()}
2085
+ ${new ImportDeclaration(["typeDefs", "inputs"], "./__generated__/typeDefs").toString()}
2086
+ ${new ImportDeclaration(["resolvers"], "./__generated__/resolver").toString()}
2087
+
2088
+ export const schema = {
2089
+ typeDefs: createTypeDef(
2090
+ assignDeep(typeDefs, {}),
2091
+ assignDeep(inputs, {}),
2092
+ ),
2093
+ resolvers: assignDeep(resolvers, {}),
2094
+ };
2095
+ `;
2096
+ const baseDBDataSourceFile = `\
2097
+ ${new ImportDeclaration([
2098
+ "Fields",
2099
+ "SasatDBDatasource",
2100
+ "EntityType"
2101
+ ], "sasat").toString()}
2102
+ ${new ImportDeclaration(["relationMap", "tableInfo"], "./__generated__/relationMap").toString()}
2103
+
2104
+ export abstract class BaseDBDataSource<
2105
+ Entity extends EntityType,
2106
+ Identifiable extends object,
2107
+ Creatable extends EntityType,
2108
+ Updatable extends Identifiable,
2109
+ EntityFields extends Fields<Entity>,
2110
+ QueryResult extends Partial<Entity> & Identifiable,
2111
+ > extends SasatDBDatasource<Entity, Identifiable, Creatable, Updatable, EntityFields, QueryResult> {
2112
+ protected relationMap = relationMap;
2113
+ protected tableInfo = tableInfo;
2114
+ }
2115
+ `;
2116
+ const staticFiles = [
2117
+ {
2118
+ name: "context",
2119
+ body: contextFile
2120
+ },
2121
+ {
2122
+ name: "pubsub",
2123
+ body: pubsubFile
2124
+ },
2125
+ {
2126
+ name: "schema",
2127
+ body: schemaFile
2128
+ },
2129
+ {
2130
+ name: "baseDBDataSource",
2131
+ body: baseDBDataSourceFile
2132
+ }
2133
+ ];
2134
+ //#endregion
2135
+ //#region src/generatorv2/codegen/tscodegen_v2.ts
2136
+ var TsCodegen_v2 = class {
2137
+ constructor() {
2138
+ this.fileExtension = "ts";
2139
+ this.generateEntity = (node) => generateEntityFile(node).generate();
2140
+ this.generateDatasource = (node) => generateDatasource(node).generate();
2141
+ this.generateGeneratedDatasource = (node) => generateAutoGeneratedDatasource(node).generate();
2142
+ this.generateGqlTypeDefs = (root) => generateTypeDefs(root).generate();
2143
+ this.generateGqlResolver = (root) => generateResolver(root).generate();
2144
+ this.generateGqlQuery = (root) => generateQueryResolver(root).generate();
2145
+ this.generateGqlMutation = (root) => generateMutationResolver(root).generate();
2146
+ this.generateGqlSubscription = (root) => generateSubscription(root).generate();
2147
+ this.generateGQLContext = (root) => generateContext(root).generate();
2148
+ this.generateFiles = async (root) => {
2149
+ return [{
2150
+ name: "relationMap",
2151
+ body: await generateRelationMap(root).generate()
2152
+ }, {
2153
+ name: "fields",
2154
+ body: await generateFields(root).generate()
2155
+ }];
2156
+ };
2157
+ this.generateOnceFiles = () => {
2158
+ return staticFiles;
2159
+ };
2160
+ this.generateConditions = (root, currentFile) => {
2161
+ return generateUserDefinedCondition(root, currentFile);
2162
+ };
2163
+ this.generateIDEncoders = (root, currentFile) => {
2164
+ return generateIDEncoder(root, currentFile);
2165
+ };
2166
+ this.generateMiddlewares = (root, currentFile) => {
2167
+ return generateMiddlewares(root, currentFile);
2168
+ };
2169
+ }
2170
+ };
2171
+ //#endregion
2172
+ //#region src/generatorv2/parser/makeContextNodes.ts
2173
+ const makeContextNodes = (store) => {
2174
+ return store.tables.flatMap((table) => {
2175
+ return table.gqlOption.mutations.flatMap((mutation) => mutation.contextFields.map((it) => ({
2176
+ name: it.contextName || it.column,
2177
+ dbtype: table.column(it.column).dataType()
2178
+ })));
2179
+ });
2180
+ };
2181
+ //#endregion
2182
+ //#region src/generatorv2/parser/makeMutationNodes.ts
2183
+ const makeEntityMutationNodes = (table, entity) => {
2184
+ if (!table.gqlOption.enabled) return [];
2185
+ return table.gqlOption.mutations.map((mutation) => {
2186
+ switch (mutation.type) {
2187
+ case "create": return makeCreateMutationNode(table, entity, mutation);
2188
+ case "update": return makeUpdateMutationNode(table, entity, mutation);
2189
+ case "delete": return makeDeleteMutationNode(table, entity, mutation);
2190
+ default: throw new Error(`invalid mutation type: ${mutation.type}`);
2191
+ }
2192
+ });
2193
+ };
2194
+ const makeContextField = (params) => ({
2195
+ fieldName: params.column,
2196
+ contextName: params.contextName || params.column
2197
+ });
2198
+ const makeCreateMutationNode = (table, entity, mutation) => {
2199
+ return {
2200
+ entity,
2201
+ contextFields: mutation.contextFields.map(makeContextField),
2202
+ entityName: table.getEntityName(),
2203
+ identifyFields: table.getPrimaryKeyColumns().map((it) => it.fieldName()),
2204
+ mutationName: `create${table.getEntityName().name}`,
2205
+ inputName: entity.name.createInputName(),
2206
+ refetch: !mutation.noReFetch,
2207
+ returnType: {
2208
+ typeName: table.getEntityName().name,
2209
+ nullable: false,
2210
+ array: false,
2211
+ entity: true
2212
+ },
2213
+ args: [{
2214
+ name: table.getEntityName().lowerCase(),
2215
+ type: {
2216
+ typeName: table.getEntityName().createInputName(),
2217
+ nullable: false,
2218
+ array: false,
2219
+ entity: true
2220
+ }
2221
+ }],
2222
+ mutationType: "create",
2223
+ subscription: mutation.subscription.enabled,
2224
+ requireIdDecodeMiddleware: entity.creatable.fields.some((it) => it.hashId),
2225
+ middlewares: mutation.middlewares
2226
+ };
2227
+ };
2228
+ const makeUpdateMutationNode = (table, entity, mutation) => {
2229
+ return {
2230
+ entity,
2231
+ contextFields: mutation.contextFields.map(makeContextField),
2232
+ entityName: table.getEntityName(),
2233
+ identifyFields: table.getPrimaryKeyColumns().map((it) => it.fieldName()),
2234
+ mutationName: `update${table.getEntityName().name}`,
2235
+ inputName: entity.name.updateInputName(),
2236
+ refetch: !mutation.noReFetch,
2237
+ returnType: {
2238
+ typeName: mutation.noReFetch ? "Boolean" : table.getEntityName().name,
2239
+ dbType: mutation.noReFetch ? "boolean" : void 0,
2240
+ nullable: false,
2241
+ array: false,
2242
+ entity: !mutation.noReFetch
2243
+ },
2244
+ args: [{
2245
+ name: table.getEntityName().lowerCase(),
2246
+ type: {
2247
+ typeName: table.getEntityName().updateInputName(),
2248
+ nullable: false,
2249
+ array: false,
2250
+ entity: true
2251
+ }
2252
+ }],
2253
+ mutationType: "update",
2254
+ subscription: mutation.subscription.enabled,
2255
+ requireIdDecodeMiddleware: entity.updateInput.fields.some((it) => it.hashId),
2256
+ middlewares: mutation.middlewares
2257
+ };
2258
+ };
2259
+ const makeDeleteMutationNode = (table, entity, mutation) => {
2260
+ return {
2261
+ entity,
2262
+ mutationName: `delete${table.getEntityName().name}`,
2263
+ inputName: entity.name.identifyInputName(),
2264
+ contextFields: mutation.contextFields.map(makeContextField),
2265
+ entityName: table.getEntityName(),
2266
+ identifyFields: table.getPrimaryKeyColumns().map((it) => it.fieldName()),
2267
+ refetch: false,
2268
+ returnType: {
2269
+ typeName: "Boolean",
2270
+ dbType: "boolean",
2271
+ nullable: false,
2272
+ array: false,
2273
+ entity: false
2274
+ },
2275
+ args: [{
2276
+ name: table.getEntityName().lowerCase(),
2277
+ type: {
2278
+ typeName: table.getEntityName().identifyInputName(),
2279
+ nullable: false,
2280
+ array: false,
2281
+ entity: true
2282
+ }
2283
+ }],
2284
+ mutationType: "delete",
2285
+ subscription: mutation.subscription.enabled,
2286
+ requireIdDecodeMiddleware: entity.identifyFields().some((it) => it.hashId),
2287
+ middlewares: mutation.middlewares
2288
+ };
2289
+ };
2290
+ //#endregion
2291
+ //#region src/generatorv2/scripts/columnToGqlType.ts
2292
+ const columnTypeToGqlPrimitive = (type) => {
2293
+ switch (type) {
2294
+ case "tinyint":
2295
+ case "smallint":
2296
+ case "mediumint":
2297
+ case "int":
2298
+ case "bigint":
2299
+ case "decimal":
2300
+ case "year": return "Int";
2301
+ case "float":
2302
+ case "double": return "Float";
2303
+ case "char":
2304
+ case "varchar":
2305
+ case "text":
2306
+ case "time":
2307
+ case "date":
2308
+ case "datetime":
2309
+ case "timestamp": return "String";
2310
+ case "boolean": return "Boolean";
2311
+ }
2312
+ };
2313
+ //#endregion
2314
+ //#region src/generatorv2/nodes/FieldNode.ts
2315
+ const getHashId = (store, entity, column) => {
2316
+ if (!column.isReference()) {
2317
+ if (column.data.option.autoIncrementHashId) return { encoder: entity.IDEncoderName() };
2318
+ return;
2319
+ }
2320
+ const ref = column.data.reference;
2321
+ const parent = store.table(ref.parentTable);
2322
+ if (!parent.column(ref.parentColumn).data.option.autoIncrementHashId) return void 0;
2323
+ return { encoder: parent.getEntityName().IDEncoderName() };
2324
+ };
2325
+ const makeFieldNode = (store, entity, column) => {
2326
+ const hashId = getHashId(store, entity.name, column);
2327
+ return {
2328
+ entity,
2329
+ fieldName: column.fieldName(),
2330
+ columnName: column.columnName(),
2331
+ gqlType: hashId ? "ID" : column.gqlType(),
2332
+ dbType: column.dataType(),
2333
+ isAutoIncrement: column.data.autoIncrement,
2334
+ isArray: false,
2335
+ isPrimary: column.isPrimary(),
2336
+ isNullable: column.isNullable(),
2337
+ isUpdatable: !(column.data.onUpdateCurrentTimeStamp || column.isPrimary()) && column.data.option.updatable,
2338
+ isGQLOpen: true,
2339
+ column: column.data,
2340
+ option: column.data.option,
2341
+ hashId
2342
+ };
2343
+ };
2344
+ const makeCreatableFieldNode = (store, entity, column) => {
2345
+ if (column.data.autoIncrement || column.data.defaultCurrentTimeStamp) return null;
2346
+ const hashId = getHashId(store, entity.name, column);
2347
+ return {
2348
+ entity,
2349
+ fieldName: column.fieldName(),
2350
+ columnName: column.columnName(),
2351
+ gqlType: hashId ? "ID" : column.gqlType(),
2352
+ dbType: column.dataType(),
2353
+ isAutoIncrement: column.data.autoIncrement,
2354
+ isArray: false,
2355
+ isPrimary: column.isPrimary(),
2356
+ isNullable: column.isNullableOnCreate(),
2357
+ isUpdatable: column.isUpdatable(),
2358
+ isGQLOpen: !(column.table.gqlOption.mutations.find((it) => it.type === "create")?.contextFields || []).some((it) => it.column === column.columnName()),
2359
+ column: column.data,
2360
+ option: column.data.option,
2361
+ hashId: getHashId(store, entity.name, column)
2362
+ };
2363
+ };
2364
+ const makeUpdatableFieldNode = (store, entity, column) => {
2365
+ if (!column.isUpdatable() || !column.data.option.updatable) return null;
2366
+ const hashId = getHashId(store, entity.name, column);
2367
+ return {
2368
+ entity,
2369
+ fieldName: column.fieldName(),
2370
+ columnName: column.columnName(),
2371
+ gqlType: hashId ? "ID" : column.gqlType(),
2372
+ dbType: column.dataType(),
2373
+ isAutoIncrement: column.data.autoIncrement,
2374
+ isArray: false,
2375
+ isNullable: true,
2376
+ isPrimary: false,
2377
+ isUpdatable: true,
2378
+ isGQLOpen: !(column.table.gqlOption.mutations.find((it) => it.type === "update")?.contextFields || []).some((it) => it.column === column.columnName()),
2379
+ column: column.data,
2380
+ option: column.data.option,
2381
+ hashId: getHashId(store, entity.name, column)
2382
+ };
2383
+ };
2384
+ //#endregion
2385
+ //#region src/migration/makeCondition.ts
2386
+ const parent = (field) => ({
2387
+ kind: "parent",
2388
+ field
2389
+ });
2390
+ const child = (field) => ({
2391
+ kind: "child",
2392
+ field
2393
+ });
2394
+ const contextOrError = (field, errorMessage) => ({
2395
+ kind: "context",
2396
+ field,
2397
+ onNotDefined: {
2398
+ action: "error",
2399
+ message: errorMessage
2400
+ }
2401
+ });
2402
+ const contextOrDefault = (field, defaultValue) => ({
2403
+ kind: "context",
2404
+ field,
2405
+ onNotDefined: {
2406
+ action: "defaultValue",
2407
+ value: defaultValue
2408
+ }
2409
+ });
2410
+ const fixed = (value) => ({
2411
+ kind: "fixed",
2412
+ value
2413
+ });
2414
+ const today = (thresholdHour, date) => ({
2415
+ kind: "today",
2416
+ type: date ? "date" : "datetime",
2417
+ thresholdHour
2418
+ });
2419
+ const now = () => ({ kind: "now" });
2420
+ const values = (begin, end) => ({
2421
+ kind: "range",
2422
+ begin,
2423
+ end
2424
+ });
2425
+ const betweenToday = (thresholdHour) => ({
2426
+ kind: "date-range",
2427
+ range: "today",
2428
+ thresholdHour
2429
+ });
2430
+ const custom = (conditionName, parentRequiredFields, childRequiredFields) => ({
2431
+ kind: "custom",
2432
+ conditionName,
2433
+ parentRequiredFields,
2434
+ childRequiredFields
2435
+ });
2436
+ const field = (column) => ({
2437
+ kind: "field",
2438
+ column
2439
+ });
2440
+ const arg = (name, type) => ({
2441
+ kind: "arg",
2442
+ name,
2443
+ type
2444
+ });
2445
+ const betweenRel = (left, range) => ({
2446
+ kind: "comparison",
2447
+ left,
2448
+ operator: "BETWEEN",
2449
+ right: range
2450
+ });
2451
+ const betweenQuery = (left, begin, end) => ({
2452
+ kind: "between",
2453
+ operator: "BETWEEN",
2454
+ left,
2455
+ begin,
2456
+ end
2457
+ });
2458
+ const comparisonRel = (left, operator, right) => ({
2459
+ kind: "comparison",
2460
+ left,
2461
+ right,
2462
+ operator
2463
+ });
2464
+ const inRel = (left, right) => ({
2465
+ kind: "comparison",
2466
+ left,
2467
+ right,
2468
+ operator: "IN"
2469
+ });
2470
+ const isNullRel = (value) => ({
2471
+ kind: "isNull",
2472
+ value,
2473
+ not: false
2474
+ });
2475
+ const isNotNullRel = (value) => ({
2476
+ kind: "isNull",
2477
+ value,
2478
+ not: true
2479
+ });
2480
+ const comparisonQuery = (left, operator, right) => ({
2481
+ kind: "comparison",
2482
+ left,
2483
+ right,
2484
+ operator
2485
+ });
2486
+ const Conditions = {
2487
+ betweenRel,
2488
+ betweenQuery,
2489
+ custom,
2490
+ rel: {
2491
+ between: betweenRel,
2492
+ comparison: comparisonRel,
2493
+ in: inRel,
2494
+ isNull: isNullRel,
2495
+ isNotNull: isNotNullRel
2496
+ },
2497
+ query: {
2498
+ between: betweenQuery,
2499
+ comparison: comparisonQuery
2500
+ },
2501
+ value: {
2502
+ parent,
2503
+ child,
2504
+ contextOrError,
2505
+ contextOrDefault,
2506
+ fixed,
2507
+ today,
2508
+ now,
2509
+ field,
2510
+ arg
2511
+ },
2512
+ range: {
2513
+ values,
2514
+ today: betweenToday
2515
+ }
2516
+ };
2517
+ //#endregion
2518
+ //#region src/generatorv2/nodes/ReferencedNode.ts
2519
+ var ReferenceNode = class ReferenceNode {
2520
+ static fromReference(entity, column, parentTable) {
2521
+ const ref = column.data.reference;
2522
+ if (!ref.fieldName) return null;
2523
+ return new ReferenceNode(entity, ref.fieldName, column.table.tableName, ref.parentTable, makeJoinCondition(ref.parentColumn, column.columnName()), false, column.isNullable(), column.isPrimary(), column.table.gqlOption.enabled && parentTable.gqlOption.enabled);
2524
+ }
2525
+ static formVirtualRelation(ds, entity, rel) {
2526
+ if (!rel.childFieldName) return null;
2527
+ return new ReferenceNode(entity, rel.childFieldName, rel.childTable, rel.parentTable, rel.conditions, rel.childType === void 0 || rel.childType === "array", rel.childType === "nullable", false, ds.table(rel.parentTable).gqlOption.enabled && ds.table(rel.childTable).gqlOption.enabled);
2528
+ }
2529
+ constructor(entity, fieldName, tableName, parentTableName, joinCondition, isArray, isNullable, isPrimary, isGQLOpen) {
2530
+ this.entity = entity;
2531
+ this.fieldName = fieldName;
2532
+ this.tableName = tableName;
2533
+ this.parentTableName = parentTableName;
2534
+ this.joinCondition = joinCondition;
2535
+ this.isArray = isArray;
2536
+ this.isNullable = isNullable;
2537
+ this.isPrimary = isPrimary;
2538
+ this.isGQLOpen = isGQLOpen;
2539
+ }
2540
+ };
2541
+ var ReferencedNode = class ReferencedNode {
2542
+ static fromReference(entity, parentTable, column) {
2543
+ const ref = column.data.reference;
2544
+ if (!ref.parentFieldName) return null;
2545
+ return new ReferencedNode(entity, ref.parentFieldName, column.table.tableName, makeJoinCondition(column.columnName(), ref.parentColumn), ref.relation === "Many", ref.relation === "OneOrZero", column.isPrimary(), parentTable.gqlOption.enabled && column.table.gqlOption.enabled);
2546
+ }
2547
+ static fromVirtualRelation(ds, entity, rel) {
2548
+ if (!rel.parentFieldName) return null;
2549
+ return new ReferencedNode(entity, rel.parentFieldName, rel.childTable, rel.conditions.map(reverseConditionNode), rel.parentType === void 0 || rel.parentType === "array", rel.parentType === "nullable", false, ds.table(rel.parentTable).gqlOption.enabled && ds.table(rel.childTable).gqlOption.enabled);
2550
+ }
2551
+ constructor(entity, fieldName, childTable, joinCondition, isArray, isNullable, isPrimary, isGQLOpen) {
2552
+ this.entity = entity;
2553
+ this.fieldName = fieldName;
2554
+ this.childTable = childTable;
2555
+ this.joinCondition = joinCondition;
2556
+ this.isArray = isArray;
2557
+ this.isNullable = isNullable;
2558
+ this.isPrimary = isPrimary;
2559
+ this.isGQLOpen = isGQLOpen;
2560
+ }
2561
+ };
2562
+ const reverseConditionValue = (cv) => {
2563
+ if (cv.kind === "parent") return {
2564
+ ...cv,
2565
+ kind: "child"
2566
+ };
2567
+ else if (cv.kind === "child") return {
2568
+ ...cv,
2569
+ kind: "parent"
2570
+ };
2571
+ return cv;
2572
+ };
2573
+ const reverseRangeCondition = (condition) => {
2574
+ if (condition.kind === "range") return {
2575
+ kind: condition.kind,
2576
+ begin: reverseConditionValue(condition.begin),
2577
+ end: reverseConditionValue(condition.end)
2578
+ };
2579
+ return condition;
2580
+ };
2581
+ const reverseConditionNode = (condition) => {
2582
+ if (condition.kind === "custom") return {
2583
+ ...condition,
2584
+ parentRequiredFields: condition.childRequiredFields,
2585
+ childRequiredFields: condition.parentRequiredFields
2586
+ };
2587
+ if (condition.kind === "isNull") {
2588
+ if (condition.not) return Conditions.rel.isNotNull(reverseConditionValue(condition.value));
2589
+ return Conditions.rel.isNull(reverseConditionValue(condition.value));
2590
+ }
2591
+ if (condition.operator === "BETWEEN") return Conditions.rel.between(reverseConditionValue(condition.left), reverseRangeCondition(condition.right));
2592
+ if (condition.operator === "IN") return Conditions.rel.in(reverseConditionValue(condition.left), condition.right.map(reverseConditionValue));
2593
+ return Conditions.rel.comparison(reverseConditionValue(condition.right), condition.operator, reverseConditionValue(condition.left));
2594
+ };
2595
+ const makeJoinCondition = (parentColumn, childColumn) => {
2596
+ return [Conditions.rel.comparison(Conditions.value.parent(parentColumn), "=", Conditions.value.child(childColumn))];
2597
+ };
2598
+ //#endregion
2599
+ //#region src/generatorv2/nodes/entityNode.ts
2600
+ var EntityNode = class {
2601
+ constructor(store, table) {
2602
+ this.name = EntityName.fromTableName(table.tableName);
2603
+ this.fields = table.columns.map((it) => makeFieldNode(store, this, it));
2604
+ this.tableName = table.tableName;
2605
+ this.gqlEnabled = table.gqlOption.enabled;
2606
+ this.identifyKeys = table.primaryKey;
2607
+ this.queries = table.gqlOption.queries;
2608
+ this.creatable = {
2609
+ gqlEnabled: table.gqlOption.enabled && table.gqlOption.mutations.find((it) => it.type === "create") !== void 0,
2610
+ fields: table.columns.map((it) => makeCreatableFieldNode(store, this, it)).filter(nonNullable)
2611
+ };
2612
+ this.updateInput = {
2613
+ gqlEnabled: table.gqlOption.enabled && table.gqlOption.mutations.find((it) => it.type === "update") !== void 0,
2614
+ fields: [...this.fields.filter((it) => it.isPrimary), ...table.columns.map((it) => makeUpdatableFieldNode(store, this, it)).filter(nonNullable)]
2615
+ };
2616
+ this.references = table.getReferenceColumns().map((column) => ReferenceNode.fromReference(this, column, store.table(column.data.reference.parentTable))).concat(table.virtualRelations.map((it) => ReferenceNode.formVirtualRelation(store, this, it))).filter(nonNullable);
2617
+ this.referencedBy = store.referencedBy(table.tableName).map((column) => ReferencedNode.fromReference(this, table, column)).concat(store.virtualReferencedBy(table.tableName).map((rel) => ReferencedNode.fromVirtualRelation(store, this, rel))).filter(nonNullable);
2618
+ const makeFindMethodNode = (columns, isArray) => {
2619
+ const fields = columns.map((column) => this.fields.find((it) => it.columnName === column));
2620
+ return {
2621
+ name: makeFindQueryName(fields.map((it) => it.fieldName)),
2622
+ params: fields.map((it) => makePrimitiveParameterNode(it.fieldName, it.columnName, it.dbType)),
2623
+ isArray
2624
+ };
2625
+ };
2626
+ this.findMethods = [makeFindMethodNode(table.primaryKey, false)];
2627
+ this.mutations = makeEntityMutationNodes(table, this);
2628
+ }
2629
+ identifyFields() {
2630
+ return this.fields.filter((it) => it.isPrimary);
2631
+ }
2632
+ primaryQueryName() {
2633
+ return makeFindQueryName(this.identifyFields().map((it) => it.fieldName));
2634
+ }
2635
+ };
2636
+ const makePrimitiveParameterNode = (fieldName, columnName, dbtype) => ({
2637
+ entity: false,
2638
+ fieldName,
2639
+ columnName,
2640
+ dbtype,
2641
+ gqltype: columnTypeToGqlPrimitive(dbtype)
2642
+ });
2643
+ //#endregion
2644
+ //#region src/generatorv2/parser/makeEntityNodes.ts
2645
+ const makeEntityNodes = (store) => {
2646
+ const make = makeEntityNode(store);
2647
+ return store.tables.map(make);
2648
+ };
2649
+ const makeEntityNode = (store) => (table) => {
2650
+ return new EntityNode(store, table);
2651
+ };
2652
+ //#endregion
2653
+ //#region src/generatorv2/parser/makeSubscriptionNode.ts
2654
+ const makeSubscriptionNodes = (store) => {
2655
+ return store.tables.flatMap((table) => {
2656
+ return table.gqlOption.mutations.map((it) => {
2657
+ return makeSubscriptionNode(table, it);
2658
+ });
2659
+ }).filter(nonNullable);
2660
+ };
2661
+ const subscriptionNamePostfix = {
2662
+ create: "Created",
2663
+ update: "Updated",
2664
+ delete: "Deleted"
2665
+ };
2666
+ const makeSubscriptionNode = (table, mutation) => {
2667
+ if (!mutation.subscription.enabled) return null;
2668
+ const subscriptionName = table.getEntityName().name + subscriptionNamePostfix[mutation.type];
2669
+ return {
2670
+ subscriptionName,
2671
+ entity: table.getEntityName(),
2672
+ publishFunctionName: "publish" + subscriptionName,
2673
+ returnType: {
2674
+ typeName: table.getEntityName().name,
2675
+ nullable: false,
2676
+ array: false,
2677
+ entity: true
2678
+ },
2679
+ args: mutation.subscription.subscriptionFilter.map((it) => {
2680
+ const column = table.column(it);
2681
+ return {
2682
+ name: it,
2683
+ type: {
2684
+ typeName: column.gqlType(),
2685
+ dbType: column.dataType(),
2686
+ nullable: false,
2687
+ array: false,
2688
+ entity: false
2689
+ }
2690
+ };
2691
+ }),
2692
+ filters: (mutation.subscription?.subscriptionFilter || []).map((it) => {
2693
+ const column = table.column(it);
2694
+ return {
2695
+ field: column.fieldName(),
2696
+ gqlType: column.gqlType()
2697
+ };
2698
+ }),
2699
+ mutationType: mutation.type,
2700
+ gqlEnabled: table.gqlOption.enabled && mutation.subscription.enabled
2701
+ };
2702
+ };
2703
+ //#endregion
2704
+ //#region src/generatorv2/parse.ts
2705
+ const parse = (store) => {
2706
+ store.tables.forEach((it) => {
2707
+ if (it.primaryKey.length === 0) throw new Error(`Table: ${it.tableName} has no primary key.`);
2708
+ });
2709
+ return {
2710
+ entities: makeEntityNodes(store),
2711
+ subscriptions: makeSubscriptionNodes(store),
2712
+ contexts: makeContextNodes(store)
2713
+ };
2714
+ };
2715
+ //#endregion
2716
+ //#region src/generatorv2/codegen_v2.ts
2717
+ var CodeGen_v2 = class {
2718
+ constructor(store) {
2719
+ this.codeGen = new TsCodegen_v2();
2720
+ this.outDir = config().migration.out;
2721
+ this.dbDataSourceDir = node_path.join(this.outDir, Directory.paths.DATA_SOURCES);
2722
+ this.generateDir = node_path.join(this.outDir, Directory.paths.GENERATED);
2723
+ this.generateEntityDir = node_path.join(this.outDir, Directory.paths.ENTITIES);
2724
+ this.generateDbDataSourceDir = node_path.join(this.outDir, Directory.paths.GENERATED_DS);
2725
+ this.root = parse(store);
2726
+ }
2727
+ async generate() {
2728
+ await this.prepareDirs();
2729
+ await Promise.all([
2730
+ ...this.root.entities.map((it) => this.generateEntity(it)),
2731
+ ...this.root.entities.map((it) => this.generateDatasource(it)),
2732
+ ...this.root.entities.map((it) => this.generateGeneratedDatasource(it)),
2733
+ this.generateGql(this.root),
2734
+ this.generateFiles(this.root),
2735
+ ...this.generateOnceFiles(),
2736
+ this.generateCondition(this.root),
2737
+ this.generateIDEncoders(this.root),
2738
+ this.generateMiddleware(this.root)
2739
+ ]);
2740
+ }
2741
+ async prepareDirs() {
2742
+ mkDirIfNotExist(this.generateDir);
2743
+ await emptyDir(this.generateDir);
2744
+ mkDirIfNotExist(this.generateEntityDir);
2745
+ mkDirIfNotExist(this.generateDbDataSourceDir);
2746
+ mkDirIfNotExist(this.dbDataSourceDir);
2747
+ }
2748
+ getFullPath(basePath, entityName) {
2749
+ return node_path.join(basePath, `${entityName}.${this.codeGen.fileExtension}`);
2750
+ }
2751
+ async generateEntity(node) {
2752
+ return (0, node_fs_promises.writeFile)(this.getFullPath(this.generateEntityDir, node.name.name), await this.codeGen.generateEntity(node));
2753
+ }
2754
+ async generateDatasource(node) {
2755
+ return writeFileIfNotExist(this.getFullPath(this.dbDataSourceDir, node.name.name), await this.codeGen.generateDatasource(node));
2756
+ }
2757
+ async generateGeneratedDatasource(node) {
2758
+ return (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDbDataSourceDir, node.name.name), await this.codeGen.generateGeneratedDatasource(node));
2759
+ }
2760
+ async generateGql(rootNode) {
2761
+ return Promise.all([
2762
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "typeDefs"), await this.codeGen.generateGqlTypeDefs(rootNode)),
2763
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "resolver"), await this.codeGen.generateGqlResolver(rootNode)),
2764
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "query"), await this.codeGen.generateGqlQuery(rootNode)),
2765
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "mutation"), await this.codeGen.generateGqlMutation(rootNode)),
2766
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "subscription"), await this.codeGen.generateGqlSubscription(rootNode)),
2767
+ (0, node_fs_promises.writeFile)(this.getFullPath(this.generateDir, "context"), await this.codeGen.generateGQLContext(rootNode))
2768
+ ]);
2769
+ }
2770
+ async generateFiles(rootNode) {
2771
+ const files = await this.codeGen.generateFiles(rootNode);
2772
+ return Promise.all(files.map((it) => writeFileIfNotExist(this.getFullPath(this.generateDir, it.name), it.body)));
2773
+ }
2774
+ generateOnceFiles() {
2775
+ return this.codeGen.generateOnceFiles().map((it) => writeFileIfNotExist(this.getFullPath(this.outDir, it.name), it.body));
2776
+ }
2777
+ async generateCondition(rootNode) {
2778
+ const filePath = this.getFullPath(this.outDir, tsFileNames.conditions);
2779
+ const content = (0, node_fs.existsSync)(filePath) ? (0, node_fs.readFileSync)(filePath).toString() : "";
2780
+ const nextContent = this.codeGen.generateConditions(rootNode, content);
2781
+ if (nextContent) (0, node_fs.writeFileSync)(filePath, nextContent);
2782
+ }
2783
+ async generateIDEncoders(rootNode) {
2784
+ const filePath = this.getFullPath(this.outDir, tsFileNames.encoder);
2785
+ const content = (0, node_fs.existsSync)(filePath) ? (0, node_fs.readFileSync)(filePath).toString() : "";
2786
+ const nextContent = this.codeGen.generateIDEncoders(rootNode, content);
2787
+ if (nextContent) (0, node_fs.writeFileSync)(filePath, nextContent);
2788
+ }
2789
+ async generateMiddleware(rootNode) {
2790
+ const filePath = this.getFullPath(this.outDir, tsFileNames.middleware);
2791
+ const content = (0, node_fs.existsSync)(filePath) ? (0, node_fs.readFileSync)(filePath).toString() : "";
2792
+ const nextContent = this.codeGen.generateMiddlewares(rootNode, content);
2793
+ if (nextContent) (0, node_fs.writeFileSync)(filePath, nextContent);
2794
+ }
2795
+ };
2796
+ //#endregion
2797
+ //#region src/migration/exec/getMigrationFiles.ts
2798
+ const getMigrationFileDir = () => {
2799
+ return node_path.default.join(process.cwd(), config().migration.dir);
2800
+ };
2801
+ const getMigrationFileNames = () => {
2802
+ return node_fs.default.readdirSync(getMigrationFileDir()).filter((it) => it.split(".").pop() === "ts");
2803
+ };
2804
+ //#endregion
2805
+ //#region src/error.ts
2806
+ var SasatError = class extends Error {
2807
+ constructor(message) {
2808
+ super(message);
2809
+ Object.setPrototypeOf(this, new.target.prototype);
2810
+ this.name = "SasatError";
2811
+ }
2812
+ };
2813
+ //#endregion
2814
+ //#region src/runtime/sql/sqlString.ts
2815
+ const { escape, escapeId } = sqlstring.default;
2816
+ const SqlString = {
2817
+ escape: (value) => escape(value, true),
2818
+ escapeId: (name) => escapeId(name)
2819
+ };
2820
+ //#endregion
2821
+ //#region src/db/sql/columnToSql.ts
2822
+ const columnToSql = (column) => {
2823
+ const words = [SqlString.escapeId(column.columnName), column.type];
2824
+ if (column.length) words.push(`(${[column.length, column.scale].filter((it) => it !== void 0).join(",")})`);
2825
+ if (column.signed === true) words.push("SIGNED");
2826
+ else if (column.signed === false) words.push("UNSIGNED");
2827
+ if (column.zerofill) words.push("ZEROFILL");
2828
+ if (column.autoIncrement) words.push("AUTO_INCREMENT");
2829
+ if (column.notNull) words.push("NOT NULL");
2830
+ else if (!column.notNull) words.push("NULL");
2831
+ if ((column.type === "timestamp" || column.type === "datetime") && column.default === "CURRENT_TIMESTAMP") words.push("DEFAULT CURRENT_TIMESTAMP");
2832
+ else if (column.default !== void 0) words.push("DEFAULT " + SqlString.escape(column.default));
2833
+ if (column.onUpdateCurrentTimeStamp) words.push("ON UPDATE CURRENT_TIMESTAMP");
2834
+ return words.join(" ");
2835
+ };
2836
+ //#endregion
2837
+ //#region src/migration/serializable/column.ts
2838
+ var BaseColumn = class {
2839
+ constructor(data, table) {
2840
+ this.data = data;
2841
+ this.table = table;
2842
+ }
2843
+ fieldName() {
2844
+ return this.data.fieldName;
2845
+ }
2846
+ columnName() {
2847
+ return this.data.columnName;
2848
+ }
2849
+ dataType() {
2850
+ return this.data.type;
2851
+ }
2852
+ tsType() {
2853
+ return columnTypeToTsType(this.dataType());
2854
+ }
2855
+ gqlType() {
2856
+ return columnTypeToGqlPrimitive(this.dataType());
2857
+ }
2858
+ isNullable() {
2859
+ return !this.data.notNull;
2860
+ }
2861
+ isNullableOnCreate() {
2862
+ return !this.data.notNull || this.data.default !== void 0 || this.data.autoIncrement;
2863
+ }
2864
+ isReference() {
2865
+ return this.data.hasReference;
2866
+ }
2867
+ serialize() {
2868
+ return JSON.parse(JSON.stringify(this.data));
2869
+ }
2870
+ toSql() {
2871
+ return columnToSql(this.data);
2872
+ }
2873
+ isPrimary() {
2874
+ return this.table.primaryKey.includes(this.columnName());
2875
+ }
2876
+ isUpdatable() {
2877
+ return !(this.isPrimary() || this.data.onUpdateCurrentTimeStamp);
2878
+ }
2879
+ };
2880
+ var NormalColumn = class extends BaseColumn {
2881
+ constructor(data, table) {
2882
+ super(data, table);
2883
+ this.data = data;
2884
+ }
2885
+ addReference(reference) {
2886
+ return new ReferenceColumn({
2887
+ ...this.data,
2888
+ hasReference: true,
2889
+ reference
2890
+ }, this.table);
2891
+ }
2892
+ };
2893
+ var ReferenceColumn = class extends BaseColumn {
2894
+ constructor(data, table) {
2895
+ super(data, table);
2896
+ this.data = data;
2897
+ }
2898
+ getConstraintName() {
2899
+ return `ref_${this.table.tableName}_${this.fieldName()}__${this.data.reference.parentTable}_${this.data.reference.parentColumn}`;
2900
+ }
2901
+ };
2902
+ //#endregion
2903
+ //#region src/migration/data/index.ts
2904
+ var DBIndex = class {
2905
+ constructor(tableName, columns) {
2906
+ this.tableName = tableName;
2907
+ this.columns = columns;
2908
+ this.constraintName = this.toConstraintName(columns);
2909
+ }
2910
+ toConstraintName(columns) {
2911
+ return `index_${this.tableName}__${columns.join("_")}`;
2912
+ }
2913
+ addSql() {
2914
+ return `ALTER TABLE ${this.tableName} ADD INDEX ${this.constraintName}(${this.columns.join(",")})`;
2915
+ }
2916
+ dropSql() {
2917
+ return `DROP INDEX ${this.constraintName} ON ${this.tableName}`;
2918
+ }
2919
+ serialize() {
2920
+ return {
2921
+ constraintName: this.constraintName,
2922
+ columns: this.columns
2923
+ };
2924
+ }
2925
+ };
2926
+ //#endregion
2927
+ //#region src/migration/functions/assembleColumn.ts
2928
+ const assembleColumn = (data, table) => {
2929
+ if (data.hasReference) return new ReferenceColumn(data, table);
2930
+ return new NormalColumn(data, table);
2931
+ };
2932
+ //#endregion
2933
+ //#region src/migration/serialized/serializedColumn.ts
2934
+ const defaultColumnOption = {
2935
+ updatable: true,
2936
+ autoIncrementHashId: false
2937
+ };
2938
+ const referenceToSql = (constraintName, ref) => {
2939
+ const onUpdate = ref.onUpdate ? ` ON UPDATE ${ref.onUpdate}` : "";
2940
+ const onDelete = ref.onDelete ? ` ON DELETE ${ref.onDelete}` : "";
2941
+ return `CONSTRAINT ${constraintName} FOREIGN KEY(${ref.columnName}) REFERENCES ${SqlString.escapeId(ref.parentTable)}(${SqlString.escapeId(ref.parentColumn)})` + onUpdate + onDelete;
2942
+ };
2943
+ //#endregion
2944
+ //#region src/migration/serializable/table.ts
2945
+ var TableHandler = class {
2946
+ get index() {
2947
+ return this.indexes;
2948
+ }
2949
+ get columns() {
2950
+ return this._columns;
2951
+ }
2952
+ get virtualRelations() {
2953
+ return this._virtualRelations;
2954
+ }
2955
+ addVirtualRelation(relation) {
2956
+ this._virtualRelations.push({
2957
+ ...relation,
2958
+ childTable: this.tableName
2959
+ });
2960
+ }
2961
+ get gqlOption() {
2962
+ return this._gqlOption;
2963
+ }
2964
+ constructor(table, store) {
2965
+ this.store = store;
2966
+ this._gqlOption = defaultGQLOption();
2967
+ this.tableName = table.tableName;
2968
+ this.primaryKey = table.primaryKey || [];
2969
+ this.uniqueKeys = table.uniqueKeys || [];
2970
+ this.indexes = table.indexes?.map((it) => new DBIndex(this.tableName, it.columns)) || [];
2971
+ this._gqlOption = table.gqlOption || defaultGQLOption();
2972
+ this._columns = (table.columns || []).map((it) => assembleColumn(it, this));
2973
+ this._virtualRelations = table.virtualRelations || [];
2974
+ }
2975
+ column(columnName) {
2976
+ const column = this.columns.find((it) => it.columnName() === columnName);
2977
+ if (!column) throw new Error(`${this.tableName}.${columnName} is Not Found`);
2978
+ return column;
2979
+ }
2980
+ addColumn(column, isPrimary = false, isUnique = false) {
2981
+ this.columns.push(column);
2982
+ if (isPrimary) this.setPrimaryKey(column.columnName());
2983
+ if (isUnique) this.addUniqueKey(column.columnName());
2984
+ }
2985
+ dropColumn(columnName) {
2986
+ this._columns = this._columns.filter((it) => it.fieldName() !== columnName);
2987
+ }
2988
+ serialize() {
2989
+ return {
2990
+ columns: this.columns.map((it) => it.serialize()),
2991
+ primaryKey: this.primaryKey,
2992
+ uniqueKeys: this.uniqueKeys,
2993
+ indexes: this.indexes,
2994
+ tableName: this.tableName,
2995
+ gqlOption: JSON.parse(JSON.stringify(this.gqlOption)),
2996
+ virtualRelations: this._virtualRelations
2997
+ };
2998
+ }
2999
+ addReferences(ref, fieldName, notNull = true) {
3000
+ const data = {
3001
+ ...this.store.table(ref.parentTable).column(ref.parentColumn).serialize(),
3002
+ hasReference: true,
3003
+ fieldName: fieldName || ref.columnName,
3004
+ columnName: ref.columnName,
3005
+ notNull,
3006
+ default: void 0,
3007
+ zerofill: false,
3008
+ autoIncrement: false,
3009
+ defaultCurrentTimeStamp: false,
3010
+ onUpdateCurrentTimeStamp: false,
3011
+ reference: ref
3012
+ };
3013
+ this.columns.push(new ReferenceColumn(data, this));
3014
+ return this;
3015
+ }
3016
+ getIndexConstraintName(columns) {
3017
+ return `index_${this.tableName}__${columns.join("_")}`;
3018
+ }
3019
+ addIndex(...columns) {
3020
+ this.indexes.push(new DBIndex(this.tableName, columns));
3021
+ return this;
3022
+ }
3023
+ removeIndex(...columns) {
3024
+ const constraint = this.getIndexConstraintName(columns);
3025
+ this.indexes = this.indexes.filter((it) => it.constraintName !== constraint);
3026
+ return this;
3027
+ }
3028
+ addUniqueKey(...columnNames) {
3029
+ if (columnNames.length === 0) throw new SasatError("No column name specified");
3030
+ this.uniqueKeys.push(columnNames);
3031
+ return this;
3032
+ }
3033
+ setPrimaryKey(...columnNames) {
3034
+ if (columnNames.length === 0) throw new Error("Primary key is required");
3035
+ this.primaryKey = columnNames;
3036
+ return this;
3037
+ }
3038
+ showCreateTable() {
3039
+ const rows = [...this.columns.map((it) => it.toSql())];
3040
+ if (this.primaryKey.length !== 0) rows.push(`PRIMARY KEY (${this.primaryKey.map(SqlString.escapeId).join(",")})`);
3041
+ this.uniqueKeys.forEach((it) => {
3042
+ if (this.uniqueKeys.length !== 0) rows.push(`UNIQUE KEY (${it.join(",")})`);
3043
+ });
3044
+ rows.push(...this._columns.filter((it) => it.isReference() && !it.data.reference.noFKey).map((it) => {
3045
+ const ref = it;
3046
+ return referenceToSql(ref.getConstraintName(), ref.data.reference);
3047
+ }));
3048
+ return `CREATE TABLE ${SqlString.escapeId(this.tableName)}
3049
+ (
3050
+ ${rows.join(", ")}
3051
+ )`;
3052
+ }
3053
+ hasColumn(columnName) {
3054
+ return !!this.columns.find((it) => it.columnName() === columnName);
3055
+ }
3056
+ isColumnPrimary(columnName) {
3057
+ return this.primaryKey.includes(columnName);
3058
+ }
3059
+ getEntityName() {
3060
+ return EntityName.fromTableName(this.tableName);
3061
+ }
3062
+ setGQLOption(option) {
3063
+ this._gqlOption = {
3064
+ ...this.gqlOption,
3065
+ ...option
3066
+ };
3067
+ }
3068
+ getReferenceColumns() {
3069
+ return this.columns.filter((it) => it.isReference());
3070
+ }
3071
+ addForeignKey(reference) {
3072
+ const columnName = reference.columnName;
3073
+ const column1 = this.column(columnName);
3074
+ if (!column1) throw new Error("Column: `" + columnName + "` Not Found");
3075
+ if (column1.isReference()) throw new Error("Column: `" + columnName + "`already has reference, multiple reference is not supported");
3076
+ const ref = column1.addReference(reference);
3077
+ this._columns = this.columns.map((it) => it.columnName() === columnName ? ref : it);
3078
+ }
3079
+ changeType(columnName, type) {
3080
+ this.updateColumn(columnName, { type });
3081
+ }
3082
+ setDefault(columnName, value) {
3083
+ this.updateColumn(columnName, { default: value });
3084
+ }
3085
+ updateColumn(columnName, diff) {
3086
+ const update = (column) => {
3087
+ if (column.isReference()) return new ReferenceColumn({
3088
+ ...column.serialize(),
3089
+ ...diff
3090
+ }, this);
3091
+ return new NormalColumn({
3092
+ ...column.serialize(),
3093
+ ...diff
3094
+ }, this);
3095
+ };
3096
+ if (!this.column(columnName)) throw new Error(this.tableName + "." + columnName + " Not Found");
3097
+ this._columns = this.columns.map((it) => it.columnName() === columnName ? update(it) : it);
3098
+ }
3099
+ getPrimaryKeyColumns() {
3100
+ return this.columns.filter((it) => this.primaryKey.includes(it.columnName()));
3101
+ }
3102
+ };
3103
+ //#endregion
3104
+ //#region src/migration/creators/columnBuilder.ts
3105
+ var ColumnBuilderBase = class {
3106
+ constructor(columnName) {
3107
+ this.columnName = columnName;
3108
+ this._primary = false;
3109
+ this._notNull = true;
3110
+ this._unique = false;
3111
+ this._option = defaultColumnOption;
3112
+ this._fieldName = columnName;
3113
+ }
3114
+ fieldName(fieldName) {
3115
+ this._fieldName = fieldName;
3116
+ return this;
3117
+ }
3118
+ notNull() {
3119
+ this._notNull = true;
3120
+ return this;
3121
+ }
3122
+ nullable() {
3123
+ this._notNull = false;
3124
+ return this;
3125
+ }
3126
+ primary() {
3127
+ this._primary = true;
3128
+ return this;
3129
+ }
3130
+ unique() {
3131
+ this._unique = true;
3132
+ return this;
3133
+ }
3134
+ updatable(updatable) {
3135
+ this._option = {
3136
+ ...this._option,
3137
+ updatable
3138
+ };
3139
+ return this;
3140
+ }
3141
+ };
3142
+ var ColumnBuilder = class extends ColumnBuilderBase {
3143
+ constructor(name, type, length, scale) {
3144
+ super(name);
3145
+ this.type = type;
3146
+ this.length = length;
3147
+ this.scale = scale;
3148
+ this._zerofill = false;
3149
+ this._autoIncrement = false;
3150
+ this._defaultCurrentTimeStamp = false;
3151
+ this._onUpdateCurrentTimeStamp = false;
3152
+ this._fieldName = name;
3153
+ }
3154
+ default(value) {
3155
+ this._default = value;
3156
+ return this;
3157
+ }
3158
+ build() {
3159
+ return {
3160
+ data: {
3161
+ hasReference: false,
3162
+ columnName: this.columnName,
3163
+ fieldName: this._fieldName,
3164
+ type: this.type,
3165
+ length: this.length,
3166
+ scale: this.scale,
3167
+ notNull: this._notNull,
3168
+ zerofill: this._zerofill,
3169
+ signed: this._signed,
3170
+ autoIncrement: this._autoIncrement,
3171
+ default: this._default,
3172
+ defaultCurrentTimeStamp: this._defaultCurrentTimeStamp,
3173
+ onUpdateCurrentTimeStamp: this._onUpdateCurrentTimeStamp,
3174
+ option: this._option
3175
+ },
3176
+ isPrimary: this._primary,
3177
+ isUnique: this._unique
3178
+ };
3179
+ }
3180
+ };
3181
+ var StringColumnBuilder = class extends ColumnBuilder {
3182
+ constructor(name, type, length) {
3183
+ super(name, type);
3184
+ this.name = name;
3185
+ this.type = type;
3186
+ this.length = length;
3187
+ }
3188
+ default(value) {
3189
+ this._default = value;
3190
+ return this;
3191
+ }
3192
+ };
3193
+ var TextColumnBuilder = class extends ColumnBuilder {
3194
+ constructor(name, type) {
3195
+ super(name, type);
3196
+ this.name = name;
3197
+ this.type = type;
3198
+ }
3199
+ default(value) {
3200
+ this._default = value;
3201
+ return this;
3202
+ }
3203
+ };
3204
+ var NumberColumnBuilder = class extends ColumnBuilder {
3205
+ signed() {
3206
+ this._signed = true;
3207
+ return this;
3208
+ }
3209
+ unsigned() {
3210
+ this._signed = false;
3211
+ return this;
3212
+ }
3213
+ zerofill() {
3214
+ this._zerofill = true;
3215
+ return this;
3216
+ }
3217
+ default(value) {
3218
+ this._default = value;
3219
+ return this;
3220
+ }
3221
+ };
3222
+ var IntegerColumnBuilder = class extends NumberColumnBuilder {
3223
+ constructor(name, type, length) {
3224
+ super(name, type, length);
3225
+ this.name = name;
3226
+ this.type = type;
3227
+ this.length = length;
3228
+ }
3229
+ autoIncrement() {
3230
+ this._autoIncrement = true;
3231
+ return this;
3232
+ }
3233
+ };
3234
+ var FloatColumnBuilder = class extends NumberColumnBuilder {
3235
+ constructor(name, type, length, scale) {
3236
+ super(name, type, length, scale);
3237
+ this.name = name;
3238
+ this.type = type;
3239
+ this.length = length;
3240
+ this.scale = scale;
3241
+ }
3242
+ autoIncrement() {
3243
+ this._autoIncrement = true;
3244
+ return this;
3245
+ }
3246
+ };
3247
+ var DecimalColumnBuilder = class extends NumberColumnBuilder {
3248
+ constructor(name, type, length, scale) {
3249
+ super(name, type, length, scale);
3250
+ this.name = name;
3251
+ this.type = type;
3252
+ this.length = length;
3253
+ this.scale = scale;
3254
+ }
3255
+ };
3256
+ var DateColumnBuilder = class extends ColumnBuilder {
3257
+ constructor(name, type) {
3258
+ super(name, type);
3259
+ this.name = name;
3260
+ this.type = type;
3261
+ }
3262
+ default(value) {
3263
+ this._default = value;
3264
+ return this;
3265
+ }
3266
+ };
3267
+ var TimeStampColumnBuilder = class extends ColumnBuilder {
3268
+ constructor(name, type) {
3269
+ super(name, type);
3270
+ this.name = name;
3271
+ this.type = type;
3272
+ }
3273
+ default(value) {
3274
+ this._default = value;
3275
+ return this;
3276
+ }
3277
+ defaultCurrentTimeStamp() {
3278
+ this._defaultCurrentTimeStamp = true;
3279
+ return this.default("CURRENT_TIMESTAMP");
3280
+ }
3281
+ onUpdateCurrentTimeStamp() {
3282
+ this._onUpdateCurrentTimeStamp = true;
3283
+ return this;
3284
+ }
3285
+ };
3286
+ var ReferenceColumnBuilder = class extends ColumnBuilderBase {
3287
+ constructor(ref, parent) {
3288
+ super(ref.columnName);
3289
+ this.ref = ref;
3290
+ this.parent = parent;
3291
+ this._option = {
3292
+ ...this._option,
3293
+ updatable: false
3294
+ };
3295
+ }
3296
+ notNull() {
3297
+ this._notNull = true;
3298
+ return this;
3299
+ }
3300
+ nullable() {
3301
+ this._notNull = false;
3302
+ return this;
3303
+ }
3304
+ primary() {
3305
+ this._primary = true;
3306
+ return this;
3307
+ }
3308
+ unique() {
3309
+ this._unique = true;
3310
+ return this;
3311
+ }
3312
+ build() {
3313
+ return {
3314
+ data: {
3315
+ ...this.parent.serialize(),
3316
+ hasReference: true,
3317
+ fieldName: this._fieldName,
3318
+ columnName: this.columnName,
3319
+ notNull: this._notNull,
3320
+ default: void 0,
3321
+ autoIncrement: false,
3322
+ defaultCurrentTimeStamp: false,
3323
+ onUpdateCurrentTimeStamp: false,
3324
+ reference: this.ref,
3325
+ option: this._option
3326
+ },
3327
+ isPrimary: this._primary,
3328
+ isUnique: this._unique
3329
+ };
3330
+ }
3331
+ };
3332
+ var AutoIncrementIDColumnBuilder = class extends ColumnBuilderBase {
3333
+ constructor(columnName, option) {
3334
+ super(columnName);
3335
+ this.option = option;
3336
+ this._option = {
3337
+ ...this._option,
3338
+ updatable: false,
3339
+ autoIncrementHashId: true,
3340
+ hashSalt: option?.salt
3341
+ };
3342
+ }
3343
+ build() {
3344
+ return {
3345
+ data: {
3346
+ hasReference: false,
3347
+ fieldName: this._fieldName,
3348
+ columnName: this.columnName,
3349
+ type: this.option?.bigint ? "bigint" : "int",
3350
+ notNull: true,
3351
+ default: void 0,
3352
+ zerofill: false,
3353
+ signed: false,
3354
+ autoIncrement: true,
3355
+ length: void 0,
3356
+ scale: void 0,
3357
+ defaultCurrentTimeStamp: false,
3358
+ onUpdateCurrentTimeStamp: false,
3359
+ option: this._option
3360
+ },
3361
+ isPrimary: true,
3362
+ isUnique: false
3363
+ };
3364
+ }
3365
+ };
3366
+ //#endregion
3367
+ //#region src/migration/creators/columnCreator.ts
3368
+ var ColumnCreator = class {
3369
+ constructor(table, name) {
3370
+ this.table = table;
3371
+ this.name = name;
3372
+ this.char = (length) => this.create(new StringColumnBuilder(this.name, "char", length));
3373
+ this.varchar = (length) => this.create(new StringColumnBuilder(this.name, "varchar", length));
3374
+ this.text = () => this.create(new TextColumnBuilder(this.name, "text"));
3375
+ this.tinyInt = (length) => this.create(new IntegerColumnBuilder(this.name, "tinyint", length));
3376
+ this.smallInt = (length) => this.create(new IntegerColumnBuilder(this.name, "smallint", length));
3377
+ this.mediumInt = (length) => this.create(new IntegerColumnBuilder(this.name, "mediumint", length));
3378
+ this.int = (length) => this.create(new IntegerColumnBuilder(this.name, "int", length));
3379
+ this.bigInt = (length) => this.create(new IntegerColumnBuilder(this.name, "bigint", length));
3380
+ this.float = (length, scale) => this.create(new FloatColumnBuilder(this.name, "float", length, scale));
3381
+ this.double = (length, scale) => this.create(new FloatColumnBuilder(this.name, "double", length, scale));
3382
+ this.decimal = (length, scale) => this.create(new DecimalColumnBuilder(this.name, "decimal", length, scale));
3383
+ this.year = () => this.create(new DateColumnBuilder(this.name, "year"));
3384
+ this.date = () => this.create(new DateColumnBuilder(this.name, "date"));
3385
+ this.time = () => this.create(new DateColumnBuilder(this.name, "time"));
3386
+ this.dateTime = () => this.create(new TimeStampColumnBuilder(this.name, "datetime"));
3387
+ this.timestamp = () => this.create(new TimeStampColumnBuilder(this.name, "timestamp"));
3388
+ }
3389
+ create(column) {
3390
+ this.table.addColumn(column);
3391
+ return column;
3392
+ }
3393
+ };
3394
+ //#endregion
3395
+ //#region src/migration/creators/tableCreator.ts
3396
+ var TableCreator = class {
3397
+ constructor(tableName, store) {
3398
+ this.tableName = tableName;
3399
+ this.store = store;
3400
+ this.columns = [];
3401
+ this.table = new TableHandler({ tableName }, store);
3402
+ }
3403
+ autoIncrementHashId(columnName, option) {
3404
+ this.addColumn(new AutoIncrementIDColumnBuilder(columnName, option));
3405
+ return this;
3406
+ }
3407
+ column(name) {
3408
+ return new ColumnCreator(this, name);
3409
+ }
3410
+ addVirtualRelation(relation) {
3411
+ this.table.addVirtualRelation(relation);
3412
+ return this;
3413
+ }
3414
+ addColumn(column) {
3415
+ if (this.table.hasColumn(column.columnName)) throw new Error(`${this.tableName}.${column.columnName} already exists`);
3416
+ this.columns.push(column);
3417
+ }
3418
+ addUniqueKey(...columnNames) {
3419
+ this.table.addUniqueKey(...columnNames);
3420
+ return this;
3421
+ }
3422
+ references(ref) {
3423
+ const column = new ReferenceColumnBuilder(ref, this.store.table(ref.parentTable).column(ref.parentColumn));
3424
+ this.addColumn(column);
3425
+ return column;
3426
+ }
3427
+ setPrimaryKey(...columnNames) {
3428
+ this.table.setPrimaryKey(...columnNames);
3429
+ return this;
3430
+ }
3431
+ create() {
3432
+ this.columns.forEach((column) => {
3433
+ const { data, isPrimary, isUnique } = column.build();
3434
+ this.table.addColumn(data.hasReference ? new ReferenceColumn(data, this.table) : new NormalColumn(data, this.table), isPrimary, isUnique);
3435
+ });
3436
+ return this.table;
3437
+ }
3438
+ createdAt() {
3439
+ this.column("createdAt").timestamp().defaultCurrentTimeStamp().notNull().updatable(false);
3440
+ return this;
3441
+ }
3442
+ updatedAt() {
3443
+ this.column("updatedAt").timestamp().defaultCurrentTimeStamp().onUpdateCurrentTimeStamp().notNull().updatable(false);
3444
+ return this;
3445
+ }
3446
+ addIndex(...columns) {
3447
+ this.table.addIndex(`index_${this.tableName}__${columns.join("_")}`, ...columns);
3448
+ return this;
3449
+ }
3450
+ enableGQL() {
3451
+ this.table.setGQLOption({
3452
+ ...this.table.gqlOption,
3453
+ enabled: true
3454
+ });
3455
+ return this;
3456
+ }
3457
+ setGQLOption(option) {
3458
+ this.table.setGQLOption(option);
3459
+ return this;
3460
+ }
3461
+ addGQLQuery(...query) {
3462
+ this.table.setGQLOption({ queries: [...this.table.gqlOption.queries, ...query] });
3463
+ return this;
3464
+ }
3465
+ addGQLMutation(...mutation) {
3466
+ this.table.setGQLOption({ mutations: [...this.table.gqlOption.mutations, ...mutation] });
3467
+ return this;
3468
+ }
3469
+ };
3470
+ //#endregion
3471
+ //#region src/db/sql/sqlCreater.ts
3472
+ const SqlCreator = {
3473
+ addColumn: (tableName, column) => `ALTER TABLE ${tableName} ADD COLUMN ${columnToSql(column)}`,
3474
+ dropColumn: (tableName, columnName) => `ALTER TABLE ${tableName} DROP COLUMN ${columnName}`,
3475
+ addUniqueKey: (tableName, columns) => `ALTER TABLE ${tableName} ADD UNIQUE ${columns.join("__")}(${columns.join(",")})`,
3476
+ addPrimaryKey: (tableName, columns) => `ALTER TABLE ${tableName} ADD PRIMARY KEY ${columns.join("__")}(${columns.join(",")})`,
3477
+ addForeignKey: (tableName, constraintName, reference) => {
3478
+ const onUpdate = reference.onUpdate ? " ON UPDATE " + reference.onUpdate : "";
3479
+ const onDelete = reference.onDelete ? " ON DELETE " + reference.onDelete : "";
3480
+ return `ALTER TABLE ${tableName} ADD CONSTRAINT '${constraintName}' FOREIGN KEY (${reference.columnName}) REFERENCES ${reference.parentTable}(${reference.parentColumn})${onUpdate}${onDelete}`;
3481
+ }
3482
+ };
3483
+ //#endregion
3484
+ //#region src/migration/creators/createColumn.ts
3485
+ const createColumn = (name) => ({
3486
+ char: (length) => new StringColumnBuilder(name, "char", length),
3487
+ varchar: (length) => new StringColumnBuilder(name, "varchar", length),
3488
+ text: () => new TextColumnBuilder(name, "text"),
3489
+ tinyInt: (length) => new IntegerColumnBuilder(name, "tinyint", length),
3490
+ smallInt: (length) => new IntegerColumnBuilder(name, "smallint", length),
3491
+ mediumInt: (length) => new IntegerColumnBuilder(name, "mediumint", length),
3492
+ int: (length) => new IntegerColumnBuilder(name, "int", length),
3493
+ bigInt: (length) => new IntegerColumnBuilder(name, "bigint", length),
3494
+ float: (length, scale) => new FloatColumnBuilder(name, "float", length, scale),
3495
+ double: (length, scale) => new FloatColumnBuilder(name, "double", length, scale),
3496
+ decimal: (length, scale) => new DecimalColumnBuilder(name, "decimal", length, scale),
3497
+ year: () => new DateColumnBuilder(name, "year"),
3498
+ date: () => new DateColumnBuilder(name, "date"),
3499
+ time: () => new DateColumnBuilder(name, "time"),
3500
+ dateTime: () => new TimeStampColumnBuilder(name, "datetime"),
3501
+ timestamp: () => new TimeStampColumnBuilder(name, "timestamp")
3502
+ });
3503
+ //#endregion
3504
+ //#region src/migration/front/tableMigrator.ts
3505
+ var TableMigrator = class TableMigrator {
3506
+ constructor(table, store) {
3507
+ this.table = table;
3508
+ this.store = store;
3509
+ }
3510
+ get primaryKey() {
3511
+ return this.table.primaryKey;
3512
+ }
3513
+ static deserialize(data, store) {
3514
+ return new TableMigrator(new TableHandler(data, store), store);
3515
+ }
3516
+ get tableName() {
3517
+ return this.table.tableName;
3518
+ }
3519
+ column(columnName) {
3520
+ return this.table.column(columnName);
3521
+ }
3522
+ showCreateTable() {
3523
+ return this.table.showCreateTable();
3524
+ }
3525
+ getIndexes() {
3526
+ return this.table.index;
3527
+ }
3528
+ serialize() {
3529
+ return this.table.serialize();
3530
+ }
3531
+ addIndex(...columns) {
3532
+ this.table.addIndex(...columns);
3533
+ const index = new DBIndex(this.tableName, columns);
3534
+ this.store.addQuery(index.addSql());
3535
+ return this;
3536
+ }
3537
+ removeIndex(...columns) {
3538
+ this.table.removeIndex(...columns);
3539
+ this.store.addQuery(new DBIndex(this.tableName, columns).dropSql());
3540
+ return this;
3541
+ }
3542
+ _addColumn(column) {
3543
+ this.table.addColumn(new NormalColumn(column, this.table));
3544
+ this.store.addQuery(SqlCreator.addColumn(this.tableName, column));
3545
+ return this;
3546
+ }
3547
+ addColumn(name, create) {
3548
+ const column = create(createColumn(name)).build();
3549
+ return this._addColumn(column.data);
3550
+ }
3551
+ dropColumn(columnName) {
3552
+ this.table.dropColumn(columnName);
3553
+ this.store.addQuery(SqlCreator.dropColumn(this.tableName, columnName));
3554
+ return this;
3555
+ }
3556
+ enableGQL() {
3557
+ this.table.setGQLOption({
3558
+ ...this.table.gqlOption,
3559
+ enabled: true
3560
+ });
3561
+ return this;
3562
+ }
3563
+ setGQLOption(option) {
3564
+ this.table.setGQLOption(option);
3565
+ return this;
3566
+ }
3567
+ addForeignKey(reference) {
3568
+ this.tableExists(reference.parentTable);
3569
+ this.table.addForeignKey(reference);
3570
+ const column = this.table.column(reference.columnName);
3571
+ const targetColumn = this.store.table(reference.parentTable).column(reference.parentColumn);
3572
+ if (!targetColumn) throw new Error("Column: " + reference.parentTable + "." + reference.parentColumn + " Not Exists");
3573
+ if (column.dataType() !== targetColumn.dataType()) throw new Error(`${this.tableName}.${reference.columnName} AND ${reference.parentTable}.${reference.parentColumn} is different Type( ${column.dataType()} != ${targetColumn.dataType()} )`);
3574
+ this.store.addQuery(SqlCreator.addForeignKey(this.tableName, column.getConstraintName(), reference));
3575
+ return this;
3576
+ }
3577
+ changeColumnType(columnName, type) {
3578
+ this.table.changeType(columnName, type);
3579
+ this.store.addQuery(`ALTER TABLE ${this.tableName} MODIFY ${columnName} ${type}`);
3580
+ return this;
3581
+ }
3582
+ tableExists(tableName) {
3583
+ if (!this.store.table(tableName)) throw new Error("QueryTable: " + tableName + " Not Exists");
3584
+ return true;
3585
+ }
3586
+ setDefault(columnName, value) {
3587
+ this.table.setDefault(columnName, value);
3588
+ this.store.addQuery(`ALTER TABLE ${this.tableName} ALTER ${columnName} SET DEFAULT ${SqlString.escape(value)}`);
3589
+ return this;
3590
+ }
3591
+ get gqlOption() {
3592
+ return this.table.gqlOption;
3593
+ }
3594
+ addGQLQuery(...queries) {
3595
+ this.table.setGQLOption({
3596
+ ...this.table.gqlOption,
3597
+ queries: [...this.table.gqlOption.queries, ...queries]
3598
+ });
3599
+ return this;
3600
+ }
3601
+ addGQLMutation(...mutations) {
3602
+ this.table.setGQLOption({
3603
+ ...this.table.gqlOption,
3604
+ mutations: [...this.table.gqlOption.mutations, ...mutations]
3605
+ });
3606
+ return this;
3607
+ }
3608
+ };
3609
+ //#endregion
3610
+ //#region src/migration/front/storeMigrator.ts
3611
+ var StoreMigrator = class StoreMigrator {
3612
+ constructor() {
3613
+ this.tables = [];
3614
+ this.migrationQueue = [];
3615
+ }
3616
+ static new() {
3617
+ if (node_fs.default.existsSync(node_path.default.join(config().migration.dir, "initialSchema.yml"))) return StoreMigrator.deserialize(readInitialSchema());
3618
+ return new StoreMigrator();
3619
+ }
3620
+ static deserialize(data) {
3621
+ const store = new StoreMigrator();
3622
+ store.tables = data.tables.map((it) => TableMigrator.deserialize(it, store));
3623
+ store.resetQueue();
3624
+ return store;
3625
+ }
3626
+ table(tableName) {
3627
+ const table = this.tables.find((it) => it.tableName === tableName);
3628
+ if (!table) throw new Error("QueryTable: " + tableName + " Not Found");
3629
+ return table;
3630
+ }
3631
+ addQuery(...query) {
3632
+ this.migrationQueue.push(...query);
3633
+ }
3634
+ createTable(tableName, tableCreator) {
3635
+ if (this.tables.find((it) => it.tableName === tableName)) throw new SasatError(`${tableName} is already exist`);
3636
+ const creator = new TableCreator(tableName, this);
3637
+ tableCreator(creator);
3638
+ const table = new TableMigrator(creator.create(), this);
3639
+ this.tables.push(table);
3640
+ this.addQuery(table.showCreateTable());
3641
+ this.addQuery(...table.getIndexes().map((it) => it.addSql()));
3642
+ return this;
3643
+ }
3644
+ dropTable(tableName) {
3645
+ this.addQuery(`DROP TABLE ${tableName}`);
3646
+ this.tables = this.tables.filter((it) => it.tableName !== tableName);
3647
+ return this;
3648
+ }
3649
+ sql(...sql) {
3650
+ this.addQuery(...sql);
3651
+ return this;
3652
+ }
3653
+ getSql() {
3654
+ return this.migrationQueue;
3655
+ }
3656
+ resetQueue() {
3657
+ this.migrationQueue = [];
3658
+ }
3659
+ serialize() {
3660
+ return { tables: this.tables.map((it) => it.serialize()) };
3661
+ }
3662
+ setConfig(conf) {
3663
+ this.conf = conf;
3664
+ return this;
3665
+ }
3666
+ getUpdateConfig() {
3667
+ return this.conf;
3668
+ }
3669
+ };
3670
+ //#endregion
3671
+ //#region src/db/formatQuery.ts
3672
+ const formatQuery = (str, ...params) => {
3673
+ let ret = str[0];
3674
+ for (let i = 0; i < params.length; i++) {
3675
+ if (typeof params[i] === "function") ret += params[i]();
3676
+ else if (Array.isArray(params[i])) ret += params[i].map((it) => SqlString.escape(it)).join(", ");
3677
+ else ret += SqlString.escape(params[i]);
3678
+ ret += str[i + 1];
3679
+ }
3680
+ return ret;
3681
+ };
3682
+ //#endregion
3683
+ //#region src/db/connectors/dbClient.ts
3684
+ const noop = () => {};
3685
+ var SQLClient = class {
3686
+ constructor() {
3687
+ this.logger = noop;
3688
+ }
3689
+ rawQuery(sql) {
3690
+ this.logger(sql);
3691
+ return this.execSql(sql);
3692
+ }
3693
+ rawCommand(sql) {
3694
+ this.logger(sql);
3695
+ return this.execSql(sql);
3696
+ }
3697
+ query(templateString, ...params) {
3698
+ return this.rawQuery(formatQuery(templateString, ...params));
3699
+ }
3700
+ command(templateString, ...params) {
3701
+ return this.rawCommand(formatQuery(templateString, ...params));
3702
+ }
3703
+ };
3704
+ var SQLTransaction = class extends SQLClient {};
3705
+ var DBClient = class extends SQLClient {
3706
+ constructor(logger = noop) {
3707
+ super();
3708
+ this._released = false;
3709
+ this.logger = logger;
3710
+ }
3711
+ isReleased() {
3712
+ return this._released;
3713
+ }
3714
+ };
3715
+ //#endregion
3716
+ //#region src/db/connectors/mysql/transaction.ts
3717
+ var MySqlTransaction = class extends SQLTransaction {
3718
+ constructor(connection) {
3719
+ super();
3720
+ this.connection = connection;
3721
+ }
3722
+ async commit() {
3723
+ const result = await this.connection.commit();
3724
+ await this.connection.end();
3725
+ return result;
3726
+ }
3727
+ async rollback() {
3728
+ await this.connection.rollback();
3729
+ await this.connection.end();
3730
+ }
3731
+ async execSql(sql) {
3732
+ return (await this.connection.query(sql))[0];
3733
+ }
3734
+ };
3735
+ //#endregion
3736
+ //#region src/db/connectors/mysql/poolClient.ts
3737
+ var MysqlPoolClient = class extends DBClient {
3738
+ constructor(poolOption, logger) {
3739
+ super(logger);
3740
+ this.poolOption = poolOption;
3741
+ this.pool = (0, mysql2_promise.createPool)({
3742
+ dateStrings: true,
3743
+ ...poolOption
3744
+ });
3745
+ this.release = this.release.bind(this);
3746
+ }
3747
+ async transaction() {
3748
+ const connection = await (0, mysql2_promise.createConnection)({
3749
+ ...config().db,
3750
+ dateStrings: true,
3751
+ ...this.poolOption
3752
+ });
3753
+ await connection.beginTransaction();
3754
+ return new MySqlTransaction(connection);
3755
+ }
3756
+ async release() {
3757
+ await this.pool.end();
3758
+ this._released = true;
3759
+ }
3760
+ async execSql(sql) {
3761
+ return (await this.pool.query(sql))[0];
3762
+ }
3763
+ };
3764
+ //#endregion
3765
+ //#region src/db/getDbClient.ts
3766
+ let client;
3767
+ const getDbClient = (option, logger) => {
3768
+ if (client && !client.isReleased()) return client;
3769
+ client = new MysqlPoolClient({
3770
+ ...config().db,
3771
+ ...option
3772
+ }, logger);
3773
+ return client;
3774
+ };
3775
+ //#endregion
3776
+ //#region src/migration/exec/getCurrentMigration.ts
3777
+ const calcRunMigrationFileNames = (records) => {
3778
+ const result = [];
3779
+ records.forEach((it) => {
3780
+ if (it.direction === "down") {
3781
+ if (result[result.length] !== it.name) throw new Error("Invalid migration history: `down` migration must be the same migration as the last `up` migration ");
3782
+ result.pop();
3783
+ return;
3784
+ }
3785
+ result.push(it.name);
3786
+ });
3787
+ return result;
3788
+ };
3789
+ const getCurrentMigration = async (options) => {
3790
+ const migrationTable = SqlString.escapeId(config().migration.table);
3791
+ const files = getMigrationFileNames();
3792
+ const client = getDbClient();
3793
+ const query = `CREATE TABLE IF NOT EXISTS ${migrationTable} (id int auto_increment primary key , name varchar(100) not null,direction enum('up', 'down') not null, migrated_at timestamp default current_timestamp)`;
3794
+ if (!options.silent) {
3795
+ Console.log(`creating migration table: ${migrationTable} :: ${Buffer.from(migrationTable).toString("base64")}`);
3796
+ Console.log(query);
3797
+ }
3798
+ await client.rawQuery(query);
3799
+ const q = `SELECT name, direction FROM ${migrationTable} ORDER BY id ASC`;
3800
+ if (!options.silent) Console.debug(q);
3801
+ const result = await client.rawQuery(q);
3802
+ console.debug(result);
3803
+ if (!result.length) return;
3804
+ const runs = calcRunMigrationFileNames(result);
3805
+ if (runs.length === 0) return;
3806
+ runs.forEach((run, i) => {
3807
+ if (files[i] !== run) throw new Error(`\
3808
+ Invalid migration order: Migration must be performed in the same order
3809
+ Found : ${files[i]}
3810
+ in migration history: ${run}`);
3811
+ });
3812
+ return runs[runs.length - 1];
3813
+ };
3814
+ //#endregion
3815
+ //#region src/migration/exec/migrationFileCompiler.ts
3816
+ const changeExtTsToJs = (fileName) => fileName.slice(0, -3) + ".mjs";
3817
+ const compileMigrationFiles = () => {
3818
+ const compiles = getMigrationFileNames().map(async (fileName) => {
3819
+ const filePath = node_path.default.join(getMigrationFileDir(), fileName);
3820
+ const r = await (0, esbuild.build)({
3821
+ entryPoints: [filePath],
3822
+ bundle: true,
3823
+ outfile: changeExtTsToJs(filePath),
3824
+ platform: "node",
3825
+ format: "esm",
3826
+ outExtension: { ".js": ".mjs" },
3827
+ banner: { js: `import { createRequire as topLevelCreateRequire } from 'module';
3828
+ const require = topLevelCreateRequire(import.meta.url);
3829
+ import { fileURLToPath as __topLevelFileURLToPath } from 'url';
3830
+ import { dirname as __topLevelDirname } from 'path';
3831
+ const __filename = __topLevelFileURLToPath(import.meta.url);
3832
+ const __dirname = __topLevelDirname(__filename);
3833
+ ` }
3834
+ });
3835
+ if (r.errors.length !== 0) throw r.errors;
3836
+ return fileName;
3837
+ });
3838
+ return Promise.all(compiles);
3839
+ };
3840
+ //#endregion
3841
+ //#region src/migration/exec/readMigrationFile.ts
3842
+ const readMigration = async (store, tsFileName, direction) => {
3843
+ const instance = new (await (import(node_path.default.join(process.cwd(), config().migration.dir, changeExtTsToJs(tsFileName))))).default();
3844
+ if (direction === "up") {
3845
+ if (instance.beforeUp) await instance.beforeUp();
3846
+ await instance.up(store);
3847
+ if (instance.afterUp) await instance.afterUp();
3848
+ } else {
3849
+ if (instance.beforeDown) await instance.beforeDown();
3850
+ await instance.down(store);
3851
+ if (instance.afterDown) await instance.afterDown();
3852
+ }
3853
+ return store;
3854
+ };
3855
+ //#endregion
3856
+ //#region src/migration/exec/createCurrentMigrationDataStore.ts
3857
+ const createCurrentMigrationDataStore = async (targetMigrationName) => {
3858
+ const allFiles = getMigrationFileNames();
3859
+ let store = StoreMigrator.new();
3860
+ if (!targetMigrationName) return store;
3861
+ const files = allFiles.slice(0, allFiles.indexOf(targetMigrationName) + 1);
3862
+ for (const tsFileName of files) store = await readMigration(store, tsFileName, "up");
3863
+ store.resetQueue();
3864
+ return store;
3865
+ };
3866
+ //#endregion
3867
+ //#region src/migration/exec/getMigrationTarget.ts
3868
+ const getMigrationTargets = (files, current) => {
3869
+ const currentIndex = current ? files.indexOf(current) + 1 : 0;
3870
+ const targetIndex = files.indexOf(config().migration.target || files[files.length - 1]) + 1;
3871
+ if (currentIndex === -1 || targetIndex === -1) throw new Error("migration target not found");
3872
+ if (targetIndex >= currentIndex) return {
3873
+ direction: "up",
3874
+ files: files.slice(currentIndex, targetIndex)
3875
+ };
3876
+ return {
3877
+ direction: "down",
3878
+ files: files.slice(targetIndex, currentIndex).reverse()
3879
+ };
3880
+ };
3881
+ //#endregion
3882
+ //#region src/migration/exec/runMigration.ts
3883
+ const runMigration = async (client, store, migrationName, direction, options) => {
3884
+ const sqls = store.getSql();
3885
+ const conf = store.getUpdateConfig();
3886
+ if (conf) setConfig(conf);
3887
+ store.resetQueue();
3888
+ if (!options.silent) sqls.forEach(Console.log);
3889
+ if (options.dry) return;
3890
+ const transaction = await client.transaction();
3891
+ try {
3892
+ for (const sql of sqls) await transaction.rawQuery(sql).catch((e) => {
3893
+ Console.error(`ERROR ON ${migrationName}`);
3894
+ Console.error(`SQL: ${sql}`);
3895
+ Console.error(`MESSAGE: ${e.message}`);
3896
+ process.exit(1);
3897
+ });
3898
+ await transaction.query`insert into ${() => config().migration.table} (name, direction) values (${[migrationName, direction]})`;
3899
+ return await transaction.commit();
3900
+ } catch (e) {
3901
+ await transaction.rollback();
3902
+ throw e;
3903
+ }
3904
+ };
3905
+ //#endregion
3906
+ //#region src/migration/controller.ts
3907
+ var MigrationController = class {
3908
+ async migrate(client, options) {
3909
+ const fileNames = getMigrationFileNames();
3910
+ console.log(4, options);
3911
+ const currentMigration = await getCurrentMigration(options);
3912
+ if (!options.silent) Console.log("--current migration--: " + currentMigration);
3913
+ console.log(2);
3914
+ let store = await createCurrentMigrationDataStore(currentMigration);
3915
+ if (store.getUpdateConfig()) setConfig(store.getUpdateConfig());
3916
+ console.log(1);
3917
+ const target = getMigrationTargets(fileNames, currentMigration);
3918
+ console.log(2);
3919
+ for (const tsFileName of target.files) {
3920
+ if (!options.silent) Console.log("---------\n" + tsFileName);
3921
+ console.log(3, tsFileName);
3922
+ store = await readMigration(store, tsFileName, target.direction);
3923
+ console.log(4);
3924
+ await runMigration(client, store, tsFileName, target.direction, options);
3925
+ store.resetQueue();
3926
+ }
3927
+ return {
3928
+ store: store.serialize(),
3929
+ currentMigration: config().migration.target || fileNames[fileNames.length - 1]
3930
+ };
3931
+ }
3932
+ };
3933
+ //#endregion
3934
+ //#region src/migration/dataStore.ts
3935
+ var DataStoreHandler = class {
3936
+ constructor(store) {
3937
+ this.tables = store.tables.map((it) => new TableHandler(it, this));
3938
+ }
3939
+ table(tableName) {
3940
+ const table = this.tables.find((it) => it.tableName === tableName);
3941
+ if (!table) throw new Error(`Table: ${tableName} is Not Found`);
3942
+ return table;
3943
+ }
3944
+ referencedBy(tableName) {
3945
+ return this.tables.flatMap((it) => it.columns.filter((it) => it.isReference() && it.data.reference.parentTable === tableName));
3946
+ }
3947
+ virtualReferencedBy(tableName) {
3948
+ return this.tables.flatMap((it) => it.virtualRelations.filter((it) => it.parentTable === tableName));
3949
+ }
3950
+ };
3951
+ //#endregion
3952
+ //#region src/cli/commands/migrate.ts
3953
+ const migrate = async (client, options) => {
3954
+ let current;
3955
+ if (!options.silent) Console.log("--migration started--");
3956
+ try {
3957
+ if (!options.skipBuild) await compileMigrationFiles();
3958
+ const conf = config();
3959
+ if (conf.migration.db) setConfig({ db: conf.migration.db });
3960
+ const result = await new MigrationController().migrate(client, options);
3961
+ current = result.currentMigration;
3962
+ if (options.generateFiles) {
3963
+ const storeHandler = new DataStoreHandler(result.store);
3964
+ writeCurrentSchema(result.store);
3965
+ await new CodeGen_v2(storeHandler).generate();
3966
+ }
3967
+ if (!options.silent) Console.success(`current migration is ${current}`);
3968
+ } catch (e) {
3969
+ Console.error(e.message);
3970
+ throw e;
3971
+ }
3972
+ };
3973
+ //#endregion
3974
+ Object.defineProperty(exports, "CodeGen_v2", {
3975
+ enumerable: true,
3976
+ get: function() {
3977
+ return CodeGen_v2;
3978
+ }
3979
+ });
3980
+ Object.defineProperty(exports, "Conditions", {
3981
+ enumerable: true,
3982
+ get: function() {
3983
+ return Conditions;
3984
+ }
3985
+ });
3986
+ Object.defineProperty(exports, "Console", {
3987
+ enumerable: true,
3988
+ get: function() {
3989
+ return Console;
3990
+ }
3991
+ });
3992
+ Object.defineProperty(exports, "DBClient", {
3993
+ enumerable: true,
3994
+ get: function() {
3995
+ return DBClient;
3996
+ }
3997
+ });
3998
+ Object.defineProperty(exports, "DBColumnTypes", {
3999
+ enumerable: true,
4000
+ get: function() {
4001
+ return DBColumnTypes;
4002
+ }
4003
+ });
4004
+ Object.defineProperty(exports, "DataStoreHandler", {
4005
+ enumerable: true,
4006
+ get: function() {
4007
+ return DataStoreHandler;
4008
+ }
4009
+ });
4010
+ Object.defineProperty(exports, "Directory", {
4011
+ enumerable: true,
4012
+ get: function() {
4013
+ return Directory;
4014
+ }
4015
+ });
4016
+ Object.defineProperty(exports, "MySqlTransaction", {
4017
+ enumerable: true,
4018
+ get: function() {
4019
+ return MySqlTransaction;
4020
+ }
4021
+ });
4022
+ Object.defineProperty(exports, "SasatError", {
4023
+ enumerable: true,
4024
+ get: function() {
4025
+ return SasatError;
4026
+ }
4027
+ });
4028
+ Object.defineProperty(exports, "SqlString", {
4029
+ enumerable: true,
4030
+ get: function() {
4031
+ return SqlString;
4032
+ }
4033
+ });
4034
+ Object.defineProperty(exports, "__toESM", {
4035
+ enumerable: true,
4036
+ get: function() {
4037
+ return __toESM;
4038
+ }
4039
+ });
4040
+ Object.defineProperty(exports, "assignDeep", {
4041
+ enumerable: true,
4042
+ get: function() {
4043
+ return assignDeep;
4044
+ }
4045
+ });
4046
+ Object.defineProperty(exports, "camelize", {
4047
+ enumerable: true,
4048
+ get: function() {
4049
+ return camelize;
4050
+ }
4051
+ });
4052
+ Object.defineProperty(exports, "capitalizeFirstLetter", {
4053
+ enumerable: true,
4054
+ get: function() {
4055
+ return capitalizeFirstLetter;
4056
+ }
4057
+ });
4058
+ Object.defineProperty(exports, "columnTypeToGqlPrimitive", {
4059
+ enumerable: true,
4060
+ get: function() {
4061
+ return columnTypeToGqlPrimitive;
4062
+ }
4063
+ });
4064
+ Object.defineProperty(exports, "compileMigrationFiles", {
4065
+ enumerable: true,
4066
+ get: function() {
4067
+ return compileMigrationFiles;
4068
+ }
4069
+ });
4070
+ Object.defineProperty(exports, "config", {
4071
+ enumerable: true,
4072
+ get: function() {
4073
+ return config;
4074
+ }
4075
+ });
4076
+ Object.defineProperty(exports, "createCurrentMigrationDataStore", {
4077
+ enumerable: true,
4078
+ get: function() {
4079
+ return createCurrentMigrationDataStore;
4080
+ }
4081
+ });
4082
+ Object.defineProperty(exports, "defaultColumnOption", {
4083
+ enumerable: true,
4084
+ get: function() {
4085
+ return defaultColumnOption;
4086
+ }
4087
+ });
4088
+ Object.defineProperty(exports, "defaultConf", {
4089
+ enumerable: true,
4090
+ get: function() {
4091
+ return defaultConf;
4092
+ }
4093
+ });
4094
+ Object.defineProperty(exports, "defaultGQLOption", {
4095
+ enumerable: true,
4096
+ get: function() {
4097
+ return defaultGQLOption;
4098
+ }
4099
+ });
4100
+ Object.defineProperty(exports, "formatQuery", {
4101
+ enumerable: true,
4102
+ get: function() {
4103
+ return formatQuery;
4104
+ }
4105
+ });
4106
+ Object.defineProperty(exports, "getDbClient", {
4107
+ enumerable: true,
4108
+ get: function() {
4109
+ return getDbClient;
4110
+ }
4111
+ });
4112
+ Object.defineProperty(exports, "getMigrationFileNames", {
4113
+ enumerable: true,
4114
+ get: function() {
4115
+ return getMigrationFileNames;
4116
+ }
4117
+ });
4118
+ Object.defineProperty(exports, "migrate", {
4119
+ enumerable: true,
4120
+ get: function() {
4121
+ return migrate;
4122
+ }
4123
+ });
4124
+ Object.defineProperty(exports, "mkDirIfNotExist", {
4125
+ enumerable: true,
4126
+ get: function() {
4127
+ return mkDirIfNotExist;
4128
+ }
4129
+ });
4130
+ Object.defineProperty(exports, "nonNullable", {
4131
+ enumerable: true,
4132
+ get: function() {
4133
+ return nonNullable;
4134
+ }
4135
+ });
4136
+ Object.defineProperty(exports, "pick", {
4137
+ enumerable: true,
4138
+ get: function() {
4139
+ return pick;
4140
+ }
4141
+ });
4142
+ Object.defineProperty(exports, "setConfig", {
4143
+ enumerable: true,
4144
+ get: function() {
4145
+ return setConfig;
4146
+ }
4147
+ });
4148
+ Object.defineProperty(exports, "unique", {
4149
+ enumerable: true,
4150
+ get: function() {
4151
+ return unique;
4152
+ }
4153
+ });
4154
+ Object.defineProperty(exports, "writeCurrentSchema", {
4155
+ enumerable: true,
4156
+ get: function() {
4157
+ return writeCurrentSchema;
4158
+ }
4159
+ });
4160
+ Object.defineProperty(exports, "writeYmlFile", {
4161
+ enumerable: true,
4162
+ get: function() {
4163
+ return writeYmlFile;
4164
+ }
4165
+ });