wrangler 0.0.0-e8e684c7 → 0.0.0-e9106dfa5

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 (207) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -174
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +37 -14
  33. package/templates/pages-template-worker.ts +33 -7
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26527 -172
  45. package/wrangler-dist/cli.js +148646 -148093
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -5542
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -4026
  55. package/src/__tests__/dev.test.tsx +0 -1318
  56. package/src/__tests__/generate.test.ts +0 -91
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -296
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  66. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  67. package/src/__tests__/helpers/mock-istty.ts +0 -74
  68. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  69. package/src/__tests__/helpers/mock-kv.ts +0 -33
  70. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  71. package/src/__tests__/helpers/mock-process.ts +0 -39
  72. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  73. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  74. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  75. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  76. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  77. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  78. package/src/__tests__/https-options.test.ts +0 -163
  79. package/src/__tests__/index.test.ts +0 -245
  80. package/src/__tests__/init.test.ts +0 -2170
  81. package/src/__tests__/jest.setup.ts +0 -157
  82. package/src/__tests__/kv.test.ts +0 -1671
  83. package/src/__tests__/logger.test.ts +0 -141
  84. package/src/__tests__/metrics.test.ts +0 -450
  85. package/src/__tests__/package-manager.test.ts +0 -353
  86. package/src/__tests__/pages.test.ts +0 -1275
  87. package/src/__tests__/parse.test.ts +0 -330
  88. package/src/__tests__/publish.test.ts +0 -6955
  89. package/src/__tests__/pubsub.test.ts +0 -367
  90. package/src/__tests__/r2.test.ts +0 -336
  91. package/src/__tests__/route.test.ts +0 -45
  92. package/src/__tests__/secret.test.ts +0 -492
  93. package/src/__tests__/tail.test.ts +0 -802
  94. package/src/__tests__/test-old-node-version.js +0 -31
  95. package/src/__tests__/user.test.ts +0 -155
  96. package/src/__tests__/validate-dev-props.test.ts +0 -56
  97. package/src/__tests__/version.test.ts +0 -35
  98. package/src/__tests__/whoami.test.tsx +0 -289
  99. package/src/__tests__/worker-namespace.test.ts +0 -329
  100. package/src/abort.d.ts +0 -3
  101. package/src/api/dev.ts +0 -93
  102. package/src/api/index.ts +0 -1
  103. package/src/bundle-reporter.tsx +0 -29
  104. package/src/bundle.ts +0 -473
  105. package/src/cfetch/index.ts +0 -121
  106. package/src/cfetch/internal.ts +0 -298
  107. package/src/cli.ts +0 -27
  108. package/src/config/README.md +0 -107
  109. package/src/config/config.ts +0 -263
  110. package/src/config/diagnostics.ts +0 -80
  111. package/src/config/environment.ts +0 -485
  112. package/src/config/index.ts +0 -251
  113. package/src/config/validation-helpers.ts +0 -597
  114. package/src/config/validation.ts +0 -1862
  115. package/src/config-cache.ts +0 -85
  116. package/src/create-worker-preview.ts +0 -257
  117. package/src/create-worker-upload-form.ts +0 -291
  118. package/src/dev/dev-vars.ts +0 -36
  119. package/src/dev/dev.tsx +0 -545
  120. package/src/dev/local.tsx +0 -449
  121. package/src/dev/remote.tsx +0 -422
  122. package/src/dev/use-esbuild.ts +0 -178
  123. package/src/dev/validate-dev-props.ts +0 -31
  124. package/src/dev-registry.tsx +0 -160
  125. package/src/dev.tsx +0 -696
  126. package/src/dialogs.tsx +0 -135
  127. package/src/dispatch-namespace.ts +0 -206
  128. package/src/durable.ts +0 -102
  129. package/src/entry.ts +0 -328
  130. package/src/environment-variables.ts +0 -35
  131. package/src/errors.ts +0 -11
  132. package/src/faye-websocket.d.ts +0 -6
  133. package/src/generate.ts +0 -131
  134. package/src/git-client.ts +0 -42
  135. package/src/global-wrangler-config-path.ts +0 -26
  136. package/src/https-options.ts +0 -127
  137. package/src/index.tsx +0 -2260
  138. package/src/init.ts +0 -622
  139. package/src/inspect.ts +0 -747
  140. package/src/intl-polyfill.d.ts +0 -139
  141. package/src/is-ci.ts +0 -14
  142. package/src/is-interactive.ts +0 -12
  143. package/src/kv.ts +0 -430
  144. package/src/logger.ts +0 -73
  145. package/src/metrics/index.ts +0 -5
  146. package/src/metrics/metrics-config.ts +0 -239
  147. package/src/metrics/metrics-dispatcher.ts +0 -96
  148. package/src/metrics/metrics-usage-headers.ts +0 -24
  149. package/src/metrics/send-event.ts +0 -92
  150. package/src/miniflare-cli/README.md +0 -30
  151. package/src/miniflare-cli/assets.ts +0 -554
  152. package/src/miniflare-cli/enum-keys.ts +0 -17
  153. package/src/miniflare-cli/index.ts +0 -207
  154. package/src/miniflare-cli/request-context.ts +0 -40
  155. package/src/module-collection.ts +0 -258
  156. package/src/open-in-browser.ts +0 -17
  157. package/src/package-manager.ts +0 -219
  158. package/src/pages/build.tsx +0 -238
  159. package/src/pages/constants.ts +0 -12
  160. package/src/pages/deployments.tsx +0 -106
  161. package/src/pages/dev.tsx +0 -528
  162. package/src/pages/errors.ts +0 -22
  163. package/src/pages/functions/buildPlugin.ts +0 -109
  164. package/src/pages/functions/buildWorker.ts +0 -155
  165. package/src/pages/functions/filepath-routing.test.ts +0 -234
  166. package/src/pages/functions/filepath-routing.ts +0 -189
  167. package/src/pages/functions/identifiers.ts +0 -78
  168. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  169. package/src/pages/functions/routes-consolidation.ts +0 -73
  170. package/src/pages/functions/routes-transformation.test.ts +0 -271
  171. package/src/pages/functions/routes-transformation.ts +0 -122
  172. package/src/pages/functions/routes.ts +0 -151
  173. package/src/pages/functions.tsx +0 -96
  174. package/src/pages/index.tsx +0 -94
  175. package/src/pages/projects.tsx +0 -169
  176. package/src/pages/publish.tsx +0 -391
  177. package/src/pages/types.ts +0 -49
  178. package/src/pages/upload.tsx +0 -413
  179. package/src/pages/utils.ts +0 -12
  180. package/src/parse.ts +0 -286
  181. package/src/paths.ts +0 -26
  182. package/src/preview.ts +0 -31
  183. package/src/proxy.ts +0 -486
  184. package/src/publish.ts +0 -822
  185. package/src/pubsub/index.ts +0 -286
  186. package/src/pubsub/pubsub-commands.tsx +0 -623
  187. package/src/r2.ts +0 -131
  188. package/src/selfsigned.d.ts +0 -29
  189. package/src/sites.tsx +0 -372
  190. package/src/tail/filters.ts +0 -281
  191. package/src/tail/index.ts +0 -312
  192. package/src/tail/printing.ts +0 -107
  193. package/src/update-check.ts +0 -19
  194. package/src/user/choose-account.tsx +0 -69
  195. package/src/user/env-vars.ts +0 -46
  196. package/src/user/generate-auth-url.ts +0 -33
  197. package/src/user/generate-random-state.ts +0 -16
  198. package/src/user/index.ts +0 -3
  199. package/src/user/user.tsx +0 -1191
  200. package/src/whoami.tsx +0 -169
  201. package/src/worker.ts +0 -204
  202. package/src/zones.ts +0 -167
  203. package/templates/first-party-worker-module-facade.ts +0 -18
  204. package/templates/format-dev-errors.ts +0 -32
  205. package/templates/serve-static-assets.ts +0 -63
  206. package/templates/service-bindings-module-facade.js +0 -54
  207. package/templates/service-bindings-sw-facade.js +0 -42
