wrangler 0.0.0-e1c615f → 0.0.0-e5d3690

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.
@@ -0,0 +1,130 @@
1
+ import React from "react";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { render } from "ink-testing-library";
5
+ import type { UserInfo } from "../whoami";
6
+ import { getUserInfo, WhoAmI } from "../whoami";
7
+ import { runInTempDir } from "./run-in-tmp";
8
+ import { mkdirSync, writeFileSync } from "node:fs";
9
+ import { setMockResponse } from "./mock-cfetch";
10
+ import { initialise } from "../user";
11
+
12
+ const ORIGINAL_CF_API_TOKEN = process.env.CF_API_TOKEN;
13
+ const ORIGINAL_CF_ACCOUNT_ID = process.env.CF_ACCOUNT_ID;
14
+
15
+ describe("getUserInfo()", () => {
16
+ runInTempDir();
17
+
18
+ beforeEach(() => {
19
+ // Clear the environment variables, so we can control them in the tests
20
+ delete process.env.CF_API_TOKEN;
21
+ delete process.env.CF_ACCOUNT_ID;
22
+ // Override where the home directory is so that we can specify a user config
23
+ mkdirSync("./home");
24
+ jest.spyOn(os, "homedir").mockReturnValue("./home");
25
+ });
26
+
27
+ afterEach(() => {
28
+ // Reset any changes to the environment variables
29
+ process.env.CF_API_TOKEN = ORIGINAL_CF_API_TOKEN;
30
+ process.env.CF_ACCOUNT_ID = ORIGINAL_CF_ACCOUNT_ID;
31
+ });
32
+
33
+ it("should return undefined if there is no config file", async () => {
34
+ await initialise();
35
+ const userInfo = await getUserInfo();
36
+ expect(userInfo).toBeUndefined();
37
+ });
38
+
39
+ it("should return undefined if there is an empty config file", async () => {
40
+ writeUserConfig();
41
+ await initialise();
42
+ const userInfo = await getUserInfo();
43
+ expect(userInfo).toBeUndefined();
44
+ });
45
+
46
+ it("should return the user's email and accounts if authenticated via config token", async () => {
47
+ writeUserConfig("some-oauth-token");
48
+ setMockResponse("/user", () => {
49
+ return { email: "user@example.com" };
50
+ });
51
+ setMockResponse("/accounts", () => {
52
+ return [
53
+ { name: "Account One", id: "account-1" },
54
+ { name: "Account Two", id: "account-2" },
55
+ { name: "Account Three", id: "account-3" },
56
+ ];
57
+ });
58
+
59
+ await initialise();
60
+ const userInfo = await getUserInfo();
61
+
62
+ expect(userInfo).toEqual({
63
+ authType: "OAuth",
64
+ apiToken: "some-oauth-token",
65
+ email: "user@example.com",
66
+ accounts: [
67
+ { name: "Account One", id: "account-1" },
68
+ { name: "Account Two", id: "account-2" },
69
+ { name: "Account Three", id: "account-3" },
70
+ ],
71
+ });
72
+ });
73
+ });
74
+
75
+ describe("WhoAmI component", () => {
76
+ it("should return undefined if there is no user", async () => {
77
+ const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
78
+
79
+ expect(lastFrame()).toMatchInlineSnapshot(
80
+ `"You are not authenticated. Please run \`wrangler login\`."`
81
+ );
82
+ });
83
+
84
+ it("should display the user's email and accounts", async () => {
85
+ const user: UserInfo = {
86
+ authType: "OAuth",
87
+ apiToken: "some-oauth-token",
88
+ email: "user@example.com",
89
+ accounts: [
90
+ { name: "Account One", id: "account-1" },
91
+ { name: "Account Two", id: "account-2" },
92
+ { name: "Account Three", id: "account-3" },
93
+ ],
94
+ };
95
+
96
+ const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
97
+
98
+ expect(lastFrame()).toContain(
99
+ "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
100
+ );
101
+ expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
102
+ expect(lastFrame()).toMatch(/Account One .+ account-1/);
103
+ expect(lastFrame()).toMatch(/Account Two .+ account-2/);
104
+ expect(lastFrame()).toMatch(/Account Three .+ account-3/);
105
+ });
106
+ });
107
+
108
+ function writeUserConfig(
109
+ oauth_token?: string,
110
+ refresh_token?: string,
111
+ expiration_time?: string
112
+ ) {
113
+ const lines: string[] = [];
114
+ if (oauth_token) {
115
+ lines.push(`oauth_token = "${oauth_token}"`);
116
+ }
117
+ if (refresh_token) {
118
+ lines.push(`refresh_token = "${refresh_token}"`);
119
+ }
120
+ if (expiration_time) {
121
+ lines.push(`expiration_time = "${expiration_time}"`);
122
+ }
123
+ const configPath = path.join(os.homedir(), ".wrangler/config");
124
+ mkdirSync(configPath, { recursive: true });
125
+ writeFileSync(
126
+ path.join(configPath, "default.toml"),
127
+ lines.join("\n"),
128
+ "utf-8"
129
+ );
130
+ }
@@ -23,7 +23,7 @@ export function toMimeType(type: CfModuleType): string {
23
23
  }
