wrangler 0.0.0-e978986 → 0.0.0-e981d0be5

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 (187) hide show
  1. package/README.md +46 -36
  2. package/bin/wrangler.js +82 -69
  3. package/config-schema.json +2278 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +131 -102
  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 +19 -0
  11. package/templates/gitignore +2 -3
  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 +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +4 -4
  28. package/templates/new-worker-scheduled.ts +17 -17
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +19 -16
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +13 -103
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26693 -0
  48. package/wrangler-dist/cli.js +148246 -120054
  49. package/Cloudflare_CA.pem +0 -18
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -4886
  55. package/pages/functions/buildPlugin.ts +0 -105
  56. package/pages/functions/buildWorker.ts +0 -151
  57. package/pages/functions/filepath-routing.test.ts +0 -234
  58. package/pages/functions/filepath-routing.ts +0 -189
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -156
  61. package/pages/functions/template-plugin.ts +0 -147
  62. package/pages/functions/template-worker.ts +0 -143
  63. package/src/__tests__/config-cache.test.ts +0 -36
  64. package/src/__tests__/configuration.test.ts +0 -3374
  65. package/src/__tests__/dev.test.tsx +0 -980
  66. package/src/__tests__/guess-worker-format.test.ts +0 -85
  67. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  68. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  69. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  70. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  71. package/src/__tests__/helpers/mock-bin.ts +0 -36
  72. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  73. package/src/__tests__/helpers/mock-console.ts +0 -87
  74. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  75. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  76. package/src/__tests__/helpers/mock-istty.ts +0 -27
  77. package/src/__tests__/helpers/mock-kv.ts +0 -33
  78. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  79. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  80. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  81. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  82. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  83. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  84. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  85. package/src/__tests__/https-options.test.ts +0 -130
  86. package/src/__tests__/index.test.ts +0 -256
  87. package/src/__tests__/init.test.ts +0 -1567
  88. package/src/__tests__/jest.setup.ts +0 -77
  89. package/src/__tests__/kv.test.ts +0 -1481
  90. package/src/__tests__/logger.test.ts +0 -115
  91. package/src/__tests__/package-manager.test.ts +0 -353
  92. package/src/__tests__/pages.test.ts +0 -657
  93. package/src/__tests__/parse.test.ts +0 -330
  94. package/src/__tests__/publish.test.ts +0 -5468
  95. package/src/__tests__/r2.test.ts +0 -233
  96. package/src/__tests__/route.test.ts +0 -45
  97. package/src/__tests__/secret.test.ts +0 -481
  98. package/src/__tests__/tail.test.ts +0 -690
  99. package/src/__tests__/user.test.ts +0 -131
  100. package/src/__tests__/whoami.test.tsx +0 -105
  101. package/src/abort.d.ts +0 -3
  102. package/src/bundle.ts +0 -200
  103. package/src/cfetch/index.ts +0 -121
  104. package/src/cfetch/internal.ts +0 -145
  105. package/src/cli.ts +0 -13
  106. package/src/config/README.md +0 -107
  107. package/src/config/config.ts +0 -234
  108. package/src/config/diagnostics.ts +0 -80
  109. package/src/config/environment.ts +0 -420
  110. package/src/config/index.ts +0 -225
  111. package/src/config/validation-helpers.ts +0 -575
  112. package/src/config/validation.ts +0 -1539
  113. package/src/config-cache.ts +0 -45
  114. package/src/create-worker-preview.ts +0 -185
  115. package/src/create-worker-upload-form.ts +0 -254
  116. package/src/dev/dev-vars.ts +0 -36
  117. package/src/dev/dev.tsx +0 -419
  118. package/src/dev/local.tsx +0 -318
  119. package/src/dev/remote.tsx +0 -227
  120. package/src/dev/use-esbuild.ts +0 -118
  121. package/src/dialogs.tsx +0 -135
  122. package/src/durable.ts +0 -102
  123. package/src/entry.ts +0 -322
  124. package/src/environment-variables.ts +0 -35
  125. package/src/errors.ts +0 -11
  126. package/src/https-options.ts +0 -123
  127. package/src/index.tsx +0 -2848
  128. package/src/inspect.ts +0 -662
  129. package/src/intl-polyfill.d.ts +0 -139
  130. package/src/kv.ts +0 -408
  131. package/src/logger.ts +0 -66
  132. package/src/miniflare-cli/README.md +0 -30
  133. package/src/miniflare-cli/enum-keys.ts +0 -17
  134. package/src/miniflare-cli/index.ts +0 -41
  135. package/src/miniflare-cli/request-context.ts +0 -40
  136. package/src/module-collection.ts +0 -258
  137. package/src/open-in-browser.ts +0 -19
  138. package/src/package-manager.ts +0 -174
  139. package/src/pages.tsx +0 -2027
  140. package/src/parse.ts +0 -202
  141. package/src/paths.ts +0 -26
  142. package/src/proxy.ts +0 -465
  143. package/src/publish.ts +0 -583
  144. package/src/r2.ts +0 -50
  145. package/src/selfsigned.d.ts +0 -29
  146. package/src/sites.tsx +0 -295
  147. package/src/tail/filters.ts +0 -279
  148. package/src/tail/index.ts +0 -299
  149. package/src/tail/printing.ts +0 -67
  150. package/src/update-check.ts +0 -19
  151. package/src/user.tsx +0 -1203
  152. package/src/whoami.tsx +0 -70
  153. package/src/worker.ts +0 -180
  154. package/templates/static-asset-facade.js +0 -47
  155. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  156. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  157. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  158. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  159. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  160. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  161. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  162. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  168. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  169. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  170. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  171. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  172. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  173. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  174. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  175. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  176. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  177. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  178. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  179. package/vendor/wrangler-mime/LICENSE +0 -21
  180. package/vendor/wrangler-mime/Mime.js +0 -97
  181. package/vendor/wrangler-mime/README.md +0 -187
  182. package/vendor/wrangler-mime/cli.js +0 -46
  183. package/vendor/wrangler-mime/index.js +0 -4
  184. package/vendor/wrangler-mime/lite.js +0 -4
  185. package/vendor/wrangler-mime/package.json +0 -52
  186. package/vendor/wrangler-mime/types/other.js +0 -1
  187. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/publish.ts DELETED
