drizzle-kit 0.20.3 → 0.20.4-38bea13

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,3410 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined")
11
+ return require.apply(this, arguments);
12
+ throw new Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __esm = (fn, res) => function __init() {
15
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
+ };
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+
37
+ // node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/vendor/ansi-styles/index.js
38
+ function assembleStyles() {
39
+ const codes = /* @__PURE__ */ new Map();
40
+ for (const [groupName, group] of Object.entries(styles)) {
41
+ for (const [styleName, style] of Object.entries(group)) {
42
+ styles[styleName] = {
43
+ open: `\x1B[${style[0]}m`,
44
+ close: `\x1B[${style[1]}m`
45
+ };
46
+ group[styleName] = styles[styleName];
47
+ codes.set(style[0], style[1]);
48
+ }
49
+ Object.defineProperty(styles, groupName, {
50
+ value: group,
51
+ enumerable: false
52
+ });
53
+ }
54
+ Object.defineProperty(styles, "codes", {
55
+ value: codes,
56
+ enumerable: false
57
+ });
58
+ styles.color.close = "\x1B[39m";
59
+ styles.bgColor.close = "\x1B[49m";
60
+ styles.color.ansi = wrapAnsi16();
61
+ styles.color.ansi256 = wrapAnsi256();
62
+ styles.color.ansi16m = wrapAnsi16m();
63
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
64
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
65
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
66
+ Object.defineProperties(styles, {
67
+ rgbToAnsi256: {
68
+ value(red, green, blue) {
69
+ if (red === green && green === blue) {
70
+ if (red < 8) {
71
+ return 16;
72
+ }
73
+ if (red > 248) {
74
+ return 231;
75
+ }
76
+ return Math.round((red - 8) / 247 * 24) + 232;
77
+ }
78
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
79
+ },
80
+ enumerable: false
81
+ },
82
+ hexToRgb: {
83
+ value(hex) {
84
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
85
+ if (!matches) {
86
+ return [0, 0, 0];
87
+ }
88
+ let [colorString] = matches;
89
+ if (colorString.length === 3) {
90
+ colorString = [...colorString].map((character) => character + character).join("");
91
+ }
92
+ const integer = Number.parseInt(colorString, 16);
93
+ return [
94
+ /* eslint-disable no-bitwise */
95
+ integer >> 16 & 255,
96
+ integer >> 8 & 255,
97
+ integer & 255
98
+ /* eslint-enable no-bitwise */
99
+ ];
100
+ },
101
+ enumerable: false
102
+ },
103
+ hexToAnsi256: {
104
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
105
+ enumerable: false
106
+ },
107
+ ansi256ToAnsi: {
108
+ value(code) {
109
+ if (code < 8) {
110
+ return 30 + code;
111
+ }
112
+ if (code < 16) {
113
+ return 90 + (code - 8);
114
+ }
115
+ let red;
116
+ let green;
117
+ let blue;
118
+ if (code >= 232) {
119
+ red = ((code - 232) * 10 + 8) / 255;
120
+ green = red;
121
+ blue = red;
122
+ } else {
123
+ code -= 16;
124
+ const remainder = code % 36;
125
+ red = Math.floor(code / 36) / 5;
126
+ green = Math.floor(remainder / 6) / 5;
127
+ blue = remainder % 6 / 5;
128
+ }
129
+ const value = Math.max(red, green, blue) * 2;
130
+ if (value === 0) {
131
+ return 30;
132
+ }
133
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
134
+ if (value === 2) {
135
+ result += 60;
136
+ }
137
+ return result;
138
+ },
139
+ enumerable: false
140
+ },
141
+ rgbToAnsi: {
142
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
143
+ enumerable: false
144
+ },
145
+ hexToAnsi: {
146
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
147
+ enumerable: false
148
+ }
149
+ });
150
+ return styles;
151
+ }
152
+ var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
153
+ var init_ansi_styles = __esm({
154
+ "node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
155
+ ANSI_BACKGROUND_OFFSET = 10;
156
+ wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
157
+ wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
158
+ wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
159
+ styles = {
160
+ modifier: {
161
+ reset: [0, 0],
162
+ // 21 isn't widely supported and 22 does the same thing
163
+ bold: [1, 22],
164
+ dim: [2, 22],
165
+ italic: [3, 23],
166
+ underline: [4, 24],
167
+ overline: [53, 55],
168
+ inverse: [7, 27],
169
+ hidden: [8, 28],
170
+ strikethrough: [9, 29]
171
+ },
172
+ color: {
173
+ black: [30, 39],
174
+ red: [31, 39],
175
+ green: [32, 39],
176
+ yellow: [33, 39],
177
+ blue: [34, 39],
178
+ magenta: [35, 39],
179
+ cyan: [36, 39],
180
+ white: [37, 39],
181
+ // Bright color
182
+ blackBright: [90, 39],
183
+ gray: [90, 39],
184
+ // Alias of `blackBright`
185
+ grey: [90, 39],
186
+ // Alias of `blackBright`
187
+ redBright: [91, 39],
188
+ greenBright: [92, 39],
189
+ yellowBright: [93, 39],
190
+ blueBright: [94, 39],
191
+ magentaBright: [95, 39],
192
+ cyanBright: [96, 39],
193
+ whiteBright: [97, 39]
194
+ },
195
+ bgColor: {
196
+ bgBlack: [40, 49],
197
+ bgRed: [41, 49],
198
+ bgGreen: [42, 49],
199
+ bgYellow: [43, 49],
200
+ bgBlue: [44, 49],
201
+ bgMagenta: [45, 49],
202
+ bgCyan: [46, 49],
203
+ bgWhite: [47, 49],
204
+ // Bright color
205
+ bgBlackBright: [100, 49],
206
+ bgGray: [100, 49],
207
+ // Alias of `bgBlackBright`
208
+ bgGrey: [100, 49],
209
+ // Alias of `bgBlackBright`
210
+ bgRedBright: [101, 49],
211
+ bgGreenBright: [102, 49],
212
+ bgYellowBright: [103, 49],
213
+ bgBlueBright: [104, 49],
214
+ bgMagentaBright: [105, 49],
215
+ bgCyanBright: [106, 49],
216
+ bgWhiteBright: [107, 49]
217
+ }
218
+ };
219
+ modifierNames = Object.keys(styles.modifier);
220
+ foregroundColorNames = Object.keys(styles.color);
221
+ backgroundColorNames = Object.keys(styles.bgColor);
222
+ colorNames = [...foregroundColorNames, ...backgroundColorNames];
223
+ ansiStyles = assembleStyles();
224
+ ansi_styles_default = ansiStyles;
225
+ }
226
+ });
227
+
228
+ // node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/vendor/supports-color/index.js
229
+ import process2 from "node:process";
230
+ import os from "node:os";
231
+ import tty from "node:tty";
232
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
233
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
234
+ const position = argv.indexOf(prefix + flag);
235
+ const terminatorPosition = argv.indexOf("--");
236
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
237
+ }
238
+ function envForceColor() {
239
+ if ("FORCE_COLOR" in env) {
240
+ if (env.FORCE_COLOR === "true") {
241
+ return 1;
242
+ }
243
+ if (env.FORCE_COLOR === "false") {
244
+ return 0;
245
+ }
246
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
247
+ }
248
+ }
249
+ function translateLevel(level) {
250
+ if (level === 0) {
251
+ return false;
252
+ }
253
+ return {
254
+ level,
255
+ hasBasic: true,
256
+ has256: level >= 2,
257
+ has16m: level >= 3
258
+ };
259
+ }
260
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
261
+ const noFlagForceColor = envForceColor();
262
+ if (noFlagForceColor !== void 0) {
263
+ flagForceColor = noFlagForceColor;
264
+ }
265
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
266
+ if (forceColor === 0) {
267
+ return 0;
268
+ }
269
+ if (sniffFlags) {
270
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
271
+ return 3;
272
+ }
273
+ if (hasFlag("color=256")) {
274
+ return 2;
275
+ }
276
+ }
277
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
278
+ return 1;
279
+ }
280
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
281
+ return 0;
282
+ }
283
+ const min = forceColor || 0;
284
+ if (env.TERM === "dumb") {
285
+ return min;
286
+ }
287
+ if (process2.platform === "win32") {
288
+ const osRelease = os.release().split(".");
289
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
290
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
291
+ }
292
+ return 1;
293
+ }
294
+ if ("CI" in env) {
295
+ if ("GITHUB_ACTIONS" in env) {
296
+ return 3;
297
+ }
298
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
299
+ return 1;
300
+ }
301
+ return min;
302
+ }
303
+ if ("TEAMCITY_VERSION" in env) {
304
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
305
+ }
306
+ if (env.COLORTERM === "truecolor") {
307
+ return 3;
308
+ }
309
+ if (env.TERM === "xterm-kitty") {
310
+ return 3;
311
+ }
312
+ if ("TERM_PROGRAM" in env) {
313
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
314
+ switch (env.TERM_PROGRAM) {
315
+ case "iTerm.app": {
316
+ return version >= 3 ? 3 : 2;
317
+ }
318
+ case "Apple_Terminal": {
319
+ return 2;
320
+ }
321
+ }
322
+ }
323
+ if (/-256(color)?$/i.test(env.TERM)) {
324
+ return 2;
325
+ }
326
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
327
+ return 1;
328
+ }
329
+ if ("COLORTERM" in env) {
330
+ return 1;
331
+ }
332
+ return min;
333
+ }
334
+ function createSupportsColor(stream, options = {}) {
335
+ const level = _supportsColor(stream, {
336
+ streamIsTTY: stream && stream.isTTY,
337
+ ...options
338
+ });
339
+ return translateLevel(level);
340
+ }
341
+ var env, flagForceColor, supportsColor, supports_color_default;
342
+ var init_supports_color = __esm({
343
+ "node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/vendor/supports-color/index.js"() {
344
+ ({ env } = process2);
345
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
346
+ flagForceColor = 0;
347
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
348
+ flagForceColor = 1;
349
+ }
350
+ supportsColor = {
351
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
352
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
353
+ };
354
+ supports_color_default = supportsColor;
355
+ }
356
+ });
357
+
358
+ // node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/utilities.js
359
+ function stringReplaceAll(string, substring, replacer) {
360
+ let index = string.indexOf(substring);
361
+ if (index === -1) {
362
+ return string;
363
+ }
364
+ const substringLength = substring.length;
365
+ let endIndex = 0;
366
+ let returnValue = "";
367
+ do {
368
+ returnValue += string.slice(endIndex, index) + substring + replacer;
369
+ endIndex = index + substringLength;
370
+ index = string.indexOf(substring, endIndex);
371
+ } while (index !== -1);
372
+ returnValue += string.slice(endIndex);
373
+ return returnValue;
374
+ }
375
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
376
+ let endIndex = 0;
377
+ let returnValue = "";
378
+ do {
379
+ const gotCR = string[index - 1] === "\r";
380
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
381
+ endIndex = index + 1;
382
+ index = string.indexOf("\n", endIndex);
383
+ } while (index !== -1);
384
+ returnValue += string.slice(endIndex);
385
+ return returnValue;
386
+ }
387
+ var init_utilities = __esm({
388
+ "node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/utilities.js"() {
389
+ }
390
+ });
391
+
392
+ // node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/index.js
393
+ function createChalk(options) {
394
+ return chalkFactory(options);
395
+ }
396
+ var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr;
397
+ var init_source = __esm({
398
+ "node_modules/.pnpm/chalk@5.2.0/node_modules/chalk/source/index.js"() {
399
+ init_ansi_styles();
400
+ init_supports_color();
401
+ init_utilities();
402
+ init_ansi_styles();
403
+ ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
404
+ GENERATOR = Symbol("GENERATOR");
405
+ STYLER = Symbol("STYLER");
406
+ IS_EMPTY = Symbol("IS_EMPTY");
407
+ levelMapping = [
408
+ "ansi",
409
+ "ansi",
410
+ "ansi256",
411
+ "ansi16m"
412
+ ];
413
+ styles2 = /* @__PURE__ */ Object.create(null);
414
+ applyOptions = (object, options = {}) => {
415
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
416
+ throw new Error("The `level` option should be an integer from 0 to 3");
417
+ }
418
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
419
+ object.level = options.level === void 0 ? colorLevel : options.level;
420
+ };
421
+ chalkFactory = (options) => {
422
+ const chalk2 = (...strings) => strings.join(" ");
423
+ applyOptions(chalk2, options);
424
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
425
+ return chalk2;
426
+ };
427
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
428
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
429
+ styles2[styleName] = {
430
+ get() {
431
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
432
+ Object.defineProperty(this, styleName, { value: builder });
433
+ return builder;
434
+ }
435
+ };
436
+ }
437
+ styles2.visible = {
438
+ get() {
439
+ const builder = createBuilder(this, this[STYLER], true);
440
+ Object.defineProperty(this, "visible", { value: builder });
441
+ return builder;
442
+ }
443
+ };
444
+ getModelAnsi = (model, level, type, ...arguments_) => {
445
+ if (model === "rgb") {
446
+ if (level === "ansi16m") {
447
+ return ansi_styles_default[type].ansi16m(...arguments_);
448
+ }
449
+ if (level === "ansi256") {
450
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
451
+ }
452
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
453
+ }
454
+ if (model === "hex") {
455
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
456
+ }
457
+ return ansi_styles_default[type][model](...arguments_);
458
+ };
459
+ usedModels = ["rgb", "hex", "ansi256"];
460
+ for (const model of usedModels) {
461
+ styles2[model] = {
462
+ get() {
463
+ const { level } = this;
464
+ return function(...arguments_) {
465
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
466
+ return createBuilder(this, styler, this[IS_EMPTY]);
467
+ };
468
+ }
469
+ };
470
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
471
+ styles2[bgModel] = {
472
+ get() {
473
+ const { level } = this;
474
+ return function(...arguments_) {
475
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
476
+ return createBuilder(this, styler, this[IS_EMPTY]);
477
+ };
478
+ }
479
+ };
480
+ }
481
+ proto = Object.defineProperties(() => {
482
+ }, {
483
+ ...styles2,
484
+ level: {
485
+ enumerable: true,
486
+ get() {
487
+ return this[GENERATOR].level;
488
+ },
489
+ set(level) {
490
+ this[GENERATOR].level = level;
491
+ }
492
+ }
493
+ });
494
+ createStyler = (open, close, parent) => {
495
+ let openAll;
496
+ let closeAll;
497
+ if (parent === void 0) {
498
+ openAll = open;
499
+ closeAll = close;
500
+ } else {
501
+ openAll = parent.openAll + open;
502
+ closeAll = close + parent.closeAll;
503
+ }
504
+ return {
505
+ open,
506
+ close,
507
+ openAll,
508
+ closeAll,
509
+ parent
510
+ };
511
+ };
512
+ createBuilder = (self2, _styler, _isEmpty) => {
513
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
514
+ Object.setPrototypeOf(builder, proto);
515
+ builder[GENERATOR] = self2;
516
+ builder[STYLER] = _styler;
517
+ builder[IS_EMPTY] = _isEmpty;
518
+ return builder;
519
+ };
520
+ applyStyle = (self2, string) => {
521
+ if (self2.level <= 0 || !string) {
522
+ return self2[IS_EMPTY] ? "" : string;
523
+ }
524
+ let styler = self2[STYLER];
525
+ if (styler === void 0) {
526
+ return string;
527
+ }
528
+ const { openAll, closeAll } = styler;
529
+ if (string.includes("\x1B")) {
530
+ while (styler !== void 0) {
531
+ string = stringReplaceAll(string, styler.close, styler.open);
532
+ styler = styler.parent;
533
+ }
534
+ }
535
+ const lfIndex = string.indexOf("\n");
536
+ if (lfIndex !== -1) {
537
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
538
+ }
539
+ return openAll + string + closeAll;
540
+ };
541
+ Object.defineProperties(createChalk.prototype, styles2);
542
+ chalk = createChalk();
543
+ chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
544
+ }
545
+ });
546
+
547
+ // src/serializer/index.ts
548
+ import * as glob from "glob";
549
+ var init_serializer = __esm({
550
+ "src/serializer/index.ts"() {
551
+ init_source();
552
+ }
553
+ });
554
+
555
+ // src/cli/validations/outputs.ts
556
+ var init_outputs = __esm({
557
+ "src/cli/validations/outputs.ts"() {
558
+ init_source();
559
+ }
560
+ });
561
+
562
+ // src/serializer/pgSerializer.ts
563
+ import {
564
+ customType,
565
+ PgBigInt53Builder,
566
+ PgBigSerial53Builder,
567
+ PgBooleanBuilder,
568
+ PgCharBuilder,
569
+ PgCidrBuilder,
570
+ PgDateBuilder,
571
+ PgDialect,
572
+ PgDoublePrecisionBuilder,
573
+ PgInetBuilder,
574
+ PgIntegerBuilder,
575
+ PgIntervalBuilder,
576
+ PgJsonbBuilder,
577
+ PgJsonBuilder,
578
+ PgMacaddr8Builder,
579
+ PgMacaddrBuilder,
580
+ PgNumericBuilder,
581
+ PgRealBuilder,
582
+ pgSchema,
583
+ PgSerialBuilder,
584
+ PgSmallIntBuilder,
585
+ PgSmallSerialBuilder,
586
+ pgTable,
587
+ PgTextBuilder,
588
+ PgTimeBuilder,
589
+ PgTimestampBuilder,
590
+ PgUUIDBuilder,
591
+ PgVarcharBuilder,
592
+ PrimaryKeyBuilder,
593
+ uniqueKeyName
594
+ } from "drizzle-orm/pg-core";
595
+ import { getTableConfig } from "drizzle-orm/pg-core";
596
+ import { is, SQL, getTableName } from "drizzle-orm";
597
+ var dialect, trimChar, fromDatabase, columnToDefault, defaultForColumn, toDrizzle;
598
+ var init_pgSerializer = __esm({
599
+ "src/serializer/pgSerializer.ts"() {
600
+ init_serializer();
601
+ init_source();
602
+ init_outputs();
603
+ dialect = new PgDialect();
604
+ trimChar = (str, char) => {
605
+ let start = 0;
606
+ let end = str.length;
607
+ while (start < end && str[start] === char)
608
+ ++start;
609
+ while (end > start && str[end - 1] === char)
610
+ --end;
611
+ return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
612
+ };
613
+ fromDatabase = async (db, tablesFilter = (table) => true, schemaFilters, progressCallback) => {
614
+ const result = {};
615
+ const internals = { tables: {} };
616
+ const where = schemaFilters.map((t) => `table_schema = '${t}'`).join(" or ");
617
+ const allTables = await db.query(
618
+ `SELECT table_schema, table_name FROM information_schema.tables WHERE ${where};`
619
+ );
620
+ const schemas = new Set(allTables.map((it) => it.table_schema));
621
+ schemas.delete("public");
622
+ const allSchemas = await db.query(`select s.nspname as table_schema
623
+ from pg_catalog.pg_namespace s
624
+ join pg_catalog.pg_user u on u.usesysid = s.nspowner
625
+ where nspname not in ('information_schema', 'pg_catalog', 'public')
626
+ and nspname not like 'pg_toast%'
627
+ and nspname not like 'pg_temp_%'
628
+ order by table_schema;`);
629
+ allSchemas.forEach((item) => {
630
+ if (schemaFilters.includes(item.table_schema)) {
631
+ schemas.add(item.table_schema);
632
+ }
633
+ });
634
+ let columnsCount = 0;
635
+ let indexesCount = 0;
636
+ let foreignKeysCount = 0;
637
+ let tableCount = 0;
638
+ const all = allTables.map((row) => {
639
+ return new Promise(async (res, rej) => {
640
+ const tableName = row.table_name;
641
+ if (!tablesFilter(tableName))
642
+ return res("");
643
+ tableCount += 1;
644
+ const tableSchema = row.table_schema;
645
+ try {
646
+ const columnToReturn = {};
647
+ const indexToReturn = {};
648
+ const foreignKeysToReturn = {};
649
+ const primaryKeys = {};
650
+ const uniqueConstrains = {};
651
+ const tableResponse = await db.query(
652
+ `SELECT a.attrelid::regclass::text, a.attname, is_nullable, a.attndims as array_dimensions
653
+ , CASE WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[])
654
+ AND EXISTS (
655
+ SELECT FROM pg_attrdef ad
656
+ WHERE ad.adrelid = a.attrelid
657
+ AND ad.adnum = a.attnum
658
+ AND pg_get_expr(ad.adbin, ad.adrelid)
659
+ = 'nextval('''
660
+ || (pg_get_serial_sequence (a.attrelid::regclass::text
661
+ , a.attname))::regclass
662
+ || '''::regclass)'
663
+ )
664
+ THEN CASE a.atttypid
665
+ WHEN 'int'::regtype THEN 'serial'
666
+ WHEN 'int8'::regtype THEN 'bigserial'
667
+ WHEN 'int2'::regtype THEN 'smallserial'
668
+ END
669
+ ELSE format_type(a.atttypid, a.atttypmod)
670
+ END AS data_type, INFORMATION_SCHEMA.COLUMNS.table_name, INFORMATION_SCHEMA.COLUMNS.column_name, INFORMATION_SCHEMA.COLUMNS.column_default, INFORMATION_SCHEMA.COLUMNS.data_type as additional_dt
671
+ FROM pg_attribute a
672
+ JOIN INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.COLUMNS.column_name = a.attname
673
+ WHERE a.attrelid = '"${tableSchema}"."${tableName}"'::regclass and INFORMATION_SCHEMA.COLUMNS.table_name = '${tableName}'
674
+ AND a.attnum > 0
675
+ AND NOT a.attisdropped
676
+ ORDER BY a.attnum;`
677
+ );
678
+ const tableConstraints = await db.query(
679
+ `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
680
+ FROM information_schema.table_constraints tc
681
+ JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
682
+ JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
683
+ AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
684
+ WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
685
+ );
686
+ columnsCount += tableResponse.length;
687
+ if (progressCallback) {
688
+ progressCallback("columns", columnsCount, "fetching");
689
+ }
690
+ const tableForeignKeys = await db.query(
691
+ `SELECT
692
+ tc.table_schema,
693
+ tc.constraint_name,
694
+ tc.table_name,
695
+ kcu.column_name,
696
+ ccu.table_schema AS foreign_table_schema,
697
+ ccu.table_name AS foreign_table_name,
698
+ ccu.column_name AS foreign_column_name,
699
+ rc.delete_rule, rc.update_rule
700
+ FROM
701
+ information_schema.table_constraints AS tc
702
+ JOIN information_schema.key_column_usage AS kcu
703
+ ON tc.constraint_name = kcu.constraint_name
704
+ AND tc.table_schema = kcu.table_schema
705
+ JOIN information_schema.constraint_column_usage AS ccu
706
+ ON ccu.constraint_name = tc.constraint_name
707
+ AND ccu.table_schema = tc.table_schema
708
+ JOIN information_schema.referential_constraints AS rc
709
+ ON ccu.constraint_name = rc.constraint_name
710
+ WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='${tableName}' and tc.table_schema='${tableSchema}';`
711
+ );
712
+ foreignKeysCount += tableForeignKeys.length;
713
+ if (progressCallback) {
714
+ progressCallback("fks", foreignKeysCount, "fetching");
715
+ }
716
+ for (const fk of tableForeignKeys) {
717
+ const columnFrom = fk.column_name;
718
+ const tableTo = fk.foreign_table_name;
719
+ const columnTo = fk.foreign_column_name;
720
+ const foreignKeyName = fk.constraint_name;
721
+ const onUpdate = fk.update_rule.toLowerCase();
722
+ const onDelete = fk.delete_rule.toLowerCase();
723
+ if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
724
+ foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
725
+ foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
726
+ } else {
727
+ foreignKeysToReturn[foreignKeyName] = {
728
+ name: foreignKeyName,
729
+ tableFrom: tableName,
730
+ tableTo,
731
+ columnsFrom: [columnFrom],
732
+ columnsTo: [columnTo],
733
+ onDelete,
734
+ onUpdate
735
+ };
736
+ }
737
+ foreignKeysToReturn[foreignKeyName].columnsFrom = [
738
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
739
+ ];
740
+ foreignKeysToReturn[foreignKeyName].columnsTo = [
741
+ ...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)
742
+ ];
743
+ }
744
+ const uniqueConstrainsRows = tableConstraints.filter(
745
+ (mapRow) => mapRow.constraint_type === "UNIQUE"
746
+ );
747
+ for (const unqs of uniqueConstrainsRows) {
748
+ const columnName = unqs.column_name;
749
+ const constraintName = unqs.constraint_name;
750
+ if (typeof uniqueConstrains[constraintName] !== "undefined") {
751
+ uniqueConstrains[constraintName].columns.push(columnName);
752
+ } else {
753
+ uniqueConstrains[constraintName] = {
754
+ columns: [columnName],
755
+ nullsNotDistinct: false,
756
+ name: constraintName
757
+ };
758
+ }
759
+ }
760
+ for (const columnResponse of tableResponse) {
761
+ const columnName = columnResponse.attname;
762
+ const columnAdditionalDT = columnResponse.additional_dt;
763
+ const columnDimensions = columnResponse.array_dimensions;
764
+ let columnType = columnResponse.data_type;
765
+ const primaryKey = tableConstraints.filter(
766
+ (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
767
+ );
768
+ const cprimaryKey = tableConstraints.filter(
769
+ (mapRow) => mapRow.constraint_type === "PRIMARY KEY"
770
+ );
771
+ if (cprimaryKey.length > 1) {
772
+ const tableCompositePkName = await db.query(
773
+ `SELECT conname AS primary_key
774
+ FROM pg_constraint
775
+ WHERE contype = 'p'
776
+ AND connamespace = '${tableSchema}'::regnamespace
777
+ AND (conrelid::regclass::text = '"${tableName}"' OR conrelid::regclass::text = '${tableName}');`
778
+ );
779
+ primaryKeys[`${tableName}_${cprimaryKey.map((pk) => pk.column_name).join("_")}`] = {
780
+ name: tableCompositePkName[0].primary_key,
781
+ columns: cprimaryKey.map((c) => c.column_name)
782
+ };
783
+ }
784
+ const defaultValue = defaultForColumn(columnResponse);
785
+ const isSerial = columnType === "serial";
786
+ let columnTypeMapped = columnType;
787
+ if (columnTypeMapped.startsWith("numeric(")) {
788
+ columnTypeMapped = columnTypeMapped.replace(",", ", ");
789
+ }
790
+ if (columnAdditionalDT === "ARRAY") {
791
+ if (typeof internals.tables[tableName] === "undefined") {
792
+ internals.tables[tableName] = {
793
+ columns: {
794
+ [columnName]: {
795
+ isArray: true,
796
+ dimensions: columnDimensions,
797
+ rawType: columnTypeMapped.substring(
798
+ 0,
799
+ columnTypeMapped.length - 2
800
+ )
801
+ }
802
+ }
803
+ };
804
+ } else {
805
+ if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
806
+ internals.tables[tableName].columns[columnName] = {
807
+ isArray: true,
808
+ dimensions: columnDimensions,
809
+ rawType: columnTypeMapped.substring(
810
+ 0,
811
+ columnTypeMapped.length - 2
812
+ )
813
+ };
814
+ }
815
+ }
816
+ }
817
+ if (columnAdditionalDT === "ARRAY") {
818
+ for (let i = 1; i < Number(columnDimensions); i++) {
819
+ columnTypeMapped += "[]";
820
+ }
821
+ }
822
+ columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
823
+ columnTypeMapped = trimChar(columnTypeMapped, '"');
824
+ columnToReturn[columnName] = {
825
+ name: columnName,
826
+ type: columnTypeMapped,
827
+ primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
828
+ // default: isSerial ? undefined : defaultValue,
829
+ notNull: columnResponse.is_nullable === "NO"
830
+ };
831
+ if (!isSerial && typeof defaultValue !== "undefined") {
832
+ columnToReturn[columnName].default = defaultValue;
833
+ }
834
+ }
835
+ const dbIndexes = await db.query(
836
+ `SELECT t.relname as table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
837
+ FROM pg_class t
838
+ JOIN pg_index ix ON t.oid = ix.indrelid
839
+ JOIN pg_class i ON i.oid = ix.indexrelid
840
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
841
+ JOIN pg_namespace ns ON ns.oid = t.relnamespace
842
+ WHERE ns.nspname = '${tableSchema}'
843
+ AND t.relname = '${tableName}'
844
+ and ix.indisprimary = false;`
845
+ );
846
+ const dbIndexFromConstraint = await db.query(
847
+ `SELECT
848
+ idx.indexrelname AS index_name,
849
+ idx.relname AS table_name,
850
+ schemaname,
851
+ CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
852
+ FROM
853
+ pg_stat_user_indexes idx
854
+ LEFT JOIN
855
+ pg_constraint con ON con.conindid = idx.indexrelid
856
+ WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
857
+ group by index_name, table_name,schemaname, generated_by_constraint;`
858
+ );
859
+ const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map((it) => it.index_name);
860
+ for (const dbIndex of dbIndexes) {
861
+ const indexName2 = dbIndex.index_name;
862
+ const indexColumnName = dbIndex.column_name;
863
+ const indexIsUnique = dbIndex.is_unique;
864
+ if (idxsInConsteraint.includes(indexName2))
865
+ continue;
866
+ if (typeof indexToReturn[indexName2] !== "undefined") {
867
+ indexToReturn[indexName2].columns.push(indexColumnName);
868
+ } else {
869
+ indexToReturn[indexName2] = {
870
+ name: indexName2,
871
+ columns: [indexColumnName],
872
+ isUnique: indexIsUnique
873
+ };
874
+ }
875
+ }
876
+ indexesCount += Object.keys(indexToReturn).length;
877
+ if (progressCallback) {
878
+ progressCallback("indexes", indexesCount, "fetching");
879
+ }
880
+ result[tableName] = {
881
+ name: tableName,
882
+ schema: tableSchema !== "public" ? tableSchema : "",
883
+ columns: columnToReturn,
884
+ indexes: indexToReturn,
885
+ foreignKeys: foreignKeysToReturn,
886
+ compositePrimaryKeys: primaryKeys,
887
+ uniqueConstraints: uniqueConstrains
888
+ };
889
+ } catch (e) {
890
+ rej(e);
891
+ return;
892
+ }
893
+ res("");
894
+ });
895
+ });
896
+ if (progressCallback) {
897
+ progressCallback("tables", tableCount, "done");
898
+ }
899
+ for await (const _ of all) {
900
+ }
901
+ if (progressCallback) {
902
+ progressCallback("columns", columnsCount, "done");
903
+ progressCallback("indexes", indexesCount, "done");
904
+ progressCallback("fks", foreignKeysCount, "done");
905
+ }
906
+ const allEnums = await db.query(
907
+ `select n.nspname as enum_schema,
908
+ t.typname as enum_name,
909
+ e.enumlabel as enum_value
910
+ from pg_type t
911
+ join pg_enum e on t.oid = e.enumtypid
912
+ join pg_catalog.pg_namespace n ON n.oid = t.typnamespace;`
913
+ );
914
+ const enumsToReturn = {};
915
+ for (const dbEnum of allEnums) {
916
+ const enumName = dbEnum.enum_name;
917
+ const enumValue = dbEnum.enum_value;
918
+ if (enumsToReturn[enumName] !== void 0 && enumsToReturn[enumName] !== null) {
919
+ enumsToReturn[enumName].values[enumValue] = enumValue;
920
+ } else {
921
+ enumsToReturn[enumName] = {
922
+ name: enumName,
923
+ values: { [enumValue]: enumValue }
924
+ };
925
+ }
926
+ }
927
+ if (progressCallback) {
928
+ progressCallback("enums", Object.keys(enumsToReturn).length, "done");
929
+ }
930
+ const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
931
+ return {
932
+ version: "5",
933
+ dialect: "pg",
934
+ tables: result,
935
+ enums: enumsToReturn,
936
+ schemas: schemasObject,
937
+ _meta: {
938
+ schemas: {},
939
+ tables: {},
940
+ columns: {}
941
+ },
942
+ internal: internals
943
+ };
944
+ };
945
+ columnToDefault = {
946
+ "numeric(": "::numeric",
947
+ // text: "::text",
948
+ // "character varying": "::character varying",
949
+ // "double precision": "::double precision",
950
+ // "time with time zone": "::time with time zone",
951
+ "time without time zone": "::time without time zone",
952
+ // "timestamp with time zone": "::timestamp with time zone",
953
+ "timestamp without time zone": "::timestamp without time zone",
954
+ // date: "::date",
955
+ // interval: "::interval",
956
+ // character: "::bpchar",
957
+ // macaddr8: "::macaddr8",
958
+ // macaddr: "::macaddr",
959
+ // inet: "::inet",
960
+ // cidr: "::cidr",
961
+ // jsonb: "::jsonb",
962
+ // json: "::json",
963
+ "character(": "::bpchar"
964
+ };
965
+ defaultForColumn = (column) => {
966
+ if (column.data_type === "serial" || column.data_type === "smallserial" || column.data_type === "bigserial") {
967
+ return void 0;
968
+ }
969
+ const hasDifferentDefaultCast = Object.keys(columnToDefault).find(
970
+ (it) => column.data_type.startsWith(it)
971
+ );
972
+ if (column.column_default === null) {
973
+ return void 0;
974
+ }
975
+ const columnDefaultAsString = column.column_default.toString();
976
+ if (columnDefaultAsString.endsWith(
977
+ hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : column.data_type
978
+ )) {
979
+ const nonPrefixPart = column.column_default.length - (hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`).length - 1;
980
+ const rt = column.column_default.toString().substring(1, nonPrefixPart);
981
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(rt) && !column.data_type.startsWith("numeric")) {
982
+ return Number(rt);
983
+ } else if (column.data_type === "json" || column.data_type === "jsonb") {
984
+ const jsonWithoutSpaces = JSON.stringify(JSON.parse(rt));
985
+ return `'${jsonWithoutSpaces}'${hasDifferentDefaultCast ? columnToDefault[hasDifferentDefaultCast] : `::${column.data_type}`}`;
986
+ } else if (column.data_type === "boolean") {
987
+ return column.column_default === "true";
988
+ } else {
989
+ return `'${rt}'`;
990
+ }
991
+ } else {
992
+ if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString) && !column.data_type.startsWith("numeric")) {
993
+ return Number(columnDefaultAsString);
994
+ } else if (column.data_type === "boolean") {
995
+ return column.column_default === "true";
996
+ } else {
997
+ return `${columnDefaultAsString}`;
998
+ }
999
+ }
1000
+ };
1001
+ toDrizzle = (schema, schemaName) => {
1002
+ const tables = {};
1003
+ Object.values(schema.tables).forEach((t) => {
1004
+ const columns = {};
1005
+ Object.values(t.columns).forEach((c) => {
1006
+ const columnName = c.name;
1007
+ const type = c.type;
1008
+ let columnBuilder;
1009
+ if (type === "bigint") {
1010
+ columnBuilder = new PgBigInt53Builder(columnName);
1011
+ } else if (type === "bigserial") {
1012
+ columnBuilder = new PgBigSerial53Builder(columnName);
1013
+ } else if (type === "boolean") {
1014
+ columnBuilder = new PgBooleanBuilder(columnName);
1015
+ } else if (type === "cidr") {
1016
+ columnBuilder = new PgCidrBuilder(columnName);
1017
+ } else if (type === "date") {
1018
+ columnBuilder = new PgDateBuilder(columnName);
1019
+ } else if (type === "double precision") {
1020
+ columnBuilder = new PgDoublePrecisionBuilder(columnName);
1021
+ } else if (type === "inet") {
1022
+ columnBuilder = new PgInetBuilder(columnName);
1023
+ } else if (type === "integer") {
1024
+ columnBuilder = new PgIntegerBuilder(columnName);
1025
+ } else if (type === "interval" || type.startsWith("interval ")) {
1026
+ columnBuilder = new PgIntervalBuilder(columnName, {});
1027
+ } else if (type === "json") {
1028
+ columnBuilder = new PgJsonBuilder(columnName);
1029
+ } else if (type === "jsonb") {
1030
+ columnBuilder = new PgJsonbBuilder(columnName);
1031
+ } else if (type === "macaddr") {
1032
+ columnBuilder = new PgMacaddrBuilder(columnName);
1033
+ } else if (type === "macaddr8") {
1034
+ columnBuilder = new PgMacaddr8Builder(columnName);
1035
+ } else if (type === "numeric" || type.startsWith("numeric(")) {
1036
+ columnBuilder = new PgNumericBuilder(columnName);
1037
+ } else if (type === "real") {
1038
+ columnBuilder = new PgRealBuilder(columnName);
1039
+ } else if (type === "serial") {
1040
+ columnBuilder = new PgSerialBuilder(columnName);
1041
+ } else if (type === "smallint") {
1042
+ columnBuilder = new PgSmallIntBuilder(columnName);
1043
+ } else if (type === "smallserial") {
1044
+ columnBuilder = new PgSmallSerialBuilder(columnName);
1045
+ } else if (type === "text") {
1046
+ columnBuilder = new PgTextBuilder(columnName, {});
1047
+ } else if (type === "time" || type.startsWith("time(") || type === "time with time zone") {
1048
+ columnBuilder = new PgTimeBuilder(columnName, false, void 0);
1049
+ } else if (type === "timestamp" || type.startsWith("timestamp(") || type === "timestamp with time zone") {
1050
+ columnBuilder = new PgTimestampBuilder(columnName, false, void 0);
1051
+ } else if (type === "uuid") {
1052
+ columnBuilder = new PgUUIDBuilder(columnName);
1053
+ } else if (type === "varchar" || type.startsWith("varchar(")) {
1054
+ columnBuilder = new PgVarcharBuilder(columnName, {});
1055
+ } else if (type === "char" || type.startsWith("char(")) {
1056
+ columnBuilder = new PgCharBuilder(columnName, {});
1057
+ } else {
1058
+ columnBuilder = customType({
1059
+ dataType() {
1060
+ return type;
1061
+ }
1062
+ })(columnName);
1063
+ }
1064
+ if (c.notNull) {
1065
+ columnBuilder = columnBuilder.notNull();
1066
+ }
1067
+ if (c.default) {
1068
+ columnBuilder = columnBuilder.default(c.default);
1069
+ }
1070
+ if (c.primaryKey) {
1071
+ columnBuilder = columnBuilder.primaryKey();
1072
+ }
1073
+ columns[columnName] = columnBuilder;
1074
+ });
1075
+ if (schemaName === "public") {
1076
+ tables[t.name] = pgTable(t.name, columns, (cb) => {
1077
+ const res = {};
1078
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1079
+ const gh = cpk.columns.map((c) => cb[c]);
1080
+ res[cpk.name] = new PrimaryKeyBuilder(
1081
+ gh,
1082
+ cpk.name
1083
+ );
1084
+ });
1085
+ return res;
1086
+ });
1087
+ } else {
1088
+ tables[t.name] = pgSchema(schemaName).table(t.name, columns, (cb) => {
1089
+ const res = {};
1090
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1091
+ const gh = cpk.columns.map((c) => cb[c]);
1092
+ res[cpk.name] = new PrimaryKeyBuilder(
1093
+ gh,
1094
+ cpk.name
1095
+ );
1096
+ });
1097
+ return res;
1098
+ });
1099
+ }
1100
+ });
1101
+ return tables;
1102
+ };
1103
+ }
1104
+ });
1105
+
1106
+ // src/serializer/sqliteSerializer.ts
1107
+ import { getTableName as getTableName2, is as is2, SQL as SQL2 } from "drizzle-orm";
1108
+ import {
1109
+ getTableConfig as getTableConfig2,
1110
+ PrimaryKeyBuilder as PrimaryKeyBuilder2,
1111
+ SQLiteBaseInteger,
1112
+ SQLiteBlobBufferBuilder,
1113
+ SQLiteIntegerBuilder,
1114
+ SQLiteNumericBuilder,
1115
+ SQLiteRealBuilder,
1116
+ SQLiteSyncDialect,
1117
+ sqliteTable,
1118
+ SQLiteTextBuilder,
1119
+ uniqueKeyName as uniqueKeyName2
1120
+ } from "drizzle-orm/sqlite-core";
1121
+ function mapSqlToSqliteType(sqlType) {
1122
+ if ([
1123
+ "int",
1124
+ "integer",
1125
+ "integer auto_increment",
1126
+ "tinyint",
1127
+ "smallint",
1128
+ "mediumint",
1129
+ "bigint",
1130
+ "unsigned big int",
1131
+ "int2",
1132
+ "int8"
1133
+ ].includes(sqlType.toLowerCase())) {
1134
+ return "integer";
1135
+ } else if ([
1136
+ "character",
1137
+ "varchar",
1138
+ "vatying character",
1139
+ "nchar",
1140
+ "native character",
1141
+ "nvarchar",
1142
+ "text",
1143
+ "clob"
1144
+ ].some((it) => it.startsWith(sqlType.toLowerCase()))) {
1145
+ return "text";
1146
+ } else if (sqlType.toLowerCase() === "blob") {
1147
+ return "blob";
1148
+ } else if (["real", "double", "double precision", "float"].includes(
1149
+ sqlType.toLowerCase()
1150
+ )) {
1151
+ return "real";
1152
+ } else {
1153
+ return "numeric";
1154
+ }
1155
+ }
1156
+ var dialect2, fromDatabase2, toDrizzle2;
1157
+ var init_sqliteSerializer = __esm({
1158
+ "src/serializer/sqliteSerializer.ts"() {
1159
+ init_serializer();
1160
+ init_outputs();
1161
+ init_source();
1162
+ dialect2 = new SQLiteSyncDialect();
1163
+ fromDatabase2 = async (db, tablesFilter = (table) => true, progressCallback) => {
1164
+ const result = {};
1165
+ const columns = await db.query(
1166
+ `SELECT
1167
+ m.name as "tableName", p.name as "columnName", p.type as "columnType", p."notnull" as "notNull", p.dflt_value as "defaultValue", p.pk as pk
1168
+ FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p
1169
+ WHERE m.type = 'table' and m.tbl_name != 'sqlite_sequence' and m.tbl_name != 'sqlite_stat1' and m.tbl_name != '_litestream_seq' and m.tbl_name != '_litestream_lock' and m.tbl_name != 'libsql_wasm_func_table';
1170
+ `
1171
+ );
1172
+ const tablesWithSeq = [];
1173
+ const seq = await db.query(
1174
+ `SELECT * FROM sqlite_master WHERE name != 'sqlite_sequence' and name != 'sqlite_stat1' and name != '_litestream_seq' and name != '_litestream_lock' and sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*';`
1175
+ );
1176
+ for (const s of seq) {
1177
+ tablesWithSeq.push(s.name);
1178
+ }
1179
+ let columnsCount = 0;
1180
+ let tablesCount = /* @__PURE__ */ new Set();
1181
+ let indexesCount = 0;
1182
+ let foreignKeysCount = 0;
1183
+ const tableToPk = {};
1184
+ for (const column of columns) {
1185
+ if (!tablesFilter(column.tableName))
1186
+ continue;
1187
+ columnsCount += 1;
1188
+ if (progressCallback) {
1189
+ progressCallback("columns", columnsCount, "fetching");
1190
+ }
1191
+ const tableName = column.tableName;
1192
+ tablesCount.add(tableName);
1193
+ if (progressCallback) {
1194
+ progressCallback("tables", tablesCount.size, "fetching");
1195
+ }
1196
+ const columnName = column.columnName;
1197
+ const isNotNull = column.notNull === 1;
1198
+ const columnType = column.columnType;
1199
+ const isPrimary = column.pk !== 0;
1200
+ const columnDefault = column.defaultValue;
1201
+ const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
1202
+ if (isPrimary) {
1203
+ if (typeof tableToPk[tableName] === "undefined") {
1204
+ tableToPk[tableName] = [columnName];
1205
+ } else {
1206
+ tableToPk[tableName].push(columnName);
1207
+ }
1208
+ }
1209
+ const table = result[tableName];
1210
+ const newColumn = {
1211
+ default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
1212
+ columnDefault
1213
+ ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : (
1214
+ // ? columnDefault.substring(1, columnDefault.length - 1)
1215
+ `(${columnDefault})`
1216
+ ),
1217
+ autoincrement: isAutoincrement,
1218
+ name: columnName,
1219
+ type: mapSqlToSqliteType(columnType),
1220
+ primaryKey: false,
1221
+ notNull: isNotNull
1222
+ };
1223
+ if (!table) {
1224
+ result[tableName] = {
1225
+ name: tableName,
1226
+ columns: {
1227
+ [columnName]: newColumn
1228
+ },
1229
+ compositePrimaryKeys: {},
1230
+ indexes: {},
1231
+ foreignKeys: {},
1232
+ uniqueConstraints: {}
1233
+ };
1234
+ } else {
1235
+ result[tableName].columns[columnName] = newColumn;
1236
+ }
1237
+ }
1238
+ for (const [key, value] of Object.entries(tableToPk)) {
1239
+ if (value.length > 1) {
1240
+ value.sort();
1241
+ result[key].compositePrimaryKeys = {
1242
+ [`${key}_${value.join("_")}_pk`]: {
1243
+ columns: value,
1244
+ name: `${key}_${value.join("_")}_pk`
1245
+ }
1246
+ };
1247
+ } else if (value.length === 1) {
1248
+ result[key].columns[value[0]].primaryKey = true;
1249
+ } else {
1250
+ }
1251
+ }
1252
+ if (progressCallback) {
1253
+ progressCallback("columns", columnsCount, "done");
1254
+ progressCallback("tables", tablesCount.size, "done");
1255
+ }
1256
+ try {
1257
+ const fks = await db.query(
1258
+ `SELECT m.name as "tableFrom", f.id as "id", f."table" as "tableTo", f."from", f."to", f."on_update" as "onUpdate", f."on_delete" as "onDelete", f.seq as "seq"
1259
+ FROM sqlite_master m, pragma_foreign_key_list(m.name) as f;`
1260
+ );
1261
+ const fkByTableName = {};
1262
+ for (const fkRow of fks) {
1263
+ foreignKeysCount += 1;
1264
+ if (progressCallback) {
1265
+ progressCallback("fks", foreignKeysCount, "fetching");
1266
+ }
1267
+ const tableName = fkRow.tableFrom;
1268
+ const columnName = fkRow.from;
1269
+ const refTableName = fkRow.tableTo;
1270
+ const refColumnName = fkRow.to;
1271
+ const updateRule = fkRow.onUpdate;
1272
+ const deleteRule = fkRow.onDelete;
1273
+ const sequence = fkRow.seq;
1274
+ const id = fkRow.id;
1275
+ const tableInResult = result[tableName];
1276
+ if (typeof tableInResult === "undefined")
1277
+ continue;
1278
+ if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
1279
+ fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
1280
+ fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
1281
+ } else {
1282
+ fkByTableName[`${tableName}_${id}`] = {
1283
+ name: "",
1284
+ tableFrom: tableName,
1285
+ tableTo: refTableName,
1286
+ columnsFrom: [columnName],
1287
+ columnsTo: [refColumnName],
1288
+ onDelete: deleteRule == null ? void 0 : deleteRule.toLowerCase(),
1289
+ onUpdate: updateRule == null ? void 0 : updateRule.toLowerCase()
1290
+ };
1291
+ }
1292
+ const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
1293
+ const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
1294
+ fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
1295
+ "_"
1296
+ )}_${refTableName}_${columnsTo.join("_")}_fk`;
1297
+ }
1298
+ for (const idx of Object.keys(fkByTableName)) {
1299
+ const value = fkByTableName[idx];
1300
+ result[value.tableFrom].foreignKeys[value.name] = value;
1301
+ }
1302
+ } catch (e) {
1303
+ }
1304
+ if (progressCallback) {
1305
+ progressCallback("fks", foreignKeysCount, "done");
1306
+ }
1307
+ const idxs = await db.query(
1308
+ `SELECT
1309
+ m.tbl_name as tableName,
1310
+ il.name as indexName,
1311
+ ii.name as columnName,
1312
+ il.[unique] as isUnique,
1313
+ il.seq as seq
1314
+ FROM sqlite_master AS m,
1315
+ pragma_index_list(m.name) AS il,
1316
+ pragma_index_info(il.name) AS ii
1317
+ WHERE
1318
+ m.type = 'table' and il.name NOT LIKE 'sqlite_autoindex_%';`
1319
+ );
1320
+ for (const idxRow of idxs) {
1321
+ const tableName = idxRow.tableName;
1322
+ const constraintName = idxRow.indexName;
1323
+ const columnName = idxRow.columnName;
1324
+ const isUnique = idxRow.isUnique === 1;
1325
+ const tableInResult = result[tableName];
1326
+ if (typeof tableInResult === "undefined")
1327
+ continue;
1328
+ indexesCount += 1;
1329
+ if (progressCallback) {
1330
+ progressCallback("indexes", indexesCount, "fetching");
1331
+ }
1332
+ if (typeof tableInResult.indexes[constraintName] !== "undefined") {
1333
+ tableInResult.indexes[constraintName].columns.push(columnName);
1334
+ } else {
1335
+ tableInResult.indexes[constraintName] = {
1336
+ name: constraintName,
1337
+ columns: [columnName],
1338
+ isUnique
1339
+ };
1340
+ }
1341
+ }
1342
+ if (progressCallback) {
1343
+ progressCallback("indexes", indexesCount, "done");
1344
+ progressCallback("enums", 0, "done");
1345
+ }
1346
+ return {
1347
+ version: "5",
1348
+ dialect: "sqlite",
1349
+ tables: result,
1350
+ enums: {},
1351
+ _meta: {
1352
+ tables: {},
1353
+ columns: {}
1354
+ }
1355
+ };
1356
+ };
1357
+ toDrizzle2 = (schema) => {
1358
+ const tables = {};
1359
+ Object.values(schema.tables).forEach((t) => {
1360
+ const columns = {};
1361
+ Object.values(t.columns).forEach((c) => {
1362
+ const columnName = c.name;
1363
+ const type = c.type;
1364
+ let columnBuilder;
1365
+ if (type === "integer") {
1366
+ columnBuilder = new SQLiteIntegerBuilder(columnName);
1367
+ } else if (type === "text") {
1368
+ columnBuilder = new SQLiteTextBuilder(columnName, {});
1369
+ } else if (type === "blob") {
1370
+ columnBuilder = new SQLiteBlobBufferBuilder(columnName);
1371
+ } else if (type === "real") {
1372
+ columnBuilder = new SQLiteRealBuilder(columnName);
1373
+ } else {
1374
+ columnBuilder = new SQLiteNumericBuilder(columnName);
1375
+ }
1376
+ if (c.notNull) {
1377
+ columnBuilder = columnBuilder.notNull();
1378
+ }
1379
+ if (c.default) {
1380
+ columnBuilder = columnBuilder.default(c.default);
1381
+ }
1382
+ if (c.primaryKey) {
1383
+ columnBuilder = columnBuilder.primaryKey();
1384
+ }
1385
+ columns[columnName] = columnBuilder;
1386
+ });
1387
+ tables[t.name] = sqliteTable(t.name, columns, (cb) => {
1388
+ const res = {};
1389
+ Object.values(t.compositePrimaryKeys).forEach((cpk) => {
1390
+ const gh = cpk.columns.map((c) => cb[c]);
1391
+ res[cpk.name] = new PrimaryKeyBuilder2(
1392
+ gh,
1393
+ cpk.name
1394
+ );
1395
+ });
1396
+ return res;
1397
+ });
1398
+ });
1399
+ return tables;
1400
+ };
1401
+ }
1402
+ });
1403
+
1404
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
1405
+ var require_readline = __commonJS({
1406
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports) {
1407
+ "use strict";
1408
+ Object.defineProperty(exports, "__esModule", { value: true });
1409
+ exports.prepareReadLine = void 0;
1410
+ var prepareReadLine = () => {
1411
+ const stdin = process.stdin;
1412
+ const stdout = process.stdout;
1413
+ const readline = __require("readline");
1414
+ const rl = readline.createInterface({
1415
+ input: stdin,
1416
+ escapeCodeTimeout: 50
1417
+ });
1418
+ readline.emitKeypressEvents(stdin, rl);
1419
+ return {
1420
+ stdin,
1421
+ stdout,
1422
+ closable: rl
1423
+ };
1424
+ };
1425
+ exports.prepareReadLine = prepareReadLine;
1426
+ }
1427
+ });
1428
+
1429
+ // node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
1430
+ var require_src = __commonJS({
1431
+ "node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
1432
+ "use strict";
1433
+ var ESC = "\x1B";
1434
+ var CSI = `${ESC}[`;
1435
+ var beep = "\x07";
1436
+ var cursor = {
1437
+ to(x, y) {
1438
+ if (!y)
1439
+ return `${CSI}${x + 1}G`;
1440
+ return `${CSI}${y + 1};${x + 1}H`;
1441
+ },
1442
+ move(x, y) {
1443
+ let ret = "";
1444
+ if (x < 0)
1445
+ ret += `${CSI}${-x}D`;
1446
+ else if (x > 0)
1447
+ ret += `${CSI}${x}C`;
1448
+ if (y < 0)
1449
+ ret += `${CSI}${-y}A`;
1450
+ else if (y > 0)
1451
+ ret += `${CSI}${y}B`;
1452
+ return ret;
1453
+ },
1454
+ up: (count = 1) => `${CSI}${count}A`,
1455
+ down: (count = 1) => `${CSI}${count}B`,
1456
+ forward: (count = 1) => `${CSI}${count}C`,
1457
+ backward: (count = 1) => `${CSI}${count}D`,
1458
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
1459
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
1460
+ left: `${CSI}G`,
1461
+ hide: `${CSI}?25l`,
1462
+ show: `${CSI}?25h`,
1463
+ save: `${ESC}7`,
1464
+ restore: `${ESC}8`
1465
+ };
1466
+ var scroll = {
1467
+ up: (count = 1) => `${CSI}S`.repeat(count),
1468
+ down: (count = 1) => `${CSI}T`.repeat(count)
1469
+ };
1470
+ var erase = {
1471
+ screen: `${CSI}2J`,
1472
+ up: (count = 1) => `${CSI}1J`.repeat(count),
1473
+ down: (count = 1) => `${CSI}J`.repeat(count),
1474
+ line: `${CSI}2K`,
1475
+ lineEnd: `${CSI}K`,
1476
+ lineStart: `${CSI}1K`,
1477
+ lines(count) {
1478
+ let clear = "";
1479
+ for (let i = 0; i < count; i++)
1480
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
1481
+ if (count)
1482
+ clear += cursor.left;
1483
+ return clear;
1484
+ }
1485
+ };
1486
+ module.exports = { cursor, scroll, erase, beep };
1487
+ }
1488
+ });
1489
+
1490
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
1491
+ var require_utils = __commonJS({
1492
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports) {
1493
+ "use strict";
1494
+ Object.defineProperty(exports, "__esModule", { value: true });
1495
+ exports.clear = void 0;
1496
+ var sisteransi_1 = require_src();
1497
+ var strip = (str) => {
1498
+ const pattern = [
1499
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
1500
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
1501
+ ].join("|");
1502
+ const RGX = new RegExp(pattern, "g");
1503
+ return typeof str === "string" ? str.replace(RGX, "") : str;
1504
+ };
1505
+ var stringWidth = (str) => [...strip(str)].length;
1506
+ var clear = function(prompt, perLine) {
1507
+ if (!perLine)
1508
+ return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
1509
+ let rows = 0;
1510
+ const lines = prompt.split(/\r?\n/);
1511
+ for (let line of lines) {
1512
+ rows += 1 + Math.floor(Math.max(stringWidth(line) - 1, 0) / perLine);
1513
+ }
1514
+ return sisteransi_1.erase.lines(rows);
1515
+ };
1516
+ exports.clear = clear;
1517
+ }
1518
+ });
1519
+
1520
+ // node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
1521
+ var require_lodash = __commonJS({
1522
+ "node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports, module) {
1523
+ var FUNC_ERROR_TEXT = "Expected a function";
1524
+ var NAN = 0 / 0;
1525
+ var symbolTag = "[object Symbol]";
1526
+ var reTrim = /^\s+|\s+$/g;
1527
+ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
1528
+ var reIsBinary = /^0b[01]+$/i;
1529
+ var reIsOctal = /^0o[0-7]+$/i;
1530
+ var freeParseInt = parseInt;
1531
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
1532
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
1533
+ var root = freeGlobal || freeSelf || Function("return this")();
1534
+ var objectProto = Object.prototype;
1535
+ var objectToString = objectProto.toString;
1536
+ var nativeMax = Math.max;
1537
+ var nativeMin = Math.min;
1538
+ var now = function() {
1539
+ return root.Date.now();
1540
+ };
1541
+ function debounce(func, wait, options) {
1542
+ var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
1543
+ if (typeof func != "function") {
1544
+ throw new TypeError(FUNC_ERROR_TEXT);
1545
+ }
1546
+ wait = toNumber(wait) || 0;
1547
+ if (isObject(options)) {
1548
+ leading = !!options.leading;
1549
+ maxing = "maxWait" in options;
1550
+ maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
1551
+ trailing = "trailing" in options ? !!options.trailing : trailing;
1552
+ }
1553
+ function invokeFunc(time) {
1554
+ var args = lastArgs, thisArg = lastThis;
1555
+ lastArgs = lastThis = void 0;
1556
+ lastInvokeTime = time;
1557
+ result = func.apply(thisArg, args);
1558
+ return result;
1559
+ }
1560
+ function leadingEdge(time) {
1561
+ lastInvokeTime = time;
1562
+ timerId = setTimeout(timerExpired, wait);
1563
+ return leading ? invokeFunc(time) : result;
1564
+ }
1565
+ function remainingWait(time) {
1566
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
1567
+ return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
1568
+ }
1569
+ function shouldInvoke(time) {
1570
+ var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
1571
+ return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
1572
+ }
1573
+ function timerExpired() {
1574
+ var time = now();
1575
+ if (shouldInvoke(time)) {
1576
+ return trailingEdge(time);
1577
+ }
1578
+ timerId = setTimeout(timerExpired, remainingWait(time));
1579
+ }
1580
+ function trailingEdge(time) {
1581
+ timerId = void 0;
1582
+ if (trailing && lastArgs) {
1583
+ return invokeFunc(time);
1584
+ }
1585
+ lastArgs = lastThis = void 0;
1586
+ return result;
1587
+ }
1588
+ function cancel() {
1589
+ if (timerId !== void 0) {
1590
+ clearTimeout(timerId);
1591
+ }
1592
+ lastInvokeTime = 0;
1593
+ lastArgs = lastCallTime = lastThis = timerId = void 0;
1594
+ }
1595
+ function flush() {
1596
+ return timerId === void 0 ? result : trailingEdge(now());
1597
+ }
1598
+ function debounced() {
1599
+ var time = now(), isInvoking = shouldInvoke(time);
1600
+ lastArgs = arguments;
1601
+ lastThis = this;
1602
+ lastCallTime = time;
1603
+ if (isInvoking) {
1604
+ if (timerId === void 0) {
1605
+ return leadingEdge(lastCallTime);
1606
+ }
1607
+ if (maxing) {
1608
+ timerId = setTimeout(timerExpired, wait);
1609
+ return invokeFunc(lastCallTime);
1610
+ }
1611
+ }
1612
+ if (timerId === void 0) {
1613
+ timerId = setTimeout(timerExpired, wait);
1614
+ }
1615
+ return result;
1616
+ }
1617
+ debounced.cancel = cancel;
1618
+ debounced.flush = flush;
1619
+ return debounced;
1620
+ }
1621
+ function throttle(func, wait, options) {
1622
+ var leading = true, trailing = true;
1623
+ if (typeof func != "function") {
1624
+ throw new TypeError(FUNC_ERROR_TEXT);
1625
+ }
1626
+ if (isObject(options)) {
1627
+ leading = "leading" in options ? !!options.leading : leading;
1628
+ trailing = "trailing" in options ? !!options.trailing : trailing;
1629
+ }
1630
+ return debounce(func, wait, {
1631
+ "leading": leading,
1632
+ "maxWait": wait,
1633
+ "trailing": trailing
1634
+ });
1635
+ }
1636
+ function isObject(value) {
1637
+ var type = typeof value;
1638
+ return !!value && (type == "object" || type == "function");
1639
+ }
1640
+ function isObjectLike(value) {
1641
+ return !!value && typeof value == "object";
1642
+ }
1643
+ function isSymbol(value) {
1644
+ return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
1645
+ }
1646
+ function toNumber(value) {
1647
+ if (typeof value == "number") {
1648
+ return value;
1649
+ }
1650
+ if (isSymbol(value)) {
1651
+ return NAN;
1652
+ }
1653
+ if (isObject(value)) {
1654
+ var other = typeof value.valueOf == "function" ? value.valueOf() : value;
1655
+ value = isObject(other) ? other + "" : other;
1656
+ }
1657
+ if (typeof value != "string") {
1658
+ return value === 0 ? value : +value;
1659
+ }
1660
+ value = value.replace(reTrim, "");
1661
+ var isBinary = reIsBinary.test(value);
1662
+ return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
1663
+ }
1664
+ module.exports = throttle;
1665
+ }
1666
+ });
1667
+
1668
+ // node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
1669
+ var require_hanji = __commonJS({
1670
+ "node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports) {
1671
+ "use strict";
1672
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
1673
+ function adopt(value) {
1674
+ return value instanceof P ? value : new P(function(resolve) {
1675
+ resolve(value);
1676
+ });
1677
+ }
1678
+ return new (P || (P = Promise))(function(resolve, reject) {
1679
+ function fulfilled(value) {
1680
+ try {
1681
+ step(generator.next(value));
1682
+ } catch (e) {
1683
+ reject(e);
1684
+ }
1685
+ }
1686
+ function rejected(value) {
1687
+ try {
1688
+ step(generator["throw"](value));
1689
+ } catch (e) {
1690
+ reject(e);
1691
+ }
1692
+ }
1693
+ function step(result) {
1694
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1695
+ }
1696
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1697
+ });
1698
+ };
1699
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1700
+ return mod && mod.__esModule ? mod : { "default": mod };
1701
+ };
1702
+ Object.defineProperty(exports, "__esModule", { value: true });
1703
+ exports.onTerminate = exports.renderWithTask = exports.render = exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
1704
+ var readline_1 = require_readline();
1705
+ var sisteransi_1 = require_src();
1706
+ var utils_1 = require_utils();
1707
+ var lodash_throttle_1 = __importDefault(require_lodash());
1708
+ var Prompt2 = class {
1709
+ constructor() {
1710
+ this.attachCallbacks = [];
1711
+ this.detachCallbacks = [];
1712
+ this.inputCallbacks = [];
1713
+ }
1714
+ requestLayout() {
1715
+ this.terminal.requestLayout();
1716
+ }
1717
+ on(type, callback) {
1718
+ if (type === "attach") {
1719
+ this.attachCallbacks.push(callback);
1720
+ } else if (type === "detach") {
1721
+ this.detachCallbacks.push(callback);
1722
+ } else if (type === "input") {
1723
+ this.inputCallbacks.push(callback);
1724
+ }
1725
+ }
1726
+ attach(terminal) {
1727
+ this.terminal = terminal;
1728
+ this.attachCallbacks.forEach((it) => it(terminal));
1729
+ }
1730
+ detach(terminal) {
1731
+ this.detachCallbacks.forEach((it) => it(terminal));
1732
+ this.terminal = void 0;
1733
+ }
1734
+ input(str, key) {
1735
+ this.inputCallbacks.forEach((it) => it(str, key));
1736
+ }
1737
+ };
1738
+ exports.Prompt = Prompt2;
1739
+ var SelectState2 = class {
1740
+ constructor(items) {
1741
+ this.items = items;
1742
+ this.selectedIdx = 0;
1743
+ }
1744
+ bind(prompt) {
1745
+ prompt.on("input", (str, key) => {
1746
+ const invalidate = this.consume(str, key);
1747
+ if (invalidate)
1748
+ prompt.requestLayout();
1749
+ });
1750
+ }
1751
+ consume(str, key) {
1752
+ if (!key)
1753
+ return false;
1754
+ if (key.name === "down") {
1755
+ this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
1756
+ return true;
1757
+ }
1758
+ if (key.name === "up") {
1759
+ this.selectedIdx -= 1;
1760
+ this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
1761
+ return true;
1762
+ }
1763
+ return false;
1764
+ }
1765
+ };
1766
+ exports.SelectState = SelectState2;
1767
+ var deferred = () => {
1768
+ let resolve;
1769
+ let reject;
1770
+ const promise = new Promise((res, rej) => {
1771
+ resolve = res;
1772
+ reject = rej;
1773
+ });
1774
+ return {
1775
+ resolve,
1776
+ reject,
1777
+ promise
1778
+ };
1779
+ };
1780
+ exports.deferred = deferred;
1781
+ var Terminal = class {
1782
+ constructor(view, stdin, stdout, closable) {
1783
+ this.view = view;
1784
+ this.stdin = stdin;
1785
+ this.stdout = stdout;
1786
+ this.closable = closable;
1787
+ this.text = "";
1788
+ this.status = "idle";
1789
+ if (this.stdin.isTTY)
1790
+ this.stdin.setRawMode(true);
1791
+ const keypress = (str, key) => {
1792
+ if (key.name === "c" && key.ctrl === true) {
1793
+ this.requestLayout();
1794
+ this.view.detach(this);
1795
+ this.tearDown(keypress);
1796
+ if (terminateHandler) {
1797
+ terminateHandler(this.stdin, this.stdout);
1798
+ return;
1799
+ }
1800
+ this.stdout.write(`
1801
+ ^C
1802
+ `);
1803
+ process.exit(1);
1804
+ }
1805
+ if (key.name === "escape") {
1806
+ this.status = "aborted";
1807
+ this.requestLayout();
1808
+ this.view.detach(this);
1809
+ this.tearDown(keypress);
1810
+ this.resolve({ status: "aborted", data: void 0 });
1811
+ return;
1812
+ }
1813
+ if (key.name === "return") {
1814
+ this.status = "submitted";
1815
+ this.requestLayout();
1816
+ this.view.detach(this);
1817
+ this.tearDown(keypress);
1818
+ this.resolve({ status: "submitted", data: this.view.result() });
1819
+ return;
1820
+ }
1821
+ view.input(str, key);
1822
+ };
1823
+ this.stdin.on("keypress", keypress);
1824
+ this.view.attach(this);
1825
+ const { resolve, promise } = (0, exports.deferred)();
1826
+ this.resolve = resolve;
1827
+ this.promise = promise;
1828
+ this.renderFunc = (0, lodash_throttle_1.default)((str) => {
1829
+ this.stdout.write(str);
1830
+ });
1831
+ }
1832
+ tearDown(keypress) {
1833
+ this.stdout.write(sisteransi_1.cursor.show);
1834
+ this.stdin.removeListener("keypress", keypress);
1835
+ if (this.stdin.isTTY)
1836
+ this.stdin.setRawMode(false);
1837
+ this.closable.close();
1838
+ }
1839
+ result() {
1840
+ return this.promise;
1841
+ }
1842
+ toggleCursor(state) {
1843
+ if (state === "hide") {
1844
+ this.stdout.write(sisteransi_1.cursor.hide);
1845
+ } else {
1846
+ this.stdout.write(sisteransi_1.cursor.show);
1847
+ }
1848
+ }
1849
+ requestLayout() {
1850
+ const string = this.view.render(this.status);
1851
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1852
+ this.text = string;
1853
+ this.renderFunc(`${clearPrefix}${string}`);
1854
+ }
1855
+ };
1856
+ exports.Terminal = Terminal;
1857
+ var TaskView2 = class {
1858
+ constructor() {
1859
+ this.attachCallbacks = [];
1860
+ this.detachCallbacks = [];
1861
+ }
1862
+ requestLayout() {
1863
+ this.terminal.requestLayout();
1864
+ }
1865
+ attach(terminal) {
1866
+ this.terminal = terminal;
1867
+ this.attachCallbacks.forEach((it) => it(terminal));
1868
+ }
1869
+ detach(terminal) {
1870
+ this.detachCallbacks.forEach((it) => it(terminal));
1871
+ this.terminal = void 0;
1872
+ }
1873
+ on(type, callback) {
1874
+ if (type === "attach") {
1875
+ this.attachCallbacks.push(callback);
1876
+ } else if (type === "detach") {
1877
+ this.detachCallbacks.push(callback);
1878
+ }
1879
+ }
1880
+ };
1881
+ exports.TaskView = TaskView2;
1882
+ var TaskTerminal = class {
1883
+ constructor(view, stdout) {
1884
+ this.view = view;
1885
+ this.stdout = stdout;
1886
+ this.text = "";
1887
+ this.view.attach(this);
1888
+ }
1889
+ requestLayout() {
1890
+ const string = this.view.render("pending");
1891
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1892
+ this.text = string;
1893
+ this.stdout.write(`${clearPrefix}${string}`);
1894
+ }
1895
+ clear() {
1896
+ const string = this.view.render("done");
1897
+ this.view.detach(this);
1898
+ const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
1899
+ this.stdout.write(`${clearPrefix}${string}`);
1900
+ }
1901
+ };
1902
+ exports.TaskTerminal = TaskTerminal;
1903
+ function render2(view) {
1904
+ const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
1905
+ if (view instanceof Prompt2) {
1906
+ const terminal = new Terminal(view, stdin, stdout, closable);
1907
+ terminal.requestLayout();
1908
+ return terminal.result();
1909
+ }
1910
+ stdout.write(`${view}
1911
+ `);
1912
+ closable.close();
1913
+ return;
1914
+ }
1915
+ exports.render = render2;
1916
+ function renderWithTask3(view, task) {
1917
+ return __awaiter(this, void 0, void 0, function* () {
1918
+ const terminal = new TaskTerminal(view, process.stdout);
1919
+ terminal.requestLayout();
1920
+ const result = yield task;
1921
+ terminal.clear();
1922
+ return result;
1923
+ });
1924
+ }
1925
+ exports.renderWithTask = renderWithTask3;
1926
+ var terminateHandler;
1927
+ function onTerminate(callback) {
1928
+ terminateHandler = callback;
1929
+ }
1930
+ exports.onTerminate = onTerminate;
1931
+ }
1932
+ });
1933
+
1934
+ // src/cli/views.ts
1935
+ var import_hanji;
1936
+ var init_views = __esm({
1937
+ "src/cli/views.ts"() {
1938
+ init_source();
1939
+ import_hanji = __toESM(require_hanji());
1940
+ }
1941
+ });
1942
+
1943
+ // node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
1944
+ var require_balanced_match = __commonJS({
1945
+ "node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
1946
+ "use strict";
1947
+ module.exports = balanced;
1948
+ function balanced(a, b, str) {
1949
+ if (a instanceof RegExp)
1950
+ a = maybeMatch(a, str);
1951
+ if (b instanceof RegExp)
1952
+ b = maybeMatch(b, str);
1953
+ var r = range(a, b, str);
1954
+ return r && {
1955
+ start: r[0],
1956
+ end: r[1],
1957
+ pre: str.slice(0, r[0]),
1958
+ body: str.slice(r[0] + a.length, r[1]),
1959
+ post: str.slice(r[1] + b.length)
1960
+ };
1961
+ }
1962
+ function maybeMatch(reg, str) {
1963
+ var m = str.match(reg);
1964
+ return m ? m[0] : null;
1965
+ }
1966
+ balanced.range = range;
1967
+ function range(a, b, str) {
1968
+ var begs, beg, left, right, result;
1969
+ var ai = str.indexOf(a);
1970
+ var bi = str.indexOf(b, ai + 1);
1971
+ var i = ai;
1972
+ if (ai >= 0 && bi > 0) {
1973
+ if (a === b) {
1974
+ return [ai, bi];
1975
+ }
1976
+ begs = [];
1977
+ left = str.length;
1978
+ while (i >= 0 && !result) {
1979
+ if (i == ai) {
1980
+ begs.push(i);
1981
+ ai = str.indexOf(a, i + 1);
1982
+ } else if (begs.length == 1) {
1983
+ result = [begs.pop(), bi];
1984
+ } else {
1985
+ beg = begs.pop();
1986
+ if (beg < left) {
1987
+ left = beg;
1988
+ right = bi;
1989
+ }
1990
+ bi = str.indexOf(b, i + 1);
1991
+ }
1992
+ i = ai < bi && ai >= 0 ? ai : bi;
1993
+ }
1994
+ if (begs.length) {
1995
+ result = [left, right];
1996
+ }
1997
+ }
1998
+ return result;
1999
+ }
2000
+ }
2001
+ });
2002
+
2003
+ // node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
2004
+ var require_brace_expansion = __commonJS({
2005
+ "node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
2006
+ var balanced = require_balanced_match();
2007
+ module.exports = expandTop;
2008
+ var escSlash = "\0SLASH" + Math.random() + "\0";
2009
+ var escOpen = "\0OPEN" + Math.random() + "\0";
2010
+ var escClose = "\0CLOSE" + Math.random() + "\0";
2011
+ var escComma = "\0COMMA" + Math.random() + "\0";
2012
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
2013
+ function numeric(str) {
2014
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
2015
+ }
2016
+ function escapeBraces(str) {
2017
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
2018
+ }
2019
+ function unescapeBraces(str) {
2020
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
2021
+ }
2022
+ function parseCommaParts(str) {
2023
+ if (!str)
2024
+ return [""];
2025
+ var parts = [];
2026
+ var m = balanced("{", "}", str);
2027
+ if (!m)
2028
+ return str.split(",");
2029
+ var pre = m.pre;
2030
+ var body = m.body;
2031
+ var post = m.post;
2032
+ var p = pre.split(",");
2033
+ p[p.length - 1] += "{" + body + "}";
2034
+ var postParts = parseCommaParts(post);
2035
+ if (post.length) {
2036
+ p[p.length - 1] += postParts.shift();
2037
+ p.push.apply(p, postParts);
2038
+ }
2039
+ parts.push.apply(parts, p);
2040
+ return parts;
2041
+ }
2042
+ function expandTop(str) {
2043
+ if (!str)
2044
+ return [];
2045
+ if (str.substr(0, 2) === "{}") {
2046
+ str = "\\{\\}" + str.substr(2);
2047
+ }
2048
+ return expand2(escapeBraces(str), true).map(unescapeBraces);
2049
+ }
2050
+ function embrace(str) {
2051
+ return "{" + str + "}";
2052
+ }
2053
+ function isPadded(el) {
2054
+ return /^-?0\d/.test(el);
2055
+ }
2056
+ function lte(i, y) {
2057
+ return i <= y;
2058
+ }
2059
+ function gte(i, y) {
2060
+ return i >= y;
2061
+ }
2062
+ function expand2(str, isTop) {
2063
+ var expansions = [];
2064
+ var m = balanced("{", "}", str);
2065
+ if (!m)
2066
+ return [str];
2067
+ var pre = m.pre;
2068
+ var post = m.post.length ? expand2(m.post, false) : [""];
2069
+ if (/\$$/.test(m.pre)) {
2070
+ for (var k = 0; k < post.length; k++) {
2071
+ var expansion = pre + "{" + m.body + "}" + post[k];
2072
+ expansions.push(expansion);
2073
+ }
2074
+ } else {
2075
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
2076
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
2077
+ var isSequence = isNumericSequence || isAlphaSequence;
2078
+ var isOptions = m.body.indexOf(",") >= 0;
2079
+ if (!isSequence && !isOptions) {
2080
+ if (m.post.match(/,.*\}/)) {
2081
+ str = m.pre + "{" + m.body + escClose + m.post;
2082
+ return expand2(str);
2083
+ }
2084
+ return [str];
2085
+ }
2086
+ var n;
2087
+ if (isSequence) {
2088
+ n = m.body.split(/\.\./);
2089
+ } else {
2090
+ n = parseCommaParts(m.body);
2091
+ if (n.length === 1) {
2092
+ n = expand2(n[0], false).map(embrace);
2093
+ if (n.length === 1) {
2094
+ return post.map(function(p) {
2095
+ return m.pre + n[0] + p;
2096
+ });
2097
+ }
2098
+ }
2099
+ }
2100
+ var N;
2101
+ if (isSequence) {
2102
+ var x = numeric(n[0]);
2103
+ var y = numeric(n[1]);
2104
+ var width = Math.max(n[0].length, n[1].length);
2105
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
2106
+ var test = lte;
2107
+ var reverse = y < x;
2108
+ if (reverse) {
2109
+ incr *= -1;
2110
+ test = gte;
2111
+ }
2112
+ var pad = n.some(isPadded);
2113
+ N = [];
2114
+ for (var i = x; test(i, y); i += incr) {
2115
+ var c;
2116
+ if (isAlphaSequence) {
2117
+ c = String.fromCharCode(i);
2118
+ if (c === "\\")
2119
+ c = "";
2120
+ } else {
2121
+ c = String(i);
2122
+ if (pad) {
2123
+ var need = width - c.length;
2124
+ if (need > 0) {
2125
+ var z = new Array(need + 1).join("0");
2126
+ if (i < 0)
2127
+ c = "-" + z + c.slice(1);
2128
+ else
2129
+ c = z + c;
2130
+ }
2131
+ }
2132
+ }
2133
+ N.push(c);
2134
+ }
2135
+ } else {
2136
+ N = [];
2137
+ for (var j = 0; j < n.length; j++) {
2138
+ N.push.apply(N, expand2(n[j], false));
2139
+ }
2140
+ }
2141
+ for (var j = 0; j < N.length; j++) {
2142
+ for (var k = 0; k < post.length; k++) {
2143
+ var expansion = pre + N[j] + post[k];
2144
+ if (!isTop || isSequence || expansion)
2145
+ expansions.push(expansion);
2146
+ }
2147
+ }
2148
+ }
2149
+ return expansions;
2150
+ }
2151
+ }
2152
+ });
2153
+
2154
+ // src/drivers/index.ts
2155
+ import { sql } from "drizzle-orm";
2156
+ var DrizzleDbClient, DrizzleORMPgClient, TursoSqlite;
2157
+ var init_drivers = __esm({
2158
+ "src/drivers/index.ts"() {
2159
+ DrizzleDbClient = class {
2160
+ constructor(db) {
2161
+ this.db = db;
2162
+ }
2163
+ };
2164
+ DrizzleORMPgClient = class extends DrizzleDbClient {
2165
+ async query(query, values) {
2166
+ const res = await this.db.execute(sql.raw(query));
2167
+ return res.rows;
2168
+ }
2169
+ async run(query) {
2170
+ const res = await this.db.execute(sql.raw(query));
2171
+ return res.rows;
2172
+ }
2173
+ };
2174
+ TursoSqlite = class extends DrizzleDbClient {
2175
+ async run(query) {
2176
+ await this.db.execute(query);
2177
+ }
2178
+ async query(query) {
2179
+ const res = await this.db.execute(query);
2180
+ return res.rows;
2181
+ }
2182
+ };
2183
+ }
2184
+ });
2185
+
2186
+ // src/utils-studio.ts
2187
+ init_pgSerializer();
2188
+ init_sqliteSerializer();
2189
+
2190
+ // src/cli/commands/sqliteIntrospect.ts
2191
+ init_views();
2192
+
2193
+ // src/global.ts
2194
+ var originUUID = "00000000-0000-0000-0000-000000000000";
2195
+
2196
+ // src/cli/commands/sqliteIntrospect.ts
2197
+ init_sqliteSerializer();
2198
+
2199
+ // node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
2200
+ var UPPERCASE = /[\p{Lu}]/u;
2201
+ var LOWERCASE = /[\p{Ll}]/u;
2202
+ var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
2203
+ var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
2204
+ var SEPARATORS = /[_.\- ]+/;
2205
+ var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
2206
+ var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
2207
+ var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
2208
+ var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
2209
+ let isLastCharLower = false;
2210
+ let isLastCharUpper = false;
2211
+ let isLastLastCharUpper = false;
2212
+ let isLastLastCharPreserved = false;
2213
+ for (let index = 0; index < string.length; index++) {
2214
+ const character = string[index];
2215
+ isLastLastCharPreserved = index > 2 ? string[index - 3] === "-" : true;
2216
+ if (isLastCharLower && UPPERCASE.test(character)) {
2217
+ string = string.slice(0, index) + "-" + string.slice(index);
2218
+ isLastCharLower = false;
2219
+ isLastLastCharUpper = isLastCharUpper;
2220
+ isLastCharUpper = true;
2221
+ index++;
2222
+ } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
2223
+ string = string.slice(0, index - 1) + "-" + string.slice(index - 1);
2224
+ isLastLastCharUpper = isLastCharUpper;
2225
+ isLastCharUpper = false;
2226
+ isLastCharLower = true;
2227
+ } else {
2228
+ isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
2229
+ isLastLastCharUpper = isLastCharUpper;
2230
+ isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
2231
+ }
2232
+ }
2233
+ return string;
2234
+ };
2235
+ var preserveConsecutiveUppercase = (input, toLowerCase) => {
2236
+ LEADING_CAPITAL.lastIndex = 0;
2237
+ return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
2238
+ };
2239
+ var postProcess = (input, toUpperCase) => {
2240
+ SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
2241
+ NUMBERS_AND_IDENTIFIER.lastIndex = 0;
2242
+ return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m));
2243
+ };
2244
+ function camelCase(input, options) {
2245
+ if (!(typeof input === "string" || Array.isArray(input))) {
2246
+ throw new TypeError("Expected the input to be `string | string[]`");
2247
+ }
2248
+ options = {
2249
+ pascalCase: false,
2250
+ preserveConsecutiveUppercase: false,
2251
+ ...options
2252
+ };
2253
+ if (Array.isArray(input)) {
2254
+ input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
2255
+ } else {
2256
+ input = input.trim();
2257
+ }
2258
+ if (input.length === 0) {
2259
+ return "";
2260
+ }
2261
+ const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
2262
+ const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
2263
+ if (input.length === 1) {
2264
+ if (SEPARATORS.test(input)) {
2265
+ return "";
2266
+ }
2267
+ return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
2268
+ }
2269
+ const hasUpperCase = input !== toLowerCase(input);
2270
+ if (hasUpperCase) {
2271
+ input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
2272
+ }
2273
+ input = input.replace(LEADING_SEPARATORS, "");
2274
+ input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
2275
+ if (options.pascalCase) {
2276
+ input = toUpperCase(input.charAt(0)) + input.slice(1);
2277
+ }
2278
+ return postProcess(input, toUpperCase);
2279
+ }
2280
+
2281
+ // src/@types/utils.ts
2282
+ String.prototype.trimChar = function(char) {
2283
+ let start = 0;
2284
+ let end = this.length;
2285
+ while (start < end && this[start] === char)
2286
+ ++start;
2287
+ while (end > start && this[end - 1] === char)
2288
+ --end;
2289
+ return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
2290
+ };
2291
+ String.prototype.squashSpaces = function() {
2292
+ return this.replace(/ +/g, " ").trim();
2293
+ };
2294
+ String.prototype.camelCase = function() {
2295
+ return camelCase(String(this));
2296
+ };
2297
+ String.prototype.concatIf = function(it, condition) {
2298
+ return condition ? `${this}${it}` : this;
2299
+ };
2300
+ Array.prototype.random = function() {
2301
+ return this[~~(Math.random() * this.length)];
2302
+ };
2303
+
2304
+ // node_modules/.pnpm/minimatch@7.4.3/node_modules/minimatch/dist/mjs/index.js
2305
+ var import_brace_expansion = __toESM(require_brace_expansion(), 1);
2306
+
2307
+ // node_modules/.pnpm/minimatch@7.4.3/node_modules/minimatch/dist/mjs/brace-expressions.js
2308
+ var posixClasses = {
2309
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
2310
+ "[:alpha:]": ["\\p{L}\\p{Nl}", true],
2311
+ "[:ascii:]": ["\\x00-\\x7f", false],
2312
+ "[:blank:]": ["\\p{Zs}\\t", true],
2313
+ "[:cntrl:]": ["\\p{Cc}", true],
2314
+ "[:digit:]": ["\\p{Nd}", true],
2315
+ "[:graph:]": ["\\p{Z}\\p{C}", true, true],
2316
+ "[:lower:]": ["\\p{Ll}", true],
2317
+ "[:print:]": ["\\p{C}", true],
2318
+ "[:punct:]": ["\\p{P}", true],
2319
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
2320
+ "[:upper:]": ["\\p{Lu}", true],
2321
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
2322
+ "[:xdigit:]": ["A-Fa-f0-9", false]
2323
+ };
2324
+ var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
2325
+ var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
2326
+ var rangesToString = (ranges) => ranges.join("");
2327
+ var parseClass = (glob2, position) => {
2328
+ const pos = position;
2329
+ if (glob2.charAt(pos) !== "[") {
2330
+ throw new Error("not in a brace expression");
2331
+ }
2332
+ const ranges = [];
2333
+ const negs = [];
2334
+ let i = pos + 1;
2335
+ let sawStart = false;
2336
+ let uflag = false;
2337
+ let escaping = false;
2338
+ let negate = false;
2339
+ let endPos = pos;
2340
+ let rangeStart = "";
2341
+ WHILE:
2342
+ while (i < glob2.length) {
2343
+ const c = glob2.charAt(i);
2344
+ if ((c === "!" || c === "^") && i === pos + 1) {
2345
+ negate = true;
2346
+ i++;
2347
+ continue;
2348
+ }
2349
+ if (c === "]" && sawStart && !escaping) {
2350
+ endPos = i + 1;
2351
+ break;
2352
+ }
2353
+ sawStart = true;
2354
+ if (c === "\\") {
2355
+ if (!escaping) {
2356
+ escaping = true;
2357
+ i++;
2358
+ continue;
2359
+ }
2360
+ }
2361
+ if (c === "[" && !escaping) {
2362
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
2363
+ if (glob2.startsWith(cls, i)) {
2364
+ if (rangeStart) {
2365
+ return ["$.", false, glob2.length - pos, true];
2366
+ }
2367
+ i += cls.length;
2368
+ if (neg)
2369
+ negs.push(unip);
2370
+ else
2371
+ ranges.push(unip);
2372
+ uflag = uflag || u;
2373
+ continue WHILE;
2374
+ }
2375
+ }
2376
+ }
2377
+ escaping = false;
2378
+ if (rangeStart) {
2379
+ if (c > rangeStart) {
2380
+ ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
2381
+ } else if (c === rangeStart) {
2382
+ ranges.push(braceEscape(c));
2383
+ }
2384
+ rangeStart = "";
2385
+ i++;
2386
+ continue;
2387
+ }
2388
+ if (glob2.startsWith("-]", i + 1)) {
2389
+ ranges.push(braceEscape(c + "-"));
2390
+ i += 2;
2391
+ continue;
2392
+ }
2393
+ if (glob2.startsWith("-", i + 1)) {
2394
+ rangeStart = c;
2395
+ i += 2;
2396
+ continue;
2397
+ }
2398
+ ranges.push(braceEscape(c));
2399
+ i++;
2400
+ }
2401
+ if (endPos < i) {
2402
+ return ["", false, 0, false];
2403
+ }
2404
+ if (!ranges.length && !negs.length) {
2405
+ return ["$.", false, glob2.length - pos, true];
2406
+ }
2407
+ if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
2408
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
2409
+ return [regexpEscape(r), false, endPos - pos, false];
2410
+ }
2411
+ const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
2412
+ const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
2413
+ const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
2414
+ return [comb, uflag, endPos - pos, true];
2415
+ };
2416
+
2417
+ // node_modules/.pnpm/minimatch@7.4.3/node_modules/minimatch/dist/mjs/escape.js
2418
+ var escape = (s, { windowsPathsNoEscape = false } = {}) => {
2419
+ return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
2420
+ };
2421
+
2422
+ // node_modules/.pnpm/minimatch@7.4.3/node_modules/minimatch/dist/mjs/unescape.js
2423
+ var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
2424
+ return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
2425
+ };
2426
+
2427
+ // node_modules/.pnpm/minimatch@7.4.3/node_modules/minimatch/dist/mjs/index.js
2428
+ var minimatch = (p, pattern, options = {}) => {
2429
+ assertValidPattern(pattern);
2430
+ if (!options.nocomment && pattern.charAt(0) === "#") {
2431
+ return false;
2432
+ }
2433
+ return new Minimatch(pattern, options).match(p);
2434
+ };
2435
+ var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
2436
+ var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
2437
+ var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
2438
+ var starDotExtTestNocase = (ext2) => {
2439
+ ext2 = ext2.toLowerCase();
2440
+ return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
2441
+ };
2442
+ var starDotExtTestNocaseDot = (ext2) => {
2443
+ ext2 = ext2.toLowerCase();
2444
+ return (f) => f.toLowerCase().endsWith(ext2);
2445
+ };
2446
+ var starDotStarRE = /^\*+\.\*+$/;
2447
+ var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
2448
+ var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
2449
+ var dotStarRE = /^\.\*+$/;
2450
+ var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
2451
+ var starRE = /^\*+$/;
2452
+ var starTest = (f) => f.length !== 0 && !f.startsWith(".");
2453
+ var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
2454
+ var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
2455
+ var qmarksTestNocase = ([$0, ext2 = ""]) => {
2456
+ const noext = qmarksTestNoExt([$0]);
2457
+ if (!ext2)
2458
+ return noext;
2459
+ ext2 = ext2.toLowerCase();
2460
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
2461
+ };
2462
+ var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
2463
+ const noext = qmarksTestNoExtDot([$0]);
2464
+ if (!ext2)
2465
+ return noext;
2466
+ ext2 = ext2.toLowerCase();
2467
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
2468
+ };
2469
+ var qmarksTestDot = ([$0, ext2 = ""]) => {
2470
+ const noext = qmarksTestNoExtDot([$0]);
2471
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
2472
+ };
2473
+ var qmarksTest = ([$0, ext2 = ""]) => {
2474
+ const noext = qmarksTestNoExt([$0]);
2475
+ return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
2476
+ };
2477
+ var qmarksTestNoExt = ([$0]) => {
2478
+ const len = $0.length;
2479
+ return (f) => f.length === len && !f.startsWith(".");
2480
+ };
2481
+ var qmarksTestNoExtDot = ([$0]) => {
2482
+ const len = $0.length;
2483
+ return (f) => f.length === len && f !== "." && f !== "..";
2484
+ };
2485
+ var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
2486
+ var path = {
2487
+ win32: { sep: "\\" },
2488
+ posix: { sep: "/" }
2489
+ };
2490
+ var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
2491
+ minimatch.sep = sep;
2492
+ var GLOBSTAR = Symbol("globstar **");
2493
+ minimatch.GLOBSTAR = GLOBSTAR;
2494
+ var plTypes = {
2495
+ "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
2496
+ "?": { open: "(?:", close: ")?" },
2497
+ "+": { open: "(?:", close: ")+" },
2498
+ "*": { open: "(?:", close: ")*" },
2499
+ "@": { open: "(?:", close: ")" }
2500
+ };
2501
+ var qmark = "[^/]";
2502
+ var star = qmark + "*?";
2503
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
2504
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
2505
+ var charSet = (s) => s.split("").reduce((set, c) => {
2506
+ set[c] = true;
2507
+ return set;
2508
+ }, {});
2509
+ var reSpecials = charSet("().*{}+?[]^$\\!");
2510
+ var addPatternStartSet = charSet("[.(");
2511
+ var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2512
+ minimatch.filter = filter;
2513
+ var ext = (a, b = {}) => Object.assign({}, a, b);
2514
+ var defaults = (def) => {
2515
+ if (!def || typeof def !== "object" || !Object.keys(def).length) {
2516
+ return minimatch;
2517
+ }
2518
+ const orig = minimatch;
2519
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2520
+ return Object.assign(m, {
2521
+ Minimatch: class Minimatch extends orig.Minimatch {
2522
+ constructor(pattern, options = {}) {
2523
+ super(pattern, ext(def, options));
2524
+ }
2525
+ static defaults(options) {
2526
+ return orig.defaults(ext(def, options)).Minimatch;
2527
+ }
2528
+ },
2529
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2530
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2531
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2532
+ defaults: (options) => orig.defaults(ext(def, options)),
2533
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2534
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2535
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2536
+ sep: orig.sep,
2537
+ GLOBSTAR
2538
+ });
2539
+ };
2540
+ minimatch.defaults = defaults;
2541
+ var braceExpand = (pattern, options = {}) => {
2542
+ assertValidPattern(pattern);
2543
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
2544
+ return [pattern];
2545
+ }
2546
+ return (0, import_brace_expansion.default)(pattern);
2547
+ };
2548
+ minimatch.braceExpand = braceExpand;
2549
+ var MAX_PATTERN_LENGTH = 1024 * 64;
2550
+ var assertValidPattern = (pattern) => {
2551
+ if (typeof pattern !== "string") {
2552
+ throw new TypeError("invalid pattern");
2553
+ }
2554
+ if (pattern.length > MAX_PATTERN_LENGTH) {
2555
+ throw new TypeError("pattern is too long");
2556
+ }
2557
+ };
2558
+ var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
2559
+ minimatch.makeRe = makeRe;
2560
+ var match = (list, pattern, options = {}) => {
2561
+ const mm = new Minimatch(pattern, options);
2562
+ list = list.filter((f) => mm.match(f));
2563
+ if (mm.options.nonull && !list.length) {
2564
+ list.push(pattern);
2565
+ }
2566
+ return list;
2567
+ };
2568
+ minimatch.match = match;
2569
+ var globUnescape = (s) => s.replace(/\\(.)/g, "$1");
2570
+ var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
2571
+ var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
2572
+ var Minimatch = class {
2573
+ options;
2574
+ set;
2575
+ pattern;
2576
+ windowsPathsNoEscape;
2577
+ nonegate;
2578
+ negate;
2579
+ comment;
2580
+ empty;
2581
+ preserveMultipleSlashes;
2582
+ partial;
2583
+ globSet;
2584
+ globParts;
2585
+ nocase;
2586
+ isWindows;
2587
+ platform;
2588
+ windowsNoMagicRoot;
2589
+ regexp;
2590
+ constructor(pattern, options = {}) {
2591
+ assertValidPattern(pattern);
2592
+ options = options || {};
2593
+ this.options = options;
2594
+ this.pattern = pattern;
2595
+ this.platform = options.platform || defaultPlatform;
2596
+ this.isWindows = this.platform === "win32";
2597
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
2598
+ if (this.windowsPathsNoEscape) {
2599
+ this.pattern = this.pattern.replace(/\\/g, "/");
2600
+ }
2601
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
2602
+ this.regexp = null;
2603
+ this.negate = false;
2604
+ this.nonegate = !!options.nonegate;
2605
+ this.comment = false;
2606
+ this.empty = false;
2607
+ this.partial = !!options.partial;
2608
+ this.nocase = !!this.options.nocase;
2609
+ this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
2610
+ this.globSet = [];
2611
+ this.globParts = [];
2612
+ this.set = [];
2613
+ this.make();
2614
+ }
2615
+ hasMagic() {
2616
+ if (this.options.magicalBraces && this.set.length > 1) {
2617
+ return true;
2618
+ }
2619
+ for (const pattern of this.set) {
2620
+ for (const part of pattern) {
2621
+ if (typeof part !== "string")
2622
+ return true;
2623
+ }
2624
+ }
2625
+ return false;
2626
+ }
2627
+ debug(..._) {
2628
+ }
2629
+ make() {
2630
+ const pattern = this.pattern;
2631
+ const options = this.options;
2632
+ if (!options.nocomment && pattern.charAt(0) === "#") {
2633
+ this.comment = true;
2634
+ return;
2635
+ }
2636
+ if (!pattern) {
2637
+ this.empty = true;
2638
+ return;
2639
+ }
2640
+ this.parseNegate();
2641
+ this.globSet = [...new Set(this.braceExpand())];
2642
+ if (options.debug) {
2643
+ this.debug = (...args) => console.error(...args);
2644
+ }
2645
+ this.debug(this.pattern, this.globSet);
2646
+ const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
2647
+ this.globParts = this.preprocess(rawGlobParts);
2648
+ this.debug(this.pattern, this.globParts);
2649
+ let set = this.globParts.map((s, _, __) => {
2650
+ if (this.isWindows && this.windowsNoMagicRoot) {
2651
+ const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
2652
+ const isDrive = /^[a-z]:/i.test(s[0]);
2653
+ if (isUNC) {
2654
+ return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
2655
+ } else if (isDrive) {
2656
+ return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
2657
+ }
2658
+ }
2659
+ return s.map((ss) => this.parse(ss));
2660
+ });
2661
+ this.debug(this.pattern, set);
2662
+ this.set = set.filter((s) => s.indexOf(false) === -1);
2663
+ if (this.isWindows) {
2664
+ for (let i = 0; i < this.set.length; i++) {
2665
+ const p = this.set[i];
2666
+ if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
2667
+ p[2] = "?";
2668
+ }
2669
+ }
2670
+ }
2671
+ this.debug(this.pattern, this.set);
2672
+ }
2673
+ // various transforms to equivalent pattern sets that are
2674
+ // faster to process in a filesystem walk. The goal is to
2675
+ // eliminate what we can, and push all ** patterns as far
2676
+ // to the right as possible, even if it increases the number
2677
+ // of patterns that we have to process.
2678
+ preprocess(globParts) {
2679
+ if (this.options.noglobstar) {
2680
+ for (let i = 0; i < globParts.length; i++) {
2681
+ for (let j = 0; j < globParts[i].length; j++) {
2682
+ if (globParts[i][j] === "**") {
2683
+ globParts[i][j] = "*";
2684
+ }
2685
+ }
2686
+ }
2687
+ }
2688
+ const { optimizationLevel = 1 } = this.options;
2689
+ if (optimizationLevel >= 2) {
2690
+ globParts = this.firstPhasePreProcess(globParts);
2691
+ globParts = this.secondPhasePreProcess(globParts);
2692
+ } else if (optimizationLevel >= 1) {
2693
+ globParts = this.levelOneOptimize(globParts);
2694
+ } else {
2695
+ globParts = this.adjascentGlobstarOptimize(globParts);
2696
+ }
2697
+ return globParts;
2698
+ }
2699
+ // just get rid of adjascent ** portions
2700
+ adjascentGlobstarOptimize(globParts) {
2701
+ return globParts.map((parts) => {
2702
+ let gs = -1;
2703
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2704
+ let i = gs;
2705
+ while (parts[i + 1] === "**") {
2706
+ i++;
2707
+ }
2708
+ if (i !== gs) {
2709
+ parts.splice(gs, i - gs);
2710
+ }
2711
+ }
2712
+ return parts;
2713
+ });
2714
+ }
2715
+ // get rid of adjascent ** and resolve .. portions
2716
+ levelOneOptimize(globParts) {
2717
+ return globParts.map((parts) => {
2718
+ parts = parts.reduce((set, part) => {
2719
+ const prev = set[set.length - 1];
2720
+ if (part === "**" && prev === "**") {
2721
+ return set;
2722
+ }
2723
+ if (part === "..") {
2724
+ if (prev && prev !== ".." && prev !== "." && prev !== "**") {
2725
+ set.pop();
2726
+ return set;
2727
+ }
2728
+ }
2729
+ set.push(part);
2730
+ return set;
2731
+ }, []);
2732
+ return parts.length === 0 ? [""] : parts;
2733
+ });
2734
+ }
2735
+ levelTwoFileOptimize(parts) {
2736
+ if (!Array.isArray(parts)) {
2737
+ parts = this.slashSplit(parts);
2738
+ }
2739
+ let didSomething = false;
2740
+ do {
2741
+ didSomething = false;
2742
+ if (!this.preserveMultipleSlashes) {
2743
+ for (let i = 1; i < parts.length - 1; i++) {
2744
+ const p = parts[i];
2745
+ if (i === 1 && p === "" && parts[0] === "")
2746
+ continue;
2747
+ if (p === "." || p === "") {
2748
+ didSomething = true;
2749
+ parts.splice(i, 1);
2750
+ i--;
2751
+ }
2752
+ }
2753
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2754
+ didSomething = true;
2755
+ parts.pop();
2756
+ }
2757
+ }
2758
+ let dd = 0;
2759
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2760
+ const p = parts[dd - 1];
2761
+ if (p && p !== "." && p !== ".." && p !== "**") {
2762
+ didSomething = true;
2763
+ parts.splice(dd - 1, 2);
2764
+ dd -= 2;
2765
+ }
2766
+ }
2767
+ } while (didSomething);
2768
+ return parts.length === 0 ? [""] : parts;
2769
+ }
2770
+ // First phase: single-pattern processing
2771
+ // <pre> is 1 or more portions
2772
+ // <rest> is 1 or more portions
2773
+ // <p> is any portion other than ., .., '', or **
2774
+ // <e> is . or ''
2775
+ //
2776
+ // **/.. is *brutal* for filesystem walking performance, because
2777
+ // it effectively resets the recursive walk each time it occurs,
2778
+ // and ** cannot be reduced out by a .. pattern part like a regexp
2779
+ // or most strings (other than .., ., and '') can be.
2780
+ //
2781
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2782
+ // <pre>/<e>/<rest> -> <pre>/<rest>
2783
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
2784
+ // **/**/<rest> -> **/<rest>
2785
+ //
2786
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
2787
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
2788
+ firstPhasePreProcess(globParts) {
2789
+ let didSomething = false;
2790
+ do {
2791
+ didSomething = false;
2792
+ for (let parts of globParts) {
2793
+ let gs = -1;
2794
+ while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
2795
+ let gss = gs;
2796
+ while (parts[gss + 1] === "**") {
2797
+ gss++;
2798
+ }
2799
+ if (gss > gs) {
2800
+ parts.splice(gs + 1, gss - gs);
2801
+ }
2802
+ let next = parts[gs + 1];
2803
+ const p = parts[gs + 2];
2804
+ const p2 = parts[gs + 3];
2805
+ if (next !== "..")
2806
+ continue;
2807
+ if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
2808
+ continue;
2809
+ }
2810
+ didSomething = true;
2811
+ parts.splice(gs, 1);
2812
+ const other = parts.slice(0);
2813
+ other[gs] = "**";
2814
+ globParts.push(other);
2815
+ gs--;
2816
+ }
2817
+ if (!this.preserveMultipleSlashes) {
2818
+ for (let i = 1; i < parts.length - 1; i++) {
2819
+ const p = parts[i];
2820
+ if (i === 1 && p === "" && parts[0] === "")
2821
+ continue;
2822
+ if (p === "." || p === "") {
2823
+ didSomething = true;
2824
+ parts.splice(i, 1);
2825
+ i--;
2826
+ }
2827
+ }
2828
+ if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
2829
+ didSomething = true;
2830
+ parts.pop();
2831
+ }
2832
+ }
2833
+ let dd = 0;
2834
+ while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
2835
+ const p = parts[dd - 1];
2836
+ if (p && p !== "." && p !== ".." && p !== "**") {
2837
+ didSomething = true;
2838
+ const needDot = dd === 1 && parts[dd + 1] === "**";
2839
+ const splin = needDot ? ["."] : [];
2840
+ parts.splice(dd - 1, 2, ...splin);
2841
+ if (parts.length === 0)
2842
+ parts.push("");
2843
+ dd -= 2;
2844
+ }
2845
+ }
2846
+ }
2847
+ } while (didSomething);
2848
+ return globParts;
2849
+ }
2850
+ // second phase: multi-pattern dedupes
2851
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
2852
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
2853
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
2854
+ //
2855
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
2856
+ // ^-- not valid because ** doens't follow symlinks
2857
+ secondPhasePreProcess(globParts) {
2858
+ for (let i = 0; i < globParts.length - 1; i++) {
2859
+ for (let j = i + 1; j < globParts.length; j++) {
2860
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
2861
+ if (!matched)
2862
+ continue;
2863
+ globParts[i] = matched;
2864
+ globParts[j] = [];
2865
+ }
2866
+ }
2867
+ return globParts.filter((gs) => gs.length);
2868
+ }
2869
+ partsMatch(a, b, emptyGSMatch = false) {
2870
+ let ai = 0;
2871
+ let bi = 0;
2872
+ let result = [];
2873
+ let which = "";
2874
+ while (ai < a.length && bi < b.length) {
2875
+ if (a[ai] === b[bi]) {
2876
+ result.push(which === "b" ? b[bi] : a[ai]);
2877
+ ai++;
2878
+ bi++;
2879
+ } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
2880
+ result.push(a[ai]);
2881
+ ai++;
2882
+ } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
2883
+ result.push(b[bi]);
2884
+ bi++;
2885
+ } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
2886
+ if (which === "b")
2887
+ return false;
2888
+ which = "a";
2889
+ result.push(a[ai]);
2890
+ ai++;
2891
+ bi++;
2892
+ } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
2893
+ if (which === "a")
2894
+ return false;
2895
+ which = "b";
2896
+ result.push(b[bi]);
2897
+ ai++;
2898
+ bi++;
2899
+ } else {
2900
+ return false;
2901
+ }
2902
+ }
2903
+ return a.length === b.length && result;
2904
+ }
2905
+ parseNegate() {
2906
+ if (this.nonegate)
2907
+ return;
2908
+ const pattern = this.pattern;
2909
+ let negate = false;
2910
+ let negateOffset = 0;
2911
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
2912
+ negate = !negate;
2913
+ negateOffset++;
2914
+ }
2915
+ if (negateOffset)
2916
+ this.pattern = pattern.slice(negateOffset);
2917
+ this.negate = negate;
2918
+ }
2919
+ // set partial to true to test if, for example,
2920
+ // "/a/b" matches the start of "/*/b/*/d"
2921
+ // Partial means, if you run out of file before you run
2922
+ // out of pattern, then that's fine, as long as all
2923
+ // the parts match.
2924
+ matchOne(file, pattern, partial = false) {
2925
+ const options = this.options;
2926
+ if (this.isWindows) {
2927
+ const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
2928
+ const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
2929
+ if (fileUNC && patternUNC) {
2930
+ const fd = file[3];
2931
+ const pd = pattern[3];
2932
+ if (fd.toLowerCase() === pd.toLowerCase()) {
2933
+ file[3] = pd;
2934
+ }
2935
+ } else if (patternUNC && typeof file[0] === "string") {
2936
+ const pd = pattern[3];
2937
+ const fd = file[0];
2938
+ if (pd.toLowerCase() === fd.toLowerCase()) {
2939
+ pattern[3] = fd;
2940
+ pattern = pattern.slice(3);
2941
+ }
2942
+ } else if (fileUNC && typeof pattern[0] === "string") {
2943
+ const fd = file[3];
2944
+ if (fd.toLowerCase() === pattern[0].toLowerCase()) {
2945
+ pattern[0] = fd;
2946
+ file = file.slice(3);
2947
+ }
2948
+ }
2949
+ }
2950
+ const { optimizationLevel = 1 } = this.options;
2951
+ if (optimizationLevel >= 2) {
2952
+ file = this.levelTwoFileOptimize(file);
2953
+ }
2954
+ this.debug("matchOne", this, { file, pattern });
2955
+ this.debug("matchOne", file.length, pattern.length);
2956
+ for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
2957
+ this.debug("matchOne loop");
2958
+ var p = pattern[pi];
2959
+ var f = file[fi];
2960
+ this.debug(pattern, p, f);
2961
+ if (p === false) {
2962
+ return false;
2963
+ }
2964
+ if (p === GLOBSTAR) {
2965
+ this.debug("GLOBSTAR", [pattern, p, f]);
2966
+ var fr = fi;
2967
+ var pr = pi + 1;
2968
+ if (pr === pl) {
2969
+ this.debug("** at the end");
2970
+ for (; fi < fl; fi++) {
2971
+ if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
2972
+ return false;
2973
+ }
2974
+ return true;
2975
+ }
2976
+ while (fr < fl) {
2977
+ var swallowee = file[fr];
2978
+ this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
2979
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
2980
+ this.debug("globstar found match!", fr, fl, swallowee);
2981
+ return true;
2982
+ } else {
2983
+ if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
2984
+ this.debug("dot detected!", file, fr, pattern, pr);
2985
+ break;
2986
+ }
2987
+ this.debug("globstar swallow a segment, and continue");
2988
+ fr++;
2989
+ }
2990
+ }
2991
+ if (partial) {
2992
+ this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
2993
+ if (fr === fl) {
2994
+ return true;
2995
+ }
2996
+ }
2997
+ return false;
2998
+ }
2999
+ let hit;
3000
+ if (typeof p === "string") {
3001
+ hit = f === p;
3002
+ this.debug("string match", p, f, hit);
3003
+ } else {
3004
+ hit = p.test(f);
3005
+ this.debug("pattern match", p, f, hit);
3006
+ }
3007
+ if (!hit)
3008
+ return false;
3009
+ }
3010
+ if (fi === fl && pi === pl) {
3011
+ return true;
3012
+ } else if (fi === fl) {
3013
+ return partial;
3014
+ } else if (pi === pl) {
3015
+ return fi === fl - 1 && file[fi] === "";
3016
+ } else {
3017
+ throw new Error("wtf?");
3018
+ }
3019
+ }
3020
+ braceExpand() {
3021
+ return braceExpand(this.pattern, this.options);
3022
+ }
3023
+ parse(pattern) {
3024
+ assertValidPattern(pattern);
3025
+ const options = this.options;
3026
+ if (pattern === "**")
3027
+ return GLOBSTAR;
3028
+ if (pattern === "")
3029
+ return "";
3030
+ let m;
3031
+ let fastTest = null;
3032
+ if (m = pattern.match(starRE)) {
3033
+ fastTest = options.dot ? starTestDot : starTest;
3034
+ } else if (m = pattern.match(starDotExtRE)) {
3035
+ fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
3036
+ } else if (m = pattern.match(qmarksRE)) {
3037
+ fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
3038
+ } else if (m = pattern.match(starDotStarRE)) {
3039
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
3040
+ } else if (m = pattern.match(dotStarRE)) {
3041
+ fastTest = dotStarTest;
3042
+ }
3043
+ let re = "";
3044
+ let hasMagic = false;
3045
+ let escaping = false;
3046
+ const patternListStack = [];
3047
+ const negativeLists = [];
3048
+ let stateChar = false;
3049
+ let uflag = false;
3050
+ let pl;
3051
+ let dotTravAllowed = pattern.charAt(0) === ".";
3052
+ let dotFileAllowed = options.dot || dotTravAllowed;
3053
+ const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
3054
+ const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
3055
+ const clearStateChar = () => {
3056
+ if (stateChar) {
3057
+ switch (stateChar) {
3058
+ case "*":
3059
+ re += star;
3060
+ hasMagic = true;
3061
+ break;
3062
+ case "?":
3063
+ re += qmark;
3064
+ hasMagic = true;
3065
+ break;
3066
+ default:
3067
+ re += "\\" + stateChar;
3068
+ break;
3069
+ }
3070
+ this.debug("clearStateChar %j %j", stateChar, re);
3071
+ stateChar = false;
3072
+ }
3073
+ };
3074
+ for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
3075
+ this.debug("%s %s %s %j", pattern, i, re, c);
3076
+ if (escaping) {
3077
+ if (c === "/") {
3078
+ return false;
3079
+ }
3080
+ if (reSpecials[c]) {
3081
+ re += "\\";
3082
+ }
3083
+ re += c;
3084
+ escaping = false;
3085
+ continue;
3086
+ }
3087
+ switch (c) {
3088
+ case "/": {
3089
+ return false;
3090
+ }
3091
+ case "\\":
3092
+ clearStateChar();
3093
+ escaping = true;
3094
+ continue;
3095
+ case "?":
3096
+ case "*":
3097
+ case "+":
3098
+ case "@":
3099
+ case "!":
3100
+ this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c);
3101
+ this.debug("call clearStateChar %j", stateChar);
3102
+ clearStateChar();
3103
+ stateChar = c;
3104
+ if (options.noext)
3105
+ clearStateChar();
3106
+ continue;
3107
+ case "(": {
3108
+ if (!stateChar) {
3109
+ re += "\\(";
3110
+ continue;
3111
+ }
3112
+ const plEntry = {
3113
+ type: stateChar,
3114
+ start: i - 1,
3115
+ reStart: re.length,
3116
+ open: plTypes[stateChar].open,
3117
+ close: plTypes[stateChar].close
3118
+ };
3119
+ this.debug(this.pattern, " ", plEntry);
3120
+ patternListStack.push(plEntry);
3121
+ re += plEntry.open;
3122
+ if (plEntry.start === 0 && plEntry.type !== "!") {
3123
+ dotTravAllowed = true;
3124
+ re += subPatternStart(pattern.slice(i + 1));
3125
+ }
3126
+ this.debug("plType %j %j", stateChar, re);
3127
+ stateChar = false;
3128
+ continue;
3129
+ }
3130
+ case ")": {
3131
+ const plEntry = patternListStack[patternListStack.length - 1];
3132
+ if (!plEntry) {
3133
+ re += "\\)";
3134
+ continue;
3135
+ }
3136
+ patternListStack.pop();
3137
+ clearStateChar();
3138
+ hasMagic = true;
3139
+ pl = plEntry;
3140
+ re += pl.close;
3141
+ if (pl.type === "!") {
3142
+ negativeLists.push(Object.assign(pl, { reEnd: re.length }));
3143
+ }
3144
+ continue;
3145
+ }
3146
+ case "|": {
3147
+ const plEntry = patternListStack[patternListStack.length - 1];
3148
+ if (!plEntry) {
3149
+ re += "\\|";
3150
+ continue;
3151
+ }
3152
+ clearStateChar();
3153
+ re += "|";
3154
+ if (plEntry.start === 0 && plEntry.type !== "!") {
3155
+ dotTravAllowed = true;
3156
+ re += subPatternStart(pattern.slice(i + 1));
3157
+ }
3158
+ continue;
3159
+ }
3160
+ case "[":
3161
+ clearStateChar();
3162
+ const [src, needUflag, consumed, magic] = parseClass(pattern, i);
3163
+ if (consumed) {
3164
+ re += src;
3165
+ uflag = uflag || needUflag;
3166
+ i += consumed - 1;
3167
+ hasMagic = hasMagic || magic;
3168
+ } else {
3169
+ re += "\\[";
3170
+ }
3171
+ continue;
3172
+ case "]":
3173
+ re += "\\" + c;
3174
+ continue;
3175
+ default:
3176
+ clearStateChar();
3177
+ re += regExpEscape(c);
3178
+ break;
3179
+ }
3180
+ }
3181
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
3182
+ let tail;
3183
+ tail = re.slice(pl.reStart + pl.open.length);
3184
+ this.debug(this.pattern, "setting tail", re, pl);
3185
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
3186
+ if (!$2) {
3187
+ $2 = "\\";
3188
+ }
3189
+ return $1 + $1 + $2 + "|";
3190
+ });
3191
+ this.debug("tail=%j\n %s", tail, tail, pl, re);
3192
+ const t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
3193
+ hasMagic = true;
3194
+ re = re.slice(0, pl.reStart) + t + "\\(" + tail;
3195
+ }
3196
+ clearStateChar();
3197
+ if (escaping) {
3198
+ re += "\\\\";
3199
+ }
3200
+ const addPatternStart = addPatternStartSet[re.charAt(0)];
3201
+ for (let n = negativeLists.length - 1; n > -1; n--) {
3202
+ const nl = negativeLists[n];
3203
+ const nlBefore = re.slice(0, nl.reStart);
3204
+ const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
3205
+ let nlAfter = re.slice(nl.reEnd);
3206
+ const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
3207
+ const closeParensBefore = nlBefore.split(")").length;
3208
+ const openParensBefore = nlBefore.split("(").length - closeParensBefore;
3209
+ let cleanAfter = nlAfter;
3210
+ for (let i = 0; i < openParensBefore; i++) {
3211
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
3212
+ }
3213
+ nlAfter = cleanAfter;
3214
+ const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
3215
+ re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
3216
+ }
3217
+ if (re !== "" && hasMagic) {
3218
+ re = "(?=.)" + re;
3219
+ }
3220
+ if (addPatternStart) {
3221
+ re = patternStart() + re;
3222
+ }
3223
+ if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
3224
+ hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
3225
+ }
3226
+ if (!hasMagic) {
3227
+ return globUnescape(re);
3228
+ }
3229
+ const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
3230
+ try {
3231
+ const ext2 = fastTest ? {
3232
+ _glob: pattern,
3233
+ _src: re,
3234
+ test: fastTest
3235
+ } : {
3236
+ _glob: pattern,
3237
+ _src: re
3238
+ };
3239
+ return Object.assign(new RegExp("^" + re + "$", flags), ext2);
3240
+ } catch (er) {
3241
+ this.debug("invalid regexp", er);
3242
+ return new RegExp("$.");
3243
+ }
3244
+ }
3245
+ makeRe() {
3246
+ if (this.regexp || this.regexp === false)
3247
+ return this.regexp;
3248
+ const set = this.set;
3249
+ if (!set.length) {
3250
+ this.regexp = false;
3251
+ return this.regexp;
3252
+ }
3253
+ const options = this.options;
3254
+ const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
3255
+ const flags = options.nocase ? "i" : "";
3256
+ let re = set.map((pattern) => {
3257
+ const pp = pattern.map((p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src);
3258
+ pp.forEach((p, i) => {
3259
+ const next = pp[i + 1];
3260
+ const prev = pp[i - 1];
3261
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
3262
+ return;
3263
+ }
3264
+ if (prev === void 0) {
3265
+ if (next !== void 0 && next !== GLOBSTAR) {
3266
+ pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
3267
+ } else {
3268
+ pp[i] = twoStar;
3269
+ }
3270
+ } else if (next === void 0) {
3271
+ pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
3272
+ } else if (next !== GLOBSTAR) {
3273
+ pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
3274
+ pp[i + 1] = GLOBSTAR;
3275
+ }
3276
+ });
3277
+ return pp.filter((p) => p !== GLOBSTAR).join("/");
3278
+ }).join("|");
3279
+ re = "^(?:" + re + ")$";
3280
+ if (this.negate)
3281
+ re = "^(?!" + re + ").*$";
3282
+ try {
3283
+ this.regexp = new RegExp(re, flags);
3284
+ } catch (ex) {
3285
+ this.regexp = false;
3286
+ }
3287
+ return this.regexp;
3288
+ }
3289
+ slashSplit(p) {
3290
+ if (this.preserveMultipleSlashes) {
3291
+ return p.split("/");
3292
+ } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
3293
+ return ["", ...p.split(/\/+/)];
3294
+ } else {
3295
+ return p.split(/\/+/);
3296
+ }
3297
+ }
3298
+ match(f, partial = this.partial) {
3299
+ this.debug("match", f, this.pattern);
3300
+ if (this.comment) {
3301
+ return false;
3302
+ }
3303
+ if (this.empty) {
3304
+ return f === "";
3305
+ }
3306
+ if (f === "/" && partial) {
3307
+ return true;
3308
+ }
3309
+ const options = this.options;
3310
+ if (this.isWindows) {
3311
+ f = f.split("\\").join("/");
3312
+ }
3313
+ const ff = this.slashSplit(f);
3314
+ this.debug(this.pattern, "split", ff);
3315
+ const set = this.set;
3316
+ this.debug(this.pattern, "set", set);
3317
+ let filename = ff[ff.length - 1];
3318
+ if (!filename) {
3319
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
3320
+ filename = ff[i];
3321
+ }
3322
+ }
3323
+ for (let i = 0; i < set.length; i++) {
3324
+ const pattern = set[i];
3325
+ let file = ff;
3326
+ if (options.matchBase && pattern.length === 1) {
3327
+ file = [filename];
3328
+ }
3329
+ const hit = this.matchOne(file, pattern, partial);
3330
+ if (hit) {
3331
+ if (options.flipNegate) {
3332
+ return true;
3333
+ }
3334
+ return !this.negate;
3335
+ }
3336
+ }
3337
+ if (options.flipNegate) {
3338
+ return false;
3339
+ }
3340
+ return this.negate;
3341
+ }
3342
+ static defaults(def) {
3343
+ return minimatch.defaults(def).Minimatch;
3344
+ }
3345
+ };
3346
+ minimatch.Minimatch = Minimatch;
3347
+ minimatch.escape = escape;
3348
+ minimatch.unescape = unescape;
3349
+
3350
+ // src/cli/commands/sqliteIntrospect.ts
3351
+ var import_hanji2 = __toESM(require_hanji());
3352
+ var sqlitePushIntrospect = async (client, filters) => {
3353
+ const matchers = filters.map((it) => {
3354
+ return new Minimatch(it);
3355
+ });
3356
+ const filter2 = (tableName) => {
3357
+ if (matchers.length === 0)
3358
+ return true;
3359
+ for (let i = 0; i < matchers.length; i++) {
3360
+ const matcher = matchers[i];
3361
+ if (matcher.match(tableName))
3362
+ return true;
3363
+ }
3364
+ return false;
3365
+ };
3366
+ const res = await fromDatabase2(client, filter2);
3367
+ const schema = { id: originUUID, prevId: "", ...res };
3368
+ return { schema };
3369
+ };
3370
+
3371
+ // src/cli/commands/pgIntrospect.ts
3372
+ var import_hanji3 = __toESM(require_hanji());
3373
+ init_views();
3374
+ init_pgSerializer();
3375
+
3376
+ // src/introspect-pg.ts
3377
+ init_pgSerializer();
3378
+
3379
+ // src/cli/commands/pgIntrospect.ts
3380
+ var pgPushIntrospect = async (connection, filters, schemaFilters) => {
3381
+ const { client } = connection;
3382
+ const matchers = filters.map((it) => {
3383
+ return new Minimatch(it);
3384
+ });
3385
+ const filter2 = (tableName) => {
3386
+ if (matchers.length === 0)
3387
+ return true;
3388
+ for (let i = 0; i < matchers.length; i++) {
3389
+ const matcher = matchers[i];
3390
+ if (matcher.match(tableName))
3391
+ return true;
3392
+ }
3393
+ return false;
3394
+ };
3395
+ const res = await fromDatabase(client, filter2, schemaFilters);
3396
+ const schema = { id: originUUID, prevId: "", ...res };
3397
+ const { internal, ...schemaWithoutInternals } = schema;
3398
+ return { schema: schemaWithoutInternals };
3399
+ };
3400
+
3401
+ // src/utils-studio.ts
3402
+ init_drivers();
3403
+ export {
3404
+ DrizzleORMPgClient,
3405
+ TursoSqlite,
3406
+ toDrizzle as drizzleSchemaPg,
3407
+ toDrizzle2 as drizzleSchemaSQLite,
3408
+ pgPushIntrospect,
3409
+ sqlitePushIntrospect
3410
+ };