@cloudflare/vite-plugin 0.0.0-229d00fce
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +484 -0
- package/dist/asset-workers/asset-worker.js +2610 -0
- package/dist/asset-workers/router-worker.js +2311 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +2403 -0
- package/dist/runner-worker/index.js +1679 -0
- package/package.json +70 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2403 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import assert7 from "node:assert";
|
|
3
|
+
import * as fs4 from "node:fs";
|
|
4
|
+
import * as path6 from "node:path";
|
|
5
|
+
import { createMiddleware } from "@hattip/adapter-node";
|
|
6
|
+
import { Miniflare } from "miniflare";
|
|
7
|
+
import "vite";
|
|
8
|
+
|
|
9
|
+
// src/cloudflare-environment.ts
|
|
10
|
+
import assert from "node:assert";
|
|
11
|
+
import { builtinModules } from "node:module";
|
|
12
|
+
import * as vite2 from "vite";
|
|
13
|
+
|
|
14
|
+
// src/node-js-compat.ts
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
|
|
17
|
+
// ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
|
|
18
|
+
var comma = ",".charCodeAt(0);
|
|
19
|
+
var semicolon = ";".charCodeAt(0);
|
|
20
|
+
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
21
|
+
var intToChar = new Uint8Array(64);
|
|
22
|
+
var charToInt = new Uint8Array(128);
|
|
23
|
+
for (let i = 0; i < chars.length; i++) {
|
|
24
|
+
const c = chars.charCodeAt(i);
|
|
25
|
+
intToChar[i] = c;
|
|
26
|
+
charToInt[c] = i;
|
|
27
|
+
}
|
|
28
|
+
function encodeInteger(builder, num, relative4) {
|
|
29
|
+
let delta = num - relative4;
|
|
30
|
+
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
|
31
|
+
do {
|
|
32
|
+
let clamped = delta & 31;
|
|
33
|
+
delta >>>= 5;
|
|
34
|
+
if (delta > 0)
|
|
35
|
+
clamped |= 32;
|
|
36
|
+
builder.write(intToChar[clamped]);
|
|
37
|
+
} while (delta > 0);
|
|
38
|
+
return num;
|
|
39
|
+
}
|
|
40
|
+
var bufLength = 1024 * 16;
|
|
41
|
+
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
|
42
|
+
decode(buf) {
|
|
43
|
+
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
44
|
+
return out.toString();
|
|
45
|
+
}
|
|
46
|
+
} : {
|
|
47
|
+
decode(buf) {
|
|
48
|
+
let out = "";
|
|
49
|
+
for (let i = 0; i < buf.length; i++) {
|
|
50
|
+
out += String.fromCharCode(buf[i]);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var StringWriter = class {
|
|
56
|
+
constructor() {
|
|
57
|
+
this.pos = 0;
|
|
58
|
+
this.out = "";
|
|
59
|
+
this.buffer = new Uint8Array(bufLength);
|
|
60
|
+
}
|
|
61
|
+
write(v) {
|
|
62
|
+
const { buffer } = this;
|
|
63
|
+
buffer[this.pos++] = v;
|
|
64
|
+
if (this.pos === bufLength) {
|
|
65
|
+
this.out += td.decode(buffer);
|
|
66
|
+
this.pos = 0;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
flush() {
|
|
70
|
+
const { buffer, out, pos } = this;
|
|
71
|
+
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
function encode(decoded) {
|
|
75
|
+
const writer = new StringWriter();
|
|
76
|
+
let sourcesIndex = 0;
|
|
77
|
+
let sourceLine = 0;
|
|
78
|
+
let sourceColumn = 0;
|
|
79
|
+
let namesIndex = 0;
|
|
80
|
+
for (let i = 0; i < decoded.length; i++) {
|
|
81
|
+
const line = decoded[i];
|
|
82
|
+
if (i > 0)
|
|
83
|
+
writer.write(semicolon);
|
|
84
|
+
if (line.length === 0)
|
|
85
|
+
continue;
|
|
86
|
+
let genColumn = 0;
|
|
87
|
+
for (let j = 0; j < line.length; j++) {
|
|
88
|
+
const segment = line[j];
|
|
89
|
+
if (j > 0)
|
|
90
|
+
writer.write(comma);
|
|
91
|
+
genColumn = encodeInteger(writer, segment[0], genColumn);
|
|
92
|
+
if (segment.length === 1)
|
|
93
|
+
continue;
|
|
94
|
+
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
|
95
|
+
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
|
96
|
+
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
|
97
|
+
if (segment.length === 4)
|
|
98
|
+
continue;
|
|
99
|
+
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return writer.flush();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ../../node_modules/.pnpm/magic-string@0.30.17/node_modules/magic-string/dist/magic-string.es.mjs
|
|
106
|
+
var BitSet = class _BitSet {
|
|
107
|
+
constructor(arg) {
|
|
108
|
+
this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
|
|
109
|
+
}
|
|
110
|
+
add(n2) {
|
|
111
|
+
this.bits[n2 >> 5] |= 1 << (n2 & 31);
|
|
112
|
+
}
|
|
113
|
+
has(n2) {
|
|
114
|
+
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
var Chunk = class _Chunk {
|
|
118
|
+
constructor(start, end, content) {
|
|
119
|
+
this.start = start;
|
|
120
|
+
this.end = end;
|
|
121
|
+
this.original = content;
|
|
122
|
+
this.intro = "";
|
|
123
|
+
this.outro = "";
|
|
124
|
+
this.content = content;
|
|
125
|
+
this.storeName = false;
|
|
126
|
+
this.edited = false;
|
|
127
|
+
{
|
|
128
|
+
this.previous = null;
|
|
129
|
+
this.next = null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
appendLeft(content) {
|
|
133
|
+
this.outro += content;
|
|
134
|
+
}
|
|
135
|
+
appendRight(content) {
|
|
136
|
+
this.intro = this.intro + content;
|
|
137
|
+
}
|
|
138
|
+
clone() {
|
|
139
|
+
const chunk = new _Chunk(this.start, this.end, this.original);
|
|
140
|
+
chunk.intro = this.intro;
|
|
141
|
+
chunk.outro = this.outro;
|
|
142
|
+
chunk.content = this.content;
|
|
143
|
+
chunk.storeName = this.storeName;
|
|
144
|
+
chunk.edited = this.edited;
|
|
145
|
+
return chunk;
|
|
146
|
+
}
|
|
147
|
+
contains(index) {
|
|
148
|
+
return this.start < index && index < this.end;
|
|
149
|
+
}
|
|
150
|
+
eachNext(fn) {
|
|
151
|
+
let chunk = this;
|
|
152
|
+
while (chunk) {
|
|
153
|
+
fn(chunk);
|
|
154
|
+
chunk = chunk.next;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
eachPrevious(fn) {
|
|
158
|
+
let chunk = this;
|
|
159
|
+
while (chunk) {
|
|
160
|
+
fn(chunk);
|
|
161
|
+
chunk = chunk.previous;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
edit(content, storeName, contentOnly) {
|
|
165
|
+
this.content = content;
|
|
166
|
+
if (!contentOnly) {
|
|
167
|
+
this.intro = "";
|
|
168
|
+
this.outro = "";
|
|
169
|
+
}
|
|
170
|
+
this.storeName = storeName;
|
|
171
|
+
this.edited = true;
|
|
172
|
+
return this;
|
|
173
|
+
}
|
|
174
|
+
prependLeft(content) {
|
|
175
|
+
this.outro = content + this.outro;
|
|
176
|
+
}
|
|
177
|
+
prependRight(content) {
|
|
178
|
+
this.intro = content + this.intro;
|
|
179
|
+
}
|
|
180
|
+
reset() {
|
|
181
|
+
this.intro = "";
|
|
182
|
+
this.outro = "";
|
|
183
|
+
if (this.edited) {
|
|
184
|
+
this.content = this.original;
|
|
185
|
+
this.storeName = false;
|
|
186
|
+
this.edited = false;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
split(index) {
|
|
190
|
+
const sliceIndex = index - this.start;
|
|
191
|
+
const originalBefore = this.original.slice(0, sliceIndex);
|
|
192
|
+
const originalAfter = this.original.slice(sliceIndex);
|
|
193
|
+
this.original = originalBefore;
|
|
194
|
+
const newChunk = new _Chunk(index, this.end, originalAfter);
|
|
195
|
+
newChunk.outro = this.outro;
|
|
196
|
+
this.outro = "";
|
|
197
|
+
this.end = index;
|
|
198
|
+
if (this.edited) {
|
|
199
|
+
newChunk.edit("", false);
|
|
200
|
+
this.content = "";
|
|
201
|
+
} else {
|
|
202
|
+
this.content = originalBefore;
|
|
203
|
+
}
|
|
204
|
+
newChunk.next = this.next;
|
|
205
|
+
if (newChunk.next) newChunk.next.previous = newChunk;
|
|
206
|
+
newChunk.previous = this;
|
|
207
|
+
this.next = newChunk;
|
|
208
|
+
return newChunk;
|
|
209
|
+
}
|
|
210
|
+
toString() {
|
|
211
|
+
return this.intro + this.content + this.outro;
|
|
212
|
+
}
|
|
213
|
+
trimEnd(rx) {
|
|
214
|
+
this.outro = this.outro.replace(rx, "");
|
|
215
|
+
if (this.outro.length) return true;
|
|
216
|
+
const trimmed = this.content.replace(rx, "");
|
|
217
|
+
if (trimmed.length) {
|
|
218
|
+
if (trimmed !== this.content) {
|
|
219
|
+
this.split(this.start + trimmed.length).edit("", void 0, true);
|
|
220
|
+
if (this.edited) {
|
|
221
|
+
this.edit(trimmed, this.storeName, true);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return true;
|
|
225
|
+
} else {
|
|
226
|
+
this.edit("", void 0, true);
|
|
227
|
+
this.intro = this.intro.replace(rx, "");
|
|
228
|
+
if (this.intro.length) return true;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
trimStart(rx) {
|
|
232
|
+
this.intro = this.intro.replace(rx, "");
|
|
233
|
+
if (this.intro.length) return true;
|
|
234
|
+
const trimmed = this.content.replace(rx, "");
|
|
235
|
+
if (trimmed.length) {
|
|
236
|
+
if (trimmed !== this.content) {
|
|
237
|
+
const newChunk = this.split(this.end - trimmed.length);
|
|
238
|
+
if (this.edited) {
|
|
239
|
+
newChunk.edit(trimmed, this.storeName, true);
|
|
240
|
+
}
|
|
241
|
+
this.edit("", void 0, true);
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
} else {
|
|
245
|
+
this.edit("", void 0, true);
|
|
246
|
+
this.outro = this.outro.replace(rx, "");
|
|
247
|
+
if (this.outro.length) return true;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
function getBtoa() {
|
|
252
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
|
|
253
|
+
return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
|
|
254
|
+
} else if (typeof Buffer === "function") {
|
|
255
|
+
return (str) => Buffer.from(str, "utf-8").toString("base64");
|
|
256
|
+
} else {
|
|
257
|
+
return () => {
|
|
258
|
+
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
var btoa = /* @__PURE__ */ getBtoa();
|
|
263
|
+
var SourceMap = class {
|
|
264
|
+
constructor(properties) {
|
|
265
|
+
this.version = 3;
|
|
266
|
+
this.file = properties.file;
|
|
267
|
+
this.sources = properties.sources;
|
|
268
|
+
this.sourcesContent = properties.sourcesContent;
|
|
269
|
+
this.names = properties.names;
|
|
270
|
+
this.mappings = encode(properties.mappings);
|
|
271
|
+
if (typeof properties.x_google_ignoreList !== "undefined") {
|
|
272
|
+
this.x_google_ignoreList = properties.x_google_ignoreList;
|
|
273
|
+
}
|
|
274
|
+
if (typeof properties.debugId !== "undefined") {
|
|
275
|
+
this.debugId = properties.debugId;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
toString() {
|
|
279
|
+
return JSON.stringify(this);
|
|
280
|
+
}
|
|
281
|
+
toUrl() {
|
|
282
|
+
return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
function guessIndent(code) {
|
|
286
|
+
const lines = code.split("\n");
|
|
287
|
+
const tabbed = lines.filter((line) => /^\t+/.test(line));
|
|
288
|
+
const spaced = lines.filter((line) => /^ {2,}/.test(line));
|
|
289
|
+
if (tabbed.length === 0 && spaced.length === 0) {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
if (tabbed.length >= spaced.length) {
|
|
293
|
+
return " ";
|
|
294
|
+
}
|
|
295
|
+
const min = spaced.reduce((previous, current) => {
|
|
296
|
+
const numSpaces = /^ +/.exec(current)[0].length;
|
|
297
|
+
return Math.min(numSpaces, previous);
|
|
298
|
+
}, Infinity);
|
|
299
|
+
return new Array(min + 1).join(" ");
|
|
300
|
+
}
|
|
301
|
+
function getRelativePath(from, to) {
|
|
302
|
+
const fromParts = from.split(/[/\\]/);
|
|
303
|
+
const toParts = to.split(/[/\\]/);
|
|
304
|
+
fromParts.pop();
|
|
305
|
+
while (fromParts[0] === toParts[0]) {
|
|
306
|
+
fromParts.shift();
|
|
307
|
+
toParts.shift();
|
|
308
|
+
}
|
|
309
|
+
if (fromParts.length) {
|
|
310
|
+
let i = fromParts.length;
|
|
311
|
+
while (i--) fromParts[i] = "..";
|
|
312
|
+
}
|
|
313
|
+
return fromParts.concat(toParts).join("/");
|
|
314
|
+
}
|
|
315
|
+
var toString = Object.prototype.toString;
|
|
316
|
+
function isObject(thing) {
|
|
317
|
+
return toString.call(thing) === "[object Object]";
|
|
318
|
+
}
|
|
319
|
+
function getLocator(source) {
|
|
320
|
+
const originalLines = source.split("\n");
|
|
321
|
+
const lineOffsets = [];
|
|
322
|
+
for (let i = 0, pos = 0; i < originalLines.length; i++) {
|
|
323
|
+
lineOffsets.push(pos);
|
|
324
|
+
pos += originalLines[i].length + 1;
|
|
325
|
+
}
|
|
326
|
+
return function locate(index) {
|
|
327
|
+
let i = 0;
|
|
328
|
+
let j = lineOffsets.length;
|
|
329
|
+
while (i < j) {
|
|
330
|
+
const m = i + j >> 1;
|
|
331
|
+
if (index < lineOffsets[m]) {
|
|
332
|
+
j = m;
|
|
333
|
+
} else {
|
|
334
|
+
i = m + 1;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const line = i - 1;
|
|
338
|
+
const column = index - lineOffsets[line];
|
|
339
|
+
return { line, column };
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
var wordRegex = /\w/;
|
|
343
|
+
var Mappings = class {
|
|
344
|
+
constructor(hires) {
|
|
345
|
+
this.hires = hires;
|
|
346
|
+
this.generatedCodeLine = 0;
|
|
347
|
+
this.generatedCodeColumn = 0;
|
|
348
|
+
this.raw = [];
|
|
349
|
+
this.rawSegments = this.raw[this.generatedCodeLine] = [];
|
|
350
|
+
this.pending = null;
|
|
351
|
+
}
|
|
352
|
+
addEdit(sourceIndex, content, loc, nameIndex) {
|
|
353
|
+
if (content.length) {
|
|
354
|
+
const contentLengthMinusOne = content.length - 1;
|
|
355
|
+
let contentLineEnd = content.indexOf("\n", 0);
|
|
356
|
+
let previousContentLineEnd = -1;
|
|
357
|
+
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
|
|
358
|
+
const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
359
|
+
if (nameIndex >= 0) {
|
|
360
|
+
segment2.push(nameIndex);
|
|
361
|
+
}
|
|
362
|
+
this.rawSegments.push(segment2);
|
|
363
|
+
this.generatedCodeLine += 1;
|
|
364
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
365
|
+
this.generatedCodeColumn = 0;
|
|
366
|
+
previousContentLineEnd = contentLineEnd;
|
|
367
|
+
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
|
|
368
|
+
}
|
|
369
|
+
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
370
|
+
if (nameIndex >= 0) {
|
|
371
|
+
segment.push(nameIndex);
|
|
372
|
+
}
|
|
373
|
+
this.rawSegments.push(segment);
|
|
374
|
+
this.advance(content.slice(previousContentLineEnd + 1));
|
|
375
|
+
} else if (this.pending) {
|
|
376
|
+
this.rawSegments.push(this.pending);
|
|
377
|
+
this.advance(content);
|
|
378
|
+
}
|
|
379
|
+
this.pending = null;
|
|
380
|
+
}
|
|
381
|
+
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
|
|
382
|
+
let originalCharIndex = chunk.start;
|
|
383
|
+
let first = true;
|
|
384
|
+
let charInHiresBoundary = false;
|
|
385
|
+
while (originalCharIndex < chunk.end) {
|
|
386
|
+
if (original[originalCharIndex] === "\n") {
|
|
387
|
+
loc.line += 1;
|
|
388
|
+
loc.column = 0;
|
|
389
|
+
this.generatedCodeLine += 1;
|
|
390
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
391
|
+
this.generatedCodeColumn = 0;
|
|
392
|
+
first = true;
|
|
393
|
+
charInHiresBoundary = false;
|
|
394
|
+
} else {
|
|
395
|
+
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
|
|
396
|
+
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
397
|
+
if (this.hires === "boundary") {
|
|
398
|
+
if (wordRegex.test(original[originalCharIndex])) {
|
|
399
|
+
if (!charInHiresBoundary) {
|
|
400
|
+
this.rawSegments.push(segment);
|
|
401
|
+
charInHiresBoundary = true;
|
|
402
|
+
}
|
|
403
|
+
} else {
|
|
404
|
+
this.rawSegments.push(segment);
|
|
405
|
+
charInHiresBoundary = false;
|
|
406
|
+
}
|
|
407
|
+
} else {
|
|
408
|
+
this.rawSegments.push(segment);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
loc.column += 1;
|
|
412
|
+
this.generatedCodeColumn += 1;
|
|
413
|
+
first = false;
|
|
414
|
+
}
|
|
415
|
+
originalCharIndex += 1;
|
|
416
|
+
}
|
|
417
|
+
this.pending = null;
|
|
418
|
+
}
|
|
419
|
+
advance(str) {
|
|
420
|
+
if (!str) return;
|
|
421
|
+
const lines = str.split("\n");
|
|
422
|
+
if (lines.length > 1) {
|
|
423
|
+
for (let i = 0; i < lines.length - 1; i++) {
|
|
424
|
+
this.generatedCodeLine++;
|
|
425
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
426
|
+
}
|
|
427
|
+
this.generatedCodeColumn = 0;
|
|
428
|
+
}
|
|
429
|
+
this.generatedCodeColumn += lines[lines.length - 1].length;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
var n = "\n";
|
|
433
|
+
var warned = {
|
|
434
|
+
insertLeft: false,
|
|
435
|
+
insertRight: false,
|
|
436
|
+
storeName: false
|
|
437
|
+
};
|
|
438
|
+
var MagicString = class _MagicString {
|
|
439
|
+
constructor(string, options = {}) {
|
|
440
|
+
const chunk = new Chunk(0, string.length, string);
|
|
441
|
+
Object.defineProperties(this, {
|
|
442
|
+
original: { writable: true, value: string },
|
|
443
|
+
outro: { writable: true, value: "" },
|
|
444
|
+
intro: { writable: true, value: "" },
|
|
445
|
+
firstChunk: { writable: true, value: chunk },
|
|
446
|
+
lastChunk: { writable: true, value: chunk },
|
|
447
|
+
lastSearchedChunk: { writable: true, value: chunk },
|
|
448
|
+
byStart: { writable: true, value: {} },
|
|
449
|
+
byEnd: { writable: true, value: {} },
|
|
450
|
+
filename: { writable: true, value: options.filename },
|
|
451
|
+
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
|
|
452
|
+
sourcemapLocations: { writable: true, value: new BitSet() },
|
|
453
|
+
storedNames: { writable: true, value: {} },
|
|
454
|
+
indentStr: { writable: true, value: void 0 },
|
|
455
|
+
ignoreList: { writable: true, value: options.ignoreList },
|
|
456
|
+
offset: { writable: true, value: options.offset || 0 }
|
|
457
|
+
});
|
|
458
|
+
this.byStart[0] = chunk;
|
|
459
|
+
this.byEnd[string.length] = chunk;
|
|
460
|
+
}
|
|
461
|
+
addSourcemapLocation(char) {
|
|
462
|
+
this.sourcemapLocations.add(char);
|
|
463
|
+
}
|
|
464
|
+
append(content) {
|
|
465
|
+
if (typeof content !== "string") throw new TypeError("outro content must be a string");
|
|
466
|
+
this.outro += content;
|
|
467
|
+
return this;
|
|
468
|
+
}
|
|
469
|
+
appendLeft(index, content) {
|
|
470
|
+
index = index + this.offset;
|
|
471
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
472
|
+
this._split(index);
|
|
473
|
+
const chunk = this.byEnd[index];
|
|
474
|
+
if (chunk) {
|
|
475
|
+
chunk.appendLeft(content);
|
|
476
|
+
} else {
|
|
477
|
+
this.intro += content;
|
|
478
|
+
}
|
|
479
|
+
return this;
|
|
480
|
+
}
|
|
481
|
+
appendRight(index, content) {
|
|
482
|
+
index = index + this.offset;
|
|
483
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
484
|
+
this._split(index);
|
|
485
|
+
const chunk = this.byStart[index];
|
|
486
|
+
if (chunk) {
|
|
487
|
+
chunk.appendRight(content);
|
|
488
|
+
} else {
|
|
489
|
+
this.outro += content;
|
|
490
|
+
}
|
|
491
|
+
return this;
|
|
492
|
+
}
|
|
493
|
+
clone() {
|
|
494
|
+
const cloned = new _MagicString(this.original, { filename: this.filename, offset: this.offset });
|
|
495
|
+
let originalChunk = this.firstChunk;
|
|
496
|
+
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
|
|
497
|
+
while (originalChunk) {
|
|
498
|
+
cloned.byStart[clonedChunk.start] = clonedChunk;
|
|
499
|
+
cloned.byEnd[clonedChunk.end] = clonedChunk;
|
|
500
|
+
const nextOriginalChunk = originalChunk.next;
|
|
501
|
+
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
|
|
502
|
+
if (nextClonedChunk) {
|
|
503
|
+
clonedChunk.next = nextClonedChunk;
|
|
504
|
+
nextClonedChunk.previous = clonedChunk;
|
|
505
|
+
clonedChunk = nextClonedChunk;
|
|
506
|
+
}
|
|
507
|
+
originalChunk = nextOriginalChunk;
|
|
508
|
+
}
|
|
509
|
+
cloned.lastChunk = clonedChunk;
|
|
510
|
+
if (this.indentExclusionRanges) {
|
|
511
|
+
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
|
|
512
|
+
}
|
|
513
|
+
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
|
|
514
|
+
cloned.intro = this.intro;
|
|
515
|
+
cloned.outro = this.outro;
|
|
516
|
+
return cloned;
|
|
517
|
+
}
|
|
518
|
+
generateDecodedMap(options) {
|
|
519
|
+
options = options || {};
|
|
520
|
+
const sourceIndex = 0;
|
|
521
|
+
const names = Object.keys(this.storedNames);
|
|
522
|
+
const mappings = new Mappings(options.hires);
|
|
523
|
+
const locate = getLocator(this.original);
|
|
524
|
+
if (this.intro) {
|
|
525
|
+
mappings.advance(this.intro);
|
|
526
|
+
}
|
|
527
|
+
this.firstChunk.eachNext((chunk) => {
|
|
528
|
+
const loc = locate(chunk.start);
|
|
529
|
+
if (chunk.intro.length) mappings.advance(chunk.intro);
|
|
530
|
+
if (chunk.edited) {
|
|
531
|
+
mappings.addEdit(
|
|
532
|
+
sourceIndex,
|
|
533
|
+
chunk.content,
|
|
534
|
+
loc,
|
|
535
|
+
chunk.storeName ? names.indexOf(chunk.original) : -1
|
|
536
|
+
);
|
|
537
|
+
} else {
|
|
538
|
+
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
|
|
539
|
+
}
|
|
540
|
+
if (chunk.outro.length) mappings.advance(chunk.outro);
|
|
541
|
+
});
|
|
542
|
+
return {
|
|
543
|
+
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
|
|
544
|
+
sources: [
|
|
545
|
+
options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
|
|
546
|
+
],
|
|
547
|
+
sourcesContent: options.includeContent ? [this.original] : void 0,
|
|
548
|
+
names,
|
|
549
|
+
mappings: mappings.raw,
|
|
550
|
+
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
generateMap(options) {
|
|
554
|
+
return new SourceMap(this.generateDecodedMap(options));
|
|
555
|
+
}
|
|
556
|
+
_ensureindentStr() {
|
|
557
|
+
if (this.indentStr === void 0) {
|
|
558
|
+
this.indentStr = guessIndent(this.original);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
_getRawIndentString() {
|
|
562
|
+
this._ensureindentStr();
|
|
563
|
+
return this.indentStr;
|
|
564
|
+
}
|
|
565
|
+
getIndentString() {
|
|
566
|
+
this._ensureindentStr();
|
|
567
|
+
return this.indentStr === null ? " " : this.indentStr;
|
|
568
|
+
}
|
|
569
|
+
indent(indentStr, options) {
|
|
570
|
+
const pattern = /^[^\r\n]/gm;
|
|
571
|
+
if (isObject(indentStr)) {
|
|
572
|
+
options = indentStr;
|
|
573
|
+
indentStr = void 0;
|
|
574
|
+
}
|
|
575
|
+
if (indentStr === void 0) {
|
|
576
|
+
this._ensureindentStr();
|
|
577
|
+
indentStr = this.indentStr || " ";
|
|
578
|
+
}
|
|
579
|
+
if (indentStr === "") return this;
|
|
580
|
+
options = options || {};
|
|
581
|
+
const isExcluded = {};
|
|
582
|
+
if (options.exclude) {
|
|
583
|
+
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
|
|
584
|
+
exclusions.forEach((exclusion) => {
|
|
585
|
+
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
|
|
586
|
+
isExcluded[i] = true;
|
|
587
|
+
}
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
let shouldIndentNextCharacter = options.indentStart !== false;
|
|
591
|
+
const replacer = (match) => {
|
|
592
|
+
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
|
|
593
|
+
shouldIndentNextCharacter = true;
|
|
594
|
+
return match;
|
|
595
|
+
};
|
|
596
|
+
this.intro = this.intro.replace(pattern, replacer);
|
|
597
|
+
let charIndex = 0;
|
|
598
|
+
let chunk = this.firstChunk;
|
|
599
|
+
while (chunk) {
|
|
600
|
+
const end = chunk.end;
|
|
601
|
+
if (chunk.edited) {
|
|
602
|
+
if (!isExcluded[charIndex]) {
|
|
603
|
+
chunk.content = chunk.content.replace(pattern, replacer);
|
|
604
|
+
if (chunk.content.length) {
|
|
605
|
+
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
} else {
|
|
609
|
+
charIndex = chunk.start;
|
|
610
|
+
while (charIndex < end) {
|
|
611
|
+
if (!isExcluded[charIndex]) {
|
|
612
|
+
const char = this.original[charIndex];
|
|
613
|
+
if (char === "\n") {
|
|
614
|
+
shouldIndentNextCharacter = true;
|
|
615
|
+
} else if (char !== "\r" && shouldIndentNextCharacter) {
|
|
616
|
+
shouldIndentNextCharacter = false;
|
|
617
|
+
if (charIndex === chunk.start) {
|
|
618
|
+
chunk.prependRight(indentStr);
|
|
619
|
+
} else {
|
|
620
|
+
this._splitChunk(chunk, charIndex);
|
|
621
|
+
chunk = chunk.next;
|
|
622
|
+
chunk.prependRight(indentStr);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
charIndex += 1;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
charIndex = chunk.end;
|
|
630
|
+
chunk = chunk.next;
|
|
631
|
+
}
|
|
632
|
+
this.outro = this.outro.replace(pattern, replacer);
|
|
633
|
+
return this;
|
|
634
|
+
}
|
|
635
|
+
insert() {
|
|
636
|
+
throw new Error(
|
|
637
|
+
"magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
|
|
638
|
+
);
|
|
639
|
+
}
|
|
640
|
+
insertLeft(index, content) {
|
|
641
|
+
if (!warned.insertLeft) {
|
|
642
|
+
console.warn(
|
|
643
|
+
"magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
|
|
644
|
+
);
|
|
645
|
+
warned.insertLeft = true;
|
|
646
|
+
}
|
|
647
|
+
return this.appendLeft(index, content);
|
|
648
|
+
}
|
|
649
|
+
insertRight(index, content) {
|
|
650
|
+
if (!warned.insertRight) {
|
|
651
|
+
console.warn(
|
|
652
|
+
"magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
|
|
653
|
+
);
|
|
654
|
+
warned.insertRight = true;
|
|
655
|
+
}
|
|
656
|
+
return this.prependRight(index, content);
|
|
657
|
+
}
|
|
658
|
+
move(start, end, index) {
|
|
659
|
+
start = start + this.offset;
|
|
660
|
+
end = end + this.offset;
|
|
661
|
+
index = index + this.offset;
|
|
662
|
+
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
|
|
663
|
+
this._split(start);
|
|
664
|
+
this._split(end);
|
|
665
|
+
this._split(index);
|
|
666
|
+
const first = this.byStart[start];
|
|
667
|
+
const last = this.byEnd[end];
|
|
668
|
+
const oldLeft = first.previous;
|
|
669
|
+
const oldRight = last.next;
|
|
670
|
+
const newRight = this.byStart[index];
|
|
671
|
+
if (!newRight && last === this.lastChunk) return this;
|
|
672
|
+
const newLeft = newRight ? newRight.previous : this.lastChunk;
|
|
673
|
+
if (oldLeft) oldLeft.next = oldRight;
|
|
674
|
+
if (oldRight) oldRight.previous = oldLeft;
|
|
675
|
+
if (newLeft) newLeft.next = first;
|
|
676
|
+
if (newRight) newRight.previous = last;
|
|
677
|
+
if (!first.previous) this.firstChunk = last.next;
|
|
678
|
+
if (!last.next) {
|
|
679
|
+
this.lastChunk = first.previous;
|
|
680
|
+
this.lastChunk.next = null;
|
|
681
|
+
}
|
|
682
|
+
first.previous = newLeft;
|
|
683
|
+
last.next = newRight || null;
|
|
684
|
+
if (!newLeft) this.firstChunk = first;
|
|
685
|
+
if (!newRight) this.lastChunk = last;
|
|
686
|
+
return this;
|
|
687
|
+
}
|
|
688
|
+
overwrite(start, end, content, options) {
|
|
689
|
+
options = options || {};
|
|
690
|
+
return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
|
|
691
|
+
}
|
|
692
|
+
update(start, end, content, options) {
|
|
693
|
+
start = start + this.offset;
|
|
694
|
+
end = end + this.offset;
|
|
695
|
+
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
|
|
696
|
+
if (this.original.length !== 0) {
|
|
697
|
+
while (start < 0) start += this.original.length;
|
|
698
|
+
while (end < 0) end += this.original.length;
|
|
699
|
+
}
|
|
700
|
+
if (end > this.original.length) throw new Error("end is out of bounds");
|
|
701
|
+
if (start === end)
|
|
702
|
+
throw new Error(
|
|
703
|
+
"Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead"
|
|
704
|
+
);
|
|
705
|
+
this._split(start);
|
|
706
|
+
this._split(end);
|
|
707
|
+
if (options === true) {
|
|
708
|
+
if (!warned.storeName) {
|
|
709
|
+
console.warn(
|
|
710
|
+
"The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
|
|
711
|
+
);
|
|
712
|
+
warned.storeName = true;
|
|
713
|
+
}
|
|
714
|
+
options = { storeName: true };
|
|
715
|
+
}
|
|
716
|
+
const storeName = options !== void 0 ? options.storeName : false;
|
|
717
|
+
const overwrite = options !== void 0 ? options.overwrite : false;
|
|
718
|
+
if (storeName) {
|
|
719
|
+
const original = this.original.slice(start, end);
|
|
720
|
+
Object.defineProperty(this.storedNames, original, {
|
|
721
|
+
writable: true,
|
|
722
|
+
value: true,
|
|
723
|
+
enumerable: true
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
const first = this.byStart[start];
|
|
727
|
+
const last = this.byEnd[end];
|
|
728
|
+
if (first) {
|
|
729
|
+
let chunk = first;
|
|
730
|
+
while (chunk !== last) {
|
|
731
|
+
if (chunk.next !== this.byStart[chunk.end]) {
|
|
732
|
+
throw new Error("Cannot overwrite across a split point");
|
|
733
|
+
}
|
|
734
|
+
chunk = chunk.next;
|
|
735
|
+
chunk.edit("", false);
|
|
736
|
+
}
|
|
737
|
+
first.edit(content, storeName, !overwrite);
|
|
738
|
+
} else {
|
|
739
|
+
const newChunk = new Chunk(start, end, "").edit(content, storeName);
|
|
740
|
+
last.next = newChunk;
|
|
741
|
+
newChunk.previous = last;
|
|
742
|
+
}
|
|
743
|
+
return this;
|
|
744
|
+
}
|
|
745
|
+
prepend(content) {
|
|
746
|
+
if (typeof content !== "string") throw new TypeError("outro content must be a string");
|
|
747
|
+
this.intro = content + this.intro;
|
|
748
|
+
return this;
|
|
749
|
+
}
|
|
750
|
+
prependLeft(index, content) {
|
|
751
|
+
index = index + this.offset;
|
|
752
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
753
|
+
this._split(index);
|
|
754
|
+
const chunk = this.byEnd[index];
|
|
755
|
+
if (chunk) {
|
|
756
|
+
chunk.prependLeft(content);
|
|
757
|
+
} else {
|
|
758
|
+
this.intro = content + this.intro;
|
|
759
|
+
}
|
|
760
|
+
return this;
|
|
761
|
+
}
|
|
762
|
+
prependRight(index, content) {
|
|
763
|
+
index = index + this.offset;
|
|
764
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
765
|
+
this._split(index);
|
|
766
|
+
const chunk = this.byStart[index];
|
|
767
|
+
if (chunk) {
|
|
768
|
+
chunk.prependRight(content);
|
|
769
|
+
} else {
|
|
770
|
+
this.outro = content + this.outro;
|
|
771
|
+
}
|
|
772
|
+
return this;
|
|
773
|
+
}
|
|
774
|
+
remove(start, end) {
|
|
775
|
+
start = start + this.offset;
|
|
776
|
+
end = end + this.offset;
|
|
777
|
+
if (this.original.length !== 0) {
|
|
778
|
+
while (start < 0) start += this.original.length;
|
|
779
|
+
while (end < 0) end += this.original.length;
|
|
780
|
+
}
|
|
781
|
+
if (start === end) return this;
|
|
782
|
+
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
|
|
783
|
+
if (start > end) throw new Error("end must be greater than start");
|
|
784
|
+
this._split(start);
|
|
785
|
+
this._split(end);
|
|
786
|
+
let chunk = this.byStart[start];
|
|
787
|
+
while (chunk) {
|
|
788
|
+
chunk.intro = "";
|
|
789
|
+
chunk.outro = "";
|
|
790
|
+
chunk.edit("");
|
|
791
|
+
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
|
792
|
+
}
|
|
793
|
+
return this;
|
|
794
|
+
}
|
|
795
|
+
reset(start, end) {
|
|
796
|
+
start = start + this.offset;
|
|
797
|
+
end = end + this.offset;
|
|
798
|
+
if (this.original.length !== 0) {
|
|
799
|
+
while (start < 0) start += this.original.length;
|
|
800
|
+
while (end < 0) end += this.original.length;
|
|
801
|
+
}
|
|
802
|
+
if (start === end) return this;
|
|
803
|
+
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
|
|
804
|
+
if (start > end) throw new Error("end must be greater than start");
|
|
805
|
+
this._split(start);
|
|
806
|
+
this._split(end);
|
|
807
|
+
let chunk = this.byStart[start];
|
|
808
|
+
while (chunk) {
|
|
809
|
+
chunk.reset();
|
|
810
|
+
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
|
811
|
+
}
|
|
812
|
+
return this;
|
|
813
|
+
}
|
|
814
|
+
lastChar() {
|
|
815
|
+
if (this.outro.length) return this.outro[this.outro.length - 1];
|
|
816
|
+
let chunk = this.lastChunk;
|
|
817
|
+
do {
|
|
818
|
+
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
|
|
819
|
+
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
|
|
820
|
+
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
|
|
821
|
+
} while (chunk = chunk.previous);
|
|
822
|
+
if (this.intro.length) return this.intro[this.intro.length - 1];
|
|
823
|
+
return "";
|
|
824
|
+
}
|
|
825
|
+
lastLine() {
|
|
826
|
+
let lineIndex = this.outro.lastIndexOf(n);
|
|
827
|
+
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
|
|
828
|
+
let lineStr = this.outro;
|
|
829
|
+
let chunk = this.lastChunk;
|
|
830
|
+
do {
|
|
831
|
+
if (chunk.outro.length > 0) {
|
|
832
|
+
lineIndex = chunk.outro.lastIndexOf(n);
|
|
833
|
+
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
|
|
834
|
+
lineStr = chunk.outro + lineStr;
|
|
835
|
+
}
|
|
836
|
+
if (chunk.content.length > 0) {
|
|
837
|
+
lineIndex = chunk.content.lastIndexOf(n);
|
|
838
|
+
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
|
|
839
|
+
lineStr = chunk.content + lineStr;
|
|
840
|
+
}
|
|
841
|
+
if (chunk.intro.length > 0) {
|
|
842
|
+
lineIndex = chunk.intro.lastIndexOf(n);
|
|
843
|
+
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
|
|
844
|
+
lineStr = chunk.intro + lineStr;
|
|
845
|
+
}
|
|
846
|
+
} while (chunk = chunk.previous);
|
|
847
|
+
lineIndex = this.intro.lastIndexOf(n);
|
|
848
|
+
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
|
|
849
|
+
return this.intro + lineStr;
|
|
850
|
+
}
|
|
851
|
+
slice(start = 0, end = this.original.length - this.offset) {
|
|
852
|
+
start = start + this.offset;
|
|
853
|
+
end = end + this.offset;
|
|
854
|
+
if (this.original.length !== 0) {
|
|
855
|
+
while (start < 0) start += this.original.length;
|
|
856
|
+
while (end < 0) end += this.original.length;
|
|
857
|
+
}
|
|
858
|
+
let result = "";
|
|
859
|
+
let chunk = this.firstChunk;
|
|
860
|
+
while (chunk && (chunk.start > start || chunk.end <= start)) {
|
|
861
|
+
if (chunk.start < end && chunk.end >= end) {
|
|
862
|
+
return result;
|
|
863
|
+
}
|
|
864
|
+
chunk = chunk.next;
|
|
865
|
+
}
|
|
866
|
+
if (chunk && chunk.edited && chunk.start !== start)
|
|
867
|
+
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
|
|
868
|
+
const startChunk = chunk;
|
|
869
|
+
while (chunk) {
|
|
870
|
+
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
|
|
871
|
+
result += chunk.intro;
|
|
872
|
+
}
|
|
873
|
+
const containsEnd = chunk.start < end && chunk.end >= end;
|
|
874
|
+
if (containsEnd && chunk.edited && chunk.end !== end)
|
|
875
|
+
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
|
|
876
|
+
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
|
|
877
|
+
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
|
|
878
|
+
result += chunk.content.slice(sliceStart, sliceEnd);
|
|
879
|
+
if (chunk.outro && (!containsEnd || chunk.end === end)) {
|
|
880
|
+
result += chunk.outro;
|
|
881
|
+
}
|
|
882
|
+
if (containsEnd) {
|
|
883
|
+
break;
|
|
884
|
+
}
|
|
885
|
+
chunk = chunk.next;
|
|
886
|
+
}
|
|
887
|
+
return result;
|
|
888
|
+
}
|
|
889
|
+
// TODO deprecate this? not really very useful
|
|
890
|
+
snip(start, end) {
|
|
891
|
+
const clone = this.clone();
|
|
892
|
+
clone.remove(0, start);
|
|
893
|
+
clone.remove(end, clone.original.length);
|
|
894
|
+
return clone;
|
|
895
|
+
}
|
|
896
|
+
_split(index) {
|
|
897
|
+
if (this.byStart[index] || this.byEnd[index]) return;
|
|
898
|
+
let chunk = this.lastSearchedChunk;
|
|
899
|
+
const searchForward = index > chunk.end;
|
|
900
|
+
while (chunk) {
|
|
901
|
+
if (chunk.contains(index)) return this._splitChunk(chunk, index);
|
|
902
|
+
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
_splitChunk(chunk, index) {
|
|
906
|
+
if (chunk.edited && chunk.content.length) {
|
|
907
|
+
const loc = getLocator(this.original)(index);
|
|
908
|
+
throw new Error(
|
|
909
|
+
`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
const newChunk = chunk.split(index);
|
|
913
|
+
this.byEnd[index] = chunk;
|
|
914
|
+
this.byStart[index] = newChunk;
|
|
915
|
+
this.byEnd[newChunk.end] = newChunk;
|
|
916
|
+
if (chunk === this.lastChunk) this.lastChunk = newChunk;
|
|
917
|
+
this.lastSearchedChunk = chunk;
|
|
918
|
+
return true;
|
|
919
|
+
}
|
|
920
|
+
toString() {
|
|
921
|
+
let str = this.intro;
|
|
922
|
+
let chunk = this.firstChunk;
|
|
923
|
+
while (chunk) {
|
|
924
|
+
str += chunk.toString();
|
|
925
|
+
chunk = chunk.next;
|
|
926
|
+
}
|
|
927
|
+
return str + this.outro;
|
|
928
|
+
}
|
|
929
|
+
isEmpty() {
|
|
930
|
+
let chunk = this.firstChunk;
|
|
931
|
+
do {
|
|
932
|
+
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
|
|
933
|
+
return false;
|
|
934
|
+
} while (chunk = chunk.next);
|
|
935
|
+
return true;
|
|
936
|
+
}
|
|
937
|
+
length() {
|
|
938
|
+
let chunk = this.firstChunk;
|
|
939
|
+
let length = 0;
|
|
940
|
+
do {
|
|
941
|
+
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
|
|
942
|
+
} while (chunk = chunk.next);
|
|
943
|
+
return length;
|
|
944
|
+
}
|
|
945
|
+
trimLines() {
|
|
946
|
+
return this.trim("[\\r\\n]");
|
|
947
|
+
}
|
|
948
|
+
trim(charType) {
|
|
949
|
+
return this.trimStart(charType).trimEnd(charType);
|
|
950
|
+
}
|
|
951
|
+
trimEndAborted(charType) {
|
|
952
|
+
const rx = new RegExp((charType || "\\s") + "+$");
|
|
953
|
+
this.outro = this.outro.replace(rx, "");
|
|
954
|
+
if (this.outro.length) return true;
|
|
955
|
+
let chunk = this.lastChunk;
|
|
956
|
+
do {
|
|
957
|
+
const end = chunk.end;
|
|
958
|
+
const aborted = chunk.trimEnd(rx);
|
|
959
|
+
if (chunk.end !== end) {
|
|
960
|
+
if (this.lastChunk === chunk) {
|
|
961
|
+
this.lastChunk = chunk.next;
|
|
962
|
+
}
|
|
963
|
+
this.byEnd[chunk.end] = chunk;
|
|
964
|
+
this.byStart[chunk.next.start] = chunk.next;
|
|
965
|
+
this.byEnd[chunk.next.end] = chunk.next;
|
|
966
|
+
}
|
|
967
|
+
if (aborted) return true;
|
|
968
|
+
chunk = chunk.previous;
|
|
969
|
+
} while (chunk);
|
|
970
|
+
return false;
|
|
971
|
+
}
|
|
972
|
+
trimEnd(charType) {
|
|
973
|
+
this.trimEndAborted(charType);
|
|
974
|
+
return this;
|
|
975
|
+
}
|
|
976
|
+
trimStartAborted(charType) {
|
|
977
|
+
const rx = new RegExp("^" + (charType || "\\s") + "+");
|
|
978
|
+
this.intro = this.intro.replace(rx, "");
|
|
979
|
+
if (this.intro.length) return true;
|
|
980
|
+
let chunk = this.firstChunk;
|
|
981
|
+
do {
|
|
982
|
+
const end = chunk.end;
|
|
983
|
+
const aborted = chunk.trimStart(rx);
|
|
984
|
+
if (chunk.end !== end) {
|
|
985
|
+
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
|
|
986
|
+
this.byEnd[chunk.end] = chunk;
|
|
987
|
+
this.byStart[chunk.next.start] = chunk.next;
|
|
988
|
+
this.byEnd[chunk.next.end] = chunk.next;
|
|
989
|
+
}
|
|
990
|
+
if (aborted) return true;
|
|
991
|
+
chunk = chunk.next;
|
|
992
|
+
} while (chunk);
|
|
993
|
+
return false;
|
|
994
|
+
}
|
|
995
|
+
trimStart(charType) {
|
|
996
|
+
this.trimStartAborted(charType);
|
|
997
|
+
return this;
|
|
998
|
+
}
|
|
999
|
+
hasChanged() {
|
|
1000
|
+
return this.original !== this.toString();
|
|
1001
|
+
}
|
|
1002
|
+
_replaceRegexp(searchValue, replacement) {
|
|
1003
|
+
function getReplacement(match, str) {
|
|
1004
|
+
if (typeof replacement === "string") {
|
|
1005
|
+
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
|
|
1006
|
+
if (i === "$") return "$";
|
|
1007
|
+
if (i === "&") return match[0];
|
|
1008
|
+
const num = +i;
|
|
1009
|
+
if (num < match.length) return match[+i];
|
|
1010
|
+
return `$${i}`;
|
|
1011
|
+
});
|
|
1012
|
+
} else {
|
|
1013
|
+
return replacement(...match, match.index, str, match.groups);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
function matchAll(re, str) {
|
|
1017
|
+
let match;
|
|
1018
|
+
const matches = [];
|
|
1019
|
+
while (match = re.exec(str)) {
|
|
1020
|
+
matches.push(match);
|
|
1021
|
+
}
|
|
1022
|
+
return matches;
|
|
1023
|
+
}
|
|
1024
|
+
if (searchValue.global) {
|
|
1025
|
+
const matches = matchAll(searchValue, this.original);
|
|
1026
|
+
matches.forEach((match) => {
|
|
1027
|
+
if (match.index != null) {
|
|
1028
|
+
const replacement2 = getReplacement(match, this.original);
|
|
1029
|
+
if (replacement2 !== match[0]) {
|
|
1030
|
+
this.overwrite(match.index, match.index + match[0].length, replacement2);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
});
|
|
1034
|
+
} else {
|
|
1035
|
+
const match = this.original.match(searchValue);
|
|
1036
|
+
if (match && match.index != null) {
|
|
1037
|
+
const replacement2 = getReplacement(match, this.original);
|
|
1038
|
+
if (replacement2 !== match[0]) {
|
|
1039
|
+
this.overwrite(match.index, match.index + match[0].length, replacement2);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
return this;
|
|
1044
|
+
}
|
|
1045
|
+
_replaceString(string, replacement) {
|
|
1046
|
+
const { original } = this;
|
|
1047
|
+
const index = original.indexOf(string);
|
|
1048
|
+
if (index !== -1) {
|
|
1049
|
+
this.overwrite(index, index + string.length, replacement);
|
|
1050
|
+
}
|
|
1051
|
+
return this;
|
|
1052
|
+
}
|
|
1053
|
+
replace(searchValue, replacement) {
|
|
1054
|
+
if (typeof searchValue === "string") {
|
|
1055
|
+
return this._replaceString(searchValue, replacement);
|
|
1056
|
+
}
|
|
1057
|
+
return this._replaceRegexp(searchValue, replacement);
|
|
1058
|
+
}
|
|
1059
|
+
_replaceAllString(string, replacement) {
|
|
1060
|
+
const { original } = this;
|
|
1061
|
+
const stringLength = string.length;
|
|
1062
|
+
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
|
|
1063
|
+
const previous = original.slice(index, index + stringLength);
|
|
1064
|
+
if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
|
|
1065
|
+
}
|
|
1066
|
+
return this;
|
|
1067
|
+
}
|
|
1068
|
+
replaceAll(searchValue, replacement) {
|
|
1069
|
+
if (typeof searchValue === "string") {
|
|
1070
|
+
return this._replaceAllString(searchValue, replacement);
|
|
1071
|
+
}
|
|
1072
|
+
if (!searchValue.global) {
|
|
1073
|
+
throw new TypeError(
|
|
1074
|
+
"MagicString.prototype.replaceAll called with a non-global RegExp argument"
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
return this._replaceRegexp(searchValue, replacement);
|
|
1078
|
+
}
|
|
1079
|
+
};
|
|
1080
|
+
|
|
1081
|
+
// src/node-js-compat.ts
|
|
1082
|
+
import { getNodeCompat } from "miniflare";
|
|
1083
|
+
import * as unenv from "unenv";
|
|
1084
|
+
var require2 = createRequire(import.meta.url);
|
|
1085
|
+
var preset = unenv.env(unenv.nodeless, unenv.cloudflare);
|
|
1086
|
+
var CLOUDFLARE_VIRTUAL_PREFIX = "\0cloudflare-";
|
|
1087
|
+
function isNodeCompat({
|
|
1088
|
+
compatibility_date,
|
|
1089
|
+
compatibility_flags
|
|
1090
|
+
}) {
|
|
1091
|
+
const nodeCompatMode = getNodeCompat(
|
|
1092
|
+
compatibility_date,
|
|
1093
|
+
compatibility_flags ?? []
|
|
1094
|
+
).mode;
|
|
1095
|
+
if (nodeCompatMode === "v2") {
|
|
1096
|
+
return true;
|
|
1097
|
+
}
|
|
1098
|
+
if (nodeCompatMode === "legacy") {
|
|
1099
|
+
throw new Error(
|
|
1100
|
+
"Unsupported Node.js compat mode (legacy). Remove the `node_compat` setting and add the `nodejs_compat` flag instead."
|
|
1101
|
+
);
|
|
1102
|
+
}
|
|
1103
|
+
if (nodeCompatMode === "v1") {
|
|
1104
|
+
throw new Error(
|
|
1105
|
+
`Unsupported Node.js compat mode (v1). Only the v2 mode is supported, either change your compat date to "2024-09-23" or later, or set the "nodejs_compat_v2" compatibility flag`
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
1108
|
+
return false;
|
|
1109
|
+
}
|
|
1110
|
+
function injectGlobalCode(id, code, workerConfig) {
|
|
1111
|
+
if (!isNodeCompat(workerConfig)) {
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
const injectedCode = Object.entries(preset.inject).map(([globalName, globalInject]) => {
|
|
1115
|
+
if (typeof globalInject === "string") {
|
|
1116
|
+
const moduleSpecifier2 = globalInject;
|
|
1117
|
+
return `import var_${globalName} from "${moduleSpecifier2}";
|
|
1118
|
+
globalThis.${globalName} = var_${globalName};
|
|
1119
|
+
`;
|
|
1120
|
+
}
|
|
1121
|
+
const [moduleSpecifier, exportName] = globalInject;
|
|
1122
|
+
return `import var_${globalName} from "${moduleSpecifier}";
|
|
1123
|
+
globalThis.${globalName} = var_${globalName}.${exportName};
|
|
1124
|
+
`;
|
|
1125
|
+
}).join("\n");
|
|
1126
|
+
const modified = new MagicString(code);
|
|
1127
|
+
modified.prepend(injectedCode);
|
|
1128
|
+
return {
|
|
1129
|
+
code: modified.toString(),
|
|
1130
|
+
map: modified.generateMap({ hires: "boundary", source: id })
|
|
1131
|
+
};
|
|
1132
|
+
}
|
|
1133
|
+
function getNodeCompatAliases() {
|
|
1134
|
+
const aliases = {};
|
|
1135
|
+
Object.keys(preset.alias).forEach((key) => {
|
|
1136
|
+
if (!preset.external.includes(key)) {
|
|
1137
|
+
aliases[key] = CLOUDFLARE_VIRTUAL_PREFIX + key;
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
return aliases;
|
|
1141
|
+
}
|
|
1142
|
+
function resolveNodeCompatId(environment, workerConfig, id) {
|
|
1143
|
+
const aliased = resolveNodeAliases(id, workerConfig) ?? id;
|
|
1144
|
+
if (aliased.startsWith("unenv/")) {
|
|
1145
|
+
const resolvedDep = require2.resolve(aliased).replace(/\.cjs$/, ".mjs");
|
|
1146
|
+
if (environment.mode === "dev" && environment.depsOptimizer) {
|
|
1147
|
+
const dep = environment.depsOptimizer.registerMissingImport(
|
|
1148
|
+
aliased,
|
|
1149
|
+
resolvedDep
|
|
1150
|
+
);
|
|
1151
|
+
return dep.id;
|
|
1152
|
+
} else {
|
|
1153
|
+
return resolvedDep;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function getNodeCompatExternals() {
|
|
1158
|
+
return preset.external;
|
|
1159
|
+
}
|
|
1160
|
+
function resolveNodeAliases(source, workerConfig) {
|
|
1161
|
+
if (!source.startsWith(CLOUDFLARE_VIRTUAL_PREFIX) || !isNodeCompat(workerConfig)) {
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
const from = source.slice(CLOUDFLARE_VIRTUAL_PREFIX.length);
|
|
1165
|
+
const alias = preset.alias[from];
|
|
1166
|
+
if (alias && preset.external.includes(alias)) {
|
|
1167
|
+
throw new Error(`Alias to external: ${source} -> ${alias}`);
|
|
1168
|
+
}
|
|
1169
|
+
return alias;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// src/shared.ts
|
|
1173
|
+
var UNKNOWN_HOST = "http://localhost";
|
|
1174
|
+
var INIT_PATH = "/__vite_plugin_cloudflare_init__";
|
|
1175
|
+
|
|
1176
|
+
// src/utils.ts
|
|
1177
|
+
import * as path from "node:path";
|
|
1178
|
+
import { Request as MiniflareRequest } from "miniflare";
|
|
1179
|
+
import "vite";
|
|
1180
|
+
function getOutputDirectory(userConfig, environmentName) {
|
|
1181
|
+
const rootOutputDirectory = userConfig.build?.outDir ?? "dist";
|
|
1182
|
+
return userConfig.environments?.[environmentName]?.build?.outDir ?? path.join(rootOutputDirectory, environmentName);
|
|
1183
|
+
}
|
|
1184
|
+
function toMiniflareRequest(request) {
|
|
1185
|
+
return new MiniflareRequest(request.url, {
|
|
1186
|
+
method: request.method,
|
|
1187
|
+
headers: [["accept-encoding", "identity"], ...request.headers],
|
|
1188
|
+
body: request.body,
|
|
1189
|
+
duplex: "half"
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
function nodeHeadersToWebHeaders(nodeHeaders) {
|
|
1193
|
+
const headers = new Headers();
|
|
1194
|
+
for (const [key, value] of Object.entries(nodeHeaders)) {
|
|
1195
|
+
if (typeof value === "string") {
|
|
1196
|
+
headers.append(key, value);
|
|
1197
|
+
} else if (Array.isArray(value)) {
|
|
1198
|
+
for (const item of value) {
|
|
1199
|
+
headers.append(key, item);
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
return headers;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// src/cloudflare-environment.ts
|
|
1207
|
+
var webSocketUndefinedError = "The WebSocket is undefined";
|
|
1208
|
+
function createHotChannel(webSocketContainer) {
|
|
1209
|
+
const listenersMap = /* @__PURE__ */ new Map();
|
|
1210
|
+
const client = {
|
|
1211
|
+
send(payload) {
|
|
1212
|
+
const webSocket = webSocketContainer.webSocket;
|
|
1213
|
+
assert(webSocket, webSocketUndefinedError);
|
|
1214
|
+
webSocket.send(JSON.stringify(payload));
|
|
1215
|
+
}
|
|
1216
|
+
};
|
|
1217
|
+
function onMessage(event) {
|
|
1218
|
+
const payload = JSON.parse(event.data.toString());
|
|
1219
|
+
const listeners = listenersMap.get(payload.event) ?? /* @__PURE__ */ new Set();
|
|
1220
|
+
for (const listener of listeners) {
|
|
1221
|
+
listener(payload.data, client);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
return {
|
|
1225
|
+
send(payload) {
|
|
1226
|
+
const webSocket = webSocketContainer.webSocket;
|
|
1227
|
+
assert(webSocket, webSocketUndefinedError);
|
|
1228
|
+
webSocket.send(JSON.stringify(payload));
|
|
1229
|
+
},
|
|
1230
|
+
on(event, listener) {
|
|
1231
|
+
const listeners = listenersMap.get(event) ?? /* @__PURE__ */ new Set();
|
|
1232
|
+
listeners.add(listener);
|
|
1233
|
+
listenersMap.set(event, listeners);
|
|
1234
|
+
},
|
|
1235
|
+
off(event, listener) {
|
|
1236
|
+
listenersMap.get(event)?.delete(listener);
|
|
1237
|
+
},
|
|
1238
|
+
listen() {
|
|
1239
|
+
const webSocket = webSocketContainer.webSocket;
|
|
1240
|
+
assert(webSocket, webSocketUndefinedError);
|
|
1241
|
+
webSocket.addEventListener("message", onMessage);
|
|
1242
|
+
},
|
|
1243
|
+
close() {
|
|
1244
|
+
const webSocket = webSocketContainer.webSocket;
|
|
1245
|
+
assert(webSocket, webSocketUndefinedError);
|
|
1246
|
+
webSocket.removeEventListener("message", onMessage);
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
var CloudflareDevEnvironment = class extends vite2.DevEnvironment {
|
|
1251
|
+
#webSocketContainer;
|
|
1252
|
+
#worker;
|
|
1253
|
+
constructor(name2, config) {
|
|
1254
|
+
const webSocketContainer = {};
|
|
1255
|
+
super(name2, config, {
|
|
1256
|
+
hot: true,
|
|
1257
|
+
transport: createHotChannel(webSocketContainer)
|
|
1258
|
+
});
|
|
1259
|
+
this.#webSocketContainer = webSocketContainer;
|
|
1260
|
+
}
|
|
1261
|
+
async initRunner(worker) {
|
|
1262
|
+
this.#worker = worker;
|
|
1263
|
+
const response = await this.#worker.fetch(
|
|
1264
|
+
new URL(INIT_PATH, UNKNOWN_HOST),
|
|
1265
|
+
{
|
|
1266
|
+
headers: {
|
|
1267
|
+
upgrade: "websocket"
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
);
|
|
1271
|
+
assert(response.ok, "Failed to initialize module runner");
|
|
1272
|
+
const webSocket = response.webSocket;
|
|
1273
|
+
assert(webSocket, "Failed to establish WebSocket");
|
|
1274
|
+
webSocket.accept();
|
|
1275
|
+
this.#webSocketContainer.webSocket = webSocket;
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
var cloudflareBuiltInModules = [
|
|
1279
|
+
"cloudflare:email",
|
|
1280
|
+
"cloudflare:sockets",
|
|
1281
|
+
"cloudflare:workers",
|
|
1282
|
+
"cloudflare:workflows"
|
|
1283
|
+
];
|
|
1284
|
+
function createCloudflareEnvironmentOptions(workerConfig, userConfig, environmentName) {
|
|
1285
|
+
return {
|
|
1286
|
+
resolve: {
|
|
1287
|
+
// Note: in order for ssr pre-bundling to take effect we need to ask vite to treat all
|
|
1288
|
+
// dependencies as not external
|
|
1289
|
+
noExternal: true,
|
|
1290
|
+
// We want to use `workerd` package exports if available (e.g. for postgres).
|
|
1291
|
+
conditions: ["workerd", "module", "browser", "development|production"]
|
|
1292
|
+
},
|
|
1293
|
+
dev: {
|
|
1294
|
+
createEnvironment(name2, config) {
|
|
1295
|
+
return new CloudflareDevEnvironment(name2, config);
|
|
1296
|
+
}
|
|
1297
|
+
},
|
|
1298
|
+
build: {
|
|
1299
|
+
createEnvironment(name2, config) {
|
|
1300
|
+
return new vite2.BuildEnvironment(name2, config);
|
|
1301
|
+
},
|
|
1302
|
+
outDir: getOutputDirectory(userConfig, environmentName),
|
|
1303
|
+
ssr: true,
|
|
1304
|
+
rollupOptions: {
|
|
1305
|
+
// Note: vite starts dev pre-bundling crawling from either optimizeDeps.entries or rollupOptions.input
|
|
1306
|
+
// so the input value here serves both as the build input as well as the starting point for
|
|
1307
|
+
// dev pre-bundling crawling (were we not to set this input field we'd have to appropriately set
|
|
1308
|
+
// optimizeDeps.entries in the dev config)
|
|
1309
|
+
input: workerConfig.main,
|
|
1310
|
+
external: [...cloudflareBuiltInModules, ...getNodeCompatExternals()]
|
|
1311
|
+
}
|
|
1312
|
+
},
|
|
1313
|
+
optimizeDeps: {
|
|
1314
|
+
// Note: ssr pre-bundling is opt-in and we need to enable it by setting `noDiscovery` to false
|
|
1315
|
+
noDiscovery: false,
|
|
1316
|
+
exclude: [
|
|
1317
|
+
...cloudflareBuiltInModules,
|
|
1318
|
+
// we have to exclude all node modules to work in dev-mode not just the unenv externals...
|
|
1319
|
+
...builtinModules.concat(builtinModules.map((m) => `node:${m}`))
|
|
1320
|
+
],
|
|
1321
|
+
esbuildOptions: {
|
|
1322
|
+
platform: "neutral",
|
|
1323
|
+
resolveExtensions: [
|
|
1324
|
+
".mjs",
|
|
1325
|
+
".js",
|
|
1326
|
+
".mts",
|
|
1327
|
+
".ts",
|
|
1328
|
+
".jsx",
|
|
1329
|
+
".tsx",
|
|
1330
|
+
".json",
|
|
1331
|
+
".cjs",
|
|
1332
|
+
".cts",
|
|
1333
|
+
".ctx"
|
|
1334
|
+
]
|
|
1335
|
+
}
|
|
1336
|
+
},
|
|
1337
|
+
keepProcessEnv: false
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
function initRunners(resolvedPluginConfig, viteDevServer, miniflare) {
|
|
1341
|
+
if (resolvedPluginConfig.type === "assets-only") {
|
|
1342
|
+
return;
|
|
1343
|
+
}
|
|
1344
|
+
return Promise.all(
|
|
1345
|
+
Object.entries(resolvedPluginConfig.workers).map(
|
|
1346
|
+
async ([environmentName, workerConfig]) => {
|
|
1347
|
+
const worker = await miniflare.getWorker(workerConfig.name);
|
|
1348
|
+
return viteDevServer.environments[environmentName].initRunner(worker);
|
|
1349
|
+
}
|
|
1350
|
+
)
|
|
1351
|
+
);
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// src/deploy-config.ts
|
|
1355
|
+
import assert2 from "node:assert";
|
|
1356
|
+
import * as fs from "node:fs";
|
|
1357
|
+
import * as path2 from "node:path";
|
|
1358
|
+
import "vite";
|
|
1359
|
+
function getDeployConfigPath(root) {
|
|
1360
|
+
return path2.resolve(root, ".wrangler", "deploy", "config.json");
|
|
1361
|
+
}
|
|
1362
|
+
function getWorkerConfigPaths(root) {
|
|
1363
|
+
const deployConfigPath = getDeployConfigPath(root);
|
|
1364
|
+
const deployConfig = JSON.parse(
|
|
1365
|
+
fs.readFileSync(deployConfigPath, "utf-8")
|
|
1366
|
+
);
|
|
1367
|
+
return [
|
|
1368
|
+
{ configPath: deployConfig.configPath },
|
|
1369
|
+
...deployConfig.auxiliaryWorkers
|
|
1370
|
+
].map(
|
|
1371
|
+
({ configPath }) => path2.resolve(path2.dirname(deployConfigPath), configPath)
|
|
1372
|
+
);
|
|
1373
|
+
}
|
|
1374
|
+
function getRelativePathToWorkerConfig(deployConfigDirectory, root, outputDirectory) {
|
|
1375
|
+
return path2.relative(
|
|
1376
|
+
deployConfigDirectory,
|
|
1377
|
+
path2.resolve(root, outputDirectory, "wrangler.json")
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
function writeDeployConfig(resolvedPluginConfig, resolvedViteConfig) {
|
|
1381
|
+
const deployConfigPath = getDeployConfigPath(resolvedViteConfig.root);
|
|
1382
|
+
const deployConfigDirectory = path2.dirname(deployConfigPath);
|
|
1383
|
+
fs.mkdirSync(deployConfigDirectory, { recursive: true });
|
|
1384
|
+
if (resolvedPluginConfig.type === "assets-only") {
|
|
1385
|
+
const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
|
|
1386
|
+
assert2(
|
|
1387
|
+
clientOutputDirectory,
|
|
1388
|
+
"Unexpected error: client environment output directory is undefined"
|
|
1389
|
+
);
|
|
1390
|
+
const deployConfig = {
|
|
1391
|
+
configPath: getRelativePathToWorkerConfig(
|
|
1392
|
+
deployConfigDirectory,
|
|
1393
|
+
resolvedViteConfig.root,
|
|
1394
|
+
clientOutputDirectory
|
|
1395
|
+
),
|
|
1396
|
+
auxiliaryWorkers: []
|
|
1397
|
+
};
|
|
1398
|
+
fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
|
|
1399
|
+
} else {
|
|
1400
|
+
const workerConfigPaths = Object.fromEntries(
|
|
1401
|
+
Object.keys(resolvedPluginConfig.workers).map((environmentName) => {
|
|
1402
|
+
const outputDirectory = resolvedViteConfig.environments[environmentName]?.build.outDir;
|
|
1403
|
+
assert2(
|
|
1404
|
+
outputDirectory,
|
|
1405
|
+
`Unexpected error: ${environmentName} environment output directory is undefined`
|
|
1406
|
+
);
|
|
1407
|
+
return [
|
|
1408
|
+
environmentName,
|
|
1409
|
+
getRelativePathToWorkerConfig(
|
|
1410
|
+
deployConfigDirectory,
|
|
1411
|
+
resolvedViteConfig.root,
|
|
1412
|
+
outputDirectory
|
|
1413
|
+
)
|
|
1414
|
+
];
|
|
1415
|
+
})
|
|
1416
|
+
);
|
|
1417
|
+
const { entryWorkerEnvironmentName } = resolvedPluginConfig;
|
|
1418
|
+
const configPath = workerConfigPaths[entryWorkerEnvironmentName];
|
|
1419
|
+
assert2(
|
|
1420
|
+
configPath,
|
|
1421
|
+
`Unexpected error: ${entryWorkerEnvironmentName} environment output directory is undefined`
|
|
1422
|
+
);
|
|
1423
|
+
const auxiliaryWorkers = Object.entries(workerConfigPaths).filter(
|
|
1424
|
+
([environmentName]) => environmentName !== entryWorkerEnvironmentName
|
|
1425
|
+
).map(([_, configPath2]) => ({ configPath: configPath2 }));
|
|
1426
|
+
const deployConfig = { configPath, auxiliaryWorkers };
|
|
1427
|
+
fs.writeFileSync(deployConfigPath, JSON.stringify(deployConfig));
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
// src/dev.ts
|
|
1432
|
+
import assert3 from "node:assert";
|
|
1433
|
+
|
|
1434
|
+
// src/constants.ts
|
|
1435
|
+
var ROUTER_WORKER_NAME = "__router-worker__";
|
|
1436
|
+
var ASSET_WORKER_NAME = "__asset-worker__";
|
|
1437
|
+
var ASSET_WORKERS_COMPATIBILITY_DATE = "2024-10-04";
|
|
1438
|
+
|
|
1439
|
+
// src/dev.ts
|
|
1440
|
+
function getDevEntryWorker(resolvedPluginConfig, miniflare) {
|
|
1441
|
+
const entryWorkerConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config : resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
|
|
1442
|
+
assert3(entryWorkerConfig, "Unexpected error: No entry worker configuration");
|
|
1443
|
+
return entryWorkerConfig.assets ? miniflare.getWorker(ROUTER_WORKER_NAME) : miniflare.getWorker(entryWorkerConfig.name);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// src/miniflare-options.ts
|
|
1447
|
+
import assert4 from "node:assert";
|
|
1448
|
+
import * as fs2 from "node:fs";
|
|
1449
|
+
import * as fsp from "node:fs/promises";
|
|
1450
|
+
import * as path3 from "node:path";
|
|
1451
|
+
import { fileURLToPath } from "node:url";
|
|
1452
|
+
import { Log, LogLevel, Response as MiniflareResponse } from "miniflare";
|
|
1453
|
+
import "vite";
|
|
1454
|
+
import {
|
|
1455
|
+
unstable_getMiniflareWorkerOptions,
|
|
1456
|
+
unstable_readConfig
|
|
1457
|
+
} from "wrangler";
|
|
1458
|
+
function getPersistence(root, persistState) {
|
|
1459
|
+
if (persistState === false) {
|
|
1460
|
+
return {};
|
|
1461
|
+
}
|
|
1462
|
+
const defaultPersistPath = ".wrangler/state";
|
|
1463
|
+
const persistPath = path3.resolve(
|
|
1464
|
+
root,
|
|
1465
|
+
typeof persistState === "object" ? persistState.path : defaultPersistPath,
|
|
1466
|
+
"v3"
|
|
1467
|
+
);
|
|
1468
|
+
return {
|
|
1469
|
+
cachePersist: path3.join(persistPath, "cache"),
|
|
1470
|
+
d1Persist: path3.join(persistPath, "d1"),
|
|
1471
|
+
durableObjectsPersist: path3.join(persistPath, "do"),
|
|
1472
|
+
kvPersist: path3.join(persistPath, "kv"),
|
|
1473
|
+
r2Persist: path3.join(persistPath, "r2"),
|
|
1474
|
+
workflowsPersist: path3.join(persistPath, "workflows")
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1477
|
+
function missingWorkerErrorMessage(workerName) {
|
|
1478
|
+
return `${workerName} does not match a worker name.`;
|
|
1479
|
+
}
|
|
1480
|
+
function getWorkerToWorkerEntrypointNamesMap(workers) {
|
|
1481
|
+
const workerToWorkerEntrypointNamesMap = new Map(
|
|
1482
|
+
workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
|
|
1483
|
+
);
|
|
1484
|
+
for (const worker of workers) {
|
|
1485
|
+
for (const value of Object.values(worker.serviceBindings ?? {})) {
|
|
1486
|
+
if (typeof value === "object" && "name" in value && typeof value.name === "string" && value.entrypoint !== void 0 && value.entrypoint !== "default") {
|
|
1487
|
+
const entrypointNames = workerToWorkerEntrypointNamesMap.get(
|
|
1488
|
+
value.name
|
|
1489
|
+
);
|
|
1490
|
+
assert4(entrypointNames, missingWorkerErrorMessage(value.name));
|
|
1491
|
+
entrypointNames.add(value.entrypoint);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
return workerToWorkerEntrypointNamesMap;
|
|
1496
|
+
}
|
|
1497
|
+
function getWorkerToDurableObjectClassNamesMap(workers) {
|
|
1498
|
+
const workerToDurableObjectClassNamesMap = new Map(
|
|
1499
|
+
workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
|
|
1500
|
+
);
|
|
1501
|
+
for (const worker of workers) {
|
|
1502
|
+
for (const value of Object.values(worker.durableObjects ?? {})) {
|
|
1503
|
+
if (typeof value === "string") {
|
|
1504
|
+
const classNames = workerToDurableObjectClassNamesMap.get(worker.name);
|
|
1505
|
+
assert4(classNames, missingWorkerErrorMessage(worker.name));
|
|
1506
|
+
classNames.add(value);
|
|
1507
|
+
} else if (typeof value === "object") {
|
|
1508
|
+
if (value.scriptName) {
|
|
1509
|
+
const classNames = workerToDurableObjectClassNamesMap.get(
|
|
1510
|
+
value.scriptName
|
|
1511
|
+
);
|
|
1512
|
+
assert4(classNames, missingWorkerErrorMessage(value.scriptName));
|
|
1513
|
+
classNames.add(value.className);
|
|
1514
|
+
} else {
|
|
1515
|
+
const classNames = workerToDurableObjectClassNamesMap.get(
|
|
1516
|
+
worker.name
|
|
1517
|
+
);
|
|
1518
|
+
assert4(classNames, missingWorkerErrorMessage(worker.name));
|
|
1519
|
+
classNames.add(value.className);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return workerToDurableObjectClassNamesMap;
|
|
1525
|
+
}
|
|
1526
|
+
function getWorkerToWorkflowEntrypointClassNamesMap(workers) {
|
|
1527
|
+
const workerToWorkflowEntrypointClassNamesMap = new Map(
|
|
1528
|
+
workers.map((workerOptions) => [workerOptions.name, /* @__PURE__ */ new Set()])
|
|
1529
|
+
);
|
|
1530
|
+
for (const worker of workers) {
|
|
1531
|
+
for (const value of Object.values(worker.workflows ?? {})) {
|
|
1532
|
+
if (value.scriptName) {
|
|
1533
|
+
const classNames = workerToWorkflowEntrypointClassNamesMap.get(
|
|
1534
|
+
value.scriptName
|
|
1535
|
+
);
|
|
1536
|
+
assert4(classNames, missingWorkerErrorMessage(value.scriptName));
|
|
1537
|
+
classNames.add(value.className);
|
|
1538
|
+
} else {
|
|
1539
|
+
const classNames = workerToWorkflowEntrypointClassNamesMap.get(
|
|
1540
|
+
worker.name
|
|
1541
|
+
);
|
|
1542
|
+
assert4(classNames, missingWorkerErrorMessage(worker.name));
|
|
1543
|
+
classNames.add(value.className);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
return workerToWorkflowEntrypointClassNamesMap;
|
|
1548
|
+
}
|
|
1549
|
+
var miniflareModulesRoot = process.platform === "win32" ? "Z:\\" : "/";
|
|
1550
|
+
var ROUTER_WORKER_PATH = "./asset-workers/router-worker.js";
|
|
1551
|
+
var ASSET_WORKER_PATH = "./asset-workers/asset-worker.js";
|
|
1552
|
+
var WRAPPER_PATH = "__VITE_WORKER_ENTRY__";
|
|
1553
|
+
var RUNNER_PATH = "./runner-worker/index.js";
|
|
1554
|
+
function getEntryWorkerConfig(resolvedPluginConfig) {
|
|
1555
|
+
if (resolvedPluginConfig.type === "assets-only") {
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
return resolvedPluginConfig.workers[resolvedPluginConfig.entryWorkerEnvironmentName];
|
|
1559
|
+
}
|
|
1560
|
+
function getDevMiniflareOptions(resolvedPluginConfig, viteDevServer) {
|
|
1561
|
+
const resolvedViteConfig = viteDevServer.config;
|
|
1562
|
+
const entryWorkerConfig = getEntryWorkerConfig(resolvedPluginConfig);
|
|
1563
|
+
const assetsConfig = resolvedPluginConfig.type === "assets-only" ? resolvedPluginConfig.config.assets : entryWorkerConfig?.assets;
|
|
1564
|
+
const assetWorkers = [
|
|
1565
|
+
{
|
|
1566
|
+
name: ROUTER_WORKER_NAME,
|
|
1567
|
+
compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
|
|
1568
|
+
modulesRoot: miniflareModulesRoot,
|
|
1569
|
+
modules: [
|
|
1570
|
+
{
|
|
1571
|
+
type: "ESModule",
|
|
1572
|
+
path: path3.join(miniflareModulesRoot, ROUTER_WORKER_PATH),
|
|
1573
|
+
contents: fs2.readFileSync(
|
|
1574
|
+
fileURLToPath(new URL(ROUTER_WORKER_PATH, import.meta.url))
|
|
1575
|
+
)
|
|
1576
|
+
}
|
|
1577
|
+
],
|
|
1578
|
+
bindings: {
|
|
1579
|
+
CONFIG: {
|
|
1580
|
+
has_user_worker: resolvedPluginConfig.type === "workers"
|
|
1581
|
+
}
|
|
1582
|
+
},
|
|
1583
|
+
serviceBindings: {
|
|
1584
|
+
ASSET_WORKER: ASSET_WORKER_NAME,
|
|
1585
|
+
...entryWorkerConfig ? { USER_WORKER: entryWorkerConfig.name } : {}
|
|
1586
|
+
}
|
|
1587
|
+
},
|
|
1588
|
+
{
|
|
1589
|
+
name: ASSET_WORKER_NAME,
|
|
1590
|
+
compatibilityDate: ASSET_WORKERS_COMPATIBILITY_DATE,
|
|
1591
|
+
modulesRoot: miniflareModulesRoot,
|
|
1592
|
+
modules: [
|
|
1593
|
+
{
|
|
1594
|
+
type: "ESModule",
|
|
1595
|
+
path: path3.join(miniflareModulesRoot, ASSET_WORKER_PATH),
|
|
1596
|
+
contents: fs2.readFileSync(
|
|
1597
|
+
fileURLToPath(new URL(ASSET_WORKER_PATH, import.meta.url))
|
|
1598
|
+
)
|
|
1599
|
+
}
|
|
1600
|
+
],
|
|
1601
|
+
bindings: {
|
|
1602
|
+
CONFIG: {
|
|
1603
|
+
...assetsConfig?.html_handling ? { html_handling: assetsConfig.html_handling } : {},
|
|
1604
|
+
...assetsConfig?.not_found_handling ? { not_found_handling: assetsConfig.not_found_handling } : {}
|
|
1605
|
+
}
|
|
1606
|
+
},
|
|
1607
|
+
serviceBindings: {
|
|
1608
|
+
__VITE_ASSET_EXISTS__: async (request) => {
|
|
1609
|
+
const { pathname } = new URL(request.url);
|
|
1610
|
+
const filePath = path3.join(resolvedViteConfig.root, pathname);
|
|
1611
|
+
let exists;
|
|
1612
|
+
try {
|
|
1613
|
+
exists = fs2.statSync(filePath).isFile();
|
|
1614
|
+
} catch (error) {
|
|
1615
|
+
exists = false;
|
|
1616
|
+
}
|
|
1617
|
+
return MiniflareResponse.json(exists);
|
|
1618
|
+
},
|
|
1619
|
+
__VITE_FETCH_ASSET__: async (request) => {
|
|
1620
|
+
const { pathname } = new URL(request.url);
|
|
1621
|
+
const filePath = path3.join(resolvedViteConfig.root, pathname);
|
|
1622
|
+
try {
|
|
1623
|
+
let html = await fsp.readFile(filePath, "utf-8");
|
|
1624
|
+
html = await viteDevServer.transformIndexHtml(pathname, html);
|
|
1625
|
+
return new MiniflareResponse(html, {
|
|
1626
|
+
headers: { "Content-Type": "text/html" }
|
|
1627
|
+
});
|
|
1628
|
+
} catch (error) {
|
|
1629
|
+
throw new Error(`Unexpected error. Failed to load ${pathname}`);
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
];
|
|
1635
|
+
const userWorkers = resolvedPluginConfig.type === "workers" ? Object.entries(resolvedPluginConfig.workers).map(
|
|
1636
|
+
([environmentName, workerConfig]) => {
|
|
1637
|
+
const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions({
|
|
1638
|
+
...workerConfig,
|
|
1639
|
+
assets: void 0
|
|
1640
|
+
});
|
|
1641
|
+
const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
|
|
1642
|
+
return {
|
|
1643
|
+
...workerOptions,
|
|
1644
|
+
// We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
|
|
1645
|
+
name: workerConfig.name,
|
|
1646
|
+
modulesRoot: miniflareModulesRoot,
|
|
1647
|
+
unsafeEvalBinding: "__VITE_UNSAFE_EVAL__",
|
|
1648
|
+
bindings: {
|
|
1649
|
+
...workerOptions.bindings,
|
|
1650
|
+
__VITE_ROOT__: resolvedViteConfig.root,
|
|
1651
|
+
__VITE_ENTRY_PATH__: workerConfig.main
|
|
1652
|
+
},
|
|
1653
|
+
serviceBindings: {
|
|
1654
|
+
...workerOptions.serviceBindings,
|
|
1655
|
+
...environmentName === resolvedPluginConfig.entryWorkerEnvironmentName && workerConfig.assets?.binding ? {
|
|
1656
|
+
[workerConfig.assets.binding]: ASSET_WORKER_NAME
|
|
1657
|
+
} : {},
|
|
1658
|
+
__VITE_INVOKE_MODULE__: async (request) => {
|
|
1659
|
+
const payload = await request.json();
|
|
1660
|
+
const invokePayloadData = payload.data;
|
|
1661
|
+
assert4(
|
|
1662
|
+
invokePayloadData.name === "fetchModule",
|
|
1663
|
+
`Invalid invoke event: ${invokePayloadData.name}`
|
|
1664
|
+
);
|
|
1665
|
+
const [moduleId] = invokePayloadData.data;
|
|
1666
|
+
if (moduleId.startsWith("cloudflare:")) {
|
|
1667
|
+
const result2 = {
|
|
1668
|
+
externalize: moduleId,
|
|
1669
|
+
type: "builtin"
|
|
1670
|
+
};
|
|
1671
|
+
return new MiniflareResponse(JSON.stringify({ result: result2 }));
|
|
1672
|
+
}
|
|
1673
|
+
const devEnvironment = viteDevServer.environments[environmentName];
|
|
1674
|
+
const result = await devEnvironment.hot.handleInvoke(payload);
|
|
1675
|
+
return new MiniflareResponse(JSON.stringify(result));
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
) : [];
|
|
1681
|
+
const workerToWorkerEntrypointNamesMap = getWorkerToWorkerEntrypointNamesMap(userWorkers);
|
|
1682
|
+
const workerToDurableObjectClassNamesMap = getWorkerToDurableObjectClassNamesMap(userWorkers);
|
|
1683
|
+
const workerToWorkflowEntrypointClassNamesMap = getWorkerToWorkflowEntrypointClassNamesMap(userWorkers);
|
|
1684
|
+
const logger = new ViteMiniflareLogger(resolvedViteConfig);
|
|
1685
|
+
return {
|
|
1686
|
+
log: logger,
|
|
1687
|
+
handleRuntimeStdio(stdout, stderr) {
|
|
1688
|
+
const decoder = new TextDecoder();
|
|
1689
|
+
stdout.forEach((data) => logger.info(decoder.decode(data)));
|
|
1690
|
+
stderr.forEach(
|
|
1691
|
+
(error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
|
|
1692
|
+
);
|
|
1693
|
+
},
|
|
1694
|
+
...getPersistence(
|
|
1695
|
+
resolvedViteConfig.root,
|
|
1696
|
+
resolvedPluginConfig.persistState
|
|
1697
|
+
),
|
|
1698
|
+
workers: [
|
|
1699
|
+
...assetWorkers,
|
|
1700
|
+
...userWorkers.map((workerOptions) => {
|
|
1701
|
+
const wrappers = [
|
|
1702
|
+
`import { createWorkerEntrypointWrapper, createDurableObjectWrapper, createWorkflowEntrypointWrapper } from '${RUNNER_PATH}';`,
|
|
1703
|
+
`export default createWorkerEntrypointWrapper('default');`
|
|
1704
|
+
];
|
|
1705
|
+
const workerEntrypointNames = workerToWorkerEntrypointNamesMap.get(
|
|
1706
|
+
workerOptions.name
|
|
1707
|
+
);
|
|
1708
|
+
assert4(
|
|
1709
|
+
workerEntrypointNames,
|
|
1710
|
+
`WorkerEntrypoint names not found for worker ${workerOptions.name}`
|
|
1711
|
+
);
|
|
1712
|
+
for (const entrypointName of [...workerEntrypointNames].sort()) {
|
|
1713
|
+
wrappers.push(
|
|
1714
|
+
`export const ${entrypointName} = createWorkerEntrypointWrapper('${entrypointName}');`
|
|
1715
|
+
);
|
|
1716
|
+
}
|
|
1717
|
+
const durableObjectClassNames = workerToDurableObjectClassNamesMap.get(
|
|
1718
|
+
workerOptions.name
|
|
1719
|
+
);
|
|
1720
|
+
assert4(
|
|
1721
|
+
durableObjectClassNames,
|
|
1722
|
+
`DurableObject class names not found for worker ${workerOptions.name}`
|
|
1723
|
+
);
|
|
1724
|
+
for (const className of [...durableObjectClassNames].sort()) {
|
|
1725
|
+
wrappers.push(
|
|
1726
|
+
`export const ${className} = createDurableObjectWrapper('${className}');`
|
|
1727
|
+
);
|
|
1728
|
+
}
|
|
1729
|
+
const workflowEntrypointClassNames = workerToWorkflowEntrypointClassNamesMap.get(workerOptions.name);
|
|
1730
|
+
assert4(
|
|
1731
|
+
workflowEntrypointClassNames,
|
|
1732
|
+
`WorkflowEntrypoint class names not found for worker ${workerOptions.name}`
|
|
1733
|
+
);
|
|
1734
|
+
for (const className of [...workflowEntrypointClassNames].sort()) {
|
|
1735
|
+
wrappers.push(
|
|
1736
|
+
`export const ${className} = createWorkflowEntrypointWrapper('${className}');`
|
|
1737
|
+
);
|
|
1738
|
+
}
|
|
1739
|
+
return {
|
|
1740
|
+
...workerOptions,
|
|
1741
|
+
modules: [
|
|
1742
|
+
{
|
|
1743
|
+
type: "ESModule",
|
|
1744
|
+
path: path3.join(miniflareModulesRoot, WRAPPER_PATH),
|
|
1745
|
+
contents: wrappers.join("\n")
|
|
1746
|
+
},
|
|
1747
|
+
{
|
|
1748
|
+
type: "ESModule",
|
|
1749
|
+
path: path3.join(miniflareModulesRoot, RUNNER_PATH),
|
|
1750
|
+
contents: fs2.readFileSync(
|
|
1751
|
+
fileURLToPath(new URL(RUNNER_PATH, import.meta.url))
|
|
1752
|
+
)
|
|
1753
|
+
}
|
|
1754
|
+
]
|
|
1755
|
+
};
|
|
1756
|
+
})
|
|
1757
|
+
]
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
function getPreviewMiniflareOptions(vitePreviewServer, persistState) {
|
|
1761
|
+
const resolvedViteConfig = vitePreviewServer.config;
|
|
1762
|
+
const configPaths = getWorkerConfigPaths(resolvedViteConfig.root);
|
|
1763
|
+
const workerConfigs = configPaths.map(
|
|
1764
|
+
(configPath) => unstable_readConfig({ config: configPath })
|
|
1765
|
+
);
|
|
1766
|
+
const workers = workerConfigs.map((config) => {
|
|
1767
|
+
const miniflareWorkerOptions = unstable_getMiniflareWorkerOptions(config);
|
|
1768
|
+
const { ratelimits, ...workerOptions } = miniflareWorkerOptions.workerOptions;
|
|
1769
|
+
return {
|
|
1770
|
+
...workerOptions,
|
|
1771
|
+
// We have to add the name again because `unstable_getMiniflareWorkerOptions` sets it to `undefined`
|
|
1772
|
+
name: config.name,
|
|
1773
|
+
modules: true,
|
|
1774
|
+
...miniflareWorkerOptions.main ? { scriptPath: miniflareWorkerOptions.main } : { script: "" }
|
|
1775
|
+
};
|
|
1776
|
+
});
|
|
1777
|
+
const logger = new ViteMiniflareLogger(resolvedViteConfig);
|
|
1778
|
+
return {
|
|
1779
|
+
log: logger,
|
|
1780
|
+
handleRuntimeStdio(stdout, stderr) {
|
|
1781
|
+
const decoder = new TextDecoder();
|
|
1782
|
+
stdout.forEach((data) => logger.info(decoder.decode(data)));
|
|
1783
|
+
stderr.forEach(
|
|
1784
|
+
(error) => logger.logWithLevel(LogLevel.ERROR, decoder.decode(error))
|
|
1785
|
+
);
|
|
1786
|
+
},
|
|
1787
|
+
...getPersistence(resolvedViteConfig.root, persistState),
|
|
1788
|
+
workers
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
var ViteMiniflareLogger = class extends Log {
|
|
1792
|
+
logger;
|
|
1793
|
+
constructor(config) {
|
|
1794
|
+
super(miniflareLogLevelFromViteLogLevel(config.logLevel));
|
|
1795
|
+
this.logger = config.logger;
|
|
1796
|
+
}
|
|
1797
|
+
logWithLevel(level, message) {
|
|
1798
|
+
if (/^Ready on http/.test(message)) {
|
|
1799
|
+
level = LogLevel.DEBUG;
|
|
1800
|
+
}
|
|
1801
|
+
switch (level) {
|
|
1802
|
+
case LogLevel.ERROR:
|
|
1803
|
+
return this.logger.error(message);
|
|
1804
|
+
case LogLevel.WARN:
|
|
1805
|
+
return this.logger.warn(message);
|
|
1806
|
+
case LogLevel.INFO:
|
|
1807
|
+
return this.logger.info(message);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
};
|
|
1811
|
+
function miniflareLogLevelFromViteLogLevel(level = "info") {
|
|
1812
|
+
switch (level) {
|
|
1813
|
+
case "error":
|
|
1814
|
+
return LogLevel.ERROR;
|
|
1815
|
+
case "warn":
|
|
1816
|
+
return LogLevel.WARN;
|
|
1817
|
+
case "info":
|
|
1818
|
+
return LogLevel.INFO;
|
|
1819
|
+
case "silent":
|
|
1820
|
+
return LogLevel.NONE;
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
// src/plugin-config.ts
|
|
1825
|
+
import assert6 from "node:assert";
|
|
1826
|
+
import * as path5 from "node:path";
|
|
1827
|
+
import * as vite5 from "vite";
|
|
1828
|
+
|
|
1829
|
+
// src/workers-configs.ts
|
|
1830
|
+
import assert5 from "node:assert";
|
|
1831
|
+
import * as fs3 from "node:fs";
|
|
1832
|
+
import * as path4 from "node:path";
|
|
1833
|
+
import { unstable_readConfig as unstable_readConfig2 } from "wrangler";
|
|
1834
|
+
|
|
1835
|
+
// package.json
|
|
1836
|
+
var name = "@cloudflare/vite-plugin";
|
|
1837
|
+
|
|
1838
|
+
// src/workers-configs.ts
|
|
1839
|
+
var nonApplicableWorkerConfigs = {
|
|
1840
|
+
/**
|
|
1841
|
+
* Object containing configs that have a vite replacement, the object's field contain details about the config's replacement
|
|
1842
|
+
*/
|
|
1843
|
+
replacedByVite: {
|
|
1844
|
+
alias: {
|
|
1845
|
+
viteReplacement: "resolve.alias",
|
|
1846
|
+
viteDocs: "https://vite.dev/config/shared-options.html#resolve-alias"
|
|
1847
|
+
},
|
|
1848
|
+
define: {
|
|
1849
|
+
viteReplacement: "define",
|
|
1850
|
+
viteDocs: "https://vite.dev/config/shared-options.html#define"
|
|
1851
|
+
},
|
|
1852
|
+
minify: {
|
|
1853
|
+
viteReplacement: "build.minify",
|
|
1854
|
+
viteDocs: "https://vite.dev/config/build-options.html#build-minify"
|
|
1855
|
+
}
|
|
1856
|
+
},
|
|
1857
|
+
/**
|
|
1858
|
+
* All the configs that are not relevant when using Vite (meaning that in the context of a Vite
|
|
1859
|
+
* application they lose their purpose/meaning)
|
|
1860
|
+
*/
|
|
1861
|
+
notRelevant: [
|
|
1862
|
+
"base_dir",
|
|
1863
|
+
"build",
|
|
1864
|
+
"find_additional_modules",
|
|
1865
|
+
"no_bundle",
|
|
1866
|
+
"node_compat",
|
|
1867
|
+
"preserve_file_names",
|
|
1868
|
+
"site",
|
|
1869
|
+
"tsconfig",
|
|
1870
|
+
"upload_source_maps"
|
|
1871
|
+
],
|
|
1872
|
+
/**
|
|
1873
|
+
* All the configs that get overridden by our plugin
|
|
1874
|
+
*/
|
|
1875
|
+
overridden: ["rules"]
|
|
1876
|
+
};
|
|
1877
|
+
var nullableNonApplicable = [
|
|
1878
|
+
"alias",
|
|
1879
|
+
"base_dir",
|
|
1880
|
+
"find_additional_modules",
|
|
1881
|
+
"minify",
|
|
1882
|
+
"no_bundle",
|
|
1883
|
+
"node_compat",
|
|
1884
|
+
"preserve_file_names",
|
|
1885
|
+
"site",
|
|
1886
|
+
"tsconfig",
|
|
1887
|
+
"upload_source_maps"
|
|
1888
|
+
];
|
|
1889
|
+
function readWorkerConfig(configPath, env2) {
|
|
1890
|
+
const nonApplicable = {
|
|
1891
|
+
replacedByVite: /* @__PURE__ */ new Set(),
|
|
1892
|
+
notRelevant: /* @__PURE__ */ new Set(),
|
|
1893
|
+
overridden: /* @__PURE__ */ new Set()
|
|
1894
|
+
};
|
|
1895
|
+
const config = unstable_readConfig2({ config: configPath, env: env2 }, {});
|
|
1896
|
+
const raw = structuredClone(config);
|
|
1897
|
+
nullableNonApplicable.forEach((prop) => {
|
|
1898
|
+
if (config[prop] !== void 0) {
|
|
1899
|
+
if (isReplacedByVite(prop)) {
|
|
1900
|
+
nonApplicable.replacedByVite.add(prop);
|
|
1901
|
+
}
|
|
1902
|
+
if (isNotRelevant(prop)) {
|
|
1903
|
+
nonApplicable.notRelevant.add(prop);
|
|
1904
|
+
}
|
|
1905
|
+
if (isOverridden(prop)) {
|
|
1906
|
+
nonApplicable.overridden.add(prop);
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
delete config[prop];
|
|
1910
|
+
});
|
|
1911
|
+
if (config.build && (config.build.command || config.build.cwd)) {
|
|
1912
|
+
nonApplicable.notRelevant.add("build");
|
|
1913
|
+
}
|
|
1914
|
+
delete config["build"];
|
|
1915
|
+
if (config.define && Object.keys(config.define).length > 0) {
|
|
1916
|
+
nonApplicable.replacedByVite.add("define");
|
|
1917
|
+
}
|
|
1918
|
+
delete config["define"];
|
|
1919
|
+
if (config.rules.length > 0) {
|
|
1920
|
+
nonApplicable.overridden.add("rules");
|
|
1921
|
+
}
|
|
1922
|
+
return {
|
|
1923
|
+
raw,
|
|
1924
|
+
nonApplicable,
|
|
1925
|
+
config
|
|
1926
|
+
};
|
|
1927
|
+
}
|
|
1928
|
+
function getWarningForWorkersConfigs(configs) {
|
|
1929
|
+
if (!("auxiliaryWorkers" in configs) || configs.auxiliaryWorkers.length === 0) {
|
|
1930
|
+
const nonApplicableLines = getWorkerNonApplicableWarnLines(
|
|
1931
|
+
configs.entryWorker,
|
|
1932
|
+
` - `
|
|
1933
|
+
);
|
|
1934
|
+
if (nonApplicableLines.length === 0) {
|
|
1935
|
+
return;
|
|
1936
|
+
}
|
|
1937
|
+
const lines2 = [
|
|
1938
|
+
`
|
|
1939
|
+
|
|
1940
|
+
\x1B[43mWARNING\x1B[0m: your worker config${configs.entryWorker.config.configPath ? ` (at \`${path4.relative("", configs.entryWorker.config.configPath)}\`)` : ""} contains the following configuration options which are ignored since they are not applicable when using Vite:`
|
|
1941
|
+
];
|
|
1942
|
+
nonApplicableLines.forEach((line) => lines2.push(line));
|
|
1943
|
+
lines2.push("");
|
|
1944
|
+
return lines2.join("\n");
|
|
1945
|
+
}
|
|
1946
|
+
const lines = [];
|
|
1947
|
+
const processWorkerConfig = (workerConfig, isEntryWorker = false) => {
|
|
1948
|
+
const nonApplicableLines = getWorkerNonApplicableWarnLines(
|
|
1949
|
+
workerConfig,
|
|
1950
|
+
` - `
|
|
1951
|
+
);
|
|
1952
|
+
if (nonApplicableLines.length > 0) {
|
|
1953
|
+
lines.push(
|
|
1954
|
+
` - (${isEntryWorker ? "entry" : "auxiliary"}) worker${workerConfig.config.name ? ` "${workerConfig.config.name}"` : ""}${workerConfig.config.configPath ? ` (config at \`${path4.relative("", workerConfig.config.configPath)}\`)` : ""}`
|
|
1955
|
+
);
|
|
1956
|
+
nonApplicableLines.forEach((line) => lines.push(line));
|
|
1957
|
+
}
|
|
1958
|
+
};
|
|
1959
|
+
processWorkerConfig(configs.entryWorker, true);
|
|
1960
|
+
configs.auxiliaryWorkers.forEach((config) => processWorkerConfig(config));
|
|
1961
|
+
if (lines.length === 0) {
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
return [
|
|
1965
|
+
"\n\x1B[43mWARNING\x1B[0m: your workers configs contain configuration options which are ignored since they are not applicable when using Vite:",
|
|
1966
|
+
...lines,
|
|
1967
|
+
""
|
|
1968
|
+
].join("\n");
|
|
1969
|
+
}
|
|
1970
|
+
function getWorkerNonApplicableWarnLines(workerConfig, linePrefix) {
|
|
1971
|
+
const lines = [];
|
|
1972
|
+
const { replacedByVite, notRelevant, overridden } = workerConfig.nonApplicable;
|
|
1973
|
+
for (const config of replacedByVite) {
|
|
1974
|
+
lines.push(
|
|
1975
|
+
`${linePrefix}\`${config}\` which is replaced by Vite's \`${nonApplicableWorkerConfigs.replacedByVite[config].viteReplacement}\` (docs: ${nonApplicableWorkerConfigs.replacedByVite[config].viteDocs})`
|
|
1976
|
+
);
|
|
1977
|
+
}
|
|
1978
|
+
if (notRelevant.size > 0)
|
|
1979
|
+
lines.push(
|
|
1980
|
+
`${linePrefix}${[...notRelevant].map((config) => `\`${config}\``).join(", ")} which ${notRelevant.size > 1 ? "are" : "is"} not relevant in the context of a Vite project`
|
|
1981
|
+
);
|
|
1982
|
+
if (overridden.size > 0)
|
|
1983
|
+
lines.push(
|
|
1984
|
+
`${linePrefix}${[...overridden].map((config) => `\`${config}\``).join(", ")} which ${overridden.size > 1 ? "are" : "is"} overridden by \`${name}\``
|
|
1985
|
+
);
|
|
1986
|
+
return lines;
|
|
1987
|
+
}
|
|
1988
|
+
function isReplacedByVite(configName) {
|
|
1989
|
+
return configName in nonApplicableWorkerConfigs["replacedByVite"];
|
|
1990
|
+
}
|
|
1991
|
+
function isNotRelevant(configName) {
|
|
1992
|
+
return nonApplicableWorkerConfigs.notRelevant.includes(configName);
|
|
1993
|
+
}
|
|
1994
|
+
function isOverridden(configName) {
|
|
1995
|
+
return nonApplicableWorkerConfigs.overridden.includes(configName);
|
|
1996
|
+
}
|
|
1997
|
+
function missingFieldErrorMessage(field, configPath, env2) {
|
|
1998
|
+
return `No ${field} field provided in '${configPath}'${env2 ? ` for '${env2}' environment` : ""}`;
|
|
1999
|
+
}
|
|
2000
|
+
function getWorkerConfig(configPath, env2, opts) {
|
|
2001
|
+
if (opts?.visitedConfigPaths?.has(configPath)) {
|
|
2002
|
+
throw new Error(`Duplicate Wrangler config path found: ${configPath}`);
|
|
2003
|
+
}
|
|
2004
|
+
const { raw, config, nonApplicable } = readWorkerConfig(configPath, env2);
|
|
2005
|
+
opts?.visitedConfigPaths?.add(configPath);
|
|
2006
|
+
assert5(
|
|
2007
|
+
config.topLevelName,
|
|
2008
|
+
missingFieldErrorMessage(`top-level 'name'`, configPath, env2)
|
|
2009
|
+
);
|
|
2010
|
+
assert5(config.name, missingFieldErrorMessage(`'name'`, configPath, env2));
|
|
2011
|
+
assert5(
|
|
2012
|
+
config.compatibility_date,
|
|
2013
|
+
missingFieldErrorMessage(`'compatibility_date'`, configPath, env2)
|
|
2014
|
+
);
|
|
2015
|
+
if (opts?.isEntryWorker && !config.main) {
|
|
2016
|
+
assert5(
|
|
2017
|
+
config.assets,
|
|
2018
|
+
missingFieldErrorMessage(`'main' or 'assets'`, configPath, env2)
|
|
2019
|
+
);
|
|
2020
|
+
return {
|
|
2021
|
+
type: "assets-only",
|
|
2022
|
+
raw,
|
|
2023
|
+
config: {
|
|
2024
|
+
...config,
|
|
2025
|
+
topLevelName: config.topLevelName,
|
|
2026
|
+
name: config.name,
|
|
2027
|
+
compatibility_date: config.compatibility_date,
|
|
2028
|
+
assets: config.assets
|
|
2029
|
+
},
|
|
2030
|
+
nonApplicable
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
assert5(config.main, missingFieldErrorMessage(`'main'`, configPath, env2));
|
|
2034
|
+
return {
|
|
2035
|
+
type: "worker",
|
|
2036
|
+
raw,
|
|
2037
|
+
config: {
|
|
2038
|
+
...config,
|
|
2039
|
+
topLevelName: config.topLevelName,
|
|
2040
|
+
name: config.name,
|
|
2041
|
+
compatibility_date: config.compatibility_date,
|
|
2042
|
+
main: config.main
|
|
2043
|
+
},
|
|
2044
|
+
nonApplicable
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
function findWranglerConfig(root) {
|
|
2048
|
+
for (const extension of ["json", "jsonc", "toml"]) {
|
|
2049
|
+
const configPath = path4.join(root, `wrangler.${extension}`);
|
|
2050
|
+
if (fs3.existsSync(configPath)) {
|
|
2051
|
+
return configPath;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// src/plugin-config.ts
|
|
2057
|
+
function workerNameToEnvironmentName(workerName) {
|
|
2058
|
+
return workerName.replaceAll("-", "_");
|
|
2059
|
+
}
|
|
2060
|
+
function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
|
|
2061
|
+
const configPaths = /* @__PURE__ */ new Set();
|
|
2062
|
+
const persistState = pluginConfig.persistState ?? true;
|
|
2063
|
+
const root = userConfig.root ? path5.resolve(userConfig.root) : process.cwd();
|
|
2064
|
+
const { CLOUDFLARE_ENV } = vite5.loadEnv(viteEnv.mode, root, "");
|
|
2065
|
+
const configPath = pluginConfig.configPath ? path5.resolve(root, pluginConfig.configPath) : findWranglerConfig(root);
|
|
2066
|
+
assert6(
|
|
2067
|
+
configPath,
|
|
2068
|
+
`Config not found. Have you created a wrangler.json(c) or wrangler.toml file?`
|
|
2069
|
+
);
|
|
2070
|
+
const entryWorkerResolvedConfig = getWorkerConfig(
|
|
2071
|
+
configPath,
|
|
2072
|
+
CLOUDFLARE_ENV,
|
|
2073
|
+
{
|
|
2074
|
+
visitedConfigPaths: configPaths,
|
|
2075
|
+
isEntryWorker: true
|
|
2076
|
+
}
|
|
2077
|
+
);
|
|
2078
|
+
if (entryWorkerResolvedConfig.type === "assets-only") {
|
|
2079
|
+
return {
|
|
2080
|
+
type: "assets-only",
|
|
2081
|
+
config: entryWorkerResolvedConfig.config,
|
|
2082
|
+
configPaths,
|
|
2083
|
+
persistState,
|
|
2084
|
+
rawConfigs: {
|
|
2085
|
+
entryWorker: entryWorkerResolvedConfig
|
|
2086
|
+
}
|
|
2087
|
+
};
|
|
2088
|
+
}
|
|
2089
|
+
const entryWorkerConfig = entryWorkerResolvedConfig.config;
|
|
2090
|
+
const entryWorkerEnvironmentName = pluginConfig.viteEnvironment?.name ?? workerNameToEnvironmentName(entryWorkerConfig.topLevelName);
|
|
2091
|
+
const workers = {
|
|
2092
|
+
[entryWorkerEnvironmentName]: entryWorkerConfig
|
|
2093
|
+
};
|
|
2094
|
+
const auxiliaryWorkersResolvedConfigs = [];
|
|
2095
|
+
for (const auxiliaryWorker of pluginConfig.auxiliaryWorkers ?? []) {
|
|
2096
|
+
const workerResolvedConfig = getWorkerConfig(
|
|
2097
|
+
path5.resolve(root, auxiliaryWorker.configPath),
|
|
2098
|
+
CLOUDFLARE_ENV,
|
|
2099
|
+
{
|
|
2100
|
+
visitedConfigPaths: configPaths
|
|
2101
|
+
}
|
|
2102
|
+
);
|
|
2103
|
+
auxiliaryWorkersResolvedConfigs.push(workerResolvedConfig);
|
|
2104
|
+
assert6(
|
|
2105
|
+
workerResolvedConfig.type === "worker",
|
|
2106
|
+
"Unexpected error: received AssetsOnlyResult with auxiliary workers."
|
|
2107
|
+
);
|
|
2108
|
+
const workerConfig = workerResolvedConfig.config;
|
|
2109
|
+
const workerEnvironmentName = auxiliaryWorker.viteEnvironment?.name ?? workerNameToEnvironmentName(workerConfig.topLevelName);
|
|
2110
|
+
if (workers[workerEnvironmentName]) {
|
|
2111
|
+
throw new Error(
|
|
2112
|
+
`Duplicate Vite environment name found: ${workerEnvironmentName}`
|
|
2113
|
+
);
|
|
2114
|
+
}
|
|
2115
|
+
workers[workerEnvironmentName] = workerConfig;
|
|
2116
|
+
}
|
|
2117
|
+
return {
|
|
2118
|
+
type: "workers",
|
|
2119
|
+
configPaths,
|
|
2120
|
+
persistState,
|
|
2121
|
+
workers,
|
|
2122
|
+
entryWorkerEnvironmentName,
|
|
2123
|
+
rawConfigs: {
|
|
2124
|
+
entryWorker: entryWorkerResolvedConfig,
|
|
2125
|
+
auxiliaryWorkers: auxiliaryWorkersResolvedConfigs
|
|
2126
|
+
}
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
// src/websockets.ts
|
|
2131
|
+
import ws from "ws";
|
|
2132
|
+
function handleWebSocket(httpServer, fetcher, logger) {
|
|
2133
|
+
const nodeWebSocket = new ws.Server({ noServer: true });
|
|
2134
|
+
httpServer.on(
|
|
2135
|
+
"upgrade",
|
|
2136
|
+
async (request, socket, head) => {
|
|
2137
|
+
const url = new URL(request.url ?? "", UNKNOWN_HOST);
|
|
2138
|
+
if (request.headers["sec-websocket-protocol"]?.startsWith("vite")) {
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
2141
|
+
const headers = nodeHeadersToWebHeaders(request.headers);
|
|
2142
|
+
const response = await fetcher(url, {
|
|
2143
|
+
headers,
|
|
2144
|
+
method: request.method
|
|
2145
|
+
});
|
|
2146
|
+
const workerWebSocket = response.webSocket;
|
|
2147
|
+
if (!workerWebSocket) {
|
|
2148
|
+
socket.destroy();
|
|
2149
|
+
return;
|
|
2150
|
+
}
|
|
2151
|
+
nodeWebSocket.handleUpgrade(
|
|
2152
|
+
request,
|
|
2153
|
+
socket,
|
|
2154
|
+
head,
|
|
2155
|
+
async (clientWebSocket) => {
|
|
2156
|
+
workerWebSocket.accept();
|
|
2157
|
+
workerWebSocket.addEventListener("message", (event) => {
|
|
2158
|
+
clientWebSocket.send(event.data);
|
|
2159
|
+
});
|
|
2160
|
+
workerWebSocket.addEventListener("error", (event) => {
|
|
2161
|
+
logger.error(
|
|
2162
|
+
`WebSocket error:
|
|
2163
|
+
${event.error?.stack || event.error?.message}`,
|
|
2164
|
+
{ error: event.error }
|
|
2165
|
+
);
|
|
2166
|
+
});
|
|
2167
|
+
workerWebSocket.addEventListener("close", () => {
|
|
2168
|
+
clientWebSocket.close();
|
|
2169
|
+
});
|
|
2170
|
+
clientWebSocket.on("message", (event) => {
|
|
2171
|
+
workerWebSocket.send(event);
|
|
2172
|
+
});
|
|
2173
|
+
clientWebSocket.on("error", (error) => {
|
|
2174
|
+
logger.error(`WebSocket error:
|
|
2175
|
+
${error.stack || error.message}`, {
|
|
2176
|
+
error
|
|
2177
|
+
});
|
|
2178
|
+
});
|
|
2179
|
+
clientWebSocket.on("close", () => {
|
|
2180
|
+
workerWebSocket.close();
|
|
2181
|
+
});
|
|
2182
|
+
nodeWebSocket.emit("connection", clientWebSocket, request);
|
|
2183
|
+
}
|
|
2184
|
+
);
|
|
2185
|
+
}
|
|
2186
|
+
);
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
// src/index.ts
|
|
2190
|
+
function cloudflare2(pluginConfig = {}) {
|
|
2191
|
+
let resolvedPluginConfig;
|
|
2192
|
+
let resolvedViteConfig;
|
|
2193
|
+
let miniflare;
|
|
2194
|
+
let workersConfigsWarningShown = false;
|
|
2195
|
+
return {
|
|
2196
|
+
name: "vite-plugin-cloudflare",
|
|
2197
|
+
config(userConfig, env2) {
|
|
2198
|
+
if (env2.isPreview) {
|
|
2199
|
+
return { appType: "custom" };
|
|
2200
|
+
}
|
|
2201
|
+
resolvedPluginConfig = resolvePluginConfig(pluginConfig, userConfig, env2);
|
|
2202
|
+
if (!workersConfigsWarningShown) {
|
|
2203
|
+
workersConfigsWarningShown = true;
|
|
2204
|
+
const workersConfigsWarning = getWarningForWorkersConfigs(
|
|
2205
|
+
resolvedPluginConfig.rawConfigs
|
|
2206
|
+
);
|
|
2207
|
+
if (workersConfigsWarning) {
|
|
2208
|
+
console.warn(workersConfigsWarning);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
return {
|
|
2212
|
+
appType: "custom",
|
|
2213
|
+
resolve: {
|
|
2214
|
+
alias: getNodeCompatAliases()
|
|
2215
|
+
},
|
|
2216
|
+
environments: resolvedPluginConfig.type === "workers" ? {
|
|
2217
|
+
...Object.fromEntries(
|
|
2218
|
+
Object.entries(resolvedPluginConfig.workers).map(
|
|
2219
|
+
([environmentName, workerConfig]) => {
|
|
2220
|
+
return [
|
|
2221
|
+
environmentName,
|
|
2222
|
+
createCloudflareEnvironmentOptions(
|
|
2223
|
+
workerConfig,
|
|
2224
|
+
userConfig,
|
|
2225
|
+
environmentName
|
|
2226
|
+
)
|
|
2227
|
+
];
|
|
2228
|
+
}
|
|
2229
|
+
)
|
|
2230
|
+
),
|
|
2231
|
+
client: {
|
|
2232
|
+
build: {
|
|
2233
|
+
outDir: getOutputDirectory(userConfig, "client")
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
} : void 0,
|
|
2237
|
+
builder: {
|
|
2238
|
+
async buildApp(builder) {
|
|
2239
|
+
const clientEnvironment = builder.environments.client;
|
|
2240
|
+
const defaultHtmlPath = path6.resolve(
|
|
2241
|
+
builder.config.root,
|
|
2242
|
+
"index.html"
|
|
2243
|
+
);
|
|
2244
|
+
if (clientEnvironment && (clientEnvironment.config.build.rollupOptions.input || fs4.existsSync(defaultHtmlPath))) {
|
|
2245
|
+
await builder.build(clientEnvironment);
|
|
2246
|
+
}
|
|
2247
|
+
if (resolvedPluginConfig.type === "workers") {
|
|
2248
|
+
const workerEnvironments = Object.keys(
|
|
2249
|
+
resolvedPluginConfig.workers
|
|
2250
|
+
).map((environmentName) => {
|
|
2251
|
+
const environment = builder.environments[environmentName];
|
|
2252
|
+
assert7(environment, `${environmentName} environment not found`);
|
|
2253
|
+
return environment;
|
|
2254
|
+
});
|
|
2255
|
+
await Promise.all(
|
|
2256
|
+
workerEnvironments.map(
|
|
2257
|
+
(environment) => builder.build(environment)
|
|
2258
|
+
)
|
|
2259
|
+
);
|
|
2260
|
+
}
|
|
2261
|
+
writeDeployConfig(resolvedPluginConfig, resolvedViteConfig);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
};
|
|
2265
|
+
},
|
|
2266
|
+
configResolved(config) {
|
|
2267
|
+
resolvedViteConfig = config;
|
|
2268
|
+
},
|
|
2269
|
+
async resolveId(source) {
|
|
2270
|
+
if (resolvedPluginConfig.type === "assets-only") {
|
|
2271
|
+
return;
|
|
2272
|
+
}
|
|
2273
|
+
const workerConfig = resolvedPluginConfig.workers[this.environment.name];
|
|
2274
|
+
if (!workerConfig) {
|
|
2275
|
+
return;
|
|
2276
|
+
}
|
|
2277
|
+
return resolveNodeCompatId(this.environment, workerConfig, source);
|
|
2278
|
+
},
|
|
2279
|
+
async transform(code, id) {
|
|
2280
|
+
if (resolvedPluginConfig.type === "assets-only") {
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
const workerConfig = resolvedPluginConfig.workers[this.environment.name];
|
|
2284
|
+
if (!workerConfig) {
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
const resolvedId = await this.resolve(workerConfig.main);
|
|
2288
|
+
if (id === resolvedId?.id) {
|
|
2289
|
+
return injectGlobalCode(id, code, workerConfig);
|
|
2290
|
+
}
|
|
2291
|
+
},
|
|
2292
|
+
generateBundle(_, bundle) {
|
|
2293
|
+
let config;
|
|
2294
|
+
if (resolvedPluginConfig.type === "workers") {
|
|
2295
|
+
const workerConfig = resolvedPluginConfig.workers[this.environment.name];
|
|
2296
|
+
const entryChunk = Object.entries(bundle).find(
|
|
2297
|
+
([_2, chunk]) => chunk.type === "chunk" && chunk.isEntry
|
|
2298
|
+
);
|
|
2299
|
+
if (!workerConfig || !entryChunk) {
|
|
2300
|
+
return;
|
|
2301
|
+
}
|
|
2302
|
+
workerConfig.main = entryChunk[0];
|
|
2303
|
+
const isEntryWorker = this.environment.name === resolvedPluginConfig.entryWorkerEnvironmentName;
|
|
2304
|
+
if (isEntryWorker && workerConfig.assets) {
|
|
2305
|
+
const workerOutputDirectory = this.environment.config.build.outDir;
|
|
2306
|
+
const clientOutputDirectory = resolvedViteConfig.environments.client?.build.outDir;
|
|
2307
|
+
assert7(
|
|
2308
|
+
clientOutputDirectory,
|
|
2309
|
+
"Unexpected error: client output directory is undefined"
|
|
2310
|
+
);
|
|
2311
|
+
workerConfig.assets.directory = path6.relative(
|
|
2312
|
+
path6.resolve(resolvedViteConfig.root, workerOutputDirectory),
|
|
2313
|
+
path6.resolve(resolvedViteConfig.root, clientOutputDirectory)
|
|
2314
|
+
);
|
|
2315
|
+
}
|
|
2316
|
+
config = workerConfig;
|
|
2317
|
+
} else if (this.environment.name === "client") {
|
|
2318
|
+
const assetsOnlyConfig = resolvedPluginConfig.config;
|
|
2319
|
+
assetsOnlyConfig.assets.directory = ".";
|
|
2320
|
+
this.emitFile({
|
|
2321
|
+
type: "asset",
|
|
2322
|
+
fileName: ".assetsignore",
|
|
2323
|
+
source: "wrangler.json"
|
|
2324
|
+
});
|
|
2325
|
+
config = assetsOnlyConfig;
|
|
2326
|
+
}
|
|
2327
|
+
if (!config) {
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
config.no_bundle = true;
|
|
2331
|
+
config.rules = [{ type: "ESModule", globs: ["**/*.js"] }];
|
|
2332
|
+
config.unsafe = void 0;
|
|
2333
|
+
this.emitFile({
|
|
2334
|
+
type: "asset",
|
|
2335
|
+
fileName: "wrangler.json",
|
|
2336
|
+
source: JSON.stringify(config)
|
|
2337
|
+
});
|
|
2338
|
+
},
|
|
2339
|
+
handleHotUpdate(options) {
|
|
2340
|
+
if (resolvedPluginConfig.configPaths.has(options.file)) {
|
|
2341
|
+
options.server.restart();
|
|
2342
|
+
}
|
|
2343
|
+
},
|
|
2344
|
+
async buildEnd() {
|
|
2345
|
+
if (miniflare) {
|
|
2346
|
+
await miniflare.dispose();
|
|
2347
|
+
miniflare = void 0;
|
|
2348
|
+
}
|
|
2349
|
+
},
|
|
2350
|
+
async configureServer(viteDevServer) {
|
|
2351
|
+
assert7(viteDevServer.httpServer, "Unexpected error: No Vite HTTP server");
|
|
2352
|
+
miniflare = new Miniflare(
|
|
2353
|
+
getDevMiniflareOptions(resolvedPluginConfig, viteDevServer)
|
|
2354
|
+
);
|
|
2355
|
+
await initRunners(resolvedPluginConfig, viteDevServer, miniflare);
|
|
2356
|
+
const entryWorker = await getDevEntryWorker(
|
|
2357
|
+
resolvedPluginConfig,
|
|
2358
|
+
miniflare
|
|
2359
|
+
);
|
|
2360
|
+
const middleware = createMiddleware(({ request }) => {
|
|
2361
|
+
return entryWorker.fetch(toMiniflareRequest(request), {
|
|
2362
|
+
redirect: "manual"
|
|
2363
|
+
});
|
|
2364
|
+
});
|
|
2365
|
+
handleWebSocket(
|
|
2366
|
+
viteDevServer.httpServer,
|
|
2367
|
+
entryWorker.fetch,
|
|
2368
|
+
viteDevServer.config.logger
|
|
2369
|
+
);
|
|
2370
|
+
return () => {
|
|
2371
|
+
viteDevServer.middlewares.use((req, res, next) => {
|
|
2372
|
+
middleware(req, res, next);
|
|
2373
|
+
});
|
|
2374
|
+
};
|
|
2375
|
+
},
|
|
2376
|
+
configurePreviewServer(vitePreviewServer) {
|
|
2377
|
+
const miniflare2 = new Miniflare(
|
|
2378
|
+
getPreviewMiniflareOptions(
|
|
2379
|
+
vitePreviewServer,
|
|
2380
|
+
pluginConfig.persistState ?? true
|
|
2381
|
+
)
|
|
2382
|
+
);
|
|
2383
|
+
const middleware = createMiddleware(({ request }) => {
|
|
2384
|
+
return miniflare2.dispatchFetch(toMiniflareRequest(request), {
|
|
2385
|
+
redirect: "manual"
|
|
2386
|
+
});
|
|
2387
|
+
});
|
|
2388
|
+
handleWebSocket(
|
|
2389
|
+
vitePreviewServer.httpServer,
|
|
2390
|
+
miniflare2.dispatchFetch,
|
|
2391
|
+
vitePreviewServer.config.logger
|
|
2392
|
+
);
|
|
2393
|
+
return () => {
|
|
2394
|
+
vitePreviewServer.middlewares.use((req, res, next) => {
|
|
2395
|
+
middleware(req, res, next);
|
|
2396
|
+
});
|
|
2397
|
+
};
|
|
2398
|
+
}
|
|
2399
|
+
};
|
|
2400
|
+
}
|
|
2401
|
+
export {
|
|
2402
|
+
cloudflare2 as cloudflare
|
|
2403
|
+
};
|