@@ -1,583 +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 { fetchResult } from "./cfetch";
8
- import { printBindings } from "./config";
9
- import { createWorkerUploadForm } from "./create-worker-upload-form";
10
- import { confirm } from "./dialogs";
11
- import { getMigrationsToUpload } from "./durable";
12
- import { logger } from "./logger";
13
- import { syncAssets } from "./sites";
14
- import type { Config } from "./config";
15
- import type {
16
- Route,
17
- ZoneIdRoute,
18
- ZoneNameRoute,
19
- CustomDomainRoute,
20
- } from "./config/environment";
21
- import type { Entry } from "./entry";
22
- import type { AssetPaths } from "./sites";
23
- import type { CfWorkerInit } from "./worker";
24
-
25
- type Props = {
26
- config: Config;
27
- accountId: string | undefined;
28
- entry: Entry;
29
- rules: Config["rules"];
30
- name: string | undefined;
31
- env: string | undefined;
32
- compatibilityDate: string | undefined;
33
- compatibilityFlags: string[] | undefined;
34
- assetPaths: AssetPaths | undefined;
35
- triggers: string[] | undefined;
36
- routes: string[] | undefined;
37
- legacyEnv: boolean | undefined;
38
- jsxFactory: string | undefined;
39
- jsxFragment: string | undefined;
40
- tsconfig: string | undefined;
41
- experimentalPublic: boolean;
42
- minify: boolean | undefined;
43
- nodeCompat: boolean | undefined;
44
- outDir: string | undefined;
45
- dryRun: boolean | undefined;
46
- };
47
-
48
- type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
49
-
50
- function sleep(ms: number) {
51
- return new Promise((resolve) => setTimeout(resolve, ms));
52
- }
53
-
54
- function renderRoute(route: Route): string {
55
- let result = "";
56
- if (typeof route === "string") {
57
- result = route;
58
- } else {
59
- result = route.pattern;
60
- const isCustomDomain = Boolean(
61
- "custom_domain" in route && route.custom_domain
62
- );
63
- if (isCustomDomain && "zone_id" in route) {
64
- result += ` (custom domain - zone id: ${route.zone_id})`;
65
- } else if (isCustomDomain && "zone_name" in route) {
66
- result += ` (custom domain - zone name: ${route.zone_name})`;
67
- } else if (isCustomDomain) {
68
- result += ` (custom domain)`;
69
- } else if ("zone_id" in route) {
70
- result += ` (zone id: ${route.zone_id})`;
71
- } else if ("zone_name" in route) {
72
- result += ` (zone name: ${route.zone_name})`;
73
- }
74
- }
75
- return result;
76
- }
77
-
78
- // this function takes a string with quotes in it
79
- // (i.e. `hello "world", if that really is your name`)
80
- // and peels out the first instance of a substring
81
- // bounded by quotes (so, in the example above, `world`)
82
- //
83
- // this is useful because the /domains api will return
84
- // which domains conflicted in an error message, bounded
85
- // by a string, which we can use to provide helpful
86
- // messages to a user
87
- function getQuoteBoundedSubstring(content: string) {
88
- const matches = content.split('"');
89
- return matches[1] ?? "";
90
- }
91
-
92
- function isOriginConflictError(
93
- e: unknown
94
- ): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
95
- return (
96
- typeof e === "object" &&
97
- e !== null &&
98
- (e as { code: number }).code === 100116
99
- );
100
- }
101
-
102
- function isDNSConflictError(
103
- e: unknown
104
- ): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
105
- return (
106
- typeof e === "object" &&
107
- e !== null &&
108
- (e as { code: number }).code === 100117
109
- );
110
- }
111
-
112
- // empty error class to throw and then explicitly catch via `instanceof`
113
- class CustomDomainOverrideRejected extends Error {}
114
-
115
- // publishing to custom domains involves a few more steps than just updating
116
- // the routing table, and thus the api implementing it is fairly defensive -
117
- // it will error eagerly on conflicts against existing domains or existing
118
- // managed DNS records
119
- //
120
- // however, you can pass params to override the errors. we start on the
121
- // defensive path, and if one of these errors occur, we prompt the user
122
- // for confirmation that they do indeed want to override the conflicts, and
123
- // then retry the request with the right override added
124
- //
125
- // if a user does not confirm that they want to override, we skip publishing
126
- // to these custom domains, but continue on through the rest of the
127
- // publish stage
128
- function publishCustomDomains(
129
- workerUrl: string,
130
- domains: Array<RouteObject>
131
- ): Promise<string[]> {
132
- const config = {
133
- override_scope: true,
134
- override_existing_origin: false,
135
- override_existing_dns_record: false,
136
- };
137
- const origins = domains.map((domainRoute) => {
138
- return {
139
- hostname: domainRoute.pattern,
140
- zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
141
- zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
142
- };
143
- });
144
-
145
- if (!process.stdout.isTTY) {
146
- // running in non-interactive mode.
147
- // existing origins / dns records are not indicative of errors,
148
- // so we aggressively update rather than aggressively fail
149
- config.override_existing_origin = true;
150
- config.override_existing_dns_record = true;
151
- }
152
-
153
- // Mixing promise chains with async/await is funky, but it allows us to keep related
154
- // logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
155
- // while retaining the flexibility of promise chain fall-throughs. We can group error
156
- // handling logic in dedicated catch calls, and all we have to do is re-throw an
157
- // error and it will pass down to the next catch call
158
- return fetchResult(`${workerUrl}/domains`, {
159
- method: "PUT",
160
- body: JSON.stringify({ ...config, origins }),
161
- headers: {
162
- "Content-Type": "application/json",
163
- },
164
- })
165
- .catch(async (err) => {
166
- if (isOriginConflictError(err)) {
167
- const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
168
- const shouldContinue = await confirm(
169
- `Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
170
- );
171
- if (!shouldContinue) {
172
- throw new CustomDomainOverrideRejected();
173
- }
174
- config.override_existing_origin = true;
175
- await fetchResult(`${workerUrl}/domains`, {
176
- method: "PUT",
177
- body: JSON.stringify({ ...config, origins }),
178
- headers: {
179
- "Content-Type": "application/json",
180
- },
181
- });
182
- } else {
183
- throw err;
184
- }
185
- })
186
- .catch(async (err) => {
187
- if (isDNSConflictError(err)) {
188
- const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
189
- const shouldContinue = await confirm(
190
- `You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
191
- );
192
- if (!shouldContinue) {
193
- throw new CustomDomainOverrideRejected();
194
- }
195
- config.override_existing_dns_record = true;
196
- await fetchResult(`${workerUrl}/domains`, {
197
- method: "PUT",
198
- body: JSON.stringify({ ...config, origins }),
199
- headers: {
200
- "Content-Type": "application/json",
201
- },
202
- });
203
- } else {
204
- throw err;
205
- }
206
- })
207
- .then(() => domains.map((domain) => renderRoute(domain)))
208
- .catch((err) => {
209
- if (err instanceof CustomDomainOverrideRejected) {
210
- return [
211
- domains.length > 1
212
- ? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
213
- : `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
214
- ];
215
- }
216
- throw err;
217
- });
218
- }
219
-
220
- export default async function publish(props: Props): Promise<void> {
221
- // TODO: warn if git/hg has uncommitted changes
222
- const { config, accountId } = props;
223
-
224
- assert(
225
- props.compatibilityDate || config.compatibility_date,
226
- "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."
227
- );
228
-
229
- const triggers = props.triggers || config.triggers?.crons;
230
- const routes =
231
- props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
232
- const routesOnly: Array<Route> = [];
233
- const customDomainsOnly: Array<RouteObject> = [];
234
- for (const route of routes) {
235
- if (typeof route !== "string" && route.custom_domain) {
236
- if (route.pattern.includes("*")) {
237
- throw new Error(
238
- `Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
239
- );
240
- }
241
- if (route.pattern.includes("/")) {
242
- throw new Error(
243
- `Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
244
- );
245
- }
246
- customDomainsOnly.push(route);
247
- } else {
248
- routesOnly.push(route);
249
- }
250
- }
251
-
252
- // deployToWorkersDev defaults to true only if there aren't any routes defined
253
- const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
254
-
255
- const jsxFactory = props.jsxFactory || config.jsx_factory;
256
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
257
-
258
- const minify = props.minify ?? config.minify;
259
-
260
- const nodeCompat = props.nodeCompat ?? config.node_compat;
261
- if (nodeCompat) {
262
- logger.warn(
263
- "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
264
- );
265
- }
266
-
267
- const scriptName = props.name;
268
- assert(
269
- scriptName,
270
- '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>"`'
271
- );
272
-
273
- assert(
274
- !config.site || config.site.bucket,
275
- "A [site] definition requires a `bucket` field with a path to the site's public directory."
276
- );
277
-
278
- if (props.outDir) {
279
- // we're using a custom output directory,
280
- // so let's first ensure it exists
281
- mkdirSync(props.outDir, { recursive: true });
282
- // add a README
283
- const readmePath = path.join(props.outDir, "README.md");
284
- writeFileSync(
285
- readmePath,
286
- `This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
287
- );
288
- }
289
-
290
- const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
291
- const envName = props.env ?? "production";
292
-
293
- const start = Date.now();
294
- const notProd = !props.legacyEnv && props.env;
295
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
296
- const workerUrl = notProd
297
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
298
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
299
-
300
- let available_on_subdomain; // we'll set this later
301
-
302
- const { format } = props.entry;
303
-
304
- if (props.experimentalPublic && format === "service-worker") {
305
- throw new Error(
306
- "You cannot publish in the service-worker format with a public directory."
307
- );
308
- }
309
-
310
- if (config.wasm_modules && format === "modules") {
311
- throw new Error(
312
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
313
- );
314
- }
315
-
316
- if (config.text_blobs && format === "modules") {
317
- throw new Error(
318
- "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"
319
- );
320
- }
321
-
322
- if (config.data_blobs && format === "modules") {
323
- throw new Error(
324
- "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"
325
- );
326
- }
327
- try {
328
- const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
329
- props.entry,
330
- typeof destination === "string" ? destination : destination.path,
331
- {
332
- serveAssetsFromWorker: props.experimentalPublic,
333
- jsxFactory,
334
- jsxFragment,
335
- rules: props.rules,
336
- tsconfig: props.tsconfig ?? config.tsconfig,
337
- minify,
338
- nodeCompat,
339
- }
340
- );
341
-
342
- const content = readFileSync(resolvedEntryPointPath, {
343
- encoding: "utf-8",
344
- });
345
-
346
- // durable object migrations
347
- const migrations = !props.dryRun
348
- ? await getMigrationsToUpload(scriptName, {
349
- accountId,
350
- config,
351
- legacyEnv: props.legacyEnv,
352
- env: props.env,
353
- })
354
- : undefined;
355
-
356
- const assets = await syncAssets(
357
- accountId,
358
- // When we're using the newer service environments, we wouldn't
359
- // have added the env name on to the script name. However, we must
360
- // include it in the kv namespace name regardless (since there's no
361
- // concept of service environments for kv namespaces yet).
362
- scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
363
- props.assetPaths,
364
- false,
365
- props.dryRun
366
- );
367
-
368
- const bindings: CfWorkerInit["bindings"] = {
369
- kv_namespaces: (config.kv_namespaces || []).concat(
370
- assets.namespace
371
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
372
- : []
373
- ),
374
- vars: config.vars,
375
- wasm_modules: config.wasm_modules,
376
- text_blobs: {
377
- ...config.text_blobs,
378
- ...(assets.manifest &&
379
- format === "service-worker" && {
380
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
381
- }),
382
- },
383
- data_blobs: config.data_blobs,
384
- durable_objects: config.durable_objects,
385
- r2_buckets: config.r2_buckets,
386
- services: config.services,
387
- unsafe: config.unsafe?.bindings,
388
- };
389
-
390
- if (assets.manifest) {
391
- modules.push({
392
- name: "__STATIC_CONTENT_MANIFEST",
393
- content: JSON.stringify(assets.manifest),
394
- type: "text",
395
- });
396
- }
397
-
398
- const worker: CfWorkerInit = {
399
- name: scriptName,
400
- main: {
401
- name: path.basename(resolvedEntryPointPath),
402
- content: content,
403
- type: bundleType,
404
- },
405
- bindings,
406
- migrations,
407
- modules,
408
- compatibility_date: props.compatibilityDate ?? config.compatibility_date,
409
- compatibility_flags:
410
- props.compatibilityFlags ?? config.compatibility_flags,
411
- usage_model: config.usage_model,
412
- };
413
-
414
- const withoutStaticAssets = {
415
- ...bindings,
416
- kv_namespaces: config.kv_namespaces,
417
- text_blobs: config.text_blobs,
418
- };
419
- printBindings(withoutStaticAssets);
420
-
421
- if (!props.dryRun) {
422
- // Upload the script so it has time to propagate.
423
- // We can also now tell whether available_on_subdomain is set
424
- available_on_subdomain = (
425
- await fetchResult<{ available_on_subdomain: boolean }>(
426
- workerUrl,
427
- {
428
- method: "PUT",
429
- body: createWorkerUploadForm(worker),
430
- },
431
- new URLSearchParams({ include_subdomain_availability: "true" })
432
- )
433
- ).available_on_subdomain;
434
- }
435
- } finally {
436
- if (typeof destination !== "string") {
437
- // this means we're using a temp dir,
438
- // so let's clean up before we proceed
439
- await destination.cleanup();
440
- }
441
- }
442
-
443
- if (props.dryRun) {
444
- logger.log(`--dry-run: exiting now.`);
445
- return;
446
- }
447
- assert(accountId, "Missing accountId");
448
-
449
- const uploadMs = Date.now() - start;
450
- const deployments: Promise<string[]>[] = [];
451
-
452
- if (deployToWorkersDev) {
453
- // Deploy to a subdomain of `workers.dev`
454
- const userSubdomain = await getSubdomain(accountId);
455
- const scriptURL =
456
- props.legacyEnv || !props.env
457
- ? `${scriptName}.${userSubdomain}.workers.dev`
458
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
459
- if (!available_on_subdomain) {
460
- // Enable the `workers.dev` subdomain.
461
- deployments.push(
462
- fetchResult(`${workerUrl}/subdomain`, {
463
- method: "POST",
464
- body: JSON.stringify({ enabled: true }),
465
- headers: {
466
- "Content-Type": "application/json",
467
- },
468
- })
469
- .then(() => [scriptURL])
470
- // Add a delay when the subdomain is first created.
471
- // This is to prevent an issue where a negative cache-hit
472
- // causes the subdomain to be unavailable for 30 seconds.
473
- // This is a temporary measure until we fix this on the edge.
474
- .then(async (url) => {
475
- await sleep(3000);
476
- return url;
477
- })
478
- );
479
- } else {
480
- deployments.push(Promise.resolve([scriptURL]));
481
- }
482
- } else {
483
- if (available_on_subdomain) {
484
- // Disable the workers.dev deployment
485
- await fetchResult(`${workerUrl}/subdomain`, {
486
- method: "POST",
487
- body: JSON.stringify({ enabled: false }),
488
- headers: {
489
- "Content-Type": "application/json",
490
- },
491
- });
492
- }
493
- }
494
-
495
- logger.log("Uploaded", workerName, formatTime(uploadMs));
496
-
497
- // Update routing table for the script.
498
- if (routesOnly.length > 0) {
499
- deployments.push(
500
- fetchResult(`${workerUrl}/routes`, {
501
- // Note: PUT will delete previous routes on this script.
502
- method: "PUT",
503
- body: JSON.stringify(
504
- routesOnly.map((route) =>
505
- typeof route !== "object" ? { pattern: route } : route
506
- )
507
- ),
508
- headers: {
509
- "Content-Type": "application/json",
510
- },
511
- }).then(() => {
512
- if (routesOnly.length > 10) {
513
- return routesOnly
514
- .slice(0, 9)
515
- .map((route) => renderRoute(route))
516
- .concat([`...and ${routesOnly.length - 10} more routes`]);
517
- }
518
- return routesOnly.map((route) => renderRoute(route));
519
- })
520
- );
521
- }
522
-
523
- // Update custom domains for the script
524
- if (customDomainsOnly.length > 0) {
525
- deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
526
- }
527
-
528
- // Configure any schedules for the script.
529
- // TODO: rename this to `schedules`?
530
- if (triggers && triggers.length) {
531
- deployments.push(
532
- fetchResult(`${workerUrl}/schedules`, {
533
- // Note: PUT will override previous schedules on this script.
534
- method: "PUT",
535
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
536
- headers: {
537
- "Content-Type": "application/json",
538
- },
539
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
540
- );
541
- }
542
-
543
- const targets = await Promise.all(deployments);
544
- const deployMs = Date.now() - start - uploadMs;
545
-
546
- if (deployments.length > 0) {
547
- logger.log("Published", workerName, formatTime(deployMs));
548
- for (const target of targets.flat()) {
549
- logger.log(" ", target);
550
- }
551
- } else {
552
- logger.log("No publish targets for", workerName, formatTime(deployMs));
553
- }
554
- }
555
-
556
- function formatTime(duration: number) {
557
- return `(${(duration / 1000).toFixed(2)} sec)`;
558
- }
559
-
560
- async function getSubdomain(accountId: string): Promise<string> {
561
- try {
562
- const { subdomain } = await fetchResult(
563
- `/accounts/${accountId}/workers/subdomain`
564
- );
565
- return subdomain;
566
- } catch (e) {
567
- const error = e as { code?: number };
568
- if (typeof error === "object" && !!error && error.code === 10007) {
569
- // 10007 error code: not found
570
- // https://api.cloudflare.com/#worker-subdomain-get-subdomain
571
-
572
- const errorMessage =
573
- "Error: You need to register a workers.dev subdomain before publishing to workers.dev";
574
- const solutionMessage =
575
- "You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
576
- const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
577
-
578
- throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
579
- } else {
580
- throw e;
581
- }
582
- }
583
- }
package/src/r2.ts DELETED
@@ -1,50 +0,0 @@
1
- import { fetchResult } from "./cfetch";
2
-
3
- /**
4
- * Information about a bucket, returned from `listR2Buckets()`.
5
- */
6
- export interface R2BucketInfo {
7
- name: string;
8
- creation_date: string;
9
- }
10
-
11
- /**
12
- * Fetch a list of all the buckets under the given `accountId`.
13
- */
14
- export async function listR2Buckets(
15
- accountId: string
16
- ): Promise<R2BucketInfo[]> {
17
- const results = await fetchResult<{
18
- buckets: R2BucketInfo[];
19
- }>(`/accounts/${accountId}/r2/buckets`);
20
- return results.buckets;
21
- }
22
-
23
- /**
24
- * Create a bucket with the given `bucketName` within the account given by `accountId`.
25
- *
26
- * A 400 is returned if the account already owns a bucket with this name.
27
- * A bucket must be explicitly deleted to be replaced.
28
- */
29
- export async function createR2Bucket(
30
- accountId: string,
31
- bucketName: string
32
- ): Promise<void> {
33
- return await fetchResult<void>(
34
- `/accounts/${accountId}/r2/buckets/${bucketName}`,
35
- { method: "PUT" }
36
- );
37
- }
38
-
39
- /**
40
- * Delete a bucket with the given name
41
- */
42
- export async function deleteR2Bucket(
43
- accountId: string,
44
- bucketName: string
45
- ): Promise<void> {
46
- return await fetchResult<void>(
47
- `/accounts/${accountId}/r2/buckets/${bucketName}`,
48
- { method: "DELETE" }
49
- );
50
- }
@@ -1,29 +0,0 @@
1
- declare module "selfsigned" {
2
- import type { pki } from "node-forge";
3
-
4
- export type Attributes = pki.CertificateField[];
5
-
6
- export interface Options {
7
- days?: number;
8
- keySize?: number;
9
- extensions?: unknown[];
10
- algorithm?: string;
11
- pkcs7?: boolean;
12
- clientCertificate?: boolean;
13
- clientCertificateCN?: string;
14
- }
15
-
16
- export interface Certificate {
17
- private: string;
18
- public: string;
19
- cert: string;
20
- fingerprint: string;
21
- }
22
-
23
- export function generate(attrs?: Attributes, options?: Options): Certificate;
24
- export function generate(
25
- attrs: Attributes,
26
- options: Options,
27
- callback: (err: Error, certificate: Certificate) => void
28
- ): void;
29
- }