wrangler 0.0.0-e9ab55a → 0.0.0-e9fae558

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 (115) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +117 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -125
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/new-worker-scheduled.js +17 -0
  27. package/templates/new-worker-scheduled.ts +32 -0
  28. package/templates/new-worker.js +15 -0
  29. package/templates/new-worker.ts +33 -0
  30. package/templates/no-op-worker.js +10 -0
  31. package/templates/pages-dev-pipeline.ts +31 -0
  32. package/templates/pages-dev-util.ts +55 -0
  33. package/templates/pages-shim.ts +9 -0
  34. package/templates/pages-template-plugin.ts +190 -0
  35. package/templates/pages-template-worker.ts +198 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +8 -0
  39. package/wrangler-dist/cli.d.ts +1732 -0
  40. package/wrangler-dist/cli.js +141470 -110893
  41. package/wrangler-dist/wasm-sync.wasm +0 -0
  42. package/import_meta_url.js +0 -3
  43. package/miniflare-config-stubs/.env.empty +0 -0
  44. package/miniflare-config-stubs/package.empty.json +0 -1
  45. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  46. package/pages/functions/buildWorker.ts +0 -62
  47. package/pages/functions/filepath-routing.test.ts +0 -39
  48. package/pages/functions/filepath-routing.ts +0 -228
  49. package/pages/functions/identifiers.ts +0 -78
  50. package/pages/functions/routes.ts +0 -158
  51. package/pages/functions/template-worker.ts +0 -136
  52. package/src/__tests__/clipboardy-mock.js +0 -4
  53. package/src/__tests__/dev.test.tsx +0 -67
  54. package/src/__tests__/index.test.ts +0 -287
  55. package/src/__tests__/jest.setup.ts +0 -22
  56. package/src/__tests__/kv.test.ts +0 -1126
  57. package/src/__tests__/mock-cfetch.ts +0 -171
  58. package/src/__tests__/mock-dialogs.ts +0 -65
  59. package/src/__tests__/publish.test.ts +0 -102
  60. package/src/__tests__/run-in-tmp.ts +0 -19
  61. package/src/__tests__/run-wrangler.ts +0 -32
  62. package/src/api/form_data.ts +0 -131
  63. package/src/api/preview.ts +0 -128
  64. package/src/api/worker.ts +0 -155
  65. package/src/cfetch/index.ts +0 -102
  66. package/src/cfetch/internal.ts +0 -69
  67. package/src/cli.ts +0 -9
  68. package/src/config.ts +0 -646
  69. package/src/dev.tsx +0 -784
  70. package/src/dialogs.tsx +0 -77
  71. package/src/index.tsx +0 -1928
  72. package/src/inspect.ts +0 -543
  73. package/src/kv.tsx +0 -276
  74. package/src/module-collection.ts +0 -64
  75. package/src/pages.tsx +0 -1040
  76. package/src/proxy.ts +0 -302
  77. package/src/publish.ts +0 -382
  78. package/src/sites.tsx +0 -118
  79. package/src/tail.tsx +0 -73
  80. package/src/user.tsx +0 -1027
  81. package/static-asset-facade.js +0 -47
  82. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  83. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  84. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  85. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  86. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  87. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  88. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  89. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  90. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  91. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  92. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  93. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  94. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  95. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  96. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  97. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  98. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  99. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  100. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  101. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  102. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  103. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  104. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  105. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  106. package/vendor/wrangler-mime/LICENSE +0 -21
  107. package/vendor/wrangler-mime/Mime.js +0 -97
  108. package/vendor/wrangler-mime/README.md +0 -187
  109. package/vendor/wrangler-mime/cli.js +0 -46
  110. package/vendor/wrangler-mime/index.js +0 -4
  111. package/vendor/wrangler-mime/lite.js +0 -4
  112. package/vendor/wrangler-mime/package.json +0 -52
  113. package/vendor/wrangler-mime/types/other.js +0 -1
  114. package/vendor/wrangler-mime/types/standard.js +0 -1
  115. package/wrangler-dist/cli.js.map +0 -7
