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
@@ -1,237 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import fs from 'node:fs';
3
- import { isBuiltin } from 'node:module';
4
- import path from 'node:path';
5
-
6
- import { getModuleTypes } from './module-rules.js';
7
- import { getNodeJsCompat } from './nodejs-compat.js';
8
-
9
- import type { ResolvedWorker } from './config.js';
10
- import type { ModuleType } from './module-rules.js';
11
- import type { NodeJsCompat } from './nodejs-compat.js';
12
- import type { CloudflarePluginOptions } from './options.js';
13
- import type { Compiler, RspackOptions, RspackPluginInstance } from '@rspack/core';
14
-
15
- /** The rspack plugin that holds generated modules, which dev rewrites when the Worker's exports change. */
16
- export type VirtualModules = InstanceType<Compiler['rspack']['experiments']['VirtualModulesPlugin']>;
17
-
18
- const PLUGIN_NAME = 'rspack-plugin-cloudflare';
19
- const TYPESCRIPT_RE = /\.[cm]?tsx?$/;
20
- // the static asset types Vite also imports as URLs; .txt stays a Text module, as wrangler treats it
21
- const ASSET_RE = /\.(?:apng|avif|bmp|cur|eot|flac|gif|ico|jfif|jpe?g|jxl|m4a|mov|mp3|mp4|ogg|opus|otf|pdf|pjp|pjpeg|png|svg|ttf|vtt|wav|webm|webmanifest|webp|woff2?|aac)$/i;
22
- // `?url` imports any file as a URL, like Vite
23
- const URL_QUERY_RE = /\?(?:[^#]*&)?url(?:[&=#]|$)/;
24
-
25
- /** Output subdirectory for assets Worker code imports, laid out the way the assets directory serves them. */
26
- export const IMPORTED_ASSETS_DIR = 'imported-assets';
27
-
28
- interface AdditionalModule {
29
- /** File name in the output directory, which is also how the bundle imports it. */
30
- fileName: string;
31
- type: 'CompiledWasm' | 'Data';
32
- }
33
-
34
- /** Copies imported `.wasm`/`.bin` files next to the bundle, where workerd loads them as their own modules. */
35
- export class AdditionalModulesPlugin implements RspackPluginInstance {
36
- readonly #files = new Map<string, { sourcePath: string; type: AdditionalModule['type']; }>();
37
-
38
- /** Every file emitted so far; dev passes these to Miniflare, since rspack's incremental asset list can leave them out. */
39
- get modules(): AdditionalModule[] {
40
- return [...this.#files].map(([fileName, { type }]) => {
41
- return { fileName, type };
42
- });
43
- }
44
-
45
- /** Records a file to emit and returns the specifier the bundle should import it by. */
46
- add(sourcePath: string, type: AdditionalModule['type']) {
47
- const hash = createHash('sha1').update(fs.readFileSync(sourcePath)).digest('hex')
48
- .slice(0, 16);
49
- const fileName = `${hash}-${path.basename(sourcePath)}`;
50
- this.#files.set(fileName, { sourcePath, type });
51
- return `./${fileName}`;
52
- }
53
-
54
- apply(compiler: Compiler) {
55
- const { Compilation, sources } = compiler.rspack;
56
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
57
- compilation.hooks.processAssets.tap({ name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL }, () => {
58
- for (const [fileName, { sourcePath }] of this.#files) {
59
- compilation.emitAsset(fileName, new sources.RawSource(fs.readFileSync(sourcePath)));
60
- compilation.fileDependencies.add(sourcePath);
61
- }
62
- });
63
- });
64
- }
65
- }
66
-
67
- function createExternals(nodeJsCompat: NodeJsCompat | undefined, moduleTypes: Map<string, ModuleType>, additionalModules: AdditionalModulesPlugin) {
68
- type ExternalsCallback = (error?: Error, result?: string) => void;
69
- return ({ request, context }: { request?: string; context?: string; }, callback: ExternalsCallback) => {
70
- if (!request) {
71
- callback();
72
- return;
73
- }
74
- if (request.startsWith('cloudflare:')) {
75
- callback(undefined, request);
76
- return;
77
- }
78
- if (nodeJsCompat) {
79
- const native = nodeJsCompat.externals.get(request);
80
- if (native) {
81
- callback(undefined, native);
82
- return;
83
- }
84
- // a builtin the preset doesn't know about yet; workerd only resolves the node: form
85
- if (isBuiltin(request) && !nodeJsCompat.polyfills.has(request)) {
86
- callback(undefined, request.startsWith('node:') ? request : `node:${request}`);
87
- return;
88
- }
89
- }
90
- const filePath = request.replace(/\?.*$/, '');
91
- const type = moduleTypes.get(path.extname(filePath));
92
- const isModule = type === 'CompiledWasm' || type === 'Data';
93
- if (isModule && !URL_QUERY_RE.test(request) && context && (filePath.startsWith('.') || path.isAbsolute(filePath))) {
94
- callback(undefined, additionalModules.add(path.resolve(context, filePath), type));
95
- return;
96
- }
97
- callback();
98
- };
99
- }
100
-
101
- /** Text modules inline as strings; with an assets directory, static files and `?url` imports become URLs served from it. */
102
- function getAssetRules(worker: ResolvedWorker, textExtensions: Set<string>) {
103
- const textRule = { test: (file: string) => textExtensions.has(path.extname(file)), type: 'asset/source' };
104
- if (!worker.assets) {
105
- return [textRule];
106
- }
107
- const generator = {
108
- filename: 'assets/[name].[contenthash:8][ext]',
109
- outputPath: IMPORTED_ASSETS_DIR,
110
- // served from the root of the assets directory, not the Worker's own public path
111
- publicPath: '/',
112
- };
113
- return [
114
- { resourceQuery: URL_QUERY_RE, type: 'asset/resource', generator },
115
- textRule,
116
- { test: ASSET_RE, type: 'asset/resource', generator },
117
- ];
118
- }
119
-
120
- /** Builds the rspack config for the Worker bundle: a single ESM file workerd can load as-is. */
121
- export function createWorkerConfig(options: {
122
- compiler: Compiler;
123
- worker: ResolvedWorker;
124
- pluginOptions: CloudflarePluginOptions;
125
- outputDir: string;
126
- /** The module to bundle. */
127
- entry: string;
128
- /** Source for `entry` when it isn't a real file, like dev's wrapper around `main`. */
129
- entrySource?: string;
130
- mode: 'development' | 'production';
131
- /** Builds in rspack's HMR runtime so dev can update the running Worker in place. */
132
- hot?: boolean;
133
- /** Where HMR imports update chunks from; workerd has no import.meta.url to derive it from. */
134
- publicPath?: string;
135
- }): { config: RspackOptions; virtualModules: VirtualModules; additionalModules: AdditionalModulesPlugin; } {
136
- const { compiler, worker, pluginOptions, outputDir, entry, entrySource, mode, hot = false, publicPath = '/' } = options;
137
- const { rspack } = compiler;
138
- const moduleTypes = getModuleTypes(worker);
139
- const textExtensions = new Set([...moduleTypes].filter(([, type]) => type === 'Text').map(([extension]) => extension));
140
- const additionalModules = new AdditionalModulesPlugin();
141
- const nodeJsCompat = getNodeJsCompat(worker);
142
-
143
- const virtualModules: Record<string, string> = {};
144
- const entries = [entry];
145
- if (entrySource !== undefined) {
146
- virtualModules[entry] = entrySource;
147
- }
148
- if (nodeJsCompat?.injectSource) {
149
- // runs before the Worker so injected globals like `process` exist while its modules evaluate
150
- const injectPath = path.join(worker.rootDir, '.wrangler', 'tmp', `rspack-${worker.name}`, 'nodejs-compat-inject.js');
151
- virtualModules[injectPath] = nodeJsCompat.injectSource;
152
- entries.unshift(injectPath);
153
- }
154
-
155
- const plugins: RspackPluginInstance[] = [
156
- new rspack.DefinePlugin(worker.config.define),
157
- // workerd loads a single module here, so keep dynamic imports in the entry chunk
158
- new rspack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
159
- additionalModules,
160
- ];
161
- const polyfills = nodeJsCompat?.polyfills;
162
- if (polyfills && polyfills.size > 0) {
163
- // rspack reads `node:` specifiers as a URL scheme that resolve.alias never sees, so swap polyfills in before resolving
164
- plugins.push(new rspack.NormalModuleReplacementPlugin(/^(?:node:)?[a-z_]/, (resource: { request: string; }) => {
165
- const polyfill = polyfills.get(resource.request);
166
- if (polyfill) {
167
- resource.request = polyfill;
168
- }
169
- }));
170
- }
171
- const virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin(virtualModules);
172
- plugins.push(virtualModulesPlugin);
173
- if (hot) {
174
- plugins.push(new rspack.HotModuleReplacementPlugin());
175
- }
176
-
177
- let config: RspackOptions = {
178
- name: `cloudflare:${worker.name}`,
179
- mode,
180
- context: worker.rootDir,
181
- target: ['webworker', 'es2024'],
182
- entry: { index: entries },
183
- output: {
184
- path: outputDir,
185
- filename: 'index.js',
186
- module: true,
187
- chunkFormat: 'module',
188
- library: { type: 'module' },
189
- clean: true,
190
- publicPath,
191
- },
192
- externalsType: 'module-import',
193
- externals: [createExternals(nodeJsCompat, moduleTypes, additionalModules)],
194
- resolve: {
195
- extensions: ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json'],
196
- extensionAlias: { '.js': ['.ts', '.tsx', '.js'], '.mjs': ['.mts', '.mjs'] },
197
- conditionNames: ['workerd', 'worker', 'browser', 'module', 'import', 'default'],
198
- alias: worker.config.alias,
199
- },
200
- module: {
201
- rules: [
202
- {
203
- test: TYPESCRIPT_RE,
204
- loader: 'builtin:swc-loader',
205
- options: {
206
- jsc: {
207
- parser: { syntax: 'typescript', tsx: true, decorators: true },
208
- target: 'es2024',
209
- },
210
- },
211
- type: 'javascript/auto',
212
- },
213
- { oneOf: getAssetRules(worker, textExtensions) },
214
- ],
215
- },
216
- devtool: 'source-map',
217
- optimization: {
218
- // wrangler doesn't minify by default either, and readable stack traces matter more on the server
219
- minimize: false,
220
- // a failed dev build must leave the last good bundle in place, since restarting another Worker reloads it from disk
221
- emitOnErrors: false,
222
- },
223
- plugins,
224
- performance: { hints: false },
225
- watchOptions: {
226
- // dev's generated entry is virtual and the bundle is written under .wrangler, so the watcher would see both as changes
227
- ignored: /[/\\](?:\.git|node_modules|\.wrangler)[/\\]/,
228
- },
229
- stats: 'errors-warnings',
230
- infrastructureLogging: compiler.options.infrastructureLogging,
231
- };
232
-
233
- if (pluginOptions.worker) {
234
- config = pluginOptions.worker(config, { name: worker.name }) ?? config;
235
- }
236
- return { config, virtualModules: virtualModulesPlugin, additionalModules };
237
- }