wrangler 0.0.0-e2f9bb2 → 0.0.0-e322475

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 (103) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +3 -1
  3. package/bin/wrangler.js +36 -4
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +15 -7
  6. package/pages/functions/buildPlugin.ts +13 -0
  7. package/pages/functions/buildWorker.ts +14 -1
  8. package/pages/functions/template-plugin.ts +3 -2
  9. package/src/__tests__/configuration.test.ts +652 -229
  10. package/src/__tests__/dev.test.tsx +372 -79
  11. package/src/__tests__/helpers/mock-cfetch.ts +2 -2
  12. package/src/__tests__/helpers/mock-console.ts +11 -1
  13. package/src/__tests__/helpers/mock-dialogs.ts +75 -11
  14. package/src/__tests__/helpers/mock-process.ts +24 -0
  15. package/src/__tests__/index.test.ts +81 -72
  16. package/src/__tests__/init.test.ts +1360 -410
  17. package/src/__tests__/jest.setup.ts +38 -0
  18. package/src/__tests__/kv.test.ts +218 -152
  19. package/src/__tests__/logger.test.ts +26 -0
  20. package/src/__tests__/package-manager.test.ts +154 -7
  21. package/src/__tests__/pages.test.ts +478 -53
  22. package/src/__tests__/parse.test.ts +8 -0
  23. package/src/__tests__/publish.test.ts +1614 -333
  24. package/src/__tests__/r2.test.ts +55 -36
  25. package/src/__tests__/secret.test.ts +39 -4
  26. package/src/__tests__/user.test.ts +1 -0
  27. package/src/__tests__/whoami.test.tsx +34 -0
  28. package/src/abort.d.ts +3 -0
  29. package/src/bundle-reporter.tsx +29 -0
  30. package/src/bundle.ts +42 -7
  31. package/src/cfetch/index.ts +21 -4
  32. package/src/cfetch/internal.ts +25 -20
  33. package/src/config/config.ts +11 -2
  34. package/src/config/environment.ts +41 -15
  35. package/src/config/index.ts +162 -0
  36. package/src/config/validation-helpers.ts +10 -1
  37. package/src/config/validation.ts +234 -78
  38. package/src/create-worker-preview.ts +32 -22
  39. package/src/create-worker-upload-form.ts +22 -8
  40. package/src/dev/dev.tsx +48 -67
  41. package/src/dev/local.tsx +16 -7
  42. package/src/dev/remote.tsx +57 -21
  43. package/src/dev/use-esbuild.ts +1 -7
  44. package/src/dialogs.tsx +48 -0
  45. package/src/durable.ts +102 -0
  46. package/src/entry.ts +71 -10
  47. package/src/generate-auth-url.ts +33 -0
  48. package/src/generate-random-state.ts +16 -0
  49. package/src/git-client.ts +42 -0
  50. package/src/index.tsx +619 -338
  51. package/src/inspect.ts +39 -0
  52. package/src/kv.ts +116 -27
  53. package/src/logger.ts +8 -1
  54. package/src/open-in-browser.ts +3 -12
  55. package/src/package-manager.ts +50 -3
  56. package/src/pages.tsx +434 -207
  57. package/src/parse.ts +44 -5
  58. package/src/proxy.ts +66 -44
  59. package/src/publish.ts +407 -137
  60. package/src/sites.tsx +103 -28
  61. package/src/user.tsx +35 -26
  62. package/src/whoami.tsx +3 -2
  63. package/src/worker.ts +10 -1
  64. package/src/zones.ts +73 -0
  65. package/templates/new-worker-scheduled.js +17 -0
  66. package/templates/new-worker-scheduled.ts +32 -0
  67. package/templates/new-worker.ts +16 -1
  68. package/templates/no-op-worker.js +10 -0
  69. package/templates/static-asset-facade.js +2 -6
  70. package/wrangler-dist/cli.js +46122 -32396
  71. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  72. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  73. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  74. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  75. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  76. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  77. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  78. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  79. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  80. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  81. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  82. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  83. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  84. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  85. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  86. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  87. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  88. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  89. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  90. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  91. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  92. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  93. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  94. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  95. package/vendor/wrangler-mime/LICENSE +0 -21
  96. package/vendor/wrangler-mime/Mime.js +0 -97
  97. package/vendor/wrangler-mime/README.md +0 -187
  98. package/vendor/wrangler-mime/cli.js +0 -46
  99. package/vendor/wrangler-mime/index.js +0 -4
  100. package/vendor/wrangler-mime/lite.js +0 -4
  101. package/vendor/wrangler-mime/package.json +0 -52
  102. package/vendor/wrangler-mime/types/other.js +0 -1
  103. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/durable.ts ADDED