package/src/proxy.ts DELETED
@@ -1,302 +0,0 @@
1
- import { connect } from "node:http2";
2
- import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
3
- import { createServer } from "node:http";
4
- import type {
5
- IncomingHttpHeaders,
6
- RequestListener,
7
- IncomingMessage,
8
- ServerResponse,
9
- Server,
10
- } from "node:http";
11
- import WebSocket from "faye-websocket";
12
- import serveStatic from "serve-static";
13
- import type { CfPreviewToken } from "./api/preview";
14
- import { useEffect, useRef } from "react";
15
-
16
- /**
17
- * `usePreviewServer` is a React hook that creates a local development
18
- * server that can be used to develop a Worker.
19
- *
20
- * When we run `wrangler dev`, we start by uploading the compiled worker
21
- * to the preview service, which responds with a preview token.
22
- * (see `useWorker`/`createWorker` for details.)
23
- * We can then use that token to connect to the preview server for a
24
- * great local development experience. Further, as we change the worker,
25
- * we can update the preview token transparently without having to restart
26
- * the development server.
27
- */
28
-
29
- /** Rewrite request headers to add the preview token. */
30
- function addCfPreviewTokenHeader(
31
- headers: IncomingHttpHeaders,
32
- previewTokenValue: string
33
- ) {
34
- headers["cf-workers-preview-token"] = previewTokenValue;
35
- }
36
-
37
- /**
38
- * Rewrite references in request headers
39
- * from the preview host to the local host.
40
- */
41
- function rewriteRemoteHostToLocalHostInHeaders(
42
- headers: IncomingHttpHeaders,
43
- remoteHost: string,
44
- localPort: number
45
- ) {
46
- for (const [name, value] of Object.entries(headers)) {
47
- // Rewrite the remote host to the local host.
48
- if (typeof value === "string" && value.includes(remoteHost)) {
49
- headers[name] = value
50
- .replaceAll(`https://${remoteHost}`, `http://localhost:${localPort}`)
51
- .replaceAll(remoteHost, `localhost:${localPort}`);
52
- }
53
- }
54
- }
55
-
56
- export function usePreviewServer({
57
- previewToken,
58
- publicRoot,
59
- port,
60
- }: {
61
- previewToken: CfPreviewToken | undefined;
62
- publicRoot: undefined | string;
63
- port: number;
64
- }) {
65
- /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
66
- const proxyServer = useRef<Server>();
67
- const proxy = (proxyServer.current ??= createProxyServer());
68
-
69
- /**
70
- * When we're not connected / getting a fresh token on changes,
71
- * we'd like to buffer streams/requests until we're connected.
72
- * Once connected, we can flush the buffered streams/requests.
73
- * streamBufferRef is used to buffer http/2 streams, while
74
- * requestResponseBufferRef is used to buffer http/1 requests.
75
- */
76
- const streamBufferRef = useRef<
77
- { stream: ServerHttp2Stream; headers: IncomingHttpHeaders }[]
78
- >([]);
79
- const requestResponseBufferRef = useRef<
80
- { request: IncomingMessage; response: ServerResponse }[]
81
- >([]);
82
-
83
- useEffect(() => {
84
- // If we don't have a token, that means either we're just starting up,
85
- // or we're refreshing the token.
86
- if (!previewToken) {
87
- const cleanupListeners: (() => void)[] = [];
88
- const bufferStream = (
89
- stream: ServerHttp2Stream,
90
- headers: IncomingHttpHeaders
91
- ) => {
92
- // store the stream in a buffer so we can replay it later
93
- streamBufferRef.current.push({ stream, headers });
94
- };
95
- proxy.on("stream", bufferStream);
96
- cleanupListeners.push(() => proxy.off("stream", bufferStream));
97
-
98
- const bufferRequestResponse = (
99
- request: IncomingMessage,
100
- response: ServerResponse
101
- ) => {
102
- // store the request and response in a buffer so we can replay it later
103
- requestResponseBufferRef.current.push({ request, response });
104
- };
105
-
106
- proxy.on("request", bufferRequestResponse);
107
- cleanupListeners.push(() => proxy.off("request", bufferRequestResponse));
108
- return () => {
109
- cleanupListeners.forEach((cleanup) => cleanup());
110
- };
111
- }
112
-
113
- // We have a token. Let's proxy requests to the preview end point.
114
- const cleanupListeners: (() => void)[] = [];
115
-
116
- const assetPath = typeof publicRoot === "string" ? publicRoot : null;
117
-
118
- // create a ClientHttp2Session
119
- const remote = connect(`https://${previewToken.host}`);
120
- cleanupListeners.push(() => remote.destroy());
121
-
122
- /** HTTP/2 -> HTTP/2 */
123
- const handleStream = createStreamHandler(previewToken, remote, port);
124
- proxy.on("stream", handleStream);
125
- cleanupListeners.push(() => proxy.off("stream", handleStream));
126
-
127
- // flush and replay buffered streams
128
- streamBufferRef.current.forEach((buffer) =>
129
- handleStream(buffer.stream, buffer.headers)
130
- );
131
- streamBufferRef.current = [];
132
-
133
- /** HTTP/1 -> HTTP/2 */
134
- const handleRequest: RequestListener = (
135
- message: IncomingMessage,
136
- response: ServerResponse
137
- ) => {
138
- const { httpVersionMajor, headers, method, url } = message;
139
- if (httpVersionMajor >= 2) {
140
- return; // Already handled by the "stream" event.
141
- }
142
- addCfPreviewTokenHeader(headers, previewToken.value);
143
- headers[":method"] = method;
144
- headers[":path"] = url;
145
- headers[":authority"] = previewToken.host;
146
- headers[":scheme"] = "https";
147
- for (const name of Object.keys(headers)) {
148
- if (HTTP1_HEADERS.has(name.toLowerCase())) {
149
- delete headers[name];
150
- }
151
- }
152
- const request = message.pipe(remote.request(headers));
153
- request.on("response", (responseHeaders) => {
154
- const status = responseHeaders[":status"] ?? 500;
155
- rewriteRemoteHostToLocalHostInHeaders(
156
- responseHeaders,
157
- previewToken.host,
158
- port
159
- );
160
- for (const name of Object.keys(responseHeaders)) {
161
- if (name.startsWith(":")) {
162
- delete responseHeaders[name];
163
- }
164
- }
165
- response.writeHead(status, responseHeaders);
166
- request.pipe(response, { end: true });
167
- });
168
- };
169
-
170
- // If an asset path is defined, check the file system
171
- // for a file first and serve if it exists.
172
- const actualHandleRequest = assetPath
173
- ? createHandleAssetsRequest(assetPath, handleRequest)
174
- : handleRequest;
175
-
176
- proxy.on("request", actualHandleRequest);
177
- cleanupListeners.push(() => proxy.off("request", actualHandleRequest));
178
-
179
- // flush and replay buffered requests
180
- requestResponseBufferRef.current.forEach(({ request, response }) =>
181
- actualHandleRequest(request, response)
182
- );
183
- requestResponseBufferRef.current = [];
184
-
185
- /** HTTP/1 -> WebSocket (over HTTP/1) */
186
- const handleUpgrade = (
187
- message: IncomingMessage,
188
- socket: WebSocket,
189
- body: Buffer
190
- ) => {
191
- const { headers, url } = message;
192
- addCfPreviewTokenHeader(headers, previewToken.value);
193
- headers["host"] = previewToken.host;
194
- const localWebsocket = new WebSocket(message, socket, body);
195
- // TODO(soon): Custom WebSocket protocol is not working?
196
- const remoteWebsocketClient = new WebSocket.Client(
197
- `wss://${previewToken.host}${url}`,
198
- [],
199
- { headers }
200
- );
201
- localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
202
- // We close down websockets whenever we refresh the token.
203
- cleanupListeners.push(() => {
204
- localWebsocket.destroy();
205
- remoteWebsocketClient.destroy();
206
- });
207
- };
208
- proxy.on("upgrade", handleUpgrade);
209
- cleanupListeners.push(() => proxy.off("upgrade", handleUpgrade));
210
-
211
- return () => {
212
- cleanupListeners.forEach((d) => d());
213
- };
214
- }, [previewToken, publicRoot, port, proxy]);
215
-
216
- // Start/stop the server whenever the
217
- // containing component is mounted/unmounted.
218
- useEffect(() => {
219
- proxy.listen(port);
220
- console.log(`⬣ Listening at http://localhost:${port}`);
221
-
222
- return () => {
223
- proxy.close();
224
- };
225
- }, [port, proxy]);
226
- }
227
-
228
- function createHandleAssetsRequest(
229
- assetPath: string,
230
- handleRequest: RequestListener
231
- ) {
232
- const handleAsset = serveStatic(assetPath, {
233
- cacheControl: false,
234
- });
235
- return (request: IncomingMessage, response: ServerResponse) => {
236
- handleAsset(request, response, () => {
237
- handleRequest(request, response);
238
- });
239
- };
240
- }
241
-
242
- /** A Set of headers we want to remove from HTTP/1 requests. */
243
- const HTTP1_HEADERS = new Set([
244
- "host",
245
- "connection",
246
- "upgrade",
247
- "keep-alive",
248
- "proxy-connection",
249
- "transfer-encoding",
250
- "http2-settings",
251
- ]);
252
-
253
- function createProxyServer() {
254
- return createServer()
255
- .on("request", function (req, res) {
256
- // log all requests
257
- console.log(
258
- new Date().toLocaleTimeString(),
259
- req.method,
260
- req.url,
261
- res.statusCode
262
- );
263
- })
264
- .on("upgrade", (req) => {
265
- // log all websocket connections
266
- console.log(
267
- new Date().toLocaleTimeString(),
268
- req.method,
269
- req.url,
270
- 101,
271
- "(WebSocket)"
272
- );
273
- })
274
- .on("error", (err) => {
275
- // log all connection errors
276
- console.error(new Date().toLocaleTimeString(), err);
277
- });
278
- }
279
-
280
- function createStreamHandler(
281
- previewToken: CfPreviewToken,
282
- remote: ClientHttp2Session,
283
- port: number
284
- ) {
285
- return function handleStream(
286
- stream: ServerHttp2Stream,
287
- headers: IncomingHttpHeaders
288
- ) {
289
- addCfPreviewTokenHeader(headers, previewToken.value);
290
- headers[":authority"] = previewToken.host;
291
- const request = stream.pipe(remote.request(headers));
292
- request.on("response", (responseHeaders: IncomingHttpHeaders) => {
293
- rewriteRemoteHostToLocalHostInHeaders(
294
- responseHeaders,
295
- previewToken.host,
296
- port
297
- );
298
- stream.respond(responseHeaders);
299
- request.pipe(stream, { end: true });
300
- });
301
- };
302
- }
package/src/publish.ts DELETED
@@ -1,382 +0,0 @@
1
- import assert from "node:assert";
2
- import path from "node:path";
3
- import { readFile } from "node:fs/promises";
4
- import * as esbuild from "esbuild";
5
- import type { Metafile } from "esbuild";
6
- import { execa } from "execa";
7
- import tmp from "tmp-promise";
8
- import type { CfWorkerInit } from "./api/worker";
9
- import { toFormData } from "./api/form_data";
10
- import { fetchResult } from "./cfetch";
11
- import type { Config } from "./config";
12
- import makeModuleCollector from "./module-collection";
13
- import { syncAssets } from "./sites";
14
-
15
- type CfScriptFormat = undefined | "modules" | "service-worker";
16
-
17
- type Props = {
18
- config: Config;
19
- format?: CfScriptFormat;
20
- script?: string;
21
- name?: string;
22
- env?: string;
23
- compatibilityDate?: string;
24
- compatibilityFlags?: string[];
25
- public?: string;
26
- site?: string;
27
- triggers?: (string | number)[];
28
- routes?: (string | number)[];
29
- legacyEnv?: boolean;
30
- jsxFactory: undefined | string;
31
- jsxFragment: undefined | string;
32
- };
33
-
34
- function sleep(ms: number) {
35
- return new Promise((resolve) => setTimeout(resolve, ms));
36
- }
37
-
38
- export default async function publish(props: Props): Promise<void> {
39
- if (props.public && props.format === "service-worker") {
40
- // TODO: check config too
41
- throw new Error(
42
- "You cannot use the service worker format with a public directory."
43
- );
44
- }
45
- // TODO: warn if git/hg has uncommitted changes
46
- const { config } = props;
47
- const {
48
- account_id: accountId,
49
- build,
50
- // @ts-expect-error hidden
51
- __path__,
52
- } = config;
53
-
54
- const envRootObj =
55
- props.env && config.env ? config.env[props.env] || {} : config;
56
-
57
- assert(
58
- envRootObj.compatibility_date || props.compatibilityDate,
59
- "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility_date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
60
- );
61
-
62
- if (accountId === undefined) {
63
- throw new Error("No account_id provided.");
64
- }
65
-
66
- const triggers = props.triggers || config.triggers?.crons;
67
- const routes = props.routes || config.routes;
68
-
69
- const jsxFactory = props.jsxFactory || config.jsx_factory;
70
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
71
-
72
- assert(config.account_id, "missing account id");
73
-
74
- let scriptName = props.name || config.name;
75
- assert(
76
- scriptName,
77
- 'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
78
- );
79
-
80
- let file: string;
81
- if (props.script) {
82
- // If the script name comes from the command line it is relative to the current working directory.
83
- file = path.resolve(props.script);
84
- } else {
85
- // If the script name comes from the config, then it is relative to the wrangler.toml file.
86
- assert(build?.upload?.main, "missing main file");
87
- file = path.resolve(path.dirname(__path__), build.upload.main);
88
- }
89
-
90
- if (props.legacyEnv) {
91
- scriptName += props.env ? `-${props.env}` : "";
92
- }
93
- const envName = props.env ?? "production";
94
-
95
- const destination = await tmp.dir({ unsafeCleanup: true });
96
- if (props.config.build?.command) {
97
- // TODO: add a deprecation message here?
98
- console.log("running:", props.config.build.command);
99
- const buildCommandPieces = props.config.build.command.split(" ");
100
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
101
- stdout: "inherit",
102
- stderr: "inherit",
103
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
104
- });
105
- }
106
-
107
- const moduleCollector = makeModuleCollector();
108
- const result = await esbuild.build({
109
- ...(props.public
110
- ? {
111
- stdin: {
112
- contents: (
113
- await readFile(
114
- path.join(__dirname, "../static-asset-facade.js"),
115
- "utf8"
116
- )
117
- ).replace("__ENTRY_POINT__", file),
118
- sourcefile: "static-asset-facade.js",
119
- resolveDir: path.dirname(file),
120
- },
121
- }
122
- : { entryPoints: [file] }),
123
- bundle: true,
124
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
125
- outdir: destination.path,
126
- external: ["__STATIC_CONTENT_MANIFEST"],
127
- format: "esm",
128
- sourcemap: true,
129
- metafile: true,
130
- conditions: ["worker", "browser"],
131
- loader: {
132
- ".js": "jsx",
133
- },
134
- plugins: [moduleCollector.plugin],
135
- ...(jsxFactory && { jsxFactory }),
136
- ...(jsxFragment && { jsxFragment }),
137
- });
138
-
139
- // result.metafile is defined because of the `metafile: true` option above.
140
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
141
- const metafile = result.metafile!;
142
- const entryPoints = Object.values(metafile.outputs).filter(
143
- (output) => output.entryPoint !== undefined
144
- );
145
- assert(
146
- entryPoints.length > 0,
147
- `Cannot find entry-point "${file}" in generated bundle.` +
148
- listEntryPoints(entryPoints)
149
- );
150
- assert(
151
- entryPoints.length < 2,
152
- "More than one entry-point found for generated bundle." +
153
- listEntryPoints(entryPoints)
154
- );
155
- const entryPointExports = entryPoints[0].exports;
156
- const resolvedEntryPointPath = path.resolve(
157
- destination.path,
158
- // We know that entryPoint is not null because we filtered out those without above.
159
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
160
- entryPoints[0].entryPoint!
161
- );
162
- const { format } = props;
163
- const bundle = {
164
- type: entryPointExports.length > 0 ? "esm" : "commonjs",
165
- exports: entryPointExports,
166
- };
167
-
168
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
169
- // That way we'll be able to accurately tell if this is a service worker or not.
170
-
171
- if (format === "modules" && bundle.type === "commonjs") {
172
- console.error("⎔ Cannot use modules with a commonjs bundle.");
173
- // TODO: a much better error message here, with what to do next
174
- return;
175
- }
176
- if (format === "service-worker" && bundle.type !== "esm") {
177
- console.error("⎔ Cannot use service-worker with a esm bundle.");
178
- // TODO: a much better error message here, with what to do next
179
- return;
180
- }
181
-
182
- const content = await readFile(resolvedEntryPointPath, { encoding: "utf-8" });
183
- await destination.cleanup();
184
-
185
- // if config.migrations
186
- // get current migration tag
187
- let migrations;
188
- if (config.migrations !== undefined) {
189
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
190
- `/accounts/${accountId}/workers/scripts`
191
- );
192
- const script = scripts.find(({ id }) => id === scriptName);
193
- if (script?.migration_tag) {
194
- // was already published once
195
- const foundIndex = config.migrations.findIndex(
196
- (migration) => migration.tag === script.migration_tag
197
- );
198
- if (foundIndex === -1) {
199
- console.warn(
200
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
201
- );
202
- migrations = {
203
- old_tag: script.migration_tag,
204
- new_tag: config.migrations[config.migrations.length - 1].tag,
205
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
206
- };
207
- } else {
208
- migrations = {
209
- old_tag: script.migration_tag,
210
- new_tag: config.migrations[config.migrations.length - 1].tag,
211
- steps: config.migrations
212
- .slice(foundIndex + 1)
213
- .map(({ tag: _tag, ...rest }) => rest),
214
- };
215
- }
216
- } else {
217
- migrations = {
218
- new_tag: config.migrations[config.migrations.length - 1].tag,
219
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
220
- };
221
- }
222
- }
223
-
224
- const assetPath = props.public || props.site || props.config.site?.bucket; // TODO: allow both
225
- const assets = assetPath
226
- ? await syncAssets(accountId, scriptName, assetPath, false)
227
- : { manifest: undefined, namespace: undefined };
228
-
229
- const bindings: CfWorkerInit["bindings"] = {
230
- kv_namespaces: envRootObj.kv_namespaces?.concat(
231
- assets.namespace
232
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
233
- : []
234
- ),
235
- vars: envRootObj.vars,
236
- durable_objects: envRootObj.durable_objects,
237
- services: envRootObj.experimental_services,
238
- };
239
-
240
- const worker: CfWorkerInit = {
241
- name: scriptName,
242
- main: {
243
- name: path.basename(resolvedEntryPointPath),
244
- content: content,
245
- type: bundle.type === "esm" ? "esm" : "commonjs",
246
- },
247
- bindings,
248
- ...(migrations && { migrations }),
249
- modules: moduleCollector.modules.concat(
250
- assets.manifest
251
- ? {
252
- name: "__STATIC_CONTENT_MANIFEST",
253
- content: JSON.stringify(assets.manifest),
254
- type: "text",
255
- }
256
- : []
257
- ),
258
- compatibility_date: config.compatibility_date,
259
- compatibility_flags: config.compatibility_flags,
260
- usage_model: config.usage_model,
261
- };
262
-
263
- const start = Date.now();
264
- function formatTime(duration: number) {
265
- return `(${(duration / 1000).toFixed(2)} sec)`;
266
- }
267
-
268
- const notProd = !props.legacyEnv && props.env;
269
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
270
- const workerUrl = notProd
271
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
272
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
273
-
274
- // Upload the script so it has time to propagate.
275
- const { available_on_subdomain } = await fetchResult(
276
- workerUrl,
277
- {
278
- method: "PUT",
279
- // @ts-expect-error: TODO: fix this type error!
280
- body: toFormData(worker),
281
- },
282
- new URLSearchParams({ available_on_subdomains: "true" })
283
- );
284
-
285
- const uploadMs = Date.now() - start;
286
- console.log("Uploaded", workerName, formatTime(uploadMs));
287
- const deployments: Promise<string[]>[] = [];
288
-
289
- const userSubdomain = (
290
- await fetchResult<{ subdomain: string }>(
291
- `/accounts/${accountId}/workers/subdomain`
292
- )
293
- ).subdomain;
294
-
295
- const scriptURL =
296
- props.legacyEnv || !props.env
297
- ? `${scriptName}.${userSubdomain}.workers.dev`
298
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
299
-
300
- // Enable the `workers.dev` subdomain.
301
- // TODO: Make this configurable.
302
- if (!available_on_subdomain) {
303
- deployments.push(
304
- fetchResult(`${workerUrl}/subdomain`, {
305
- method: "POST",
306
- body: JSON.stringify({ enabled: true }),
307
- headers: {
308
- "Content-Type": "application/json",
309
- },
310
- })
311
- .then(() => [scriptURL])
312
- // Add a delay when the subdomain is first created.
313
- // This is to prevent an issue where a negative cache-hit
314
- // causes the subdomain to be unavailable for 30 seconds.
315
- // This is a temporary measure until we fix this on the edge.
316
- .then(async (url) => {
317
- await sleep(3000);
318
- return url;
319
- })
320
- );
321
- } else {
322
- deployments.push(Promise.resolve([scriptURL]));
323
- }
324
-
325
- // Update routing table for the script.
326
- if (routes && routes.length) {
327
- deployments.push(
328
- fetchResult(`${workerUrl}/routes`, {
329
- // TODO: PATCH will not delete previous routes on this script,
330
- // whereas PUT will. We need to decide on the default behaviour
331
- // and how to configure it.
332
- method: "PUT",
333
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
334
- headers: {
335
- "Content-Type": "application/json",
336
- },
337
- }).then(() => {
338
- if (routes.length > 10) {
339
- return routes
340
- .slice(0, 9)
341
- .map(String)
342
- .concat([`...and ${routes.length - 10} more routes`]);
343
- }
344
- return routes.map(String);
345
- })
346
- );
347
- }
348
-
349
- // Configure any schedules for the script.
350
- // TODO: rename this to `schedules`?
351
- if (triggers && triggers.length) {
352
- deployments.push(
353
- fetchResult(`${workerUrl}/schedules`, {
354
- // TODO: Unlike routes, this endpoint does not support PATCH.
355
- // So technically, this will override any previous schedules.
356
- // We should change the endpoint to support PATCH.
357
- method: "PUT",
358
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
359
- headers: {
360
- "Content-Type": "application/json",
361
- },
362
- }).then(() => triggers.map(String))
363
- );
364
- }
365
-
366
- if (!deployments.length) {
367
- return;
368
- }
369
-
370
- const targets = await Promise.all(deployments);
371
- const deployMs = Date.now() - start - uploadMs;
372
- console.log("Deployed", workerName, formatTime(deployMs));
373
- for (const target of targets.flat()) {
374
- console.log(" ", target);
375
- }
376
- }
377
-
378
- function listEntryPoints(outputs: ValueOf<Metafile["outputs"]>[]): string {
379
- return outputs.map((output) => output.entryPoint).join("\n");
380
- }
381
-
382
- type ValueOf<T> = T[keyof T];