wrangler 0.0.0-e0b9366 → 0.0.0-e11e1691

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 (169) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +168 -85
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +167 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +3 -3
  31. package/templates/new-worker.ts +22 -4
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +6 -103
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23937 -0
  48. package/wrangler-dist/cli.js +164016 -134056
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  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/pages/functions/buildWorker.ts +0 -62
  55. package/pages/functions/filepath-routing.test.ts +0 -223
  56. package/pages/functions/filepath-routing.ts +0 -181
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -151
  59. package/pages/functions/template-worker.ts +0 -130
  60. package/src/__tests__/configuration.test.ts +0 -2551
  61. package/src/__tests__/dev.test.tsx +0 -401
  62. package/src/__tests__/dev2.test.tsx +0 -152
  63. package/src/__tests__/guess-worker-format.test.ts +0 -58
  64. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  65. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  66. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  70. package/src/__tests__/helpers/mock-console.ts +0 -70
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  72. package/src/__tests__/helpers/mock-kv.ts +0 -33
  73. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  74. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  75. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  76. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  77. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  78. package/src/__tests__/https-options.test.ts +0 -127
  79. package/src/__tests__/index.test.ts +0 -991
  80. package/src/__tests__/jest.setup.ts +0 -69
  81. package/src/__tests__/kv.test.ts +0 -1382
  82. package/src/__tests__/logout.test.ts +0 -52
  83. package/src/__tests__/package-manager.test.ts +0 -206
  84. package/src/__tests__/pages.test.ts +0 -44
  85. package/src/__tests__/parse.test.ts +0 -322
  86. package/src/__tests__/publish.test.ts +0 -2611
  87. package/src/__tests__/r2.test.ts +0 -198
  88. package/src/__tests__/route.test.ts +0 -45
  89. package/src/__tests__/secret.test.ts +0 -425
  90. package/src/__tests__/sentry.test.ts +0 -146
  91. package/src/__tests__/tail.test.ts +0 -564
  92. package/src/__tests__/whoami.test.tsx +0 -100
  93. package/src/bundle.ts +0 -142
  94. package/src/cfetch/index.ts +0 -104
  95. package/src/cfetch/internal.ts +0 -139
  96. package/src/cli.ts +0 -19
  97. package/src/config/README.md +0 -107
  98. package/src/config/config.ts +0 -279
  99. package/src/config/diagnostics.ts +0 -80
  100. package/src/config/environment.ts +0 -305
  101. package/src/config/index.ts +0 -52
  102. package/src/config/validation-helpers.ts +0 -468
  103. package/src/config/validation.ts +0 -1037
  104. package/src/create-worker-preview.ts +0 -166
  105. package/src/create-worker-upload-form.ts +0 -217
  106. package/src/dev/dev.tsx +0 -357
  107. package/src/dev/local.tsx +0 -241
  108. package/src/dev/remote.tsx +0 -201
  109. package/src/dev/use-esbuild.ts +0 -100
  110. package/src/dialogs.tsx +0 -77
  111. package/src/entry.ts +0 -159
  112. package/src/environment-variables.ts +0 -33
  113. package/src/https-options.ts +0 -122
  114. package/src/index.tsx +0 -2364
  115. package/src/inspect.ts +0 -617
  116. package/src/kv.ts +0 -339
  117. package/src/module-collection.ts +0 -253
  118. package/src/open-in-browser.ts +0 -25
  119. package/src/package-manager.ts +0 -126
  120. package/src/pages.tsx +0 -1045
  121. package/src/parse.ts +0 -183
  122. package/src/paths.ts +0 -26
  123. package/src/proxy.ts +0 -438
  124. package/src/publish.ts +0 -354
  125. package/src/r2.ts +0 -50
  126. package/src/reporting.ts +0 -131
  127. package/src/selfsigned.d.ts +0 -29
  128. package/src/sites.tsx +0 -273
  129. package/src/tail/filters.ts +0 -279
  130. package/src/tail/index.ts +0 -299
  131. package/src/tail/printing.ts +0 -62
  132. package/src/user.tsx +0 -1118
  133. package/src/whoami.tsx +0 -69
  134. package/src/worker.ts +0 -163
  135. package/templates/static-asset-facade.js +0 -47
  136. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  137. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  138. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  139. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  140. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  141. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  142. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  143. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  148. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  150. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  151. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  152. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  153. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  154. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  156. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  157. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  158. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  159. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  160. package/vendor/wrangler-mime/LICENSE +0 -21
  161. package/vendor/wrangler-mime/Mime.js +0 -97
  162. package/vendor/wrangler-mime/README.md +0 -187
  163. package/vendor/wrangler-mime/cli.js +0 -46
  164. package/vendor/wrangler-mime/index.js +0 -4
  165. package/vendor/wrangler-mime/lite.js +0 -4
  166. package/vendor/wrangler-mime/package.json +0 -52
  167. package/vendor/wrangler-mime/types/other.js +0 -1
  168. package/vendor/wrangler-mime/types/standard.js +0 -1
  169. package/wrangler-dist/cli.js.map +0 -7
