rspack-plugin-cloudflare 0.1.0 → 0.3.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.
Files changed (75) hide show
  1. package/README.md +10 -5
  2. package/THIRD_PARTY_NOTICES.txt +139 -0
  3. package/dist/index.d.ts +51 -7
  4. package/dist/index.js +3592 -131
  5. package/dist/index.js.map +1 -1
  6. package/dist/workers/asset-worker/index.js +5783 -0
  7. package/dist/workers/asset-worker/index.js.map +1 -0
  8. package/dist/workers/router-worker/index.js +6245 -0
  9. package/dist/workers/router-worker/index.js.map +1 -0
  10. package/package.json +14 -12
  11. package/dist/assets.d.ts +0 -31
  12. package/dist/assets.js +0 -112
  13. package/dist/assets.js.map +0 -1
  14. package/dist/build.d.ts +0 -216
  15. package/dist/build.js +0 -140
  16. package/dist/build.js.map +0 -1
  17. package/dist/config.d.ts +0 -19
  18. package/dist/config.js +0 -103
  19. package/dist/config.js.map +0 -1
  20. package/dist/containers.d.ts +0 -30
  21. package/dist/containers.js +0 -167
  22. package/dist/containers.js.map +0 -1
  23. package/dist/dev-entry.d.ts +0 -11
  24. package/dist/dev-entry.js +0 -44
  25. package/dist/dev-entry.js.map +0 -1
  26. package/dist/dev-worker.d.ts +0 -73
  27. package/dist/dev-worker.js +0 -247
  28. package/dist/dev-worker.js.map +0 -1
  29. package/dist/dev.d.ts +0 -28
  30. package/dist/dev.js +0 -422
  31. package/dist/dev.js.map +0 -1
  32. package/dist/http.d.ts +0 -23
  33. package/dist/http.js +0 -89
  34. package/dist/http.js.map +0 -1
  35. package/dist/inspector.d.ts +0 -5
  36. package/dist/inspector.js +0 -41
  37. package/dist/inspector.js.map +0 -1
  38. package/dist/miniflare.d.ts +0 -1
  39. package/dist/miniflare.js +0 -6
  40. package/dist/miniflare.js.map +0 -1
  41. package/dist/module-rules.d.ts +0 -4
  42. package/dist/module-rules.js +0 -29
  43. package/dist/module-rules.js.map +0 -1
  44. package/dist/nodejs-compat.d.ts +0 -14
  45. package/dist/nodejs-compat.js +0 -46
  46. package/dist/nodejs-compat.js.map +0 -1
  47. package/dist/options.d.ts +0 -45
  48. package/dist/options.js +0 -2
  49. package/dist/options.js.map +0 -1
  50. package/dist/routing.d.ts +0 -12
  51. package/dist/routing.js +0 -40
  52. package/dist/routing.js.map +0 -1
  53. package/dist/tunnel.d.ts +0 -15
  54. package/dist/tunnel.js +0 -94
  55. package/dist/tunnel.js.map +0 -1
  56. package/dist/worker-config.d.ts +0 -42
  57. package/dist/worker-config.js +0 -194
  58. package/dist/worker-config.js.map +0 -1
  59. package/src/assets.ts +0 -148
  60. package/src/build.ts +0 -153
  61. package/src/config.ts +0 -138
  62. package/src/containers.ts +0 -183
  63. package/src/dev-entry.ts +0 -50
  64. package/src/dev-worker.ts +0 -297
  65. package/src/dev.ts +0 -478
  66. package/src/http.ts +0 -102
  67. package/src/index.ts +0 -164
  68. package/src/inspector.ts +0 -44
  69. package/src/miniflare.ts +0 -7
  70. package/src/module-rules.ts +0 -36
  71. package/src/nodejs-compat.ts +0 -63
  72. package/src/options.ts +0 -46
  73. package/src/routing.ts +0 -48
  74. package/src/tunnel.ts +0 -106
  75. package/src/worker-config.ts +0 -237
