wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef
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.
- package/README.md +3 -3
- package/bin/wrangler.js +12 -3
- package/miniflare-dist/index.mjs +79 -0
- package/miniflare-dist/index.mjs.map +7 -0
- package/package.json +49 -22
- package/pages/functions/buildWorker.ts +62 -0
- package/pages/functions/filepath-routing.test.ts +223 -0
- package/pages/functions/filepath-routing.ts +181 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +151 -0
- package/pages/functions/template-worker.ts +130 -0
- package/src/__tests__/configuration.test.ts +2874 -0
- package/src/__tests__/dev.test.tsx +588 -0
- package/src/__tests__/guess-worker-format.test.ts +83 -0
- package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +48 -0
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/helpers/mock-cfetch.ts +207 -0
- package/src/__tests__/helpers/mock-console.ts +70 -0
- package/src/__tests__/helpers/mock-dialogs.ts +65 -0
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +32 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +127 -0
- package/src/__tests__/index.test.ts +953 -119
- package/src/__tests__/jest.setup.ts +74 -0
- package/src/__tests__/kv.test.ts +1380 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +180 -0
- package/src/__tests__/parse.test.ts +322 -0
- package/src/__tests__/publish.test.ts +3946 -0
- package/src/__tests__/r2.test.ts +198 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +425 -0
- package/src/__tests__/sentry.test.ts +146 -0
- package/src/__tests__/tail.test.ts +638 -0
- package/src/__tests__/user.test.ts +83 -0
- package/src/__tests__/whoami.test.tsx +95 -0
- package/src/bundle.ts +155 -0
- package/src/cfetch/index.ts +104 -0
- package/src/cfetch/internal.ts +139 -0
- package/src/cli.ts +18 -7
- package/src/config/README.md +107 -0
- package/src/config/config.ts +229 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +371 -0
- package/src/config/index.ts +62 -0
- package/src/config/validation-helpers.ts +557 -0
- package/src/config/validation.ts +1240 -0
- package/src/create-worker-preview.ts +173 -0
- package/src/create-worker-upload-form.ts +240 -0
- package/src/dev/dev.tsx +413 -0
- package/src/dev/local.tsx +287 -0
- package/src/dev/remote.tsx +209 -0
- package/src/dev/use-esbuild.ts +109 -0
- package/src/dialogs.tsx +6 -14
- package/src/entry.ts +256 -0
- package/src/environment-variables.ts +33 -0
- package/src/errors.ts +11 -0
- package/src/https-options.ts +122 -0
- package/src/index.tsx +1503 -959
- package/src/inspect.ts +624 -0
- package/src/intl-polyfill.d.ts +139 -0
- package/src/kv.ts +319 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +38 -0
- package/src/module-collection.ts +257 -0
- package/src/open-in-browser.ts +25 -0
- package/src/package-manager.ts +126 -0
- package/src/pages.tsx +1074 -212
- package/src/parse.ts +183 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +455 -0
- package/src/publish.ts +326 -295
- package/src/r2.ts +50 -0
- package/src/reporting.ts +131 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +224 -59
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +62 -0
- package/src/user.tsx +340 -203
- package/src/whoami.tsx +69 -0
- package/src/worker.ts +172 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +136988 -131174
- package/wrangler-dist/cli.js.map +3 -3
- package/src/__tests__/fixtures/init/.gitkeep +0 -0
- package/src/__tests__/mock-cfetch.js +0 -46
- package/src/api/form_data.ts +0 -158
- package/src/api/inspect.ts +0 -441
- package/src/api/preview.ts +0 -123
- package/src/api/worker.ts +0 -161
- package/src/cfetch.ts +0 -72
- package/src/config.ts +0 -124
- package/src/dev.tsx +0 -736
- package/src/kv.tsx +0 -211
- package/src/tail.tsx +0 -71
- package/src/util/fetch.ts +0 -74
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { reinitialiseAuthTokens } from "../../user";
|
|
2
|
+
|
|
3
|
+
const ORIGINAL_CLOUDFLARE_API_TOKEN = process.env.CLOUDFLARE_API_TOKEN;
|
|
4
|
+
const ORIGINAL_CLOUDFLARE_ACCOUNT_ID = process.env.CLOUDFLARE_ACCOUNT_ID;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Mock the API token so that we don't need to read it from user configuration files.
|
|
8
|
+
*
|
|
9
|
+
* Note that you can remove any API token from the environment by setting the value to `null`.
|
|
10
|
+
* This is useful if a higher `describe()` block has already called `mockApiToken()`.
|
|
11
|
+
*/
|
|
12
|
+
export function mockApiToken({
|
|
13
|
+
apiToken = "some-api-token",
|
|
14
|
+
}: { apiToken?: string | null } = {}) {
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
if (apiToken === null) {
|
|
17
|
+
delete process.env.CLOUDFLARE_API_TOKEN;
|
|
18
|
+
} else {
|
|
19
|
+
process.env.CLOUDFLARE_API_TOKEN = apiToken;
|
|
20
|
+
}
|
|
21
|
+
// Now we have updated the environment, we must reinitialize the user auth state.
|
|
22
|
+
reinitialiseAuthTokens();
|
|
23
|
+
});
|
|
24
|
+
afterEach(() => {
|
|
25
|
+
process.env.CLOUDFLARE_API_TOKEN = ORIGINAL_CLOUDFLARE_API_TOKEN;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Mock the current account ID so that we don't need to read it from configuration files.
|
|
31
|
+
*
|
|
32
|
+
* Note that you can remove any account ID from the environment by setting the value to `null`.
|
|
33
|
+
* This is useful if a higher `describe()` block has already called `mockAccountId()`.
|
|
34
|
+
*/
|
|
35
|
+
export function mockAccountId({
|
|
36
|
+
accountId = "some-account-id",
|
|
37
|
+
}: { accountId?: string | null } = {}) {
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
if (accountId === null) {
|
|
40
|
+
delete process.env.CLOUDFLARE_ACCOUNT_ID;
|
|
41
|
+
} else {
|
|
42
|
+
process.env.CLOUDFLARE_ACCOUNT_ID = accountId;
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
afterEach(() => {
|
|
46
|
+
process.env.CLOUDFLARE_ACCOUNT_ID = ORIGINAL_CLOUDFLARE_ACCOUNT_ID;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, resolve } from "node:path";
|
|
3
|
+
import cmdShim from "cmd-shim";
|
|
4
|
+
|
|
5
|
+
const nodeShebang = "#!/usr/bin/env node";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Create a binary file in a temp directory and make it available on the PATH.
|
|
9
|
+
*/
|
|
10
|
+
export async function mockBinary(
|
|
11
|
+
binaryName: string,
|
|
12
|
+
code: string
|
|
13
|
+
): Promise<() => void> {
|
|
14
|
+
// Ensure there is a directory to put the mock binary in.
|
|
15
|
+
const tmpDir = resolve(mkdtempSync(".mock-binary-"));
|
|
16
|
+
|
|
17
|
+
// Use a fake extension on Windows because we will create a cmd-shim to run the binary.
|
|
18
|
+
const extension = process.platform === "win32" ? ".x-mock-bin" : "";
|
|
19
|
+
const filePath = resolve(tmpDir, `${binaryName}${extension}`);
|
|
20
|
+
writeFileSync(filePath, nodeShebang + "\n" + code);
|
|
21
|
+
chmodSync(filePath, 0o777);
|
|
22
|
+
|
|
23
|
+
if (process.platform === "win32") {
|
|
24
|
+
await cmdShim(filePath, basename(filePath, ".x-mock-bin"));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Update PATH using the appropriate separator for the platform.
|
|
28
|
+
const oldPath = process.env.PATH;
|
|
29
|
+
const sep = process.platform === "win32" ? ";" : ":";
|
|
30
|
+
process.env.PATH = tmpDir + sep + oldPath;
|
|
31
|
+
|
|
32
|
+
return function unMock() {
|
|
33
|
+
rmSync(tmpDir, { recursive: true });
|
|
34
|
+
process.env.PATH = process.env.PATH?.replace(tmpDir + sep, "");
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { URL, URLSearchParams } from "node:url";
|
|
2
|
+
import { pathToRegexp } from "path-to-regexp";
|
|
3
|
+
import { getCloudflareApiBaseUrl } from "../../cfetch";
|
|
4
|
+
import type { FetchResult, FetchError } from "../../cfetch";
|
|
5
|
+
import type { RequestInit } from "undici";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The signature of the function that will handle a mock request.
|
|
9
|
+
*/
|
|
10
|
+
export type MockHandler<ResponseType> = (
|
|
11
|
+
uri: RegExpExecArray,
|
|
12
|
+
init: RequestInit,
|
|
13
|
+
queryParams: URLSearchParams
|
|
14
|
+
) => ResponseType | Promise<ResponseType>;
|
|
15
|
+
|
|
16
|
+
type RemoveMockFn = () => void;
|
|
17
|
+
|
|
18
|
+
interface MockFetch<ResponseType> {
|
|
19
|
+
regexp: RegExp;
|
|
20
|
+
method: string | undefined;
|
|
21
|
+
handler: MockHandler<ResponseType>;
|
|
22
|
+
}
|
|
23
|
+
const mocks: MockFetch<unknown>[] = [];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The mock implementation of `cfApi.fetch()`.
|
|
27
|
+
*
|
|
28
|
+
* This function will attempt to match the given request to one of the mock handlers configured by calls to `setMock`.
|
|
29
|
+
*
|
|
30
|
+
* Once found the handler will be used to generate a mock response.
|
|
31
|
+
*/
|
|
32
|
+
export async function mockFetchInternal(
|
|
33
|
+
resource: string,
|
|
34
|
+
init: RequestInit = {},
|
|
35
|
+
queryParams: URLSearchParams = new URLSearchParams()
|
|
36
|
+
) {
|
|
37
|
+
for (const { regexp, method, handler } of mocks) {
|
|
38
|
+
const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
|
|
39
|
+
const uri = regexp.exec(resourcePath);
|
|
40
|
+
// Do the resource path and (if specified) the HTTP method match?
|
|
41
|
+
if (uri !== null && (!method || method === (init.method ?? "GET"))) {
|
|
42
|
+
// The `resource` regular expression will extract the labelled groups from the URL.
|
|
43
|
+
// These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
|
|
44
|
+
return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw new Error(
|
|
48
|
+
`no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Specify an expected resource path that is to be handled, resulting in a raw JSON response.
|
|
54
|
+
*
|
|
55
|
+
* @param resource The path of the resource to be matched.
|
|
56
|
+
* This can include wildcards whose value will be passed to the `handler`.
|
|
57
|
+
* @param handler The function that will generate the mock response for this request.
|
|
58
|
+
*/
|
|
59
|
+
export function setMockRawResponse<ResponseType>(
|
|
60
|
+
resource: string,
|
|
61
|
+
handler: MockHandler<ResponseType>
|
|
62
|
+
): RemoveMockFn;
|
|
63
|
+
/**
|
|
64
|
+
* Specify an expected resource path that is to be handled, resulting in a raw JSON response.
|
|
65
|
+
*
|
|
66
|
+
* @param resource The path of the resource to be matched.
|
|
67
|
+
* This can include wildcards whose value will be passed to the `handler`.
|
|
68
|
+
* @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
|
|
69
|
+
* @param handler The function that will generate the mock response for this request.
|
|
70
|
+
*/
|
|
71
|
+
export function setMockRawResponse<ResponseType>(
|
|
72
|
+
resource: string,
|
|
73
|
+
method: string,
|
|
74
|
+
handler: MockHandler<ResponseType>
|
|
75
|
+
): RemoveMockFn;
|
|
76
|
+
/**
|
|
77
|
+
* Specify an expected resource path that is to be handled, resulting in a raw JSON response.
|
|
78
|
+
*/
|
|
79
|
+
export function setMockRawResponse<ResponseType>(
|
|
80
|
+
resource: string,
|
|
81
|
+
...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
|
|
82
|
+
): RemoveMockFn {
|
|
83
|
+
const handler = args.pop() as MockHandler<ResponseType>;
|
|
84
|
+
const method = args.pop() as string;
|
|
85
|
+
const mock = {
|
|
86
|
+
resource,
|
|
87
|
+
method,
|
|
88
|
+
handler,
|
|
89
|
+
regexp: pathToRegexp(resource),
|
|
90
|
+
};
|
|
91
|
+
mocks.push(mock);
|
|
92
|
+
return () => {
|
|
93
|
+
const mockIndex = mocks.indexOf(mock);
|
|
94
|
+
if (mockIndex !== -1) {
|
|
95
|
+
mocks.splice(mockIndex, 1);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Specify an expected resource path that is to be handled, resulting in a `FetchRequest`.
|
|
102
|
+
*
|
|
103
|
+
* The mock `handler` should return the `result`, which will then be wrapped in a `FetchRequest` object.
|
|
104
|
+
*
|
|
105
|
+
* @param resource The path of the resource to be matched.
|
|
106
|
+
* This can include wildcards whose value will be passed to the `handler`.
|
|
107
|
+
* @param handler The function that will generate the mock response for this request.
|
|
108
|
+
*/
|
|
109
|
+
export function setMockResponse<ResponseType>(
|
|
110
|
+
resource: string,
|
|
111
|
+
handler: MockHandler<ResponseType>
|
|
112
|
+
): RemoveMockFn;
|
|
113
|
+
/**
|
|
114
|
+
* Specify an expected resource path that is to be handled, resulting in a FetchRequest..
|
|
115
|
+
*
|
|
116
|
+
* @param resource The path of the resource to be matched.
|
|
117
|
+
* This can include wildcards whose value will be passed to the `handler`.
|
|
118
|
+
* @param method The HTTP method (e.g. GET, POST, etc) that the request must have to match this mock handler.
|
|
119
|
+
* @param handler The function that will generate the mock response for this request.
|
|
120
|
+
*/
|
|
121
|
+
export function setMockResponse<ResponseType>(
|
|
122
|
+
resource: string,
|
|
123
|
+
method: string,
|
|
124
|
+
handler: MockHandler<ResponseType>
|
|
125
|
+
): RemoveMockFn;
|
|
126
|
+
/**
|
|
127
|
+
* Specify an expected resource path that is to be handled, resulting in a FetchRequest.
|
|
128
|
+
*/
|
|
129
|
+
export function setMockResponse<ResponseType>(
|
|
130
|
+
resource: string,
|
|
131
|
+
...args: [string, MockHandler<ResponseType>] | [MockHandler<ResponseType>]
|
|
132
|
+
): RemoveMockFn {
|
|
133
|
+
const handler = args.pop() as MockHandler<ResponseType>;
|
|
134
|
+
const method = args.pop() as string;
|
|
135
|
+
return setMockRawResponse(resource, method, (...handlerArgs) =>
|
|
136
|
+
createFetchResult(handler(...handlerArgs))
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* A helper to make it easier to create `FetchResult` objects in tests.
|
|
142
|
+
*/
|
|
143
|
+
export async function createFetchResult<ResponseType>(
|
|
144
|
+
result: ResponseType | Promise<ResponseType>,
|
|
145
|
+
success = true,
|
|
146
|
+
errors: FetchError[] = [],
|
|
147
|
+
messages: string[] = [],
|
|
148
|
+
result_info?: unknown
|
|
149
|
+
): Promise<FetchResult<ResponseType>> {
|
|
150
|
+
return result_info
|
|
151
|
+
? {
|
|
152
|
+
result: await result,
|
|
153
|
+
success,
|
|
154
|
+
errors,
|
|
155
|
+
messages,
|
|
156
|
+
result_info,
|
|
157
|
+
}
|
|
158
|
+
: {
|
|
159
|
+
result: await result,
|
|
160
|
+
success,
|
|
161
|
+
errors,
|
|
162
|
+
messages,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Remove all the configured mock handlers.
|
|
168
|
+
*
|
|
169
|
+
* This should be called in an `afterEach()` block to ensure that mock handlers do not leak between tests.
|
|
170
|
+
*/
|
|
171
|
+
export function unsetAllMocks() {
|
|
172
|
+
mocks.length = 0;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* We special-case fetching the request for `kv:key get`, because it's
|
|
177
|
+
* the only cloudflare API endpoint that returns a plain string as the
|
|
178
|
+
* value, and not as the "standard" FetchResult-style json. Hence, we also
|
|
179
|
+
* special-case mocking it here.
|
|
180
|
+
*/
|
|
181
|
+
|
|
182
|
+
const kvGetMocks = new Map<string, string>();
|
|
183
|
+
|
|
184
|
+
export function mockFetchKVGetValue(
|
|
185
|
+
accountId: string,
|
|
186
|
+
namespaceId: string,
|
|
187
|
+
key: string
|
|
188
|
+
) {
|
|
189
|
+
const mapKey = `${accountId}/${namespaceId}/${key}`;
|
|
190
|
+
if (kvGetMocks.has(mapKey)) {
|
|
191
|
+
return kvGetMocks.get(mapKey);
|
|
192
|
+
}
|
|
193
|
+
throw new Error(`no mock value found for \`kv:key get\` - ${mapKey}`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function setMockFetchKVGetValue(
|
|
197
|
+
accountId: string,
|
|
198
|
+
namespaceId: string,
|
|
199
|
+
key: string,
|
|
200
|
+
value: string
|
|
201
|
+
) {
|
|
202
|
+
kvGetMocks.set(`${accountId}/${namespaceId}/${key}`, value);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function unsetMockFetchKVGetValues() {
|
|
206
|
+
kvGetMocks.clear();
|
|
207
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import * as util from "node:util";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* We use this module to mock console methods, and optionally
|
|
5
|
+
* assert on the values they're called with in our tests.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
let logSpy: jest.SpyInstance,
|
|
9
|
+
errorSpy: jest.SpyInstance,
|
|
10
|
+
warnSpy: jest.SpyInstance;
|
|
11
|
+
|
|
12
|
+
const std = {
|
|
13
|
+
get out() {
|
|
14
|
+
return normalizeOutput(logSpy);
|
|
15
|
+
},
|
|
16
|
+
get err() {
|
|
17
|
+
return normalizeOutput(errorSpy);
|
|
18
|
+
},
|
|
19
|
+
get warn() {
|
|
20
|
+
return normalizeOutput(warnSpy);
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function normalizeOutput(spy: jest.SpyInstance): string {
|
|
25
|
+
return stripTrailingWhitespace(
|
|
26
|
+
normalizeSlashes(stripTimings(captureCalls(spy)))
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function captureCalls(spy: jest.SpyInstance): string {
|
|
31
|
+
return spy.mock.calls
|
|
32
|
+
.map((args: unknown[]) => util.format("%s", ...args))
|
|
33
|
+
.join("\n");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function mockConsoleMethods() {
|
|
37
|
+
beforeEach(() => {
|
|
38
|
+
logSpy = jest.spyOn(console, "log").mockImplementation();
|
|
39
|
+
errorSpy = jest.spyOn(console, "error").mockImplementation();
|
|
40
|
+
warnSpy = jest.spyOn(console, "warn").mockImplementation();
|
|
41
|
+
});
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
logSpy.mockRestore();
|
|
44
|
+
errorSpy.mockRestore();
|
|
45
|
+
warnSpy.mockRestore();
|
|
46
|
+
});
|
|
47
|
+
return std;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Ensure slashes in the `str` are OS file-system agnostic.
|
|
52
|
+
*
|
|
53
|
+
* Use this in snapshot tests to be resilient to file-system differences.
|
|
54
|
+
*/
|
|
55
|
+
export function normalizeSlashes(str: string): string {
|
|
56
|
+
return str.replace(/\\/g, "/");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Strip "timing data" out of the `stdout` string, since this is not always deterministic.
|
|
61
|
+
*
|
|
62
|
+
* Use this in snapshot tests to be resilient to slight changes in timing of processing.
|
|
63
|
+
*/
|
|
64
|
+
export function stripTimings(stdout: string): string {
|
|
65
|
+
return stdout.replace(/\(\d+\.\d+ sec\)/g, "(TIMINGS)");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function stripTrailingWhitespace(str: string): string {
|
|
69
|
+
return str.replace(/[^\S\n]+\n/g, "\n");
|
|
70
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { confirm, prompt } from "../../dialogs";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The expected values for a confirmation request.
|
|
5
|
+
*/
|
|
6
|
+
export interface ConfirmExpectation {
|
|
7
|
+
/** The text expected to be seen in the confirmation dialog. */
|
|
8
|
+
text: string;
|
|
9
|
+
/** The mock response send back from the confirmation dialog. */
|
|
10
|
+
result: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Mock the implementation of `confirm()` that will respond with configured results
|
|
15
|
+
* for configured confirmation text messages.
|
|
16
|
+
*
|
|
17
|
+
* If there is a call to `confirm()` that does not match any of the expectations
|
|
18
|
+
* then an error is thrown.
|
|
19
|
+
*/
|
|
20
|
+
export function mockConfirm(...expectations: ConfirmExpectation[]) {
|
|
21
|
+
(confirm as jest.Mock).mockImplementation((text: string) => {
|
|
22
|
+
for (const { text: expectedText, result } of expectations) {
|
|
23
|
+
if (text === expectedText) {
|
|
24
|
+
return Promise.resolve(result);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
throw new Error(`Unexpected confirmation message: ${text}`);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The expected values for a prompt request.
|
|
33
|
+
*/
|
|
34
|
+
export interface PromptExpectation {
|
|
35
|
+
/** The text expected to be seen in the prompt dialog. */
|
|
36
|
+
text: string;
|
|
37
|
+
/** The type of the prompt. */
|
|
38
|
+
type: "text" | "password";
|
|
39
|
+
/** The mock response send back from the prompt dialog. */
|
|
40
|
+
result: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Mock the implementation of `prompt()` that will respond with configured results
|
|
45
|
+
* for configured prompt text messages.
|
|
46
|
+
*
|
|
47
|
+
* If there is a call to `prompt()` that does not match any of the expectations
|
|
48
|
+
* then an error is thrown.
|
|
49
|
+
*/
|
|
50
|
+
export function mockPrompt(...expectations: PromptExpectation[]) {
|
|
51
|
+
(prompt as jest.Mock).mockImplementation(
|
|
52
|
+
(text: string, type: "text" | "password") => {
|
|
53
|
+
for (const {
|
|
54
|
+
text: expectedText,
|
|
55
|
+
type: expectedType,
|
|
56
|
+
result,
|
|
57
|
+
} of expectations) {
|
|
58
|
+
if (text === expectedText && type == expectedType) {
|
|
59
|
+
return Promise.resolve(result);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`Unexpected confirmation message: ${text}`);
|
|
63
|
+
}
|
|
64
|
+
);
|
|
65
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
|
|
2
|
+
import type { NamespaceKeyInfo } from "../../kv";
|
|
3
|
+
|
|
4
|
+
export function mockKeyListRequest(
|
|
5
|
+
expectedNamespaceId: string,
|
|
6
|
+
expectedKeys: NamespaceKeyInfo[],
|
|
7
|
+
keysPerRequest = 1000,
|
|
8
|
+
blankCursorValue: "" | undefined | null = undefined
|
|
9
|
+
) {
|
|
10
|
+
const requests = { count: 0 };
|
|
11
|
+
// See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
|
|
12
|
+
|
|
13
|
+
setMockRawResponse(
|
|
14
|
+
"/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
|
|
15
|
+
"GET",
|
|
16
|
+
([_url, accountId, namespaceId], _init, query) => {
|
|
17
|
+
requests.count++;
|
|
18
|
+
expect(accountId).toEqual("some-account-id");
|
|
19
|
+
expect(namespaceId).toEqual(expectedNamespaceId);
|
|
20
|
+
if (expectedKeys.length <= keysPerRequest) {
|
|
21
|
+
return createFetchResult(expectedKeys);
|
|
22
|
+
} else {
|
|
23
|
+
const start = parseInt(query.get("cursor") ?? "0") || 0;
|
|
24
|
+
const end = start + keysPerRequest;
|
|
25
|
+
const cursor = end < expectedKeys.length ? end : blankCursorValue;
|
|
26
|
+
return createFetchResult(expectedKeys.slice(start, end), true, [], [], {
|
|
27
|
+
cursor,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
);
|
|
32
|
+
return requests;
|
|
33
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { ChildProcess } from "child_process";
|
|
2
|
+
import fetchMock from "jest-fetch-mock";
|
|
3
|
+
import { Request } from "undici";
|
|
4
|
+
const { fetch } = jest.requireActual("undici") as {
|
|
5
|
+
fetch: (input: string) => Promise<unknown>;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// the response to send when wrangler wants an oauth grant
|
|
9
|
+
let oauthGrantResponse: GrantResponseOptions | "timeout" = {};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A mock implementation for `openInBrowser` that sends an oauth grant response
|
|
13
|
+
* to wrangler. Use it like this:
|
|
14
|
+
*
|
|
15
|
+
* ```js
|
|
16
|
+
* jest.mock("../open-in-browser");
|
|
17
|
+
* (openInBrowser as jest.Mock).mockImplementation(mockOpenInBrowser);
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export const mockOpenInBrowser = async (url: string, ..._args: unknown[]) => {
|
|
21
|
+
const { searchParams } = new URL(url);
|
|
22
|
+
if (oauthGrantResponse === "timeout") {
|
|
23
|
+
throw "unimplemented";
|
|
24
|
+
} else {
|
|
25
|
+
const queryParams = toQueryParams(oauthGrantResponse, searchParams);
|
|
26
|
+
// don't await this -- it will block the rest of the login flow
|
|
27
|
+
fetch(`${searchParams.get("redirect_uri")}?${queryParams}`).catch((e) => {
|
|
28
|
+
throw new Error(
|
|
29
|
+
"Failed to send OAuth Grant to wrangler, maybe the server was closed?",
|
|
30
|
+
e as Error
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
return new ChildProcess();
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Functions to help with mocking various parts of the OAuth Flow
|
|
39
|
+
*/
|
|
40
|
+
export const mockOAuthFlow = () => {
|
|
41
|
+
afterEach(() => {
|
|
42
|
+
fetchMock.resetMocks();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const mockGrantAuthorization = ({
|
|
46
|
+
respondWith,
|
|
47
|
+
}: {
|
|
48
|
+
respondWith: "timeout" | "success" | "failure" | GrantResponseOptions;
|
|
49
|
+
}) => {
|
|
50
|
+
if (respondWith === "failure") {
|
|
51
|
+
oauthGrantResponse = {
|
|
52
|
+
error: "access_denied",
|
|
53
|
+
};
|
|
54
|
+
} else if (respondWith === "success") {
|
|
55
|
+
oauthGrantResponse = {
|
|
56
|
+
code: "test-oauth-code",
|
|
57
|
+
};
|
|
58
|
+
} else if (respondWith === "timeout") {
|
|
59
|
+
oauthGrantResponse = "timeout";
|
|
60
|
+
} else {
|
|
61
|
+
oauthGrantResponse = respondWith;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const mockRevokeAuthorization = () => {
|
|
66
|
+
const outcome = {
|
|
67
|
+
actual: new Request("https://example.org"),
|
|
68
|
+
expected: new Request("https://dash.cloudflare.com/oauth2/revoke", {
|
|
69
|
+
method: "POST",
|
|
70
|
+
}),
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
fetchMock.mockIf(outcome.expected.url, async (req) => {
|
|
74
|
+
outcome.actual = req;
|
|
75
|
+
return "";
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return outcome;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const mockGrantAccessToken = ({
|
|
82
|
+
respondWith,
|
|
83
|
+
}: {
|
|
84
|
+
respondWith: MockTokenResponse;
|
|
85
|
+
}) => {
|
|
86
|
+
const outcome = {
|
|
87
|
+
actual: new Request("https://example.org"),
|
|
88
|
+
expected: new Request("https://dash.cloudflare.com/oauth2/token", {
|
|
89
|
+
method: "POST",
|
|
90
|
+
}),
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
fetchMock.mockOnceIf(outcome.expected.url, async (req) => {
|
|
94
|
+
outcome.actual = req;
|
|
95
|
+
return makeTokenResponse(respondWith);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
return outcome;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
mockGrantAuthorization,
|
|
103
|
+
mockRevokeAuthorization,
|
|
104
|
+
mockGrantAccessToken,
|
|
105
|
+
};
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
type GrantResponseOptions = {
|
|
109
|
+
code?: string;
|
|
110
|
+
error?: ErrorType | ErrorType[];
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const toQueryParams = (
|
|
114
|
+
{ code, error }: GrantResponseOptions,
|
|
115
|
+
wranglerRequestParams: URLSearchParams
|
|
116
|
+
): string => {
|
|
117
|
+
const queryParams = [];
|
|
118
|
+
if (code) {
|
|
119
|
+
queryParams.push(`code=${code}`);
|
|
120
|
+
}
|
|
121
|
+
if (error) {
|
|
122
|
+
const stringifiedErr = Array.isArray(error) ? error.join(",") : error;
|
|
123
|
+
queryParams.push(`error=${stringifiedErr}`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
queryParams.push(`state=${wranglerRequestParams.get("state")}`);
|
|
127
|
+
|
|
128
|
+
return queryParams.join("&");
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
type ErrorType =
|
|
132
|
+
| "invalid_request"
|
|
133
|
+
| "invalid_grant"
|
|
134
|
+
| "unauthorized_client"
|
|
135
|
+
| "access_denied"
|
|
136
|
+
| "unsupported_response_type"
|
|
137
|
+
| "invalid_scope"
|
|
138
|
+
| "server_error"
|
|
139
|
+
| "temporarily_unavailable"
|
|
140
|
+
| "invalid_client"
|
|
141
|
+
| "unsupported_grant_type"
|
|
142
|
+
| "invalid_json"
|
|
143
|
+
| "invalid_token"
|
|
144
|
+
| "test-token-grant-error";
|
|
145
|
+
|
|
146
|
+
type MockTokenResponse =
|
|
147
|
+
| "ok"
|
|
148
|
+
| "error"
|
|
149
|
+
| {
|
|
150
|
+
access_token: string;
|
|
151
|
+
expires_in: number;
|
|
152
|
+
refresh_token: string;
|
|
153
|
+
scope: string;
|
|
154
|
+
}
|
|
155
|
+
| {
|
|
156
|
+
error: ErrorType;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const makeTokenResponse = (partialResponse: MockTokenResponse): string => {
|
|
160
|
+
let fullResponse: MockTokenResponse;
|
|
161
|
+
|
|
162
|
+
if (partialResponse === "ok") {
|
|
163
|
+
fullResponse = {
|
|
164
|
+
access_token: "test-access-token",
|
|
165
|
+
expires_in: 100000,
|
|
166
|
+
refresh_token: "test-refresh-token",
|
|
167
|
+
scope: "account:read",
|
|
168
|
+
};
|
|
169
|
+
} else if (partialResponse === "error") {
|
|
170
|
+
fullResponse = {
|
|
171
|
+
error: "test-token-grant-error",
|
|
172
|
+
};
|
|
173
|
+
} else {
|
|
174
|
+
fullResponse = partialResponse;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return JSON.stringify(fullResponse);
|
|
178
|
+
};
|