24
24
  }
25
25
 
26
- function toModule(module: CfModule, entryType?: CfModuleType): Blob {
26
+ function toModule(module: CfModule, entryType: CfModuleType): Blob {
27
27
  const { type: moduleType, content } = module;
28
28
  const type = toMimeType(moduleType ?? entryType);
29
29
 
package/src/api/worker.ts CHANGED
@@ -112,7 +112,7 @@ export interface CfWorkerInit {
112
112
  /**
113
113
  * The name of the worker.
114
114
  */
115
- name: string | void;
115
+ name: string | undefined;
116
116
  /**
117
117
  * The entrypoint module.
118
118
  */
@@ -120,7 +120,7 @@ export interface CfWorkerInit {
120
120
  /**
121
121
  * The list of additional modules.
122
122
  */
123
- modules: void | CfModule[];
123
+ modules: undefined | CfModule[];
124
124
  /**
125
125
  * All the bindings
126
126
  */
@@ -130,10 +130,10 @@ export interface CfWorkerInit {
130
130
  vars?: CfVars;
131
131
  services?: CfService[];
132
132
  };
133
- migrations: void | CfDurableObjectMigrations;
134
- compatibility_date: string | void;
135
- compatibility_flags: void | string[];
136
- usage_model: void | "bundled" | "unbound";
133
+ migrations: undefined | CfDurableObjectMigrations;
134
+ compatibility_date: string | undefined;
135
+ compatibility_flags: undefined | string[];
136
+ usage_model: undefined | "bundled" | "unbound";
137
137
  }
138
138
 
139
139
  /**
@@ -94,9 +94,17 @@ function throwFetchError(
94
94
  const errors = response.errors
95
95
  .map((error) => `${error.code}: ${error.message}`)
96
96
  .join("\n");
97
- throw new Error(`Failed to fetch ${resource} - ${errors}`);
97
+ const error = new Error(`Failed to fetch ${resource} - \n${errors}`);
98
+ // add the first error code directly to this error
99
+ // so consumers can use it for specific behaviour
100
+ const code = response.errors[0]?.code;
101
+ if (code) {
102
+ //@ts-expect-error non-standard property on Error
103
+ error.code = code;
104
+ }
105
+ throw error;
98
106
  }
99
107
 
100
108
  function hasCursor(result_info: unknown): result_info is { cursor: string } {
101
- return (result_info as { cursor } | undefined)?.cursor !== undefined;
109
+ return (result_info as { cursor: string } | undefined)?.cursor !== undefined;
102
110
  }
@@ -31,15 +31,21 @@ export async function fetchInternal<ResponseType>(
31
31
  headers,
32
32
  });
33
33
 
34
- if (response.ok) {
35
- return (await response.json()) as ResponseType;
36
- } else {
34
+ const jsonText = await response.text();
35
+ try {
36
+ const json = JSON.parse(jsonText);
37
+ return json as ResponseType;
38
+ } catch (e) {
37
39
  throw new Error(
38
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
40
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText}\nInvalid JSON response:\n${jsonText}`
39
41
  );
40
42
  }
41
43
  }
42
44
 
45
+ function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
46
+ return { ...headers };
47
+ }
48
+
43
49
  async function requireLoggedIn(): Promise<void> {
44
50
  const loggedIn = await loginOrRefreshIfRequired();
45
51
  if (!loggedIn) {
@@ -55,10 +61,6 @@ function requireApiToken(): string {
55
61
  return apiToken;
56
62
  }
57
63
 
58
- function cloneHeaders(headers: HeadersInit): HeadersInit {
59
- return { ...headers };
60
- }
61
-
62
64
  function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
63
65
  if (headers["Authorization"]) {
64
66
  throw new Error(