wrangler 0.0.0-beta.6 → 0.0.0-bfbb0be

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 (179) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +106 -5
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +77 -35
  7. package/src/__tests__/config-cache.test.ts +36 -0
  8. package/src/__tests__/configuration.test.ts +3548 -0
  9. package/src/__tests__/dev.test.tsx +1055 -0
  10. package/src/__tests__/guess-worker-format.test.ts +85 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +32 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +130 -0
  31. package/src/__tests__/index.test.ts +235 -130
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +107 -0
  34. package/src/__tests__/kv.test.ts +1619 -0
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1242 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6188 -0
  40. package/src/__tests__/r2.test.ts +233 -0
  41. package/src/__tests__/route.test.ts +45 -0
  42. package/src/__tests__/secret.test.ts +486 -0
  43. package/src/__tests__/tail.test.ts +690 -0
  44. package/src/__tests__/user.test.ts +132 -0
  45. package/src/__tests__/whoami.test.tsx +139 -0
  46. package/src/abort.d.ts +3 -0
  47. package/src/bundle-reporter.tsx +29 -0
  48. package/src/bundle.ts +204 -0
  49. package/src/cfetch/index.ts +121 -0
  50. package/src/cfetch/internal.ts +142 -0
  51. package/src/cli.ts +10 -7
  52. package/src/config/README.md +107 -0
  53. package/src/config/config.ts +243 -0
  54. package/src/config/diagnostics.ts +80 -0
  55. package/src/config/environment.ts +420 -0
  56. package/src/config/index.ts +225 -0
  57. package/src/config/validation-helpers.ts +584 -0
  58. package/src/config/validation.ts +1580 -0
  59. package/src/config-cache.ts +44 -0
  60. package/src/create-worker-preview.ts +185 -0
  61. package/src/create-worker-upload-form.ts +254 -0
  62. package/src/dev/dev-vars.ts +36 -0
  63. package/src/dev/dev.tsx +399 -0
  64. package/src/dev/local.tsx +321 -0
  65. package/src/dev/remote.tsx +282 -0
  66. package/src/dev/use-esbuild.ts +112 -0
  67. package/src/dialogs.tsx +68 -18
  68. package/src/durable.ts +102 -0
  69. package/src/entry.ts +328 -0
  70. package/src/environment-variables.ts +35 -0
  71. package/src/errors.ts +11 -0
  72. package/src/git-client.ts +42 -0
  73. package/src/https-options.ts +123 -0
  74. package/src/index.tsx +2100 -1002
  75. package/src/inspect.ts +662 -0
  76. package/src/intl-polyfill.d.ts +139 -0
  77. package/src/kv.ts +408 -0
  78. package/src/logger.ts +73 -0
  79. package/src/miniflare-cli/README.md +30 -0
  80. package/src/miniflare-cli/enum-keys.ts +17 -0
  81. package/src/miniflare-cli/index.ts +41 -0
  82. package/src/miniflare-cli/request-context.ts +40 -0
  83. package/src/module-collection.ts +258 -0
  84. package/src/open-in-browser.ts +17 -0
  85. package/src/package-manager.ts +174 -0
  86. package/src/pages/build.tsx +202 -0
  87. package/src/pages/constants.ts +7 -0
  88. package/src/pages/deployments.tsx +101 -0
  89. package/src/pages/dev.tsx +948 -0
  90. package/src/pages/functions/buildPlugin.ts +105 -0
  91. package/src/pages/functions/buildWorker.ts +151 -0
  92. package/src/pages/functions/filepath-routing.test.ts +234 -0
  93. package/src/pages/functions/filepath-routing.ts +189 -0
  94. package/src/pages/functions/identifiers.ts +78 -0
  95. package/src/pages/functions/routes.ts +151 -0
  96. package/src/pages/index.tsx +84 -0
  97. package/src/pages/projects.tsx +157 -0
  98. package/src/pages/publish.tsx +325 -0
  99. package/src/pages/types.ts +40 -0
  100. package/src/pages/upload.tsx +363 -0
  101. package/src/pages/utils.ts +12 -0
  102. package/src/parse.ts +222 -0
  103. package/src/paths.ts +26 -0
  104. package/src/proxy.ts +476 -0
  105. package/src/publish.ts +666 -215
  106. package/src/r2.ts +50 -0
  107. package/src/selfsigned.d.ts +29 -0
  108. package/src/sites.tsx +316 -59
  109. package/src/tail/filters.ts +279 -0
  110. package/src/tail/index.ts +299 -0
  111. package/src/tail/printing.ts +67 -0
  112. package/src/update-check.ts +19 -0
  113. package/src/user/choose-account.tsx +60 -0
  114. package/src/user/env-vars.ts +17 -0
  115. package/src/user/generate-auth-url.ts +33 -0
  116. package/src/user/generate-random-state.ts +16 -0
  117. package/src/user/index.ts +3 -0
  118. package/src/{user.tsx → user/user.tsx} +380 -276
  119. package/src/whoami.tsx +71 -0
  120. package/src/worker.ts +181 -0
  121. package/src/zones.ts +73 -0
  122. package/templates/gitignore +171 -0
  123. package/templates/new-worker-scheduled.js +17 -0
  124. package/templates/new-worker-scheduled.ts +32 -0
  125. package/templates/new-worker.js +15 -0
  126. package/templates/new-worker.ts +30 -0
  127. package/templates/no-op-worker.js +10 -0
  128. package/templates/pages-template-plugin.ts +155 -0
  129. package/templates/pages-template-worker.ts +161 -0
  130. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  131. package/templates/tsconfig.json +105 -0
  132. package/wrangler-dist/cli.js +108270 -117183
  133. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  134. package/src/__tests__/mock-cfetch.js +0 -46
  135. package/src/api/form_data.ts +0 -125
  136. package/src/api/inspect.ts +0 -441
  137. package/src/api/preview.ts +0 -123
  138. package/src/api/worker.ts +0 -140
  139. package/src/cfetch.ts +0 -72
  140. package/src/config.ts +0 -100
  141. package/src/dev.tsx +0 -687
  142. package/src/kv.tsx +0 -211
  143. package/src/pages.tsx +0 -340
  144. package/src/tail.tsx +0 -71
  145. package/src/util/fetch.ts +0 -74
  146. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  147. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  148. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  149. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  150. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  151. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  152. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  153. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  155. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  156. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  157. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  158. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  159. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  160. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  161. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  162. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  163. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  164. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  165. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  166. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  167. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  168. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  169. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  170. package/vendor/wrangler-mime/LICENSE +0 -21
  171. package/vendor/wrangler-mime/Mime.js +0 -97
  172. package/vendor/wrangler-mime/README.md +0 -187
  173. package/vendor/wrangler-mime/cli.js +0 -46
  174. package/vendor/wrangler-mime/index.js +0 -4
  175. package/vendor/wrangler-mime/lite.js +0 -4
  176. package/vendor/wrangler-mime/package.json +0 -52
  177. package/vendor/wrangler-mime/types/other.js +0 -1
  178. package/vendor/wrangler-mime/types/standard.js +0 -1
  179. package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts CHANGED
