rspack-plugin-cloudflare 0.0.1-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +126 -2
- package/dist/assets.d.ts +31 -0
- package/dist/assets.js +112 -0
- package/dist/assets.js.map +1 -0
- package/dist/build.d.ts +216 -0
- package/dist/build.js +140 -0
- package/dist/build.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +103 -0
- package/dist/config.js.map +1 -0
- package/dist/containers.d.ts +30 -0
- package/dist/containers.js +167 -0
- package/dist/containers.js.map +1 -0
- package/dist/dev-entry.d.ts +11 -0
- package/dist/dev-entry.js +44 -0
- package/dist/dev-entry.js.map +1 -0
- package/dist/dev-worker.d.ts +73 -0
- package/dist/dev-worker.js +247 -0
- package/dist/dev-worker.js.map +1 -0
- package/dist/dev.d.ts +28 -0
- package/dist/dev.js +422 -0
- package/dist/dev.js.map +1 -0
- package/dist/http.d.ts +23 -0
- package/dist/http.js +89 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +139 -0
- package/dist/index.js.map +1 -0
- package/dist/inspector.d.ts +5 -0
- package/dist/inspector.js +41 -0
- package/dist/inspector.js.map +1 -0
- package/dist/miniflare.d.ts +1 -0
- package/dist/miniflare.js +6 -0
- package/dist/miniflare.js.map +1 -0
- package/dist/module-rules.d.ts +4 -0
- package/dist/module-rules.js +29 -0
- package/dist/module-rules.js.map +1 -0
- package/dist/nodejs-compat.d.ts +14 -0
- package/dist/nodejs-compat.js +46 -0
- package/dist/nodejs-compat.js.map +1 -0
- package/dist/options.d.ts +45 -0
- package/dist/options.js +2 -0
- package/dist/options.js.map +1 -0
- package/dist/routing.d.ts +12 -0
- package/dist/routing.js +40 -0
- package/dist/routing.js.map +1 -0
- package/dist/tunnel.d.ts +15 -0
- package/dist/tunnel.js +94 -0
- package/dist/tunnel.js.map +1 -0
- package/dist/worker-config.d.ts +42 -0
- package/dist/worker-config.js +194 -0
- package/dist/worker-config.js.map +1 -0
- package/package.json +77 -3
- package/runtime/dev-runtime.js +265 -0
- package/src/assets.ts +148 -0
- package/src/build.ts +153 -0
- package/src/config.ts +138 -0
- package/src/containers.ts +183 -0
- package/src/dev-entry.ts +50 -0
- package/src/dev-worker.ts +297 -0
- package/src/dev.ts +478 -0
- package/src/http.ts +102 -0
- package/src/index.ts +164 -0
- package/src/inspector.ts +44 -0
- package/src/miniflare.ts +7 -0
- package/src/module-rules.ts +36 -0
- package/src/nodejs-compat.ts +63 -0
- package/src/options.ts +46 -0
- package/src/routing.ts +48 -0
- package/src/tunnel.ts +106 -0
- package/src/worker-config.ts +237 -0
package/src/dev.ts
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { unstable_convertConfigBindingsToStartWorkerBindings, unstable_printBindings } from 'wrangler';
|
|
5
|
+
import { WebSocketServer } from 'ws';
|
|
6
|
+
|
|
7
|
+
import { createAssetServer } from './assets.js';
|
|
8
|
+
import {
|
|
9
|
+
getContainerEngine,
|
|
10
|
+
getDockerPath,
|
|
11
|
+
prepareContainerImages,
|
|
12
|
+
removeContainers,
|
|
13
|
+
} from './containers.js';
|
|
14
|
+
import { DevWorker } from './dev-worker.js';
|
|
15
|
+
import {
|
|
16
|
+
createRequestInit,
|
|
17
|
+
getRequestHeaders,
|
|
18
|
+
getRequestUrl,
|
|
19
|
+
sendErrorPage,
|
|
20
|
+
sendResponse,
|
|
21
|
+
} from './http.js';
|
|
22
|
+
import { DEBUG_PATH, getDebugPageHtml, resolveInspectorPort } from './inspector.js';
|
|
23
|
+
import { miniflare } from './miniflare.js';
|
|
24
|
+
import { parseStaticRouting, routeRequest } from './routing.js';
|
|
25
|
+
|
|
26
|
+
import type { AssetServer, ReadableFileSystem } from './assets.js';
|
|
27
|
+
import type { ResolvedWorker } from './config.js';
|
|
28
|
+
import type { ContainerImage } from './containers.js';
|
|
29
|
+
import type { CloudflarePluginOptions } from './options.js';
|
|
30
|
+
import type { Compiler } from '@rspack/core';
|
|
31
|
+
import type { FSWatcher } from 'node:fs';
|
|
32
|
+
import type { IncomingMessage, Server, ServerResponse } from 'node:http';
|
|
33
|
+
import type { Duplex } from 'node:stream';
|
|
34
|
+
|
|
35
|
+
type Logger = ReturnType<Compiler['getInfrastructureLogger']>;
|
|
36
|
+
|
|
37
|
+
/** What the session needs from the dev server it runs inside. */
|
|
38
|
+
interface DevServerHooks {
|
|
39
|
+
waitUntilValid: () => Promise<void>;
|
|
40
|
+
/** Sends a message to connected HMR clients, which drives the browser's error overlay. */
|
|
41
|
+
sendToClients: (type: string, data?: unknown) => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// paths the dev server answers itself, before anything reaches the Worker or the assets directory
|
|
45
|
+
const DEV_SERVER_PATH_RE = /^\/(?:webpack-dev-server|__webpack_dev_server__|__open-in-editor|lazy-compilation-using-)/;
|
|
46
|
+
// Miniflare's own endpoints, like trigger handlers, which skip asset routing
|
|
47
|
+
const MINIFLARE_PATH_RE = /^\/(?:cdn-cgi\/local|__cf_local)\//;
|
|
48
|
+
// pre-v5 Miniflare paths still in docs and scripts, mapped the same way the Vite plugin does
|
|
49
|
+
const LEGACY_PATH_REWRITES = [
|
|
50
|
+
['/cdn-cgi/handler', '/cdn-cgi/local'],
|
|
51
|
+
['/cdn-cgi/mf/scheduled', '/cdn-cgi/local/scheduled'],
|
|
52
|
+
['/cdn-cgi/mf/stream', '/__cf_local/stream'],
|
|
53
|
+
['/cdn-cgi/mf/imagedelivery', '/__cf_local/imagedelivery'],
|
|
54
|
+
['/cdn-cgi/explorer', '/cdn-cgi/local/explorer'],
|
|
55
|
+
] as const;
|
|
56
|
+
// local secrets files that wrangler reads alongside the config
|
|
57
|
+
const SECRETS_FILE_RE = /^\.(?:dev\.vars|env)(?:\..+)?$/;
|
|
58
|
+
|
|
59
|
+
function rewriteLegacyMiniflarePath(pathname: string) {
|
|
60
|
+
for (const [oldPrefix, newPrefix] of LEGACY_PATH_REWRITES) {
|
|
61
|
+
if (pathname === oldPrefix || pathname.startsWith(`${oldPrefix}/`)) {
|
|
62
|
+
return newPrefix + pathname.slice(oldPrefix.length);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return pathname;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Runs the entry Worker and any auxiliary Workers in one Miniflare, routing dev server requests like Cloudflare does. */
|
|
69
|
+
export class DevSession {
|
|
70
|
+
readonly #compiler: Compiler;
|
|
71
|
+
readonly #options: CloudflarePluginOptions;
|
|
72
|
+
readonly #logger: Logger;
|
|
73
|
+
readonly #workers: DevWorker[];
|
|
74
|
+
readonly #entry: DevWorker;
|
|
75
|
+
#hooks: DevServerHooks | undefined;
|
|
76
|
+
#assets: AssetServer | undefined;
|
|
77
|
+
#routing;
|
|
78
|
+
#miniflare: InstanceType<typeof miniflare.Miniflare> | undefined;
|
|
79
|
+
#inspectorPort: number | undefined;
|
|
80
|
+
#configWatchers: FSWatcher[] = [];
|
|
81
|
+
// images already built this session, which are also the ones whose containers need removing on exit
|
|
82
|
+
readonly #containerTags = new Set<string>();
|
|
83
|
+
readonly #removeContainersOnExit = () => removeContainers(getDockerPath(), this.#containerTags);
|
|
84
|
+
// Workers rebuilt since Miniflare last picked up their code, and those whose build is failing
|
|
85
|
+
readonly #updated = new Set<DevWorker>();
|
|
86
|
+
readonly #failing = new Set<DevWorker>();
|
|
87
|
+
// builds finish independently, so loading them into Miniflare happens strictly one at a time
|
|
88
|
+
#loading = Promise.resolve();
|
|
89
|
+
// open while any Worker is building, so requests wait for the code they'd otherwise miss
|
|
90
|
+
#gate: { promise: Promise<void>; release: () => void; } | undefined;
|
|
91
|
+
|
|
92
|
+
constructor(options: { compiler: Compiler; resolvers: (() => ResolvedWorker)[]; pluginOptions: CloudflarePluginOptions; logger: Logger; }) {
|
|
93
|
+
this.#compiler = options.compiler;
|
|
94
|
+
this.#options = options.pluginOptions;
|
|
95
|
+
this.#logger = options.logger;
|
|
96
|
+
this.#workers = options.resolvers.map(resolve => new DevWorker({
|
|
97
|
+
compiler: options.compiler,
|
|
98
|
+
resolve,
|
|
99
|
+
pluginOptions: options.pluginOptions,
|
|
100
|
+
logger: options.logger,
|
|
101
|
+
events: {
|
|
102
|
+
onBuildStart: () => this.#openGate(),
|
|
103
|
+
onBuildDone: (worker) => {
|
|
104
|
+
this.#loading = this.#loading.then(() => this.#onBuildDone(worker));
|
|
105
|
+
return this.#loading;
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
}));
|
|
109
|
+
const [entry] = this.#workers;
|
|
110
|
+
if (!entry) {
|
|
111
|
+
throw new Error('A dev session needs at least one Worker.');
|
|
112
|
+
}
|
|
113
|
+
this.#entry = entry;
|
|
114
|
+
this.#routing = parseStaticRouting(entry.resolved.config.assets?.run_worker_first);
|
|
115
|
+
this.#openGate();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
#openGate() {
|
|
119
|
+
if (this.#gate) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
123
|
+
this.#gate = { promise, release: resolve };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
#releaseGateIfIdle() {
|
|
127
|
+
if (this.#gate && this.#workers.every(worker => !worker.building)) {
|
|
128
|
+
this.#gate.release();
|
|
129
|
+
this.#gate = undefined;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async #ready() {
|
|
134
|
+
while (this.#gate) {
|
|
135
|
+
await this.#gate.promise;
|
|
136
|
+
}
|
|
137
|
+
return this.#miniflare;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async #onBuildDone(worker: DevWorker) {
|
|
141
|
+
if (worker.buildError) {
|
|
142
|
+
this.#failing.add(worker);
|
|
143
|
+
this.#logger.error(`Worker "${worker.name}" build failed${this.#miniflare ? '; still serving the previous build' : ''}:\n${worker.buildError}`);
|
|
144
|
+
this.#hooks?.sendToClients('errors', [{ moduleName: `Worker "${worker.name}"`, message: worker.buildError }]);
|
|
145
|
+
} else {
|
|
146
|
+
this.#updated.add(worker);
|
|
147
|
+
if (this.#failing.delete(worker) && this.#failing.size === 0) {
|
|
148
|
+
// dismisses the overlay without reloading the page
|
|
149
|
+
this.#hooks?.sendToClients('still-ok');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// the last Worker to finish loads everyone's changes together
|
|
153
|
+
if (this.#workers.some(other => other.building)) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
await this.#load();
|
|
158
|
+
} catch (error) {
|
|
159
|
+
this.#logger.error(`Workers failed to start:\n${String(error)}`);
|
|
160
|
+
}
|
|
161
|
+
this.#releaseGateIfIdle();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Gets new builds running: hot updates when possible, otherwise a restart of every Worker. */
|
|
165
|
+
async #load() {
|
|
166
|
+
if (!this.#miniflare) {
|
|
167
|
+
if (this.#failing.size > 0) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
this.#miniflare = new miniflare.Miniflare(await this.#getMiniflareOptions());
|
|
171
|
+
await this.#miniflare.ready;
|
|
172
|
+
this.#printReady();
|
|
173
|
+
this.#markLoaded();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const restart = this.#workers.find(worker => worker.restartReason);
|
|
178
|
+
if (restart) {
|
|
179
|
+
await this.#restart(`Worker "${restart.name}" restarted: ${restart.restartReason ?? ''}`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
for (const worker of this.#updated) {
|
|
183
|
+
const result = await worker.applyHotUpdate(this.#miniflare);
|
|
184
|
+
if (result.reload) {
|
|
185
|
+
await this.#restart(`Worker "${worker.name}" restarted: ${result.reason ?? 'the update could not be applied in place'}`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
this.#logger.info(`Worker "${worker.name}" hot updated`);
|
|
189
|
+
}
|
|
190
|
+
this.#updated.clear();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async #restart(message: string) {
|
|
194
|
+
await this.#miniflare?.setOptions(await this.#getMiniflareOptions());
|
|
195
|
+
this.#logger.info(message);
|
|
196
|
+
this.#markLoaded();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#markLoaded() {
|
|
200
|
+
for (const worker of this.#workers) {
|
|
201
|
+
worker.markLoaded();
|
|
202
|
+
}
|
|
203
|
+
this.#updated.clear();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#printReady() {
|
|
207
|
+
for (const worker of this.#workers) {
|
|
208
|
+
const { config, name } = worker.resolved;
|
|
209
|
+
unstable_printBindings(unstable_convertConfigBindingsToStartWorkerBindings(config), {
|
|
210
|
+
name,
|
|
211
|
+
local: true,
|
|
212
|
+
warnIfNoBindings: false,
|
|
213
|
+
isMultiWorker: this.#workers.length > 1,
|
|
214
|
+
containers: config.containers,
|
|
215
|
+
tailConsumers: config.tail_consumers,
|
|
216
|
+
streamingTailConsumers: config.streaming_tail_consumers,
|
|
217
|
+
log: (message: string) => this.#logger.info(message),
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const names = this.#workers.map(worker => `"${worker.name}"`).join(', ');
|
|
221
|
+
const debug = this.#inspectorPort === undefined ? '' : `; debug at ${DEBUG_PATH} (inspector on port ${this.#inspectorPort})`;
|
|
222
|
+
this.#logger.info(`${this.#workers.length > 1 ? 'Workers' : 'Worker'} ${names} ready${debug}`);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Serves rspack's hot-update modules, which workerd imports through Miniflare's module fallback as `/<worker>/<file>`. */
|
|
226
|
+
async #serveHotUpdate(request: Parameters<typeof miniflare.parseModuleFallbackRequest>[0]) {
|
|
227
|
+
const parsed = await miniflare.parseModuleFallbackRequest(request);
|
|
228
|
+
const [, workerName = '', ...rest] = (parsed?.specifier ?? '').split('/');
|
|
229
|
+
const worker = this.#workers.find(candidate => candidate.name === workerName);
|
|
230
|
+
const source = await worker?.readHotUpdate(rest.join('/'));
|
|
231
|
+
if (source === undefined) {
|
|
232
|
+
return new miniflare.Response(null, { status: 404 });
|
|
233
|
+
}
|
|
234
|
+
return miniflare.Response.json({ esModule: source });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
#assetsServiceBinding(): Record<string, unknown> {
|
|
238
|
+
const binding = this.#entry.resolved.assets?.binding;
|
|
239
|
+
const assets = this.#assets;
|
|
240
|
+
if (!binding || !assets) {
|
|
241
|
+
return {};
|
|
242
|
+
}
|
|
243
|
+
return {
|
|
244
|
+
[binding]: {
|
|
245
|
+
node: (req: IncomingMessage, res: ServerResponse) => {
|
|
246
|
+
assets.handle(req, res).catch((error: unknown) => this.#sendError(res, error));
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Builds images not seen yet this session, returning the engine Miniflare should start containers with. */
|
|
253
|
+
async #prepareContainers(images: ContainerImage[]) {
|
|
254
|
+
if (images.length === 0) {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
const dockerPath = getDockerPath();
|
|
258
|
+
const pending = images.filter(image => !this.#containerTags.has(image.tag));
|
|
259
|
+
if (pending.length > 0) {
|
|
260
|
+
this.#logger.info('Building container images for local development...');
|
|
261
|
+
await prepareContainerImages(dockerPath, pending);
|
|
262
|
+
for (const image of pending) {
|
|
263
|
+
this.#containerTags.add(image.tag);
|
|
264
|
+
}
|
|
265
|
+
// rspack serve may exit without a shutdown hook, like on a crash, and containers would keep running
|
|
266
|
+
process.off('exit', this.#removeContainersOnExit);
|
|
267
|
+
process.on('exit', this.#removeContainersOnExit);
|
|
268
|
+
this.#logger.info('Container images built; restart dev to rebuild them after changing a Dockerfile.');
|
|
269
|
+
}
|
|
270
|
+
return getContainerEngine(dockerPath);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async #getMiniflareOptions() {
|
|
274
|
+
const workers: unknown[] = [];
|
|
275
|
+
const externalWorkers: unknown[] = [];
|
|
276
|
+
const containerImages: ContainerImage[] = [];
|
|
277
|
+
for (const worker of this.#workers) {
|
|
278
|
+
if (!worker.resolved.main) {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const extraBindings = worker === this.#entry ? this.#assetsServiceBinding() : {};
|
|
282
|
+
const options = await worker.getMiniflareOptions(extraBindings, this.#inspectorPort !== undefined);
|
|
283
|
+
workers.push(options.worker);
|
|
284
|
+
externalWorkers.push(...options.externalWorkers);
|
|
285
|
+
containerImages.push(...options.containerImages);
|
|
286
|
+
}
|
|
287
|
+
const containerEngine = await this.#prepareContainers(containerImages);
|
|
288
|
+
|
|
289
|
+
const { rootDir } = this.#entry.resolved;
|
|
290
|
+
const { persistState = true } = this.#options;
|
|
291
|
+
let resourcePersistencePath: string | undefined;
|
|
292
|
+
if (persistState !== false) {
|
|
293
|
+
const statePath = typeof persistState === 'object' ? persistState.path : path.join('.wrangler', 'state');
|
|
294
|
+
resourcePersistencePath = path.resolve(rootDir, statePath, 'v3');
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return miniflare.convertV4MiniflareOptions({
|
|
298
|
+
log: new miniflare.Log(miniflare.LogLevel.INFO),
|
|
299
|
+
inspectorPort: this.#inspectorPort,
|
|
300
|
+
resourcePersistencePath,
|
|
301
|
+
resourceTmpPath: path.join(rootDir, '.wrangler', 'tmp'),
|
|
302
|
+
containerEngine,
|
|
303
|
+
// lets service bindings reach Workers running in other local dev sessions, and theirs reach these
|
|
304
|
+
unsafeDevRegistryPath: miniflare.getDefaultDevRegistryPath(),
|
|
305
|
+
// serves /cdn-cgi/local/scheduled and friends for testing non-fetch handlers
|
|
306
|
+
unsafeTriggerHandlers: true,
|
|
307
|
+
unsafeModuleFallbackService: (request: Parameters<typeof miniflare.parseModuleFallbackRequest>[0]) => this.#serveHotUpdate(request),
|
|
308
|
+
// the entry Worker comes first, which makes it the one requests reach
|
|
309
|
+
workers: [...workers, ...externalWorkers],
|
|
310
|
+
} as Parameters<typeof miniflare.convertV4MiniflareOptions>[0]);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
#createAssetServer() {
|
|
314
|
+
const { assets, config } = this.#entry.resolved;
|
|
315
|
+
const hooks = this.#hooks;
|
|
316
|
+
if (!assets || !hooks) {
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
return createAssetServer({
|
|
320
|
+
directory: assets.directory,
|
|
321
|
+
config: config.assets,
|
|
322
|
+
// the dev server replaces the client compiler's output filesystem with an in-memory one
|
|
323
|
+
getOutputFileSystem: () => this.#compiler.outputFileSystem as ReadableFileSystem | null ?? undefined,
|
|
324
|
+
// assets imported by Worker code, which `rspack build` copies into the assets directory
|
|
325
|
+
extraDirectories: [this.#entry.importedAssetsDir],
|
|
326
|
+
waitUntilValid: hooks.waitUntilValid,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Rebuilds a Worker when its Wrangler config or local secrets change, like the Vite plugin restarting its server. */
|
|
331
|
+
#watchConfigs() {
|
|
332
|
+
const pending = new Map<DevWorker, ReturnType<typeof setTimeout>>();
|
|
333
|
+
const reload = (worker: DevWorker) => {
|
|
334
|
+
clearTimeout(pending.get(worker));
|
|
335
|
+
// editors often write a file in several steps, so wait for them to settle
|
|
336
|
+
pending.set(worker, setTimeout(() => {
|
|
337
|
+
pending.delete(worker);
|
|
338
|
+
this.#reloadWorker(worker).catch((error: unknown) => {
|
|
339
|
+
this.#logger.error(`Worker "${worker.name}" failed to reload its config:\n${String(error)}`);
|
|
340
|
+
});
|
|
341
|
+
}, 100));
|
|
342
|
+
};
|
|
343
|
+
const directories = new Set(this.#workers.map(worker => worker.resolved.rootDir));
|
|
344
|
+
for (const directory of directories) {
|
|
345
|
+
this.#configWatchers.push(fs.watch(directory, (_event, fileName) => {
|
|
346
|
+
if (!fileName) {
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
for (const worker of this.#workers) {
|
|
350
|
+
const { configPath, rootDir } = worker.resolved;
|
|
351
|
+
if (rootDir === directory && (fileName === path.basename(configPath) || SECRETS_FILE_RE.test(fileName))) {
|
|
352
|
+
reload(worker);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}));
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async #reloadWorker(worker: DevWorker) {
|
|
360
|
+
this.#logger.info(`Worker "${worker.name}" config changed; rebuilding`);
|
|
361
|
+
this.#openGate();
|
|
362
|
+
await worker.reload();
|
|
363
|
+
if (worker === this.#entry) {
|
|
364
|
+
this.#routing = parseStaticRouting(worker.resolved.config.assets?.run_worker_first);
|
|
365
|
+
this.#assets = this.#createAssetServer();
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async #upgrade(webSocketServer: WebSocketServer, url: URL, req: IncomingMessage, socket: Duplex, head: Buffer) {
|
|
370
|
+
const mf = await this.#ready();
|
|
371
|
+
if (!mf) {
|
|
372
|
+
socket.destroy();
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const response = await mf.dispatchFetch(url, { method: req.method, headers: [...getRequestHeaders(req)] });
|
|
376
|
+
const workerSocket = response.webSocket;
|
|
377
|
+
if (!workerSocket || socket.destroyed) {
|
|
378
|
+
socket.destroy();
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
webSocketServer.handleUpgrade(req, socket, head, (clientSocket) => {
|
|
382
|
+
miniflare.coupleWebSocket(clientSocket, workerSocket).catch((error: unknown) => {
|
|
383
|
+
this.#logger.error(`WebSocket to the Worker failed: ${String(error)}`);
|
|
384
|
+
clientSocket.terminate();
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
#sendError(res: ServerResponse, error: unknown) {
|
|
390
|
+
this.#logger.error(error instanceof Error ? error.stack ?? error.message : String(error));
|
|
391
|
+
sendErrorPage(res, error);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async #start() {
|
|
395
|
+
this.#inspectorPort = await resolveInspectorPort(this.#options.inspectorPort);
|
|
396
|
+
for (const worker of this.#workers) {
|
|
397
|
+
worker.start();
|
|
398
|
+
}
|
|
399
|
+
this.#watchConfigs();
|
|
400
|
+
// an assets-only project has nothing to build
|
|
401
|
+
this.#releaseGateIfIdle();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
start(hooks: DevServerHooks) {
|
|
405
|
+
this.#hooks = hooks;
|
|
406
|
+
this.#assets = this.#createAssetServer();
|
|
407
|
+
this.#start().catch((error: unknown) => {
|
|
408
|
+
this.#logger.error(`Workers failed to start:\n${String(error)}`);
|
|
409
|
+
this.#gate?.release();
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Connect middleware that routes each request to the Worker or the assets directory, like Cloudflare's router does. */
|
|
414
|
+
async handle(req: IncomingMessage, res: ServerResponse, next: () => void) {
|
|
415
|
+
const url = getRequestUrl(req);
|
|
416
|
+
if (DEV_SERVER_PATH_RE.test(url.pathname)) {
|
|
417
|
+
next();
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
if (url.pathname === DEBUG_PATH && this.#inspectorPort !== undefined) {
|
|
421
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
422
|
+
res.end(getDebugPageHtml(this.#workers.map(worker => worker.name), this.#inspectorPort));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
try {
|
|
426
|
+
const hasWorker = this.#entry.resolved.main !== undefined;
|
|
427
|
+
url.pathname = rewriteLegacyMiniflarePath(url.pathname);
|
|
428
|
+
const route = MINIFLARE_PATH_RE.test(url.pathname) ? 'worker' : routeRequest(this.#routing, url.pathname, Boolean(this.#assets));
|
|
429
|
+
const assets = this.#assets;
|
|
430
|
+
const servesAsset = !hasWorker || route === 'asset' || (route === 'asset-then-worker' && await assets?.exists(url.pathname));
|
|
431
|
+
if (assets && servesAsset) {
|
|
432
|
+
await assets.handle(req, res);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const mf = await this.#ready();
|
|
436
|
+
if (!mf) {
|
|
437
|
+
// already logged when the build failed, so only the browser needs telling
|
|
438
|
+
const errors = [...this.#failing].map(worker => `Worker "${worker.name}":\n${worker.buildError ?? ''}`);
|
|
439
|
+
sendErrorPage(res, `Workers failed to start:\n${errors.join('\n\n')}`);
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const response = await mf.dispatchFetch(url, createRequestInit(req, res));
|
|
443
|
+
sendResponse(res, response);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
this.#sendError(res, error);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Forwards WebSocket upgrades to the Worker, leaving the dev server's own HMR socket alone. */
|
|
450
|
+
attachUpgradeHandler(server: Server, devServerSocketPath: string) {
|
|
451
|
+
if (!this.#entry.resolved.main) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const webSocketServer = new WebSocketServer({ noServer: true });
|
|
455
|
+
server.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer) => {
|
|
456
|
+
const url = getRequestUrl(req);
|
|
457
|
+
if (url.pathname === devServerSocketPath || routeRequest(this.#routing, url.pathname, Boolean(this.#assets)) === 'asset') {
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
socket.on('error', () => socket.destroy());
|
|
461
|
+
this.#upgrade(webSocketServer, url, req, socket, head).catch((error: unknown) => {
|
|
462
|
+
this.#logger.error(`WebSocket upgrade to the Worker failed: ${String(error)}`);
|
|
463
|
+
socket.destroy();
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
async dispose() {
|
|
469
|
+
for (const watcher of this.#configWatchers) {
|
|
470
|
+
watcher.close();
|
|
471
|
+
}
|
|
472
|
+
await Promise.all(this.#workers.map(worker => worker.dispose()));
|
|
473
|
+
await this.#miniflare?.dispose();
|
|
474
|
+
this.#miniflare = undefined;
|
|
475
|
+
this.#removeContainersOnExit();
|
|
476
|
+
process.off('exit', this.#removeContainersOnExit);
|
|
477
|
+
}
|
|
478
|
+
}
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import type { TLSSocket } from 'node:tls';
|
|
5
|
+
|
|
6
|
+
export function getRequestUrl(req: IncomingMessage) {
|
|
7
|
+
const forwardedProto = req.headers['x-forwarded-proto'];
|
|
8
|
+
let protocol = 'http:';
|
|
9
|
+
if (typeof forwardedProto === 'string') {
|
|
10
|
+
protocol = `${forwardedProto.split(',', 1)[0]?.trim()}:`;
|
|
11
|
+
} else if ((req.socket as TLSSocket).encrypted) {
|
|
12
|
+
protocol = 'https:';
|
|
13
|
+
}
|
|
14
|
+
const host = req.headers[':authority'] ?? req.headers.host ?? 'localhost';
|
|
15
|
+
return new URL(req.url ?? '/', `${protocol}//${String(host)}`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function getRequestHeaders(req: IncomingMessage) {
|
|
19
|
+
const headers = new Headers();
|
|
20
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
21
|
+
// HTTP/2 pseudo-headers can't be set on a fetch Headers object
|
|
22
|
+
if (value === undefined || name.startsWith(':')) {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
for (const item of value) {
|
|
27
|
+
headers.append(name, item);
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
headers.set(name, value);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return headers;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createRequestInit(req: IncomingMessage, res: ServerResponse) {
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
res.on('close', () => controller.abort());
|
|
39
|
+
const headers = getRequestHeaders(req);
|
|
40
|
+
// responses come back through undici, which decodes compressed bodies but keeps Content-Encoding; asking for identity avoids a mismatch
|
|
41
|
+
headers.set('accept-encoding', 'identity');
|
|
42
|
+
const method = req.method ?? 'GET';
|
|
43
|
+
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
44
|
+
return {
|
|
45
|
+
method,
|
|
46
|
+
// entries rather than a Headers object, since Miniflare's undici has its own Headers class
|
|
47
|
+
headers: [...headers],
|
|
48
|
+
body: hasBody ? Readable.toWeb(req) as ReadableStream : undefined,
|
|
49
|
+
duplex: 'half' as const,
|
|
50
|
+
redirect: 'manual' as const,
|
|
51
|
+
signal: controller.signal,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function escapeHtml(text: string) {
|
|
56
|
+
return text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Responds with the error's (source-mapped) stack, as a page for browsers and plain text for everything else. */
|
|
60
|
+
export function sendErrorPage(res: ServerResponse, error: unknown) {
|
|
61
|
+
if (res.headersSent) {
|
|
62
|
+
res.destroy();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
66
|
+
if (res.req.headers.accept?.includes('text/html')) {
|
|
67
|
+
res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
68
|
+
res.end(`<!doctype html><title>Worker error</title><body style="font-family:system-ui;margin:2rem"><h1>Worker error</h1><pre style="white-space:pre-wrap">${escapeHtml(message)}</pre></body>`);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
72
|
+
res.end(message);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The parts of a fetch Response we forward, so Miniflare's own undici Response fits as well as the global one. */
|
|
76
|
+
interface ForwardableResponse {
|
|
77
|
+
status: number;
|
|
78
|
+
headers: Iterable<[string, string]> & { getSetCookie: () => string[]; };
|
|
79
|
+
body: import('node:stream/web').ReadableStream | null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function sendResponse(res: ServerResponse, response: ForwardableResponse) {
|
|
83
|
+
const headers: Record<string, string | string[]> = {};
|
|
84
|
+
for (const [name, value] of response.headers) {
|
|
85
|
+
if (name === 'set-cookie') {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
headers[name] = value;
|
|
89
|
+
}
|
|
90
|
+
const cookies = response.headers.getSetCookie();
|
|
91
|
+
if (cookies.length > 0) {
|
|
92
|
+
headers['set-cookie'] = cookies;
|
|
93
|
+
}
|
|
94
|
+
res.writeHead(response.status, headers);
|
|
95
|
+
if (!response.body || res.req.method === 'HEAD') {
|
|
96
|
+
res.end();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const body = Readable.fromWeb(response.body);
|
|
100
|
+
res.on('close', () => body.destroy());
|
|
101
|
+
body.pipe(res);
|
|
102
|
+
}
|