@prisma/cli-init 0.0.0-dev.202506161520 → 0.0.0-dev.202506171828

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,95 +1,3148 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
1
2
  import {
2
3
  credentialsFile,
3
4
  poll,
4
5
  printPpgInitOutput,
5
6
  requestOrThrow,
6
7
  successMessage
7
- } from "./chunk-XVYIFWIU.js";
8
+ } from "./chunk-CKLVKRSC.js";
9
+ import {
10
+ Engine,
11
+ encodeAPIKey,
12
+ ensureDirectory,
13
+ getDataDirPath,
14
+ integer,
15
+ literal,
16
+ minLength,
17
+ minValue,
18
+ number,
19
+ object,
20
+ optional,
21
+ parseJson,
22
+ pipe,
23
+ readDirectoryNames,
24
+ readFileAsText,
25
+ safeParse,
26
+ streamAsTextTo,
27
+ string,
28
+ url,
29
+ withResolvers,
30
+ y
31
+ } from "./chunk-ASMCGOOW.js";
32
+ import {
33
+ __commonJS,
34
+ __require,
35
+ __toESM
36
+ } from "./chunk-YX4UTTNJ.js";
37
+
38
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js
39
+ var require_polyfills = __commonJS({
40
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js"(exports, module) {
41
+ "use strict";
42
+ var constants = __require("constants");
43
+ var origCwd = process.cwd;
44
+ var cwd = null;
45
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
46
+ process.cwd = function() {
47
+ if (!cwd)
48
+ cwd = origCwd.call(process);
49
+ return cwd;
50
+ };
51
+ try {
52
+ process.cwd();
53
+ } catch (er) {
54
+ }
55
+ if (typeof process.chdir === "function") {
56
+ chdir = process.chdir;
57
+ process.chdir = function(d2) {
58
+ cwd = null;
59
+ chdir.call(process, d2);
60
+ };
61
+ if (Object.setPrototypeOf)
62
+ Object.setPrototypeOf(process.chdir, chdir);
63
+ }
64
+ var chdir;
65
+ module.exports = patch;
66
+ function patch(fs3) {
67
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
68
+ patchLchmod(fs3);
69
+ }
70
+ if (!fs3.lutimes) {
71
+ patchLutimes(fs3);
72
+ }
73
+ fs3.chown = chownFix(fs3.chown);
74
+ fs3.fchown = chownFix(fs3.fchown);
75
+ fs3.lchown = chownFix(fs3.lchown);
76
+ fs3.chmod = chmodFix(fs3.chmod);
77
+ fs3.fchmod = chmodFix(fs3.fchmod);
78
+ fs3.lchmod = chmodFix(fs3.lchmod);
79
+ fs3.chownSync = chownFixSync(fs3.chownSync);
80
+ fs3.fchownSync = chownFixSync(fs3.fchownSync);
81
+ fs3.lchownSync = chownFixSync(fs3.lchownSync);
82
+ fs3.chmodSync = chmodFixSync(fs3.chmodSync);
83
+ fs3.fchmodSync = chmodFixSync(fs3.fchmodSync);
84
+ fs3.lchmodSync = chmodFixSync(fs3.lchmodSync);
85
+ fs3.stat = statFix(fs3.stat);
86
+ fs3.fstat = statFix(fs3.fstat);
87
+ fs3.lstat = statFix(fs3.lstat);
88
+ fs3.statSync = statFixSync(fs3.statSync);
89
+ fs3.fstatSync = statFixSync(fs3.fstatSync);
90
+ fs3.lstatSync = statFixSync(fs3.lstatSync);
91
+ if (fs3.chmod && !fs3.lchmod) {
92
+ fs3.lchmod = function(path3, mode, cb) {
93
+ if (cb)
94
+ process.nextTick(cb);
95
+ };
96
+ fs3.lchmodSync = function() {
97
+ };
98
+ }
99
+ if (fs3.chown && !fs3.lchown) {
100
+ fs3.lchown = function(path3, uid, gid, cb) {
101
+ if (cb)
102
+ process.nextTick(cb);
103
+ };
104
+ fs3.lchownSync = function() {
105
+ };
106
+ }
107
+ if (platform === "win32") {
108
+ fs3.rename = typeof fs3.rename !== "function" ? fs3.rename : function(fs$rename) {
109
+ function rename(from, to, cb) {
110
+ var start = Date.now();
111
+ var backoff = 0;
112
+ fs$rename(from, to, function CB(er) {
113
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
114
+ setTimeout(function() {
115
+ fs3.stat(to, function(stater, st) {
116
+ if (stater && stater.code === "ENOENT")
117
+ fs$rename(from, to, CB);
118
+ else
119
+ cb(er);
120
+ });
121
+ }, backoff);
122
+ if (backoff < 100)
123
+ backoff += 10;
124
+ return;
125
+ }
126
+ if (cb)
127
+ cb(er);
128
+ });
129
+ }
130
+ if (Object.setPrototypeOf)
131
+ Object.setPrototypeOf(rename, fs$rename);
132
+ return rename;
133
+ }(fs3.rename);
134
+ }
135
+ fs3.read = typeof fs3.read !== "function" ? fs3.read : function(fs$read) {
136
+ function read(fd, buffer, offset, length, position, callback_) {
137
+ var callback;
138
+ if (callback_ && typeof callback_ === "function") {
139
+ var eagCounter = 0;
140
+ callback = function(er, _, __) {
141
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
142
+ eagCounter++;
143
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
144
+ }
145
+ callback_.apply(this, arguments);
146
+ };
147
+ }
148
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
149
+ }
150
+ if (Object.setPrototypeOf)
151
+ Object.setPrototypeOf(read, fs$read);
152
+ return read;
153
+ }(fs3.read);
154
+ fs3.readSync = typeof fs3.readSync !== "function" ? fs3.readSync : /* @__PURE__ */ function(fs$readSync) {
155
+ return function(fd, buffer, offset, length, position) {
156
+ var eagCounter = 0;
157
+ while (true) {
158
+ try {
159
+ return fs$readSync.call(fs3, fd, buffer, offset, length, position);
160
+ } catch (er) {
161
+ if (er.code === "EAGAIN" && eagCounter < 10) {
162
+ eagCounter++;
163
+ continue;
164
+ }
165
+ throw er;
166
+ }
167
+ }
168
+ };
169
+ }(fs3.readSync);
170
+ function patchLchmod(fs4) {
171
+ fs4.lchmod = function(path3, mode, callback) {
172
+ fs4.open(
173
+ path3,
174
+ constants.O_WRONLY | constants.O_SYMLINK,
175
+ mode,
176
+ function(err, fd) {
177
+ if (err) {
178
+ if (callback)
179
+ callback(err);
180
+ return;
181
+ }
182
+ fs4.fchmod(fd, mode, function(err2) {
183
+ fs4.close(fd, function(err22) {
184
+ if (callback)
185
+ callback(err2 || err22);
186
+ });
187
+ });
188
+ }
189
+ );
190
+ };
191
+ fs4.lchmodSync = function(path3, mode) {
192
+ var fd = fs4.openSync(path3, constants.O_WRONLY | constants.O_SYMLINK, mode);
193
+ var threw = true;
194
+ var ret;
195
+ try {
196
+ ret = fs4.fchmodSync(fd, mode);
197
+ threw = false;
198
+ } finally {
199
+ if (threw) {
200
+ try {
201
+ fs4.closeSync(fd);
202
+ } catch (er) {
203
+ }
204
+ } else {
205
+ fs4.closeSync(fd);
206
+ }
207
+ }
208
+ return ret;
209
+ };
210
+ }
211
+ function patchLutimes(fs4) {
212
+ if (constants.hasOwnProperty("O_SYMLINK") && fs4.futimes) {
213
+ fs4.lutimes = function(path3, at, mt, cb) {
214
+ fs4.open(path3, constants.O_SYMLINK, function(er, fd) {
215
+ if (er) {
216
+ if (cb)
217
+ cb(er);
218
+ return;
219
+ }
220
+ fs4.futimes(fd, at, mt, function(er2) {
221
+ fs4.close(fd, function(er22) {
222
+ if (cb)
223
+ cb(er2 || er22);
224
+ });
225
+ });
226
+ });
227
+ };
228
+ fs4.lutimesSync = function(path3, at, mt) {
229
+ var fd = fs4.openSync(path3, constants.O_SYMLINK);
230
+ var ret;
231
+ var threw = true;
232
+ try {
233
+ ret = fs4.futimesSync(fd, at, mt);
234
+ threw = false;
235
+ } finally {
236
+ if (threw) {
237
+ try {
238
+ fs4.closeSync(fd);
239
+ } catch (er) {
240
+ }
241
+ } else {
242
+ fs4.closeSync(fd);
243
+ }
244
+ }
245
+ return ret;
246
+ };
247
+ } else if (fs4.futimes) {
248
+ fs4.lutimes = function(_a, _b, _c, cb) {
249
+ if (cb)
250
+ process.nextTick(cb);
251
+ };
252
+ fs4.lutimesSync = function() {
253
+ };
254
+ }
255
+ }
256
+ function chmodFix(orig) {
257
+ if (!orig)
258
+ return orig;
259
+ return function(target, mode, cb) {
260
+ return orig.call(fs3, target, mode, function(er) {
261
+ if (chownErOk(er))
262
+ er = null;
263
+ if (cb)
264
+ cb.apply(this, arguments);
265
+ });
266
+ };
267
+ }
268
+ function chmodFixSync(orig) {
269
+ if (!orig)
270
+ return orig;
271
+ return function(target, mode) {
272
+ try {
273
+ return orig.call(fs3, target, mode);
274
+ } catch (er) {
275
+ if (!chownErOk(er))
276
+ throw er;
277
+ }
278
+ };
279
+ }
280
+ function chownFix(orig) {
281
+ if (!orig)
282
+ return orig;
283
+ return function(target, uid, gid, cb) {
284
+ return orig.call(fs3, target, uid, gid, function(er) {
285
+ if (chownErOk(er))
286
+ er = null;
287
+ if (cb)
288
+ cb.apply(this, arguments);
289
+ });
290
+ };
291
+ }
292
+ function chownFixSync(orig) {
293
+ if (!orig)
294
+ return orig;
295
+ return function(target, uid, gid) {
296
+ try {
297
+ return orig.call(fs3, target, uid, gid);
298
+ } catch (er) {
299
+ if (!chownErOk(er))
300
+ throw er;
301
+ }
302
+ };
303
+ }
304
+ function statFix(orig) {
305
+ if (!orig)
306
+ return orig;
307
+ return function(target, options, cb) {
308
+ if (typeof options === "function") {
309
+ cb = options;
310
+ options = null;
311
+ }
312
+ function callback(er, stats) {
313
+ if (stats) {
314
+ if (stats.uid < 0)
315
+ stats.uid += 4294967296;
316
+ if (stats.gid < 0)
317
+ stats.gid += 4294967296;
318
+ }
319
+ if (cb)
320
+ cb.apply(this, arguments);
321
+ }
322
+ return options ? orig.call(fs3, target, options, callback) : orig.call(fs3, target, callback);
323
+ };
324
+ }
325
+ function statFixSync(orig) {
326
+ if (!orig)
327
+ return orig;
328
+ return function(target, options) {
329
+ var stats = options ? orig.call(fs3, target, options) : orig.call(fs3, target);
330
+ if (stats) {
331
+ if (stats.uid < 0)
332
+ stats.uid += 4294967296;
333
+ if (stats.gid < 0)
334
+ stats.gid += 4294967296;
335
+ }
336
+ return stats;
337
+ };
338
+ }
339
+ function chownErOk(er) {
340
+ if (!er)
341
+ return true;
342
+ if (er.code === "ENOSYS")
343
+ return true;
344
+ var nonroot = !process.getuid || process.getuid() !== 0;
345
+ if (nonroot) {
346
+ if (er.code === "EINVAL" || er.code === "EPERM")
347
+ return true;
348
+ }
349
+ return false;
350
+ }
351
+ }
352
+ }
353
+ });
354
+
355
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js
356
+ var require_legacy_streams = __commonJS({
357
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js"(exports, module) {
358
+ "use strict";
359
+ var Stream = __require("stream").Stream;
360
+ module.exports = legacy;
361
+ function legacy(fs3) {
362
+ return {
363
+ ReadStream,
364
+ WriteStream
365
+ };
366
+ function ReadStream(path3, options) {
367
+ if (!(this instanceof ReadStream))
368
+ return new ReadStream(path3, options);
369
+ Stream.call(this);
370
+ var self = this;
371
+ this.path = path3;
372
+ this.fd = null;
373
+ this.readable = true;
374
+ this.paused = false;
375
+ this.flags = "r";
376
+ this.mode = 438;
377
+ this.bufferSize = 64 * 1024;
378
+ options = options || {};
379
+ var keys = Object.keys(options);
380
+ for (var index = 0, length = keys.length; index < length; index++) {
381
+ var key = keys[index];
382
+ this[key] = options[key];
383
+ }
384
+ if (this.encoding)
385
+ this.setEncoding(this.encoding);
386
+ if (this.start !== void 0) {
387
+ if ("number" !== typeof this.start) {
388
+ throw TypeError("start must be a Number");
389
+ }
390
+ if (this.end === void 0) {
391
+ this.end = Infinity;
392
+ } else if ("number" !== typeof this.end) {
393
+ throw TypeError("end must be a Number");
394
+ }
395
+ if (this.start > this.end) {
396
+ throw new Error("start must be <= end");
397
+ }
398
+ this.pos = this.start;
399
+ }
400
+ if (this.fd !== null) {
401
+ process.nextTick(function() {
402
+ self._read();
403
+ });
404
+ return;
405
+ }
406
+ fs3.open(this.path, this.flags, this.mode, function(err, fd) {
407
+ if (err) {
408
+ self.emit("error", err);
409
+ self.readable = false;
410
+ return;
411
+ }
412
+ self.fd = fd;
413
+ self.emit("open", fd);
414
+ self._read();
415
+ });
416
+ }
417
+ function WriteStream(path3, options) {
418
+ if (!(this instanceof WriteStream))
419
+ return new WriteStream(path3, options);
420
+ Stream.call(this);
421
+ this.path = path3;
422
+ this.fd = null;
423
+ this.writable = true;
424
+ this.flags = "w";
425
+ this.encoding = "binary";
426
+ this.mode = 438;
427
+ this.bytesWritten = 0;
428
+ options = options || {};
429
+ var keys = Object.keys(options);
430
+ for (var index = 0, length = keys.length; index < length; index++) {
431
+ var key = keys[index];
432
+ this[key] = options[key];
433
+ }
434
+ if (this.start !== void 0) {
435
+ if ("number" !== typeof this.start) {
436
+ throw TypeError("start must be a Number");
437
+ }
438
+ if (this.start < 0) {
439
+ throw new Error("start must be >= zero");
440
+ }
441
+ this.pos = this.start;
442
+ }
443
+ this.busy = false;
444
+ this._queue = [];
445
+ if (this.fd === null) {
446
+ this._open = fs3.open;
447
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
448
+ this.flush();
449
+ }
450
+ }
451
+ }
452
+ }
453
+ });
454
+
455
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js
456
+ var require_clone = __commonJS({
457
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js"(exports, module) {
458
+ "use strict";
459
+ module.exports = clone;
460
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
461
+ return obj.__proto__;
462
+ };
463
+ function clone(obj) {
464
+ if (obj === null || typeof obj !== "object")
465
+ return obj;
466
+ if (obj instanceof Object)
467
+ var copy = { __proto__: getPrototypeOf(obj) };
468
+ else
469
+ var copy = /* @__PURE__ */ Object.create(null);
470
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
471
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
472
+ });
473
+ return copy;
474
+ }
475
+ }
476
+ });
477
+
478
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
479
+ var require_graceful_fs = __commonJS({
480
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js"(exports, module) {
481
+ "use strict";
482
+ var fs3 = __require("fs");
483
+ var polyfills = require_polyfills();
484
+ var legacy = require_legacy_streams();
485
+ var clone = require_clone();
486
+ var util = __require("util");
487
+ var gracefulQueue;
488
+ var previousSymbol;
489
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
490
+ gracefulQueue = Symbol.for("graceful-fs.queue");
491
+ previousSymbol = Symbol.for("graceful-fs.previous");
492
+ } else {
493
+ gracefulQueue = "___graceful-fs.queue";
494
+ previousSymbol = "___graceful-fs.previous";
495
+ }
496
+ function noop() {
497
+ }
498
+ function publishQueue(context, queue2) {
499
+ Object.defineProperty(context, gracefulQueue, {
500
+ get: function() {
501
+ return queue2;
502
+ }
503
+ });
504
+ }
505
+ var debug = noop;
506
+ if (util.debuglog)
507
+ debug = util.debuglog("gfs4");
508
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
509
+ debug = function() {
510
+ var m = util.format.apply(util, arguments);
511
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
512
+ console.error(m);
513
+ };
514
+ if (!fs3[gracefulQueue]) {
515
+ queue = global[gracefulQueue] || [];
516
+ publishQueue(fs3, queue);
517
+ fs3.close = function(fs$close) {
518
+ function close(fd, cb) {
519
+ return fs$close.call(fs3, fd, function(err) {
520
+ if (!err) {
521
+ resetQueue();
522
+ }
523
+ if (typeof cb === "function")
524
+ cb.apply(this, arguments);
525
+ });
526
+ }
527
+ Object.defineProperty(close, previousSymbol, {
528
+ value: fs$close
529
+ });
530
+ return close;
531
+ }(fs3.close);
532
+ fs3.closeSync = function(fs$closeSync) {
533
+ function closeSync(fd) {
534
+ fs$closeSync.apply(fs3, arguments);
535
+ resetQueue();
536
+ }
537
+ Object.defineProperty(closeSync, previousSymbol, {
538
+ value: fs$closeSync
539
+ });
540
+ return closeSync;
541
+ }(fs3.closeSync);
542
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
543
+ process.on("exit", function() {
544
+ debug(fs3[gracefulQueue]);
545
+ __require("assert").equal(fs3[gracefulQueue].length, 0);
546
+ });
547
+ }
548
+ }
549
+ var queue;
550
+ if (!global[gracefulQueue]) {
551
+ publishQueue(global, fs3[gracefulQueue]);
552
+ }
553
+ module.exports = patch(clone(fs3));
554
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs3.__patched) {
555
+ module.exports = patch(fs3);
556
+ fs3.__patched = true;
557
+ }
558
+ function patch(fs4) {
559
+ polyfills(fs4);
560
+ fs4.gracefulify = patch;
561
+ fs4.createReadStream = createReadStream;
562
+ fs4.createWriteStream = createWriteStream;
563
+ var fs$readFile = fs4.readFile;
564
+ fs4.readFile = readFile;
565
+ function readFile(path3, options, cb) {
566
+ if (typeof options === "function")
567
+ cb = options, options = null;
568
+ return go$readFile(path3, options, cb);
569
+ function go$readFile(path4, options2, cb2, startTime) {
570
+ return fs$readFile(path4, options2, function(err) {
571
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
572
+ enqueue([go$readFile, [path4, options2, cb2], err, startTime || Date.now(), Date.now()]);
573
+ else {
574
+ if (typeof cb2 === "function")
575
+ cb2.apply(this, arguments);
576
+ }
577
+ });
578
+ }
579
+ }
580
+ var fs$writeFile = fs4.writeFile;
581
+ fs4.writeFile = writeFile2;
582
+ function writeFile2(path3, data, options, cb) {
583
+ if (typeof options === "function")
584
+ cb = options, options = null;
585
+ return go$writeFile(path3, data, options, cb);
586
+ function go$writeFile(path4, data2, options2, cb2, startTime) {
587
+ return fs$writeFile(path4, data2, options2, function(err) {
588
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
589
+ enqueue([go$writeFile, [path4, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
590
+ else {
591
+ if (typeof cb2 === "function")
592
+ cb2.apply(this, arguments);
593
+ }
594
+ });
595
+ }
596
+ }
597
+ var fs$appendFile = fs4.appendFile;
598
+ if (fs$appendFile)
599
+ fs4.appendFile = appendFile;
600
+ function appendFile(path3, data, options, cb) {
601
+ if (typeof options === "function")
602
+ cb = options, options = null;
603
+ return go$appendFile(path3, data, options, cb);
604
+ function go$appendFile(path4, data2, options2, cb2, startTime) {
605
+ return fs$appendFile(path4, data2, options2, function(err) {
606
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
607
+ enqueue([go$appendFile, [path4, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
608
+ else {
609
+ if (typeof cb2 === "function")
610
+ cb2.apply(this, arguments);
611
+ }
612
+ });
613
+ }
614
+ }
615
+ var fs$copyFile = fs4.copyFile;
616
+ if (fs$copyFile)
617
+ fs4.copyFile = copyFile;
618
+ function copyFile(src, dest, flags, cb) {
619
+ if (typeof flags === "function") {
620
+ cb = flags;
621
+ flags = 0;
622
+ }
623
+ return go$copyFile(src, dest, flags, cb);
624
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
625
+ return fs$copyFile(src2, dest2, flags2, function(err) {
626
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
627
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
628
+ else {
629
+ if (typeof cb2 === "function")
630
+ cb2.apply(this, arguments);
631
+ }
632
+ });
633
+ }
634
+ }
635
+ var fs$readdir = fs4.readdir;
636
+ fs4.readdir = readdir;
637
+ var noReaddirOptionVersions = /^v[0-5]\./;
638
+ function readdir(path3, options, cb) {
639
+ if (typeof options === "function")
640
+ cb = options, options = null;
641
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path4, options2, cb2, startTime) {
642
+ return fs$readdir(path4, fs$readdirCallback(
643
+ path4,
644
+ options2,
645
+ cb2,
646
+ startTime
647
+ ));
648
+ } : function go$readdir2(path4, options2, cb2, startTime) {
649
+ return fs$readdir(path4, options2, fs$readdirCallback(
650
+ path4,
651
+ options2,
652
+ cb2,
653
+ startTime
654
+ ));
655
+ };
656
+ return go$readdir(path3, options, cb);
657
+ function fs$readdirCallback(path4, options2, cb2, startTime) {
658
+ return function(err, files) {
659
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
660
+ enqueue([
661
+ go$readdir,
662
+ [path4, options2, cb2],
663
+ err,
664
+ startTime || Date.now(),
665
+ Date.now()
666
+ ]);
667
+ else {
668
+ if (files && files.sort)
669
+ files.sort();
670
+ if (typeof cb2 === "function")
671
+ cb2.call(this, err, files);
672
+ }
673
+ };
674
+ }
675
+ }
676
+ if (process.version.substr(0, 4) === "v0.8") {
677
+ var legStreams = legacy(fs4);
678
+ ReadStream = legStreams.ReadStream;
679
+ WriteStream = legStreams.WriteStream;
680
+ }
681
+ var fs$ReadStream = fs4.ReadStream;
682
+ if (fs$ReadStream) {
683
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
684
+ ReadStream.prototype.open = ReadStream$open;
685
+ }
686
+ var fs$WriteStream = fs4.WriteStream;
687
+ if (fs$WriteStream) {
688
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
689
+ WriteStream.prototype.open = WriteStream$open;
690
+ }
691
+ Object.defineProperty(fs4, "ReadStream", {
692
+ get: function() {
693
+ return ReadStream;
694
+ },
695
+ set: function(val) {
696
+ ReadStream = val;
697
+ },
698
+ enumerable: true,
699
+ configurable: true
700
+ });
701
+ Object.defineProperty(fs4, "WriteStream", {
702
+ get: function() {
703
+ return WriteStream;
704
+ },
705
+ set: function(val) {
706
+ WriteStream = val;
707
+ },
708
+ enumerable: true,
709
+ configurable: true
710
+ });
711
+ var FileReadStream = ReadStream;
712
+ Object.defineProperty(fs4, "FileReadStream", {
713
+ get: function() {
714
+ return FileReadStream;
715
+ },
716
+ set: function(val) {
717
+ FileReadStream = val;
718
+ },
719
+ enumerable: true,
720
+ configurable: true
721
+ });
722
+ var FileWriteStream = WriteStream;
723
+ Object.defineProperty(fs4, "FileWriteStream", {
724
+ get: function() {
725
+ return FileWriteStream;
726
+ },
727
+ set: function(val) {
728
+ FileWriteStream = val;
729
+ },
730
+ enumerable: true,
731
+ configurable: true
732
+ });
733
+ function ReadStream(path3, options) {
734
+ if (this instanceof ReadStream)
735
+ return fs$ReadStream.apply(this, arguments), this;
736
+ else
737
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
738
+ }
739
+ function ReadStream$open() {
740
+ var that = this;
741
+ open(that.path, that.flags, that.mode, function(err, fd) {
742
+ if (err) {
743
+ if (that.autoClose)
744
+ that.destroy();
745
+ that.emit("error", err);
746
+ } else {
747
+ that.fd = fd;
748
+ that.emit("open", fd);
749
+ that.read();
750
+ }
751
+ });
752
+ }
753
+ function WriteStream(path3, options) {
754
+ if (this instanceof WriteStream)
755
+ return fs$WriteStream.apply(this, arguments), this;
756
+ else
757
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
758
+ }
759
+ function WriteStream$open() {
760
+ var that = this;
761
+ open(that.path, that.flags, that.mode, function(err, fd) {
762
+ if (err) {
763
+ that.destroy();
764
+ that.emit("error", err);
765
+ } else {
766
+ that.fd = fd;
767
+ that.emit("open", fd);
768
+ }
769
+ });
770
+ }
771
+ function createReadStream(path3, options) {
772
+ return new fs4.ReadStream(path3, options);
773
+ }
774
+ function createWriteStream(path3, options) {
775
+ return new fs4.WriteStream(path3, options);
776
+ }
777
+ var fs$open = fs4.open;
778
+ fs4.open = open;
779
+ function open(path3, flags, mode, cb) {
780
+ if (typeof mode === "function")
781
+ cb = mode, mode = null;
782
+ return go$open(path3, flags, mode, cb);
783
+ function go$open(path4, flags2, mode2, cb2, startTime) {
784
+ return fs$open(path4, flags2, mode2, function(err, fd) {
785
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
786
+ enqueue([go$open, [path4, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
787
+ else {
788
+ if (typeof cb2 === "function")
789
+ cb2.apply(this, arguments);
790
+ }
791
+ });
792
+ }
793
+ }
794
+ return fs4;
795
+ }
796
+ function enqueue(elem) {
797
+ debug("ENQUEUE", elem[0].name, elem[1]);
798
+ fs3[gracefulQueue].push(elem);
799
+ retry();
800
+ }
801
+ var retryTimer;
802
+ function resetQueue() {
803
+ var now = Date.now();
804
+ for (var i = 0; i < fs3[gracefulQueue].length; ++i) {
805
+ if (fs3[gracefulQueue][i].length > 2) {
806
+ fs3[gracefulQueue][i][3] = now;
807
+ fs3[gracefulQueue][i][4] = now;
808
+ }
809
+ }
810
+ retry();
811
+ }
812
+ function retry() {
813
+ clearTimeout(retryTimer);
814
+ retryTimer = void 0;
815
+ if (fs3[gracefulQueue].length === 0)
816
+ return;
817
+ var elem = fs3[gracefulQueue].shift();
818
+ var fn = elem[0];
819
+ var args = elem[1];
820
+ var err = elem[2];
821
+ var startTime = elem[3];
822
+ var lastTime = elem[4];
823
+ if (startTime === void 0) {
824
+ debug("RETRY", fn.name, args);
825
+ fn.apply(null, args);
826
+ } else if (Date.now() - startTime >= 6e4) {
827
+ debug("TIMEOUT", fn.name, args);
828
+ var cb = args.pop();
829
+ if (typeof cb === "function")
830
+ cb.call(null, err);
831
+ } else {
832
+ var sinceAttempt = Date.now() - lastTime;
833
+ var sinceStart = Math.max(lastTime - startTime, 1);
834
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
835
+ if (sinceAttempt >= desiredDelay) {
836
+ debug("RETRY", fn.name, args);
837
+ fn.apply(null, args.concat([startTime]));
838
+ } else {
839
+ fs3[gracefulQueue].push(elem);
840
+ }
841
+ }
842
+ if (retryTimer === void 0) {
843
+ retryTimer = setTimeout(retry, 0);
844
+ }
845
+ }
846
+ }
847
+ });
848
+
849
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js
850
+ var require_retry_operation = __commonJS({
851
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js"(exports, module) {
852
+ "use strict";
853
+ function RetryOperation(timeouts, options) {
854
+ if (typeof options === "boolean") {
855
+ options = { forever: options };
856
+ }
857
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
858
+ this._timeouts = timeouts;
859
+ this._options = options || {};
860
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
861
+ this._fn = null;
862
+ this._errors = [];
863
+ this._attempts = 1;
864
+ this._operationTimeout = null;
865
+ this._operationTimeoutCb = null;
866
+ this._timeout = null;
867
+ this._operationStart = null;
868
+ if (this._options.forever) {
869
+ this._cachedTimeouts = this._timeouts.slice(0);
870
+ }
871
+ }
872
+ module.exports = RetryOperation;
873
+ RetryOperation.prototype.reset = function() {
874
+ this._attempts = 1;
875
+ this._timeouts = this._originalTimeouts;
876
+ };
877
+ RetryOperation.prototype.stop = function() {
878
+ if (this._timeout) {
879
+ clearTimeout(this._timeout);
880
+ }
881
+ this._timeouts = [];
882
+ this._cachedTimeouts = null;
883
+ };
884
+ RetryOperation.prototype.retry = function(err) {
885
+ if (this._timeout) {
886
+ clearTimeout(this._timeout);
887
+ }
888
+ if (!err) {
889
+ return false;
890
+ }
891
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
892
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
893
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
894
+ return false;
895
+ }
896
+ this._errors.push(err);
897
+ var timeout = this._timeouts.shift();
898
+ if (timeout === void 0) {
899
+ if (this._cachedTimeouts) {
900
+ this._errors.splice(this._errors.length - 1, this._errors.length);
901
+ this._timeouts = this._cachedTimeouts.slice(0);
902
+ timeout = this._timeouts.shift();
903
+ } else {
904
+ return false;
905
+ }
906
+ }
907
+ var self = this;
908
+ var timer = setTimeout(function() {
909
+ self._attempts++;
910
+ if (self._operationTimeoutCb) {
911
+ self._timeout = setTimeout(function() {
912
+ self._operationTimeoutCb(self._attempts);
913
+ }, self._operationTimeout);
914
+ if (self._options.unref) {
915
+ self._timeout.unref();
916
+ }
917
+ }
918
+ self._fn(self._attempts);
919
+ }, timeout);
920
+ if (this._options.unref) {
921
+ timer.unref();
922
+ }
923
+ return true;
924
+ };
925
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
926
+ this._fn = fn;
927
+ if (timeoutOps) {
928
+ if (timeoutOps.timeout) {
929
+ this._operationTimeout = timeoutOps.timeout;
930
+ }
931
+ if (timeoutOps.cb) {
932
+ this._operationTimeoutCb = timeoutOps.cb;
933
+ }
934
+ }
935
+ var self = this;
936
+ if (this._operationTimeoutCb) {
937
+ this._timeout = setTimeout(function() {
938
+ self._operationTimeoutCb();
939
+ }, self._operationTimeout);
940
+ }
941
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
942
+ this._fn(this._attempts);
943
+ };
944
+ RetryOperation.prototype.try = function(fn) {
945
+ console.log("Using RetryOperation.try() is deprecated");
946
+ this.attempt(fn);
947
+ };
948
+ RetryOperation.prototype.start = function(fn) {
949
+ console.log("Using RetryOperation.start() is deprecated");
950
+ this.attempt(fn);
951
+ };
952
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
953
+ RetryOperation.prototype.errors = function() {
954
+ return this._errors;
955
+ };
956
+ RetryOperation.prototype.attempts = function() {
957
+ return this._attempts;
958
+ };
959
+ RetryOperation.prototype.mainError = function() {
960
+ if (this._errors.length === 0) {
961
+ return null;
962
+ }
963
+ var counts = {};
964
+ var mainError = null;
965
+ var mainErrorCount = 0;
966
+ for (var i = 0; i < this._errors.length; i++) {
967
+ var error = this._errors[i];
968
+ var message = error.message;
969
+ var count = (counts[message] || 0) + 1;
970
+ counts[message] = count;
971
+ if (count >= mainErrorCount) {
972
+ mainError = error;
973
+ mainErrorCount = count;
974
+ }
975
+ }
976
+ return mainError;
977
+ };
978
+ }
979
+ });
980
+
981
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js
982
+ var require_retry = __commonJS({
983
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js"(exports) {
984
+ "use strict";
985
+ var RetryOperation = require_retry_operation();
986
+ exports.operation = function(options) {
987
+ var timeouts = exports.timeouts(options);
988
+ return new RetryOperation(timeouts, {
989
+ forever: options && options.forever,
990
+ unref: options && options.unref,
991
+ maxRetryTime: options && options.maxRetryTime
992
+ });
993
+ };
994
+ exports.timeouts = function(options) {
995
+ if (options instanceof Array) {
996
+ return [].concat(options);
997
+ }
998
+ var opts = {
999
+ retries: 10,
1000
+ factor: 2,
1001
+ minTimeout: 1 * 1e3,
1002
+ maxTimeout: Infinity,
1003
+ randomize: false
1004
+ };
1005
+ for (var key in options) {
1006
+ opts[key] = options[key];
1007
+ }
1008
+ if (opts.minTimeout > opts.maxTimeout) {
1009
+ throw new Error("minTimeout is greater than maxTimeout");
1010
+ }
1011
+ var timeouts = [];
1012
+ for (var i = 0; i < opts.retries; i++) {
1013
+ timeouts.push(this.createTimeout(i, opts));
1014
+ }
1015
+ if (options && options.forever && !timeouts.length) {
1016
+ timeouts.push(this.createTimeout(i, opts));
1017
+ }
1018
+ timeouts.sort(function(a2, b) {
1019
+ return a2 - b;
1020
+ });
1021
+ return timeouts;
1022
+ };
1023
+ exports.createTimeout = function(attempt, opts) {
1024
+ var random = opts.randomize ? Math.random() + 1 : 1;
1025
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
1026
+ timeout = Math.min(timeout, opts.maxTimeout);
1027
+ return timeout;
1028
+ };
1029
+ exports.wrap = function(obj, options, methods) {
1030
+ if (options instanceof Array) {
1031
+ methods = options;
1032
+ options = null;
1033
+ }
1034
+ if (!methods) {
1035
+ methods = [];
1036
+ for (var key in obj) {
1037
+ if (typeof obj[key] === "function") {
1038
+ methods.push(key);
1039
+ }
1040
+ }
1041
+ }
1042
+ for (var i = 0; i < methods.length; i++) {
1043
+ var method = methods[i];
1044
+ var original = obj[method];
1045
+ obj[method] = function retryWrapper(original2) {
1046
+ var op = exports.operation(options);
1047
+ var args = Array.prototype.slice.call(arguments, 1);
1048
+ var callback = args.pop();
1049
+ args.push(function(err) {
1050
+ if (op.retry(err)) {
1051
+ return;
1052
+ }
1053
+ if (err) {
1054
+ arguments[0] = op.mainError();
1055
+ }
1056
+ callback.apply(this, arguments);
1057
+ });
1058
+ op.attempt(function() {
1059
+ original2.apply(obj, args);
1060
+ });
1061
+ }.bind(obj, original);
1062
+ obj[method].options = options;
1063
+ }
1064
+ };
1065
+ }
1066
+ });
1067
+
1068
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js
1069
+ var require_retry2 = __commonJS({
1070
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js"(exports, module) {
1071
+ "use strict";
1072
+ module.exports = require_retry();
1073
+ }
1074
+ });
1075
+
1076
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
1077
+ var require_signals = __commonJS({
1078
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports, module) {
1079
+ "use strict";
1080
+ module.exports = [
1081
+ "SIGABRT",
1082
+ "SIGALRM",
1083
+ "SIGHUP",
1084
+ "SIGINT",
1085
+ "SIGTERM"
1086
+ ];
1087
+ if (process.platform !== "win32") {
1088
+ module.exports.push(
1089
+ "SIGVTALRM",
1090
+ "SIGXCPU",
1091
+ "SIGXFSZ",
1092
+ "SIGUSR2",
1093
+ "SIGTRAP",
1094
+ "SIGSYS",
1095
+ "SIGQUIT",
1096
+ "SIGIOT"
1097
+ // should detect profiler and enable/disable accordingly.
1098
+ // see #21
1099
+ // 'SIGPROF'
1100
+ );
1101
+ }
1102
+ if (process.platform === "linux") {
1103
+ module.exports.push(
1104
+ "SIGIO",
1105
+ "SIGPOLL",
1106
+ "SIGPWR",
1107
+ "SIGSTKFLT",
1108
+ "SIGUNUSED"
1109
+ );
1110
+ }
1111
+ }
1112
+ });
1113
+
1114
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
1115
+ var require_signal_exit = __commonJS({
1116
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports, module) {
1117
+ "use strict";
1118
+ var process2 = global.process;
1119
+ var processOk = function(process3) {
1120
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
1121
+ };
1122
+ if (!processOk(process2)) {
1123
+ module.exports = function() {
1124
+ return function() {
1125
+ };
1126
+ };
1127
+ } else {
1128
+ assert = __require("assert");
1129
+ signals = require_signals();
1130
+ isWin = /^win/i.test(process2.platform);
1131
+ EE = __require("events");
1132
+ if (typeof EE !== "function") {
1133
+ EE = EE.EventEmitter;
1134
+ }
1135
+ if (process2.__signal_exit_emitter__) {
1136
+ emitter = process2.__signal_exit_emitter__;
1137
+ } else {
1138
+ emitter = process2.__signal_exit_emitter__ = new EE();
1139
+ emitter.count = 0;
1140
+ emitter.emitted = {};
1141
+ }
1142
+ if (!emitter.infinite) {
1143
+ emitter.setMaxListeners(Infinity);
1144
+ emitter.infinite = true;
1145
+ }
1146
+ module.exports = function(cb, opts) {
1147
+ if (!processOk(global.process)) {
1148
+ return function() {
1149
+ };
1150
+ }
1151
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1152
+ if (loaded === false) {
1153
+ load();
1154
+ }
1155
+ var ev = "exit";
1156
+ if (opts && opts.alwaysLast) {
1157
+ ev = "afterexit";
1158
+ }
1159
+ var remove = function() {
1160
+ emitter.removeListener(ev, cb);
1161
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1162
+ unload();
1163
+ }
1164
+ };
1165
+ emitter.on(ev, cb);
1166
+ return remove;
1167
+ };
1168
+ unload = function unload2() {
1169
+ if (!loaded || !processOk(global.process)) {
1170
+ return;
1171
+ }
1172
+ loaded = false;
1173
+ signals.forEach(function(sig) {
1174
+ try {
1175
+ process2.removeListener(sig, sigListeners[sig]);
1176
+ } catch (er) {
1177
+ }
1178
+ });
1179
+ process2.emit = originalProcessEmit;
1180
+ process2.reallyExit = originalProcessReallyExit;
1181
+ emitter.count -= 1;
1182
+ };
1183
+ module.exports.unload = unload;
1184
+ emit = function emit2(event, code, signal) {
1185
+ if (emitter.emitted[event]) {
1186
+ return;
1187
+ }
1188
+ emitter.emitted[event] = true;
1189
+ emitter.emit(event, code, signal);
1190
+ };
1191
+ sigListeners = {};
1192
+ signals.forEach(function(sig) {
1193
+ sigListeners[sig] = function listener() {
1194
+ if (!processOk(global.process)) {
1195
+ return;
1196
+ }
1197
+ var listeners = process2.listeners(sig);
1198
+ if (listeners.length === emitter.count) {
1199
+ unload();
1200
+ emit("exit", null, sig);
1201
+ emit("afterexit", null, sig);
1202
+ if (isWin && sig === "SIGHUP") {
1203
+ sig = "SIGINT";
1204
+ }
1205
+ process2.kill(process2.pid, sig);
1206
+ }
1207
+ };
1208
+ });
1209
+ module.exports.signals = function() {
1210
+ return signals;
1211
+ };
1212
+ loaded = false;
1213
+ load = function load2() {
1214
+ if (loaded || !processOk(global.process)) {
1215
+ return;
1216
+ }
1217
+ loaded = true;
1218
+ emitter.count += 1;
1219
+ signals = signals.filter(function(sig) {
1220
+ try {
1221
+ process2.on(sig, sigListeners[sig]);
1222
+ return true;
1223
+ } catch (er) {
1224
+ return false;
1225
+ }
1226
+ });
1227
+ process2.emit = processEmit;
1228
+ process2.reallyExit = processReallyExit;
1229
+ };
1230
+ module.exports.load = load;
1231
+ originalProcessReallyExit = process2.reallyExit;
1232
+ processReallyExit = function processReallyExit2(code) {
1233
+ if (!processOk(global.process)) {
1234
+ return;
1235
+ }
1236
+ process2.exitCode = code || /* istanbul ignore next */
1237
+ 0;
1238
+ emit("exit", process2.exitCode, null);
1239
+ emit("afterexit", process2.exitCode, null);
1240
+ originalProcessReallyExit.call(process2, process2.exitCode);
1241
+ };
1242
+ originalProcessEmit = process2.emit;
1243
+ processEmit = function processEmit2(ev, arg) {
1244
+ if (ev === "exit" && processOk(global.process)) {
1245
+ if (arg !== void 0) {
1246
+ process2.exitCode = arg;
1247
+ }
1248
+ var ret = originalProcessEmit.apply(this, arguments);
1249
+ emit("exit", process2.exitCode, null);
1250
+ emit("afterexit", process2.exitCode, null);
1251
+ return ret;
1252
+ } else {
1253
+ return originalProcessEmit.apply(this, arguments);
1254
+ }
1255
+ };
1256
+ }
1257
+ var assert;
1258
+ var signals;
1259
+ var isWin;
1260
+ var EE;
1261
+ var emitter;
1262
+ var unload;
1263
+ var emit;
1264
+ var sigListeners;
1265
+ var loaded;
1266
+ var load;
1267
+ var originalProcessReallyExit;
1268
+ var processReallyExit;
1269
+ var originalProcessEmit;
1270
+ var processEmit;
1271
+ }
1272
+ });
1273
+
1274
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js
1275
+ var require_mtime_precision = __commonJS({
1276
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js"(exports, module) {
1277
+ "use strict";
1278
+ var cacheSymbol = Symbol();
1279
+ function probe(file, fs3, callback) {
1280
+ const cachedPrecision = fs3[cacheSymbol];
1281
+ if (cachedPrecision) {
1282
+ return fs3.stat(file, (err, stat) => {
1283
+ if (err) {
1284
+ return callback(err);
1285
+ }
1286
+ callback(null, stat.mtime, cachedPrecision);
1287
+ });
1288
+ }
1289
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
1290
+ fs3.utimes(file, mtime, mtime, (err) => {
1291
+ if (err) {
1292
+ return callback(err);
1293
+ }
1294
+ fs3.stat(file, (err2, stat) => {
1295
+ if (err2) {
1296
+ return callback(err2);
1297
+ }
1298
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1299
+ Object.defineProperty(fs3, cacheSymbol, { value: precision });
1300
+ callback(null, stat.mtime, precision);
1301
+ });
1302
+ });
1303
+ }
1304
+ function getMtime(precision) {
1305
+ let now = Date.now();
1306
+ if (precision === "s") {
1307
+ now = Math.ceil(now / 1e3) * 1e3;
1308
+ }
1309
+ return new Date(now);
1310
+ }
1311
+ module.exports.probe = probe;
1312
+ module.exports.getMtime = getMtime;
1313
+ }
1314
+ });
1315
+
1316
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
1317
+ var require_lockfile = __commonJS({
1318
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1319
+ "use strict";
1320
+ var path3 = __require("path");
1321
+ var fs3 = require_graceful_fs();
1322
+ var retry = require_retry2();
1323
+ var onExit = require_signal_exit();
1324
+ var mtimePrecision = require_mtime_precision();
1325
+ var locks = {};
1326
+ function getLockFile(file, options) {
1327
+ return options.lockfilePath || `${file}.lock`;
1328
+ }
1329
+ function resolveCanonicalPath(file, options, callback) {
1330
+ if (!options.realpath) {
1331
+ return callback(null, path3.resolve(file));
1332
+ }
1333
+ options.fs.realpath(file, callback);
1334
+ }
1335
+ function acquireLock(file, options, callback) {
1336
+ const lockfilePath = getLockFile(file, options);
1337
+ options.fs.mkdir(lockfilePath, (err) => {
1338
+ if (!err) {
1339
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1340
+ if (err2) {
1341
+ options.fs.rmdir(lockfilePath, () => {
1342
+ });
1343
+ return callback(err2);
1344
+ }
1345
+ callback(null, mtime, mtimePrecision2);
1346
+ });
1347
+ }
1348
+ if (err.code !== "EEXIST") {
1349
+ return callback(err);
1350
+ }
1351
+ if (options.stale <= 0) {
1352
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1353
+ }
1354
+ options.fs.stat(lockfilePath, (err2, stat) => {
1355
+ if (err2) {
1356
+ if (err2.code === "ENOENT") {
1357
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1358
+ }
1359
+ return callback(err2);
1360
+ }
1361
+ if (!isLockStale(stat, options)) {
1362
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1363
+ }
1364
+ removeLock(file, options, (err3) => {
1365
+ if (err3) {
1366
+ return callback(err3);
1367
+ }
1368
+ acquireLock(file, { ...options, stale: 0 }, callback);
1369
+ });
1370
+ });
1371
+ });
1372
+ }
1373
+ function isLockStale(stat, options) {
1374
+ return stat.mtime.getTime() < Date.now() - options.stale;
1375
+ }
1376
+ function removeLock(file, options, callback) {
1377
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1378
+ if (err && err.code !== "ENOENT") {
1379
+ return callback(err);
1380
+ }
1381
+ callback();
1382
+ });
1383
+ }
1384
+ function updateLock(file, options) {
1385
+ const lock3 = locks[file];
1386
+ if (lock3.updateTimeout) {
1387
+ return;
1388
+ }
1389
+ lock3.updateDelay = lock3.updateDelay || options.update;
1390
+ lock3.updateTimeout = setTimeout(() => {
1391
+ lock3.updateTimeout = null;
1392
+ options.fs.stat(lock3.lockfilePath, (err, stat) => {
1393
+ const isOverThreshold = lock3.lastUpdate + options.stale < Date.now();
1394
+ if (err) {
1395
+ if (err.code === "ENOENT" || isOverThreshold) {
1396
+ return setLockAsCompromised(file, lock3, Object.assign(err, { code: "ECOMPROMISED" }));
1397
+ }
1398
+ lock3.updateDelay = 1e3;
1399
+ return updateLock(file, options);
1400
+ }
1401
+ const isMtimeOurs = lock3.mtime.getTime() === stat.mtime.getTime();
1402
+ if (!isMtimeOurs) {
1403
+ return setLockAsCompromised(
1404
+ file,
1405
+ lock3,
1406
+ Object.assign(
1407
+ new Error("Unable to update lock within the stale threshold"),
1408
+ { code: "ECOMPROMISED" }
1409
+ )
1410
+ );
1411
+ }
1412
+ const mtime = mtimePrecision.getMtime(lock3.mtimePrecision);
1413
+ options.fs.utimes(lock3.lockfilePath, mtime, mtime, (err2) => {
1414
+ const isOverThreshold2 = lock3.lastUpdate + options.stale < Date.now();
1415
+ if (lock3.released) {
1416
+ return;
1417
+ }
1418
+ if (err2) {
1419
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1420
+ return setLockAsCompromised(file, lock3, Object.assign(err2, { code: "ECOMPROMISED" }));
1421
+ }
1422
+ lock3.updateDelay = 1e3;
1423
+ return updateLock(file, options);
1424
+ }
1425
+ lock3.mtime = mtime;
1426
+ lock3.lastUpdate = Date.now();
1427
+ lock3.updateDelay = null;
1428
+ updateLock(file, options);
1429
+ });
1430
+ });
1431
+ }, lock3.updateDelay);
1432
+ if (lock3.updateTimeout.unref) {
1433
+ lock3.updateTimeout.unref();
1434
+ }
1435
+ }
1436
+ function setLockAsCompromised(file, lock3, err) {
1437
+ lock3.released = true;
1438
+ if (lock3.updateTimeout) {
1439
+ clearTimeout(lock3.updateTimeout);
1440
+ }
1441
+ if (locks[file] === lock3) {
1442
+ delete locks[file];
1443
+ }
1444
+ lock3.options.onCompromised(err);
1445
+ }
1446
+ function lock2(file, options, callback) {
1447
+ options = {
1448
+ stale: 1e4,
1449
+ update: null,
1450
+ realpath: true,
1451
+ retries: 0,
1452
+ fs: fs3,
1453
+ onCompromised: (err) => {
1454
+ throw err;
1455
+ },
1456
+ ...options
1457
+ };
1458
+ options.retries = options.retries || 0;
1459
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1460
+ options.stale = Math.max(options.stale || 0, 2e3);
1461
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1462
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
1463
+ resolveCanonicalPath(file, options, (err, file2) => {
1464
+ if (err) {
1465
+ return callback(err);
1466
+ }
1467
+ const operation = retry.operation(options.retries);
1468
+ operation.attempt(() => {
1469
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1470
+ if (operation.retry(err2)) {
1471
+ return;
1472
+ }
1473
+ if (err2) {
1474
+ return callback(operation.mainError());
1475
+ }
1476
+ const lock3 = locks[file2] = {
1477
+ lockfilePath: getLockFile(file2, options),
1478
+ mtime,
1479
+ mtimePrecision: mtimePrecision2,
1480
+ options,
1481
+ lastUpdate: Date.now()
1482
+ };
1483
+ updateLock(file2, options);
1484
+ callback(null, (releasedCallback) => {
1485
+ if (lock3.released) {
1486
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1487
+ }
1488
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1489
+ });
1490
+ });
1491
+ });
1492
+ });
1493
+ }
1494
+ function unlock(file, options, callback) {
1495
+ options = {
1496
+ fs: fs3,
1497
+ realpath: true,
1498
+ ...options
1499
+ };
1500
+ resolveCanonicalPath(file, options, (err, file2) => {
1501
+ if (err) {
1502
+ return callback(err);
1503
+ }
1504
+ const lock3 = locks[file2];
1505
+ if (!lock3) {
1506
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1507
+ }
1508
+ lock3.updateTimeout && clearTimeout(lock3.updateTimeout);
1509
+ lock3.released = true;
1510
+ delete locks[file2];
1511
+ removeLock(file2, options, callback);
1512
+ });
1513
+ }
1514
+ function check2(file, options, callback) {
1515
+ options = {
1516
+ stale: 1e4,
1517
+ realpath: true,
1518
+ fs: fs3,
1519
+ ...options
1520
+ };
1521
+ options.stale = Math.max(options.stale || 0, 2e3);
1522
+ resolveCanonicalPath(file, options, (err, file2) => {
1523
+ if (err) {
1524
+ return callback(err);
1525
+ }
1526
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1527
+ if (err2) {
1528
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1529
+ }
1530
+ return callback(null, !isLockStale(stat, options));
1531
+ });
1532
+ });
1533
+ }
1534
+ function getLocks() {
1535
+ return locks;
1536
+ }
1537
+ onExit(() => {
1538
+ for (const file in locks) {
1539
+ const options = locks[file].options;
1540
+ try {
1541
+ options.fs.rmdirSync(getLockFile(file, options));
1542
+ } catch (e) {
1543
+ }
1544
+ }
1545
+ });
1546
+ module.exports.lock = lock2;
1547
+ module.exports.unlock = unlock;
1548
+ module.exports.check = check2;
1549
+ module.exports.getLocks = getLocks;
1550
+ }
1551
+ });
1552
+
1553
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js
1554
+ var require_adapter = __commonJS({
1555
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js"(exports, module) {
1556
+ "use strict";
1557
+ var fs3 = require_graceful_fs();
1558
+ function createSyncFs(fs4) {
1559
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1560
+ const newFs = { ...fs4 };
1561
+ methods.forEach((method) => {
1562
+ newFs[method] = (...args) => {
1563
+ const callback = args.pop();
1564
+ let ret;
1565
+ try {
1566
+ ret = fs4[`${method}Sync`](...args);
1567
+ } catch (err) {
1568
+ return callback(err);
1569
+ }
1570
+ callback(null, ret);
1571
+ };
1572
+ });
1573
+ return newFs;
1574
+ }
1575
+ function toPromise(method) {
1576
+ return (...args) => new Promise((resolve2, reject) => {
1577
+ args.push((err, result) => {
1578
+ if (err) {
1579
+ reject(err);
1580
+ } else {
1581
+ resolve2(result);
1582
+ }
1583
+ });
1584
+ method(...args);
1585
+ });
1586
+ }
1587
+ function toSync(method) {
1588
+ return (...args) => {
1589
+ let err;
1590
+ let result;
1591
+ args.push((_err, _result) => {
1592
+ err = _err;
1593
+ result = _result;
1594
+ });
1595
+ method(...args);
1596
+ if (err) {
1597
+ throw err;
1598
+ }
1599
+ return result;
1600
+ };
1601
+ }
1602
+ function toSyncOptions(options) {
1603
+ options = { ...options };
1604
+ options.fs = createSyncFs(options.fs || fs3);
1605
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1606
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1607
+ }
1608
+ return options;
1609
+ }
1610
+ module.exports = {
1611
+ toPromise,
1612
+ toSync,
1613
+ toSyncOptions
1614
+ };
1615
+ }
1616
+ });
1617
+
1618
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js
1619
+ var require_proper_lockfile = __commonJS({
1620
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js"(exports, module) {
1621
+ "use strict";
1622
+ var lockfile = require_lockfile();
1623
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1624
+ async function lock2(file, options) {
1625
+ const release = await toPromise(lockfile.lock)(file, options);
1626
+ return toPromise(release);
1627
+ }
1628
+ function lockSync(file, options) {
1629
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1630
+ return toSync(release);
1631
+ }
1632
+ function unlock(file, options) {
1633
+ return toPromise(lockfile.unlock)(file, options);
1634
+ }
1635
+ function unlockSync(file, options) {
1636
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1637
+ }
1638
+ function check2(file, options) {
1639
+ return toPromise(lockfile.check)(file, options);
1640
+ }
1641
+ function checkSync(file, options) {
1642
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1643
+ }
1644
+ module.exports = lock2;
1645
+ module.exports.lock = lock2;
1646
+ module.exports.unlock = unlock;
1647
+ module.exports.lockSync = lockSync;
1648
+ module.exports.unlockSync = unlockSync;
1649
+ module.exports.check = check2;
1650
+ module.exports.checkSync = checkSync;
1651
+ }
1652
+ });
1653
+
1654
+ // src/Init.ts
1655
+ import { confirm, input, select } from "@inquirer/prompts";
1656
+ import internals from "@prisma/internals";
1657
+ import dotenv from "dotenv";
1658
+ import { Schema as Shape } from "effect";
1659
+ import fs2 from "fs";
1660
+ import { bold as bold2, dim, green, red as red2, yellow } from "kleur/colors";
1661
+ import ora from "ora";
1662
+ import path2 from "path";
1663
+ import { match, P } from "ts-pattern";
1664
+
1665
+ // src/utils/client-output-path.ts
1666
+ import fs from "fs";
1667
+ import path from "path";
1668
+ import { getTsconfig } from "get-tsconfig";
1669
+ function determineClientOutputPath(schemaDir) {
1670
+ const sourceDir = getSourceDir();
1671
+ const outputPath = path.join(sourceDir, "generated", "prisma");
1672
+ const relativeOutputPath = path.relative(schemaDir, outputPath);
1673
+ return relativeOutputPath.replaceAll(path.sep, "/");
1674
+ }
1675
+ function getSourceDir() {
1676
+ const projectDir = process.cwd();
1677
+ const sourceRootFromTsConfig = getSourceDirFromTypeScriptConfig();
1678
+ if (sourceRootFromTsConfig) {
1679
+ return path.join(projectDir, sourceRootFromTsConfig);
1680
+ }
1681
+ for (const dir of ["src", "lib", "app"]) {
1682
+ const absoluteSourceDir = path.join(projectDir, dir);
1683
+ if (fs.existsSync(absoluteSourceDir)) {
1684
+ return absoluteSourceDir;
1685
+ }
1686
+ }
1687
+ return projectDir;
1688
+ }
1689
+ function getSourceDirFromTypeScriptConfig() {
1690
+ const tsconfig = getTsconfig();
1691
+ if (!tsconfig) {
1692
+ return void 0;
1693
+ }
1694
+ const { config } = tsconfig;
1695
+ return config.compilerOptions?.rootDir ?? config.compilerOptions?.baseUrl ?? config.compilerOptions?.rootDirs?.[0];
1696
+ }
1697
+
1698
+ // src/platform/accelerate/regions.ts
1699
+ var getRegionsOrThrow = async (input2) => {
1700
+ const { token } = input2;
1701
+ const { system } = await requestOrThrow({
1702
+ token,
1703
+ body: {
1704
+ query: (
1705
+ /* GraphQL */
1706
+ `
1707
+ query {
1708
+ system {
1709
+ accelerate {
1710
+ regions {
1711
+ id
1712
+ displayName
1713
+ ppgStatus
1714
+ }
1715
+ }
1716
+ }
1717
+ }
1718
+ `
1719
+ )
1720
+ }
1721
+ });
1722
+ return system.accelerate.regions;
1723
+ };
1724
+ var getPrismaPostgresRegionsOrThrow = async (input2) => {
1725
+ const regions = await getRegionsOrThrow(input2);
1726
+ const ppgRegions = regions.filter((_) => _.ppgStatus !== "unsupported").sort((a2, b) => b.displayName.localeCompare(a2.displayName));
1727
+ return ppgRegions;
1728
+ };
1729
+
1730
+ // src/utils/print.ts
1731
+ import { bgRed, bold, red } from "kleur/colors";
1732
+ function printError(text) {
1733
+ return bold(bgRed(" ERROR ")) + " " + red(text);
1734
+ }
1735
+
1736
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
1737
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1738
+ function normalizeWindowsPath(input2 = "") {
1739
+ if (!input2) {
1740
+ return input2;
1741
+ }
1742
+ return input2.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1743
+ }
1744
+ var _UNC_REGEX = /^[/\\]{2}/;
1745
+ var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1746
+ var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
1747
+ var normalize = function(path3) {
1748
+ if (path3.length === 0) {
1749
+ return ".";
1750
+ }
1751
+ path3 = normalizeWindowsPath(path3);
1752
+ const isUNCPath = path3.match(_UNC_REGEX);
1753
+ const isPathAbsolute = isAbsolute(path3);
1754
+ const trailingSeparator = path3[path3.length - 1] === "/";
1755
+ path3 = normalizeString(path3, !isPathAbsolute);
1756
+ if (path3.length === 0) {
1757
+ if (isPathAbsolute) {
1758
+ return "/";
1759
+ }
1760
+ return trailingSeparator ? "./" : ".";
1761
+ }
1762
+ if (trailingSeparator) {
1763
+ path3 += "/";
1764
+ }
1765
+ if (_DRIVE_LETTER_RE.test(path3)) {
1766
+ path3 += "/";
1767
+ }
1768
+ if (isUNCPath) {
1769
+ if (!isPathAbsolute) {
1770
+ return `//./${path3}`;
1771
+ }
1772
+ return `//${path3}`;
1773
+ }
1774
+ return isPathAbsolute && !isAbsolute(path3) ? `/${path3}` : path3;
1775
+ };
1776
+ var join = function(...segments) {
1777
+ let path3 = "";
1778
+ for (const seg of segments) {
1779
+ if (!seg) {
1780
+ continue;
1781
+ }
1782
+ if (path3.length > 0) {
1783
+ const pathTrailing = path3[path3.length - 1] === "/";
1784
+ const segLeading = seg[0] === "/";
1785
+ const both = pathTrailing && segLeading;
1786
+ if (both) {
1787
+ path3 += seg.slice(1);
1788
+ } else {
1789
+ path3 += pathTrailing || segLeading ? seg : `/${seg}`;
1790
+ }
1791
+ } else {
1792
+ path3 += seg;
1793
+ }
1794
+ }
1795
+ return normalize(path3);
1796
+ };
1797
+ function normalizeString(path3, allowAboveRoot) {
1798
+ let res = "";
1799
+ let lastSegmentLength = 0;
1800
+ let lastSlash = -1;
1801
+ let dots = 0;
1802
+ let char = null;
1803
+ for (let index = 0; index <= path3.length; ++index) {
1804
+ if (index < path3.length) {
1805
+ char = path3[index];
1806
+ } else if (char === "/") {
1807
+ break;
1808
+ } else {
1809
+ char = "/";
1810
+ }
1811
+ if (char === "/") {
1812
+ if (lastSlash === index - 1 || dots === 1)
1813
+ ;
1814
+ else if (dots === 2) {
1815
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1816
+ if (res.length > 2) {
1817
+ const lastSlashIndex = res.lastIndexOf("/");
1818
+ if (lastSlashIndex === -1) {
1819
+ res = "";
1820
+ lastSegmentLength = 0;
1821
+ } else {
1822
+ res = res.slice(0, lastSlashIndex);
1823
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1824
+ }
1825
+ lastSlash = index;
1826
+ dots = 0;
1827
+ continue;
1828
+ } else if (res.length > 0) {
1829
+ res = "";
1830
+ lastSegmentLength = 0;
1831
+ lastSlash = index;
1832
+ dots = 0;
1833
+ continue;
1834
+ }
1835
+ }
1836
+ if (allowAboveRoot) {
1837
+ res += res.length > 0 ? "/.." : "..";
1838
+ lastSegmentLength = 2;
1839
+ }
1840
+ } else {
1841
+ if (res.length > 0) {
1842
+ res += `/${path3.slice(lastSlash + 1, index)}`;
1843
+ } else {
1844
+ res = path3.slice(lastSlash + 1, index);
1845
+ }
1846
+ lastSegmentLength = index - lastSlash - 1;
1847
+ }
1848
+ lastSlash = index;
1849
+ dots = 0;
1850
+ } else if (char === "." && dots !== -1) {
1851
+ ++dots;
1852
+ } else {
1853
+ dots = -1;
1854
+ }
1855
+ }
1856
+ return res;
1857
+ }
1858
+ var isAbsolute = function(p) {
1859
+ return _IS_ABSOLUTE_RE.test(p);
1860
+ };
1861
+
1862
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/utils.mjs
1863
+ var normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
1864
+ var SLASH_RE = /[/\\]/;
1865
+ function filename(path3) {
1866
+ const base = path3.split(SLASH_RE).pop();
1867
+ if (!base) {
1868
+ return void 0;
1869
+ }
1870
+ const separatorIndex = base.lastIndexOf(".");
1871
+ if (separatorIndex <= 0) {
1872
+ return base;
1873
+ }
1874
+ return base.slice(0, separatorIndex);
1875
+ }
1876
+
1877
+ // ../../node_modules/.pnpm/get-port-please@3.1.2/node_modules/get-port-please/dist/index.mjs
1878
+ import { createServer } from "net";
1879
+ import { networkInterfaces } from "os";
1880
+ var unsafePorts = /* @__PURE__ */ new Set([
1881
+ 1,
1882
+ // tcpmux
1883
+ 7,
1884
+ // echo
1885
+ 9,
1886
+ // discard
1887
+ 11,
1888
+ // systat
1889
+ 13,
1890
+ // daytime
1891
+ 15,
1892
+ // netstat
1893
+ 17,
1894
+ // qotd
1895
+ 19,
1896
+ // chargen
1897
+ 20,
1898
+ // ftp data
1899
+ 21,
1900
+ // ftp access
1901
+ 22,
1902
+ // ssh
1903
+ 23,
1904
+ // telnet
1905
+ 25,
1906
+ // smtp
1907
+ 37,
1908
+ // time
1909
+ 42,
1910
+ // name
1911
+ 43,
1912
+ // nicname
1913
+ 53,
1914
+ // domain
1915
+ 69,
1916
+ // tftp
1917
+ 77,
1918
+ // priv-rjs
1919
+ 79,
1920
+ // finger
1921
+ 87,
1922
+ // ttylink
1923
+ 95,
1924
+ // supdup
1925
+ 101,
1926
+ // hostriame
1927
+ 102,
1928
+ // iso-tsap
1929
+ 103,
1930
+ // gppitnp
1931
+ 104,
1932
+ // acr-nema
1933
+ 109,
1934
+ // pop2
1935
+ 110,
1936
+ // pop3
1937
+ 111,
1938
+ // sunrpc
1939
+ 113,
1940
+ // auth
1941
+ 115,
1942
+ // sftp
1943
+ 117,
1944
+ // uucp-path
1945
+ 119,
1946
+ // nntp
1947
+ 123,
1948
+ // NTP
1949
+ 135,
1950
+ // loc-srv /epmap
1951
+ 137,
1952
+ // netbios
1953
+ 139,
1954
+ // netbios
1955
+ 143,
1956
+ // imap2
1957
+ 161,
1958
+ // snmp
1959
+ 179,
1960
+ // BGP
1961
+ 389,
1962
+ // ldap
1963
+ 427,
1964
+ // SLP (Also used by Apple Filing Protocol)
1965
+ 465,
1966
+ // smtp+ssl
1967
+ 512,
1968
+ // print / exec
1969
+ 513,
1970
+ // login
1971
+ 514,
1972
+ // shell
1973
+ 515,
1974
+ // printer
1975
+ 526,
1976
+ // tempo
1977
+ 530,
1978
+ // courier
1979
+ 531,
1980
+ // chat
1981
+ 532,
1982
+ // netnews
1983
+ 540,
1984
+ // uucp
1985
+ 548,
1986
+ // AFP (Apple Filing Protocol)
1987
+ 554,
1988
+ // rtsp
1989
+ 556,
1990
+ // remotefs
1991
+ 563,
1992
+ // nntp+ssl
1993
+ 587,
1994
+ // smtp (rfc6409)
1995
+ 601,
1996
+ // syslog-conn (rfc3195)
1997
+ 636,
1998
+ // ldap+ssl
1999
+ 989,
2000
+ // ftps-data
2001
+ 990,
2002
+ // ftps
2003
+ 993,
2004
+ // ldap+ssl
2005
+ 995,
2006
+ // pop3+ssl
2007
+ 1719,
2008
+ // h323gatestat
2009
+ 1720,
2010
+ // h323hostcall
2011
+ 1723,
2012
+ // pptp
2013
+ 2049,
2014
+ // nfs
2015
+ 3659,
2016
+ // apple-sasl / PasswordServer
2017
+ 4045,
2018
+ // lockd
2019
+ 5060,
2020
+ // sip
2021
+ 5061,
2022
+ // sips
2023
+ 6e3,
2024
+ // X11
2025
+ 6566,
2026
+ // sane-port
2027
+ 6665,
2028
+ // Alternate IRC [Apple addition]
2029
+ 6666,
2030
+ // Alternate IRC [Apple addition]
2031
+ 6667,
2032
+ // Standard IRC [Apple addition]
2033
+ 6668,
2034
+ // Alternate IRC [Apple addition]
2035
+ 6669,
2036
+ // Alternate IRC [Apple addition]
2037
+ 6697,
2038
+ // IRC + TLS
2039
+ 10080
2040
+ // Amanda
2041
+ ]);
2042
+ function isUnsafePort(port) {
2043
+ return unsafePorts.has(port);
2044
+ }
2045
+ function isSafePort(port) {
2046
+ return !isUnsafePort(port);
2047
+ }
2048
+ var __defProp = Object.defineProperty;
2049
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2050
+ var __publicField = (obj, key, value) => {
2051
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2052
+ return value;
2053
+ };
2054
+ var GetPortError = class extends Error {
2055
+ constructor(message, opts) {
2056
+ super(message, opts);
2057
+ this.message = message;
2058
+ __publicField(this, "name", "GetPortError");
2059
+ }
2060
+ };
2061
+ function _log(verbose, message) {
2062
+ if (verbose) {
2063
+ console.log(`[get-port] ${message}`);
2064
+ }
2065
+ }
2066
+ function _generateRange(from, to) {
2067
+ if (to < from) {
2068
+ return [];
2069
+ }
2070
+ const r = [];
2071
+ for (let index = from; index <= to; index++) {
2072
+ r.push(index);
2073
+ }
2074
+ return r;
2075
+ }
2076
+ function _tryPort(port, host) {
2077
+ return new Promise((resolve2) => {
2078
+ const server = createServer();
2079
+ server.unref();
2080
+ server.on("error", () => {
2081
+ resolve2(false);
2082
+ });
2083
+ server.listen({ port, host }, () => {
2084
+ const { port: port2 } = server.address();
2085
+ server.close(() => {
2086
+ resolve2(isSafePort(port2) && port2);
2087
+ });
2088
+ });
2089
+ });
2090
+ }
2091
+ function _getLocalHosts(additional) {
2092
+ const hosts = new Set(additional);
2093
+ for (const _interface of Object.values(networkInterfaces())) {
2094
+ for (const config of _interface || []) {
2095
+ if (config.address && !config.internal && !config.address.startsWith("fe80::")) {
2096
+ hosts.add(config.address);
2097
+ }
2098
+ }
2099
+ }
2100
+ return [...hosts];
2101
+ }
2102
+ async function _findPort(ports, host) {
2103
+ for (const port of ports) {
2104
+ const r = await _tryPort(port, host);
2105
+ if (r) {
2106
+ return r;
2107
+ }
2108
+ }
2109
+ }
2110
+ function _fmtOnHost(hostname) {
2111
+ return hostname ? `on host ${JSON.stringify(hostname)}` : "on any host";
2112
+ }
2113
+ var HOSTNAME_RE = /^(?!-)[\d.:A-Za-z-]{1,63}(?<!-)$/;
2114
+ function _validateHostname(hostname, _public, verbose) {
2115
+ if (hostname && !HOSTNAME_RE.test(hostname)) {
2116
+ const fallbackHost = _public ? "0.0.0.0" : "127.0.0.1";
2117
+ _log(
2118
+ verbose,
2119
+ `Invalid hostname: ${JSON.stringify(hostname)}. Using ${JSON.stringify(
2120
+ fallbackHost
2121
+ )} as fallback.`
2122
+ );
2123
+ return fallbackHost;
2124
+ }
2125
+ return hostname;
2126
+ }
2127
+ async function getPort(_userOptions = {}) {
2128
+ if (typeof _userOptions === "number" || typeof _userOptions === "string") {
2129
+ _userOptions = { port: Number.parseInt(_userOptions + "") || 0 };
2130
+ }
2131
+ const _port = Number(_userOptions.port ?? process.env.PORT);
2132
+ const _userSpecifiedAnyPort = Boolean(
2133
+ _userOptions.port || _userOptions.ports?.length || _userOptions.portRange?.length
2134
+ );
2135
+ const options = {
2136
+ name: "default",
2137
+ random: _port === 0,
2138
+ ports: [],
2139
+ portRange: [],
2140
+ alternativePortRange: _userSpecifiedAnyPort ? [] : [3e3, 3100],
2141
+ verbose: false,
2142
+ ..._userOptions,
2143
+ port: _port,
2144
+ host: _validateHostname(
2145
+ _userOptions.host ?? process.env.HOST,
2146
+ _userOptions.public,
2147
+ _userOptions.verbose
2148
+ )
2149
+ };
2150
+ if (options.random && !_userSpecifiedAnyPort) {
2151
+ return getRandomPort(options.host);
2152
+ }
2153
+ const portsToCheck = [
2154
+ options.port,
2155
+ ...options.ports,
2156
+ ..._generateRange(...options.portRange)
2157
+ ].filter((port) => {
2158
+ if (!port) {
2159
+ return false;
2160
+ }
2161
+ if (!isSafePort(port)) {
2162
+ _log(options.verbose, `Ignoring unsafe port: ${port}`);
2163
+ return false;
2164
+ }
2165
+ return true;
2166
+ });
2167
+ if (portsToCheck.length === 0) {
2168
+ portsToCheck.push(3e3);
2169
+ }
2170
+ let availablePort = await _findPort(portsToCheck, options.host);
2171
+ if (!availablePort && options.alternativePortRange.length > 0) {
2172
+ availablePort = await _findPort(
2173
+ _generateRange(...options.alternativePortRange),
2174
+ options.host
2175
+ );
2176
+ if (portsToCheck.length > 0) {
2177
+ let message = `Unable to find an available port (tried ${portsToCheck.join(
2178
+ "-"
2179
+ )} ${_fmtOnHost(options.host)}).`;
2180
+ if (availablePort) {
2181
+ message += ` Using alternative port ${availablePort}.`;
2182
+ }
2183
+ _log(options.verbose, message);
2184
+ }
2185
+ }
2186
+ if (!availablePort && _userOptions.random !== false) {
2187
+ availablePort = await getRandomPort(options.host);
2188
+ if (availablePort) {
2189
+ _log(options.verbose, `Using random port ${availablePort}`);
2190
+ }
2191
+ }
2192
+ if (!availablePort) {
2193
+ const triedRanges = [
2194
+ options.port,
2195
+ options.portRange.join("-"),
2196
+ options.alternativePortRange.join("-")
2197
+ ].filter(Boolean).join(", ");
2198
+ throw new GetPortError(
2199
+ `Unable to find an available port ${_fmtOnHost(
2200
+ options.host
2201
+ )} (tried ${triedRanges})`
2202
+ );
2203
+ }
2204
+ return availablePort;
2205
+ }
2206
+ async function getRandomPort(host) {
2207
+ const port = await checkPort(0, host);
2208
+ if (port === false) {
2209
+ throw new GetPortError(`Unable to find a random port ${_fmtOnHost(host)}`);
2210
+ }
2211
+ return port;
2212
+ }
2213
+ async function checkPort(port, host = process.env.HOST, verbose) {
2214
+ if (!host) {
2215
+ host = _getLocalHosts([void 0, "0.0.0.0"]);
2216
+ }
2217
+ if (!Array.isArray(host)) {
2218
+ return _tryPort(port, host);
2219
+ }
2220
+ for (const _host of host) {
2221
+ const _port = await _tryPort(port, _host);
2222
+ if (_port === false) {
2223
+ if (port < 1024 && verbose) {
2224
+ _log(
2225
+ verbose,
2226
+ `Unable to listen to the privileged port ${port} ${_fmtOnHost(
2227
+ _host
2228
+ )}`
2229
+ );
2230
+ }
2231
+ return false;
2232
+ }
2233
+ if (port === 0 && _port !== 0) {
2234
+ port = _port;
2235
+ }
2236
+ }
2237
+ return port;
2238
+ }
2239
+
2240
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-ANXBDSUI.js
2241
+ var s = { done: false, hasNext: false };
2242
+ var o = (t) => ({ hasNext: true, next: t, done: false });
2243
+
2244
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-3GOCSNFN.js
2245
+ function C(t, ...o3) {
2246
+ let n = t, u3 = o3.map((e) => "lazy" in e ? y2(e) : void 0), p = 0;
2247
+ for (; p < o3.length; ) {
2248
+ if (u3[p] === void 0 || !B(n)) {
2249
+ let i = o3[p];
2250
+ n = i(n), p += 1;
2251
+ continue;
2252
+ }
2253
+ let r = [];
2254
+ for (let i = p; i < o3.length; i++) {
2255
+ let l = u3[i];
2256
+ if (l === void 0 || (r.push(l), l.isSingle))
2257
+ break;
2258
+ }
2259
+ let a2 = [];
2260
+ for (let i of n)
2261
+ if (f(i, a2, r))
2262
+ break;
2263
+ let { isSingle: s2 } = r.at(-1);
2264
+ n = s2 ? a2[0] : a2, p += r.length;
2265
+ }
2266
+ return n;
2267
+ }
2268
+ function f(t, o3, n) {
2269
+ if (n.length === 0)
2270
+ return o3.push(t), false;
2271
+ let u3 = t, p = s, e = false;
2272
+ for (let [r, a2] of n.entries()) {
2273
+ let { index: s2, items: i } = a2;
2274
+ if (i.push(u3), p = a2(u3, s2, i), a2.index += 1, p.hasNext) {
2275
+ if (p.hasMany ?? false) {
2276
+ for (let l of p.next)
2277
+ if (f(l, o3, n.slice(r + 1)))
2278
+ return true;
2279
+ return e;
2280
+ }
2281
+ u3 = p.next;
2282
+ }
2283
+ if (!p.hasNext)
2284
+ break;
2285
+ p.done && (e = true);
2286
+ }
2287
+ return p.hasNext && o3.push(u3), e;
2288
+ }
2289
+ function y2(t) {
2290
+ let { lazy: o3, lazyArgs: n } = t, u3 = o3(...n);
2291
+ return Object.assign(u3, { isSingle: o3.single ?? false, index: 0, items: [] });
2292
+ }
2293
+ function B(t) {
2294
+ return typeof t == "string" || typeof t == "object" && t !== null && Symbol.iterator in t;
2295
+ }
8
2296
 
