rspack-plugin-cloudflare 0.0.0-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.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -2
  3. package/dist/assets.d.ts +31 -0
  4. package/dist/assets.js +112 -0
  5. package/dist/assets.js.map +1 -0
  6. package/dist/build.d.ts +216 -0
  7. package/dist/build.js +140 -0
  8. package/dist/build.js.map +1 -0
  9. package/dist/config.d.ts +19 -0
  10. package/dist/config.js +103 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/containers.d.ts +30 -0
  13. package/dist/containers.js +167 -0
  14. package/dist/containers.js.map +1 -0
  15. package/dist/dev-entry.d.ts +11 -0
  16. package/dist/dev-entry.js +44 -0
  17. package/dist/dev-entry.js.map +1 -0
  18. package/dist/dev-worker.d.ts +73 -0
  19. package/dist/dev-worker.js +247 -0
  20. package/dist/dev-worker.js.map +1 -0
  21. package/dist/dev.d.ts +28 -0
  22. package/dist/dev.js +422 -0
  23. package/dist/dev.js.map +1 -0
  24. package/dist/http.d.ts +23 -0
  25. package/dist/http.js +89 -0
  26. package/dist/http.js.map +1 -0
  27. package/dist/index.d.ts +10 -0
  28. package/dist/index.js +139 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/inspector.d.ts +5 -0
  31. package/dist/inspector.js +41 -0
  32. package/dist/inspector.js.map +1 -0
  33. package/dist/miniflare.d.ts +1 -0
  34. package/dist/miniflare.js +6 -0
  35. package/dist/miniflare.js.map +1 -0
  36. package/dist/module-rules.d.ts +4 -0
  37. package/dist/module-rules.js +29 -0
  38. package/dist/module-rules.js.map +1 -0
  39. package/dist/nodejs-compat.d.ts +14 -0
  40. package/dist/nodejs-compat.js +46 -0
  41. package/dist/nodejs-compat.js.map +1 -0
  42. package/dist/options.d.ts +45 -0
  43. package/dist/options.js +2 -0
  44. package/dist/options.js.map +1 -0
  45. package/dist/routing.d.ts +12 -0
  46. package/dist/routing.js +40 -0
  47. package/dist/routing.js.map +1 -0
  48. package/dist/tunnel.d.ts +15 -0
  49. package/dist/tunnel.js +94 -0
  50. package/dist/tunnel.js.map +1 -0
  51. package/dist/worker-config.d.ts +42 -0
  52. package/dist/worker-config.js +194 -0
  53. package/dist/worker-config.js.map +1 -0
  54. package/package.json +91 -5
  55. package/runtime/dev-runtime.js +265 -0
  56. package/src/assets.ts +148 -0
  57. package/src/build.ts +153 -0
  58. package/src/config.ts +138 -0
  59. package/src/containers.ts +183 -0
  60. package/src/dev-entry.ts +50 -0
  61. package/src/dev-worker.ts +297 -0
  62. package/src/dev.ts +478 -0
  63. package/src/http.ts +102 -0
  64. package/src/index.ts +164 -0
  65. package/src/inspector.ts +44 -0
  66. package/src/miniflare.ts +7 -0
  67. package/src/module-rules.ts +36 -0
  68. package/src/nodejs-compat.ts +63 -0
  69. package/src/options.ts +46 -0
  70. package/src/routing.ts +48 -0
  71. package/src/tunnel.ts +106 -0
  72. package/src/worker-config.ts +237 -0