package/src/publish.ts DELETED
@@ -1,822 +0,0 @@
1
- import assert from "node:assert";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import path from "node:path";
4
- import { URLSearchParams } from "node:url";
5
- import tmp from "tmp-promise";
6
- import { bundleWorker } from "./bundle";
7
- import { printBundleSize } from "./bundle-reporter";
8
- import { fetchListResult, fetchResult } from "./cfetch";
9
- import { printBindings } from "./config";
10
- import { createWorkerUploadForm } from "./create-worker-upload-form";
11
- import { confirm } from "./dialogs";
12
- import { getMigrationsToUpload } from "./durable";
13
- import { logger } from "./logger";
14
- import { getMetricsUsageHeaders } from "./metrics";
15
- import { ParseError } from "./parse";
16
- import { syncAssets } from "./sites";
17
- import { getZoneForRoute } from "./zones";
18
- import type { Config } from "./config";
19
- import type {
20
- Route,
21
- ZoneIdRoute,
22
- ZoneNameRoute,
23
- CustomDomainRoute,
24
- } from "./config/environment";
25
- import type { Entry } from "./entry";
26
- import type { AssetPaths } from "./sites";
27
- import type { CfWorkerInit } from "./worker";
28
-
29
- type Props = {
30
- config: Config;
31
- accountId: string | undefined;
32
- entry: Entry;
33
- rules: Config["rules"];
34
- name: string | undefined;
35
- env: string | undefined;
36
- compatibilityDate: string | undefined;
37
- compatibilityFlags: string[] | undefined;
38
- assetPaths: AssetPaths | undefined;
39
- vars: Record<string, string> | undefined;
40
- defines: Record<string, string> | undefined;
41
- triggers: string[] | undefined;
42
- routes: string[] | undefined;
43
- legacyEnv: boolean | undefined;
44
- jsxFactory: string | undefined;
45
- jsxFragment: string | undefined;
46
- tsconfig: string | undefined;
47
- isWorkersSite: boolean;
48
- minify: boolean | undefined;
49
- nodeCompat: boolean | undefined;
50
- outDir: string | undefined;
51
- dryRun: boolean | undefined;
52
- noBundle: boolean | undefined;
53
- };
54
-
55
- type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
56
-
57
- export type CustomDomain = {
58
- id: string;
59
- zone_id: string;
60
- zone_name: string;
61
- hostname: string;
62
- service: string;
63
- environment: string;
64
- };
65
- type UpdatedCustomDomain = CustomDomain & { modified: boolean };
66
- type ConflictingCustomDomain = CustomDomain & {
67
- external_dns_record_id?: string;
68
- external_cert_id?: string;
69
- };
70
-
71
- export type CustomDomainChangeset = {
72
- added: CustomDomain[];
73
- removed: CustomDomain[];
74
- updated: UpdatedCustomDomain[];
75
- conflicting: ConflictingCustomDomain[];
76
- };
77
-
78
- function sleep(ms: number) {
79
- return new Promise((resolve) => setTimeout(resolve, ms));
80
- }
81
-
82
- function renderRoute(route: Route): string {
83
- let result = "";
84
- if (typeof route === "string") {
85
- result = route;
86
- } else {
87
- result = route.pattern;
88
- const isCustomDomain = Boolean(
89
- "custom_domain" in route && route.custom_domain
90
- );
91
- if (isCustomDomain && "zone_id" in route) {
92
- result += ` (custom domain - zone id: ${route.zone_id})`;
93
- } else if (isCustomDomain && "zone_name" in route) {
94
- result += ` (custom domain - zone name: ${route.zone_name})`;
95
- } else if (isCustomDomain) {
96
- result += ` (custom domain)`;
97
- } else if ("zone_id" in route) {
98
- result += ` (zone id: ${route.zone_id})`;
99
- } else if ("zone_name" in route) {
100
- result += ` (zone name: ${route.zone_name})`;
101
- }
102
- }
103
- return result;
104
- }
105
-
106
- // publishing to custom domains involves a few more steps than just updating
107
- // the routing table, and thus the api implementing it is fairly defensive -
108
- // it will error eagerly on conflicts against existing domains or existing
109
- // managed DNS records
110
-
111
- // however, you can pass params to override the errors. to know if we should
112
- // override the current state, we generate a "changeset" of required actions
113
- // to get to the state we want (specified by the list of custom domains). the
114
- // changeset returns an "updated" collection (existing custom domains
115
- // connected to other scripts) and a "conflicting" collection (the requested
116
- // custom domains that have a managed, conflicting DNS record preventing the
117
- // host's use as a custom domain). with this information, we can prompt to
118
- // the user what will occur if we create the custom domains requested, and
119
- // add the override param if they confirm the action
120
- //
121
- // if a user does not confirm that they want to override, we skip publishing
122
- // to these custom domains, but continue on through the rest of the
123
- // publish stage
124
- async function publishCustomDomains(
125
- workerUrl: string,
126
- accountId: string,
127
- domains: Array<RouteObject>
128
- ): Promise<string[]> {
129
- const config = {
130
- override_scope: true,
131
- override_existing_origin: false,
132
- override_existing_dns_record: false,
133
- };
134
- const origins = domains.map((domainRoute) => {
135
- return {
136
- hostname: domainRoute.pattern,
137
- zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
138
- zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
139
- };
140
- });
141
-
142
- const fail = () => {
143
- return [
144
- domains.length > 1
145
- ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
146
- : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
147
- ];
148
- };
149
-
150
- if (!process.stdout.isTTY) {
151
- // running in non-interactive mode.
152
- // existing origins / dns records are not indicative of errors,
153
- // so we aggressively update rather than aggressively fail
154
- config.override_existing_origin = true;
155
- config.override_existing_dns_record = true;
156
- } else {
157
- // get a changeset for operations required to achieve a state with the requested domains
158
- const changeset = await fetchResult<CustomDomainChangeset>(
159
- `${workerUrl}/domains/changeset?replace_state=true`,
160
- {
161
- method: "POST",
162
- body: JSON.stringify(origins),
163
- headers: {
164
- "Content-Type": "application/json",
165
- },
166
- }
167
- );
168
-
169
- const updatesRequired = changeset.updated.filter(
170
- (domain) => domain.modified
171
- );
172
- if (updatesRequired.length > 0) {
173
- // find out which scripts the conflict domains are already attached to
174
- // so we can provide that in the confirmation prompt
175
- const existing = await Promise.all(
176
- updatesRequired.map((domain) =>
177
- fetchResult<CustomDomain>(
178
- `/accounts/${accountId}/workers/domains/records/${domain.id}`
179
- )
180
- )
181
- );
182
- const existingRendered = existing
183
- .map(
184
- (domain) =>
185
- `\t• ${domain.hostname} (used as a domain for "${domain.service}")`
186
- )
187
- .join("\n");
188
- const message = `Custom Domains already exist for these domains:
189
- ${existingRendered}
190
- Update them to point to this script instead?`;
191
- if (!(await confirm(message))) return fail();
192
- config.override_existing_origin = true;
193
- }
194
-
195
- if (changeset.conflicting.length > 0) {
196
- const conflicitingRendered = changeset.conflicting
197
- .map((domain) => `\t• ${domain.hostname}`)
198
- .join("\n");
199
- const message = `You already have DNS records that conflict for these Custom Domains:
200
- ${conflicitingRendered}
201
- Update them to point to this script instead?`;
202
- if (!(await confirm(message))) return fail();
203
- config.override_existing_dns_record = true;
204
- }
205
- }
206
-
207
- // publish to domains
208
- await fetchResult(`${workerUrl}/domains/records`, {
209
- method: "PUT",
210
- body: JSON.stringify({ ...config, origins }),
211
- headers: {
212
- "Content-Type": "application/json",
213
- },
214
- });
215
-
216
- return domains.map((domain) => renderRoute(domain));
217
- }
218
-
219
- export default async function publish(props: Props): Promise<void> {
220
- // TODO: warn if git/hg has uncommitted changes
221
- const { config, accountId } = props;
222
-
223
- if (!(props.compatibilityDate || config.compatibility_date)) {
224
- const compatibilityDateStr = `${new Date().getFullYear()}-${(
225
- new Date().getMonth() + ""
226
- ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
227
-
228
- throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
229
- \`\`\`
230
- compatibility_date = "${compatibilityDateStr}"
231
- \`\`\`
232
- Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
233
- See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
234
- }
235
-
236
- const triggers = props.triggers || config.triggers?.crons;
237
- const routes =
238
- props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
239
- const routesOnly: Array<Route> = [];
240
- const customDomainsOnly: Array<RouteObject> = [];
241
- for (const route of routes) {
242
- if (typeof route !== "string" && route.custom_domain) {
243
- if (route.pattern.includes("*")) {
244
- throw new Error(
245
- `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
246
- );
247
- }
248
- if (route.pattern.includes("/")) {
249
- throw new Error(
250
- `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
251
- );
252
- }
253
- customDomainsOnly.push(route);
254
- } else {
255
- routesOnly.push(route);
256
- }
257
- }
258
-
259
- // deployToWorkersDev defaults to true only if there aren't any routes defined
260
- const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
261
-
262
- const jsxFactory = props.jsxFactory || config.jsx_factory;
263
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
264
-
265
- const minify = props.minify ?? config.minify;
266
-
267
- const nodeCompat = props.nodeCompat ?? config.node_compat;
268
- if (nodeCompat) {
269
- logger.warn(
270
- "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
271
- );
272
- }
273
-
274
- // Warn if user tries minify or node-compat with no-bundle
275
- if (props.noBundle && minify) {
276
- logger.warn(
277
- "`--minify` and `--no-bundle` can't be used together. If you want to minify your Worker and disable Wrangler's bundling, please minify as part of your own bundling process."
278
- );
279
- }
280
-
281
- if (props.noBundle && nodeCompat) {
282
- logger.warn(
283
- "`--node-compat` and `--no-bundle` can't be used together. If you want to polyfill Node.js built-ins and disable Wrangler's bundling, please polyfill as part of your own bundling process."
284
- );
285
- }
286
-
287
- const scriptName = props.name;
288
- assert(
289
- scriptName,
290
- '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>"`'
291
- );
292
-
293
- assert(
294
- !config.site || config.site.bucket,
295
- "A [site] definition requires a `bucket` field with a path to the site's assets directory."
296
- );
297
-
298
- if (props.outDir) {
299
- // we're using a custom output directory,
300
- // so let's first ensure it exists
301
- mkdirSync(props.outDir, { recursive: true });
302
- // add a README
303
- const readmePath = path.join(props.outDir, "README.md");
304
- writeFileSync(
305
- readmePath,
306
- `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
307
- );
308
- }
309
-
310
- const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
311
- const envName = props.env ?? "production";
312
-
313
- const start = Date.now();
314
- const notProd = Boolean(!props.legacyEnv && props.env);
315
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
316
- const workerUrl = notProd
317
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
318
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
319
-
320
- let available_on_subdomain; // we'll set this later
321
-
322
- const { format } = props.entry;
323
-
324
- if (
325
- !props.isWorkersSite &&
326
- Boolean(props.assetPaths) &&
327
- format === "service-worker"
328
- ) {
329
- throw new Error(
330
- "You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
331
- );
332
- }
333
-
334
- if (config.wasm_modules && format === "modules") {
335
- throw new Error(
336
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
337
- );
338
- }
339
-
340
- if (config.text_blobs && format === "modules") {
341
- throw new Error(
342
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
343
- );
344
- }
345
-
346
- if (config.data_blobs && format === "modules") {
347
- throw new Error(
348
- "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
349
- );
350
- }
351
- try {
352
- if (props.noBundle) {
353
- // if we're not building, let's just copy the entry to the destination directory
354
- const destinationDir =
355
- typeof destination === "string" ? destination : destination.path;
356
- mkdirSync(destinationDir, { recursive: true });
357
- writeFileSync(
358
- path.join(destinationDir, path.basename(props.entry.file)),
359
- readFileSync(props.entry.file, "utf-8")
360
- );
361
- }
362
-
363
- const {
364
- modules,
365
- resolvedEntryPointPath,
366
- bundleType,
367
- }: Awaited<ReturnType<typeof bundleWorker>> = props.noBundle
368
- ? // we can skip the whole bundling step and mock a bundle here
369
- {
370
- modules: [],
371
- resolvedEntryPointPath: props.entry.file,
372
- bundleType: props.entry.format === "modules" ? "esm" : "commonjs",
373
- stop: undefined,
374
- }
375
- : await bundleWorker(
376
- props.entry,
377
- typeof destination === "string" ? destination : destination.path,
378
- {
379
- serveAssetsFromWorker:
380
- !props.isWorkersSite && Boolean(props.assetPaths),
381
- jsxFactory,
382
- jsxFragment,
383
- rules: props.rules,
384
- tsconfig: props.tsconfig ?? config.tsconfig,
385
- minify,
386
- nodeCompat,
387
- define: { ...config.define, ...props.defines },
388
- checkFetch: false,
389
- assets: config.assets && {
390
- ...config.assets,
391
- // enable the cache when publishing
392
- bypassCache: false,
393
- },
394
- services: config.services,
395
- // We don't set workerDefinitions here,
396
- // because we don't want to apply the dev-time
397
- // facades on top of it
398
- workerDefinitions: undefined,
399
- firstPartyWorkerDevFacade: false,
400
- }
401
- );
402
-
403
- const content = readFileSync(resolvedEntryPointPath, {
404
- encoding: "utf-8",
405
- });
406
-
407
- // durable object migrations
408
- const migrations = !props.dryRun
409
- ? await getMigrationsToUpload(scriptName, {
410
- accountId,
411
- config,
412
- legacyEnv: props.legacyEnv,
413
- env: props.env,
414
- })
415
- : undefined;
416
-
417
- const assets = await syncAssets(
418
- accountId,
419
- // When we're using the newer service environments, we wouldn't
420
- // have added the env name on to the script name. However, we must
421
- // include it in the kv namespace name regardless (since there's no
422
- // concept of service environments for kv namespaces yet).
423
- scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
424
- props.assetPaths,
425
- false,
426
- props.dryRun
427
- );
428
-
429
- const bindings: CfWorkerInit["bindings"] = {
430
- kv_namespaces: (config.kv_namespaces || []).concat(
431
- assets.namespace
432
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
433
- : []
434
- ),
435
- vars: { ...config.vars, ...props.vars },
436
- wasm_modules: config.wasm_modules,
437
- text_blobs: {
438
- ...config.text_blobs,
439
- ...(assets.manifest &&
440
- format === "service-worker" && {
441
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
442
- }),
443
- },
444
- data_blobs: config.data_blobs,
445
- durable_objects: config.durable_objects,
446
- r2_buckets: config.r2_buckets,
447
- services: config.services,
448
- dispatch_namespaces: config.dispatch_namespaces,
449
- logfwdr: config.logfwdr,
450
- unsafe: config.unsafe?.bindings,
451
- };
452
-
453
- if (assets.manifest) {
454
- modules.push({
455
- name: "__STATIC_CONTENT_MANIFEST",
456
- content: JSON.stringify(assets.manifest),
457
- type: "text",
458
- });
459
- }
460
-
461
- const worker: CfWorkerInit = {
462
- name: scriptName,
463
- main: {
464
- name: path.basename(resolvedEntryPointPath),
465
- content: content,
466
- type: bundleType,
467
- },
468
- bindings,
469
- migrations,
470
- modules,
471
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
472
- compatibility_flags:
473
- props.compatibilityFlags ?? config.compatibility_flags,
474
- usage_model: config.usage_model,
475
- keep_bindings: true,
476
- };
477
-
478
- void printBundleSize(
479
- { name: path.basename(resolvedEntryPointPath), content: content },
480
- modules
481
- );
482
-
483
- const withoutStaticAssets = {
484
- ...bindings,
485
- kv_namespaces: config.kv_namespaces,
486
- text_blobs: config.text_blobs,
487
- };
488
-
489
- // mask anything that was overridden in cli args
490
- // so that we don't log potential secrets into the terminal
491
- const maskedVars = { ...withoutStaticAssets.vars };
492
- for (const key of Object.keys(maskedVars)) {
493
- if (maskedVars[key] !== config.vars[key]) {
494
- // This means it was overridden in cli args
495
- // so let's mask it
496
- maskedVars[key] = "(hidden)";
497
- }
498
- }
499
-
500
- printBindings({ ...withoutStaticAssets, vars: maskedVars });
501
-
502
- if (!props.dryRun) {
503
- // Upload the script so it has time to propagate.
504
- // We can also now tell whether available_on_subdomain is set
505
- const result = await fetchResult<{
506
- available_on_subdomain: boolean;
507
- id: string | null;
508
- etag: string | null;
509
- pipeline_hash: string | null;
510
- }>(
511
- workerUrl,
512
- {
513
- method: "PUT",
514
- body: createWorkerUploadForm(worker),
515
- headers: await getMetricsUsageHeaders(config.send_metrics),
516
- },
517
- new URLSearchParams({
518
- include_subdomain_availability: "true",
519
- // pass excludeScript so the whole body of the
520
- // script doesn't get included in the response
521
- excludeScript: "true",
522
- })
523
- );
524
-
525
- available_on_subdomain = result.available_on_subdomain;
526
-
527
- if (config.first_party_worker) {
528
- // Print some useful information returned after publishing
529
- // Not all fields will be populated for every worker
530
- // These fields are likely to be scraped by tools, so do not rename
531
- if (result.id) logger.log("Worker ID: ", result.id);
532
- if (result.etag) logger.log("Worker ETag: ", result.etag);
533
- if (result.pipeline_hash)
534
- logger.log("Worker PipelineHash: ", result.pipeline_hash);
535
- }
536
- }
537
- } finally {
538
- if (typeof destination !== "string") {
539
- // this means we're using a temp dir,
540
- // so let's clean up before we proceed
541
- await destination.cleanup();
542
- }
543
- }
544
-
545
- if (props.dryRun) {
546
- logger.log(`--dry-run: exiting now.`);
547
- return;
548
- }
549
- assert(accountId, "Missing accountId");
550
-
551
- const uploadMs = Date.now() - start;
552
- const deployments: Promise<string[]>[] = [];
553
-
554
- if (deployToWorkersDev) {
555
- // Deploy to a subdomain of `workers.dev`
556
- const userSubdomain = await getSubdomain(accountId);
557
- const scriptURL =
558
- props.legacyEnv || !props.env
559
- ? `${scriptName}.${userSubdomain}.workers.dev`
560
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
561
- if (!available_on_subdomain) {
562
- // Enable the `workers.dev` subdomain.
563
- deployments.push(
564
- fetchResult(`${workerUrl}/subdomain`, {
565
- method: "POST",
566
- body: JSON.stringify({ enabled: true }),
567
- headers: {
568
- "Content-Type": "application/json",
569
- },
570
- })
571
- .then(() => [scriptURL])
572
- // Add a delay when the subdomain is first created.
573
- // This is to prevent an issue where a negative cache-hit
574
- // causes the subdomain to be unavailable for 30 seconds.
575
- // This is a temporary measure until we fix this on the edge.
576
- .then(async (url) => {
577
- await sleep(3000);
578
- return url;
579
- })
580
- );
581
- } else {
582
- deployments.push(Promise.resolve([scriptURL]));
583
- }
584
- } else {
585
- if (available_on_subdomain) {
586
- // Disable the workers.dev deployment
587
- await fetchResult(`${workerUrl}/subdomain`, {
588
- method: "POST",
589
- body: JSON.stringify({ enabled: false }),
590
- headers: {
591
- "Content-Type": "application/json",
592
- },
593
- });
594
- }
595
- }
596
-
597
- logger.log("Uploaded", workerName, formatTime(uploadMs));
598
-
599
- // Update routing table for the script.
600
- if (routesOnly.length > 0) {
601
- deployments.push(
602
- publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
603
- if (routesOnly.length > 10) {
604
- return routesOnly
605
- .slice(0, 9)
606
- .map((route) => renderRoute(route))
607
- .concat([`...and ${routesOnly.length - 10} more routes`]);
608
- }
609
- return routesOnly.map((route) => renderRoute(route));
610
- })
611
- );
612
- }
613
-
614
- // Update custom domains for the script
615
- if (customDomainsOnly.length > 0) {
616
- deployments.push(
617
- publishCustomDomains(workerUrl, accountId, customDomainsOnly)
618
- );
619
- }
620
-
621
- // Configure any schedules for the script.
622
- // TODO: rename this to `schedules`?
623
- if (triggers && triggers.length) {
624
- deployments.push(
625
- fetchResult(`${workerUrl}/schedules`, {
626
- // Note: PUT will override previous schedules on this script.
627
- method: "PUT",
628
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
629
- headers: {
630
- "Content-Type": "application/json",
631
- },
632
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
633
- );
634
- }
635
-
636
- const targets = await Promise.all(deployments);
637
- const deployMs = Date.now() - start - uploadMs;
638
-
639
- if (deployments.length > 0) {
640
- logger.log("Published", workerName, formatTime(deployMs));
641
- for (const target of targets.flat()) {
642
- // Append protocol only on workers.dev domains
643
- logger.log(
644
- " ",
645
- (target.endsWith("workers.dev") ? "https://" : "") + target
646
- );
647
- }
648
- } else {
649
- logger.log("No publish targets for", workerName, formatTime(deployMs));
650
- }
651
- }
652
-
653
- function formatTime(duration: number) {
654
- return `(${(duration / 1000).toFixed(2)} sec)`;
655
- }
656
-
657
- async function getSubdomain(accountId: string): Promise<string> {
658
- try {
659
- const { subdomain } = await fetchResult(
660
- `/accounts/${accountId}/workers/subdomain`
661
- );
662
- return subdomain;
663
- } catch (e) {
664
- const error = e as { code?: number };
665
- if (typeof error === "object" && !!error && error.code === 10007) {
666
- // 10007 error code: not found
667
- // https://api.cloudflare.com/#worker-subdomain-get-subdomain
668
-
669
- const errorMessage =
670
- "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
671
- const solutionMessage =
672
- "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
673
- const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
674
-
675
- throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
676
- } else {
677
- throw e;
678
- }
679
- }
680
- }
681
-
682
- /**
683
- * Associate the newly deployed Worker with the given routes.
684
- */
685
- async function publishRoutes(
686
- routes: Route[],
687
- {
688
- workerUrl,
689
- scriptName,
690
- notProd,
691
- }: { workerUrl: string; scriptName: string; notProd: boolean }
692
- ): Promise<string[]> {
693
- try {
694
- return await fetchResult(`${workerUrl}/routes`, {
695
- // Note: PUT will delete previous routes on this script.
696
- method: "PUT",
697
- body: JSON.stringify(
698
- routes.map((route) =>
699
- typeof route !== "object" ? { pattern: route } : route
700
- )
701
- ),
702
- headers: {
703
- "Content-Type": "application/json",
704
- },
705
- });
706
- } catch (e) {
707
- if (isAuthenticationError(e)) {
708
- // An authentication error is probably due to a known issue,
709
- // where the user is logged in via an API token that does not have "All Zones".
710
- return await publishRoutesFallback(routes, { scriptName, notProd });
711
- } else {
712
- throw e;
713
- }
714
- }
715
- }
716
-
717
- /**
718
- * Try updating routes for the Worker using a less optimal zone-based API.
719
- *
720
- * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
721
- */
722
- async function publishRoutesFallback(
723
- routes: Route[],
724
- { scriptName, notProd }: { scriptName: string; notProd: boolean }
725
- ) {
726
- if (notProd) {
727
- throw new Error(
728
- "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
729
- "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
730
- );
731
- }
732
- logger.warn(
733
- "The current authentication token does not have 'All Zones' permissions.\n" +
734
- "Falling back to using the zone-based API endpoint to update each route individually.\n" +
735
- "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
736
- "Existing routes for this Worker in such zones will not be deleted."
737
- );
738
-
739
- const deployedRoutes: string[] = [];
740
-
741
- // Collect the routes (and their zones) that will be deployed.
742
- const activeZones = new Map<string, string>();
743
- const routesToDeploy = new Map<string, string>();
744
- for (const route of routes) {
745
- const zone = await getZoneForRoute(route);
746
- if (zone) {
747
- activeZones.set(zone.id, zone.host);
748
- routesToDeploy.set(
749
- typeof route === "string" ? route : route.pattern,
750
- zone.id
751
- );
752
- }
753
- }
754
-
755
- // Collect the routes that are already deployed.
756
- const allRoutes = new Map<string, string>();
757
- const alreadyDeployedRoutes = new Set<string>();
758
- for (const [zone, host] of activeZones) {
759
- try {
760
- for (const { pattern, script } of await fetchListResult<{
761
- pattern: string;
762
- script: string;
763
- }>(`/zones/${zone}/workers/routes`)) {
764
- allRoutes.set(pattern, script);
765
- if (script === scriptName) {
766
- alreadyDeployedRoutes.add(pattern);
767
- }
768
- }
769
- } catch (e) {
770
- if (isAuthenticationError(e)) {
771
- e.notes.push({
772
- text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
773
- });
774
- }
775
- throw e;
776
- }
777
- }
778
-
779
- // Deploy each route that is not already deployed.
780
- for (const [routePattern, zoneId] of routesToDeploy.entries()) {
781
- if (allRoutes.has(routePattern)) {
782
- const knownScript = allRoutes.get(routePattern);
783
- if (knownScript === scriptName) {
784
- // This route is already associated with this worker, so no need to hit the API.
785
- alreadyDeployedRoutes.delete(routePattern);
786
- continue;
787
- } else {
788
- throw new Error(
789
- `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
790
- );
791
- }
792
- }
793
-
794
- const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
795
- method: "POST",
796
- body: JSON.stringify({
797
- pattern: routePattern,
798
- script: scriptName,
799
- }),
800
- headers: {
801
- "Content-Type": "application/json",
802
- },
803
- });
804
-
805
- deployedRoutes.push(pattern);
806
- }
807
-
808
- if (alreadyDeployedRoutes.size) {
809
- logger.warn(
810
- "Previously deployed routes:\n" +
811
- "The following routes were already associated with this worker, and have not been deleted:\n" +
812
- [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
813
- "If these routes are not wanted then you can remove them in the dashboard."
814
- );
815
- }
816
-
817
- return deployedRoutes;
818
- }
819
-
820
- function isAuthenticationError(e: unknown): e is ParseError {
821
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
822
- }