9
- // src/Init.ts
10
- import { confirm, input, select } from "@inquirer/prompts";
11
- import internals from "@prisma/internals";
12
- import dotenv from "dotenv";
13
- import { Schema as Shape } from "effect";
14
- import fs2 from "fs";
15
- import { bold as bold2, dim, green, red as red2, yellow } from "kleur/colors";
16
- import ora from "ora";
17
- import path2 from "path";
18
- import { match, P } from "ts-pattern";
2297
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-LFJW7BOT.js
2298
+ function y3(t, i) {
2299
+ let a2 = i.length - t.length;
2300
+ if (a2 === 1) {
2301
+ let [n, ...r] = i;
2302
+ return C(n, { lazy: t, lazyArgs: r });
2303
+ }
2304
+ if (a2 === 0) {
2305
+ let n = { lazy: t, lazyArgs: i };
2306
+ return Object.assign((e) => C(e, n), n);
2307
+ }
2308
+ throw new Error("Wrong number of arguments");
2309
+ }
19
2310
 
20
- // src/utils/client-output-path.ts
21
- import fs from "fs";
22
- import path from "path";
23
- import { getTsconfig } from "get-tsconfig";
24
- function determineClientOutputPath(schemaDir) {
25
- const sourceDir = getSourceDir();
26
- const outputPath = path.join(sourceDir, "generated", "prisma");
27
- const relativeOutputPath = path.relative(schemaDir, outputPath);
28
- return relativeOutputPath.replaceAll(path.sep, "/");
2311
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-D6FCK2GA.js
2312
+ function u(o3, n, a2) {
2313
+ let t = (r) => o3(r, ...n);
2314
+ return a2 === void 0 ? t : Object.assign(t, { lazy: a2, lazyArgs: n });
29
2315
  }
30
- function getSourceDir() {
31
- const projectDir = process.cwd();
32
- const sourceRootFromTsConfig = getSourceDirFromTypeScriptConfig();
33
- if (sourceRootFromTsConfig) {
34
- return path.join(projectDir, sourceRootFromTsConfig);
2316
+
2317
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-WIMGWYZL.js
2318
+ function u2(r, n, o3) {
2319
+ let a2 = r.length - n.length;
2320
+ if (a2 === 0)
2321
+ return r(...n);
2322
+ if (a2 === 1)
2323
+ return u(r, n, o3);
2324
+ throw new Error("Wrong number of arguments");
2325
+ }
2326
+
2327
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-ENS7GPLZ.js
2328
+ function a(...r) {
2329
+ return u2(o2, r);
2330
+ }
2331
+ function o2(r, t) {
2332
+ let e = [];
2333
+ for (let n = r; n < t; n++)
2334
+ e.push(n);
2335
+ return e;
2336
+ }
2337
+
2338
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-GKXRNLHM.js
2339
+ function d(...e) {
2340
+ return y3(f2, e);
2341
+ }
2342
+ function f2(e) {
2343
+ if (e.length === 0)
2344
+ return o;
2345
+ let n = /* @__PURE__ */ new Map();
2346
+ for (let r of e)
2347
+ n.set(r, (n.get(r) ?? 0) + 1);
2348
+ return (r) => {
2349
+ let t = n.get(r);
2350
+ return t === void 0 || t === 0 ? { done: false, hasNext: true, next: r } : (n.set(r, t - 1), s);
2351
+ };
2352
+ }
2353
+
2354
+ // ../../dev/server/src/port.ts
2355
+ var DEFAULT_DATABASE_PORT = 51214;
2356
+ var DEFAULT_SERVER_PORT = 51213;
2357
+ var DEFAULT_SHADOW_DATABASE_PORT = 51215;
2358
+ var MAX_PORT = 65535;
2359
+ var NO_PORT = -Infinity;
2360
+ async function pickPorts(options) {
2361
+ const { debug, name, requestedPorts, servers } = options;
2362
+ const { portsUsedByOtherServers, portsUsedByThisServerLastTime } = extractUsedPorts(name, servers);
2363
+ if (debug) {
2364
+ console.debug(`ports used by other servers: ${Object.keys(portsUsedByOtherServers).join(", ")}`);
2365
+ console.debug(`ports used by "${name}" server last time: ${JSON.stringify(portsUsedByThisServerLastTime)}`);
35
2366
  }
36
- for (const dir of ["src", "lib", "app"]) {
37
- const absoluteSourceDir = path.join(projectDir, dir);
38
- if (fs.existsSync(absoluteSourceDir)) {
39
- return absoluteSourceDir;
2367
+ const pickedPorts = { databasePort: NO_PORT, port: NO_PORT, shadowDatabasePort: NO_PORT };
2368
+ const portKeys = ["port", "databasePort", "shadowDatabasePort"];
2369
+ for (const portKey of portKeys) {
2370
+ const port = await trySpecificPorts({
2371
+ debug,
2372
+ portKey,
2373
+ portsUsedByOtherServers,
2374
+ portsUsedByThisServerLastTime,
2375
+ requestedPorts
2376
+ }) ?? await tryAnyPort({ debug, pickedPorts, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime });
2377
+ if (debug) {
2378
+ console.debug(`Got port for "${portKey}": ${port}`);
40
2379
  }
2380
+ pickedPorts[portKey] = port;
41
2381
  }
42
- return projectDir;
2382
+ if (debug) {
2383
+ console.debug(`Picked ports: ${JSON.stringify(pickedPorts)}`);
2384
+ }
2385
+ return pickedPorts;
43
2386
  }
44
- function getSourceDirFromTypeScriptConfig() {
45
- const tsconfig = getTsconfig();
46
- if (!tsconfig) {
47
- return void 0;
2387
+ async function trySpecificPorts(options) {
2388
+ const { debug, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime, requestedPorts } = options;
2389
+ const { [portKey]: requestedPort, ...otherRequestedPorts } = requestedPorts;
2390
+ if (isPortSpecified(requestedPort)) {
2391
+ await assertPickablePort({ debug, otherRequestedPorts, portKey, portsUsedByOtherServers, requestedPort });
2392
+ return requestedPort;
48
2393
  }
49
- const { config } = tsconfig;
50
- return config.compilerOptions?.rootDir ?? config.compilerOptions?.baseUrl ?? config.compilerOptions?.rootDirs?.[0];
2394
+ const portUsedLastTime = portsUsedByThisServerLastTime?.[portKey] ?? NO_PORT;
2395
+ if (!isPortSpecified(portUsedLastTime)) {
2396
+ if (debug) {
2397
+ console.debug(`No port specified for "${portKey}". Trying to pick a new port.`);
2398
+ }
2399
+ return null;
2400
+ }
2401
+ const isPortUsedByOtherServers = portUsedLastTime in portsUsedByOtherServers;
2402
+ if (isPortUsedByOtherServers || Object.values(otherRequestedPorts).includes(portUsedLastTime)) {
2403
+ if (debug) {
2404
+ console.debug(
2405
+ `Port ${portUsedLastTime} that was used last time for this server, ${isPortUsedByOtherServers ? "is also used by another server" : "has been requested for another service"}. Trying to pick a new port.`
2406
+ );
2407
+ }
2408
+ return null;
2409
+ }
2410
+ if (await checkPort(portUsedLastTime) === false) {
2411
+ if (debug) {
2412
+ console.debug(
2413
+ `Port ${portUsedLastTime}, that was used last time for this server, is not available. Trying to pick a new port.`
2414
+ );
2415
+ }
2416
+ return null;
2417
+ }
2418
+ if (debug) {
2419
+ console.debug(`Using port ${portUsedLastTime} for "${portKey}" as it was used last time and is available.`);
2420
+ }
2421
+ return portUsedLastTime;
2422
+ }
2423
+ async function tryAnyPort(options) {
2424
+ const { debug, pickedPorts, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime } = options;
2425
+ const minimumPort = Math.max(DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT) + 1;
2426
+ const excludedPorts = [
2427
+ ...Object.values(pickedPorts),
2428
+ ...Object.keys(portsUsedByOtherServers).map(Number),
2429
+ ...Object.values(portsUsedByThisServerLastTime || {})
2430
+ ];
2431
+ const maximumSpecificPort = Math.min(Math.max(minimumPort, ...excludedPorts) + 100, MAX_PORT);
2432
+ const ports = d(a(minimumPort, maximumSpecificPort), excludedPorts);
2433
+ const defaultPort2 = {
2434
+ port: DEFAULT_SERVER_PORT,
2435
+ databasePort: DEFAULT_DATABASE_PORT,
2436
+ shadowDatabasePort: DEFAULT_SHADOW_DATABASE_PORT
2437
+ }[portKey];
2438
+ try {
2439
+ return await getPort({
2440
+ port: defaultPort2 in portsUsedByOtherServers || Object.values(pickedPorts).includes(defaultPort2) || Object.values(portsUsedByThisServerLastTime || {}).includes(defaultPort2) ? void 0 : defaultPort2,
2441
+ ports
2442
+ });
2443
+ } catch (error) {
2444
+ if (error instanceof Error && error.name === "GetPortError" && maximumSpecificPort + 1 <= MAX_PORT) {
2445
+ if (debug) {
2446
+ console.debug(`Expanding port lookup to range [${maximumSpecificPort + 1}, ${MAX_PORT}].`);
2447
+ }
2448
+ return await getPort({ portRange: [maximumSpecificPort + 1, MAX_PORT] });
2449
+ }
2450
+ throw error;
2451
+ }
2452
+ }
2453
+ function isPortSpecified(port) {
2454
+ return port >= 0;
51
2455
  }
2456
+ function extractUsedPorts(name, servers) {
2457
+ const portsUsedByOtherServers = {};
2458
+ let portsUsedByThisServerLastTime;
2459
+ for (const server of servers) {
2460
+ const { databasePort, port, shadowDatabasePort } = server;
2461
+ if (server.name === name) {
2462
+ portsUsedByThisServerLastTime = { databasePort, port, shadowDatabasePort };
2463
+ continue;
2464
+ }
2465
+ portsUsedByOtherServers[databasePort] = true;
2466
+ portsUsedByOtherServers[port] = true;
2467
+ portsUsedByOtherServers[shadowDatabasePort] = true;
2468
+ }
2469
+ return { portsUsedByOtherServers, portsUsedByThisServerLastTime };
2470
+ }
2471
+ async function assertPickablePort(options) {
2472
+ const { debug, otherRequestedPorts, portKey, portsUsedByOtherServers, requestedPort } = options;
2473
+ if (requestedPort in portsUsedByOtherServers) {
2474
+ if (debug) {
2475
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is already used by another server.`);
2476
+ }
2477
+ throw new PortBelongsToAnotherServerError(requestedPort);
2478
+ }
2479
+ if (Object.values(otherRequestedPorts).includes(requestedPort)) {
2480
+ if (debug) {
2481
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but also for another key.`);
2482
+ }
2483
+ throw new PortRequestedTwiceError(requestedPort);
2484
+ }
2485
+ if (isUnsafePort(requestedPort)) {
2486
+ if (debug) {
2487
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is unsafe.`);
2488
+ }
2489
+ throw new PortNotAvailableError(requestedPort);
2490
+ }
2491
+ if (await checkPort(requestedPort) === false) {
2492
+ if (debug) {
2493
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is not available.`);
2494
+ }
2495
+ throw new PortNotAvailableError(requestedPort);
2496
+ }
2497
+ }
2498
+ var PortNotAvailableError = class extends Error {
2499
+ constructor(port) {
2500
+ super(`Port \`${port}\` is not available.`);
2501
+ this.port = port;
2502
+ }
2503
+ name = "PortNotAvailableError";
2504
+ };
2505
+ var PortRequestedTwiceError = class extends Error {
2506
+ constructor(port) {
2507
+ super(`Port number \`${port}\` was requested twice. Please choose a different port for each service.`);
2508
+ this.port = port;
2509
+ }
2510
+ name = "PortRequestedTwiceError";
2511
+ };
2512
+ var PortBelongsToAnotherServerError = class extends Error {
2513
+ constructor(port) {
2514
+ super(`Port number \`${port}\` belongs to another Prisma Dev server. Please choose a different port.`);
2515
+ this.port = port;
2516
+ }
2517
+ name = "PortBelongsToAnotherServerError";
2518
+ };
52
2519
 
53
- // src/platform/accelerate/regions.ts
54
- var getRegionsOrThrow = async (input2) => {
55
- const { token } = input2;
56
- const { system } = await requestOrThrow({
57
- token,
58
- body: {
59
- query: (
60
- /* GraphQL */
61
- `
62
- query {
63
- system {
64
- accelerate {
65
- regions {
66
- id
67
- displayName
68
- ppgStatus
69
- }
70
- }
2520
+ // ../../dev/server/src/db.ts
2521
+ var BASE_PGLITE_OPTIONS = {
2522
+ connectionLimit: 1,
2523
+ connectTimeout: 0,
2524
+ database: "template1",
2525
+ maxIdleConnectionLifetime: 0,
2526
+ password: "postgres",
2527
+ poolTimeout: 0,
2528
+ socketTimeout: 0,
2529
+ sslMode: "disable",
2530
+ username: "postgres"
2531
+ };
2532
+ var BASE_DB_URL = `postgres://${BASE_PGLITE_OPTIONS.username}:${BASE_PGLITE_OPTIONS.password}@localhost`;
2533
+ var CONNECTION_STRING_QUERY_PARAMS = new URLSearchParams({ sslmode: BASE_PGLITE_OPTIONS.sslMode });
2534
+ var PRISMA_ORM_CONNECTION_STRING_QUERY_PARAMS = new URLSearchParams({
2535
+ ...Object.fromEntries(CONNECTION_STRING_QUERY_PARAMS.entries()),
2536
+ connection_limit: String(BASE_PGLITE_OPTIONS.connectionLimit),
2537
+ connect_timeout: String(BASE_PGLITE_OPTIONS.connectTimeout),
2538
+ max_idle_connection_lifetime: String(BASE_PGLITE_OPTIONS.maxIdleConnectionLifetime),
2539
+ pool_timeout: String(BASE_PGLITE_OPTIONS.poolTimeout),
2540
+ single_use_connections: "true",
2541
+ socket_timeout: String(BASE_PGLITE_OPTIONS.socketTimeout)
2542
+ });
2543
+ async function startDBServer(purpose, serverState) {
2544
+ const port = purpose === "database" ? serverState.databasePort : serverState.shadowDatabasePort;
2545
+ if (serverState.dryRun) {
2546
+ return getStartDBServerResult(purpose, serverState, { db: null, port, server: null });
2547
+ }
2548
+ const { debug } = serverState;
2549
+ const getDBFn = purpose === "shadow_database" ? getShadowDB : getDB;
2550
+ const db = await getDBFn(serverState.pgliteDataDirPath, debug);
2551
+ if (debug) {
2552
+ db.onNotification((channel, payload) => {
2553
+ console.debug(`[${purpose}][${channel}] ${payload}`);
2554
+ });
2555
+ }
2556
+ const { PGLiteSocketServer } = await import("@electric-sql/pglite-socket");
2557
+ const server = new PGLiteSocketServer({ db, debug, inspect: debug, port });
2558
+ if (debug) {
2559
+ server.addEventListener("listening", (event) => {
2560
+ const { detail } = event;
2561
+ console.debug(`[${purpose}] server listening on ${JSON.stringify(detail)}`);
2562
+ });
2563
+ server.addEventListener("connection", (event) => {
2564
+ const { clientAddress, clientPort } = event.detail;
2565
+ console.debug(`[${purpose}] client connected from ${clientAddress}:${clientPort}`);
2566
+ });
2567
+ server.addEventListener("error", (event) => {
2568
+ const { detail } = event;
2569
+ console.error(`[${purpose}] server error:`, detail);
2570
+ });
2571
+ }
2572
+ try {
2573
+ await server.start();
2574
+ } catch (error) {
2575
+ if (error instanceof Error && "code" in error && error.code === "EADDRINUSE") {
2576
+ throw new PortNotAvailableError(port);
2577
+ }
2578
+ throw error;
2579
+ }
2580
+ return getStartDBServerResult(purpose, serverState, { db, port, server });
2581
+ }
2582
+ function getStartDBServerResult(purpose, serverState, options) {
2583
+ const { debug } = serverState;
2584
+ const { db, port, server } = options || {};
2585
+ if (debug) {
2586
+ console.debug(`[${purpose}] server started on port ${port}`);
2587
+ }
2588
+ return {
2589
+ ...BASE_PGLITE_OPTIONS,
2590
+ close: async () => {
2591
+ const errors = [];
2592
+ try {
2593
+ await server?.stop();
2594
+ if (debug) {
2595
+ console.debug(`[${purpose}] server stopped on port ${port}`);
2596
+ }
2597
+ } catch (error) {
2598
+ console.error(`[${purpose}] server stop error`, error);
2599
+ errors.push(error);
2600
+ }
2601
+ if (purpose === "database") {
2602
+ try {
2603
+ await db?.syncToFs();
2604
+ if (debug) {
2605
+ console.debug(`[${purpose}] synced to filesystem`);
71
2606
  }
2607
+ } catch (error) {
2608
+ console.error(`[${purpose}] sync error`, error);
2609
+ errors.push(error);
72
2610
  }
73
- `
74
- )
2611
+ }
2612
+ try {
2613
+ await db?.close();
2614
+ if (debug) {
2615
+ console.debug(`[${purpose}] closed`);
2616
+ }
2617
+ } catch (error) {
2618
+ console.error(`[${purpose}] close error`, error);
2619
+ errors.push(error);
2620
+ }
2621
+ if (errors.length > 0) {
2622
+ throw new AggregateError(errors, `Failed to close ${purpose} properly`);
2623
+ }
2624
+ },
2625
+ connectionString: getConnectionString(port, CONNECTION_STRING_QUERY_PARAMS),
2626
+ dump: async (destinationPath) => {
2627
+ if (purpose === "shadow_database" || !db) {
2628
+ return;
2629
+ }
2630
+ await dumpDB({ db, debug, destinationPath });
2631
+ },
2632
+ port,
2633
+ prismaORMConnectionString: getConnectionString(port, PRISMA_ORM_CONNECTION_STRING_QUERY_PARAMS),
2634
+ terminalCommand: `PGPASSWORD=${BASE_PGLITE_OPTIONS.password} PGSSLMODE=${BASE_PGLITE_OPTIONS.sslMode} psql -h localhost -p ${port} -U ${BASE_PGLITE_OPTIONS.username} -d ${BASE_PGLITE_OPTIONS.database}`
2635
+ };
2636
+ }
2637
+ function getConnectionString(port, queryParams) {
2638
+ return `${BASE_DB_URL}:${port}/${BASE_PGLITE_OPTIONS.database}?${queryParams.toString()}`;
2639
+ }
2640
+ async function getDB(dataDir, debug) {
2641
+ const { PGlite } = await import("@electric-sql/pglite");
2642
+ return await PGlite.create({
2643
+ database: BASE_PGLITE_OPTIONS.database,
2644
+ dataDir,
2645
+ debug: debug ? 5 : void 0,
2646
+ relaxedDurability: false,
2647
+ username: BASE_PGLITE_OPTIONS.username
2648
+ });
2649
+ }
2650
+ async function getShadowDB(_dataDir, debug) {
2651
+ const { PGlite } = await import("@electric-sql/pglite");
2652
+ return await PGlite.create({
2653
+ database: BASE_PGLITE_OPTIONS.database,
2654
+ dataDir: "memory://",
2655
+ debug: debug ? 5 : void 0,
2656
+ relaxedDurability: false,
2657
+ username: BASE_PGLITE_OPTIONS.username
2658
+ });
2659
+ }
2660
+ async function dumpDB(options) {
2661
+ const { dataDir, db, debug, destinationPath } = options;
2662
+ const pg = db || await getDB(dataDir, debug);
2663
+ const { pgDump } = await import("@electric-sql/pglite-tools/pg_dump");
2664
+ const dumpFile = await pgDump({
2665
+ args: [
2666
+ // TODO: enable once it's fixed by PGLite team. This is highly recommended for cross-major-version pg restores.
2667
+ // "--quote-all-identifiers",
2668
+ // TODO: remove once we decide to also dump data.
2669
+ "--schema-only",
2670
+ "--no-owner"
2671
+ // avoids `ALTER TABLE public."Post" OWNER TO postgres;`
2672
+ ],
2673
+ fileName: destinationPath ? filename(destinationPath) : void 0,
2674
+ // workaround, see https://prisma-company.slack.com/archives/C08LDD4THBJ/p1749486737052709?thread_ts=1749211391.517819&cid=C08LDD4THBJ
2675
+ pg: await pg.clone()
2676
+ });
2677
+ if (destinationPath) {
2678
+ if (debug) {
2679
+ console.debug(`[DB] Dumping database to ${destinationPath}`);
2680
+ }
2681
+ return await streamAsTextTo(dumpFile, destinationPath);
2682
+ }
2683
+ if (debug) {
2684
+ console.debug(`[DB] Dumping database to memory`);
2685
+ }
2686
+ return await dumpFile.text();
2687
+ }
2688
+
2689
+ // ../../dev/server/src/http.ts
2690
+ import { createServer as createServer2 } from "http";
2691
+ import { promisify } from "util";
2692
+ import getPlatformModule from "@prisma/get-platform";
2693
+ async function startHTTPServer(dbServer, serverState) {
2694
+ const { port } = serverState;
2695
+ if (serverState.dryRun) {
2696
+ return getStartHTTPServerResult(port, null);
2697
+ }
2698
+ const app = await getApp(port, dbServer, serverState);
2699
+ const { promise: waitReady, reject, resolve: resolve2 } = withResolvers();
2700
+ const { serve } = await import("@hono/node-server");
2701
+ const server = serve({ createServer: createServer2, fetch: app.fetch, overrideGlobalObjects: false, port }, resolve2);
2702
+ server.on("error", (error) => {
2703
+ if (typeof error === "object" && "code" in error && error.code === "EADDRINUSE") {
2704
+ return reject(new PortNotAvailableError(port));
75
2705
  }
2706
+ console.error("[Accelerate]", error);
76
2707
  });
77
- return system.accelerate.regions;
2708
+ await waitReady;
2709
+ return getStartHTTPServerResult(port, server);
2710
+ }
2711
+ function getStartHTTPServerResult(port, server) {
2712
+ return {
2713
+ async close() {
2714
+ if (!server) {
2715
+ return;
2716
+ }
2717
+ await Promise.allSettled([promisify(server.close.bind(server))(), Engine.stopAll()]);
2718
+ },
2719
+ port,
2720
+ url: `http://localhost:${port}`
2721
+ };
2722
+ }
2723
+ async function getApp(port, dbServer, serverState) {
2724
+ const { debug } = serverState;
2725
+ const [{ Hono }, { accelerateRoute }, { utilityRoute }] = await Promise.all([
2726
+ import("hono/tiny"),
2727
+ import("./accelerate-GABM6I4V.js"),
2728
+ import("./utility-W6LOZZIT.js")
2729
+ ]);
2730
+ const app = new Hono();
2731
+ const platform = await getPlatformModule.getPlatformInfo();
2732
+ if (debug) {
2733
+ console.debug("[Accelerate] platform info: %s", JSON.stringify(platform));
2734
+ }
2735
+ if (debug) {
2736
+ const { logger } = await import("hono/logger");
2737
+ app.use(
2738
+ "*",
2739
+ logger((...args) => console.log("[Accelerate]", ...args))
2740
+ );
2741
+ }
2742
+ app.use("*", async (ctx, next) => {
2743
+ ctx.set("db", dbServer);
2744
+ ctx.set("debug", Boolean(debug));
2745
+ ctx.set("platform", platform);
2746
+ ctx.set("port", port);
2747
+ ctx.set("protocol", "http");
2748
+ ctx.set("serverState", serverState);
2749
+ ctx.set("shadowDBPort", serverState.shadowDatabasePort);
2750
+ return await next();
2751
+ });
2752
+ const mainRoute = new Hono();
2753
+ mainRoute.route("/", accelerateRoute);
2754
+ mainRoute.route("/", utilityRoute);
2755
+ app.route("/", mainRoute);
2756
+ return app;
2757
+ }
2758
+
2759
+ // ../../dev/server/src/state.ts
2760
+ import { writeFile } from "fs/promises";
2761
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
2762
+
2763
+ // ../../dev/server/src/kernel.ts
2764
+ function checkProcessExists(pid, debug) {
2765
+ if (pid == null) {
2766
+ return false;
2767
+ }
2768
+ try {
2769
+ return y.kill?.(pid, 0) ?? true;
2770
+ } catch (error) {
2771
+ if (debug) {
2772
+ console.error(`Error checking if process with PID ${pid} exists:`, error);
2773
+ }
2774
+ return false;
2775
+ }
2776
+ }
2777
+
2778
+ // ../../dev/server/src/state.ts
2779
+ var urlSchema = pipe(string(), url());
2780
+ var databaseSchema = object({
2781
+ connectionString: urlSchema,
2782
+ prismaORMConnectionString: optional(urlSchema),
2783
+ terminalCommand: optional(string())
2784
+ });
2785
+ var serverSchema = object({
2786
+ url: urlSchema
2787
+ });
2788
+ var portSchema = pipe(number(), integer(), minValue(1));
2789
+ var exportsSchema = object({
2790
+ database: databaseSchema,
2791
+ http: serverSchema,
2792
+ ppg: serverSchema,
2793
+ shadowDatabase: databaseSchema
2794
+ });
2795
+ var serverDumpV1Schema = object({
2796
+ databasePort: portSchema,
2797
+ exports: optional(exportsSchema),
2798
+ name: pipe(string(), minLength(1)),
2799
+ pid: optional(pipe(number(), integer(), minValue(0))),
2800
+ port: portSchema,
2801
+ shadowDatabasePort: portSchema,
2802
+ version: literal("1")
2803
+ });
2804
+ var PRIVATE_INITIALIZE_SYMBOL = Symbol("initialize");
2805
+ var DEFAULT_NAME = "default";
2806
+ var ServerState = class {
2807
+ _databasePort;
2808
+ debug;
2809
+ dryRun;
2810
+ name;
2811
+ persistenceMode;
2812
+ pid;
2813
+ _port;
2814
+ _shadowDatabasePort;
2815
+ constructor(options) {
2816
+ this._databasePort = options.databasePort ?? NO_PORT;
2817
+ this.debug = options.debug ?? false;
2818
+ this.dryRun = options.dryRun ?? false;
2819
+ this.name = options.name ?? DEFAULT_NAME;
2820
+ this.persistenceMode = options.persistenceMode;
2821
+ this.pid = options.pid ?? y.pid;
2822
+ this._port = options.port ?? NO_PORT;
2823
+ this._shadowDatabasePort = options.shadowDatabasePort ?? NO_PORT;
2824
+ }
2825
+ static async createExclusively(options) {
2826
+ const serverState = options?.dryRun !== true && options?.persistenceMode !== "stateless" ? new StatefulServerState(options) : new StatelessServerState(options);
2827
+ await serverState[PRIVATE_INITIALIZE_SYMBOL]();
2828
+ return serverState;
2829
+ }
2830
+ static async fromServerDump(options) {
2831
+ const { debug, name = DEFAULT_NAME } = options ?? {};
2832
+ const dataDirPath = getDataDirPath(name);
2833
+ const serverDumpPath = StatefulServerState.getServerDumpPath(dataDirPath);
2834
+ const serverDumpFileContent = await readFileAsText(serverDumpPath);
2835
+ if (serverDumpFileContent == null) {
2836
+ if (debug) {
2837
+ console.debug(`[State] No server dump file found at: ${serverDumpPath}`);
2838
+ }
2839
+ return null;
2840
+ }
2841
+ if (debug) {
2842
+ console.debug(`[State] server dump file found at "${serverDumpPath}":`);
2843
+ console.debug(serverDumpFileContent);
2844
+ }
2845
+ const {
2846
+ issues,
2847
+ output: serverDump,
2848
+ success
2849
+ } = safeParse(pipe(string(), parseJson(), serverDumpV1Schema), serverDumpFileContent);
2850
+ if (!success) {
2851
+ if (debug) {
2852
+ console.debug(`[State] Invalid server dump file at "${serverDumpPath}":
2853
+ ${JSON.stringify(issues, null, 2)}`);
2854
+ }
2855
+ throw new Error(`Invalid Prisma Dev state for "${name}".`);
2856
+ }
2857
+ return new StatefulServerState({
2858
+ databasePort: serverDump.databasePort,
2859
+ debug,
2860
+ dryRun: false,
2861
+ name,
2862
+ pid: serverDump.pid,
2863
+ port: serverDump.port,
2864
+ serverDump,
2865
+ shadowDatabasePort: serverDump.shadowDatabasePort
2866
+ });
2867
+ }
2868
+ static async scan(options) {
2869
+ const { debug } = options ?? {};
2870
+ const dataDirsPath = join(getDataDirPath(DEFAULT_NAME), "..");
2871
+ if (debug) {
2872
+ console.debug(`[State] scanning for server states in: ${dataDirsPath}`);
2873
+ }
2874
+ const names = await readDirectoryNames(dataDirsPath);
2875
+ if (debug) {
2876
+ console.debug(`[State] found server names: ${JSON.stringify(names)}`);
2877
+ }
2878
+ return await Promise.all(names.map((name) => getServerStatus(name, options)));
2879
+ }
2880
+ get databasePort() {
2881
+ return this._databasePort;
2882
+ }
2883
+ get port() {
2884
+ return this._port;
2885
+ }
2886
+ get shadowDatabasePort() {
2887
+ return this._shadowDatabasePort;
2888
+ }
78
2889
  };
79
- var getPrismaPostgresRegionsOrThrow = async (input2) => {
80
- const regions = await getRegionsOrThrow(input2);
81
- const ppgRegions = regions.filter((_) => _.ppgStatus !== "unsupported").sort((a, b) => b.displayName.localeCompare(a.displayName));
82
- return ppgRegions;
2890
+ var StatelessServerState = class extends ServerState {
2891
+ constructor(options) {
2892
+ super({
2893
+ ...options,
2894
+ databasePort: options?.databasePort ?? DEFAULT_DATABASE_PORT,
2895
+ persistenceMode: "stateless",
2896
+ port: options?.port ?? DEFAULT_SERVER_PORT,
2897
+ shadowDatabasePort: options?.shadowDatabasePort ?? DEFAULT_SHADOW_DATABASE_PORT
2898
+ });
2899
+ }
2900
+ get databaseDumpPath() {
2901
+ return "<DUMP_PATH>";
2902
+ }
2903
+ get pgliteDataDirPath() {
2904
+ return "memory://";
2905
+ }
2906
+ async [PRIVATE_INITIALIZE_SYMBOL]() {
2907
+ }
2908
+ async close() {
2909
+ }
2910
+ async writeServerDump() {
2911
+ }
2912
+ };
2913
+ var StatefulServerState = class _StatefulServerState extends ServerState {
2914
+ #databaseDumpPath;
2915
+ #dataDirPath;
2916
+ #pglitePath;
2917
+ #serverDumpPath;
2918
+ #serverDump;
2919
+ #unlock = null;
2920
+ constructor(options) {
2921
+ super({ ...options, persistenceMode: "stateful" });
2922
+ this.#dataDirPath = getDataDirPath(this.name);
2923
+ this.#databaseDumpPath = join(this.#dataDirPath, "db_dump.bak");
2924
+ this.#pglitePath = join(this.#dataDirPath, ".pglite");
2925
+ this.#serverDump = options?.serverDump ?? null;
2926
+ this.#serverDumpPath = _StatefulServerState.getServerDumpPath(this.#dataDirPath);
2927
+ }
2928
+ static getServerDumpPath(dataDirPath) {
2929
+ return join(dataDirPath, "server.json");
2930
+ }
2931
+ get databaseDumpPath() {
2932
+ return this.#databaseDumpPath;
2933
+ }
2934
+ get exports() {
2935
+ return this.#serverDump?.exports;
2936
+ }
2937
+ get pgliteDataDirPath() {
2938
+ return this.#pglitePath;
2939
+ }
2940
+ async [PRIVATE_INITIALIZE_SYMBOL]() {
2941
+ await ensureDirectory(this.#dataDirPath);
2942
+ if (this.debug) {
2943
+ console.debug(`[State] using data directory: ${this.#dataDirPath}`);
2944
+ }
2945
+ try {
2946
+ this.#unlock = await (0, import_proper_lockfile.lock)(this.#dataDirPath, { lockfilePath: join(this.#dataDirPath, ".lock") });
2947
+ if (this.debug) {
2948
+ console.debug(`[State] obtained lock on: ${this.#dataDirPath}`);
2949
+ }
2950
+ const servers = await ServerState.scan({ debug: this.debug, onlyMetadata: true });
2951
+ const ports = await pickPorts({
2952
+ debug: this.debug,
2953
+ name: this.name,
2954
+ requestedPorts: {
2955
+ databasePort: this.databasePort,
2956
+ port: this.port,
2957
+ shadowDatabasePort: this.shadowDatabasePort
2958
+ },
2959
+ servers
2960
+ });
2961
+ this._databasePort = ports.databasePort;
2962
+ this._port = ports.port;
2963
+ this._shadowDatabasePort = ports.shadowDatabasePort;
2964
+ await this.writeServerDump();
2965
+ } catch (error) {
2966
+ if (error instanceof Error && "code" in error && error.code === "ELOCKED") {
2967
+ throw new ServerAlreadyRunningError(this);
2968
+ }
2969
+ throw error;
2970
+ }
2971
+ }
2972
+ async close() {
2973
+ if (this.#unlock == null) {
2974
+ return;
2975
+ }
2976
+ try {
2977
+ await this.#unlock();
2978
+ this.#unlock = null;
2979
+ if (this.debug) {
2980
+ console.debug(`[State] released lock on: ${this.#dataDirPath}`);
2981
+ }
2982
+ } catch (error) {
2983
+ console.error(`[State] failed to release lock on: ${this.#dataDirPath}`);
2984
+ throw error;
2985
+ }
2986
+ }
2987
+ async writeServerDump(exports) {
2988
+ this.#serverDump = {
2989
+ name: this.name,
2990
+ version: "1",
2991
+ pid: y.pid,
2992
+ port: this.port,
2993
+ databasePort: this.databasePort,
2994
+ shadowDatabasePort: this.shadowDatabasePort,
2995
+ exports
2996
+ };
2997
+ await writeFile(this.#serverDumpPath, `${JSON.stringify(this.#serverDump, null, 2)}
2998
+ `, { encoding: "utf-8" });
2999
+ }
3000
+ };
3001
+ async function getServerStatus(name, options) {
3002
+ const { debug, onlyMetadata } = options || {};
3003
+ const baseResult = {
3004
+ databasePort: -1,
3005
+ exports: void 0,
3006
+ name,
3007
+ pid: void 0,
3008
+ port: -1,
3009
+ shadowDatabasePort: -1,
3010
+ version: "1"
3011
+ };
3012
+ try {
3013
+ const serverState = await ServerState.fromServerDump({ debug, name });
3014
+ if (!serverState) {
3015
+ if (debug) {
3016
+ console.debug(`[State] no server state found for name: ${name}`);
3017
+ }
3018
+ return { ...baseResult, status: "no_such_server" };
3019
+ }
3020
+ baseResult.databasePort = serverState.databasePort;
3021
+ baseResult.exports = serverState.exports;
3022
+ baseResult.pid = serverState.pid;
3023
+ baseResult.port = serverState.port;
3024
+ baseResult.shadowDatabasePort = serverState.shadowDatabasePort;
3025
+ const { exports, pid } = serverState;
3026
+ if (onlyMetadata) {
3027
+ return { ...baseResult, status: "unknown" };
3028
+ }
3029
+ if (!checkProcessExists(pid, debug)) {
3030
+ if (debug) {
3031
+ console.debug(`[State] server state for "${name}" has no running process with PID: ${pid}`);
3032
+ }
3033
+ return { ...baseResult, status: "not_running" };
3034
+ }
3035
+ const dataDirPath = getDataDirPath(name);
3036
+ try {
3037
+ if (!await (0, import_proper_lockfile.check)(dataDirPath, { lockfilePath: join(dataDirPath, ".lock") })) {
3038
+ if (debug) {
3039
+ console.debug(`[State] server state for "${name}" is not locked, indicating it is not running.`);
3040
+ }
3041
+ return { ...baseResult, status: "starting_up" };
3042
+ }
3043
+ } catch (error) {
3044
+ if (debug) {
3045
+ console.error(`[State] server state for "${name}" failed to check lock:`, error);
3046
+ }
3047
+ }
3048
+ if (!exports) {
3049
+ return { ...baseResult, status: "starting_up" };
3050
+ }
3051
+ const { http } = exports;
3052
+ const { hc } = await import("hono/client");
3053
+ const healthResponse = await hc(http.url).health.$get();
3054
+ if (!healthResponse.ok) {
3055
+ if (debug) {
3056
+ console.debug(`[State] server state for "${name}" is not live: ${JSON.stringify(healthResponse)}`);
3057
+ }
3058
+ return { ...baseResult, status: "not_running" };
3059
+ }
3060
+ const health = await healthResponse.json();
3061
+ if (health.name !== name) {
3062
+ if (debug) {
3063
+ console.debug(`[State] server state for "${name}" has mismatched health response: ${JSON.stringify(health)}`);
3064
+ }
3065
+ return { ...baseResult, status: "unknown" };
3066
+ }
3067
+ if (debug) {
3068
+ console.debug(`[State] server state for "${name}" is live: ${JSON.stringify(health)}`);
3069
+ }
3070
+ return { ...baseResult, status: "running" };
3071
+ } catch (error) {
3072
+ if (debug) {
3073
+ console.error(`[State] failed to get server status for "${name}":`, error);
3074
+ }
3075
+ return { ...baseResult, status: "error" };
3076
+ }
3077
+ }
3078
+ var ServerStateAlreadyExistsError = class extends Error {
3079
+ name = "ServerStateAlreadyExistsError";
3080
+ constructor(name) {
3081
+ super(`A Prisma Dev server with the name "${name}" is already running.`);
3082
+ }
3083
+ };
3084
+ var ServerAlreadyRunningError = class extends ServerStateAlreadyExistsError {
3085
+ #server;
3086
+ name = "ServerAlreadyRunningError";
3087
+ constructor(server) {
3088
+ super(server.name);
3089
+ this.#server = server;
3090
+ }
3091
+ get server() {
3092
+ return ServerState.fromServerDump({ debug: this.#server.debug, name: this.#server.name });
3093
+ }
83
3094
  };
84
3095
 
85
- // src/utils/print.ts
86
- import { bgRed, bold, red } from "kleur/colors";
87
- function printError(text) {
88
- return bold(bgRed(" ERROR ")) + " " + red(text);
3096
+ // ../../dev/server/src/index.ts
3097
+ async function unstable_startServer(options) {
3098
+ const serverState = await ServerState.createExclusively(options);
3099
+ const [dbServer, shadowDbServer] = await Promise.all([
3100
+ startDBServer("database", serverState),
3101
+ startDBServer("shadow_database", serverState)
3102
+ ]);
3103
+ const httpServer = await startHTTPServer(dbServer, serverState);
3104
+ const ppgURL = `prisma+postgres://localhost:${httpServer.port}/?${new URLSearchParams({
3105
+ api_key: encodeAPIKey({
3106
+ databaseUrl: dbServer.prismaORMConnectionString,
3107
+ name: serverState.name,
3108
+ shadowDatabaseUrl: shadowDbServer.prismaORMConnectionString
3109
+ })
3110
+ }).toString()}`;
3111
+ const exports = {
3112
+ database: {
3113
+ connectionString: dbServer.connectionString,
3114
+ prismaORMConnectionString: dbServer.prismaORMConnectionString,
3115
+ terminalCommand: dbServer.terminalCommand
3116
+ },
3117
+ http: { url: httpServer.url },
3118
+ ppg: { url: ppgURL },
3119
+ shadowDatabase: {
3120
+ connectionString: shadowDbServer.prismaORMConnectionString,
3121
+ prismaORMConnectionString: shadowDbServer.prismaORMConnectionString,
3122
+ terminalCommand: shadowDbServer.terminalCommand
3123
+ }
3124
+ };
3125
+ await serverState.writeServerDump(exports);
3126
+ return {
3127
+ ...exports,
3128
+ close: () => closeServer(serverState, [httpServer, dbServer, shadowDbServer]),
3129
+ name: serverState.name
3130
+ };
3131
+ async function closeServer(serverState2, servers) {
3132
+ const results = await Promise.allSettled(servers.map((server) => server.close()));
3133
+ const errors = results.filter((result) => result.status === "rejected").map((result) => new Error(result.reason));
3134
+ try {
3135
+ await serverState2.close();
3136
+ } catch (error) {
3137
+ errors.push(error);
3138
+ }
3139
+ if (errors.length > 0) {
3140
+ throw new AggregateError(errors, `Failed to close some servers`);
3141
+ }
3142
+ }
89
3143
  }
90
3144
 
91
3145
  // src/Init.ts
92
- var PRISMA_DEV_DEFAULT_URL = "prisma+postgres://localhost:51213/?api_key=eyJkYXRhYmFzZVVybCI6InBvc3RncmVzOi8vcG9zdGdyZXM6cG9zdGdyZXNAbG9jYWxob3N0OjUxMjE0L3RlbXBsYXRlMT9zc2xtb2RlPWRpc2FibGUmY29ubmVjdGlvbl9saW1pdD0xJmNvbm5lY3RfdGltZW91dD0wJm1heF9pZGxlX2Nvbm5lY3Rpb25fbGlmZXRpbWU9MCZwb29sX3RpbWVvdXQ9MCZzaW5nbGVfdXNlX2Nvbm5lY3Rpb25zPXRydWUmc29ja2V0X3RpbWVvdXQ9MCIsIm5hbWUiOiJkZWZhdWx0Iiwic2hhZG93RGF0YWJhc2VVcmwiOiJwb3N0Z3JlczovL3Bvc3RncmVzOnBvc3RncmVzQGxvY2FsaG9zdDo1MTIxNS90ZW1wbGF0ZTE_c3NsbW9kZT1kaXNhYmxlJmNvbm5lY3Rpb25fbGltaXQ9MSZjb25uZWN0X3RpbWVvdXQ9MCZtYXhfaWRsZV9jb25uZWN0aW9uX2xpZmV0aW1lPTAmcG9vbF90aW1lb3V0PTAmc2luZ2xlX3VzZV9jb25uZWN0aW9ucz10cnVlJnNvY2tldF90aW1lb3V0PTAifQ";
93
3146
  var defaultSchema = (props) => {
94
3147
  const {
95
3148
  datasourceProvider = "postgresql",
@@ -148,19 +3201,31 @@ model User {
148
3201
  }
149
3202
  return schema;
150
3203
  };
151
- var defaultEnv = (url = PRISMA_DEV_DEFAULT_URL, comments = true) => {
3204
+ var defaultEnv = async (url2, comments = true) => {
3205
+ if (url2 === void 0) {
3206
+ const state = await ServerState.createExclusively({ persistenceMode: "stateful" });
3207
+ await state.close();
3208
+ const server = await unstable_startServer({
3209
+ databasePort: state.databasePort,
3210
+ dryRun: true,
3211
+ port: state.port,
3212
+ shadowDatabasePort: state.shadowDatabasePort
3213
+ });
3214
+ url2 = server.ppg.url;
3215
+ }
3216
+ url2 = new URL(url2);
152
3217
  let env = comments ? `# Environment variables declared in this file are automatically made available to Prisma.
153
3218
  # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
154
3219
 
155
3220
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
156
3221
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
157
3222
 
158
- ${url === PRISMA_DEV_DEFAULT_URL ? `# The following \`prisma+postgres\` URL is similar to the URL produced by running a local Prisma Postgres
3223
+ ${url2.protocol === "prisma+postgres:" && url2.hostname === "localhost" ? `# The following \`prisma+postgres\` URL is similar to the URL produced by running a local Prisma Postgres
159
3224
  # server with the \`prisma dev\` CLI command, when not choosing any non-default ports or settings. The API key, unlike the
160
3225
  # one found in a remote Prisma Postgres URL, does not contain any sensitive information.
161
3226
 
162
3227
  ` : ""}` : "";
163
- env += `DATABASE_URL="${url}"`;
3228
+ env += `DATABASE_URL="${url2.toString()}"`;
164
3229
  return env;
165
3230
  };
166
3231
  var defaultPort = (datasourceProvider) => {
@@ -279,7 +3344,7 @@ var Init = class _Init {
279
3344
  if (outputDirName) {
280
3345
  throw Error("The init command does not take any argument.");
281
3346
  }
282
- const { datasourceProvider, url } = await match(args).with(
3347
+ const { datasourceProvider, url: url2 } = await match(args).with(
283
3348
  {
284
3349
  "--datasource-provider": P.when(
285
3350
  (datasourceProvider2) => Boolean(datasourceProvider2)
@@ -288,16 +3353,16 @@ var Init = class _Init {
288
3353
  (input2) => {
289
3354
  const datasourceProvider2 = input2["--datasource-provider"].toLowerCase();
290
3355
  assertDatasourceProvider(datasourceProvider2);
291
- const url2 = defaultURL(datasourceProvider2);
292
- return { datasourceProvider: datasourceProvider2, url: url2 };
3356
+ const url3 = defaultURL(datasourceProvider2);
3357
+ return { datasourceProvider: datasourceProvider2, url: url3 };
293
3358
  }
294
3359
  ).with(
295
3360
  {
296
- "--url": P.when((url2) => Boolean(url2))
3361
+ "--url": P.when((url3) => Boolean(url3))
297
3362
  },
298
3363
  async (input2) => {
299
- const url2 = input2["--url"];
300
- const canConnect = await internals.canConnectToDatabase(url2);
3364
+ const url3 = input2["--url"];
3365
+ const canConnect = await internals.canConnectToDatabase(url3);
301
3366
  if (canConnect !== true) {
302
3367
  const { code, message } = canConnect;
303
3368
  if (code !== "P1003") {
@@ -308,8 +3373,8 @@ var Init = class _Init {
308
3373
  }
309
3374
  }
310
3375
  }
311
- const datasourceProvider2 = internals.protocolToConnectorType(`${url2.split(":")[0]}:`);
312
- return { datasourceProvider: datasourceProvider2, url: url2 };
3376
+ const datasourceProvider2 = internals.protocolToConnectorType(`${url3.split(":")[0]}:`);
3377
+ return { datasourceProvider: datasourceProvider2, url: url3 };
313
3378
  }
314
3379
  ).otherwise(() => {
315
3380
  return {
@@ -330,7 +3395,7 @@ var Init = class _Init {
330
3395
  let generatedSchema;
331
3396
  let generatedName;
332
3397
  if (isPpgCommand) {
333
- const PlatformCommands = await import("./_-Q6GUYNSI.js");
3398
+ const PlatformCommands = await import("./_-ZO7HQXCR.js");
334
3399
  const credentials = await credentialsFile.load();
335
3400
  if (internals.isError(credentials))
336
3401
  throw credentials;
@@ -481,11 +3546,11 @@ var Init = class _Init {
481
3546
  withModel: args["--with-model"]
482
3547
  })
483
3548
  );
484
- const databaseUrl = prismaPostgresDatabaseUrl || url;
3549
+ const databaseUrl = prismaPostgresDatabaseUrl || url2;
485
3550
  const warnings = [];
486
3551
  const envPath = path2.join(outputDir, ".env");
487
3552
  if (!fs2.existsSync(envPath)) {
488
- fs2.writeFileSync(envPath, defaultEnv(databaseUrl));
3553
+ fs2.writeFileSync(envPath, await defaultEnv(databaseUrl));
489
3554
  } else {
490
3555
  const envFile = fs2.readFileSync(envPath, { encoding: "utf8" });
491
3556
  const config = dotenv.parse(envFile);
@@ -525,39 +3590,41 @@ var Init = class _Init {
525
3590
  console.error("Failed to append client path to .gitignore file, reason: ", e);
526
3591
  }
527
3592
  const steps = [];
528
- if (datasourceProvider === "mongodb") {
529
- steps.push(`Define models in the schema.prisma file.`);
3593
+ const isPrismaDev = !args["--url"] && (datasourceProvider === "postgres" || datasourceProvider === "postgresql");
3594
+ if (isPrismaDev) {
3595
+ steps.push(
3596
+ `Run ${green(internals.getCommandWithExecutor("prisma dev"))} to start a local Prisma Postgres server.`
3597
+ );
3598
+ } else if (!args["--url"]) {
3599
+ steps.push(
3600
+ `Set the ${green("DATABASE_URL")} in the ${green(
3601
+ ".env"
3602
+ )} file to point to your existing database. If your database has no ${datasourceProvider === "mongodb" ? "collections" : "tables"} yet, read https://pris.ly/d/getting-started`
3603
+ );
3604
+ }
3605
+ if (isPrismaDev || datasourceProvider === "mongodb") {
3606
+ steps.push(`Define models in the ${green("schema.prisma")} file.`);
530
3607
  } else {
531
3608
  steps.push(
532
3609
  `Run ${green(internals.getCommandWithExecutor("prisma db pull"))} to turn your database schema into a Prisma schema.`
533
3610
  );
534
3611
  }
535
- steps.push(
536
- `Run ${green(
537
- internals.getCommandWithExecutor("prisma generate")
538
- )} to generate the Prisma Client. You can then start querying your database.`
539
- );
3612
+ if (isPrismaDev) {
3613
+ steps.push(
3614
+ `Run ${green(internals.getCommandWithExecutor("prisma migrate dev"))} to migrate your local Prisma Postgres database.`
3615
+ );
3616
+ } else {
3617
+ steps.push(
3618
+ `Run ${green(
3619
+ internals.getCommandWithExecutor("prisma generate")
3620
+ )} to generate the Prisma Client. You can then start querying your database.`
3621
+ );
3622
+ }
540
3623
  steps.push(
541
3624
  `Tip: Explore how you can extend the ${green(
542
3625
  "ORM"
543
- )} with scalable connection pooling, global caching, and real-time database events. Read: https://pris.ly/cli/beyond-orm`
3626
+ )} with scalable connection pooling, global caching, and a managed serverless Postgres database. Read: https://pris.ly/cli/beyond-orm`
544
3627
  );
545
- if (!url && !args["--datasource-provider"]) {
546
- steps.unshift(
547
- `Set the ${green("provider")} of the ${green("datasource")} block in ${green(
548
- "schema.prisma"
549
- )} to match your database: ${green("postgresql")}, ${green("mysql")}, ${green("sqlite")}, ${green(
550
- "sqlserver"
551
- )}, ${green("mongodb")} or ${green("cockroachdb")}.`
552
- );
553
- }
554
- if (!args["--url"]) {
555
- steps.unshift(
556
- `Set the ${green("DATABASE_URL")} in the ${green(
557
- ".env"
558
- )} file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started`
559
- );
560
- }
561
3628
  const defaultOutput = `
562
3629
  \u2714 Your Prisma schema was created at ${green("prisma/schema.prisma")}
563
3630
  You can now open it in your favorite editor.
@@ -565,7 +3632,7 @@ ${warnings.length > 0 && internals.logger.should.warn() ? `
565
3632
  ${warnings.join("\n")}
566
3633
  ` : ""}
567
3634
  Next steps:
568
- ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
3635
+ ${steps.map((s2, i) => `${i + 1}. ${s2}`).join("\n")}
569
3636
 
570
3637
  More information in our documentation:
571
3638
  ${internals.link("https://pris.ly/d/getting-started")}