@vite-hub/cli 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,53 +1,22 @@
1
- import { B as isRecord, b as loadAllEnv, c as createNetlifyApiClient, f as resolveHostCredentials, l as createVercelProvisionClient, m as cliErrorDiagnostics, o as createCloudflareApiClient, p as runHostCli, s as createCloudflareProvisionClient, u as isProvisionRequestError, x as withViteStageEnvironment, z as internalErrorDiagnostics } from "./provision-DXl97xG0.js";
2
- import { i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-B4mPbSbj.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
+ import { $ as internalErrorDiagnostics, B as formatInstallArgument, H as installSpecifier, I as featureIds, L as featurePackages, Q as isRecord, R as featureSupport, V as impliedFeatures, W as invariant, b as loadAllEnv, c as createNetlifyApiClient, f as resolveHostCredentials, l as createVercelProvisionClient, m as cliErrorDiagnostics, o as createCloudflareApiClient, p as runHostCli, s as createCloudflareProvisionClient, u as isProvisionRequestError, x as withViteStageEnvironment, z as features } from "./provision-DlknnTAt.js";
3
+ import { i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-DbplCDko.js";
3
4
  import { createRequire } from "node:module";
4
5
  import { spawn } from "node:child_process";
5
6
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
6
7
  import process$1 from "node:process";
7
8
  import { basename, dirname, join, relative, resolve } from "pathe";
8
- import { defineDiagnostics } from "nostics";
9
- import { mkdir, mkdtemp, open, readFile, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
9
+ import { mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
10
10
  import { basename as basename$1, delimiter, sep } from "node:path";
11
11
  import { createInterface } from "node:readline/promises";
12
- import { constants, tmpdir } from "node:os";
12
+ import { constants, homedir, tmpdir } from "node:os";
13
13
  import { parse as parse$1 } from "@babel/parser";
14
+ import { parse as parse$2 } from "rc9";
14
15
  import { parseArgs, parseEnv } from "node:util";
15
16
  import { createPublicKey, diffieHellman, generateKeyPairSync, randomBytes } from "node:crypto";
16
17
  import { hsalsa, xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
17
18
  import { blake2b } from "@noble/hashes/blake2.js";
18
- //#region \0rolldown/runtime.js
19
- var __defProp = Object.defineProperty;
20
- var __exportAll = (all, no_symbols) => {
21
- let target = {};
22
- for (var name in all) __defProp(target, name, {
23
- get: all[name],
24
- enumerable: true
25
- });
26
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
27
- return target;
28
- };
29
- //#endregion
30
- //#region ../internal/dist/invariant.js
31
- const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
32
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
33
- codes: { INTERNAL_INVARIANT_FAILED: {
34
- why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
35
- fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
36
- } }
37
- });
38
- /**
39
- * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
40
- * Use a code from the package catalog when a developer can cause the error or fix it.
41
- */
42
- function invariantError(what) {
43
- return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
44
- }
45
- /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
46
- function invariant(condition, what) {
47
- if (!condition) throw invariantError(what);
48
- }
49
- //#endregion
50
- //#region ../internal/dist/ast.js
19
+ // ../internal/dist/ast.js
51
20
  /** Parses JavaScript or TypeScript. `jsx` adds JSX syntax. */
52
21
  function parseProgram(code, options = {}) {
53
22
  const plugins = [];
@@ -149,16 +118,15 @@ function quoteString(value, style) {
149
118
  if (style.quote === "\"") return json;
150
119
  return `'${json.slice(1, -1).replaceAll("\\\"", "\"").replaceAll("'", "\\'")}'`;
151
120
  }
152
- //#endregion
153
- //#region ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
121
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
154
122
  var comma = ",".charCodeAt(0);
155
123
  var semicolon = ";".charCodeAt(0);
156
124
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
157
- var intToChar = /* @__PURE__ */ new Uint8Array(64);
125
+ var intToChar$1 = /* @__PURE__ */ new Uint8Array(64);
158
126
  var charToInt = /* @__PURE__ */ new Uint8Array(128);
159
127
  for (let i = 0; i < chars.length; i++) {
160
128
  const c = chars.charCodeAt(i);
161
- intToChar[i] = c;
129
+ intToChar$1[i] = c;
162
130
  charToInt[c] = i;
163
131
  }
164
132
  function encodeInteger(builder, num) {
@@ -166,7 +134,7 @@ function encodeInteger(builder, num) {
166
134
  let clamped = num & 31;
167
135
  num >>>= 5;
168
136
  if (num > 0) clamped |= 32;
169
- builder.write(intToChar[clamped]);
137
+ builder.write(intToChar$1[clamped]);
170
138
  } while (num > 0);
171
139
  }
172
140
  function encodeSign(num) {
@@ -199,6 +167,21 @@ var StringWriter = class {
199
167
  return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
200
168
  }
201
169
  };
170
+ function encodeRangeMappings(decoded) {
171
+ if (decoded.length === 0) return "";
172
+ const writer = new StringWriter();
173
+ for (let i = 0; i < decoded.length; i++) {
174
+ const indices = decoded[i];
175
+ if (i > 0) writer.write(semicolon);
176
+ let index = 0;
177
+ for (let j = 0; j < indices.length; j++) {
178
+ const offset = indices[j];
179
+ encodeInteger(writer, offset - index);
180
+ index = offset;
181
+ }
182
+ }
183
+ return writer.flush();
184
+ }
202
185
  function encode(decoded) {
203
186
  const writer = new StringWriter();
204
187
  let sourcesIndex = 0;
@@ -229,8 +212,7 @@ function encode(decoded) {
229
212
  }
230
213
  return writer.flush();
231
214
  }
232
- //#endregion
233
- //#region ../../node_modules/.pnpm/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
215
+ // ../../node_modules/.pnpm/magic-string@1.4.5/node_modules/magic-string/dist/index.mjs
234
216
  var BitSet = class BitSet {
235
217
  constructor(arg) {
236
218
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -241,6 +223,17 @@ var BitSet = class BitSet {
241
223
  has(n) {
242
224
  return !!(this.bits[n >> 5] & 1 << (n & 31));
243
225
  }
226
+ forEach(fn) {
227
+ const bits = this.bits;
228
+ for (let w = 0; w < bits.length; w++) {
229
+ let word = bits[w];
230
+ while (word) {
231
+ const lowest = word & -word;
232
+ fn((w << 5) + 31 - Math.clz32(lowest));
233
+ word ^= lowest;
234
+ }
235
+ }
236
+ }
244
237
  };
245
238
  var Chunk = class Chunk {
246
239
  constructor(start, end, content) {
@@ -252,6 +245,8 @@ var Chunk = class Chunk {
252
245
  this.content = content;
253
246
  this.storeName = false;
254
247
  this.edited = false;
248
+ this.replacesUntil = -1;
249
+ this.replacedFrom = -1;
255
250
  this.previous = null;
256
251
  this.next = null;
257
252
  }
@@ -268,20 +263,24 @@ var Chunk = class Chunk {
268
263
  chunk.content = this.content;
269
264
  chunk.storeName = this.storeName;
270
265
  chunk.edited = this.edited;
266
+ chunk.replacesUntil = this.replacesUntil;
267
+ chunk.replacedFrom = this.replacedFrom;
271
268
  return chunk;
272
269
  }
273
270
  contains(index) {
274
271
  return this.start < index && index < this.end;
275
272
  }
276
273
  eachNext(fn) {
277
- let chunk = this;
274
+ fn(this);
275
+ let chunk = this.next;
278
276
  while (chunk) {
279
277
  fn(chunk);
280
278
  chunk = chunk.next;
281
279
  }
282
280
  }
283
281
  eachPrevious(fn) {
284
- let chunk = this;
282
+ fn(this);
283
+ let chunk = this.previous;
285
284
  while (chunk) {
286
285
  fn(chunk);
287
286
  chunk = chunk.previous;
@@ -306,6 +305,8 @@ var Chunk = class Chunk {
306
305
  reset() {
307
306
  this.intro = "";
308
307
  this.outro = "";
308
+ this.replacesUntil = -1;
309
+ this.replacedFrom = -1;
309
310
  if (this.edited) {
310
311
  this.content = this.original;
311
312
  this.storeName = false;
@@ -322,8 +323,8 @@ var Chunk = class Chunk {
322
323
  this.outro = "";
323
324
  this.end = index;
324
325
  if (this.edited) {
325
- newChunk.edit("", false);
326
- this.content = "";
326
+ newChunk.edit("", false, true);
327
+ newChunk.replacedFrom = this.replacedFrom;
327
328
  } else this.content = originalBefore;
328
329
  newChunk.next = this.next;
329
330
  if (newChunk.next) newChunk.next.previous = newChunk;
@@ -340,8 +341,8 @@ var Chunk = class Chunk {
340
341
  const trimmed = this.content.replace(rx, "");
341
342
  if (trimmed.length) {
342
343
  if (trimmed !== this.content) {
343
- this.split(this.start + trimmed.length).edit("", void 0, true);
344
344
  if (this.edited) this.edit(trimmed, this.storeName, true);
345
+ else this.split(this.start + trimmed.length).edit("", void 0, true);
345
346
  }
346
347
  return true;
347
348
  } else {
@@ -356,9 +357,11 @@ var Chunk = class Chunk {
356
357
  const trimmed = this.content.replace(rx, "");
357
358
  if (trimmed.length) {
358
359
  if (trimmed !== this.content) {
359
- const newChunk = this.split(this.end - trimmed.length);
360
- if (this.edited) newChunk.edit(trimmed, this.storeName, true);
361
- this.edit("", void 0, true);
360
+ if (this.edited) this.edit(trimmed, this.storeName, true);
361
+ else {
362
+ this.split(this.end - trimmed.length);
363
+ this.edit("", void 0, true);
364
+ }
362
365
  }
363
366
  return true;
364
367
  } else {
@@ -368,14 +371,29 @@ var Chunk = class Chunk {
368
371
  }
369
372
  }
370
373
  };
374
+ /**
375
+ * The single error type thrown by MagicString.
376
+ *
377
+ * Every message is prefixed with `[MagicString]` so its source is obvious at a
378
+ * glance, and is kept short and consistent in tone.
379
+ */
380
+ var MagicStringError = class extends Error {
381
+ name = "MagicStringError";
382
+ constructor(message, options) {
383
+ super(`[MagicString] ${message}`, options);
384
+ }
385
+ };
371
386
  function getBtoa() {
387
+ /* v8 ignore next -- environment fallback, unreachable when `btoa` is present */
372
388
  if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
373
- else if (typeof Buffer === "function") return (str) => Buffer.from(str, "utf-8").toString("base64");
374
- else return () => {
375
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
389
+ const buffer = globalThis["Buffer"];
390
+ if (buffer) return (str) => buffer.from(str, "utf-8").toString("base64");
391
+ return () => {
392
+ throw new MagicStringError("unsupported environment: `btoa` or `Buffer` is required");
376
393
  };
394
+ /* v8 ignore stop */
377
395
  }
378
- const btoa = /*#__PURE__*/ getBtoa();
396
+ const btoa = /* #__PURE__ */ getBtoa();
379
397
  var SourceMap = class {
380
398
  constructor(properties) {
381
399
  this.version = 3;
@@ -383,28 +401,49 @@ var SourceMap = class {
383
401
  this.sources = properties.sources;
384
402
  this.sourcesContent = properties.sourcesContent;
385
403
  this.names = properties.names;
386
- this.mappings = encode(properties.mappings);
404
+ this.mappings = typeof properties.mappings === "string" ? properties.mappings : encode(properties.mappings);
387
405
  if (typeof properties.x_google_ignoreList !== "undefined") this.x_google_ignoreList = properties.x_google_ignoreList;
388
406
  if (typeof properties.debugId !== "undefined") this.debugId = properties.debugId;
407
+ if (typeof properties.rangeMappings !== "undefined") {
408
+ let shouldOutputRangeMapping = false;
409
+ for (const line of properties.rangeMappings) if (line.length !== 0) {
410
+ shouldOutputRangeMapping = true;
411
+ break;
412
+ }
413
+ if (shouldOutputRangeMapping) this.rangeMappings = encodeRangeMappings(properties.rangeMappings);
414
+ }
389
415
  }
416
+ /**
417
+ * Returns the equivalent of `JSON.stringify(map)`
418
+ */
390
419
  toString() {
391
420
  return JSON.stringify(this);
392
421
  }
422
+ /**
423
+ * Returns a DataURI containing the sourcemap. Useful for doing this sort of thing:
424
+ * `generateMap(options?: SourceMapOptions): SourceMap;`
425
+ */
393
426
  toUrl() {
394
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
427
+ return `data:application/json;charset=utf-8;base64,${btoa(this.toString())}`;
395
428
  }
396
429
  };
397
- function guessIndent(code) {
398
- const lines = code.split("\n");
399
- const tabbed = lines.filter((line) => /^\t+/.test(line));
400
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
401
- if (tabbed.length === 0 && spaced.length === 0) return null;
402
- if (tabbed.length >= spaced.length) return " ";
403
- const min = spaced.reduce((previous, current) => {
404
- const numSpaces = /^ +/.exec(current)[0].length;
405
- return Math.min(numSpaces, previous);
406
- }, Infinity);
407
- return new Array(min + 1).join(" ");
430
+ function getLocator(source) {
431
+ const lineOffsets = [0];
432
+ for (let i = source.indexOf("\n"); i !== -1; i = source.indexOf("\n", i + 1)) lineOffsets.push(i + 1);
433
+ return function locate(index) {
434
+ let i = 0;
435
+ let j = lineOffsets.length;
436
+ while (i < j) {
437
+ const m = i + j >> 1;
438
+ if (index < lineOffsets[m]) j = m;
439
+ else i = m + 1;
440
+ }
441
+ const line = i - 1;
442
+ return {
443
+ line,
444
+ column: index - lineOffsets[line]
445
+ };
446
+ };
408
447
  }
409
448
  function getRelativePath(from, to) {
410
449
  const fromParts = from.split(/[/\\]/);
@@ -420,41 +459,157 @@ function getRelativePath(from, to) {
420
459
  }
421
460
  return fromParts.concat(toParts).join("/");
422
461
  }
462
+ function guessIndent(code) {
463
+ const lines = code.split("\n");
464
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
465
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
466
+ if (tabbed.length === 0 && spaced.length === 0) return null;
467
+ if (tabbed.length >= spaced.length) return " ";
468
+ const min = spaced.reduce((previous, current) => {
469
+ const numSpaces = /^ +/.exec(current)[0].length;
470
+ return Math.min(numSpaces, previous);
471
+ }, Infinity);
472
+ return " ".repeat(min);
473
+ }
423
474
  const toString = Object.prototype.toString;
424
475
  function isObject(thing) {
425
476
  return toString.call(thing) === "[object Object]";
426
477
  }
427
- function getLocator(source) {
428
- const originalLines = source.split("\n");
429
- const lineOffsets = [];
430
- for (let i = 0, pos = 0; i < originalLines.length; i++) {
431
- lineOffsets.push(pos);
432
- pos += originalLines[i].length + 1;
433
- }
434
- return function locate(index) {
435
- let i = 0;
436
- let j = lineOffsets.length;
437
- while (i < j) {
438
- const m = i + j >> 1;
439
- if (index < lineOffsets[m]) j = m;
440
- else i = m + 1;
478
+ const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
479
+ const intToChar = /* #__PURE__ */ (() => {
480
+ const chars = /* @__PURE__ */ new Uint8Array(64);
481
+ for (let i = 0; i < 64; i++) chars[i] = BASE64_CHARS.charCodeAt(i);
482
+ return chars;
483
+ })();
484
+ const COMMA = 44;
485
+ const SEMICOLON = 59;
486
+ const BUFFER_SIZE = 16384;
487
+ const FLUSH_THRESHOLD = 16348;
488
+ const scratch = /* #__PURE__ */ new Uint8Array(BUFFER_SIZE);
489
+ function writeVlq(pos, num) {
490
+ num = num < 0 ? -num << 1 | 1 : num << 1;
491
+ do {
492
+ let clamped = num & 31;
493
+ num >>>= 5;
494
+ if (num > 0) clamped |= 32;
495
+ scratch[pos++] = intToChar[clamped];
496
+ } while (num > 0);
497
+ return pos;
498
+ }
499
+ const decoder = /* #__PURE__ */ new TextDecoder();
500
+ var MappingsEncoder = class {
501
+ constructor() {
502
+ this.out = "";
503
+ this.pos = 0;
504
+ this.lines = [];
505
+ this.buffered = 0;
506
+ this.needsComma = false;
507
+ this.prevGenColumn = 0;
508
+ this.prevSourceIndex = 0;
509
+ this.prevSourceLine = 0;
510
+ this.prevSourceColumn = 0;
511
+ this.prevNameIndex = 0;
512
+ }
513
+ endLine(segments) {
514
+ this.lines.push(segments);
515
+ this.buffered += segments.length + 1;
516
+ if (this.buffered >= 4096) this.drain(null);
517
+ }
518
+ segments(segments) {
519
+ this.drain(segments);
520
+ }
521
+ finish(segments) {
522
+ this.drain(segments);
523
+ this.flush();
524
+ return this.out;
525
+ }
526
+ drain(trailing) {
527
+ const lines = this.lines;
528
+ const lineCount = lines.length;
529
+ for (let l = 0; l <= lineCount; l++) {
530
+ const line = l < lineCount ? lines[l] : trailing;
531
+ if (line === null) break;
532
+ for (let i = 0; i < line.length; i++) {
533
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
534
+ const segment = line[i];
535
+ if (this.needsComma) scratch[this.pos++] = COMMA;
536
+ this.needsComma = true;
537
+ this.pos = writeVlq(this.pos, segment[0] - this.prevGenColumn);
538
+ this.prevGenColumn = segment[0];
539
+ this.pos = writeVlq(this.pos, segment[1] - this.prevSourceIndex);
540
+ this.prevSourceIndex = segment[1];
541
+ this.pos = writeVlq(this.pos, segment[2] - this.prevSourceLine);
542
+ this.prevSourceLine = segment[2];
543
+ this.pos = writeVlq(this.pos, segment[3] - this.prevSourceColumn);
544
+ this.prevSourceColumn = segment[3];
545
+ if (segment.length === 5) {
546
+ this.pos = writeVlq(this.pos, segment[4] - this.prevNameIndex);
547
+ this.prevNameIndex = segment[4];
548
+ }
549
+ }
550
+ if (l < lineCount) {
551
+ if (this.pos > FLUSH_THRESHOLD) this.flush();
552
+ scratch[this.pos++] = SEMICOLON;
553
+ this.needsComma = false;
554
+ this.prevGenColumn = 0;
555
+ }
441
556
  }
442
- const line = i - 1;
443
- return {
444
- line,
445
- column: index - lineOffsets[line]
446
- };
447
- };
557
+ lines.length = 0;
558
+ this.buffered = 0;
559
+ this.flush();
560
+ }
561
+ flush() {
562
+ this.out += decoder.decode(scratch.subarray(0, this.pos));
563
+ this.pos = 0;
564
+ }
565
+ };
566
+ const NEWLINE_CHAR$1 = 10;
567
+ function isWordCode(code) {
568
+ return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95;
448
569
  }
449
- const wordRegex = /\w/;
450
570
  var Mappings = class {
451
- constructor(hires) {
571
+ constructor(hires, encoder = null) {
452
572
  this.hires = hires;
453
573
  this.generatedCodeLine = 0;
454
574
  this.generatedCodeColumn = 0;
455
575
  this.raw = [];
456
576
  this.rawSegments = this.raw[this.generatedCodeLine] = [];
457
- this.pending = null;
577
+ this.rawRangeMappingsIndices = [];
578
+ this.rawRangeMappings = hires === "experimental-range" ? [this.rawRangeMappingsIndices] : void 0;
579
+ this.encoder = encoder;
580
+ }
581
+ nextLine() {
582
+ if (this.encoder === null) {
583
+ this.generatedCodeLine += 1;
584
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
585
+ } else {
586
+ this.encoder.endLine(this.rawSegments);
587
+ this.rawSegments = [];
588
+ this.generatedCodeLine += 1;
589
+ }
590
+ this.generatedCodeColumn = 0;
591
+ if (this.rawRangeMappings) this.rawRangeMappings[this.generatedCodeLine] = this.rawRangeMappingsIndices = [];
592
+ }
593
+ /**
594
+ * Emits the mappings for one MagicString: its intro, every chunk (with the
595
+ * chunk's own intro/outro) and its outro. `sourceIndex === -1` means the
596
+ * string has no source of its own, so its content only advances the
597
+ * generated position without mapping anything.
598
+ */
599
+ addMagicString(magicString, sourceIndex, nameIndex) {
600
+ const { original } = magicString;
601
+ const locate = getLocator(original);
602
+ if (magicString.intro) this.advance(magicString.intro);
603
+ magicString.firstChunk.eachNext((chunk) => {
604
+ if (chunk.intro.length) this.advance(chunk.intro);
605
+ if (sourceIndex === -1) this.advance(chunk.content);
606
+ else if (chunk.edited) {
607
+ const name = chunk.storeName ? nameIndex.get(original.slice(chunk.start, chunk.replacesUntil)) : void 0;
608
+ this.addEdit(sourceIndex, chunk.content, locate(chunk.start), name ?? -1);
609
+ } else this.addUneditedChunk(sourceIndex, chunk, original, locate(chunk.start), magicString.sourcemapLocations);
610
+ if (chunk.outro.length) this.advance(chunk.outro);
611
+ });
612
+ if (magicString.outro) this.advance(magicString.outro);
458
613
  }
459
614
  addEdit(sourceIndex, content, loc, nameIndex) {
460
615
  if (content.length) {
@@ -470,9 +625,7 @@ var Mappings = class {
470
625
  ];
471
626
  if (nameIndex >= 0) segment.push(nameIndex);
472
627
  this.rawSegments.push(segment);
473
- this.generatedCodeLine += 1;
474
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
475
- this.generatedCodeColumn = 0;
628
+ this.nextLine();
476
629
  previousContentLineEnd = contentLineEnd;
477
630
  contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
478
631
  }
@@ -485,73 +638,193 @@ var Mappings = class {
485
638
  if (nameIndex >= 0) segment.push(nameIndex);
486
639
  this.rawSegments.push(segment);
487
640
  this.advance(content.slice(previousContentLineEnd + 1));
488
- } else if (this.pending) {
489
- this.rawSegments.push(this.pending);
490
- this.advance(content);
491
641
  }
492
- this.pending = null;
493
642
  }
494
643
  addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
495
- let originalCharIndex = chunk.start;
496
- let first = true;
497
- let charInHiresBoundary = false;
498
- while (originalCharIndex < chunk.end) {
499
- if (original[originalCharIndex] === "\n") {
500
- loc.line += 1;
501
- loc.column = 0;
502
- this.generatedCodeLine += 1;
503
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
504
- this.generatedCodeColumn = 0;
505
- first = true;
506
- charInHiresBoundary = false;
507
- } else {
508
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
509
- const segment = [
510
- this.generatedCodeColumn,
511
- sourceIndex,
512
- loc.line,
513
- loc.column
514
- ];
515
- if (this.hires === "boundary") {
516
- if (wordRegex.test(original[originalCharIndex])) {
644
+ const end = chunk.end;
645
+ let i = chunk.start;
646
+ if (this.hires) {
647
+ const boundary = this.hires === "boundary";
648
+ const experimentalRange = this.hires === "experimental-range";
649
+ const encoder = experimentalRange ? null : this.encoder;
650
+ let charInHiresBoundary = false;
651
+ while (i < end) {
652
+ if (encoder !== null && this.rawSegments.length >= 4096) {
653
+ encoder.segments(this.rawSegments);
654
+ this.rawSegments.length = 0;
655
+ }
656
+ if (experimentalRange && i + 1 >= end) this.rawSegments.push([
657
+ this.generatedCodeColumn,
658
+ sourceIndex,
659
+ loc.line,
660
+ loc.column
661
+ ]);
662
+ const code = original.charCodeAt(i);
663
+ if (code === NEWLINE_CHAR$1) {
664
+ loc.line += 1;
665
+ loc.column = 0;
666
+ this.nextLine();
667
+ charInHiresBoundary = false;
668
+ } else {
669
+ if (boundary) {
670
+ if (isWordCode(code)) {
517
671
  if (!charInHiresBoundary) {
518
- this.rawSegments.push(segment);
672
+ this.rawSegments.push([
673
+ this.generatedCodeColumn,
674
+ sourceIndex,
675
+ loc.line,
676
+ loc.column
677
+ ]);
519
678
  charInHiresBoundary = true;
520
679
  }
521
680
  } else {
522
- this.rawSegments.push(segment);
681
+ this.rawSegments.push([
682
+ this.generatedCodeColumn,
683
+ sourceIndex,
684
+ loc.line,
685
+ loc.column
686
+ ]);
523
687
  charInHiresBoundary = false;
524
688
  }
525
- } else this.rawSegments.push(segment);
689
+ } else if (experimentalRange) {
690
+ if (i === chunk.start) {
691
+ this.rawRangeMappingsIndices.push(this.rawSegments.length);
692
+ this.rawSegments.push([
693
+ this.generatedCodeColumn,
694
+ sourceIndex,
695
+ loc.line,
696
+ loc.column
697
+ ]);
698
+ }
699
+ } else this.rawSegments.push([
700
+ this.generatedCodeColumn,
701
+ sourceIndex,
702
+ loc.line,
703
+ loc.column
704
+ ]);
705
+ loc.column += 1;
706
+ this.generatedCodeColumn += 1;
526
707
  }
527
- loc.column += 1;
528
- this.generatedCodeColumn += 1;
529
- first = false;
708
+ i += 1;
709
+ }
710
+ } else {
711
+ const bits = sourcemapLocations.bits;
712
+ while (i < end) {
713
+ let newline = original.indexOf("\n", i);
714
+ if (newline === -1 || newline > end) newline = end;
715
+ if (newline > i) {
716
+ this.rawSegments.push([
717
+ this.generatedCodeColumn,
718
+ sourceIndex,
719
+ loc.line,
720
+ loc.column
721
+ ]);
722
+ for (let w = i + 1 >> 5, last = newline - 1 >> 5; w <= last; w++) {
723
+ let word = bits[w];
724
+ if (!word) continue;
725
+ const base = w << 5;
726
+ while (word) {
727
+ const lowest = word & -word;
728
+ const index = base + 31 - Math.clz32(lowest);
729
+ if (index > i && index < newline) {
730
+ const offset = index - i;
731
+ this.rawSegments.push([
732
+ this.generatedCodeColumn + offset,
733
+ sourceIndex,
734
+ loc.line,
735
+ loc.column + offset
736
+ ]);
737
+ }
738
+ word ^= lowest;
739
+ }
740
+ }
741
+ loc.column += newline - i;
742
+ this.generatedCodeColumn += newline - i;
743
+ }
744
+ if (newline === end) break;
745
+ loc.line += 1;
746
+ loc.column = 0;
747
+ this.nextLine();
748
+ i = newline + 1;
530
749
  }
531
- originalCharIndex += 1;
532
750
  }
533
- this.pending = null;
534
751
  }
535
752
  advance(str) {
536
753
  if (!str) return;
537
- const lines = str.split("\n");
538
- if (lines.length > 1) {
539
- for (let i = 0; i < lines.length - 1; i++) {
540
- this.generatedCodeLine++;
541
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
542
- }
543
- this.generatedCodeColumn = 0;
544
- }
545
- this.generatedCodeColumn += lines[lines.length - 1].length;
754
+ const lastNewline = str.lastIndexOf("\n");
755
+ for (let i = str.indexOf("\n"); i !== -1; i = str.indexOf("\n", i + 1)) this.nextLine();
756
+ this.generatedCodeColumn += str.length - lastNewline - 1;
546
757
  }
547
758
  };
548
759
  const n = "\n";
760
+ const NEWLINE_CHAR = "\n".charCodeAt(0);
761
+ const CR_CHAR = "\r".charCodeAt(0);
549
762
  const warned = {
550
763
  insertLeft: false,
551
764
  insertRight: false,
552
765
  storeName: false
553
766
  };
767
+ /**
768
+ * Expands the `$` substitution patterns that `String.prototype.replace` accepts
769
+ * in a string replacement.
770
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
771
+ *
772
+ * `captures` holds the capture groups in order, so `captures[0]` is `$1`.
773
+ * `namedCaptures` is `undefined` when the pattern has no named groups, and
774
+ * `$<name>` is then literal text - which is also the case for a string search
775
+ * value, where there are no groups of either kind.
776
+ */
777
+ function expandReplacement(replacement, matched, position, str, captures, namedCaptures) {
778
+ if (!replacement.includes("$")) return replacement;
779
+ let result = "";
780
+ let index = 0;
781
+ while (index < replacement.length) {
782
+ const dollar = replacement.indexOf("$", index);
783
+ if (dollar === -1) {
784
+ result += replacement.slice(index);
785
+ break;
786
+ }
787
+ result += replacement.slice(index, dollar);
788
+ const char = replacement[dollar + 1];
789
+ let expansion = "$";
790
+ let consumed = 1;
791
+ if (char === "$") consumed = 2;
792
+ else if (char === "&") {
793
+ expansion = matched;
794
+ consumed = 2;
795
+ } else if (char === "`") {
796
+ expansion = str.slice(0, position);
797
+ consumed = 2;
798
+ } else if (char === "'") {
799
+ expansion = str.slice(position + matched.length);
800
+ consumed = 2;
801
+ } else if (char === "<" && namedCaptures !== void 0) {
802
+ const close = replacement.indexOf(">", dollar + 2);
803
+ if (close !== -1) {
804
+ expansion = namedCaptures[replacement.slice(dollar + 2, close)] ?? "";
805
+ consumed = close + 1 - dollar;
806
+ }
807
+ } else if (char >= "0" && char <= "9") {
808
+ const second = replacement[dollar + 2];
809
+ const double = second >= "0" && second <= "9" ? Number(char + second) : NaN;
810
+ const single = Number(char);
811
+ if (double >= 1 && double <= captures.length) {
812
+ expansion = captures[double - 1] ?? "";
813
+ consumed = 3;
814
+ } else if (single >= 1 && single <= captures.length) {
815
+ expansion = captures[single - 1] ?? "";
816
+ consumed = 2;
817
+ }
818
+ }
819
+ result += expansion;
820
+ index = dollar + consumed;
821
+ }
822
+ return result;
823
+ }
554
824
  var MagicString = class MagicString {
825
+ /**
826
+ * Wraps `string` for editing; every index passed to the editing methods refers to this original string.
827
+ */
555
828
  constructor(string, options = {}) {
556
829
  const chunk = new Chunk(0, string.length, string);
557
830
  Object.defineProperties(this, {
@@ -581,11 +854,11 @@ var MagicString = class MagicString {
581
854
  },
582
855
  byStart: {
583
856
  writable: true,
584
- value: {}
857
+ value: /* @__PURE__ */ new Map([[0, chunk]])
585
858
  },
586
859
  byEnd: {
587
860
  writable: true,
588
- value: {}
861
+ value: /* @__PURE__ */ new Map([[string.length, chunk]])
589
862
  },
590
863
  filename: {
591
864
  writable: true,
@@ -601,7 +874,7 @@ var MagicString = class MagicString {
601
874
  },
602
875
  storedNames: {
603
876
  writable: true,
604
- value: {}
877
+ value: /* @__PURE__ */ new Set()
605
878
  },
606
879
  indentStr: {
607
880
  writable: true,
@@ -614,47 +887,74 @@ var MagicString = class MagicString {
614
887
  offset: {
615
888
  writable: true,
616
889
  value: options.offset || 0
890
+ },
891
+ hasMovedChunks: {
892
+ writable: true,
893
+ value: false
617
894
  }
618
895
  });
619
- this.byStart[0] = chunk;
620
- this.byEnd[string.length] = chunk;
621
896
  }
897
+ /**
898
+ * Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is false.
899
+ */
622
900
  addSourcemapLocation(char) {
623
901
  this.sourcemapLocations.add(char);
624
902
  }
903
+ /**
904
+ * Appends the specified content to the end of the string.
905
+ */
625
906
  append(content) {
626
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
907
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
627
908
  this.outro += content;
628
909
  return this;
629
910
  }
911
+ /**
912
+ * Appends the specified content at the index in the original string.
913
+ * If a range *ending* with index is subsequently moved, the insert will be moved with it.
914
+ * See also `s.prependLeft(...)`.
915
+ */
630
916
  appendLeft(index, content) {
631
- index = index + this.offset;
632
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
917
+ index = this._resolveIndex(index);
918
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
919
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
633
920
  this._split(index);
634
- const chunk = this.byEnd[index];
921
+ const chunk = this.byEnd.get(index);
635
922
  if (chunk) chunk.appendLeft(content);
636
923
  else this.intro += content;
637
924
  return this;
638
925
  }
926
+ /**
927
+ * Appends the specified content at the index in the original string.
928
+ * If a range *starting* with index is subsequently moved, the insert will be moved with it.
929
+ * See also `s.prependRight(...)`.
930
+ */
639
931
  appendRight(index, content) {
640
- index = index + this.offset;
641
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
932
+ index = this._resolveIndex(index);
933
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
934
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
642
935
  this._split(index);
643
- const chunk = this.byStart[index];
936
+ const chunk = this.byStart.get(index);
644
937
  if (chunk) chunk.appendRight(content);
645
938
  else this.outro += content;
646
939
  return this;
647
940
  }
941
+ /**
942
+ * Returns an independent copy: the chunk list, string-level intro/outro,
943
+ * sourcemap locations, stored names, indent exclusion ranges, `offset`,
944
+ * `filename` and `ignoreList` are all copied; later edits to either string
945
+ * do not affect the other.
946
+ */
648
947
  clone() {
649
948
  const cloned = new MagicString(this.original, {
650
949
  filename: this.filename,
950
+ ignoreList: this.ignoreList,
651
951
  offset: this.offset
652
952
  });
653
953
  let originalChunk = this.firstChunk;
654
954
  let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
655
955
  while (originalChunk) {
656
- cloned.byStart[clonedChunk.start] = clonedChunk;
657
- cloned.byEnd[clonedChunk.end] = clonedChunk;
956
+ cloned.byStart.set(clonedChunk.start, clonedChunk);
957
+ cloned.byEnd.set(clonedChunk.end, clonedChunk);
658
958
  const nextOriginalChunk = originalChunk.next;
659
959
  const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
660
960
  if (nextClonedChunk) {
@@ -667,47 +967,72 @@ var MagicString = class MagicString {
667
967
  cloned.lastChunk = clonedChunk;
668
968
  if (this.indentExclusionRanges) cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
669
969
  cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
970
+ cloned.storedNames = new Set(this.storedNames);
670
971
  cloned.intro = this.intro;
671
972
  cloned.outro = this.outro;
973
+ cloned.hasMovedChunks = this.hasMovedChunks;
672
974
  return cloned;
673
975
  }
976
+ /**
977
+ * Generates a sourcemap object with raw mappings in array form, rather than encoded as a string.
978
+ * Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead.
979
+ */
674
980
  generateDecodedMap(options) {
675
981
  options = options || {};
676
- const sourceIndex = 0;
677
- const names = Object.keys(this.storedNames);
678
982
  const mappings = new Mappings(options.hires);
679
- const locate = getLocator(this.original);
680
- if (this.intro) mappings.advance(this.intro);
681
- this.firstChunk.eachNext((chunk) => {
682
- const loc = locate(chunk.start);
683
- if (chunk.intro.length) mappings.advance(chunk.intro);
684
- if (chunk.edited) mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
685
- else mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
686
- if (chunk.outro.length) mappings.advance(chunk.outro);
983
+ const names = this._generateMappings(mappings);
984
+ return {
985
+ ...this._mapProperties(options, names),
986
+ mappings: mappings.raw,
987
+ rangeMappings: mappings.rawRangeMappings
988
+ };
989
+ }
990
+ /**
991
+ * Generates a version 3 sourcemap.
992
+ */
993
+ generateMap(options) {
994
+ options = options || {};
995
+ const encoder = new MappingsEncoder();
996
+ const mappings = new Mappings(options.hires, encoder);
997
+ const names = this._generateMappings(mappings);
998
+ return new SourceMap({
999
+ ...this._mapProperties(options, names),
1000
+ mappings: encoder.finish(mappings.rawSegments),
1001
+ rangeMappings: mappings.rawRangeMappings
687
1002
  });
688
- if (this.outro) mappings.advance(this.outro);
1003
+ }
1004
+ /** @internal */
1005
+ _generateMappings(mappings) {
1006
+ const names = [...this.storedNames];
1007
+ mappings.addMagicString(this, 0, new Map(names.map((name, i) => [name, i])));
1008
+ return names;
1009
+ }
1010
+ /** @internal */
1011
+ _mapProperties(options, names) {
689
1012
  return {
690
1013
  file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
691
1014
  sources: [options.source ? getRelativePath(options.file || "", options.source) : options.file || ""],
692
1015
  sourcesContent: options.includeContent ? [this.original] : void 0,
693
1016
  names,
694
- mappings: mappings.raw,
695
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
1017
+ x_google_ignoreList: this.ignoreList ? [0] : void 0
696
1018
  };
697
1019
  }
698
- generateMap(options) {
699
- return new SourceMap(this.generateDecodedMap(options));
700
- }
1020
+ /** @internal */
701
1021
  _ensureindentStr() {
702
1022
  if (this.indentStr === void 0) this.indentStr = guessIndent(this.original);
703
1023
  }
1024
+ /** @internal */
704
1025
  _getRawIndentString() {
705
1026
  this._ensureindentStr();
706
1027
  return this.indentStr;
707
1028
  }
1029
+ /**
1030
+ * Returns the indentation string guessed from the original content, falling back to a single tab character.
1031
+ * This is the value `s.indent()` uses when no prefix is supplied.
1032
+ */
708
1033
  getIndentString() {
709
1034
  this._ensureindentStr();
710
- return this.indentStr === null ? " " : this.indentStr;
1035
+ return this.indentStr ?? " ";
711
1036
  }
712
1037
  indent(indentStr, options) {
713
1038
  const pattern = /^[^\r\n]/gm;
@@ -720,55 +1045,78 @@ var MagicString = class MagicString {
720
1045
  indentStr = this.indentStr || " ";
721
1046
  }
722
1047
  if (indentStr === "") return this;
1048
+ const resolvedIndentStr = indentStr;
723
1049
  options = options || {};
724
- const isExcluded = {};
1050
+ const isExcluded = new BitSet();
725
1051
  if (options.exclude) (typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude).forEach((exclusion) => {
726
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded[i] = true;
1052
+ for (let i = exclusion[0]; i < exclusion[1]; i += 1) isExcluded.add(i);
727
1053
  });
728
1054
  let shouldIndentNextCharacter = options.indentStart !== false;
729
- const replacer = (match) => {
730
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
731
- shouldIndentNextCharacter = true;
732
- return match;
1055
+ const indentPiece = (str) => {
1056
+ if (str === "") return str;
1057
+ const indented = str.replace(pattern, (match, offset) => offset > 0 || shouldIndentNextCharacter ? `${resolvedIndentStr}${match}` : match);
1058
+ shouldIndentNextCharacter = str[str.length - 1] === "\n";
1059
+ return indented;
733
1060
  };
734
- this.intro = this.intro.replace(pattern, replacer);
1061
+ this.intro = indentPiece(this.intro);
735
1062
  let charIndex = 0;
736
1063
  let chunk = this.firstChunk;
1064
+ const indentAt = (index) => {
1065
+ shouldIndentNextCharacter = false;
1066
+ if (index === chunk.start) chunk.appendRight(resolvedIndentStr);
1067
+ else {
1068
+ this._splitChunk(chunk, index);
1069
+ chunk = chunk.next;
1070
+ chunk.prependRight(resolvedIndentStr);
1071
+ }
1072
+ };
737
1073
  while (chunk) {
738
1074
  const end = chunk.end;
1075
+ if (!isExcluded.has(chunk.start)) chunk.intro = indentPiece(chunk.intro);
739
1076
  if (chunk.edited) {
740
- if (!isExcluded[charIndex]) {
741
- chunk.content = chunk.content.replace(pattern, replacer);
742
- if (chunk.content.length) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1077
+ if (!isExcluded.has(chunk.start)) chunk.content = indentPiece(chunk.content);
1078
+ else if (chunk.content) shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
1079
+ } else if (options.exclude) {
1080
+ charIndex = chunk.start;
1081
+ while (charIndex < end) {
1082
+ if (!isExcluded.has(charIndex)) {
1083
+ const char = this.original.charCodeAt(charIndex);
1084
+ if (char === NEWLINE_CHAR) shouldIndentNextCharacter = true;
1085
+ else if (char !== CR_CHAR && shouldIndentNextCharacter) indentAt(charIndex);
1086
+ }
1087
+ charIndex += 1;
743
1088
  }
744
1089
  } else {
745
1090
  charIndex = chunk.start;
746
1091
  while (charIndex < end) {
747
- if (!isExcluded[charIndex]) {
748
- const char = this.original[charIndex];
749
- if (char === "\n") shouldIndentNextCharacter = true;
750
- else if (char !== "\r" && shouldIndentNextCharacter) {
751
- shouldIndentNextCharacter = false;
752
- if (charIndex === chunk.start) chunk.prependRight(indentStr);
753
- else {
754
- this._splitChunk(chunk, charIndex);
755
- chunk = chunk.next;
756
- chunk.prependRight(indentStr);
757
- }
758
- }
1092
+ if (!shouldIndentNextCharacter) {
1093
+ const nextLine = this.original.indexOf(n, charIndex);
1094
+ if (nextLine === -1 || nextLine >= end) break;
1095
+ shouldIndentNextCharacter = true;
1096
+ charIndex = nextLine + 1;
1097
+ continue;
1098
+ }
1099
+ const char = this.original.charCodeAt(charIndex);
1100
+ if (char === NEWLINE_CHAR || char === CR_CHAR) {
1101
+ charIndex += 1;
1102
+ continue;
759
1103
  }
1104
+ indentAt(charIndex);
760
1105
  charIndex += 1;
761
1106
  }
762
1107
  }
1108
+ if (!isExcluded.has(chunk.end - 1)) chunk.outro = indentPiece(chunk.outro);
763
1109
  charIndex = chunk.end;
764
1110
  chunk = chunk.next;
765
1111
  }
766
- this.outro = this.outro.replace(pattern, replacer);
1112
+ this.outro = indentPiece(this.outro);
767
1113
  return this;
768
1114
  }
1115
+ /** @internal */
769
1116
  insert() {
770
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
1117
+ throw new MagicStringError("insert() is deprecated, use appendLeft() or prependRight()");
771
1118
  }
1119
+ /** @internal */
772
1120
  insertLeft(index, content) {
773
1121
  if (!warned.insertLeft) {
774
1122
  console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
@@ -776,6 +1124,7 @@ var MagicString = class MagicString {
776
1124
  }
777
1125
  return this.appendLeft(index, content);
778
1126
  }
1127
+ /** @internal */
779
1128
  insertRight(index, content) {
780
1129
  if (!warned.insertRight) {
781
1130
  console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
@@ -783,53 +1132,117 @@ var MagicString = class MagicString {
783
1132
  }
784
1133
  return this.prependRight(index, content);
785
1134
  }
786
- move(start, end, index) {
787
- start = start + this.offset;
788
- end = end + this.offset;
789
- index = index + this.offset;
790
- if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
1135
+ /**
1136
+ * Moves the characters from `start` and `end` to `index`.
1137
+ *
1138
+ * `affinity` controls where the range is anchored at `index`. With the
1139
+ * default `'right'`, it is inserted before the content that starts at `index`;
1140
+ * with `'left'`, it is inserted after the content that ends at `index`. The
1141
+ * two differ only when other content has already been moved to that boundary,
1142
+ * mirroring the `appendLeft`/`appendRight` distinction.
1143
+ */
1144
+ move(start, end, index, affinity = "right") {
1145
+ start = this._resolveIndex(start);
1146
+ end = this._resolveIndex(end);
1147
+ index = this._resolveIndex(index);
1148
+ if (start === end) return this;
1149
+ if (start < 0 || end > this.original.length || index < 0 || index > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1150
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
1151
+ if (index >= start && index <= end) throw new MagicStringError("cannot move a selection inside itself");
791
1152
  this._split(start);
792
1153
  this._split(end);
793
1154
  this._split(index);
794
- const first = this.byStart[start];
795
- const last = this.byEnd[end];
1155
+ const first = this.byStart.get(start);
1156
+ const last = this.byEnd.get(end);
1157
+ if (!first || !last) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1158
+ if (this.hasMovedChunks) {
1159
+ let cursor = first;
1160
+ while (cursor !== last) {
1161
+ cursor = cursor.next;
1162
+ if (!cursor || cursor.start < start || cursor.end > end) throw new MagicStringError(`cannot move ${start} to ${end} because an earlier move split that range`);
1163
+ }
1164
+ }
796
1165
  const oldLeft = first.previous;
797
1166
  const oldRight = last.next;
798
- const newRight = this.byStart[index];
799
- if (!newRight && last === this.lastChunk) return this;
800
- const newLeft = newRight ? newRight.previous : this.lastChunk;
1167
+ let newLeft;
1168
+ let newRight;
1169
+ if (affinity === "left") {
1170
+ newLeft = this.byEnd.get(index) ?? null;
1171
+ if (!newLeft) {
1172
+ if (first === this.firstChunk) return this;
1173
+ newRight = this.firstChunk;
1174
+ } else {
1175
+ if (newLeft.next === first) return this;
1176
+ newRight = newLeft.next;
1177
+ }
1178
+ } else {
1179
+ newRight = this.byStart.get(index) ?? null;
1180
+ if (!newRight) {
1181
+ if (last === this.lastChunk) return this;
1182
+ newLeft = this.lastChunk;
1183
+ } else {
1184
+ if (newRight.previous === last) return this;
1185
+ newLeft = newRight.previous;
1186
+ }
1187
+ }
801
1188
  if (oldLeft) oldLeft.next = oldRight;
802
1189
  if (oldRight) oldRight.previous = oldLeft;
803
1190
  if (newLeft) newLeft.next = first;
804
1191
  if (newRight) newRight.previous = last;
805
- if (!first.previous) this.firstChunk = last.next;
806
- if (!last.next) {
807
- this.lastChunk = first.previous;
1192
+ if (!oldLeft) this.firstChunk = oldRight;
1193
+ if (!oldRight) {
1194
+ this.lastChunk = oldLeft;
808
1195
  this.lastChunk.next = null;
809
1196
  }
810
1197
  first.previous = newLeft;
811
1198
  last.next = newRight || null;
812
1199
  if (!newLeft) this.firstChunk = first;
813
1200
  if (!newRight) this.lastChunk = last;
1201
+ this.hasMovedChunks = true;
814
1202
  return this;
815
1203
  }
1204
+ /**
1205
+ * Replaces the characters from `start` to `end` with `content`, along with the appended/prepended content in
1206
+ * that range. The same restrictions as `s.remove()` apply.
1207
+ *
1208
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1209
+ * for later inclusion in a sourcemap's names array - and a contentOnly property which determines whether only
1210
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1211
+ *
1212
+ * It may be preferred to use `s.update(...)` instead if you wish to avoid overwriting the appended/prepended content.
1213
+ */
816
1214
  overwrite(start, end, content, options) {
817
- options = options || {};
1215
+ if (options === true) {
1216
+ if (!warned.storeName) {
1217
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
1218
+ warned.storeName = true;
1219
+ }
1220
+ return this.update(start, end, content, {
1221
+ storeName: true,
1222
+ overwrite: true
1223
+ });
1224
+ }
1225
+ const optionObject = typeof options === "object" && options ? options : {};
818
1226
  return this.update(start, end, content, {
819
- ...options,
820
- overwrite: !options.contentOnly
1227
+ ...optionObject,
1228
+ overwrite: !optionObject.contentOnly
821
1229
  });
822
1230
  }
1231
+ /**
1232
+ * Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply.
1233
+ *
1234
+ * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored
1235
+ * for later inclusion in a sourcemap's names array - and an overwrite property which determines whether only
1236
+ * the content is overwritten, or anything that was appended/prepended to the range as well.
1237
+ */
823
1238
  update(start, end, content, options) {
824
- start = start + this.offset;
825
- end = end + this.offset;
826
- if (typeof content !== "string") throw new TypeError("replacement content must be a string");
827
- if (this.original.length !== 0) {
828
- while (start < 0) start += this.original.length;
829
- while (end < 0) end += this.original.length;
830
- }
831
- if (end > this.original.length) throw new Error("end is out of bounds");
832
- if (start === end) throw new Error("Cannot overwrite a zero-length range – use appendLeft or prependRight instead");
1239
+ start = this._resolveIndex(start);
1240
+ end = this._resolveIndex(end);
1241
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
1242
+ if (start < 0) throw new MagicStringError(`start ${start} is out of bounds`);
1243
+ if (end > this.original.length) throw new MagicStringError(`end ${end} is out of bounds`);
1244
+ if (start === end) throw new MagicStringError(`cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`);
1245
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
833
1246
  this._split(start);
834
1247
  this._split(end);
835
1248
  if (options === true) {
@@ -839,152 +1252,178 @@ var MagicString = class MagicString {
839
1252
  }
840
1253
  options = { storeName: true };
841
1254
  }
842
- const storeName = options !== void 0 ? options.storeName : false;
843
- const overwrite = options !== void 0 ? options.overwrite : false;
844
- if (storeName) {
845
- const original = this.original.slice(start, end);
846
- Object.defineProperty(this.storedNames, original, {
847
- writable: true,
848
- value: true,
849
- enumerable: true
850
- });
1255
+ const optionObject = typeof options === "object" && options ? options : {};
1256
+ const storeName = optionObject.storeName || false;
1257
+ const overwrite = optionObject.overwrite || false;
1258
+ if (storeName) this.storedNames.add(this.original.slice(start, end));
1259
+ const first = this.byStart.get(start);
1260
+ for (let chunk = first; chunk.end < end;) {
1261
+ const next = chunk.next;
1262
+ if (next === null || next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
1263
+ chunk = next;
851
1264
  }
852
- const first = this.byStart[start];
853
- const last = this.byEnd[end];
854
- if (first) {
855
- let chunk = first;
856
- while (chunk !== last) {
857
- if (chunk.next !== this.byStart[chunk.end]) throw new Error("Cannot overwrite across a split point");
858
- chunk = chunk.next;
859
- chunk.edit("", false);
860
- }
861
- first.edit(content, storeName, !overwrite);
862
- } else {
863
- const newChunk = new Chunk(start, end, "").edit(content, storeName);
864
- last.next = newChunk;
865
- newChunk.previous = last;
1265
+ for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
1266
+ chunk.edit("", false, !overwrite);
1267
+ chunk.replacesUntil = -1;
1268
+ chunk.replacedFrom = start;
866
1269
  }
1270
+ first.edit(content, storeName, !overwrite);
1271
+ first.replacesUntil = end;
1272
+ first.replacedFrom = -1;
867
1273
  return this;
868
1274
  }
1275
+ /**
1276
+ * Prepends the string with the specified content.
1277
+ */
869
1278
  prepend(content) {
870
- if (typeof content !== "string") throw new TypeError("outro content must be a string");
1279
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
871
1280
  this.intro = content + this.intro;
872
1281
  return this;
873
1282
  }
1283
+ /**
1284
+ * Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at index
1285
+ */
874
1286
  prependLeft(index, content) {
875
- index = index + this.offset;
876
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1287
+ index = this._resolveIndex(index);
1288
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1289
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
877
1290
  this._split(index);
878
- const chunk = this.byEnd[index];
1291
+ const chunk = this.byEnd.get(index);
879
1292
  if (chunk) chunk.prependLeft(content);
880
1293
  else this.intro = content + this.intro;
881
1294
  return this;
882
1295
  }
1296
+ /**
1297
+ * Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index`
1298
+ */
883
1299
  prependRight(index, content) {
884
- index = index + this.offset;
885
- if (typeof content !== "string") throw new TypeError("inserted content must be a string");
1300
+ index = this._resolveIndex(index);
1301
+ if (index < 0 || index > this.original.length) throw new MagicStringError(`index ${index} is out of bounds`);
1302
+ if (typeof content !== "string") throw new MagicStringError(`content must be a string, got ${typeof content}`);
886
1303
  this._split(index);
887
- const chunk = this.byStart[index];
1304
+ const chunk = this.byStart.get(index);
888
1305
  if (chunk) chunk.prependRight(content);
889
1306
  else this.outro = content + this.outro;
890
1307
  return this;
891
1308
  }
1309
+ /**
1310
+ * Removes the characters from `start` to `end` (of the original string, **not** the generated string).
1311
+ * Content appended or prepended at positions strictly inside the range is removed with it, while
1312
+ * content attached at `start` or `end` is preserved — use `s.overwrite(start, end, '')` to remove
1313
+ * the range including its edge inserts.
1314
+ * Repeated removals and removals with partially overlapping ranges are allowed.
1315
+ */
892
1316
  remove(start, end) {
893
- start = start + this.offset;
894
- end = end + this.offset;
895
- if (this.original.length !== 0) {
896
- while (start < 0) start += this.original.length;
897
- while (end < 0) end += this.original.length;
898
- }
1317
+ start = this._resolveIndex(start);
1318
+ end = this._resolveIndex(end);
899
1319
  if (start === end) return this;
900
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
901
- if (start > end) throw new Error("end must be greater than start");
1320
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1321
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
902
1322
  this._split(start);
903
1323
  this._split(end);
904
- let chunk = this.byStart[start];
1324
+ let chunk = this.byStart.get(start);
905
1325
  while (chunk) {
906
- chunk.intro = "";
907
- chunk.outro = "";
908
- chunk.edit("");
909
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1326
+ if (chunk.start > start) chunk.intro = "";
1327
+ if (chunk.end < end) chunk.outro = "";
1328
+ chunk.edit("", false, true);
1329
+ chunk.replacesUntil = -1;
1330
+ chunk.replacedFrom = -1;
1331
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
910
1332
  }
911
1333
  return this;
912
1334
  }
1335
+ /**
1336
+ * Reset the modified characters from `start` to `end` (of the original string, **not** the generated string).
1337
+ */
913
1338
  reset(start, end) {
914
- start = start + this.offset;
915
- end = end + this.offset;
916
- if (this.original.length !== 0) {
917
- while (start < 0) start += this.original.length;
918
- while (end < 0) end += this.original.length;
919
- }
1339
+ start = this._resolveIndex(start);
1340
+ end = this._resolveIndex(end);
920
1341
  if (start === end) return this;
921
- if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
922
- if (start > end) throw new Error("end must be greater than start");
1342
+ if (start < 0 || end > this.original.length) throw new MagicStringError(`range ${start}–${end} is out of bounds`);
1343
+ if (start > end) throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`);
923
1344
  this._split(start);
924
1345
  this._split(end);
925
- let chunk = this.byStart[start];
1346
+ let chunk = this.byStart.get(start);
926
1347
  while (chunk) {
927
1348
  chunk.reset();
928
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1349
+ chunk = end > chunk.end ? this.byStart.get(chunk.end) : void 0;
929
1350
  }
930
1351
  return this;
931
1352
  }
1353
+ /**
1354
+ * Returns the last character of the generated string, or `''` if it is empty.
1355
+ */
932
1356
  lastChar() {
933
1357
  if (this.outro.length) return this.outro[this.outro.length - 1];
934
1358
  let chunk = this.lastChunk;
935
- do {
1359
+ while (chunk) {
936
1360
  if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
937
1361
  if (chunk.content.length) return chunk.content[chunk.content.length - 1];
938
1362
  if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
939
- } while (chunk = chunk.previous);
1363
+ chunk = chunk.previous;
1364
+ }
940
1365
  if (this.intro.length) return this.intro[this.intro.length - 1];
941
1366
  return "";
942
1367
  }
1368
+ /**
1369
+ * Returns everything after the last newline in the generated string, or the whole string if there is no newline.
1370
+ */
943
1371
  lastLine() {
944
1372
  let lineIndex = this.outro.lastIndexOf(n);
945
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1373
+ if (lineIndex !== -1) return this.outro.slice(lineIndex + 1);
946
1374
  let lineStr = this.outro;
947
1375
  let chunk = this.lastChunk;
948
- do {
1376
+ while (chunk) {
949
1377
  if (chunk.outro.length > 0) {
950
1378
  lineIndex = chunk.outro.lastIndexOf(n);
951
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1379
+ if (lineIndex !== -1) return chunk.outro.slice(lineIndex + 1) + lineStr;
952
1380
  lineStr = chunk.outro + lineStr;
953
1381
  }
954
1382
  if (chunk.content.length > 0) {
955
1383
  lineIndex = chunk.content.lastIndexOf(n);
956
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1384
+ if (lineIndex !== -1) return chunk.content.slice(lineIndex + 1) + lineStr;
957
1385
  lineStr = chunk.content + lineStr;
958
1386
  }
959
1387
  if (chunk.intro.length > 0) {
960
1388
  lineIndex = chunk.intro.lastIndexOf(n);
961
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1389
+ if (lineIndex !== -1) return chunk.intro.slice(lineIndex + 1) + lineStr;
962
1390
  lineStr = chunk.intro + lineStr;
963
1391
  }
964
- } while (chunk = chunk.previous);
1392
+ chunk = chunk.previous;
1393
+ }
965
1394
  lineIndex = this.intro.lastIndexOf(n);
966
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1395
+ if (lineIndex !== -1) return this.intro.slice(lineIndex + 1) + lineStr;
967
1396
  return this.intro + lineStr;
968
1397
  }
1398
+ /**
1399
+ * Returns the content of the generated string that corresponds to the slice
1400
+ * between `start` and `end` of the original string, walking the generated
1401
+ * string from the chunk holding `start` to the chunk holding `end`. Throws
1402
+ * if either index falls inside replaced content. After `move()`, a range
1403
+ * whose end now comes before its start in the output yields `''`.
1404
+ */
969
1405
  slice(start = 0, end = this.original.length - this.offset) {
970
- start = start + this.offset;
971
- end = end + this.offset;
972
- if (this.original.length !== 0) {
973
- while (start < 0) start += this.original.length;
974
- while (end < 0) end += this.original.length;
975
- }
1406
+ start = this._resolveIndex(start);
1407
+ end = this._resolveIndex(end);
976
1408
  let result = "";
977
- let chunk = this.firstChunk;
978
- while (chunk && (chunk.start > start || chunk.end <= start)) {
979
- if (chunk.start < end && chunk.end >= end) return result;
980
- chunk = chunk.next;
1409
+ let chunk;
1410
+ if (this.hasMovedChunks) {
1411
+ chunk = this.firstChunk;
1412
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
1413
+ if (chunk.start < end && chunk.end >= end || end === 0 && chunk.start === 0) return result;
1414
+ chunk = chunk.next;
1415
+ }
1416
+ } else {
1417
+ if (start >= end) return result;
1418
+ chunk = this._chunkAt(start);
981
1419
  }
982
- if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1420
+ if (chunk && chunk.edited && chunk.start !== start) throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`);
983
1421
  const startChunk = chunk;
984
1422
  while (chunk) {
1423
+ if (end === 0 && chunk.start === 0) break;
985
1424
  if (chunk.intro && (startChunk !== chunk || chunk.start === start)) result += chunk.intro;
986
1425
  const containsEnd = chunk.start < end && chunk.end >= end;
987
- if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1426
+ if (containsEnd && chunk.edited && chunk.end !== end) throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`);
988
1427
  const sliceStart = startChunk === chunk ? start - chunk.start : 0;
989
1428
  const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
990
1429
  result += chunk.content.slice(sliceStart, sliceEnd);
@@ -994,37 +1433,74 @@ var MagicString = class MagicString {
994
1433
  }
995
1434
  return result;
996
1435
  }
1436
+ /**
1437
+ * Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed.
1438
+ */
997
1439
  snip(start, end) {
998
1440
  const clone = this.clone();
999
- clone.remove(0, start);
1000
- clone.remove(end, clone.original.length);
1441
+ clone.remove(-clone.offset, start);
1442
+ clone.remove(end, clone.original.length - clone.offset);
1001
1443
  return clone;
1002
1444
  }
1445
+ /**
1446
+ * Applies `offset`, resolves a negative index from the end of `original` as
1447
+ * `update`/`remove` always have, and rejects anything that is not an integer.
1448
+ * Bounds are checked by the caller, because the methods report them differently.
1449
+ *
1450
+ * @internal
1451
+ */
1452
+ _resolveIndex(index) {
1453
+ const resolved = index + this.offset;
1454
+ if (!Number.isInteger(resolved)) throw new MagicStringError(`index must be an integer, got ${index}`);
1455
+ if (resolved < 0 && this.original.length !== 0) return Math.max(0, resolved + this.original.length);
1456
+ return resolved;
1457
+ }
1458
+ /**
1459
+ * The chunk whose original range holds `index` (`chunk.start <= index < chunk.end`),
1460
+ * or `undefined` when `index` is at or past the end. Searches from the last
1461
+ * visited chunk so that scans over nearby indices stay cheap.
1462
+ *
1463
+ * @internal
1464
+ */
1465
+ _chunkAt(index) {
1466
+ let chunk = this.byStart.get(index);
1467
+ if (chunk) return chunk;
1468
+ chunk = this.lastSearchedChunk;
1469
+ const searchForward = index >= chunk.end;
1470
+ while (chunk && !chunk.contains(index)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1471
+ if (chunk) this.lastSearchedChunk = chunk;
1472
+ return chunk;
1473
+ }
1474
+ /** @internal */
1003
1475
  _split(index) {
1004
- if (this.byStart[index] || this.byEnd[index]) return;
1476
+ if (this.byStart.get(index) || this.byEnd.get(index)) return;
1005
1477
  let chunk = this.lastSearchedChunk;
1006
1478
  let previousChunk = chunk;
1007
1479
  const searchForward = index > chunk.end;
1008
1480
  while (chunk) {
1009
1481
  if (chunk.contains(index)) return this._splitChunk(chunk, index);
1010
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1482
+ chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
1011
1483
  if (chunk === previousChunk) return;
1012
1484
  previousChunk = chunk;
1013
1485
  }
1014
1486
  }
1487
+ /** @internal */
1015
1488
  _splitChunk(chunk, index) {
1016
1489
  if (chunk.edited && chunk.content.length) {
1017
1490
  const loc = getLocator(this.original)(index);
1018
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
1491
+ throw new MagicStringError(`cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
1019
1492
  }
1020
1493
  const newChunk = chunk.split(index);
1021
- this.byEnd[index] = chunk;
1022
- this.byStart[index] = newChunk;
1023
- this.byEnd[newChunk.end] = newChunk;
1494
+ this.byEnd.set(index, chunk);
1495
+ this.byStart.set(index, newChunk);
1496
+ this.byEnd.set(newChunk.end, newChunk);
1024
1497
  if (chunk === this.lastChunk) this.lastChunk = newChunk;
1025
1498
  this.lastSearchedChunk = chunk;
1026
1499
  return true;
1027
1500
  }
1501
+ /**
1502
+ * Returns the generated string.
1503
+ */
1028
1504
  toString() {
1029
1505
  let str = this.intro;
1030
1506
  let chunk = this.firstChunk;
@@ -1034,29 +1510,48 @@ var MagicString = class MagicString {
1034
1510
  }
1035
1511
  return str + this.outro;
1036
1512
  }
1513
+ /**
1514
+ * Returns true if the resulting source is empty (disregarding white space).
1515
+ */
1037
1516
  isEmpty() {
1517
+ if (this.intro.length && this.intro.trim()) return false;
1038
1518
  let chunk = this.firstChunk;
1039
- do
1519
+ while (chunk) {
1040
1520
  if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
1041
- while (chunk = chunk.next);
1521
+ chunk = chunk.next;
1522
+ }
1523
+ if (this.outro.length && this.outro.trim()) return false;
1042
1524
  return true;
1043
1525
  }
1526
+ /**
1527
+ * Returns the length of the generated string, counting only content attached to the original characters.
1528
+ * Content outside the string body (`s.prepend()`/`s.append()`, and inserts before the first or after the last
1529
+ * character) is not counted, so this can differ from `s.toString().length`.
1530
+ */
1044
1531
  length() {
1045
1532
  let chunk = this.firstChunk;
1046
1533
  let length = 0;
1047
- do
1534
+ while (chunk) {
1048
1535
  length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1049
- while (chunk = chunk.next);
1536
+ chunk = chunk.next;
1537
+ }
1050
1538
  return length;
1051
1539
  }
1540
+ /**
1541
+ * Removes empty lines from the start and end.
1542
+ */
1052
1543
  trimLines() {
1053
1544
  return this.trim("[\\r\\n]");
1054
1545
  }
1546
+ /**
1547
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end.
1548
+ */
1055
1549
  trim(charType) {
1056
1550
  return this.trimStart(charType).trimEnd(charType);
1057
1551
  }
1552
+ /** @internal */
1058
1553
  trimEndAborted(charType) {
1059
- const rx = new RegExp((charType || "\\s") + "+$");
1554
+ const rx = new RegExp(`${charType || "\\s"}+$`);
1060
1555
  this.outro = this.outro.replace(rx, "");
1061
1556
  if (this.outro.length) return true;
1062
1557
  let chunk = this.lastChunk;
@@ -1064,22 +1559,28 @@ var MagicString = class MagicString {
1064
1559
  const end = chunk.end;
1065
1560
  const aborted = chunk.trimEnd(rx);
1066
1561
  if (chunk.end !== end) {
1067
- if (this.lastChunk === chunk) this.lastChunk = chunk.next;
1068
- this.byEnd[chunk.end] = chunk;
1069
- this.byStart[chunk.next.start] = chunk.next;
1070
- this.byEnd[chunk.next.end] = chunk.next;
1562
+ const next = chunk.next;
1563
+ if (this.lastChunk === chunk) this.lastChunk = next;
1564
+ this.byEnd.set(chunk.end, chunk);
1565
+ this.byStart.set(next.start, next);
1566
+ this.byEnd.set(next.end, next);
1071
1567
  }
1072
1568
  if (aborted) return true;
1073
1569
  chunk = chunk.previous;
1074
1570
  } while (chunk);
1075
- return false;
1571
+ this.intro = this.intro.replace(rx, "");
1572
+ return this.intro.length > 0;
1076
1573
  }
1574
+ /**
1575
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end.
1576
+ */
1077
1577
  trimEnd(charType) {
1078
1578
  this.trimEndAborted(charType);
1079
1579
  return this;
1080
1580
  }
1581
+ /** @internal */
1081
1582
  trimStartAborted(charType) {
1082
- const rx = new RegExp("^" + (charType || "\\s") + "+");
1583
+ const rx = new RegExp(`^${charType || "\\s"}+`);
1083
1584
  this.intro = this.intro.replace(rx, "");
1084
1585
  if (this.intro.length) return true;
1085
1586
  let chunk = this.firstChunk;
@@ -1087,86 +1588,148 @@ var MagicString = class MagicString {
1087
1588
  const end = chunk.end;
1088
1589
  const aborted = chunk.trimStart(rx);
1089
1590
  if (chunk.end !== end) {
1090
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1091
- this.byEnd[chunk.end] = chunk;
1092
- this.byStart[chunk.next.start] = chunk.next;
1093
- this.byEnd[chunk.next.end] = chunk.next;
1591
+ const next = chunk.next;
1592
+ if (chunk === this.lastChunk) this.lastChunk = next;
1593
+ this.byEnd.set(chunk.end, chunk);
1594
+ this.byStart.set(next.start, next);
1595
+ this.byEnd.set(next.end, next);
1094
1596
  }
1095
1597
  if (aborted) return true;
1096
1598
  chunk = chunk.next;
1097
1599
  } while (chunk);
1098
- return false;
1600
+ this.outro = this.outro.replace(rx, "");
1601
+ return this.outro.length > 0;
1099
1602
  }
1603
+ /**
1604
+ * Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start.
1605
+ */
1100
1606
  trimStart(charType) {
1101
1607
  this.trimStartAborted(charType);
1102
1608
  return this;
1103
1609
  }
1610
+ /**
1611
+ * Indicates if the string has been changed.
1612
+ */
1104
1613
  hasChanged() {
1105
- return this.original !== this.toString();
1614
+ if (this.intro || this.outro) return true;
1615
+ let outputIndex = 0;
1616
+ let chunk = this.firstChunk;
1617
+ while (chunk) {
1618
+ if (chunk.intro || chunk.outro) return true;
1619
+ if (!chunk.edited && chunk.start === outputIndex) outputIndex = chunk.end;
1620
+ else {
1621
+ if (!this.original.startsWith(chunk.content, outputIndex)) return true;
1622
+ outputIndex += chunk.content.length;
1623
+ }
1624
+ chunk = chunk.next;
1625
+ }
1626
+ return outputIndex !== this.original.length;
1627
+ }
1628
+ /**
1629
+ * Whether the original range [start, end) has had any of its characters
1630
+ * removed. `replace`/`replaceAll` search `original`, so a match can land on
1631
+ * text that is no longer in the output - overwriting it would resurrect the
1632
+ * removed characters, so such matches are skipped instead.
1633
+ *
1634
+ * @internal
1635
+ */
1636
+ _hasRemovedContent(start, end) {
1637
+ const atBoundary = this.byStart.get(start);
1638
+ if (atBoundary && start === end) {
1639
+ const previous = this.byEnd.get(start);
1640
+ return !!previous && previous.content === "" && atBoundary.content === "";
1641
+ }
1642
+ let chunk = this._chunkAt(start);
1643
+ while (chunk && chunk.start < end) {
1644
+ if (chunk.content === "" && (chunk.replacedFrom < start || this.byStart.get(chunk.replacedFrom).replacesUntil < chunk.end)) return true;
1645
+ chunk = this.byStart.get(chunk.end);
1646
+ }
1647
+ return false;
1106
1648
  }
1649
+ /** @internal */
1107
1650
  _replaceRegexp(searchValue, replacement) {
1108
- function getReplacement(match, str) {
1109
- if (typeof replacement === "string") return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1110
- if (i === "$") return "$";
1111
- if (i === "&") return match[0];
1112
- if (+i < match.length) return match[+i];
1113
- return `$${i}`;
1114
- });
1115
- else return replacement(...match, match.index, str, match.groups);
1116
- }
1117
- function matchAll(re, str) {
1118
- let match;
1119
- const matches = [];
1120
- while (match = re.exec(str)) matches.push(match);
1121
- return matches;
1651
+ function getReplacement(match, index, str) {
1652
+ if (typeof replacement === "string") return expandReplacement(replacement, match[0], index, str, match.slice(1), match.groups);
1653
+ else return match.groups === void 0 ? replacement(match[0], ...match.slice(1), index, str) : replacement(match[0], ...match.slice(1), index, str, match.groups);
1122
1654
  }
1123
- if (searchValue.global) matchAll(searchValue, this.original).forEach((match) => {
1124
- if (match.index != null) {
1125
- const replacement = getReplacement(match, this.original);
1126
- if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
1127
- }
1128
- });
1129
- else {
1655
+ const replaceMatch = (match) => {
1656
+ /* v8 ignore next 2 -- `match.index` is always defined for matches from `matchAll` */
1657
+ if (match.index == null) return false;
1658
+ if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
1659
+ const replacement = getReplacement(match, match.index, this.original);
1660
+ if (replacement === match[0]) return true;
1661
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
1662
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1663
+ return true;
1664
+ };
1665
+ if (searchValue.global) {
1666
+ searchValue.lastIndex = 0;
1667
+ for (const match of this.original.matchAll(searchValue)) replaceMatch(match);
1668
+ } else {
1130
1669
  const match = this.original.match(searchValue);
1131
- if (match && match.index != null) {
1132
- const replacement = getReplacement(match, this.original);
1133
- if (replacement !== match[0]) this.overwrite(match.index, match.index + match[0].length, replacement);
1670
+ if (match && !replaceMatch(match)) {
1671
+ const global = new RegExp(searchValue.source, `${searchValue.flags}g`);
1672
+ for (const next of this.original.matchAll(global)) if (replaceMatch(next)) break;
1134
1673
  }
1135
1674
  }
1136
1675
  return this;
1137
1676
  }
1677
+ /** @internal */
1138
1678
  _replaceString(string, replacement) {
1139
1679
  const { original } = this;
1140
- const index = original.indexOf(string);
1141
- if (index !== -1) {
1680
+ let index = original.indexOf(string);
1681
+ while (index !== -1) {
1682
+ if (this._hasRemovedContent(index, index + string.length)) {
1683
+ index = original.indexOf(string, index + string.length);
1684
+ continue;
1685
+ }
1142
1686
  if (typeof replacement === "function") replacement = replacement(string, index, original);
1143
- if (string !== replacement) this.overwrite(index, index + string.length, replacement);
1687
+ else replacement = expandReplacement(replacement, string, index, original, [], void 0);
1688
+ if (string !== replacement) {
1689
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
1690
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1691
+ }
1692
+ break;
1144
1693
  }
1145
1694
  return this;
1146
1695
  }
1696
+ /**
1697
+ * String replacement with RegExp or string.
1698
+ */
1147
1699
  replace(searchValue, replacement) {
1148
1700
  if (typeof searchValue === "string") return this._replaceString(searchValue, replacement);
1149
1701
  return this._replaceRegexp(searchValue, replacement);
1150
1702
  }
1703
+ /** @internal */
1151
1704
  _replaceAllString(string, replacement) {
1152
1705
  const { original } = this;
1153
1706
  const stringLength = string.length;
1707
+ if (stringLength === 0) {
1708
+ for (let index = 0; index <= original.length; index += 1) {
1709
+ if (this._hasRemovedContent(index, index)) continue;
1710
+ const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
1711
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
1712
+ }
1713
+ return this;
1714
+ }
1154
1715
  for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
1716
+ if (this._hasRemovedContent(index, index + stringLength)) continue;
1155
1717
  const previous = original.slice(index, index + stringLength);
1156
- let _replacement = replacement;
1157
- if (typeof replacement === "function") _replacement = replacement(previous, index, original);
1158
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
1718
+ const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
1719
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1159
1720
  }
1160
1721
  return this;
1161
1722
  }
1723
+ /**
1724
+ * Same as `s.replace`, but replace all matched strings instead of just one.
1725
+ */
1162
1726
  replaceAll(searchValue, replacement) {
1163
1727
  if (typeof searchValue === "string") return this._replaceAllString(searchValue, replacement);
1164
- if (!searchValue.global) throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1728
+ if (!searchValue.global) throw new MagicStringError("replaceAll() requires a global RegExp");
1165
1729
  return this._replaceRegexp(searchValue, replacement);
1166
1730
  }
1167
1731
  };
1168
- //#endregion
1169
- //#region ../internal/dist/config-edit.js
1732
+ // ../internal/dist/config-edit.js
1170
1733
  const viteModule = "vite-hub";
1171
1734
  const nuxtModule = "vite-hub/nuxt";
1172
1735
  function fail(reason, at) {
@@ -1427,7 +1990,7 @@ function locateNuxtOptions(code, program, root, names, namespaces) {
1427
1990
  }
1428
1991
  };
1429
1992
  }
1430
- function parse$2(code) {
1993
+ function parse$3(code) {
1431
1994
  try {
1432
1995
  return parseProgram(code);
1433
1996
  } catch (error) {
@@ -1435,7 +1998,7 @@ function parse$2(code) {
1435
1998
  }
1436
1999
  }
1437
2000
  function locate(file, code) {
1438
- const program = parse$2(code);
2001
+ const program = parse$3(code);
1439
2002
  if ("ok" in program) return program;
1440
2003
  let commonjs;
1441
2004
  walk(program, (node) => {
@@ -1633,7 +2196,7 @@ function insertViteHubConfig(file, code, options) {
1633
2196
  code
1634
2197
  };
1635
2198
  if (located.reason !== "no-vitehub") return located;
1636
- const program = parse$2(code);
2199
+ const program = parse$3(code);
1637
2200
  if ("ok" in program) return program;
1638
2201
  const exported = defaultExport(program);
1639
2202
  if (!exported) return fail("no-vitehub");
@@ -1678,605 +2241,7 @@ function insertViteHubConfig(file, code, options) {
1678
2241
  code: next
1679
2242
  };
1680
2243
  }
1681
- //#endregion
1682
- //#region ../internal/dist/features.js
1683
- /**
1684
- * The feature keys of `vitehub({...})`. `vitehub add <feature>` and `vitehub status` read this list before the owner
1685
- * package of a feature is installed, so the catalog is plain data with no owner imports.
1686
- */
1687
- const featureIds = [
1688
- "agent",
1689
- "auth",
1690
- "blob",
1691
- "browser",
1692
- "cache",
1693
- "channels",
1694
- "comments",
1695
- "connections",
1696
- "console",
1697
- "database",
1698
- "email",
1699
- "env",
1700
- "i18n",
1701
- "kv",
1702
- "mcp",
1703
- "observability",
1704
- "queue",
1705
- "rateLimit",
1706
- "realtime",
1707
- "sandboxTask",
1708
- "schedule",
1709
- "workflow",
1710
- "workspace"
1711
- ];
1712
- /** `dev` stores default Node development support. Use `featureSupport()` with the configured host for development lookups. */
1713
- const featureHosts = [
1714
- "dev",
1715
- "cloudflare",
1716
- "vercel",
1717
- "netlify",
1718
- "deno",
1719
- "node"
1720
- ];
1721
- const noHostLimit = "No host limit in ViteHub.";
1722
- function native(driver, display, detail, guarantee = "native") {
1723
- return {
1724
- detail,
1725
- display,
1726
- driver,
1727
- guarantee,
1728
- level: "native"
1729
- };
1730
- }
1731
- function explicit(option, display, detail) {
1732
- return {
1733
- detail,
1734
- display,
1735
- level: "explicit",
1736
- option
1737
- };
1738
- }
1739
- function unsupported$1(detail) {
1740
- return {
1741
- detail,
1742
- level: "unsupported"
1743
- };
1744
- }
1745
- function everywhere(driver, display, detail = noHostLimit) {
1746
- const support = native(driver, display, detail);
1747
- return {
1748
- cloudflare: support,
1749
- deno: support,
1750
- dev: support,
1751
- netlify: support,
1752
- node: support,
1753
- vercel: support
1754
- };
1755
- }
1756
- function feature(definition) {
1757
- return {
1758
- devPackages: [],
1759
- enabledByDefault: false,
1760
- implies: [],
1761
- packages: [],
1762
- ...definition
1763
- };
1764
- }
1765
- const sourceExtensions = [
1766
- "ts",
1767
- "mts",
1768
- "js",
1769
- "mjs",
1770
- "cts",
1771
- "cjs"
1772
- ];
1773
- /** `<base>.<ext>` for each source extension. */
1774
- function sourceFiles(base) {
1775
- return sourceExtensions.map((extension) => `${base}.${extension}`);
1776
- }
1777
- /**
1778
- * A starter for Definitions in `dir`, one `<name>.ts` file each. With `suffix`, the owner also discovers the Vite
1779
- * form `src/<name>.<suffix>.ts`, and a Definition folder `<dir>/<name>/` when `folder` names its entry file.
1780
- */
1781
- function starter(dir, template, options = {}) {
1782
- return {
1783
- conflicts: (name) => [
1784
- ...sourceFiles(`${dir}/${name}`).slice(1),
1785
- ...options.folder ? sourceFiles(`${dir}/${name}/${options.folder}`) : [],
1786
- ...options.suffix ? [...sourceFiles(`src/${name}.${options.suffix}`), ...sourceFiles(`${name}.${options.suffix}`)] : []
1787
- ],
1788
- dir,
1789
- file: (name) => `${dir}/${name}.ts`,
1790
- template
1791
- };
1792
- }
1793
- const features = {
1794
- agent: feature({
1795
- definition: starter("server/agents", (name) => `import { defineAgent } from "vite-hub/agent"
1796
-
1797
- export default defineAgent({
1798
- driver: { run: () => ({ text: "Hello from ${name}." }) },
1799
- })
1800
- `, {
1801
- folder: "agent",
1802
- suffix: "agent"
1803
- }),
1804
- docs: "/docs/agents",
1805
- enabledByDiscovery: ["agents"],
1806
- hosts: {
1807
- ...everywhere("nitro", "Nitro"),
1808
- deno: native("nitro", "Nitro", "Agent routes run in the Nitro output. The Agent Deno runtime is not supported on this host."),
1809
- netlify: native("nitro", "Nitro", "Agent HTTP routes run in generated functions. `agent.invocations` is not supported.")
1810
- },
1811
- id: "agent",
1812
- packages: ["@vite-hub/agent"],
1813
- summary: "Agents in `server/agents/` with tools, Capabilities, channels, and invocations.",
1814
- title: "Agent"
1815
- }),
1816
- auth: feature({
1817
- docs: "/docs/auth",
1818
- enabledByDiscovery: sourceFiles("auth"),
1819
- hosts: everywhere("better-auth", "Better Auth"),
1820
- id: "auth",
1821
- packages: ["@vite-hub/auth", "better-auth"],
1822
- summary: "Better Auth sign-in, sessions, and organizations, with tables that ViteHub owns.",
1823
- title: "Auth"
1824
- }),
1825
- blob: feature({
1826
- docs: "/docs/blob",
1827
- hosts: {
1828
- cloudflare: native("cloudflare", "R2", "Cloudflare R2 binding or S3-compatible HTTP access."),
1829
- deno: explicit("blob.driver", "S3", "Use a remote S3-compatible store. No Deno-native Blob driver is provided."),
1830
- dev: native("fs", "fs", "Local filesystem storage for development.", "single-host"),
1831
- netlify: native("netlify-blobs", "Netlify Blobs", "Netlify Blobs selected from the detected host."),
1832
- node: native("fs", "fs / S3", "Filesystem, S3-compatible, MinIO, or files-sdk drivers.", "single-host"),
1833
- vercel: native("vercel", "Vercel Blob", "Vercel Blob through the vercel driver.")
1834
- },
1835
- id: "blob",
1836
- packages: ["@vite-hub/blob"],
1837
- providerPackages: { driver: { s3: [
1838
- "@aws-sdk/client-s3",
1839
- "@aws-sdk/lib-storage",
1840
- "@aws-sdk/s3-presigned-post",
1841
- "@aws-sdk/s3-request-presigner"
1842
- ] } },
1843
- service: "blob",
1844
- summary: "Object storage for files and uploads, with one API on every host.",
1845
- title: "Blob"
1846
- }),
1847
- browser: feature({
1848
- docs: "/docs/browser",
1849
- enabledByDiscovery: ["browsers"],
1850
- hosts: {
1851
- cloudflare: native("cloudflare", "Browser Run", "Cloudflare Browser Run binding and provider output."),
1852
- deno: unsupported$1("Browser Definitions do not have a Deno provider."),
1853
- dev: unsupported$1("Browser Definitions need the Cloudflare host. Use createBrowser({ driver: localBrowser({ executablePath }) }) from code for a trusted local process."),
1854
- netlify: unsupported$1("Browser Definitions do not have a Netlify provider."),
1855
- node: unsupported$1("The Node host has no built-in Browser Provider. Use localBrowser() from code for a trusted process."),
1856
- vercel: unsupported$1("Browser Definitions do not have a Vercel provider.")
1857
- },
1858
- id: "browser",
1859
- packages: ["@vite-hub/browser"],
1860
- service: "browser",
1861
- summary: "Headless browser sessions for Agents and server code.",
1862
- title: "Browser"
1863
- }),
1864
- cache: feature({
1865
- developmentOverrides: [
1866
- "cloudflare",
1867
- "deno",
1868
- "vercel"
1869
- ],
1870
- docs: "/docs/reference/config-options",
1871
- hosts: {
1872
- cloudflare: native("cloudflare", "Workers KV", "Workers KV binding `CACHE`."),
1873
- deno: native("deno-kv", "Deno KV", "Native Deno KV."),
1874
- dev: native("fs-lite", "fs-lite", "`.vitehub/data/cache` during development.", "single-host"),
1875
- netlify: explicit("cache.driver", "KV", "`cache: true` has no default store on Netlify. Set `cache: { driver: \"kv\" }` and enable `kv`."),
1876
- node: native("fs-lite", "fs-lite", "`.vitehub/data/cache` on the server disk.", "single-host"),
1877
- vercel: native("vercel", "Runtime Cache", "Vercel Runtime Cache.")
1878
- },
1879
- id: "cache",
1880
- summary: "Storage for Nitro's cache mount, used by defineCachedFunction() and defineCachedEventHandler().",
1881
- title: "Cache"
1882
- }),
1883
- channels: feature({
1884
- docs: "/docs/channels",
1885
- enabledByDiscovery: ["channels"],
1886
- hosts: everywhere("nitro", "Nitro"),
1887
- id: "channels",
1888
- packages: ["@vite-hub/channels"],
1889
- summary: "Chat channels such as Slack, Discord, and GitHub that deliver messages to Agents.",
1890
- title: "Channels"
1891
- }),
1892
- comments: feature({
1893
- docs: "/docs/comments",
1894
- enabledByDiscovery: [
1895
- "comments.ts",
1896
- "comments.mts",
1897
- "comments.js",
1898
- "comments.mjs"
1899
- ],
1900
- hosts: everywhere("database", "Database"),
1901
- id: "comments",
1902
- implies: [{ feature: "database" }],
1903
- packages: ["@vite-hub/comments"],
1904
- summary: "Comments on the app's pages, stored in a ViteHub Database.",
1905
- title: "Comments"
1906
- }),
1907
- connections: feature({
1908
- docs: "/docs/connections",
1909
- enabledByDiscovery: ["connections"],
1910
- hosts: everywhere("database", "Database"),
1911
- id: "connections",
1912
- implies: [{ feature: "database" }],
1913
- packages: [
1914
- "@vite-hub/connections",
1915
- "@vite-hub/database",
1916
- "drizzle-orm"
1917
- ],
1918
- summary: "OAuth and API key Connections in `server/connections/`, with grants stored in a Database.",
1919
- title: "Connections"
1920
- }),
1921
- console: feature({
1922
- docs: "/docs/console",
1923
- hosts: everywhere("nitro", "Nitro"),
1924
- id: "console",
1925
- packages: [],
1926
- summary: "The Operations endpoint and MCP at `/_vitehub`, which the hosted Console at console.vitehub.dev and the CLI call.",
1927
- title: "Console"
1928
- }),
1929
- database: feature({
1930
- definition: {
1931
- conflicts: (name) => [
1932
- ...sourceFiles(`server/databases/${name}`).slice(1),
1933
- ...sourceFiles(`server/databases/${name}/index`),
1934
- ...name === "default" ? ["src/database.ts"] : [...sourceFiles(`src/${name}.database`), "src/database.ts"]
1935
- ],
1936
- dir: "server/databases",
1937
- file: (name) => `server/databases/${name}.ts`,
1938
- template: (name) => `import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
1939
- import { defineDatabase } from "vite-hub/database"
1940
-
1941
- export default defineDatabase({
1942
- ${name === "default" ? "" : ` name: ${JSON.stringify(name)},\n`} schema: {
1943
- notes: sqliteTable("notes", {
1944
- id: integer("id").primaryKey(),
1945
- title: text("title").notNull(),
1946
- }),
1947
- },
1948
- })
1949
- `
1950
- },
1951
- developmentOverrides: [
1952
- "deno",
1953
- "netlify",
1954
- "vercel"
1955
- ],
1956
- devPackages: ["drizzle-kit"],
1957
- docs: "/docs/database",
1958
- hosts: {
1959
- cloudflare: native("cloudflare", "D1", "Cloudflare D1 binding, with authenticated HTTP available for development. A PostgreSQL Database Definition connects through Hyperdrive or `connection.url`."),
1960
- deno: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Deno-native database driver is provided."),
1961
- dev: native("sqlite", "SQLite", "Local SQLite through libSQL and Drizzle.", "single-host"),
1962
- netlify: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. No Netlify-native database driver is provided."),
1963
- node: native("sqlite", "SQLite / libSQL / Postgres", "SQLite or hosted libSQL through the selected Database connection, or a PostgreSQL Database Definition.", "single-host"),
1964
- vercel: explicit("database.connection", "libSQL / D1 / Postgres", "Configure hosted libSQL, D1 over authenticated HTTP, or a PostgreSQL Database Definition. The default local SQLite file is not supported in Vercel functions.")
1965
- },
1966
- id: "database",
1967
- packages: ["@vite-hub/database", "drizzle-orm"],
1968
- summary: "Drizzle Databases in `server/databases/` with migrations and a local SQLite in development.",
1969
- title: "Database"
1970
- }),
1971
- email: feature({
1972
- docs: "/docs/email",
1973
- hosts: {
1974
- cloudflare: native("cloudflare", "Cloudflare Email", "The Cloudflare Email driver is the default. Resend is also supported."),
1975
- deno: explicit("email.driver", "Resend", "Configure the built-in fetch-based Resend driver."),
1976
- dev: native("log", "Log", "`email: true` keeps each message in the development outbox and sends nothing. Set `email.driver` for a production build.", "process-local"),
1977
- netlify: explicit("email.driver", "Resend", "Configure the built-in Resend driver."),
1978
- node: explicit("email.driver", "Resend / custom", "Configure Resend or provide a custom ViteHub Email driver."),
1979
- vercel: explicit("email.driver", "Resend", "Configure the built-in Resend driver.")
1980
- },
1981
- developmentOverrides: [
1982
- "deno",
1983
- "netlify",
1984
- "vercel"
1985
- ],
1986
- id: "email",
1987
- packages: ["@vite-hub/email"],
1988
- summary: "Send email from server code and Agents, with a development outbox.",
1989
- title: "Email"
1990
- }),
1991
- env: feature({
1992
- docs: "/docs/env",
1993
- enabledByDefault: true,
1994
- hosts: everywhere("nitro", "Nitro"),
1995
- id: "env",
1996
- summary: "Typed environment variables and secrets, validated at build and at runtime.",
1997
- title: "Env"
1998
- }),
1999
- i18n: feature({
2000
- docs: "/docs/i18n",
2001
- hosts: everywhere("nitro", "Nitro 3", "Requires Nitro 3 with request async context, or Nuxt 5. Nuxt 4 and Nitro 2 are unsupported."),
2002
- id: "i18n",
2003
- packages: ["@vite-hub/i18n"],
2004
- summary: "Messages with translation records for each locale and a locale for each request.",
2005
- title: "I18n"
2006
- }),
2007
- kv: feature({
2008
- developmentOverrides: ["netlify"],
2009
- docs: "/docs/kv",
2010
- hosts: {
2011
- cloudflare: native("cloudflare", "Workers KV", "Cloudflare Workers KV binding."),
2012
- deno: native("deno-kv", "Deno KV", "Native Deno KV through Deno.openKv()."),
2013
- dev: native("fs-lite", "fs-lite", "Local filesystem-backed KV for development.", "single-host"),
2014
- netlify: explicit("kv.driver", "Upstash / Redis", "Set `kv.driver` to `upstash`, `redis`, or `database`, or set Upstash REST credentials at build time. No Netlify-native KV output is provided. Without them, KV uses a Postgres Default Database, else `fs-lite` files that other function instances cannot read."),
2015
- node: native("fs-lite", "Redis / Postgres / fs-lite", "A table in a Postgres Default Database, else local files. Redis requires kv: { driver: 'redis' }; REDIS_URL supplies its URL on every server. Upstash with REST credentials at build time.", "single-host"),
2016
- vercel: native("upstash", "Upstash", "Upstash Redis with KV REST credentials.")
2017
- },
2018
- id: "kv",
2019
- packages: ["@vite-hub/kv"],
2020
- summary: "Key-value storage with one API on every host.",
2021
- title: "KV"
2022
- }),
2023
- mcp: feature({
2024
- docs: "/docs/mcp",
2025
- hosts: everywhere("nitro", "Nitro"),
2026
- id: "mcp",
2027
- packages: ["@vite-hub/mcp"],
2028
- summary: "The app's own MCP server, with one tool per file in `server/mcp/tools/`.",
2029
- title: "MCP server"
2030
- }),
2031
- observability: feature({
2032
- docs: "/docs/agents/observability",
2033
- hosts: everywhere("evlog", "Evlog"),
2034
- id: "observability",
2035
- packages: ["evlog"],
2036
- summary: "Request logs through Evlog, the logs that the Console reads, and Agent telemetry with a service name.",
2037
- title: "Observability"
2038
- }),
2039
- queue: feature({
2040
- definition: starter("server/queues", (name) => `import { defineQueue } from "vite-hub/queue"
2041
-
2042
- export default defineQueue<{ id: string }>({
2043
- handler: async ({ payload }) => {
2044
- console.log("${name}", payload.id)
2045
- },
2046
- })
2047
- `, { suffix: "queue" }),
2048
- docs: "/docs/queue",
2049
- enabledByDiscovery: ["queues"],
2050
- hosts: {
2051
- cloudflare: native("cloudflare", "Queues", "Cloudflare Queues bindings and consumers."),
2052
- deno: unsupported$1("No Deno Queue driver is provided."),
2053
- dev: native("local", "Local driver", "The local driver stores jobs in .vitehub/data/queue and runs them in the dev server process.", "single-host"),
2054
- netlify: unsupported$1("Netlify has no Queue driver, so `vitehub({ queue })` fails on Netlify."),
2055
- node: native("local", "Postgres / local driver", "With a Postgres Default Database, the postgres driver keeps jobs in Postgres and every instance runs them. Else the local driver keeps jobs on the disk of one host.", "single-host"),
2056
- vercel: native("vercel", "Vercel Queues", "Vercel Queues callbacks and runtime client.")
2057
- },
2058
- id: "queue",
2059
- packages: ["@vite-hub/queue"],
2060
- providerPackages: { driver: { postgres: ["postgres"] } },
2061
- service: "queue",
2062
- summary: "Background jobs in `server/queues/` with retries and delivery on every supported host.",
2063
- title: "Queue"
2064
- }),
2065
- rateLimit: feature({
2066
- developmentOverrides: ["cloudflare"],
2067
- docs: "/docs/rate-limit",
2068
- hosts: {
2069
- cloudflare: native("cloudflare", "Cloudflare", "Native Cloudflare Rate Limiting binding."),
2070
- deno: unsupported$1("ViteHub has no native Deno Rate Limit driver."),
2071
- dev: native("memory", "memory", "Process-local memory driver for development and tests.", "process-local"),
2072
- netlify: unsupported$1("ViteHub has no native Netlify Rate Limit driver."),
2073
- node: native("memory", "memory, or KV", "Without KV, each process counts alone. With KV on, ViteHub selects the kv provider, which shares the counts when KV uses Redis or a Postgres Database.", "process-local"),
2074
- vercel: unsupported$1("ViteHub has no native Vercel Rate Limit driver.")
2075
- },
2076
- id: "rateLimit",
2077
- packages: ["@vite-hub/rate-limit"],
2078
- service: "rateLimit",
2079
- summary: "Rate limits in `server/rate-limits/` that protect routes and Agent tools.",
2080
- title: "Rate Limit"
2081
- }),
2082
- realtime: feature({
2083
- definition: starter("server/realtime", (name) => `import { defineRealtime } from "vite-hub/realtime"
2084
-
2085
- export default defineRealtime({
2086
- authorize: true,
2087
- document: { workspace: "${name}" },
2088
- })
2089
- `),
2090
- developmentOverrides: [
2091
- "cloudflare",
2092
- "deno",
2093
- "netlify",
2094
- "vercel"
2095
- ],
2096
- docs: "/docs/realtime",
2097
- enabledByDiscovery: ["realtime"],
2098
- hosts: {
2099
- cloudflare: native("cloudflare", "Durable Objects", "Cloudflare Durable Objects run the production rooms."),
2100
- deno: unsupported$1("Realtime has no distributed Deno driver, and process memory is rejected for the Deno host."),
2101
- dev: native("memory", "memory", "Process-memory driver for local development.", "process-local"),
2102
- netlify: unsupported$1("Realtime has no distributed Netlify driver, and process memory is rejected for the Netlify host."),
2103
- node: native("node", "Postgres or Redis", "Each instance keeps its rooms in memory and shares them through Redis with REDIS_URL, else Postgres on a Postgres Default Database. Without either, rooms stay in one process."),
2104
- vercel: unsupported$1("Realtime has no distributed Vercel driver, and process memory is rejected for the Vercel host.")
2105
- },
2106
- id: "realtime",
2107
- packages: ["@vite-hub/realtime"],
2108
- service: "realtime",
2109
- summary: "Shared rooms with presence and Yjs documents.",
2110
- title: "Realtime"
2111
- }),
2112
- sandboxTask: feature({
2113
- docs: "/docs/sandbox",
2114
- hosts: {
2115
- cloudflare: native("cloudflare", "CF Sandbox", "Cloudflare Sandbox execution provider."),
2116
- deno: unsupported$1("No Deno Sandbox driver is provided."),
2117
- dev: unsupported$1("The default Node host has no Sandbox Provider. With the Cloudflare or Vercel host, `vite dev` runs each Sandbox Task as a process on this machine, with no isolation and no provider account. `sandboxTask: { remote: true }` uses the host's Sandbox instead."),
2118
- netlify: explicit("sandboxTask.driver", "Vercel Sandbox", "The Netlify host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
2119
- node: explicit("sandboxTask.driver", "Vercel Sandbox", "The Node host has no Sandbox, so `sandboxTask: true` fails. Set `sandboxTask: { driver: \"vercel\" }` and Vercel credentials to use Vercel Sandbox."),
2120
- vercel: native("vercel", "Vercel Sandbox", "Vercel Sandbox execution provider.")
2121
- },
2122
- id: "sandboxTask",
2123
- packages: ["@vite-hub/sandbox"],
2124
- service: "sandbox",
2125
- summary: "Sandbox Tasks in `server/sandbox-tasks/`. Each run starts an isolated Cloudflare or Vercel Sandbox.",
2126
- title: "Sandbox"
2127
- }),
2128
- schedule: feature({
2129
- definition: starter("server/schedules", (name) => `import { defineSchedule } from "vite-hub/schedule"
2130
-
2131
- export default defineSchedule({
2132
- cron: "0 * * * *",
2133
- handler: () => {
2134
- console.log("${name}")
2135
- },
2136
- })
2137
- `, { suffix: "schedule" }),
2138
- developmentOverrides: [
2139
- "cloudflare",
2140
- "netlify",
2141
- "vercel"
2142
- ],
2143
- docs: "/docs/schedule",
2144
- enabledByDiscovery: ["schedules"],
2145
- hosts: {
2146
- cloudflare: native("cloudflare", "Cron triggers", "Cloudflare scheduled events and Nitro Provider Wake."),
2147
- deno: native("deno", "Deno.cron", "`Deno.cron` output that the generated `.output/main.ts` loads before the Nitro server."),
2148
- dev: native("local", "Local / process", "Local development runner and the explicit process runtime.", "single-host"),
2149
- netlify: native("netlify", "Scheduled fn", "One generated Netlify scheduled function per static Schedule."),
2150
- node: native("process", "process", "Process runtime for one long-lived process or replica. `schedule: true` uses it. Set `providerOutput: false` to wake Schedules yourself.", "single-host"),
2151
- vercel: native("vercel", "Vercel Cron", "Vercel Cron Jobs provider output.")
2152
- },
2153
- id: "schedule",
2154
- packages: ["@vite-hub/schedule"],
2155
- summary: "Cron Schedules in `server/schedules/` that run on the host's scheduler.",
2156
- title: "Schedule"
2157
- }),
2158
- workflow: feature({
2159
- definition: starter("server/workflows", () => `import { defineWorkflow } from "vite-hub/workflow"
2160
-
2161
- export default defineWorkflow<{ id: string }>({
2162
- handler: async ({ payload }) => {
2163
- return { id: payload.id }
2164
- },
2165
- })
2166
- `, {
2167
- folder: "index",
2168
- suffix: "workflow"
2169
- }),
2170
- docs: "/docs/workflows",
2171
- enabledByDiscovery: ["workflows"],
2172
- hosts: {
2173
- cloudflare: native("cloudflare", "CF Workflows", "Cloudflare Workflows provider."),
2174
- deno: explicit("workflow.driver", "OpenWorkflow", "Set `workflow.driver` to \"openworkflow\" with `workflow.postgres.url`, and start its worker. A build without a driver fails."),
2175
- dev: native("openworkflow", "OpenWorkflow", "The Node host runs OpenWorkflow and its worker in the dev server, on .vitehub/data/openworkflow.sqlite.db. workflow.remote lets it use the Postgres Default Database or OPENWORKFLOW_POSTGRES_URL."),
2176
- netlify: explicit("workflow.driver", "OpenWorkflow", "Use OpenWorkflow explicitly. No Netlify-native Workflow driver is provided."),
2177
- node: {
2178
- ...native("openworkflow", "OpenWorkflow", "OpenWorkflow is the default, and each server runs its worker. It uses OPENWORKFLOW_POSTGRES_URL or the Postgres Default Database. Without them, runs use a SQLite file on one host.", "single-host"),
2179
- envOverrides: ["OPENWORKFLOW_POSTGRES_URL"].map((env) => ({
2180
- env,
2181
- support: native("openworkflow", "OpenWorkflow (Postgres)", `${env} selects Postgres. Several servers can run the worker on the same database, and each run executes once.`)
2182
- }))
2183
- },
2184
- vercel: native("vercel", "Vercel Workflow", "Vercel Workflow provider and Workflow DevKit output.")
2185
- },
2186
- id: "workflow",
2187
- packages: ["@vite-hub/workflow"],
2188
- summary: "Durable Workflows in `server/workflows/` with steps and driver retries.",
2189
- title: "Workflow"
2190
- }),
2191
- workspace: feature({
2192
- developmentOverrides: [
2193
- "cloudflare",
2194
- "deno",
2195
- "netlify",
2196
- "vercel"
2197
- ],
2198
- docs: "/docs/workspace",
2199
- enabledByDiscovery: ["workspaces"],
2200
- hosts: {
2201
- cloudflare: native("memory", "Artifacts / GitHub", "Memory by default, or Cloudflare Artifacts beta and GitHub for durable state.", "process-local"),
2202
- deno: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
2203
- dev: native("local", "local / memory", "Local filesystem or in-memory Workspace Store.", "single-host"),
2204
- netlify: explicit("workspace.store", "GitHub", "Select the GitHub Workspace Store explicitly for durable state."),
2205
- node: native("local", "local / GitHub", "Local filesystem, memory, or GitHub Workspace Store.", "single-host"),
2206
- vercel: {
2207
- ...native("memory", "memory / Blob / GitHub", "Process-local memory by default. BLOB_READ_WRITE_TOKEN selects Vercel Blob; GitHub can be selected explicitly for durable state.", "process-local"),
2208
- envOverrides: [{
2209
- env: "BLOB_READ_WRITE_TOKEN",
2210
- support: native("vercel", "Blob / GitHub", "BLOB_READ_WRITE_TOKEN selects durable Vercel Blob storage by default.")
2211
- }]
2212
- }
2213
- },
2214
- id: "workspace",
2215
- packages: ["@vite-hub/workspace"],
2216
- summary: "File workspaces that Agents read and edit, backed by local, Blob, or GitHub stores.",
2217
- title: "Workspace"
2218
- })
2219
- };
2220
- /** Packages needed by a feature, its provider, and its enabled feature integrations. */
2221
- function featurePackages(id, value, host, enabled = []) {
2222
- const definition = features[id];
2223
- const options = value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2224
- const stores = options?.stores;
2225
- const selected = (id === "blob" && stores && typeof stores === "object" && !Array.isArray(stores) ? [value, ...Object.values(stores)] : [value]).flatMap((value) => Object.entries(definition.providerPackages ?? {}).flatMap(([key, choices]) => {
2226
- const choice = value && typeof value === "object" && !Array.isArray(value) ? Reflect.get(value, key) : void 0;
2227
- return typeof choice === "string" ? choices[choice] ?? [] : [];
2228
- }));
2229
- if (id === "observability" && typeof options?.service === "string") selected.push("@vite-hub/agent");
2230
- if (id === "observability" && options?.posthog) selected.push("posthog-node");
2231
- const sandboxDriver = typeof options?.driver === "string" ? options.driver : host;
2232
- if (id === "sandboxTask" && (sandboxDriver === "vercel" || sandboxDriver === "cloudflare")) selected.push(sandboxDriverPackages[sandboxDriver]);
2233
- if ((id === "queue" || id === "workflow") && host === "vercel" && (options?.driver ?? "vercel") === "vercel") selected.push(...vercelProviderPackages[id]);
2234
- if (id === "console" && enabled.includes("agent")) selected.push(...consoleFeaturePackages.agents);
2235
- return [.../* @__PURE__ */ new Set([...definition.packages, ...selected])];
2236
- }
2237
- const sandboxDriverPackages = {
2238
- cloudflare: "@cloudflare/sandbox",
2239
- vercel: "@vercel/sandbox"
2240
- };
2241
- /**
2242
- * The SDKs of the Vercel provider. Native Vercel Workflows also need `workflow` and `@workflow/builders`, but only
2243
- * `@vite-hub/workflow` knows when a Workflow is native, so it checks those two itself.
2244
- */
2245
- const vercelProviderPackages = {
2246
- queue: ["@vercel/queue", "@vercel/functions"],
2247
- workflow: ["@vercel/functions"]
2248
- };
2249
- /** Additional Console owners selected by its enabled Agent integration. */
2250
- const consoleFeaturePackages = { agents: ["@libsql/client", "drizzle-orm"] };
2251
- function featureSupport(id, host, appHost) {
2252
- const definition = features[id];
2253
- if (host !== "dev") return definition.hosts[host];
2254
- invariant(appHost, "every caller of featureSupport() for the dev host passes the configured ViteHub host");
2255
- if (id === "workflow" && appHost === "deno") return native("vercel", "Inline", "Development runs each Workflow inline unless OpenWorkflow storage or a provider is configured.", "process-local");
2256
- return definition.hosts[appHost === "node" || definition.developmentOverrides?.includes(appHost) ? "dev" : appHost];
2257
- }
2258
- /**
2259
- * The features that `enabled` turn on through implications, without the ones already in `enabled`.
2260
- * This follows implications transitively.
2261
- * `disabled` lists features that the app sets to `false`; an implication never turns them on.
2262
- */
2263
- function impliedFeatures(enabled, disabled = []) {
2264
- const on = new Set(enabled);
2265
- const implied = [];
2266
- const pending = [...enabled];
2267
- while (pending.length) {
2268
- const id = pending.shift();
2269
- for (const implication of features[id].implies) {
2270
- if (on.has(implication.feature) || disabled.includes(implication.feature)) continue;
2271
- on.add(implication.feature);
2272
- implied.push(implication.feature);
2273
- pending.push(implication.feature);
2274
- }
2275
- }
2276
- return implied;
2277
- }
2278
- //#endregion
2279
- //#region src/setup/project.ts
2244
+ // src/setup/project.ts
2280
2245
  const nuxtConfigFiles = [
2281
2246
  "nuxt.config.ts",
2282
2247
  "nuxt.config.mts",
@@ -2341,21 +2306,57 @@ function detectPackageManager(root, manifest, env) {
2341
2306
  packageManagerSource: "default"
2342
2307
  };
2343
2308
  }
2344
- function nuxtServerDirs(root, config) {
2309
+ const nuxtLayerKeys = [
2310
+ "extends",
2311
+ "_extends",
2312
+ "theme",
2313
+ "_layers"
2314
+ ];
2315
+ function nuxtDirectoryOverride(value) {
2316
+ return value !== null && typeof value === "object" && [
2317
+ "rootDir",
2318
+ "serverDir",
2319
+ ...nuxtLayerKeys
2320
+ ].some((key) => Object.hasOwn(value, key));
2321
+ }
2322
+ async function nuxtRcAllowsStaticDiscovery(folder) {
2323
+ const file = join(folder, ".nuxtrc");
2324
+ try {
2325
+ if (!(await stat(file)).isFile()) return false;
2326
+ return !nuxtDirectoryOverride(parse$2(await readFile(file, "utf8")));
2327
+ } catch (error) {
2328
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
2329
+ }
2330
+ }
2331
+ async function nuxtServerDirs(root, config, env) {
2345
2332
  const nuxt = config?.ok ? config.site.nuxt : void 0;
2346
2333
  if (!nuxt || nuxt.spread) return;
2347
- const extended = nuxt.keys.extends;
2348
- if (extended && !(extended.kind === "literal" && Array.isArray(extended.value) && extended.value.length === 0)) return;
2349
- if (nuxt.keys._layers || nuxt.keys.srcDir || existsSync(join(root, "layers"))) return;
2334
+ for (const key of nuxtLayerKeys) {
2335
+ const layer = nuxt.keys[key];
2336
+ if (layer && !(layer.kind === "literal" && Array.isArray(layer.value) && layer.value.length === 0)) return;
2337
+ }
2338
+ for (const [key, override] of Object.entries(nuxt.keys)) {
2339
+ if (!key.startsWith("$") || key === "$meta") continue;
2340
+ if (override.kind === "expression") return;
2341
+ if (key === "$env") {
2342
+ if (override.value !== null && typeof override.value === "object" && Object.values(override.value).some(nuxtDirectoryOverride)) return;
2343
+ } else if (nuxtDirectoryOverride(override.value)) return;
2344
+ }
2345
+ if (existsSync(join(root, "layers"))) return;
2350
2346
  const rootDir = nuxt.keys.rootDir;
2351
2347
  const serverDir = nuxt.keys.serverDir;
2352
2348
  if (rootDir && (rootDir.kind !== "literal" || typeof rootDir.value !== "string")) return;
2353
2349
  if (serverDir && (serverDir.kind !== "literal" || typeof serverDir.value !== "string")) return;
2354
2350
  const appRoot = rootDir?.kind === "literal" && typeof rootDir.value === "string" ? resolve(root, rootDir.value) : root;
2355
2351
  if (existsSync(join(appRoot, "layers"))) return;
2352
+ const home = homedir();
2353
+ for (const folder of /* @__PURE__ */ new Set([
2354
+ ...parentFolders(root),
2355
+ home,
2356
+ env.XDG_CONFIG_HOME || join(home, ".config")
2357
+ ])) if (!await nuxtRcAllowsStaticDiscovery(folder)) return;
2356
2358
  return [resolve(appRoot, serverDir?.kind === "literal" && typeof serverDir.value === "string" ? serverDir.value || "server" : "server")];
2357
2359
  }
2358
- /** The real folders of `name` in NODE_PATH, which Node's resolver reads after every node_modules folder. */
2359
2360
  function globalPackageDirs(name) {
2360
2361
  return (process$1.env.NODE_PATH ?? "").split(delimiter).filter(Boolean).flatMap((dir) => {
2361
2362
  try {
@@ -2408,11 +2409,10 @@ async function readSetupProject(root, env) {
2408
2409
  },
2409
2410
  ...detectPackageManager(root, manifest, env),
2410
2411
  root,
2411
- serverDirs: framework === "nuxt" ? nuxtServerDirs(root, config) : [join(root, "server")]
2412
+ serverDirs: framework === "nuxt" ? await nuxtServerDirs(root, config, env) : [join(root, "server")]
2412
2413
  };
2413
2414
  }
2414
- //#endregion
2415
- //#region ../internal/dist/definition-catalog.js
2415
+ // ../internal/dist/definition-catalog.js
2416
2416
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
2417
2417
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
2418
2418
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
@@ -2468,8 +2468,7 @@ function hasDefinitionFiles(path) {
2468
2468
  if (!existsSync(path)) return false;
2469
2469
  return statSync(path).isFile() || listSourceFiles(path).length > 0;
2470
2470
  }
2471
- //#endregion
2472
- //#region ../internal/dist/deployment.js
2471
+ // ../internal/dist/deployment.js
2473
2472
  const unsupported = (reason) => ({
2474
2473
  reason,
2475
2474
  supported: false
@@ -2540,7 +2539,7 @@ const plans = {
2540
2539
  nitroPreset: "netlify",
2541
2540
  output: {
2542
2541
  directory: ".netlify",
2543
- entry: "functions-internal/server/server.mjs",
2542
+ entry: "v1/functions/server/server.mjs",
2544
2543
  packaging: "none"
2545
2544
  },
2546
2545
  runtime: "node",
@@ -2663,8 +2662,7 @@ function detectHost(env = process.env) {
2663
2662
  }
2664
2663
  return providerHosts.find(([name]) => env[name]?.trim())?.[1];
2665
2664
  }
2666
- //#endregion
2667
- //#region src/setup/status.ts
2665
+ // src/setup/status.ts
2668
2666
  const addArgs = {
2669
2667
  bun: {
2670
2668
  dev: ["add", "-d"],
@@ -2683,6 +2681,10 @@ const addArgs = {
2683
2681
  prod: ["add"]
2684
2682
  }
2685
2683
  };
2684
+ /** Quotes `value` for a POSIX shell when it needs quotes. */
2685
+ function shellQuote(value) {
2686
+ return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
2687
+ }
2686
2688
  /** The arguments of the `packageManager` command that installs `packages`, such as `["add", "-D", "drizzle-kit"]`. */
2687
2689
  function installArgs(packageManager, packages, dev) {
2688
2690
  return [...addArgs[packageManager][dev ? "dev" : "prod"], ...packages];
@@ -2697,9 +2699,11 @@ const removeArgs = {
2697
2699
  function uninstallArgs(packageManager, packages) {
2698
2700
  return [...removeArgs[packageManager], ...packages];
2699
2701
  }
2700
- /** The shell command that installs `prod` and then `dev`, such as `pnpm add kv && pnpm add -D drizzle-kit`. */
2702
+ function formatInstallCommand(command, args) {
2703
+ return [command, ...args].map(formatInstallArgument).join(" ");
2704
+ }
2701
2705
  function installCommand(packageManager, prod, dev) {
2702
- const commands = [...prod.length ? [[packageManager, ...installArgs(packageManager, prod, false)].join(" ")] : [], ...dev.length ? [[packageManager, ...installArgs(packageManager, dev, true)].join(" ")] : []];
2706
+ const commands = [...prod.length ? [formatInstallCommand(packageManager, installArgs(packageManager, prod, false))] : [], ...dev.length ? [formatInstallCommand(packageManager, installArgs(packageManager, dev, true))] : []];
2703
2707
  return commands.length ? commands.join(" && ") : void 0;
2704
2708
  }
2705
2709
  function readHost(project, env) {
@@ -2770,21 +2774,32 @@ function readEnabled(project, id, withoutDefinitions) {
2770
2774
  reason: "default"
2771
2775
  };
2772
2776
  }
2773
- /** True when the config sets `option`, such as `blob.driver`, as a literal key of the feature object. */
2774
- function setsOption(project, option) {
2775
- const config = project.config;
2776
- if (!config?.ok) return false;
2777
+ const kvDefaultStoreOption = "kv.stores.default.driver";
2778
+ function kvStores(value) {
2779
+ return isRecord(value) && isRecord(value.stores) ? value.stores : void 0;
2780
+ }
2781
+ function missingProviderOption(project, option, value) {
2777
2782
  const [id, key] = option.split(".");
2778
- const value = config.site.keys[id];
2779
- if (value?.kind === "expression") return true;
2780
- const options = value?.value;
2781
- return !!options && typeof options === "object" && !Array.isArray(options) && key in options;
2783
+ const configured = project.config?.ok ? project.config.site.keys[id] : void 0;
2784
+ if (configured?.kind === "expression") return;
2785
+ const options = value ?? configured?.value;
2786
+ const stores = option === "kv.driver" ? kvStores(options) : void 0;
2787
+ if (stores) {
2788
+ const store = stores.default;
2789
+ const driver = isRecord(store) ? store.driver : void 0;
2790
+ if (driver !== "upstash" && driver !== "redis" && driver !== "database") return kvDefaultStoreOption;
2791
+ return;
2792
+ }
2793
+ if (!isRecord(options) || !(key in options)) return option;
2782
2794
  }
2783
2795
  function featureFix(project, id, support, host, missing, providerChosen) {
2784
- const install = installCommand(project.packageManager, missing.prod, missing.dev);
2796
+ const install = installCommand(project.packageManager, missing.prod.map(installSpecifier), missing.dev.map(installSpecifier));
2785
2797
  if (install) return install;
2786
2798
  if (support.level === "unsupported") return `Set \`${id}: false\`, or build for another host than ${host}.`;
2787
- if (support.level === "explicit" && !providerChosen && !setsOption(project, support.option)) return `Set \`${support.option}\` in vitehub() to choose a provider on ${host}.`;
2799
+ if (support.level === "explicit" && !providerChosen) {
2800
+ const option = missingProviderOption(project, support.option);
2801
+ if (option) return `Set \`${option}\` in vitehub() to choose a provider on ${host}.`;
2802
+ }
2788
2803
  }
2789
2804
  /** What the project enables, on which host, and what each enabled feature still needs. Reads the config without running it. */
2790
2805
  function setupStatus(project, env, withoutDefinitions) {
@@ -2819,7 +2834,8 @@ function setupStatus(project, env, withoutDefinitions) {
2819
2834
  } : featureSupport(id, host.name);
2820
2835
  const definition = features[id];
2821
2836
  const value = project.config?.ok ? project.config.site.keys[id] : void 0;
2822
- const packages = featurePackages(id, value?.kind === "literal" ? value.value : void 0, host.name, featureIds.filter((feature) => enabled.get(feature)?.enabled === "on"));
2837
+ const literal = value?.kind === "literal" ? value.value : void 0;
2838
+ const packages = featurePackages(id, literal, host.name, featureIds.filter((feature) => enabled.get(feature)?.enabled === "on"));
2823
2839
  const missing = state.enabled === "on" ? {
2824
2840
  dev: definition.devPackages.filter((name) => !project.installed(name)),
2825
2841
  prod: packages.filter((name) => !project.installed(name))
@@ -2829,11 +2845,15 @@ function setupStatus(project, env, withoutDefinitions) {
2829
2845
  };
2830
2846
  const providerChosen = id === "workflow" && host.name !== "netlify" && packages.includes("openworkflow");
2831
2847
  const fix = state.enabled === "on" ? featureFix(project, id, support, host.name, missing, providerChosen) : void 0;
2848
+ const resolvedSupport = support.level === "explicit" && support.option === "kv.driver" && kvStores(literal) ? {
2849
+ ...support,
2850
+ option: kvDefaultStoreOption
2851
+ } : support;
2832
2852
  return {
2833
2853
  id,
2834
2854
  ...state,
2835
2855
  missingPackages: [...missing.prod, ...missing.dev],
2836
- support,
2856
+ support: resolvedSupport,
2837
2857
  ...fix ? { fix } : {}
2838
2858
  };
2839
2859
  }),
@@ -2844,8 +2864,7 @@ function setupStatus(project, env, withoutDefinitions) {
2844
2864
  schemaVersion: 1
2845
2865
  };
2846
2866
  }
2847
- //#endregion
2848
- //#region src/setup/deploy/host.ts
2867
+ // src/setup/deploy/host.ts
2849
2868
  /** A failed host CLI that may print values on stdout, such as `vercel env ls --json`: only stderr goes into the reason. */
2850
2869
  function hostListFailed(step, result, secrets) {
2851
2870
  return hostCliFailed(step, {
@@ -3033,13 +3052,14 @@ function createDeployRun(stderr, secrets) {
3033
3052
  options.signal?.addEventListener("abort", abort, { once: true });
3034
3053
  if (options.timeoutMs) timeout = setTimeout(stop, options.timeoutMs);
3035
3054
  if (options.signal?.aborted) abort();
3036
- child.stdin?.on("error", () => {});
3055
+ child.stdin?.on("error", (error) => {
3056
+ if (!(error.code === "EPIPE" || stopping && error.code === "ERR_STREAM_DESTROYED")) failure ??= error;
3057
+ });
3037
3058
  child.stdin?.end(options.stdin ?? "");
3038
3059
  });
3039
3060
  }
3040
3061
  };
3041
3062
  }
3042
- /** Resolve npm/pnpm Windows shims to Node entrypoints without evaluating any batch or shell syntax. */
3043
3063
  function windowsNodeEntry(file) {
3044
3064
  if (/\.(?:exe|cmd|bat)$/iu.test(file)) return;
3045
3065
  if (!existsSync(file)) return;
@@ -3198,8 +3218,7 @@ async function readDeployCommit(run, root, env) {
3198
3218
  return;
3199
3219
  }
3200
3220
  }
3201
- //#endregion
3202
- //#region src/setup/build-output.ts
3221
+ // src/setup/build-output.ts
3203
3222
  /** Runs the build script for `host`. VITEHUB_HOST_SOURCE=cli makes `host` win over a `host` literal in vitehub(). */
3204
3223
  async function build(project, host, context) {
3205
3224
  const command = `${project.packageManager} run build`;
@@ -3223,7 +3242,6 @@ async function build(project, host, context) {
3223
3242
  function stringList(value) {
3224
3243
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
3225
3244
  }
3226
- /** One entry of `env` in `deployment.json`. Only names: the build never writes a value there. */
3227
3245
  function readEnvEntry(value) {
3228
3246
  if (!isRecord(value)) return [];
3229
3247
  const names = stringList(value.names);
@@ -3241,7 +3259,6 @@ function readEnvEntry(value) {
3241
3259
  ...owners.length ? { owners } : {}
3242
3260
  }];
3243
3261
  }
3244
- /** `deploy` of `deployment.json`. Only paths that start with one `/` and a key that IndexNow accepts. */
3245
3262
  function readDeploy(value) {
3246
3263
  if (!isRecord(value)) return { check: [] };
3247
3264
  const check = stringList(value.check).filter((path) => path.startsWith("/") && !path.startsWith("//"));
@@ -3283,17 +3300,9 @@ async function readBuildOutput(root, host) {
3283
3300
  ...identityName ? { identityName } : {}
3284
3301
  };
3285
3302
  }
3286
- //#endregion
3287
- //#region src/setup/deploy/cloudflare.ts
3288
- /** The flags that ViteHub's own build writes into `commands.deploy` (`packages/vite-hub/src/plugins.ts`). */
3303
+ // src/setup/deploy/cloudflare.ts
3289
3304
  const valueFlags = /* @__PURE__ */ new Set(["--config"]);
3290
3305
  const plainFlags = /* @__PURE__ */ new Set(["--containers-rollout=gradual"]);
3291
- /**
3292
- * Reads `commands.deploy` from `<output>/nitro.json` and checks that it is the Wrangler deploy that the build writes:
3293
- * `npx wrangler deploy --config <file> [--containers-rollout=gradual]`. With
3294
- * `database.migrateOnDeploy`, `npx wrangler d1 migrations apply <binding> --remote --config <file> && ` comes before it
3295
- * once for each D1 binding (`packages/database/src/internal/migrate-on-deploy.ts`).
3296
- */
3297
3306
  async function readWranglerCommand(outputDir) {
3298
3307
  let manifest;
3299
3308
  try {
@@ -3335,6 +3344,11 @@ async function readWranglerCommand(outputDir) {
3335
3344
  */
3336
3345
  async function wranglerVarNames(outputDir) {
3337
3346
  const { config } = await readWranglerCommand(outputDir);
3347
+ const wrangler = await readWranglerConfig(outputDir, config);
3348
+ return isRecord(wrangler.vars) ? Object.keys(wrangler.vars) : [];
3349
+ }
3350
+ /** The Wrangler config that the `--config` flag of `commands.deploy` names. */
3351
+ async function readWranglerConfig(outputDir, config) {
3338
3352
  const file = join(outputDir, config);
3339
3353
  let value;
3340
3354
  try {
@@ -3342,9 +3356,40 @@ async function wranglerVarNames(outputDir) {
3342
3356
  } catch {
3343
3357
  throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file }), setupExitCodes.error);
3344
3358
  }
3345
- return isRecord(value) && isRecord(value.vars) ? Object.keys(value.vars) : [];
3359
+ return isRecord(value) ? value : {};
3360
+ }
3361
+ /**
3362
+ * The D1 bindings of the Wrangler config whose `migrations_dir` holds `.sql` files, except the bindings that the deploy
3363
+ * command migrates. Wrangler reads `migrations_dir` relative to the config file, and its default pattern is `*.sql`
3364
+ * without dot files. A binding with `migrations_pattern` selects other files, and ViteHub's build never writes one.
3365
+ */
3366
+ async function unmigratedD1Bindings(outputDir, config, wrangler, migrated) {
3367
+ const found = [];
3368
+ for (const entry of Array.isArray(wrangler.d1_databases) ? wrangler.d1_databases : []) {
3369
+ if (!isRecord(entry)) continue;
3370
+ const binding = optionalString$1(entry.binding);
3371
+ const dir = optionalString$1(entry.migrations_dir);
3372
+ if (!binding || !dir || entry.migrations_pattern !== void 0 || migrated.includes(binding)) continue;
3373
+ const files = (await readdir(join(outputDir, dirname(config), dir), { withFileTypes: true }).catch(() => [])).filter((item) => item.isFile() && item.name.endsWith(".sql") && !item.name.startsWith(".")).map((item) => item.name).toSorted();
3374
+ if (files.length) found.push({
3375
+ binding,
3376
+ files,
3377
+ table: optionalString$1(entry.migrations_table) ?? "d1_migrations"
3378
+ });
3379
+ }
3380
+ return found;
3381
+ }
3382
+ /** The `results` rows of `wrangler d1 execute --json`, which prints one `{ results, success, meta }` per statement. */
3383
+ function d1ResultNames(result) {
3384
+ let value;
3385
+ try {
3386
+ value = JSON.parse(result.stdout.slice(Math.max(result.stdout.indexOf("["), 0)));
3387
+ } catch {
3388
+ return;
3389
+ }
3390
+ if (!Array.isArray(value)) return void 0;
3391
+ return value.flatMap((item) => isRecord(item) && Array.isArray(item.results) ? item.results : []).flatMap((row) => isRecord(row) && typeof row.name === "string" ? [row.name] : []);
3346
3392
  }
3347
- /** Wrangler writes one JSON object per line to `WRANGLER_OUTPUT_FILE_PATH`. */
3348
3393
  async function readWranglerOutput(file) {
3349
3394
  return (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => {
3350
3395
  try {
@@ -3361,7 +3406,6 @@ const durationUnits = {
3361
3406
  hour: 36e5,
3362
3407
  day: 864e5
3363
3408
  };
3364
- /** `Claim within: 59 minutes` as an ISO time, from now. */
3365
3409
  function claimExpiry(text) {
3366
3410
  const match = /Claim within:\s*(\d+)\s*(second|minute|hour|day)s?/u.exec(text);
3367
3411
  return match ? new Date(Date.now() + Number(match[1]) * durationUnits[match[2]]).toISOString() : void 0;
@@ -3381,18 +3425,60 @@ async function cloudflareAdapter(context) {
3381
3425
  env: options.env ?? env,
3382
3426
  ...options
3383
3427
  });
3384
- return { async deploy() {
3385
- if (!context.preview && !context.temporary) for (const binding of command.migrations) {
3428
+ /** The migrations of `target` that its migrations table does not list. A database without the table has none applied. */
3429
+ const pendingD1Migrations = async (target) => {
3430
+ const query = async (sql) => {
3431
+ const step = `wrangler d1 execute ${target.binding}`;
3386
3432
  const result = await run([
3387
3433
  "d1",
3388
- "migrations",
3389
- "apply",
3390
- binding,
3434
+ "execute",
3435
+ target.binding,
3391
3436
  "--remote",
3392
3437
  "--config",
3393
- command.config
3394
- ], { show: true });
3395
- if (result.exitCode !== 0) throw hostCliFailed(`wrangler d1 migrations apply ${binding}`, result, context.secrets);
3438
+ command.config,
3439
+ "--json",
3440
+ "--command",
3441
+ sql
3442
+ ], { env: {
3443
+ ...env,
3444
+ WRANGLER_LOG: "log"
3445
+ } });
3446
+ if (result.exitCode !== 0) throw hostCliFailed(step, result, context.secrets);
3447
+ const names = d1ResultNames(result);
3448
+ if (!names) throw hostCliFailed(`${step} printed no JSON`, result, context.secrets);
3449
+ return names;
3450
+ };
3451
+ const tables = await query(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '${target.table.replaceAll("'", "''")}'`);
3452
+ const applied = new Set(tables.length ? await query(`SELECT name FROM "${target.table.replaceAll("\"", "\"\"")}"`) : []);
3453
+ return target.files.filter((file) => !applied.has(file));
3454
+ };
3455
+ return { async deploy() {
3456
+ if (!context.preview && !context.temporary) {
3457
+ const wranglerConfig = await readWranglerConfig(context.outputDir, command.config);
3458
+ const environment = env.CLOUDFLARE_ENV;
3459
+ const named = environment && isRecord(wranglerConfig.env) && Object.hasOwn(wranglerConfig.env, environment) ? wranglerConfig.env[environment] : void 0;
3460
+ const config = isRecord(named) ? named : wranglerConfig;
3461
+ for (const target of await unmigratedD1Bindings(context.outputDir, command.config, config, command.migrations)) {
3462
+ const pending = await pendingD1Migrations(target);
3463
+ if (!pending.length) continue;
3464
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_D1_MIGRATIONS_PENDING({
3465
+ apply: `npx wrangler d1 migrations apply ${shellQuote(target.binding)} --remote --config ${shellQuote(command.config)}${environment ? ` --env ${shellQuote(environment)}` : ""}`,
3466
+ binding: target.binding,
3467
+ migrations: pending.join(", ")
3468
+ }), setupExitCodes.error);
3469
+ }
3470
+ for (const binding of command.migrations) {
3471
+ const result = await run([
3472
+ "d1",
3473
+ "migrations",
3474
+ "apply",
3475
+ binding,
3476
+ "--remote",
3477
+ "--config",
3478
+ command.config
3479
+ ], { show: true });
3480
+ if (result.exitCode !== 0) throw hostCliFailed(`wrangler d1 migrations apply ${binding}`, result, context.secrets);
3481
+ }
3396
3482
  }
3397
3483
  return await untilInterrupted(async (signal) => {
3398
3484
  const folder = await mkdtemp(join(tmpdir(), "vitehub-deploy-"));
@@ -3453,7 +3539,6 @@ async function cloudflareAdapter(context) {
3453
3539
  });
3454
3540
  } };
3455
3541
  }
3456
- /** Version and deployment `source` values: https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/versions/methods/list/ */
3457
3542
  /**
3458
3543
  * The secrets of the linked Worker. Wrangler 4.158 (`wrangler secret put --help`, `wrangler secret list --help`, in
3459
3544
  * test/fixtures/host-cli-help/). `secret put` reads the value from stdin when stdin is not a terminal, and creates a
@@ -3547,7 +3632,6 @@ function parseDeployments(value) {
3547
3632
  }];
3548
3633
  });
3549
3634
  }
3550
- /** A Workers API request that answers undefined on any error, for data that only adds to a listing. */
3551
3635
  async function optional(request) {
3552
3636
  try {
3553
3637
  return await request;
@@ -3640,9 +3724,7 @@ const listCloudflareDeployments = async (context, { limit, includeLive }) => {
3640
3724
  if (includeLive && live && !recent.includes(live)) recent.push(live);
3641
3725
  return recent;
3642
3726
  };
3643
- //#endregion
3644
- //#region src/setup/deploy/deno.ts
3645
- /** The first line of the `deploy.mjs` that ViteHub's Deno build writes (`packages/internal/src/build/deno-runtime-packages.ts`). */
3727
+ // src/setup/deploy/deno.ts
3646
3728
  const runnerFirstLine = "import { spawn } from \"node:child_process\"";
3647
3729
  async function denoAdapter(context, organization) {
3648
3730
  const runner = join(context.outputDir, "deploy.mjs");
@@ -3678,10 +3760,6 @@ function denoOrganization(link, env) {
3678
3760
  if (!organization) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ORG_REQUIRED(), setupExitCodes.inputNeeded, { missing: [{ field: "DENO_DEPLOY_ORG" }] });
3679
3761
  return organization;
3680
3762
  }
3681
- /**
3682
- * One `KEY='value'` line for `deno deploy env load`, which parses the file with `@std/dotenv`. A single-quoted value
3683
- * is taken as it is. A value with a quote or a line break has no safe dotenv form, so it is refused.
3684
- */
3685
3763
  function dotenvLine(name, value) {
3686
3764
  if (/['\r\n]/u.test(value)) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
3687
3765
  host: "deno",
@@ -3826,8 +3904,7 @@ const listDenoDeployments = async (context, { limit, includeLive }) => {
3826
3904
  });
3827
3905
  return recent;
3828
3906
  };
3829
- //#endregion
3830
- //#region ../internal/dist/abort.js
3907
+ // ../internal/dist/abort.js
3831
3908
  /**
3832
3909
  * Runs `task` and rejects as soon as `signal` aborts, without waiting for the task.
3833
3910
  *
@@ -3857,9 +3934,7 @@ function abortReason(signal, message) {
3857
3934
  if (signal?.reason !== void 0) return signal.reason;
3858
3935
  return new DOMException(message, "AbortError");
3859
3936
  }
3860
- //#endregion
3861
- //#region src/setup/deploy/netlify.ts
3862
- /** Nitro's Netlify preset writes static files to `dist` (`output.publicDir`). */
3937
+ // src/setup/deploy/netlify.ts
3863
3938
  const publishDir = "dist";
3864
3939
  function netlifyAdapter(context) {
3865
3940
  const netlify = hostCli("netlify", "netlify-cli", context.root, context.env);
@@ -3877,7 +3952,6 @@ function netlifyAdapter(context) {
3877
3952
  "--json",
3878
3953
  ...context.preview ? ["--context", "deploy-preview"] : ["--prod"]
3879
3954
  ];
3880
- if (existsSync(join(context.outputDir, "functions", "server.mjs"))) args.push("--functions", join(context.outputDir, "functions"));
3881
3955
  args.push(...site ? ["--site", site.id] : ["--site-name", context.projectName]);
3882
3956
  if (context.commit) args.push("--message", commitMessage(context.commit));
3883
3957
  const result = await context.run(netlify[0], [...netlify.slice(1), ...args], {
@@ -3904,12 +3978,10 @@ function netlifyAdapter(context) {
3904
3978
  };
3905
3979
  } };
3906
3980
  }
3907
- /** The Netlify deploy context of a host env target. */
3908
3981
  const netlifyContexts = {
3909
3982
  preview: "deploy-preview",
3910
3983
  production: "production"
3911
3984
  };
3912
- /** The contexts that one `all` value stands for, as the Netlify UI lists them for "different value for each context". */
3913
3985
  const allContexts = [
3914
3986
  "production",
3915
3987
  "deploy-preview",
@@ -3930,13 +4002,6 @@ function netlifyValues(value) {
3930
4002
  }
3931
4003
  return values;
3932
4004
  }
3933
- /**
3934
- * The `updateEnvVar` body that gives an existing variable Functions scope and, for a secret, secret storage. Undefined
3935
- * when the variable already has both, so PATCH can set the one value. PUT replaces every value, so the body keeps the
3936
- * values of the other contexts. Netlify masks secret values of every context except `dev`, so a secret with values
3937
- * in other contexts cannot be rewritten without losing them: that is refused before any write.
3938
- * https://docs.netlify.com/build/environment-variables/secrets-controller/
3939
- */
3940
4005
  function netlifyUpdate(existing, name, context, value, secret) {
3941
4006
  const refuse = (reason) => setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
3942
4007
  host: "netlify",
@@ -4135,8 +4200,7 @@ const listNetlifyDeployments = async (context, { limit, includeLive }) => {
4135
4200
  }
4136
4201
  return recent;
4137
4202
  };
4138
- //#endregion
4139
- //#region src/setup/deploy/vercel.ts
4203
+ // src/setup/deploy/vercel.ts
4140
4204
  /** Check the CLI's saved session without reading its auth files or exposing a token. */
4141
4205
  async function hasVercelLogin(root, context) {
4142
4206
  try {
@@ -4149,7 +4213,6 @@ async function hasVercelLogin(root, context) {
4149
4213
  return false;
4150
4214
  }
4151
4215
  }
4152
- /** Reads `claimUrl` and `expiresAt` that `vercel deploy --temporary` keeps in `.vercel/anonymous.json`. Its token stays there. */
4153
4216
  async function readClaim(root) {
4154
4217
  let value;
4155
4218
  try {
@@ -4270,7 +4333,6 @@ const gitSources = /* @__PURE__ */ new Set([
4270
4333
  "import/repo",
4271
4334
  "clone/repo"
4272
4335
  ]);
4273
- /** `source` of a deployment: https://vercel.com/docs/rest-api/reference/endpoints/deployments/list-deployments */
4274
4336
  function vercelSource(value, commit) {
4275
4337
  if (value === "cli") return "cli";
4276
4338
  if (typeof value === "string" && gitSources.has(value)) return "git";
@@ -4284,7 +4346,6 @@ function vercelState(value) {
4284
4346
  if (value === "BUILDING" || value === "INITIALIZING" || value === "QUEUED" || value === "BLOCKED") return "building";
4285
4347
  return "unknown";
4286
4348
  }
4287
- /** `vitehubCommit` and `vitehubDirty` from `vercel deploy --meta`, else the commit of a Git integration build. */
4288
4349
  function vercelCommit(meta) {
4289
4350
  if (!isRecord(meta)) return;
4290
4351
  const marked = optionalString$1(meta.vitehubCommit);
@@ -4346,8 +4407,7 @@ const listVercelDeployments = async (context, { limit, includeLive }) => {
4346
4407
  }
4347
4408
  return recent;
4348
4409
  };
4349
- //#endregion
4350
- //#region src/setup/link.ts
4410
+ // src/setup/link.ts
4351
4411
  /** The link file, relative to the project root. It is gitignored and never holds a secret. */
4352
4412
  const SETUP_LINK_FILE = ".vitehub/link.json";
4353
4413
  const linkHosts = [
@@ -4365,7 +4425,6 @@ function optionalString(value) {
4365
4425
  function invalidResponse(host) {
4366
4426
  return cliErrorDiagnostics.CLI_HOST_RESPONSE_INVALID({ host });
4367
4427
  }
4368
- /** The same normalization as the deployment identity of `vitehub({ name })`. */
4369
4428
  function normalizeName(value) {
4370
4429
  return value?.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || void 0;
4371
4430
  }
@@ -4386,7 +4445,6 @@ function nameRequired() {
4386
4445
  rerun: "vitehub link --project <name>"
4387
4446
  });
4388
4447
  }
4389
- /** `--project`, else the literal `name` of vitehub(), else the package.json name, normalized as the build does. */
4390
4448
  async function projectName(project, option) {
4391
4449
  if (option?.trim()) return option.trim();
4392
4450
  const config = project.config;
@@ -4425,6 +4483,11 @@ function rerunCommand(host, name, options, extra) {
4425
4483
  ].join(" ");
4426
4484
  }
4427
4485
  function notFound(host, name, options, account) {
4486
+ if (host === "deno") return setupFailure(cliErrorDiagnostics.SETUP_LINK_PROJECT_NOT_FOUND({
4487
+ account,
4488
+ host,
4489
+ project: name
4490
+ }), setupExitCodes.conflict);
4428
4491
  const rerun = rerunCommand(host, name, options, "--create");
4429
4492
  return setupFailure(cliErrorDiagnostics.SETUP_LINK_PROJECT_NOT_FOUND({
4430
4493
  account,
@@ -4433,7 +4496,6 @@ function notFound(host, name, options, account) {
4433
4496
  rerun
4434
4497
  }), setupExitCodes.conflict, { rerun });
4435
4498
  }
4436
- /** Returns undefined when the host API answers 404. */
4437
4499
  async function unlessNotFound(request) {
4438
4500
  try {
4439
4501
  return await request;
@@ -4604,6 +4666,55 @@ async function linkNetlify(name, options, token, fetchImpl) {
4604
4666
  verified: true
4605
4667
  };
4606
4668
  }
4669
+ async function linkDeno(name, options, token, root, context) {
4670
+ const linked = {
4671
+ ...options.account ? { account: { id: options.account } } : {},
4672
+ created: false,
4673
+ project: { name }
4674
+ };
4675
+ const organization = options.account ?? context.env.DENO_DEPLOY_ORG?.trim();
4676
+ if (!token || !organization) return {
4677
+ ...linked,
4678
+ verified: false
4679
+ };
4680
+ const deno = hostCli("deno", "deno", root, context.env);
4681
+ const step = "deno deploy apps get";
4682
+ const secrets = [token];
4683
+ const run = context.runHostCli ?? createDeployRun(context.stderr, secrets);
4684
+ const runOptions = {
4685
+ cwd: root,
4686
+ env: context.env,
4687
+ timeoutMs: 3e4
4688
+ };
4689
+ const result = await run(deno[0], [
4690
+ ...deno.slice(1),
4691
+ "deploy",
4692
+ "apps",
4693
+ "get",
4694
+ "--json",
4695
+ "--non-interactive",
4696
+ "--org",
4697
+ organization,
4698
+ "--app",
4699
+ name
4700
+ ], runOptions).catch((error) => {
4701
+ throw hostCliFailed(step, {
4702
+ exitCode: null,
4703
+ stderr: error instanceof Error ? error.message : String(error),
4704
+ stdout: ""
4705
+ }, secrets);
4706
+ });
4707
+ if (result.exitCode === 4) throw notFound("deno", name, options, organization);
4708
+ if (result.exitCode !== 0) throw hostCliFailed(step, {
4709
+ ...result,
4710
+ stderr: result.stderr ?? ""
4711
+ }, secrets);
4712
+ return {
4713
+ ...linked,
4714
+ account: { id: organization },
4715
+ verified: true
4716
+ };
4717
+ }
4607
4718
  /** `content` of a `.gitignore` with a `.vitehub` line, or undefined when it already ignores `.vitehub`. */
4608
4719
  function gitignoreWithViteHub(content) {
4609
4720
  if (content.split(/\r?\n/u).some((line) => /^\/?(?:\*\*\/)?\.vitehub\/?$/u.test(line.trim()))) return;
@@ -4630,12 +4741,7 @@ async function linkSetupProject(project, options, context) {
4630
4741
  const credentials = await resolveHostCredentials(host, credentialsContext);
4631
4742
  const fetchImpl = context.fetch ?? globalThis.fetch;
4632
4743
  let linked;
4633
- if (host === "deno") linked = {
4634
- ...options.account ? { account: { id: options.account } } : {},
4635
- created: false,
4636
- project: { name },
4637
- verified: false
4638
- };
4744
+ if (host === "deno") linked = await linkDeno(name, options, credentials.ok ? credentials.token : void 0, project.root, context);
4639
4745
  else if (!credentials.ok) throw setupFailure(cliErrorDiagnostics.SETUP_LINK_CREDENTIALS_MISSING({
4640
4746
  fix: credentials.fix,
4641
4747
  host
@@ -4875,9 +4981,7 @@ function describeCredentials(credentials) {
4875
4981
  async function readSetupLinkStatus(project, host, context) {
4876
4982
  return (await readSetupLinkState(project, host, context)).status;
4877
4983
  }
4878
- //#endregion
4879
- //#region src/setup/env-encrypted.ts
4880
- /** dotenvx marks an encrypted value with this prefix. */
4984
+ // src/setup/env-encrypted.ts
4881
4985
  const prefix = "encrypted:";
4882
4986
  /** The file where dotenvx writes private keys. It must never be in git. */
4883
4987
  const envKeysFile = ".env.keys";
@@ -4943,8 +5047,7 @@ async function decryptEnvValues(root, items, env) {
4943
5047
  values
4944
5048
  };
4945
5049
  }
4946
- //#endregion
4947
- //#region src/setup/deploy/github.ts
5050
+ // src/setup/deploy/github.ts
4948
5051
  const apiBase = "https://api.github.com";
4949
5052
  const repositoryPattern = /^[\w.-]+\/[\w.-]+$/u;
4950
5053
  /** GitHub accepts letters, digits, and `_`, not a digit first, and reserves the `GITHUB_` prefix. */
@@ -5024,7 +5127,6 @@ function concat(...parts) {
5024
5127
  }
5025
5128
  return out;
5026
5129
  }
5027
- /** "expand 32-byte k" as little-endian words. */
5028
5130
  const sigma = new Uint32Array([
5029
5131
  1634760805,
5030
5132
  857760878,
@@ -5041,7 +5143,6 @@ function wordBytes(input) {
5041
5143
  input.forEach((word, index) => view.setUint32(index * 4, word, true));
5042
5144
  return out;
5043
5145
  }
5044
- /** `crypto_box_beforenm`: HSalsa20 of the X25519 shared secret with a zero input. */
5045
5146
  function boxKey(shared) {
5046
5147
  const out = /* @__PURE__ */ new Uint32Array(8);
5047
5148
  hsalsa(sigma, words(shared), /* @__PURE__ */ new Uint32Array(4), out);
@@ -5122,17 +5223,9 @@ function githubEnv(context) {
5122
5223
  }
5123
5224
  };
5124
5225
  }
5125
- //#endregion
5126
- //#region src/setup/env.ts
5127
- var env_exports = /* @__PURE__ */ __exportAll({
5128
- checkDeployEnv: () => checkDeployEnv,
5129
- diffEnvNames: () => diffEnvNames,
5130
- readLocalEnvValues: () => readLocalEnvValues,
5131
- runEnvCommand: () => runEnvCommand
5132
- });
5133
- /** The stage that a deploy without `--preview` reads. */
5226
+ // src/setup/env.ts
5227
+ var env_exports = /* @__PURE__ */ __exportAll({ runEnvCommand: () => runEnvCommand });
5134
5228
  const defaultStage = "production";
5135
- /** The host CLI tokens. They are never values to push, and no output may show them. */
5136
5229
  const tokenNames = [
5137
5230
  "CLOUDFLARE_API_TOKEN",
5138
5231
  "VERCEL_TOKEN",
@@ -5145,7 +5238,6 @@ const hostEnvs = {
5145
5238
  netlify: netlifyEnv,
5146
5239
  vercel: vercelEnv
5147
5240
  };
5148
- /** Hosts without a preview environment: a Worker has one set of secrets, and ViteHub deploys Deno to production only. */
5149
5241
  const noPreview = /* @__PURE__ */ new Set(["cloudflare", "deno"]);
5150
5242
  function readEnvArgs(args, push, usage) {
5151
5243
  try {
@@ -5222,7 +5314,6 @@ function linkedTarget(links, host, command) {
5222
5314
  });
5223
5315
  return selected.link;
5224
5316
  }
5225
- /** The names and the env folder of the last build for `host`. Builds first when there is no build output for `host`. */
5226
5317
  async function readNames(project, host, context) {
5227
5318
  try {
5228
5319
  return await readBuildOutput(project.root, host);
@@ -5234,7 +5325,6 @@ async function readNames(project, host, context) {
5234
5325
  await build(project, host, context);
5235
5326
  return await readBuildOutput(project.root, host);
5236
5327
  }
5237
- /** Plain vars set by the build rather than uploaded as secrets. */
5238
5328
  async function configVarNames(host, outputDir) {
5239
5329
  return new Set(host === "cloudflare" ? await wranglerVarNames(outputDir) : []);
5240
5330
  }
@@ -5276,10 +5366,6 @@ async function openTarget(args, command, context) {
5276
5366
  target
5277
5367
  };
5278
5368
  }
5279
- /**
5280
- * GitHub is a destination, not a host: the names come from the build of the linked host (or `--host`), and the stage
5281
- * only picks the local `.env.<stage>` file. Names that GitHub reserves (`GITHUB_*`) drop out of each entry.
5282
- */
5283
5369
  async function openGitHubTarget(args, options, project, command, context) {
5284
5370
  const selected = selectSetupLink(await readSetupLinks(project.root), args.host);
5285
5371
  if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, `${command} --to github`);
@@ -5350,7 +5436,6 @@ function isRequired(entry) {
5350
5436
  function matchesPrefix(entry, name) {
5351
5437
  return !!entry.prefix && name.startsWith(entry.prefix) && name.length > entry.prefix.length;
5352
5438
  }
5353
- /** True when one of `names` sets the entry: one of its names, or a name with its prefix. */
5354
5439
  function isSet(entry, names) {
5355
5440
  return entry.names.some((name) => names.has(name)) || [...names].some((name) => matchesPrefix(entry, name));
5356
5441
  }
@@ -5390,7 +5475,6 @@ function targetLabel(output) {
5390
5475
  if (output.github) return `the GitHub Actions secrets of ${output.github.repository}${output.github.environment ? `, environment ${output.github.environment}` : ""}, stage ${output.stage}`;
5391
5476
  return `${output.project} on ${output.host}, stage ${output.stage}${output.target === output.stage ? "" : ` (${output.target})`}`;
5392
5477
  }
5393
- /** The flags that name the destination again, for a hint or a rerun. */
5394
5478
  function destinationFlags(output) {
5395
5479
  return [...output.github ? [
5396
5480
  "--to github",
@@ -5433,12 +5517,10 @@ function destination(target) {
5433
5517
  ...target.github ? { github: target.github } : {}
5434
5518
  };
5435
5519
  }
5436
- /** An env file as output names it: relative to the project root, such as `config/.env.production`. */
5437
5520
  function fileSource(root, path) {
5438
5521
  const folder = relative(root, dirname(path));
5439
5522
  return `${folder ? `${folder}/` : ""}.env${basename(path).slice(4)}`;
5440
5523
  }
5441
- /** Trace the same replacements and iteration order as Vite's patched dotenv-expand. */
5442
5524
  function expandedFiles(raw, env) {
5443
5525
  const parsed = Object.fromEntries([...raw].map(([name, file]) => [name, file.value]));
5444
5526
  const files = new Map([...raw].map(([name, file]) => [name, /* @__PURE__ */ new Set([file.path])]));
@@ -5526,11 +5608,6 @@ async function readLocalEnvValues(root, envDir, stage, env) {
5526
5608
  }
5527
5609
  return values;
5528
5610
  }
5529
- /**
5530
- * The value of each entry: the first name in read order that has a local value, and every local name of a prefix.
5531
- * `onHost` keeps what the host has: an entry with one of its names on the host keeps that alias, and a prefix entry
5532
- * skips only the members that the host has.
5533
- */
5534
5611
  function planPush(entries, values, only, onHost = /* @__PURE__ */ new Set()) {
5535
5612
  const wanted = only.length ? new Set(only) : void 0;
5536
5613
  const unknown = only.filter((name) => !entries.some((entry) => entry.names.includes(name) || matchesPrefix(entry, name)));
@@ -5569,11 +5646,6 @@ function planPush(entries, values, only, onHost = /* @__PURE__ */ new Set()) {
5569
5646
  skipped
5570
5647
  };
5571
5648
  }
5572
- /**
5573
- * True when `directory` or a parent folder looks like a git repository, or `GIT_DIR` names one: a `.git` file, as in a
5574
- * worktree, or a `.git` folder with `HEAD`. It does not ask git, because git reports a broken repository the same way
5575
- * as no repository, and a broken one must refuse.
5576
- */
5577
5649
  function inGitRepository(directory, env) {
5578
5650
  if (env.GIT_DIR) return true;
5579
5651
  for (let current = directory;; current = dirname(current)) {
@@ -5582,7 +5654,6 @@ function inGitRepository(directory, env) {
5582
5654
  if (dirname(current) === current) return false;
5583
5655
  }
5584
5656
  }
5585
- /** What git says about one env file, by its real path. Throws when git cannot answer. */
5586
5657
  async function gitFileState(file, label, run, env) {
5587
5658
  const failed = (reason) => setupFailure(cliErrorDiagnostics.SETUP_ENV_GIT_FAILED({
5588
5659
  file: label,
@@ -5616,12 +5687,6 @@ async function gitFileState(file, label, run, env) {
5616
5687
  if (ignored.exitCode === 1) return "unignored";
5617
5688
  throw failed(ignored.stderr.trim() || `git check-ignore exited with ${ignored.exitCode}`);
5618
5689
  }
5619
- /**
5620
- * Refuses a secret whose value reads an env file that git tracks, or that git does not ignore: pushing it would hide
5621
- * that the secret is in git, or that the next commit can add it. It checks every file that the value reads, through
5622
- * `$NAME` expansion too, by its real path, so a symlink to a tracked file does not pass. When git cannot answer inside a
5623
- * repository, it refuses. A file outside any git repository passes with a warning, since git cannot commit it.
5624
- */
5625
5690
  async function assertUntracked(planned, root, run, env, stderr) {
5626
5691
  const byFile = /* @__PURE__ */ new Map();
5627
5692
  for (const item of planned) {
@@ -5652,7 +5717,6 @@ async function assertUntracked(planned, root, run, env, stderr) {
5652
5717
  const realKeys = await realpath(keysPath).catch(() => void 0);
5653
5718
  if (planned.some((item) => item.encrypted) && realKeys && inGitRepository(dirname(realKeys), env) && await gitFileState(realKeys, ".env.keys", run, env) === "tracked") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_KEYS_TRACKED({ file: envKeysFile }), setupExitCodes.conflict);
5654
5719
  }
5655
- /** Replaces each encrypted value with its plaintext. The private keys and the plaintext join the values that output redacts. */
5656
5720
  async function decryptPlanned(planned, root, env, secrets) {
5657
5721
  const { keys, values } = await decryptEnvValues(root, planned.filter((item) => item.encrypted).map((item) => ({
5658
5722
  file: item.source,
@@ -5697,7 +5761,6 @@ function pushRerun(args) {
5697
5761
  ...args.json ? ["--json"] : []
5698
5762
  ].join(" ");
5699
5763
  }
5700
- /** Short plain values, such as "1", would hide host output that has nothing to do with them. */
5701
5764
  function addRedactions(planned, secrets) {
5702
5765
  for (const item of planned) if (item.secret || item.value.length >= 4) secrets.push(item.value);
5703
5766
  }
@@ -5746,7 +5809,6 @@ async function runPush(args, context) {
5746
5809
  else writePush(output, context);
5747
5810
  return setupExitCodes.done;
5748
5811
  }
5749
- /** The name that ViteHub derives its own keys from. A deploy can generate it, because no one else has to know it. */
5750
5812
  const appSecretName = "VITEHUB_SECRET";
5751
5813
  async function confirmGenerate(label) {
5752
5814
  const terminal = createInterface({
@@ -5851,7 +5913,7 @@ async function checkDeployEnv(options) {
5851
5913
  if (stored.length && !hostEnv && host !== "cloudflare") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_NOT_LINKED({
5852
5914
  host,
5853
5915
  names: stored.map((item) => item.name).join(", ")
5854
- }), setupExitCodes.inputNeeded, { rerun: `vitehub link --host ${host} --create` });
5916
+ }), setupExitCodes.inputNeeded, { rerun: host === "deno" ? "vitehub link --host deno" : `vitehub link --host ${host} --create` });
5855
5917
  await assertUntracked(stored, options.root, options.run, context.env, context.stderr);
5856
5918
  const planned = await decryptPlanned(stored, options.root, context.env, options.secrets);
5857
5919
  output.missing = missing.map(diffEntry);
@@ -5886,5 +5948,4 @@ async function runEnvCommand(feature, args, context) {
5886
5948
  return writeSetupError(context, json, error);
5887
5949
  }
5888
5950
  }
5889
- //#endregion
5890
- export { readDeployCommit as A, readSetupProject as B, denoOrganization as C, build as D, listCloudflareDeployments as E, uninstallArgs as F, featureSupport as G, featureHosts as H, hostFromNitroPreset as I, editViteHubConfig as J, features as K, hasDefinitionFiles as L, installCommand as M, setsOption as N, readBuildOutput as O, setupStatus as P, listMatchingFiles as R, denoAdapter as S, cloudflareAdapter as T, featureIds as U, setupLockfiles as V, featurePackages as W, locateViteHubConfig as X, insertViteHubConfig as Y, __exportAll as Z, listVercelDeployments as _, ensureViteHubGitignore as a, netlifyAdapter as b, linkSetupProject as c, readSetupLinkStatus as d, readSetupLinks as f, hasVercelLogin as g, writeSeparateResourcesNote as h, addSetupLink as i, installArgs as j, createDeployRun as k, readLinkHostOption as l, unlinkSetupProject as m, env_exports as n, gitignoreWithViteHub as o, selectSetupLink as p, impliedFeatures as q, SETUP_LINK_FILE as r, hostRequired as s, checkDeployEnv as t, readSetupLinkState as u, vercelAdapter as v, listDenoDeployments as w, abortable as x, listNetlifyDeployments as y, detectPackageManager as z };
5951
+ export { readDeployCommit as A, listMatchingFiles as B, denoOrganization as C, build as D, listCloudflareDeployments as E, setupStatus as F, insertViteHubConfig as G, readSetupProject as H, shellQuote as I, locateViteHubConfig as K, uninstallArgs as L, installArgs as M, installCommand as N, readBuildOutput as O, missingProviderOption as P, hostFromNitroPreset as R, denoAdapter as S, cloudflareAdapter as T, setupLockfiles as U, detectPackageManager as V, editViteHubConfig as W, listVercelDeployments as _, ensureViteHubGitignore as a, netlifyAdapter as b, linkSetupProject as c, readSetupLinkStatus as d, readSetupLinks as f, hasVercelLogin as g, writeSeparateResourcesNote as h, addSetupLink as i, formatInstallCommand as j, createDeployRun as k, readLinkHostOption as l, unlinkSetupProject as m, env_exports as n, gitignoreWithViteHub as o, selectSetupLink as p, SETUP_LINK_FILE as r, hostRequired as s, checkDeployEnv as t, readSetupLinkState as u, vercelAdapter as v, listDenoDeployments as w, abortable as x, listNetlifyDeployments as y, hasDefinitionFiles as z };