@@ -0,0 +1,102 @@
1
+ import assert from "node:assert";
2
+ import { fetchResult } from "./cfetch";
3
+ import { logger } from "./logger";
4
+ import type { Config } from "./config";
5
+ import type { CfWorkerInit } from "./worker";
6
+
7
+ /**
8
+ * For a given Worker + migrations config, figure out which migrations
9
+ * to upload based on the current migration tag of the deployed Worker.
10
+ */
11
+ export async function getMigrationsToUpload(
12
+ scriptName: string,
13
+ props: {
14
+ accountId: string | undefined;
15
+ config: Config;
16
+ legacyEnv: boolean | undefined;
17
+ env: string | undefined;
18
+ }
19
+ ): Promise<CfWorkerInit["migrations"]> {
20
+ const { config, accountId } = props;
21
+
22
+ assert(accountId, "Missing accountId");
23
+ // if config.migrations
24
+ let migrations;
25
+ if (config.migrations.length > 0) {
26
+ // get current migration tag
27
+ type ScriptData = { id: string; migration_tag?: string };
28
+ let script: ScriptData | undefined;
29
+ if (!props.legacyEnv) {
30
+ try {
31
+ if (props.env) {
32
+ const scriptData = await fetchResult<{
33
+ script: ScriptData;
34
+ }>(
35
+ `/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
36
+ );
37
+ script = scriptData.script;
38
+ } else {
39
+ const scriptData = await fetchResult<{
40
+ default_environment: {
41
+ script: ScriptData;
42
+ };
43
+ }>(`/accounts/${accountId}/workers/services/${scriptName}`);
44
+ script = scriptData.default_environment.script;
45
+ }
46
+ } catch (err) {
47
+ if (
48
+ ![
49
+ 10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
50
+ 10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
51
+ ].includes((err as { code: number }).code)
52
+ ) {
53
+ throw err;
54
+ }
55
+ // else it's a 404, no script found, and we can proceed
56
+ }
57
+ } else {
58
+ const scripts = await fetchResult<ScriptData[]>(
59
+ `/accounts/${accountId}/workers/scripts`
60
+ );
61
+ script = scripts.find(({ id }) => id === scriptName);
62
+ }
63
+
64
+ if (script?.migration_tag) {
65
+ // was already published once
66
+ const scriptMigrationTag = script.migration_tag;
67
+ const foundIndex = config.migrations.findIndex(
68
+ (migration) => migration.tag === scriptMigrationTag
69
+ );
70
+ if (foundIndex === -1) {
71
+ logger.warn(
72
+ `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
73
+ );
74
+ migrations = {
75
+ old_tag: script.migration_tag,
76
+ new_tag: config.migrations[config.migrations.length - 1].tag,
77
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
78
+ };
79
+ } else {
80
+ if (foundIndex !== config.migrations.length - 1) {
81
+ // there are new migrations to send up
82
+ migrations = {
83
+ old_tag: script.migration_tag,
84
+ new_tag: config.migrations[config.migrations.length - 1].tag,
85
+ steps: config.migrations
86
+ .slice(foundIndex + 1)
87
+ .map(({ tag: _tag, ...rest }) => rest),
88
+ };
89
+ }
90
+ // else, we're up to date, no migrations to send
91
+ }
92
+ } else {
93
+ // first time publishing durable objects to this script,
94
+ // so we send all the migrations
95
+ migrations = {
96
+ new_tag: config.migrations[config.migrations.length - 1].tag,
97
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
98
+ };
99
+ }
100
+ }
101
+ return migrations;
102
+ }
package/src/entry.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import * as esbuild from "esbuild";
5
5
  import { execaCommand } from "execa";
@@ -19,7 +19,11 @@ export type Entry = { file: string; directory: string; format: CfScriptFormat };
19
19
  * Compute the entry-point for the Worker.
20
20
  */
21
21
  export async function getEntry(
22
- args: { script?: string; format?: CfScriptFormat | undefined },
22
+ args: {
23
+ script?: string;
24
+ format?: CfScriptFormat | undefined;
25
+ assets?: string | undefined;
26
+ },
23
27
  config: Config,
24
28
  command: "dev" | "publish"
25
29
  ): Promise<Entry> {
@@ -35,6 +39,8 @@ export async function getEntry(
35
39
  ? path.resolve(config.site?.["entry-point"])
36
40
  : // site.entry-point could be a directory
37
41
  path.resolve(config.site?.["entry-point"], "index.js");
42
+ } else if (args.assets) {
43
+ file = path.resolve(__dirname, "../templates/no-op-worker.js");
38
44
  } else {
39
45
  throw new Error(
40
46
  `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.`
@@ -45,11 +51,16 @@ export async function getEntry(
45
51
  file = path.resolve(directory, config.main);
46
52
  }
47
53
 
48
- await runCustomBuild(file, config.build);
54
+ const relativeFile = path.relative(directory, file) || ".";
55
+ await runCustomBuild(file, relativeFile, config.build);
49
56
 
50
57
  if (fileExists(file) === false) {
51
58
  throw new Error(
52
- `Could not resolve "${path.relative(process.cwd(), file)}".`
59
+ getMissingEntryPointMessage(
60
+ `The entry-point file at "${relativeFile}" was not found.`,
61
+ file,
62
+ relativeFile
63
+ )
53
64
  );
54
65
  }
55
66
  const format = await guessWorkerFormat(
@@ -90,7 +101,8 @@ export async function getEntry(
90
101
  }
91
102
 
92
103
  export async function runCustomBuild(
93
- expectedEntry: string,
104
+ expectedEntryAbsolute: string,
105
+ expectedEntryRelative: string,
94
106
  build: Config["build"]
95
107
  ) {
96
108
  if (build?.command) {
@@ -105,12 +117,14 @@ export async function runCustomBuild(
105
117
  ...(build.cwd && { cwd: build.cwd }),
106
118
  });
107
119
 
108
- if (fileExists(expectedEntry) === false) {
120
+ if (fileExists(expectedEntryAbsolute) === false) {
109
121
  throw new Error(
110
- `Could not resolve "${path.relative(
111
- process.cwd(),
112
- expectedEntry
113
- )}" after running custom build: ${build.command}`
122
+ getMissingEntryPointMessage(
123
+ `The expected output file at "${expectedEntryRelative}" was not found after running custom build: ${build.command}.\n` +
124
+ "The `main` property in wrangler.toml should point to the file generated by the custom build.",
125
+ expectedEntryAbsolute,
126
+ expectedEntryRelative
127
+ )
114
128
  );
115
129
  }
116
130
  }
@@ -265,3 +279,50 @@ function generateAddScriptNameExamples(
265
279
  })
266
280
  .join("\n");
267
281
  }
282
+
283
+ /**
284
+ * Generate an appropriate message for when the entry-point is missing.
285
+ *
286
+ * To be more helpful to developers, we check whether there is a suitable file
287
+ * nearby to the expected file path.
288
+ */
289
+ function getMissingEntryPointMessage(
290
+ message: string,
291
+ absoluteEntryPointPath: string,
292
+ relativeEntryPointPath: string
293
+ ): string {
294
+ if (
295
+ existsSync(absoluteEntryPointPath) &&
296
+ statSync(absoluteEntryPointPath).isDirectory()
297
+ ) {
298
+ // The expected entry-point is a directory, so offer further guidance.
299
+ message += `\nThe provided entry-point path, "${relativeEntryPointPath}", points to a directory, rather than a file.\n`;
300
+
301
+ // Perhaps we can even guess what the correct path should be...
302
+ const possiblePaths: string[] = [];
303
+ for (const basenamePath of [
304
+ "worker",
305
+ "dist/worker",
306
+ "index",
307
+ "dist/index",
308
+ ]) {
309
+ for (const extension of [".ts", ".tsx", ".js", ".jsx"]) {
310
+ const filePath = basenamePath + extension;
311
+ if (fileExists(path.resolve(absoluteEntryPointPath, filePath))) {
312
+ possiblePaths.push(path.join(relativeEntryPointPath, filePath));
313
+ }
314
+ }
315
+ }
316
+
317
+ if (possiblePaths.length > 0) {
318
+ message +=
319
+ `\nDid you mean to set the main field to${
320
+ possiblePaths.length > 1 ? " one of" : ""
321
+ }:\n` +
322
+ "```\n" +
323
+ possiblePaths.map((filePath) => `main = "./${filePath}"\n`).join("") +
324
+ "```";
325
+ }
326
+ }
327
+ return message;
328
+ }
@@ -0,0 +1,33 @@
1
+ interface GenerateAuthUrlProps {
2
+ authUrl: string;
3
+ clientId: string;
4
+ callbackUrl: string;
5
+ scopes: string[];
6
+ stateQueryParam: string;
7
+ codeChallenge: string;
8
+ }
9
+
10
+ /**
11
+ * generateAuthUrl was extracted from getAuthURL in user.tsx
12
+ * to make it possible to mock the generated URL
13
+ */
14
+ export const generateAuthUrl = ({
15
+ authUrl,
16
+ clientId,
17
+ callbackUrl,
18
+ scopes,
19
+ stateQueryParam,
20
+ codeChallenge,
21
+ }: GenerateAuthUrlProps) => {
22
+ return (
23
+ authUrl +
24
+ `?response_type=code&` +
25
+ `client_id=${encodeURIComponent(clientId)}&` +
26
+ `redirect_uri=${encodeURIComponent(callbackUrl)}&` +
27
+ // we add offline_access manually for every request
28
+ `scope=${encodeURIComponent([...scopes, "offline_access"].join(" "))}&` +
29
+ `state=${stateQueryParam}&` +
30
+ `code_challenge=${encodeURIComponent(codeChallenge)}&` +
31
+ `code_challenge_method=S256`
32
+ );
33
+ };
@@ -0,0 +1,16 @@
1
+ import { webcrypto as crypto } from "node:crypto";
2
+ import { PKCE_CHARSET } from "./user";
3
+
4
+ /**
5
+ * Generates random state to be passed for anti-csrf.
6
+ * extracted from user.tsx to make it possible to
7
+ * mock the generated URL
8
+ */
9
+ export function generateRandomState(lengthOfState: number): string {
10
+ const output = new Uint32Array(lengthOfState);
11
+ // @ts-expect-error crypto's types aren't there yet
12
+ crypto.getRandomValues(output);
13
+ return Array.from(output)
14
+ .map((num: number) => PKCE_CHARSET[num % PKCE_CHARSET.length])
15
+ .join("");
16
+ }
@@ -0,0 +1,42 @@
1
+ import { execa } from "execa";
2
+ import { findUp } from "find-up";
3
+
4
+ /**
5
+ * Check whether the given current working directory is within a git repository
6
+ * by looking for a `.git` directory in this or an ancestor directory.
7
+ */
8
+ export async function isInsideGitRepo(cwd: string) {
9
+ const res = await findUp(".git", { cwd, type: "directory" });
10
+ return res !== undefined;
11
+ }
12
+
13
+ /**
14
+ * Check whether git is installed by trying to run it.
15
+ */
16
+ export async function isGitInstalled() {
17
+ try {
18
+ return (await execa("git", ["--version"])).exitCode === 0;
19
+ } catch (err) {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Initialize a new Worker project with a git repository.
26
+ *
27
+ * We want the branch to be called `main` but earlier versions of git do not support `--initial-branch`.
28
+ * If that is the case then we just fallback to the default initial branch name.
29
+ */
30
+ export async function initializeGit(cwd: string) {
31
+ try {
32
+ // Try to create the repository with the HEAD branch of `main`.
33
+ await execa("git", ["init", "--initial-branch", "main"], {
34
+ cwd,
35
+ });
36
+ } catch {
37
+ // Unable to create the repo with a HEAD branch name, so just fall back to the default.
38
+ await execa("git", ["init"], {
39
+ cwd,
40
+ });
41
+ }
42
+ }