@@ -1,288 +1,739 @@
1
- import type { CfWorkerInit } from "./api/worker";
2
- import { toFormData } from "./api/form_data";
3
- import esbuild from "esbuild";
4
- import tmp from "tmp-promise";
5
- import type { Config } from "./config";
6
- import path from "path";
7
- import { readFile } from "fs/promises";
8
- import cfetch from "./cfetch";
9
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 { ParseError } from "./parse";
10
15
  import { syncAssets } from "./sites";
11
-
12
- type CfScriptFormat = void | "modules" | "service-worker";
16
+ import { getZoneForRoute } from "./zones";
17
+ import type { Config } from "./config";
18
+ import type {
19
+ Route,
20
+ ZoneIdRoute,
21
+ ZoneNameRoute,
22
+ CustomDomainRoute,
23
+ } from "./config/environment";
24
+ import type { Entry } from "./entry";
25
+ import type { AssetPaths } from "./sites";
26
+ import type { CfWorkerInit } from "./worker";
13
27
 
14
28
  type Props = {
15
29
  config: Config;
16
- format?: CfScriptFormat;
17
- script?: string;
18
- name?: string;
19
- env?: string;
20
- public?: string;
21
- site?: string;
22
- triggers?: (string | number)[];
23
- routes?: (string | number)[];
24
- legacyEnv?: boolean;
25
- jsxFactory: void | string;
26
- jsxFragment: void | string;
30
+ accountId: string | undefined;
31
+ entry: Entry;
32
+ rules: Config["rules"];
33
+ name: string | undefined;
34
+ env: string | undefined;
35
+ compatibilityDate: string | undefined;
36
+ compatibilityFlags: string[] | undefined;
37
+ assetPaths: AssetPaths | undefined;
38
+ triggers: string[] | undefined;
39
+ routes: string[] | undefined;
40
+ legacyEnv: boolean | undefined;
41
+ jsxFactory: string | undefined;
42
+ jsxFragment: string | undefined;
43
+ tsconfig: string | undefined;
44
+ isWorkersSite: boolean;
45
+ minify: boolean | undefined;
46
+ nodeCompat: boolean | undefined;
47
+ outDir: string | undefined;
48
+ dryRun: boolean | undefined;
27
49
  };
28
50
 
51
+ type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
52
+
29
53
  function sleep(ms: number) {
30
54
  return new Promise((resolve) => setTimeout(resolve, ms));
31
55
  }
32
56
 