package/src/dev-worker.ts DELETED
@@ -1,297 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import fs from 'node:fs/promises';
3
- import path from 'node:path';
4
-
5
- import { maybeStartOrUpdateRemoteProxySession, unstable_convertConfigBindingsToStartWorkerBindings, unstable_getMiniflareWorkerOptions } from 'wrangler';
6
-
7
- import { getContainerImages } from './containers.js';
8
- import {
9
- HMR_HEADER,
10
- HMR_RUNNER_CLASS,
11
- HMR_TOKEN_BINDING,
12
- createDevEntrySource,
13
- getConfiguredExports,
14
- } from './dev-entry.js';
15
- import { miniflare } from './miniflare.js';
16
- import { IMPORTED_ASSETS_DIR, createWorkerConfig } from './worker-config.js';
17
-
18
- import type { ResolvedWorker } from './config.js';
19
- import type { CloudflarePluginOptions } from './options.js';
20
- import type { AdditionalModulesPlugin, VirtualModules } from './worker-config.js';
21
- import type {
22
- Compiler,
23
- MultiStats,
24
- Stats,
25
- Watching,
26
- } from '@rspack/core';
27
-
28
- type Logger = ReturnType<Compiler['getInfrastructureLogger']>;
29
- type Miniflare = InstanceType<typeof miniflare.Miniflare>;
30
- type RemoteProxySessionData = Awaited<ReturnType<typeof maybeStartOrUpdateRemoteProxySession>>;
31
-
32
- // with module output, rspack writes both update chunks and manifests (`*.hot-update.json.mjs`) as ES modules
33
- const HOT_UPDATE_RE = /\.hot-update\.(?:json\.)?mjs$/;
34
-
35
- function isPlainObject(value: unknown): value is Record<string, unknown> {
36
- return typeof value === 'object' && value !== null && !Array.isArray(value);
37
- }
38
-
39
- /** The export names rspack found on `main`, or undefined when it couldn't tell, like for CommonJS. */
40
- function getProvidedExports(stats: Stats, main: string) {
41
- const { modules = [] } = stats.toJson({ all: false, modules: true, providedExports: true });
42
- const mainModule = modules.find(module => module.nameForCondition && path.resolve(module.nameForCondition) === path.resolve(main));
43
- const provided = mainModule?.providedExports;
44
- return Array.isArray(provided) ? provided.map(String).toSorted((left, right) => left.localeCompare(right)) : undefined;
45
- }
46
-
47
- interface DevWorkerEvents {
48
- /** A build began, so requests should wait for it. */
49
- onBuildStart: (worker: DevWorker) => void;
50
- /** A build finished, successfully or not; `buildError` says which. */
51
- onBuildDone: (worker: DevWorker) => Promise<void>;
52
- }
53
-
54
- /** One Worker in a dev session: its rspack watcher, its hot updates, and its slice of the Miniflare config. */
55
- export class DevWorker {
56
- readonly #compiler: Compiler;
57
- readonly #options: CloudflarePluginOptions;
58
- readonly #logger: Logger;
59
- readonly #events: DevWorkerEvents;
60
- readonly #resolve: () => ResolvedWorker;
61
- // proves an update request came from this session rather than a browser that happened to send the header
62
- readonly #hmrToken = randomUUID();
63
- #resolved: ResolvedWorker;
64
- #watching: Watching | undefined;
65
- #virtualModules: VirtualModules | undefined;
66
- #additionalModules: AdditionalModulesPlugin | undefined;
67
- // the names the dev entry re-exports, which workerd bound when the Worker last (re)started
68
- #exportNames: string[] = [];
69
- #loadedModules = '';
70
- #restartReason: string | undefined = 'it is starting';
71
- #remoteProxy: RemoteProxySessionData = null;
72
- // new on every (re)start so changed Dockerfiles get fresh image tags instead of reusing stale images
73
- #containerBuildId = '';
74
- buildError: string | undefined;
75
- building = true;
76
-
77
- constructor(options: { compiler: Compiler; resolve: () => ResolvedWorker; pluginOptions: CloudflarePluginOptions; logger: Logger; events: DevWorkerEvents; }) {
78
- this.#compiler = options.compiler;
79
- this.#options = options.pluginOptions;
80
- this.#logger = options.logger;
81
- this.#events = options.events;
82
- this.#resolve = options.resolve;
83
- this.#resolved = options.resolve();
84
- }
85
-
86
- // on disk rather than in memory so workerd can read the bundle's source maps for stack traces
87
- get #outputDir() {
88
- return path.join(this.#resolved.rootDir, '.wrangler', 'rspack', this.#resolved.name);
89
- }
90
-
91
- // a virtual module, so it only needs a path that resolves imports the same way main does
92
- get #entryPath() {
93
- return path.join(this.#resolved.rootDir, '.wrangler', 'tmp', `rspack-${this.#resolved.name}`, 'dev-entry.js');
94
- }
95
-
96
- /** Records a finished build, returning false when it triggered another build that should be waited for instead. */
97
- #handleBuild(main: string, error: Error | null, stats: Stats | MultiStats | undefined) {
98
- if (error || !stats || stats.hasErrors() || !('compilation' in stats)) {
99
- this.buildError = error?.message ?? stats?.toString({ preset: 'errors-only', colors: false }) ?? 'Unknown error';
100
- return true;
101
- }
102
- const exportNames = getProvidedExports(stats, main);
103
- if (exportNames && exportNames.join(',') !== this.#exportNames.join(',')) {
104
- // the dev entry re-exports by name and workerd binds exports at startup, so regenerate it and restart on the rebuild
105
- this.#exportNames = exportNames;
106
- this.#restartReason ??= 'its exports changed';
107
- this.#virtualModules?.writeModule(this.#entryPath, createDevEntrySource(main, exportNames));
108
- this.#rebuildEntry();
109
- return false;
110
- }
111
- const entryExports = getProvidedExports(stats, this.#entryPath)?.filter(name => name !== HMR_RUNNER_CLASS);
112
- if (entryExports && entryExports.join(',') !== this.#exportNames.join(',')) {
113
- // workerd binds whatever the built entry exports, so a build that missed the rewrite must not reach it
114
- this.#rebuildEntry();
115
- return false;
116
- }
117
- this.buildError = undefined;
118
- return true;
119
- }
120
-
121
- // the watcher is paused while a build callback runs and can drop the virtual entry's change event, and a bare
122
- // invalidate() then rebuilds with the old entry, so name the changed file outright
123
- #rebuildEntry() {
124
- this.#watching?.invalidateWithChangesAndRemovals(new Set([this.#entryPath]));
125
- }
126
-
127
- #getModules() {
128
- const modules = [{ type: 'ESModule', path: path.join(this.#outputDir, 'index.js') }];
129
- for (const { fileName, type } of this.#additionalModules?.modules ?? []) {
130
- modules.push({ type, path: path.join(this.#outputDir, fileName) });
131
- }
132
- return modules;
133
- }
134
-
135
- /** Starts or refreshes the proxy for bindings marked `remote: true`, which wrangler only opens when some exist. */
136
- async #getRemoteProxyConnectionString() {
137
- if (this.#options.remoteBindings === false) {
138
- return;
139
- }
140
- const { config } = this.#resolved;
141
- this.#remoteProxy = await maybeStartOrUpdateRemoteProxySession({
142
- name: config.name,
143
- bindings: unstable_convertConfigBindingsToStartWorkerBindings(config) ?? {},
144
- account_id: config.account_id,
145
- complianceRegion: config.compliance_region,
146
- }, this.#remoteProxy);
147
- return this.#remoteProxy?.session.remoteProxyConnectionString;
148
- }
149
-
150
- async #closeWatcher() {
151
- const watching = this.#watching;
152
- this.#watching = undefined;
153
- await new Promise<void>((resolve) => {
154
- if (watching) {
155
- watching.close(() => resolve());
156
- } else {
157
- resolve();
158
- }
159
- });
160
- }
161
-
162
- get resolved() {
163
- return this.#resolved;
164
- }
165
-
166
- get name() {
167
- return this.#resolved.name;
168
- }
169
-
170
- /** Why the next build needs a restart instead of a hot update, if it does. */
171
- get restartReason() {
172
- if (this.#restartReason) {
173
- return this.#restartReason;
174
- }
175
- if (JSON.stringify(this.#getModules()) !== this.#loadedModules) {
176
- return 'its .wasm or .bin modules changed';
177
- }
178
- }
179
-
180
- start() {
181
- const { main } = this.#resolved;
182
- this.#containerBuildId = randomUUID().slice(0, 8);
183
- if (!main) {
184
- this.building = false;
185
- return;
186
- }
187
- this.building = true;
188
- this.#exportNames = getConfiguredExports(this.#resolved);
189
- const { config, virtualModules, additionalModules } = createWorkerConfig({
190
- compiler: this.#compiler,
191
- worker: this.#resolved,
192
- pluginOptions: this.#options,
193
- outputDir: this.#outputDir,
194
- entry: this.#entryPath,
195
- entrySource: createDevEntrySource(main, this.#exportNames),
196
- mode: 'development',
197
- hot: true,
198
- // a prefix per Worker, so Miniflare's module fallback can tell whose hot update is being imported
199
- publicPath: `/${this.name}/`,
200
- });
201
- this.#virtualModules = virtualModules;
202
- this.#additionalModules = additionalModules;
203
- const workerCompiler = this.#compiler.rspack.rspack(config);
204
- workerCompiler.hooks.invalid.tap('rspack-plugin-cloudflare', () => {
205
- this.building = true;
206
- this.#events.onBuildStart(this);
207
- });
208
- this.#watching = workerCompiler.watch({}, (error, stats) => {
209
- if (this.#handleBuild(main, error, stats)) {
210
- this.building = false;
211
- this.#events.onBuildDone(this).catch((loadError: unknown) => {
212
- this.#logger.error(`Worker "${this.name}" failed to load: ${String(loadError)}`);
213
- });
214
- }
215
- });
216
- }
217
-
218
- /** Re-reads the Wrangler config and rebuilds from scratch, since anything from `main` to bindings may have changed. */
219
- async reload() {
220
- await this.#closeWatcher();
221
- this.#resolved = this.#resolve();
222
- this.#restartReason = 'its Wrangler config changed';
223
- this.start();
224
- }
225
-
226
- /** Records that Miniflare is now running this Worker's latest build. */
227
- markLoaded() {
228
- this.#restartReason = undefined;
229
- this.#loadedModules = JSON.stringify(this.#getModules());
230
- }
231
-
232
- /** Asks the running Worker to apply its pending hot update, through a fetch its dev entry recognizes by token. */
233
- async applyHotUpdate(mf: Miniflare): Promise<{ reload: boolean; reason?: string; }> {
234
- const response = await mf.dispatchFetch('http://localhost/', {
235
- headers: { [HMR_HEADER]: this.#hmrToken, [miniflare.CoreHeaders.ROUTE_OVERRIDE]: this.name },
236
- });
237
- const result: unknown = await response.json();
238
- if (isPlainObject(result) && result.reload === false) {
239
- return { reload: false };
240
- }
241
- const reason = isPlainObject(result) && typeof result.reason === 'string' ? result.reason : `the update request failed (${response.status})`;
242
- return { reload: true, reason };
243
- }
244
-
245
- /** Reads one of this Worker's hot-update modules, given its path below the Worker's public path. */
246
- async readHotUpdate(relativePath: string) {
247
- const filePath = path.join(this.#outputDir, relativePath);
248
- // anything other than a hot update is a genuinely missing import, which should fail like it would in production
249
- if (!HOT_UPDATE_RE.test(filePath) || !filePath.startsWith(this.#outputDir + path.sep)) {
250
- return;
251
- }
252
- return fs.readFile(filePath, 'utf8');
253
- }
254
-
255
- /** Where assets imported by the Worker's code are emitted, laid out the way they're served. */
256
- get importedAssetsDir() {
257
- return path.join(this.#outputDir, IMPORTED_ASSETS_DIR);
258
- }
259
-
260
- /** This Worker's Miniflare options, any external Workers wrangler adds for its bindings, and the container images it needs. */
261
- async getMiniflareOptions(extraServiceBindings: Record<string, unknown>, inspectorEnabled: boolean) {
262
- const { config, environment } = this.#resolved;
263
- const remoteProxyConnectionString = await this.#getRemoteProxyConnectionString();
264
- const { workerOptions, externalWorkers } = unstable_getMiniflareWorkerOptions({ ...config, assets: undefined }, environment, {
265
- remoteProxyConnectionString,
266
- containerBuildId: this.#containerBuildId,
267
- });
268
- const { modulesRules: _modulesRules, ...options } = workerOptions;
269
- const containersEnabled = Boolean(config.containers?.length) && config.dev.enable_containers;
270
- return {
271
- externalWorkers,
272
- containerImages: containersEnabled ? getContainerImages(config, options.durableObjects) : [],
273
- worker: {
274
- ...options,
275
- name: this.name,
276
- durableObjects: {
277
- ...(options.durableObjects as Record<string, unknown> | undefined),
278
- // applies hot updates; ephemeral and never evicted so its I/O context lives as long as the modules it evaluates
279
- [HMR_RUNNER_CLASS]: { className: HMR_RUNNER_CLASS, unsafeUniqueKey: miniflare.kUnsafeEphemeralUniqueKey, unsafePreventEviction: true },
280
- },
281
- unsafeUseModuleFallbackService: true,
282
- bindings: { ...(options.bindings as Record<string, unknown> | undefined), [HMR_TOKEN_BINDING]: this.#hmrToken },
283
- serviceBindings: { ...(options.serviceBindings as Record<string, unknown> | undefined), ...extraServiceBindings },
284
- // rspack already bundled everything into one module, so module rules have nothing left to match
285
- modulesRoot: this.#outputDir,
286
- modules: this.#getModules(),
287
- unsafeInspectorProxy: inspectorEnabled,
288
- },
289
- };
290
- }
291
-
292
- async dispose() {
293
- await this.#closeWatcher();
294
- await this.#remoteProxy?.session.dispose();
295
- this.#remoteProxy = null;
296
- }
297
- }