package/dist/index.js ADDED
@@ -0,0 +1,139 @@
1
+ import { buildWorkers, copyImportedAssets } from './build.js';
2
+ import { getWorkerResolvers } from './config.js';
3
+ import { DevSession } from './dev.js';
4
+ import { startTunnel } from './tunnel.js';
5
+ const PLUGIN_NAME = 'rspack-plugin-cloudflare';
6
+ // listen addresses a tunnel can't dial by name, so it reaches the dev server through localhost instead
7
+ const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', 'local-ip', 'local-ipv4', 'local-ipv6']);
8
+ function getDevServerOrigin(server) {
9
+ const address = server.server?.address();
10
+ const port = typeof address === 'object' && address ? address.port : Number(server.options.port);
11
+ const serverOption = server.options.server;
12
+ const serverType = typeof serverOption === 'object' ? serverOption.type : serverOption;
13
+ const protocol = serverType === undefined || serverType === 'http' ? 'http' : 'https';
14
+ const { host } = server.options;
15
+ const hostname = !host || WILDCARD_HOSTS.has(host) ? 'localhost' : host;
16
+ return new URL(`${protocol}://${hostname}:${port}`);
17
+ }
18
+ /** Lets the tunnel's hostnames past the dev server's Host header check. */
19
+ function allowHosts(server, urls) {
20
+ const { allowedHosts } = server.options;
21
+ if (allowedHosts === 'all') {
22
+ return;
23
+ }
24
+ const hostnames = urls.map(url => new URL(url).hostname);
25
+ // a list keeps what 'auto' allowed, since localhost, IPs and the configured host always pass
26
+ if (Array.isArray(allowedHosts)) {
27
+ server.options.allowedHosts = [...allowedHosts, ...hostnames];
28
+ }
29
+ else if (allowedHosts && allowedHosts !== 'auto') {
30
+ server.options.allowedHosts = [allowedHosts, ...hostnames];
31
+ }
32
+ else {
33
+ server.options.allowedHosts = hostnames;
34
+ }
35
+ }
36
+ function getSocketPath(server) {
37
+ const socketOptions = server.options.webSocketServer;
38
+ if (typeof socketOptions === 'object' && socketOptions && typeof socketOptions.options?.path === 'string') {
39
+ return socketOptions.options.path;
40
+ }
41
+ return '/ws';
42
+ }
43
+ export class CloudflarePlugin {
44
+ #tunnel;
45
+ options;
46
+ constructor(options = {}) {
47
+ this.options = options;
48
+ }
49
+ async #openTunnel(server, entry, logger) {
50
+ const { tunnel: tunnelOption } = this.options;
51
+ if (!entry || !tunnelOption) {
52
+ return;
53
+ }
54
+ logger.warn('Starting a Cloudflare Tunnel: anyone with its URL can reach this dev server and its Worker\'s local bindings.');
55
+ this.#tunnel = await startTunnel({
56
+ origin: getDevServerOrigin(server),
57
+ tunnel: tunnelOption === true ? {} : tunnelOption,
58
+ config: entry.config,
59
+ cwd: entry.rootDir,
60
+ });
61
+ allowHosts(server, this.#tunnel.urls);
62
+ for (const url of this.#tunnel.urls) {
63
+ logger.info(`Tunnel: ${url}`);
64
+ }
65
+ }
66
+ apply(compiler) {
67
+ const logger = compiler.getInfrastructureLogger(PLUGIN_NAME);
68
+ const resolvers = getWorkerResolvers(compiler.context, this.options);
69
+ let session;
70
+ // `rspack serve` builds the dev server from these options after plugins apply, so wrapping them here hooks us in
71
+ const devServer = compiler.options.devServer;
72
+ if (devServer) {
73
+ const { setupMiddlewares, onListening } = devServer;
74
+ devServer.setupMiddlewares = (middlewares, server) => {
75
+ const result = setupMiddlewares ? setupMiddlewares(middlewares, server) : middlewares;
76
+ session = new DevSession({ compiler, resolvers, pluginOptions: this.options, logger });
77
+ session.start({
78
+ waitUntilValid: () => new Promise((resolve) => {
79
+ if (server.middleware) {
80
+ server.middleware.waitUntilValid(() => resolve());
81
+ }
82
+ else {
83
+ resolve();
84
+ }
85
+ }),
86
+ sendToClients: (type, data) => {
87
+ if (server.webSocketServer) {
88
+ server.sendMessage(server.webSocketServer.clients, type, data);
89
+ }
90
+ },
91
+ });
92
+ const activeSession = session;
93
+ // ahead of dev-middleware so `run_worker_first` decides who answers, not whatever the client build emitted
94
+ const devMiddlewareIndex = result.findIndex(middleware => typeof middleware === 'object' && middleware.name === '@rspack/dev-middleware');
95
+ result.splice(devMiddlewareIndex === -1 ? result.length : devMiddlewareIndex, 0, {
96
+ name: PLUGIN_NAME,
97
+ middleware: (req, res, next) => {
98
+ activeSession.handle(req, res, next).catch(next);
99
+ },
100
+ });
101
+ return result;
102
+ };
103
+ devServer.onListening = (server) => {
104
+ if (session && server.server) {
105
+ session.attachUpgradeHandler(server.server, getSocketPath(server));
106
+ }
107
+ if (this.options.tunnel) {
108
+ this.#openTunnel(server, resolvers[0]?.(), logger).catch((error) => {
109
+ logger.error(`Tunnel failed to start: ${error instanceof Error ? error.message : String(error)}`);
110
+ });
111
+ }
112
+ onListening?.(server);
113
+ };
114
+ }
115
+ // the Workers `rspack build` bundled, whose imported assets join the client output once it has emitted
116
+ let builtWorkers;
117
+ compiler.hooks.beforeRun.tapPromise(PLUGIN_NAME, async () => {
118
+ const workers = resolvers.map(resolve => resolve());
119
+ await buildWorkers({ compiler, workers, pluginOptions: this.options });
120
+ for (const worker of workers) {
121
+ logger.info(`Built ${worker.main ? 'Worker' : 'assets-only config'} "${worker.name}" into ${worker.outputDir}`);
122
+ }
123
+ builtWorkers = workers;
124
+ });
125
+ compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, async () => {
126
+ if (builtWorkers) {
127
+ await copyImportedAssets(builtWorkers);
128
+ }
129
+ });
130
+ compiler.hooks.shutdown.tapPromise(PLUGIN_NAME, async () => {
131
+ this.#tunnel?.close();
132
+ await session?.dispose();
133
+ });
134
+ }
135
+ }
136
+ export function cloudflare(options) {
137
+ return new CloudflarePlugin(options);
138
+ }
139
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAiB1C,MAAM,WAAW,GAAG,0BAA0B,CAAC;AAE/C,uGAAuG;AACvG,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC;AAE1F,SAAS,kBAAkB,CAAC,MAAuB;IAClD,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;IACzC,MAAM,IAAI,GAAG,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACjG,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;IAC3C,MAAM,UAAU,GAAG,OAAO,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;IACvF,MAAM,QAAQ,GAAG,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,MAAM,CAAC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UAAU,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAC3D,MAAM,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;YACpD,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;YACvE,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;gBAC9B,MAAM,CAAC,IAAI,CAAC,SAAS,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,oBAAoB,KAAK,MAAM,CAAC,IAAI,UAAU,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC;YACjH,CAAC;YACD,YAAY,GAAG,OAAO,CAAC;QACxB,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAC3D,IAAI,YAAY,EAAE,CAAC;gBAClB,MAAM,kBAAkB,CAAC,YAAY,CAAC,CAAC;YACxC,CAAC;QACF,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,WAAW,EAAE,KAAK,IAAI,EAAE;YAC1D,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,CAAC;YACtB,MAAM,OAAO,EAAE,OAAO,EAAE,CAAC;QAC1B,CAAC,CAAC,CAAC;IACJ,CAAC;CACD;AAED,MAAM,UAAU,UAAU,CAAC,OAAiC;IAC3D,OAAO,IAAI,gBAAgB,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export declare const DEBUG_PATH = "/__debug";
2
+ /** Resolves the inspector port: the configured one, or 9229 falling back to the next free port like the Vite plugin. */
3
+ export declare function resolveInspectorPort(option: number | false | undefined): Promise<number | undefined>;
4
+ /** A page that sends the browser to Cloudflare's hosted DevTools, connected to each Worker through Miniflare's inspector proxy. */
5
+ export declare function getDebugPageHtml(workerNames: string[], inspectorPort: number): string;
@@ -0,0 +1,41 @@
1
+ import net from 'node:net';
2
+ export const DEBUG_PATH = '/__debug';
3
+ const DEFAULT_INSPECTOR_PORT = 9229;
4
+ function isPortFree(port) {
5
+ return new Promise((resolve) => {
6
+ const server = net.createServer();
7
+ server.once('error', () => resolve(false));
8
+ server.listen(port, '127.0.0.1', () => {
9
+ server.close(() => resolve(true));
10
+ });
11
+ });
12
+ }
13
+ /** Resolves the inspector port: the configured one, or 9229 falling back to the next free port like the Vite plugin. */
14
+ export async function resolveInspectorPort(option) {
15
+ if (option === false) {
16
+ return;
17
+ }
18
+ if (option !== undefined) {
19
+ return option;
20
+ }
21
+ for (let port = DEFAULT_INSPECTOR_PORT; port < 65535; port++) {
22
+ if (await isPortFree(port)) {
23
+ return port;
24
+ }
25
+ }
26
+ }
27
+ /** A page that sends the browser to Cloudflare's hosted DevTools, connected to each Worker through Miniflare's inspector proxy. */
28
+ export function getDebugPageHtml(workerNames, inspectorPort) {
29
+ const urls = workerNames.map((name) => {
30
+ const params = new URLSearchParams({ theme: 'systemPreferred', debugger: 'true', ws: `localhost:${inspectorPort}/${name}`, domain: name });
31
+ return `https://devtools.devprod.cloudflare.dev/js_app?${params.toString()}`;
32
+ });
33
+ return `<!doctype html><script>
34
+ const [first, ...rest] = ${JSON.stringify(urls)};
35
+ for (const url of rest) {
36
+ window.open(url);
37
+ }
38
+ window.location.replace(first);
39
+ </script>`;
40
+ }
41
+ //# sourceMappingURL=inspector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspector.js","sourceRoot":"","sources":["../src/inspector.ts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,UAAU,CAAC;AAE3B,MAAM,CAAC,MAAM,UAAU,GAAG,UAAU,CAAC;AACrC,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,SAAS,UAAU,CAAC,IAAY;IAC/B,OAAO,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AO;2BACmB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;;;;;UAKrC,CAAC;AACX,CAAC"}
@@ -0,0 +1 @@
1
+ export declare const miniflare: typeof import("miniflare");
@@ -0,0 +1,6 @@
1
+ import { createRequire } from 'node:module';
2
+ // wrangler's Miniflare options target its own Miniflare build, so load that copy rather than whichever one is hoisted
3
+ const require = createRequire(import.meta.url);
4
+ const wranglerRequire = createRequire(require.resolve('wrangler/package.json'));
5
+ export const miniflare = wranglerRequire('miniflare');
6
+ //# sourceMappingURL=miniflare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"miniflare.js","sourceRoot":"","sources":["../src/miniflare.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,sHAAsH;AACtH,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,aAAa,CAAC,OAAO,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC,CAAC;AAEhF,MAAM,CAAC,MAAM,SAAS,GAAG,eAAe,CAAC,WAAW,CAA+B,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { ResolvedWorker } from './config.js';
2
+ export type ModuleType = 'CompiledWasm' | 'Data' | 'Text';
3
+ /** Maps file extensions to the non-JS module type wrangler would give them, with config rules taking precedence. */
4
+ export declare function getModuleTypes(worker: ResolvedWorker): Map<string, ModuleType>;
@@ -0,0 +1,29 @@
1
+ import path from 'node:path';
2
+ // wrangler's defaults, which apply after any rules in the config
3
+ const DEFAULT_RULES = [
4
+ { type: 'Text', globs: ['**/*.txt', '**/*.html', '**/*.sql'] },
5
+ { type: 'Data', globs: ['**/*.bin'] },
6
+ { type: 'CompiledWasm', globs: ['**/*.wasm', '**/*.wasm?module'] },
7
+ ];
8
+ const MODULE_TYPES = ['CompiledWasm', 'Data', 'Text'];
9
+ function isModuleType(type) {
10
+ return MODULE_TYPES.includes(type);
11
+ }
12
+ /** Maps file extensions to the non-JS module type wrangler would give them, with config rules taking precedence. */
13
+ export function getModuleTypes(worker) {
14
+ const types = new Map();
15
+ for (const rule of [...worker.config.rules, ...DEFAULT_RULES]) {
16
+ if (!isModuleType(rule.type)) {
17
+ continue;
18
+ }
19
+ for (const glob of rule.globs) {
20
+ // wrangler's module rules use `**/*.ext` style globs, so the extension is all that matters
21
+ const extension = path.extname(glob.replace(/\?.*$/, ''));
22
+ if (extension && !types.has(extension)) {
23
+ types.set(extension, rule.type);
24
+ }
25
+ }
26
+ }
27
+ return types;
28
+ }
29
+ //# sourceMappingURL=module-rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-rules.js","sourceRoot":"","sources":["../src/module-rules.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAM7B,iEAAiE;AACjE,MAAM,aAAa,GAA6C;IAC/D,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE;IAC9D,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,UAAU,CAAC,EAAE;IACrC,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,WAAW,EAAE,kBAAkB,CAAC,EAAE;CAClE,CAAC;AAEF,MAAM,YAAY,GAAsB,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,CAAwB,CAAC;AAEhG,SAAS,YAAY,CAAC,IAAY;IACjC,OAAO,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AACpC,CAAC;AAED,oHAAoH;AACpH,MAAM,UAAU,cAAc,CAAC,MAAsB;IACpD,MAAM,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,aAAa,CAAC,EAAE,CAAC;QAC/D,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,SAAS;QACV,CAAC;QACD,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC/B,2FAA2F;YAC3F,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;YAC1D,IAAI,SAAS,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;gBACxC,KAAK,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { ResolvedWorker } from './config.js';
2
+ export interface NodeJsCompat {
3
+ /** Builtin specifiers workerd provides natively, mapped to the specifier to import at runtime. */
4
+ externals: Map<string, string>;
5
+ /** Builtin specifiers workerd lacks, mapped to the unenv polyfill file that replaces them. */
6
+ polyfills: Map<string, string>;
7
+ /** A module that sets up injected globals like `process` and runs polyfills, when the preset needs any. */
8
+ injectSource: string | undefined;
9
+ }
10
+ /**
11
+ * Applies Cloudflare's unenv preset, as wrangler and the Vite plugin do: modules workerd has natively stay external,
12
+ * the rest are polyfilled, and globals like `process` are injected for older compatibility dates.
13
+ */
14
+ export declare function getNodeJsCompat(worker: ResolvedWorker): NodeJsCompat | undefined;
@@ -0,0 +1,46 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { getCloudflarePreset } from '@cloudflare/unenv-preset';
3
+ import { defineEnv } from 'unenv';
4
+ import { miniflare } from './miniflare.js';
5
+ function resolvePolyfill(specifier) {
6
+ // polyfills are this package's dependencies, which the user's project can't necessarily resolve
7
+ return fileURLToPath(import.meta.resolve(specifier));
8
+ }
9
+ function createInjectSource(inject, polyfills) {
10
+ const lines = [];
11
+ for (const [index, [globalName, specifier]] of Object.entries(inject).entries()) {
12
+ const [moduleSpecifier, exportName] = typeof specifier === 'string' ? [specifier, 'default'] : specifier;
13
+ if (!moduleSpecifier || !exportName) {
14
+ continue;
15
+ }
16
+ lines.push(`import { ${exportName} as inject${index} } from ${JSON.stringify(resolvePolyfill(moduleSpecifier))};`, `globalThis.${globalName} = inject${index};`);
17
+ }
18
+ for (const polyfill of polyfills) {
19
+ lines.push(`import ${JSON.stringify(resolvePolyfill(polyfill))};`);
20
+ }
21
+ return lines.length > 0 ? lines.join('\n') : undefined;
22
+ }
23
+ /**
24
+ * Applies Cloudflare's unenv preset, as wrangler and the Vite plugin do: modules workerd has natively stay external,
25
+ * the rest are polyfilled, and globals like `process` are injected for older compatibility dates.
26
+ */
27
+ export function getNodeJsCompat(worker) {
28
+ const { compatibility_date: compatibilityDate, compatibility_flags: compatibilityFlags } = worker.config;
29
+ if (!miniflare.getNodeCompat(compatibilityDate, compatibilityFlags).isNodejsCompatEnabled) {
30
+ return undefined;
31
+ }
32
+ const { env } = defineEnv({ presets: [getCloudflarePreset({ compatibilityDate, compatibilityFlags })] });
33
+ const nativeModules = new Set(env.external);
34
+ const externals = new Map();
35
+ const polyfills = new Map();
36
+ for (const [specifier, target] of Object.entries(env.alias)) {
37
+ if (nativeModules.has(target)) {
38
+ externals.set(specifier, target);
39
+ }
40
+ else {
41
+ polyfills.set(specifier, resolvePolyfill(target));
42
+ }
43
+ }
44
+ return { externals, polyfills, injectSource: createInjectSource(env.inject, env.polyfill) };
45
+ }
46
+ //# sourceMappingURL=nodejs-compat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodejs-compat.js","sourceRoot":"","sources":["../src/nodejs-compat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,EAAE,SAAS,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AAE,GAAG,MAAM,CAAC,MAAM,CAAC;IACzG,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,iBAAiB,EAAE,kBAAkB,CAAC,CAAC,qBAAqB,EAAE,CAAC;QAC3F,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,GAAG,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC,mBAAmB,CAAC,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACzG,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC5C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC5C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC5C,KAAK,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7D,IAAI,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YAC/B,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAClC,CAAC;aAAM,CAAC;YACP,SAAS,CAAC,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;IACD,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,kBAAkB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC7F,CAAC"}
@@ -0,0 +1,45 @@
1
+ import type { RspackOptions } from '@rspack/core';
2
+ import type { Unstable_Config } from 'wrangler';
3
+ export type WorkerConfig = Unstable_Config;
4
+ /** Overrides merged into the Wrangler config after it loads, or a function that edits or returns overrides. */
5
+ export type WorkerConfigCustomizer = Partial<WorkerConfig> | ((config: WorkerConfig) => Partial<WorkerConfig> | void);
6
+ export interface AuxiliaryWorkerOptions {
7
+ /** Wrangler config for the auxiliary Worker, relative to the rspack `context`. */
8
+ configPath: string;
9
+ /** Changes the auxiliary Worker's config in code, applied after its config file loads. */
10
+ config?: WorkerConfigCustomizer;
11
+ /** Where `rspack build` writes it, relative to its Wrangler config. Defaults to `dist/<worker name>`. */
12
+ outputDir?: string;
13
+ }
14
+ export interface TunnelOptions {
15
+ /** An existing named tunnel with a route to the dev server. Without one, a Quick Tunnel gets a random trycloudflare.com URL. */
16
+ name?: string;
17
+ /** Email addresses or `*@domain` patterns allowed through a Quick Tunnel, which then asks visitors to sign in. */
18
+ allowedMail?: string[];
19
+ }
20
+ export interface CloudflarePluginOptions {
21
+ /** Wrangler config file, relative to the rspack `context`. Defaults to the nearest wrangler.jsonc, wrangler.json or wrangler.toml at or above `context`. */
22
+ configPath?: string;
23
+ /** Changes the Worker config in code, applied after the config file loads. */
24
+ config?: WorkerConfigCustomizer;
25
+ /** Wrangler environment to use, like `wrangler --env`, for every Worker. Defaults to `CLOUDFLARE_ENV`. */
26
+ environment?: string;
27
+ /** More Workers the entry Worker reaches through service bindings, run and built alongside it. */
28
+ auxiliaryWorkers?: AuxiliaryWorkerOptions[];
29
+ /** Adjusts the rspack config used to bundle a Worker. Return a new config or mutate the one given. */
30
+ worker?: (config: RspackOptions, context: {
31
+ name: string;
32
+ }) => RspackOptions | void;
33
+ /** Where `rspack build` writes the Worker bundle and its generated `wrangler.json`, relative to the Wrangler config. Defaults to `dist/<worker name>`. */
34
+ outputDir?: string;
35
+ /** Where local binding state (KV, Durable Objects, etc.) lives in dev, relative to the Wrangler config. `false` keeps it in memory. Defaults to `.wrangler/state`, shared with `wrangler dev`. */
36
+ persistState?: boolean | {
37
+ path: string;
38
+ };
39
+ /** Port for the workerd inspector in dev, or `false` to turn it off. Defaults to 9229, or the next free port. */
40
+ inspectorPort?: number | false;
41
+ /** Connects bindings marked `remote: true` to their real resources on Cloudflare in dev. `false` keeps every binding local. */
42
+ remoteBindings?: boolean;
43
+ /** Shares the dev server publicly through a Cloudflare Tunnel once it's listening. */
44
+ tunnel?: boolean | TunnelOptions;
45
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ interface StaticRouting {
2
+ /** Paths that always go to the Worker. */
3
+ userWorker: RegExp[];
4
+ /** Paths that always skip the Worker, from `!/` rules. */
5
+ assetWorker: RegExp[];
6
+ }
7
+ /** Mirrors `assets.run_worker_first`, where `true` sends everything to the Worker and an array holds `/` and `!/` glob rules. */
8
+ export declare function parseStaticRouting(runWorkerFirst: boolean | string[] | undefined): StaticRouting;
9
+ type Route = 'worker' | 'asset' | 'asset-then-worker';
10
+ /** Negative rules win over positive ones, matching Cloudflare's router. */
11
+ export declare function routeRequest(routing: StaticRouting, pathname: string, hasAssets: boolean): Route;
12
+ export {};
@@ -0,0 +1,40 @@
1
+ function ruleToRegExp(rule) {
2
+ const escaped = rule.split('*').map(part => part.replaceAll(/[$()+.?[\\\]^{|}]/g, String.raw `\$&`));
3
+ return new RegExp(`^${escaped.join('.*')}$`);
4
+ }
5
+ /** Mirrors `assets.run_worker_first`, where `true` sends everything to the Worker and an array holds `/` and `!/` glob rules. */
6
+ export function parseStaticRouting(runWorkerFirst) {
7
+ if (runWorkerFirst === true) {
8
+ return { userWorker: [/^\/.*$/], assetWorker: [] };
9
+ }
10
+ const routing = { userWorker: [], assetWorker: [] };
11
+ if (!Array.isArray(runWorkerFirst)) {
12
+ return routing;
13
+ }
14
+ for (const rule of runWorkerFirst) {
15
+ if (rule.startsWith('!/')) {
16
+ routing.assetWorker.push(ruleToRegExp(rule.slice(1)));
17
+ }
18
+ else if (rule.startsWith('/')) {
19
+ routing.userWorker.push(ruleToRegExp(rule));
20
+ }
21
+ else {
22
+ throw new Error(`Invalid \`run_worker_first\` rule '${rule}': rules must start with '/' or '!/'.`);
23
+ }
24
+ }
25
+ return routing;
26
+ }
27
+ /** Negative rules win over positive ones, matching Cloudflare's router. */
28
+ export function routeRequest(routing, pathname, hasAssets) {
29
+ if (!hasAssets) {
30
+ return 'worker';
31
+ }
32
+ if (routing.assetWorker.some(rule => rule.test(pathname))) {
33
+ return 'asset';
34
+ }
35
+ if (routing.userWorker.some(rule => rule.test(pathname))) {
36
+ return 'worker';
37
+ }
38
+ return 'asset-then-worker';
39
+ }
40
+ //# sourceMappingURL=routing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing.js","sourceRoot":"","sources":["../src/routing.ts"],"names":[],"mappings":"AAOA,SAAS,YAAY,CAAC,IAAY;IACjC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,oBAAoB,EAAE,MAAM,CAAC,GAAG,CAAA,KAAK,CAAC,CAAC,CAAC;IACpG,OAAO,IAAI,MAAM,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC9C,CAAC;AAED,iIAAiI;AACjI,MAAM,UAAU,kBAAkB,CAAC,cAA8C;IAChF,IAAI,cAAc,KAAK,IAAI,EAAE,CAAC;QAC7B,OAAO,EAAE,UAAU,EAAE,CAAC,QAAQ,CAAC,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;IACpD,CAAC;IACD,MAAM,OAAO,GAAkB,EAAE,UAAU,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;IACnE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,CAAC;QACpC,OAAO,OAAO,CAAC;IAChB,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,cAAc,EAAE,CAAC;QACnC,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3B,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACvD,CAAC;aAAM,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACjC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7C,CAAC;aAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,sCAAsC,IAAI,uCAAuC,CAAC,CAAC;QACpG,CAAC;IACF,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAID,2EAA2E;AAC3E,MAAM,UAAU,YAAY,CAAC,OAAsB,EAAE,QAAgB,EAAE,SAAkB;IACxF,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,IAAI,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC;QAC3D,OAAO,OAAO,CAAC;IAChB,CAAC;IACD,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC;QAC1D,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,OAAO,mBAAmB,CAAC;AAC5B,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { TunnelOptions, WorkerConfig } from './options.js';
2
+ export interface Tunnel {
3
+ urls: string[];
4
+ close: () => void;
5
+ }
6
+ /**
7
+ * Shares the dev server through a Cloudflare Tunnel: a Quick Tunnel on a random trycloudflare.com URL, or a named
8
+ * tunnel whose routes point at the dev server. wrangler runs it, so it downloads and updates cloudflared as needed.
9
+ */
10
+ export declare function startTunnel(options: {
11
+ origin: URL;
12
+ tunnel: TunnelOptions;
13
+ config: WorkerConfig;
14
+ cwd: string;
15
+ }): Promise<Tunnel>;
package/dist/tunnel.js ADDED
@@ -0,0 +1,94 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { unstable_resolveNamedTunnel } from 'wrangler';
5
+ const QUICK_TUNNEL_URL_RE = /https:\/\/[\da-z-]+\.trycloudflare\.com/;
6
+ // cloudflared logs this once the edge accepts the tunnel, which is when the public URL starts working
7
+ const CONNECTED_RE = /Registered tunnel connection/;
8
+ const STARTUP_TIMEOUT_MS = 30000;
9
+ function getWranglerBin() {
10
+ const require = createRequire(import.meta.url);
11
+ return path.join(path.dirname(require.resolve('wrangler/package.json')), 'bin', 'wrangler.js');
12
+ }
13
+ function stopProcessTree(child) {
14
+ if (child.exitCode !== null || child.pid === undefined) {
15
+ return;
16
+ }
17
+ if (process.platform === 'win32') {
18
+ // Windows has no SIGTERM for wrangler to forward, so cloudflared would outlive it without killing the whole tree
19
+ spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { stdio: 'ignore' });
20
+ }
21
+ else {
22
+ child.kill('SIGTERM');
23
+ }
24
+ }
25
+ function waitUntilConnected(child, isNamed) {
26
+ return new Promise((resolve, reject) => {
27
+ let output = '';
28
+ let quickUrl;
29
+ let settled = false;
30
+ function fail(error) {
31
+ if (!settled) {
32
+ settled = true;
33
+ stopProcessTree(child);
34
+ reject(error);
35
+ }
36
+ }
37
+ function onData(data) {
38
+ // only kept for the error message, so a long-running tunnel doesn't keep growing it
39
+ if (output.length < 20000) {
40
+ output += String(data);
41
+ }
42
+ quickUrl ??= QUICK_TUNNEL_URL_RE.exec(output)?.[0];
43
+ if (!settled && CONNECTED_RE.test(output) && (isNamed || quickUrl)) {
44
+ settled = true;
45
+ resolve(quickUrl);
46
+ }
47
+ }
48
+ AbortSignal.timeout(STARTUP_TIMEOUT_MS).addEventListener('abort', () => {
49
+ fail(new Error(`The tunnel didn't connect within ${STARTUP_TIMEOUT_MS / 1000}s:\n${output}`));
50
+ });
51
+ child.stdout?.on('data', onData);
52
+ child.stderr?.on('data', onData);
53
+ child.once('error', fail);
54
+ child.once('exit', (code) => {
55
+ fail(new Error(`wrangler tunnel exited with code ${String(code)}:\n${output}`));
56
+ });
57
+ });
58
+ }
59
+ /**
60
+ * Shares the dev server through a Cloudflare Tunnel: a Quick Tunnel on a random trycloudflare.com URL, or a named
61
+ * tunnel whose routes point at the dev server. wrangler runs it, so it downloads and updates cloudflared as needed.
62
+ */
63
+ export async function startTunnel(options) {
64
+ const { origin, tunnel, config } = options;
65
+ const args = ['tunnel'];
66
+ const env = { ...process.env };
67
+ let urls = [];
68
+ if (tunnel.name === undefined) {
69
+ args.push('quick-start', origin.href, ...(tunnel.allowedMail ?? []).flatMap(mail => ['--allowed-mail', mail]));
70
+ if (origin.protocol === 'https:') {
71
+ // the dev server's certificate is for the developer's own hostname, never the loopback address cloudflared dials
72
+ env.NO_TLS_VERIFY = 'true';
73
+ }
74
+ }
75
+ else {
76
+ if (tunnel.allowedMail?.length) {
77
+ throw new Error('`tunnel.allowedMail` only works with Quick Tunnels; protect a named tunnel with Cloudflare Access instead.');
78
+ }
79
+ // also checks the tunnel has a route to this dev server, which is the usual setup mistake
80
+ const { hostnames } = await unstable_resolveNamedTunnel(tunnel.name, origin, {
81
+ accountId: config.account_id,
82
+ complianceRegion: config.compliance_region,
83
+ });
84
+ urls = hostnames.map(hostname => `https://${hostname}`);
85
+ args.push('run', tunnel.name);
86
+ }
87
+ const child = spawn(process.execPath, [getWranglerBin(), ...args], { cwd: options.cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
88
+ const quickUrl = await waitUntilConnected(child, tunnel.name !== undefined);
89
+ if (quickUrl) {
90
+ urls = [quickUrl];
91
+ }
92
+ return { urls, close: () => stopProcessTree(child) };
93
+ }
94
+ //# sourceMappingURL=tunnel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tunnel.js","sourceRoot":"","sources":["../src/tunnel.ts"],"names":[],"mappings":"A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,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,cAAc,EAAE,EAAE,GAAG,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IACjI,MAAM,QAAQ,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC;IAC5E,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IACnB,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,eAAe,CAAC,KAAK,CAAC,EAAE,CAAC;AACtD,CAAC"}
@@ -0,0 +1,42 @@
1
+ import type { ResolvedWorker } from './config.js';
2
+ import type { CloudflarePluginOptions } from './options.js';
3
+ import type { Compiler, RspackOptions, RspackPluginInstance } from '@rspack/core';
4
+ /** The rspack plugin that holds generated modules, which dev rewrites when the Worker's exports change. */
5
+ export type VirtualModules = InstanceType<Compiler['rspack']['experiments']['VirtualModulesPlugin']>;
6
+ /** Output subdirectory for assets Worker code imports, laid out the way the assets directory serves them. */
7
+ export declare const IMPORTED_ASSETS_DIR = "imported-assets";
8
+ interface AdditionalModule {
9
+ /** File name in the output directory, which is also how the bundle imports it. */
10
+ fileName: string;
11
+ type: 'CompiledWasm' | 'Data';
12
+ }
13
+ /** Copies imported `.wasm`/`.bin` files next to the bundle, where workerd loads them as their own modules. */
14
+ export declare class AdditionalModulesPlugin implements RspackPluginInstance {
15
+ #private;
16
+ /** Every file emitted so far; dev passes these to Miniflare, since rspack's incremental asset list can leave them out. */
17
+ get modules(): AdditionalModule[];
18
+ /** Records a file to emit and returns the specifier the bundle should import it by. */
19
+ add(sourcePath: string, type: AdditionalModule['type']): string;
20
+ apply(compiler: Compiler): void;
21
+ }
22
+ /** Builds the rspack config for the Worker bundle: a single ESM file workerd can load as-is. */
23
+ export declare function createWorkerConfig(options: {
24
+ compiler: Compiler;
25
+ worker: ResolvedWorker;
26
+ pluginOptions: CloudflarePluginOptions;
27
+ outputDir: string;
28
+ /** The module to bundle. */
29
+ entry: string;
30
+ /** Source for `entry` when it isn't a real file, like dev's wrapper around `main`. */
31
+ entrySource?: string;
32
+ mode: 'development' | 'production';
33
+ /** Builds in rspack's HMR runtime so dev can update the running Worker in place. */
34
+ hot?: boolean;
35
+ /** Where HMR imports update chunks from; workerd has no import.meta.url to derive it from. */
36
+ publicPath?: string;
37
+ }): {
38
+ config: RspackOptions;
39
+ virtualModules: VirtualModules;
40
+ additionalModules: AdditionalModulesPlugin;
41
+ };
42
+ export {};