@@ -1,201 +0,0 @@
1
- import assert from "node:assert";
2
- import { readFile } from "node:fs/promises";
3
- import path from "node:path";
4
- import { useState, useEffect, useRef } from "react";
5
- import { createWorkerPreview } from "../create-worker-preview";
6
- import useInspector from "../inspect";
7
- import { usePreviewServer } from "../proxy";
8
- import { syncAssets } from "../sites";
9
- import type { CfPreviewToken } from "../create-worker-preview";
10
- import type { AssetPaths } from "../sites";
11
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
12
- import type { EsbuildBundle } from "./use-esbuild";
13
-
14
- export function Remote(props: {
15
- name: string | undefined;
16
- bundle: EsbuildBundle | undefined;
17
- format: CfScriptFormat | undefined;
18
- public: undefined | string;
19
- assetPaths: undefined | AssetPaths;
20
- port: number;
21
- localProtocol: "https" | "http";
22
- inspectorPort: number;
23
- accountId: undefined | string;
24
- apiToken: undefined | string;
25
- bindings: CfWorkerInit["bindings"];
26
- compatibilityDate: string | undefined;
27
- compatibilityFlags: undefined | string[];
28
- usageModel: undefined | "bundled" | "unbound";
29
- env: string | undefined;
30
- legacyEnv: boolean | undefined;
31
- zone: { id: string; host: string } | undefined;
32
- }) {
33
- assert(props.accountId, "accountId is required");
34
- assert(props.apiToken, "apiToken is required");
35
- const previewToken = useWorker({
36
- name: props.name,
37
- bundle: props.bundle,
38
- format: props.format,
39
- modules: props.bundle ? props.bundle.modules : [],
40
- accountId: props.accountId,
41
- apiToken: props.apiToken,
42
- bindings: props.bindings,
43
- assetPaths: props.assetPaths,
44
- port: props.port,
45
- compatibilityDate: props.compatibilityDate,
46
- compatibilityFlags: props.compatibilityFlags,
47
- usageModel: props.usageModel,
48
- env: props.env,
49
- legacyEnv: props.legacyEnv,
50
- zone: props.zone,
51
- });
52
-
53
- usePreviewServer({
54
- previewToken,
55
- publicRoot: props.public,
56
- localProtocol: props.localProtocol,
57
- localPort: props.port,
58
- });
59
-
60
- useInspector({
61
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
62
- port: props.inspectorPort,
63
- logToTerminal: true,
64
- });
65
- return null;
66
- }
67
-
68
- export function useWorker(props: {
69
- name: string | undefined;
70
- bundle: EsbuildBundle | undefined;
71
- format: CfScriptFormat | undefined;
72
- modules: CfModule[];
73
- accountId: string;
74
- apiToken: string;
75
- bindings: CfWorkerInit["bindings"];
76
- assetPaths: undefined | AssetPaths;
77
- port: number;
78
- compatibilityDate: string | undefined;
79
- compatibilityFlags: string[] | undefined;
80
- usageModel: undefined | "bundled" | "unbound";
81
- env: string | undefined;
82
- legacyEnv: boolean | undefined;
83
- zone: { id: string; host: string } | undefined;
84
- }): CfPreviewToken | undefined {
85
- const {
86
- name,
87
- bundle,
88
- format,
89
- modules,
90
- accountId,
91
- apiToken,
92
- bindings,
93
- assetPaths,
94
- compatibilityDate,
95
- compatibilityFlags,
96
- usageModel,
97
- port,
98
- } = props;
99
- const [token, setToken] = useState<CfPreviewToken | undefined>();
100
-
101
- // This is the most reliable way to detect whether
102
- // something's "happened" in our system; We make a ref and
103
- // mark it once we log our initial message. Refs are vars!
104
- const startedRef = useRef(false);
105
-
106
- useEffect(() => {
107
- async function start() {
108
- setToken(undefined); // reset token in case we're re-running
109
-
110
- if (!bundle || !format) return;
111
-
112
- if (!startedRef.current) {
113
- startedRef.current = true;
114
- } else {
115
- console.log("⎔ Detected changes, restarted server.");
116
- }
117
-
118
- const assets = await syncAssets(
119
- accountId,
120
- // When we're using the newer service environments, we wouldn't
121
- // have added the env name on to the script name. However, we must
122
- // include it in the kv namespace name regardless (since there's no
123
- // concept of service environments for kv namespaces yet).
124
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
125
- assetPaths,
126
- true
127
- ); // TODO: cancellable?
128
-
129
- const content = await readFile(bundle.path, "utf-8");
130
-
131
- const init: CfWorkerInit = {
132
- name,
133
- main: {
134
- name: path.basename(bundle.path),
135
- type: format === "modules" ? "esm" : "commonjs",
136
- content,
137
- },
138
- modules: modules.concat(
139
- assets.manifest
140
- ? {
141
- name: "__STATIC_CONTENT_MANIFEST",
142
- content: JSON.stringify(assets.manifest),
143
- type: "text",
144
- }
145
- : []
146
- ),
147
- bindings: {
148
- ...bindings,
149
- kv_namespaces: (bindings.kv_namespaces || []).concat(
150
- assets.namespace
151
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
152
- : []
153
- ),
154
- text_blobs: {
155
- ...bindings.text_blobs,
156
- ...(assets.manifest &&
157
- format === "service-worker" && {
158
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
159
- }),
160
- },
161
- },
162
- migrations: undefined, // no migrations in dev
163
- compatibility_date: compatibilityDate,
164
- compatibility_flags: compatibilityFlags,
165
- usage_model: usageModel,
166
- };
167
- setToken(
168
- await createWorkerPreview(
169
- init,
170
- {
171
- accountId,
172
- apiToken,
173
- },
174
- { env: props.env, legacyEnv: props.legacyEnv, zone: props.zone }
175
- )
176
- );
177
- }
178
- start().catch((err) => {
179
- // we want to log the error, but not end the process
180
- // since it could recover after the developer fixes whatever's wrong
181
- console.error("remote worker:", err);
182
- });
183
- }, [
184
- name,
185
- bundle,
186
- format,
187
- accountId,
188
- apiToken,
189
- port,
190
- assetPaths,
191
- compatibilityDate,
192
- compatibilityFlags,
193
- usageModel,
194
- bindings,
195
- modules,
196
- props.env,
197
- props.legacyEnv,
198
- props.zone,
199
- ]);
200
- return token;
201
- }
@@ -1,100 +0,0 @@
1
- import assert from "node:assert";
2
- import { useState, useEffect } from "react";
3
- import { bundleWorker } from "../bundle";
4
- import type { Config } from "../config";
5
- import type { Entry } from "../entry";
6
- import type { CfModule } from "../worker";
7
- import type { WatchMode } from "esbuild";
8
-
9
- export type EsbuildBundle = {
10
- id: number;
11
- path: string;
12
- entry: Entry;
13
- type: "esm" | "commonjs";
14
- modules: CfModule[];
15
- serveAssetsFromWorker: boolean;
16
- };
17
-
18
- export function useEsbuild({
19
- entry,
20
- destination,
21
- staticRoot,
22
- jsxFactory,
23
- jsxFragment,
24
- rules,
25
- serveAssetsFromWorker,
26
- }: {
27
- entry: Entry;
28
- destination: string | undefined;
29
- staticRoot: undefined | string;
30
- jsxFactory: string | undefined;
31
- jsxFragment: string | undefined;
32
- rules: Config["rules"];
33
- serveAssetsFromWorker: boolean;
34
- }): EsbuildBundle | undefined {
35
- const [bundle, setBundle] = useState<EsbuildBundle>();
36
- useEffect(() => {
37
- let stopWatching: (() => void) | undefined = undefined;
38
-
39
- const watchMode: WatchMode = {
40
- async onRebuild(error) {
41
- if (error) console.error("watch build failed:", error);
42
- else {
43
- // nothing really changes here, so let's increment the id
44
- // to change the return object's identity
45
- setBundle((previousBundle) => {
46
- assert(
47
- previousBundle,
48
- "Rebuild triggered with no previous build available"
49
- );
50
- return { ...previousBundle, id: previousBundle.id + 1 };
51
- });
52
- }
53
- },
54
- };
55
-
56
- async function build() {
57
- if (!destination) return;
58
-
59
- const { resolvedEntryPointPath, bundleType, modules, stop } =
60
- await bundleWorker(entry, destination, {
61
- // In dev, we serve assets from the local proxy before we send the request to the worker.
62
- serveAssetsFromWorker: false,
63
- jsxFactory,
64
- jsxFragment,
65
- rules,
66
- watch: watchMode,
67
- });
68
-
69
- // Capture the `stop()` method to use as the `useEffect()` destructor.
70
- stopWatching = stop;
71
-
72
- setBundle({
73
- id: 0,
74
- entry,
75
- path: resolvedEntryPointPath,
76
- type: bundleType,
77
- modules,
78
- serveAssetsFromWorker,
79
- });
80
- }
81
-
82
- build().catch(() => {
83
- // esbuild already logs errors to stderr and we don't want to end the process
84
- // on build errors anyway so this is a no-op error handler
85
- });
86
-
87
- return () => {
88
- stopWatching?.();
89
- };
90
- }, [
91
- entry,
92
- destination,
93
- staticRoot,
94
- jsxFactory,
95
- jsxFragment,
96
- serveAssetsFromWorker,
97
- rules,
98
- ]);
99
- return bundle;
100
- }
package/src/dialogs.tsx DELETED
@@ -1,77 +0,0 @@
1
- import { Box, Text, useInput, render } from "ink";
2
- import TextInput from "ink-text-input";
3
- import * as React from "react";
4
- import { useState } from "react";
5
- type ConfirmProps = {
6
- text: string;
7
- onConfirm: (answer: boolean) => void;
8
- };
9
- function Confirm(props: ConfirmProps) {
10
- useInput((input: string) => {
11
- if (input === "y") {
12
- props.onConfirm(true);
13
- } else if (input === "n") {
14
- props.onConfirm(false);
15
- } else {
16
- console.log("Unrecognised input");
17
- }
18
- });
19
- return (
20
- <Box>
21
- <Text>{props.text} (y/n) </Text>
22
- </Box>
23
- );
24
- }
25
-
26
- export function confirm(text: string): Promise<boolean> {
27
- return new Promise((resolve) => {
28
- const { unmount } = render(
29
- <Confirm
30
- text={text}
31
- onConfirm={(answer: boolean) => {
32
- unmount();
33
- resolve(answer);
34
- }}
35
- />
36
- );
37
- });
38
- }
39
-
40
- type PromptProps = {
41
- text: string;
42
- type?: "text" | "password";
43
- onSubmit: (text: string) => void;
44
- };
45
-
46
- function Prompt(props: PromptProps) {
47
- const [value, setValue] = useState("");
48
-
49
- return (
50
- <Box>
51
- <Text>{props.text} </Text>
52
- <Box>
53
- <TextInput
54
- mask={props.type === "password" ? "*" : undefined}
55
- value={value}
56
- onChange={setValue}
57
- onSubmit={props.onSubmit}
58
- />
59
- </Box>
60
- </Box>
61
- );
62
- }
63
-
64
- export async function prompt(text: string, type: "text" | "password" = "text") {
65
- return new Promise((resolve) => {
66
- const { unmount } = render(
67
- <Prompt
68
- text={text}
69
- type={type}
70
- onSubmit={(inputText) => {
71
- unmount();
72
- resolve(inputText);
73
- }}
74
- />
75
- );
76
- });
77
- }
package/src/entry.ts DELETED
@@ -1,159 +0,0 @@
1
- import assert from "node:assert";
2
- import { existsSync } from "node:fs";
3
- import path from "node:path";
4
- import * as esbuild from "esbuild";
5
- import { execaCommand } from "execa";
6
- import type { Config } from "./config";
7
- import type { CfScriptFormat } from "./worker";
8
- import type { Metafile } from "esbuild";
9
-
10
- /**
11
- * An entry point for the Worker.
12
- *
13
- * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
14
- */
15
- export type Entry = { file: string; directory: string; format: CfScriptFormat };
16
-
17
- /**
18
- * Compute the entry-point for the Worker.
19
- */
20
- export async function getEntry(
21
- args: { script?: string; format?: CfScriptFormat | undefined },
22
- config: Config,
23
- command: string
24
- ): Promise<Entry> {
25
- let file: string;
26
- let directory = process.cwd();
27
- if (args.script) {
28
- // If the script name comes from the command line it is relative to the current working directory.
29
- file = path.resolve(args.script);
30
- } else if (config.main === undefined) {
31
- throw new Error(
32
- `Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command} path/to/script\`) or the \`main\` config field.`
33
- );
34
- } else {
35
- directory = path.resolve(path.dirname(config.configPath ?? "."));
36
- file = path.resolve(directory, config.main);
37
- }
38
-
39
- await runCustomBuild(file, config.build);
40
-
41
- if (fileExists(file) === false) {
42
- throw new Error(
43
- `Could not resolve "${path.relative(process.cwd(), file)}".`
44
- );
45
- }
46
- const format = await guessWorkerFormat(
47
- file,
48
- directory,
49
- args.format ?? config.build?.upload?.format
50
- );
51
- return { file, directory, format };
52
- }
53
-
54
- export async function runCustomBuild(
55
- expectedEntry: string,
56
- build: Config["build"]
57
- ) {
58
- if (build?.command) {
59
- // TODO: add a deprecation message here?
60
- console.log("running:", build.command);
61
- await execaCommand(build.command, {
62
- shell: true,
63
- stdout: "inherit",
64
- stderr: "inherit",
65
- timeout: 1000 * 30,
66
- ...(build.cwd && { cwd: build.cwd }),
67
- });
68
-
69
- if (fileExists(expectedEntry) === false) {
70
- throw new Error(
71
- `Could not resolve "${path.relative(
72
- process.cwd(),
73
- expectedEntry
74
- )}" after running custom build: ${build.command}`
75
- );
76
- }
77
- }
78
- }
79
-
80
- /**
81
- * A function to "guess" the type of worker.
82
- * We do this by running a lightweight build of the actual script,
83
- * and looking at the metafile generated by esbuild. If it has a default
84
- * export (or really, any exports), that means it's a "modules" worker.
85
- * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
86
- * well in practice.
87
- */
88
- export default async function guessWorkerFormat(
89
- entryFile: string,
90
- entryWorkingDirectory: string,
91
- hint: CfScriptFormat | undefined
92
- ): Promise<CfScriptFormat> {
93
- const result = await esbuild.build({
94
- entryPoints: [entryFile],
95
- absWorkingDir: entryWorkingDirectory,
96
- metafile: true,
97
- bundle: false,
98
- format: "esm",
99
- write: false,
100
- });
101
- // result.metafile is defined because of the `metafile: true` option above.
102
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
103
- const metafile = result.metafile!;
104
- const entryPoints = Object.entries(metafile.outputs).filter(
105
- ([_path, output]) => output.entryPoint !== undefined
106
- );
107
- assert(
108
- entryPoints.length > 0,
109
- `Cannot find entry-point "${entryFile}" in generated bundle.` +
110
- listEntryPoints(entryPoints)
111
- );
112
- assert(
113
- entryPoints.length < 2,
114
- "More than one entry-point found for generated bundle." +
115
- listEntryPoints(entryPoints)
116
- );
117
- const guessedWorkerFormat =
118
- entryPoints[0][1].exports.length > 0 ? "modules" : "service-worker";
119
-
120
- if (hint) {
121
- if (hint !== guessedWorkerFormat) {
122
- if (hint === "service-worker") {
123
- throw new Error(
124
- "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have ES module exports. Please pass `--format modules`, or simply remove the configuration."
125
- );
126
- } else {
127
- throw new Error(
128
- "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
129
- );
130
- }
131
- }
132
- }
133
- return guessedWorkerFormat;
134
- }
135
-
136
- function listEntryPoints(
137
- outputs: [string, ValueOf<Metafile["outputs"]>][]
138
- ): string {
139
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
140
- }
141
-
142
- type ValueOf<T> = T[keyof T];
143
-
144
- /**
145
- * Returns true if the given `filePath` exists as-is,
146
- * or if some version of it (by appending a common extension) exists.
147
- */
148
- export function fileExists(filePath: string): boolean {
149
- if (path.extname(filePath) !== "") {
150
- return existsSync(filePath);
151
- }
152
- const base = path.join(path.dirname(filePath), path.basename(filePath));
153
- for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
154
- if (existsSync(base + ext)) {
155
- return true;
156
- }
157
- }
158
- return false;
159
- }
@@ -1,33 +0,0 @@
1
- /**
2
- * Create a function used to access an environment variable.
3
- *
4
- * This is not memoized to allow us to change the value at runtime, such as in testing.
5
- * A warning is shown if the client is using a deprecated version - but only once.
6
- */
7
- export function getEnvironmentVariableFactory({
8
- variableName,
9
- deprecatedName,
10
- defaultValue,
11
- }: {
12
- variableName: string;
13
- deprecatedName?: string;
14
- defaultValue?: string;
15
- }) {
16
- let hasWarned = false;
17
- return () => {
18
- if (process.env[variableName]) {
19
- return process.env[variableName];
20
- } else if (deprecatedName && process.env[deprecatedName]) {
21
- if (!hasWarned) {
22
- // Only show the warning once.
23
- hasWarned = true;
24
- console.warn(
25
- `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
26
- );
27
- }
28
- return process.env[deprecatedName];
29
- } else {
30
- return defaultValue;
31
- }
32
- };
33
- }
@@ -1,122 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { homedir, networkInterfaces } from "node:os";
3
- import * as path from "node:path";
4
- import { promisify } from "node:util";
5
- import type { Attributes, Options } from "selfsigned";
6
-
7
- // Most of this file has been borrowed from the implementation in Miniflare.
8
- // See https://github.com/cloudflare/miniflare/blob/870b401ef5/packages/http-server/src/plugin.ts#L313-L397
9
- // Thanks @mrbbot.
10
- const CERT_EXPIRY_DAYS = 30;
11
- const ONE_DAY_IN_MS = 86400000;
12
-
13
- /**
14
- * Get the options (i.e. SSL certificates) for running an HTTPS server.
15
- *
16
- * The certificates are self-signed and generated locally, and cached in the `CERT_ROOT` directory.
17
- */
18
- export async function getHttpsOptions() {
19
- const certDirectory = path.join(homedir(), ".wrangler/local-cert");
20
- const keyPath = path.join(certDirectory, "key.pem");
21
- const certPath = path.join(certDirectory, "cert.pem");
22
-
23
- const regenerate =
24
- !fs.existsSync(keyPath) ||
25
- !fs.existsSync(certPath) ||
26
- hasCertificateExpired(keyPath, certPath);
27
-
28
- if (regenerate) {
29
- console.log("Generating new self-signed certificate...");
30
- const { key, cert } = await generateCertificate();
31
- try {
32
- // Write certificate files so we can reuse them later.
33
- fs.mkdirSync(certDirectory, { recursive: true });
34
- fs.writeFileSync(keyPath, key, "utf8");
35
- fs.writeFileSync(certPath, cert, "utf8");
36
- } catch (e) {
37
- const message = e instanceof Error ? e.message : `${e}`;
38
- console.warn(
39
- `Unable to cache generated self-signed certificate in ${certDirectory}.\n${message}`
40
- );
41
- }
42
- return { key, cert };
43
- } else {
44
- return {
45
- key: fs.readFileSync(keyPath, "utf8"),
46
- cert: fs.readFileSync(certPath, "utf8"),
47
- };
48
- }
49
- }
50
-
51
- /**
52
- * Determine if the certificate defined in `keyPath` and `certPath` files
53
- * have expired based on the date when they were last modified.
54
- */
55
- function hasCertificateExpired(keyPath: string, certPath: string): boolean {
56
- const keyStat = fs.statSync(keyPath);
57
- const certStat = fs.statSync(certPath);
58
- const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
59
- return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
60
- }
61
-
62
- /**
63
- * Generate a new self-signed certificate and cache it in `CERT_ROOT` directory.
64
- */
65
- async function generateCertificate() {
66
- // `selfsigned` imports `node-forge`, which is a pretty big library.
67
- // To reduce startup time, only load this dynamically when needed.
68
- // eslint-disable-next-line @typescript-eslint/consistent-type-imports
69
- const generate: typeof import("selfsigned").generate = promisify(
70
- // eslint-disable-next-line @typescript-eslint/no-var-requires
71
- require("selfsigned").generate
72
- );
73
-
74
- const certAttrs: Attributes = [{ name: "commonName", value: "localhost" }];
75
-
76
- const certOptions: Options = {
77
- algorithm: "sha256",
78
- days: CERT_EXPIRY_DAYS,
79
- keySize: 2048,
80
- extensions: [
81
- { name: "basicConstraints", cA: true },
82
- {
83
- name: "keyUsage",
84
- keyCertSign: true,
85
- digitalSignature: true,
86
- nonRepudiation: true,
87
- keyEncipherment: true,
88
- dataEncipherment: true,
89
- },
90
- {
91
- name: "extKeyUsage",
92
- serverAuth: true,
93
- clientAuth: true,
94
- codeSigning: true,
95
- timeStamping: true,
96
- },
97
- {
98
- name: "subjectAltName",
99
- altNames: [
100
- { type: 2, value: "localhost" },
101
- ...getAccessibleHosts().map((ip) => ({ type: 7, ip })),
102
- ],
103
- },
104
- ],
105
- };
106
-
107
- const { private: key, cert } = await generate(certAttrs, certOptions);
108
- return { key, cert };
109
- }
110
-
111
- /**
112
- * Ask the OS for the addresses of locally accessible hosts.
113
- */
114
- function getAccessibleHosts(ipv4 = false): string[] {
115
- const hosts: string[] = [];
116
- Object.values(networkInterfaces()).forEach((net) =>
117
- net?.forEach(({ family, address }) => {
118
- if (!ipv4 || family === "IPv4") hosts.push(address);
119
- })
120
- );
121
- return hosts;
122
- }