33
- export default async function publish(props: Props): Promise<void> {
34
- if (props.public && props.format === "service-worker") {
35
- // TODO: check config too
36
- throw new Error(
37
- "You cannot use the service worker format with a public directory."
57
+ function renderRoute(route: Route): string {
58
+ let result = "";
59
+ if (typeof route === "string") {
60
+ result = route;
61
+ } else {
62
+ result = route.pattern;
63
+ const isCustomDomain = Boolean(
64
+ "custom_domain" in route && route.custom_domain
38
65
  );
66
+ if (isCustomDomain && "zone_id" in route) {
67
+ result += ` (custom domain - zone id: ${route.zone_id})`;
68
+ } else if (isCustomDomain && "zone_name" in route) {
69
+ result += ` (custom domain - zone name: ${route.zone_name})`;
70
+ } else if (isCustomDomain) {
71
+ result += ` (custom domain)`;
72
+ } else if ("zone_id" in route) {
73
+ result += ` (zone id: ${route.zone_id})`;
74
+ } else if ("zone_name" in route) {
75
+ result += ` (zone name: ${route.zone_name})`;
76
+ }
39
77
  }
40
- // TODO: warn if git/hg has uncommitted changes
41
- const { config } = props;
42
- const {
43
- account_id: accountId,
44
- build,
45
- // @ts-expect-error hidden
46
- __path__,
47
- } = config;
78
+ return result;
79
+ }
48
80
 
49
- const triggers = props.triggers || config.triggers?.crons;
50
- const routes = props.routes || config.routes;
81
+ // this function takes a string with quotes in it
82
+ // (i.e. `hello "world", if that really is your name`)
83
+ // and peels out the first instance of a substring
84
+ // bounded by quotes (so, in the example above, `world`)
85
+ //
86
+ // this is useful because the /domains api will return
87
+ // which domains conflicted in an error message, bounded
88
+ // by a string, which we can use to provide helpful
89
+ // messages to a user
90
+ function getQuoteBoundedSubstring(content: string) {
91
+ const matches = content.split('"');
92
+ return matches[1] ?? "";
93
+ }
51
94
 
52
- const jsxFactory = props.jsxFactory || config.jsxFactory;
53
- const jsxFragment = props.jsxFragment || config.jsxFragment;
95
+ function isOriginConflictError(
96
+ e: unknown
97
+ ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
98
+ return (
99
+ typeof e === "object" &&
100
+ e !== null &&
101
+ (e as { code: number }).code === 100116
102
+ );
103
+ }
54
104
 
55
- assert(config.account_id, "missing account id");
105
+ function isDNSConflictError(
106
+ e: unknown
107
+ ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
108
+ return (
109
+ typeof e === "object" &&
110
+ e !== null &&
111
+ (e as { code: number }).code === 100117
112
+ );
113
+ }
56
114
 
57
- let file: string;
58
- if (props.script) {
59
- file = props.script;
60
- assert(props.name, "name is required when using script");
61
- } else {
62
- assert(build?.upload?.main, "missing main file");
63
- assert(config.name, "missing name");
64
- file = path.join(path.dirname(__path__), build.upload.main);
65
- }
115
+ // empty error class to throw and then explicitly catch via `instanceof`
116
+ class CustomDomainOverrideRejected extends Error {}
66
117
 
67
- let scriptName = props.script ? props.name : config.name;
68
- if (props.legacyEnv) {
69
- scriptName += props.env ? `-${props.env}` : "";
118
+ // publishing to custom domains involves a few more steps than just updating
119
+ // the routing table, and thus the api implementing it is fairly defensive -
120
+ // it will error eagerly on conflicts against existing domains or existing
121
+ // managed DNS records
122
+ //
123
+ // however, you can pass params to override the errors. we start on the
124
+ // defensive path, and if one of these errors occur, we prompt the user
125
+ // for confirmation that they do indeed want to override the conflicts, and
126
+ // then retry the request with the right override added
127
+ //
128
+ // if a user does not confirm that they want to override, we skip publishing
129
+ // to these custom domains, but continue on through the rest of the
130
+ // publish stage
131
+ function publishCustomDomains(
132
+ workerUrl: string,
133
+ domains: Array<RouteObject>
134
+ ): Promise<string[]> {
135
+ const config = {
136
+ override_scope: true,
137
+ override_existing_origin: false,
138
+ override_existing_dns_record: false,
139
+ };
140
+ const origins = domains.map((domainRoute) => {
141
+ return {
142
+ hostname: domainRoute.pattern,
143
+ zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
144
+ zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
145
+ };
146
+ });
147
+
148
+ if (!process.stdout.isTTY) {
149
+ // running in non-interactive mode.
150
+ // existing origins / dns records are not indicative of errors,
151
+ // so we aggressively update rather than aggressively fail
152
+ config.override_existing_origin = true;
153
+ config.override_existing_dns_record = true;
70
154
  }
71
- const envName = props.env ?? "production";
72
155
 
73
- const destination = await tmp.dir({ unsafeCleanup: true });
74
-
75
- const result = await esbuild.build({
76
- ...(props.public
77
- ? {
78
- stdin: {
79
- contents: (
80
- await readFile(
81
- path.join(__dirname, "../static-asset-facade.js"),
82
- "utf8"
83
- )
84
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
85
- sourcefile: "static-asset-facade.js",
86
- resolveDir: path.dirname(file),
156
+ // Mixing promise chains with async/await is funky, but it allows us to keep related
157
+ // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
158
+ // while retaining the flexibility of promise chain fall-throughs. We can group error
159
+ // handling logic in dedicated catch calls, and all we have to do is re-throw an
160
+ // error and it will pass down to the next catch call
161
+ return fetchResult(`${workerUrl}/domains`, {
162
+ method: "PUT",
163
+ body: JSON.stringify({ ...config, origins }),
164
+ headers: {
165
+ "Content-Type": "application/json",
166
+ },
167
+ })
168
+ .catch(async (err) => {
169
+ if (isOriginConflictError(err)) {
170
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
171
+ const shouldContinue = await confirm(
172
+ `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
173
+ );
174
+ if (!shouldContinue) {
175
+ throw new CustomDomainOverrideRejected();
176
+ }
177
+ config.override_existing_origin = true;
178
+ await fetchResult(`${workerUrl}/domains`, {
179
+ method: "PUT",
180
+ body: JSON.stringify({ ...config, origins }),
181
+ headers: {
182
+ "Content-Type": "application/json",
87
183
  },
184
+ });
185
+ } else {
186
+ throw err;
187
+ }
188
+ })
189
+ .catch(async (err) => {
190
+ if (isDNSConflictError(err)) {
191
+ const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
192
+ const shouldContinue = await confirm(
193
+ `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
194
+ );
195
+ if (!shouldContinue) {
196
+ throw new CustomDomainOverrideRejected();
88
197
  }
89
- : { entryPoints: [file] }),
90
- bundle: true,
91
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
92
- outdir: destination.path,
93
- external: ["__STATIC_CONTENT_MANIFEST"],
94
- format: "esm",
95
- sourcemap: true,
96
- metafile: true,
97
- loader: {
98
- ".js": "jsx",
99
- },
100
- ...(jsxFactory && { jsxFactory }),
101
- ...(jsxFragment && { jsxFragment }),
102
- });
103
-
104
- const chunks = Object.entries(result.metafile.outputs).find(
105
- ([_path, { entryPoint }]) =>
106
- entryPoint ===
107
- (props.public
108
- ? path.join(path.dirname(file), "static-asset-facade.js")
109
- : file)
110
- );
198
+ config.override_existing_dns_record = true;
199
+ await fetchResult(`${workerUrl}/domains`, {
200
+ method: "PUT",
201
+ body: JSON.stringify({ ...config, origins }),
202
+ headers: {
203
+ "Content-Type": "application/json",
204
+ },
205
+ });
206
+ } else {
207
+ throw err;
208
+ }
209
+ })
210
+ .then(() => domains.map((domain) => renderRoute(domain)))
211
+ .catch((err) => {
212
+ if (err instanceof CustomDomainOverrideRejected) {
213
+ return [
214
+ domains.length > 1
215
+ ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
216
+ : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
217
+ ];
218
+ }
219
+ throw err;
220
+ });
221
+ }
111
222
 
112
- const { format } = props;
113
- const bundle = {
114
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
115
- exports: chunks[1].exports,
116
- };
223
+ export default async function publish(props: Props): Promise<void> {
224
+ // TODO: warn if git/hg has uncommitted changes
225
+ const { config, accountId } = props;
117
226
 
118
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
119
- // That way we'll be able to accurately tell if this is a service worker or not.
227
+ if (!(props.compatibilityDate || config.compatibility_date)) {
228
+ const compatibilityDateStr = `${new Date().getFullYear()}-${(
229
+ new Date().getMonth() + ""
230
+ ).padStart(2, "0")}-${(new Date().getDate() + "").padStart(2, "0")}`;
120
231
 
121
- if (format === "modules" && bundle.type === "commonjs") {
122
- console.error("⎔ Cannot use modules with a commonjs bundle.");
123
- // TODO: a much better error message here, with what to do next
124
- return;
232
+ throw new Error(`A compatibility_date is required when publishing. Add the following to your wrangler.toml file:.
233
+ \`\`\`
234
+ compatibility_date = "${compatibilityDateStr}"
235
+ \`\`\`
236
+ Or you could pass it in your terminal as \`--compatibility-date ${compatibilityDateStr}\`
237
+ See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information.`);
125
238
  }
126
- if (format === "service-worker" && bundle.type !== "esm") {
127
- console.error("⎔ Cannot use service-worker with a esm bundle.");
128
- // TODO: a much better error message here, with what to do next
129
- return;
239
+
240
+ const triggers = props.triggers || config.triggers?.crons;
241
+ const routes =
242
+ props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
243
+ const routesOnly: Array<Route> = [];
244
+ const customDomainsOnly: Array<RouteObject> = [];
245
+ for (const route of routes) {
246
+ if (typeof route !== "string" && route.custom_domain) {
247
+ if (route.pattern.includes("*")) {
248
+ throw new Error(
249
+ `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
250
+ );
251
+ }
252
+ if (route.pattern.includes("/")) {
253
+ throw new Error(
254
+ `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
255
+ );
256
+ }
257
+ customDomainsOnly.push(route);
258
+ } else {
259
+ routesOnly.push(route);
260
+ }
130
261
  }
131
262
 
132
- const content = await readFile(chunks[0], { encoding: "utf-8" });
133
- destination.cleanup();
134
- const assets =
135
- props.public || props.site || props.config.site?.bucket // TODO: allow both
136
- ? await syncAssets(
137
- accountId,
138
- scriptName,
139
- props.public || props.site || props.config.site?.bucket,
140
- false
141
- )
142
- : { manifest: undefined, namespace: undefined };
263
+ // deployToWorkersDev defaults to true only if there aren't any routes defined
264
+ const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
143
265
 
144
- const envRootObj = props.env ? config[`env.${props.env}`] : config;
266
+ const jsxFactory = props.jsxFactory || config.jsx_factory;
267
+ const jsxFragment = props.jsxFragment || config.jsx_fragment;
145
268
 
146
- const worker: CfWorkerInit = {
147
- main: {
148
- name: scriptName,
149
- content: content,
150
- type:
151
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
152
- ? "esm"
153
- : "commonjs",
154
- },
155
- variables: {
156
- ...(envRootObj?.vars || {}),
157
- ...(envRootObj?.kv_namespaces || []).reduce(
158
- (obj, { binding, preview_id, id }) => {
159
- return { ...obj, [binding]: { namespaceId: id } };
160
- },
161
- {}
162
- ),
163
- ...(assets.namespace
164
- ? { __STATIC_CONTENT: { namespaceId: assets.namespace } }
165
- : {}),
166
- },
167
- modules: assets.manifest
168
- ? [].concat({
169
- name: "__STATIC_CONTENT_MANIFEST",
170
- content: JSON.stringify(assets.manifest),
171
- type: "text",
172
- })
173
- : [],
174
- };
269
+ const minify = props.minify ?? config.minify;
175
270
 
176
- const start = Date.now();
177
- function formatTime(duration: number) {
178
- return `(${(duration / 1000).toFixed(2)} sec)`;
271
+ const nodeCompat = props.nodeCompat ?? config.node_compat;
272
+ if (nodeCompat) {
273
+ logger.warn(
274
+ "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."
275
+ );
276
+ }
277
+
278
+ const scriptName = props.name;
279
+ assert(
280
+ scriptName,
281
+ '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>"`'
282
+ );
283
+
284
+ assert(
285
+ !config.site || config.site.bucket,
286
+ "A [site] definition requires a `bucket` field with a path to the site's assets directory."
287
+ );
288
+
289
+ if (props.outDir) {
290
+ // we're using a custom output directory,
291
+ // so let's first ensure it exists
292
+ mkdirSync(props.outDir, { recursive: true });
293
+ // add a README
294
+ const readmePath = path.join(props.outDir, "README.md");
295
+ writeFileSync(
296
+ readmePath,
297
+ `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
298
+ );
179
299
  }
180
300
 
181
- const notProd = !props.legacyEnv && props.env;
301
+ const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
302
+ const envName = props.env ?? "production";
303
+
304
+ const start = Date.now();
305
+ const notProd = Boolean(!props.legacyEnv && props.env);
182
306
  const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
183
307
  const workerUrl = notProd
184
308
  ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
185
309
  : `/accounts/${accountId}/workers/scripts/${scriptName}`;
186
310
 
187
- // Upload the script so it has time to propogate.
188
- const { available_on_subdomain } = await cfetch(
189
- `${workerUrl}?available_on_subdomain=true`,
190
- {
191
- method: "PUT",
192
- // @ts-expect-error: TODO: fix this type error!
193
- body: toFormData(worker),
311
+ let available_on_subdomain; // we'll set this later
312
+
313
+ const { format } = props.entry;
314
+
315
+ if (
316
+ !props.isWorkersSite &&
317
+ Boolean(props.assetPaths) &&
318
+ format === "service-worker"
319
+ ) {
320
+ throw new Error(
321
+ "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/"
322
+ );
323
+ }
324
+
325
+ if (config.wasm_modules && format === "modules") {
326
+ throw new Error(
327
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
328
+ );
329
+ }
330
+
331
+ if (config.text_blobs && format === "modules") {
332
+ throw new Error(
333
+ "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"
334
+ );
335
+ }
336
+
337
+ if (config.data_blobs && format === "modules") {
338
+ throw new Error(
339
+ "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"
340
+ );
341
+ }
342
+ try {
343
+ const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
344
+ props.entry,
345
+ typeof destination === "string" ? destination : destination.path,
346
+ {
347
+ serveAssetsFromWorker:
348
+ !props.isWorkersSite && Boolean(props.assetPaths),
349
+ jsxFactory,
350
+ jsxFragment,
351
+ rules: props.rules,
352
+ tsconfig: props.tsconfig ?? config.tsconfig,
353
+ minify,
354
+ nodeCompat,
355
+ }
356
+ );
357
+
358
+ const content = readFileSync(resolvedEntryPointPath, {
359
+ encoding: "utf-8",
360
+ });
361
+
362
+ // durable object migrations
363
+ const migrations = !props.dryRun
364
+ ? await getMigrationsToUpload(scriptName, {
365
+ accountId,
366
+ config,
367
+ legacyEnv: props.legacyEnv,
368
+ env: props.env,
369
+ })
370
+ : undefined;
371
+
372
+ const assets = await syncAssets(
373
+ accountId,
374
+ // When we're using the newer service environments, we wouldn't
375
+ // have added the env name on to the script name. However, we must
376
+ // include it in the kv namespace name regardless (since there's no
377
+ // concept of service environments for kv namespaces yet).
378
+ scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
379
+ props.assetPaths,
380
+ false,
381
+ props.dryRun
382
+ );
383
+
384
+ const bindings: CfWorkerInit["bindings"] = {
385
+ kv_namespaces: (config.kv_namespaces || []).concat(
386
+ assets.namespace
387
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
388
+ : []
389
+ ),
390
+ vars: config.vars,
391
+ wasm_modules: config.wasm_modules,
392
+ text_blobs: {
393
+ ...config.text_blobs,
394
+ ...(assets.manifest &&
395
+ format === "service-worker" && {
396
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
397
+ }),
398
+ },
399
+ data_blobs: config.data_blobs,
400
+ durable_objects: config.durable_objects,
401
+ r2_buckets: config.r2_buckets,
402
+ services: config.services,
403
+ unsafe: config.unsafe?.bindings,
404
+ };
405
+
406
+ if (assets.manifest) {
407
+ modules.push({
408
+ name: "__STATIC_CONTENT_MANIFEST",
409
+ content: JSON.stringify(assets.manifest),
410
+ type: "text",
411
+ });
194
412
  }
195
- );
196
413
 
197
- const uploadMs = Date.now() - start;
198
- console.log("Uploaded", workerName, formatTime(uploadMs));
199
- const deployments: Promise<string[]>[] = [];
414
+ const worker: CfWorkerInit = {
415
+ name: scriptName,
416
+ main: {
417
+ name: path.basename(resolvedEntryPointPath),
418
+ content: content,
419
+ type: bundleType,
420
+ },
421
+ bindings,
422
+ migrations,
423
+ modules,
424
+ compatibility_date: props.compatibilityDate ?? config.compatibility_date,
425
+ compatibility_flags:
426
+ props.compatibilityFlags ?? config.compatibility_flags,
427
+ usage_model: config.usage_model,
428
+ };
200
429
 
201
- const userSubdomain = (
202
- await cfetch<{ subdomain: string }>(
203
- `/accounts/${accountId}/workers/subdomain`
204
- )
205
- ).subdomain;
430
+ const withoutStaticAssets = {
431
+ ...bindings,
432
+ kv_namespaces: config.kv_namespaces,
433
+ text_blobs: config.text_blobs,
434
+ };
435
+ printBindings(withoutStaticAssets);
436
+
437
+ if (!props.dryRun) {
438
+ // Upload the script so it has time to propagate.
439
+ // We can also now tell whether available_on_subdomain is set
440
+ available_on_subdomain = (
441
+ await fetchResult<{ available_on_subdomain: boolean }>(
442
+ workerUrl,
443
+ {
444
+ method: "PUT",
445
+ body: createWorkerUploadForm(worker),
446
+ },
447
+ new URLSearchParams({
448
+ include_subdomain_availability: "true",
449
+ // pass excludeScript so the whole body of the
450
+ // script doesn't get included in the response
451
+ excludeScript: "true",
452
+ })
453
+ )
454
+ ).available_on_subdomain;
455
+ }
456
+ void printBundleSize(
457
+ { name: path.basename(resolvedEntryPointPath), content: content },
458
+ modules
459
+ );
460
+ } finally {
461
+ if (typeof destination !== "string") {
462
+ // this means we're using a temp dir,
463
+ // so let's clean up before we proceed
464
+ await destination.cleanup();
465
+ }
466
+ }
206
467
 
207
- const scriptURL =
208
- props.legacyEnv || !props.env
209
- ? `${scriptName}.${userSubdomain}.workers.dev`
210
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
468
+ if (props.dryRun) {
469
+ logger.log(`--dry-run: exiting now.`);
470
+ return;
471
+ }
472
+ assert(accountId, "Missing accountId");
211
473
 
212
- // Enable the `workers.dev` subdomain.
213
- // TODO: Make this configurable.
214
- if (!available_on_subdomain) {
215
- deployments.push(
216
- cfetch(`${workerUrl}/subdomain`, {
474
+ const uploadMs = Date.now() - start;
475
+ const deployments: Promise<string[]>[] = [];
476
+
477
+ if (deployToWorkersDev) {
478
+ // Deploy to a subdomain of `workers.dev`
479
+ const userSubdomain = await getSubdomain(accountId);
480
+ const scriptURL =
481
+ props.legacyEnv || !props.env
482
+ ? `${scriptName}.${userSubdomain}.workers.dev`
483
+ : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
484
+ if (!available_on_subdomain) {
485
+ // Enable the `workers.dev` subdomain.
486
+ deployments.push(
487
+ fetchResult(`${workerUrl}/subdomain`, {
488
+ method: "POST",
489
+ body: JSON.stringify({ enabled: true }),
490
+ headers: {
491
+ "Content-Type": "application/json",
492
+ },
493
+ })
494
+ .then(() => [scriptURL])
495
+ // Add a delay when the subdomain is first created.
496
+ // This is to prevent an issue where a negative cache-hit
497
+ // causes the subdomain to be unavailable for 30 seconds.
498
+ // This is a temporary measure until we fix this on the edge.
499
+ .then(async (url) => {
500
+ await sleep(3000);
501
+ return url;
502
+ })
503
+ );
504
+ } else {
505
+ deployments.push(Promise.resolve([scriptURL]));
506
+ }
507
+ } else {
508
+ if (available_on_subdomain) {
509
+ // Disable the workers.dev deployment
510
+ await fetchResult(`${workerUrl}/subdomain`, {
217
511
  method: "POST",
218
- body: JSON.stringify({ enabled: true }),
512
+ body: JSON.stringify({ enabled: false }),
219
513
  headers: {
220
514
  "Content-Type": "application/json",
221
515
  },
222
- })
223
- .then(() => [scriptURL])
224
- // Add a delay when the subdomain is first created.
225
- // This is to prevent an issue where a negative cache-hit
226
- // causes the subdomain to be unavailable for 30 seconds.
227
- // This is a temporary measure until we fix this on the edge.
228
- .then((url) => {
229
- sleep(3000);
230
- return url;
231
- })
232
- );
233
- } else {
234
- deployments.push(Promise.resolve([scriptURL]));
516
+ });
517
+ }
235
518
  }
236
519
 
520
+ logger.log("Uploaded", workerName, formatTime(uploadMs));
521
+
237
522
  // Update routing table for the script.
238
- if (routes && routes.length) {
523
+ if (routesOnly.length > 0) {
239
524
  deployments.push(
240
- cfetch(`${workerUrl}/routes`, {
241
- // TODO: PATCH will not delete previous routes on this script,
242
- // whereas PUT will. We need to decide on the default behaviour
243
- // and how to configure it.
244
- method: "PUT",
245
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
246
- headers: {
247
- "Content-Type": "application/json",
248
- },
249
- }).then(() => {
250
- if (routes.length > 10) {
251
- return routes
525
+ publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
526
+ if (routesOnly.length > 10) {
527
+ return routesOnly
252
528
  .slice(0, 9)
253
- .map(String)
254
- .concat([`...and ${routes.length - 10} more routes`]);
529
+ .map((route) => renderRoute(route))
530
+ .concat([`...and ${routesOnly.length - 10} more routes`]);
255
531
  }
256
- return routes.map(String);
532
+ return routesOnly.map((route) => renderRoute(route));
257
533
  })
258
534
  );
259
535
  }
260
536
 
537
+ // Update custom domains for the script
538
+ if (customDomainsOnly.length > 0) {
539
+ deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
540
+ }
541
+
261
542
  // Configure any schedules for the script.
262
543
  // TODO: rename this to `schedules`?
263
544
  if (triggers && triggers.length) {
264
545
  deployments.push(
265
- cfetch(`${workerUrl}/schedules`, {
266
- // TODO: Unlike routes, this endpoint does not support PATCH.
267
- // So technically, this will override any previous schedules.
268
- // We should change the endpoint to support PATCH.
546
+ fetchResult(`${workerUrl}/schedules`, {
547
+ // Note: PUT will override previous schedules on this script.
269
548
  method: "PUT",
270
549
  body: JSON.stringify(triggers.map((cron) => ({ cron }))),
271
550
  headers: {
272
551
  "Content-Type": "application/json",
273
552
  },
274
- }).then(() => triggers.map(String))
553
+ }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
275
554
  );
276
555
  }
277
556
 
278
- if (!deployments.length) {
279
- return;
280
- }
281
-
282
557
  const targets = await Promise.all(deployments);
283
558
  const deployMs = Date.now() - start - uploadMs;
284
- console.log("Deployed", workerName, formatTime(deployMs));
285
- for (const target of targets.flat()) {
286
- console.log(" ", target);
559
+
560
+ if (deployments.length > 0) {
561
+ logger.log("Published", workerName, formatTime(deployMs));
562
+ for (const target of targets.flat()) {
563
+ logger.log(" ", target);
564
+ }
565
+ } else {
566
+ logger.log("No publish targets for", workerName, formatTime(deployMs));
287
567
  }
288
568
  }
569
+
570
+ function formatTime(duration: number) {
571
+ return `(${(duration / 1000).toFixed(2)} sec)`;
572
+ }
573
+
574
+ async function getSubdomain(accountId: string): Promise<string> {
575
+ try {
576
+ const { subdomain } = await fetchResult(
577
+ `/accounts/${accountId}/workers/subdomain`
578
+ );
579
+ return subdomain;
580
+ } catch (e) {
581
+ const error = e as { code?: number };
582
+ if (typeof error === "object" && !!error && error.code === 10007) {
583
+ // 10007 error code: not found
584
+ // https://api.cloudflare.com/#worker-subdomain-get-subdomain
585
+
586
+ const errorMessage =
587
+ "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
588
+ const solutionMessage =
589
+ "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
590
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
591
+
592
+ throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
593
+ } else {
594
+ throw e;
595
+ }
596
+ }
597
+ }
598
+
599
+ /**
600
+ * Associate the newly deployed Worker with the given routes.
601
+ */
602
+ async function publishRoutes(
603
+ routes: Route[],
604
+ {
605
+ workerUrl,
606
+ scriptName,
607
+ notProd,
608
+ }: { workerUrl: string; scriptName: string; notProd: boolean }
609
+ ): Promise<string[]> {
610
+ try {
611
+ return await fetchResult(`${workerUrl}/routes`, {
612
+ // Note: PUT will delete previous routes on this script.
613
+ method: "PUT",
614
+ body: JSON.stringify(
615
+ routes.map((route) =>
616
+ typeof route !== "object" ? { pattern: route } : route
617
+ )
618
+ ),
619
+ headers: {
620
+ "Content-Type": "application/json",
621
+ },
622
+ });
623
+ } catch (e) {
624
+ if (isAuthenticationError(e)) {
625
+ // An authentication error is probably due to a known issue,
626
+ // where the user is logged in via an API token that does not have "All Zones".
627
+ return await publishRoutesFallback(routes, { scriptName, notProd });
628
+ } else {
629
+ throw e;
630
+ }
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Try updating routes for the Worker using a less optimal zone-based API.
636
+ *
637
+ * Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
638
+ */
639
+ async function publishRoutesFallback(
640
+ routes: Route[],
641
+ { scriptName, notProd }: { scriptName: string; notProd: boolean }
642
+ ) {
643
+ if (notProd) {
644
+ throw new Error(
645
+ "Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
646
+ "Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
647
+ );
648
+ }
649
+ logger.warn(
650
+ "The current authentication token does not have 'All Zones' permissions.\n" +
651
+ "Falling back to using the zone-based API endpoint to update each route individually.\n" +
652
+ "Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
653
+ "Existing routes for this Worker in such zones will not be deleted."
654
+ );
655
+
656
+ const deployedRoutes: string[] = [];
657
+
658
+ // Collect the routes (and their zones) that will be deployed.
659
+ const activeZones = new Map<string, string>();
660
+ const routesToDeploy = new Map<string, string>();
661
+ for (const route of routes) {
662
+ const zone = await getZoneForRoute(route);
663
+ if (zone) {
664
+ activeZones.set(zone.id, zone.host);
665
+ routesToDeploy.set(
666
+ typeof route === "string" ? route : route.pattern,
667
+ zone.id
668
+ );
669
+ }
670
+ }
671
+
672
+ // Collect the routes that are already deployed.
673
+ const allRoutes = new Map<string, string>();
674
+ const alreadyDeployedRoutes = new Set<string>();
675
+ for (const [zone, host] of activeZones) {
676
+ try {
677
+ for (const { pattern, script } of await fetchListResult<{
678
+ pattern: string;
679
+ script: string;
680
+ }>(`/zones/${zone}/workers/routes`)) {
681
+ allRoutes.set(pattern, script);
682
+ if (script === scriptName) {
683
+ alreadyDeployedRoutes.add(pattern);
684
+ }
685
+ }
686
+ } catch (e) {
687
+ if (isAuthenticationError(e)) {
688
+ e.notes.push({
689
+ text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
690
+ });
691
+ }
692
+ throw e;
693
+ }
694
+ }
695
+
696
+ // Deploy each route that is not already deployed.
697
+ for (const [routePattern, zoneId] of routesToDeploy.entries()) {
698
+ if (allRoutes.has(routePattern)) {
699
+ const knownScript = allRoutes.get(routePattern);
700
+ if (knownScript === scriptName) {
701
+ // This route is already associated with this worker, so no need to hit the API.
702
+ alreadyDeployedRoutes.delete(routePattern);
703
+ continue;
704
+ } else {
705
+ throw new Error(
706
+ `The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
707
+ );
708
+ }
709
+ }
710
+
711
+ const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
712
+ method: "POST",
713
+ body: JSON.stringify({
714
+ pattern: routePattern,
715
+ script: scriptName,
716
+ }),
717
+ headers: {
718
+ "Content-Type": "application/json",
719
+ },
720
+ });
721
+
722
+ deployedRoutes.push(pattern);
723
+ }
724
+
725
+ if (alreadyDeployedRoutes.size) {
726
+ logger.warn(
727
+ "Previously deployed routes:\n" +
728
+ "The following routes were already associated with this worker, and have not been deleted:\n" +
729
+ [...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
730
+ "If these routes are not wanted then you can remove them in the dashboard."
731
+ );
732
+ }
733
+
734
+ return deployedRoutes;
735
+ }
736
+
737
+ function isAuthenticationError(e: unknown): e is ParseError {
738
+ return e instanceof ParseError && (e as { code?: number }).code === 10000;
739
+ }