wrangler 0.0.0-e22f9d7 → 0.0.0-e2b7352
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 +33 -16
- package/pages/functions/buildWorker.ts +1 -1
- package/pages/functions/filepath-routing.test.ts +212 -28
- package/pages/functions/filepath-routing.ts +91 -131
- package/pages/functions/routes.ts +11 -18
- package/pages/functions/template-worker.ts +19 -33
- package/src/__tests__/configuration.test.ts +2820 -0
- package/src/__tests__/dev.test.tsx +535 -61
- package/src/__tests__/guess-worker-format.test.ts +68 -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__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +52 -16
- package/src/__tests__/helpers/mock-console.ts +70 -0
- package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
- package/src/__tests__/helpers/mock-kv.ts +33 -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 +773 -77
- package/src/__tests__/jest.setup.ts +53 -6
- package/src/__tests__/kv.test.ts +725 -456
- package/src/__tests__/logout.test.ts +52 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +82 -0
- package/src/__tests__/parse.test.ts +322 -0
- package/src/__tests__/publish.test.ts +3509 -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__/whoami.test.tsx +100 -0
- package/src/bundle.ts +155 -0
- package/src/cfetch/index.ts +21 -19
- package/src/cfetch/internal.ts +92 -22
- package/src/cli.ts +10 -0
- package/src/config/README.md +107 -0
- package/src/config/config.ts +218 -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 +554 -0
- package/src/config/validation.ts +1232 -0
- package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
- package/src/create-worker-upload-form.ts +217 -0
- package/src/dev/dev.tsx +392 -0
- package/src/dev/local.tsx +232 -0
- package/src/dev/remote.tsx +203 -0
- package/src/dev/use-esbuild.ts +104 -0
- package/src/dialogs.tsx +2 -2
- package/src/entry.ts +240 -0
- package/src/environment-variables.ts +33 -0
- package/src/https-options.ts +122 -0
- package/src/index.tsx +1218 -803
- package/src/inspect.ts +103 -25
- package/src/intl-polyfill.d.ts +139 -0
- package/src/{kv.tsx → kv.ts} +104 -61
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +37 -0
- package/src/module-collection.ts +229 -35
- package/src/open-in-browser.ts +25 -0
- package/src/package-manager.ts +126 -0
- package/src/pages.tsx +74 -44
- package/src/parse.ts +183 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +177 -39
- package/src/publish.ts +286 -300
- package/src/r2.ts +50 -0
- package/src/reporting.ts +131 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +224 -62
- 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 +278 -178
- package/src/whoami.tsx +69 -0
- package/src/{api/worker.ts → worker.ts} +45 -37
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +130377 -112126
- package/wrangler-dist/cli.js.map +3 -3
- package/src/__tests__/run-in-tmp.ts +0 -19
- package/src/__tests__/run-wrangler.ts +0 -32
- package/src/api/form_data.ts +0 -131
- package/src/config.ts +0 -487
- package/src/dev.tsx +0 -784
- package/src/tail.tsx +0 -73
|
@@ -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
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { URLSearchParams } from "node:url";
|
|
1
|
+
import { URL, URLSearchParams } from "node:url";
|
|
3
2
|
import { pathToRegexp } from "path-to-regexp";
|
|
4
|
-
import {
|
|
5
|
-
import type { FetchResult } from "
|
|
3
|
+
import { getCloudflareApiBaseUrl } from "../../cfetch";
|
|
4
|
+
import type { FetchResult, FetchError } from "../../cfetch";
|
|
5
|
+
import type { RequestInit } from "undici";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* The signature of the function that will handle a mock request.
|
|
@@ -11,7 +11,7 @@ export type MockHandler<ResponseType> = (
|
|
|
11
11
|
uri: RegExpExecArray,
|
|
12
12
|
init: RequestInit,
|
|
13
13
|
queryParams: URLSearchParams
|
|
14
|
-
) => ResponseType
|
|
14
|
+
) => ResponseType | Promise<ResponseType>;
|
|
15
15
|
|
|
16
16
|
type RemoveMockFn = () => void;
|
|
17
17
|
|
|
@@ -35,16 +35,18 @@ export async function mockFetchInternal(
|
|
|
35
35
|
queryParams: URLSearchParams = new URLSearchParams()
|
|
36
36
|
) {
|
|
37
37
|
for (const { regexp, method, handler } of mocks) {
|
|
38
|
-
const resourcePath = new URL(resource,
|
|
38
|
+
const resourcePath = new URL(resource, getCloudflareApiBaseUrl()).pathname;
|
|
39
39
|
const uri = regexp.exec(resourcePath);
|
|
40
40
|
// Do the resource path and (if specified) the HTTP method match?
|
|
41
|
-
if (uri !== null && (!method || method === init.method)) {
|
|
41
|
+
if (uri !== null && (!method || method === (init.method ?? "GET"))) {
|
|
42
42
|
// The `resource` regular expression will extract the labelled groups from the URL.
|
|
43
43
|
// These are passed through to the `handler` call, to allow it to do additional checks or behaviour.
|
|
44
|
-
return handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
|
|
44
|
+
return await handler(uri, init, queryParams); // TODO: should we have some kind of fallthrough system? we'll see.
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
throw new Error(
|
|
47
|
+
throw new Error(
|
|
48
|
+
`no mocks found for ${init.method ?? "any HTTP"} request to ${resource}`
|
|
49
|
+
);
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
/**
|
|
@@ -138,23 +140,23 @@ export function setMockResponse<ResponseType>(
|
|
|
138
140
|
/**
|
|
139
141
|
* A helper to make it easier to create `FetchResult` objects in tests.
|
|
140
142
|
*/
|
|
141
|
-
export function createFetchResult<ResponseType>(
|
|
142
|
-
result: ResponseType
|
|
143
|
+
export async function createFetchResult<ResponseType>(
|
|
144
|
+
result: ResponseType | Promise<ResponseType>,
|
|
143
145
|
success = true,
|
|
144
|
-
errors = [],
|
|
145
|
-
messages = [],
|
|
146
|
+
errors: FetchError[] = [],
|
|
147
|
+
messages: string[] = [],
|
|
146
148
|
result_info?: unknown
|
|
147
|
-
): FetchResult<ResponseType
|
|
149
|
+
): Promise<FetchResult<ResponseType>> {
|
|
148
150
|
return result_info
|
|
149
151
|
? {
|
|
150
|
-
result,
|
|
152
|
+
result: await result,
|
|
151
153
|
success,
|
|
152
154
|
errors,
|
|
153
155
|
messages,
|
|
154
156
|
result_info,
|
|
155
157
|
}
|
|
156
158
|
: {
|
|
157
|
-
result,
|
|
159
|
+
result: await result,
|
|
158
160
|
success,
|
|
159
161
|
errors,
|
|
160
162
|
messages,
|
|
@@ -169,3 +171,37 @@ export function createFetchResult<ResponseType>(
|
|
|
169
171
|
export function unsetAllMocks() {
|
|
170
172
|
mocks.length = 0;
|
|
171
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,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,103 @@
|
|
|
1
|
+
const ORIGINAL_STDIN = process.stdin;
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Mock process.stdin so that we can pipe in text for non-interactive mode tests.
|
|
5
|
+
*/
|
|
6
|
+
export function useMockStdin({ isTTY }: { isTTY: boolean }) {
|
|
7
|
+
const mockStdin = new MockStdIn(isTTY);
|
|
8
|
+
|
|
9
|
+
beforeEach(() => {
|
|
10
|
+
mockStdin.reset();
|
|
11
|
+
Object.defineProperty(process, "stdin", {
|
|
12
|
+
value: mockStdin,
|
|
13
|
+
configurable: true,
|
|
14
|
+
writable: false,
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
Object.defineProperty(process, "stdin", {
|
|
20
|
+
value: ORIGINAL_STDIN,
|
|
21
|
+
configurable: true,
|
|
22
|
+
writable: false,
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
return mockStdin;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const failCallback: (value: unknown) => void = () => {
|
|
30
|
+
throw new Error(
|
|
31
|
+
"TEST FAILURE: stdin callback called before being initialized."
|
|
32
|
+
);
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A mock version of `process.std`, which can be used to simulate piping data
|
|
37
|
+
* into the wrangler process in non-interactive mode.
|
|
38
|
+
*/
|
|
39
|
+
class MockStdIn {
|
|
40
|
+
private endCallback = failCallback;
|
|
41
|
+
private errorCallback = failCallback;
|
|
42
|
+
private chunks: string[] = [];
|
|
43
|
+
private error: Error | undefined;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Set this to true if you want the stdin stream to error.
|
|
47
|
+
*/
|
|
48
|
+
throwError(error: Error) {
|
|
49
|
+
this.error = error;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Call this to clean out the chunks that are queued for sending.
|
|
54
|
+
*/
|
|
55
|
+
reset() {
|
|
56
|
+
this.chunks.length = 0;
|
|
57
|
+
this.error = undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Queue up some chunks to be sent.
|
|
62
|
+
*/
|
|
63
|
+
send(...chunks: string[]) {
|
|
64
|
+
this.chunks.push(...chunks);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
/**
|
|
69
|
+
* Used by wrangler to check whether stdin is interactive.
|
|
70
|
+
*/
|
|
71
|
+
readonly isTTY: boolean
|
|
72
|
+
) {}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Used by wrangler to add event listeners.
|
|
76
|
+
*/
|
|
77
|
+
on(eventName: string, callback: () => void) {
|
|
78
|
+
switch (eventName) {
|
|
79
|
+
case "readable":
|
|
80
|
+
setImmediate(callback);
|
|
81
|
+
break;
|
|
82
|
+
case "end":
|
|
83
|
+
this.endCallback = callback;
|
|
84
|
+
break;
|
|
85
|
+
case "error":
|
|
86
|
+
this.errorCallback = callback;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Used by wrangler to get the next chunk of data in the stream.
|
|
93
|
+
*/
|
|
94
|
+
read() {
|
|
95
|
+
if (this.error) {
|
|
96
|
+
setImmediate(() => this.errorCallback(this.error));
|
|
97
|
+
}
|
|
98
|
+
if (this.chunks.length === 0) {
|
|
99
|
+
setImmediate(this.endCallback);
|
|
100
|
+
}
|
|
101
|
+
return this.chunks.shift() ?? null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { WebSocket } from "mock-socket";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A version of the mock WebSocket that supports the methods that we use.
|
|
5
|
+
*/
|
|
6
|
+
export class MockWebSocket extends WebSocket {
|
|
7
|
+
on(event: string | symbol, listener: (...args: unknown[]) => void): this {
|
|
8
|
+
switch (event) {
|
|
9
|
+
case "message":
|
|
10
|
+
this.onmessage = ({ data }) => {
|
|
11
|
+
listener(data);
|
|
12
|
+
};
|
|
13
|
+
break;
|
|
14
|
+
case "open":
|
|
15
|
+
this.onopen = listener;
|
|
16
|
+
break;
|
|
17
|
+
case "close":
|
|
18
|
+
this.onclose = listener;
|
|
19
|
+
break;
|
|
20
|
+
default:
|
|
21
|
+
throw new Error("Unknown event type: " + event.toString());
|
|
22
|
+
}
|
|
23
|
+
return this;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
terminate() {
|
|
27
|
+
this.close();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { reinitialiseAuthTokens } from "../../user";
|
|
5
|
+
|
|
6
|
+
const originalCwd = process.cwd();
|
|
7
|
+
|
|
8
|
+
export function runInTempDir({ homedir }: { homedir?: string } = {}) {
|
|
9
|
+
let tmpDir: string;
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
|
|
13
|
+
process.chdir(tmpDir);
|
|
14
|
+
if (homedir !== undefined) {
|
|
15
|
+
// Override where the home directory is so that we can write our own user config,
|
|
16
|
+
// without destroying the real thing.
|
|
17
|
+
fs.mkdirSync(homedir);
|
|
18
|
+
// Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
|
|
19
|
+
// rather than an alias to the module (e.g. `import * as os from "node:os";`).
|
|
20
|
+
// This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
|
|
21
|
+
// getter that is not configurable (and so cannot be spied upon).
|
|
22
|
+
jest.spyOn(os, "homedir").mockReturnValue(homedir);
|
|
23
|
+
// Now that we have changed the home directory location, we must reinitialize the user auth state
|
|
24
|
+
reinitialiseAuthTokens();
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
afterEach(() => {
|
|
29
|
+
process.chdir(originalCwd);
|
|
30
|
+
fs.rmSync(tmpDir, { recursive: true });
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { main } from "../../index";
|
|
2
|
+
import { normalizeSlashes, stripTimings } from "./mock-console";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A helper to 'run' wrangler commands for tests.
|
|
6
|
+
*/
|
|
7
|
+
export async function runWrangler(cmd?: string) {
|
|
8
|
+
try {
|
|
9
|
+
await main(cmd?.split(" ") ?? []);
|
|
10
|
+
} catch (err) {
|
|
11
|
+
if (err instanceof Error) {
|
|
12
|
+
err.message = normalizeSlashes(stripTimings(err.message));
|
|
13
|
+
}
|
|
14
|
+
throw err;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import TOML from "@iarna/toml";
|
|
3
|
+
import type { RawConfig } from "../../config";
|
|
4
|
+
|
|
5
|
+
/** Write a mock wrangler.toml file to disk. */
|
|
6
|
+
export default function writeWranglerToml(config: RawConfig = {}) {
|
|
7
|
+
fs.writeFileSync(
|
|
8
|
+
"./wrangler.toml",
|
|
9
|
+
TOML.stringify({
|
|
10
|
+
compatibility_date: "2022-01-12",
|
|
11
|
+
name: "test-name",
|
|
12
|
+
...(config as TOML.JsonMap),
|
|
13
|
+
}),
|
|
14
|
+
|
|
15
|
+
"utf-8"
|
|
16
|
+
);
|
|
17
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { getHttpsOptions } from "../https-options";
|
|
5
|
+
import { mockConsoleMethods } from "./helpers/mock-console";
|
|
6
|
+
import { runInTempDir } from "./helpers/run-in-tmp";
|
|
7
|
+
|
|
8
|
+
describe("getHttpsOptions()", () => {
|
|
9
|
+
runInTempDir({ homedir: "./home" });
|
|
10
|
+
const std = mockConsoleMethods();
|
|
11
|
+
|
|
12
|
+
it("should use cached values if they have not expired", async () => {
|
|
13
|
+
fs.mkdirSync(resolve(os.homedir(), ".wrangler/local-cert"), {
|
|
14
|
+
recursive: true,
|
|
15
|
+
});
|
|
16
|
+
fs.writeFileSync(
|
|
17
|
+
resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
|
|
18
|
+
"PRIVATE KEY"
|
|
19
|
+
);
|
|
20
|
+
fs.writeFileSync(
|
|
21
|
+
resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
|
|
22
|
+
"PUBLIC KEY"
|
|
23
|
+
);
|
|
24
|
+
const result = await getHttpsOptions();
|
|
25
|
+
expect(result.key).toEqual("PRIVATE KEY");
|
|
26
|
+
expect(result.cert).toEqual("PUBLIC KEY");
|
|
27
|
+
expect(std.out).toMatchInlineSnapshot(`""`);
|
|
28
|
+
expect(std.warn).toMatchInlineSnapshot(`""`);
|
|
29
|
+
expect(std.err).toMatchInlineSnapshot(`""`);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("should generate and cache new keys if none are cached", async () => {
|
|
33
|
+
const result = await getHttpsOptions();
|
|
34
|
+
const key = fs.readFileSync(
|
|
35
|
+
resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
|
|
36
|
+
"utf8"
|
|
37
|
+
);
|
|
38
|
+
const cert = fs.readFileSync(
|
|
39
|
+
resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
|
|
40
|
+
"utf8"
|
|
41
|
+
);
|
|
42
|
+
expect(result.key).toEqual(key);
|
|
43
|
+
expect(result.cert).toEqual(cert);
|
|
44
|
+
expect(std.out).toMatchInlineSnapshot(
|
|
45
|
+
`"Generating new self-signed certificate..."`
|
|
46
|
+
);
|
|
47
|
+
expect(std.warn).toMatchInlineSnapshot(`""`);
|
|
48
|
+
expect(std.err).toMatchInlineSnapshot(`""`);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("should generate and cache new keys if cached files have expired", async () => {
|
|
52
|
+
fs.mkdirSync(resolve(os.homedir(), ".wrangler/local-cert"), {
|
|
53
|
+
recursive: true,
|
|
54
|
+
});
|
|
55
|
+
const ORIGINAL_KEY = "EXPIRED PRIVATE KEY";
|
|
56
|
+
const ORIGINAL_CERT = "EXPIRED PUBLIC KEY";
|
|
57
|
+
fs.writeFileSync(
|
|
58
|
+
resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
|
|
59
|
+
ORIGINAL_KEY
|
|
60
|
+
);
|
|
61
|
+
fs.writeFileSync(
|
|
62
|
+
resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
|
|
63
|
+
ORIGINAL_CERT
|
|
64
|
+
);
|
|
65
|
+
mockStatSync(/\.pem$/, { mtimeMs: new Date(2000).valueOf() });
|
|
66
|
+
|
|
67
|
+
const result = await getHttpsOptions();
|
|
68
|
+
const key = fs.readFileSync(
|
|
69
|
+
resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
|
|
70
|
+
"utf8"
|
|
71
|
+
);
|
|
72
|
+
const cert = fs.readFileSync(
|
|
73
|
+
resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
|
|
74
|
+
"utf8"
|
|
75
|
+
);
|
|
76
|
+
expect(key).not.toEqual(ORIGINAL_KEY);
|
|
77
|
+
expect(cert).not.toEqual(ORIGINAL_CERT);
|
|
78
|
+
expect(result.key).toEqual(key);
|
|
79
|
+
expect(result.cert).toEqual(cert);
|
|
80
|
+
expect(std.out).toMatchInlineSnapshot(
|
|
81
|
+
`"Generating new self-signed certificate..."`
|
|
82
|
+
);
|
|
83
|
+
expect(std.warn).toMatchInlineSnapshot(`""`);
|
|
84
|
+
expect(std.err).toMatchInlineSnapshot(`""`);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("should warn if not able to write to the cache", async () => {
|
|
88
|
+
mockWriteFileSyncThrow(/\.pem$/);
|
|
89
|
+
await getHttpsOptions();
|
|
90
|
+
expect(
|
|
91
|
+
fs.existsSync(resolve(os.homedir(), ".wrangler/local-cert/key.pem"))
|
|
92
|
+
).toBe(false);
|
|
93
|
+
expect(
|
|
94
|
+
fs.existsSync(resolve(os.homedir(), ".wrangler/local-cert/cert.pem"))
|
|
95
|
+
).toBe(false);
|
|
96
|
+
expect(std.out).toMatchInlineSnapshot(
|
|
97
|
+
`"Generating new self-signed certificate..."`
|
|
98
|
+
);
|
|
99
|
+
expect(std.warn).toMatchInlineSnapshot(`
|
|
100
|
+
"Unable to cache generated self-signed certificate in home/.wrangler/local-cert.
|
|
101
|
+
ERROR: Cannot write file"
|
|
102
|
+
`);
|
|
103
|
+
expect(std.err).toMatchInlineSnapshot(`""`);
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
function mockStatSync(matcher: RegExp, stats: Partial<fs.Stats>) {
|
|
108
|
+
const originalStatSync = jest.requireActual("node:fs").statSync;
|
|
109
|
+
jest.spyOn(fs, "statSync").mockImplementation((statPath, options) => {
|
|
110
|
+
return matcher.test(statPath.toString())
|
|
111
|
+
? (stats as fs.Stats)
|
|
112
|
+
: originalStatSync(statPath, options);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function mockWriteFileSyncThrow(matcher: RegExp) {
|
|
117
|
+
const originalWriteFileSync = jest.requireActual("node:fs").writeFileSync;
|
|
118
|
+
jest
|
|
119
|
+
.spyOn(fs, "writeFileSync")
|
|
120
|
+
.mockImplementation((filePath, data, options) => {
|
|
121
|
+
if (matcher.test(filePath.toString())) {
|
|
122
|
+
throw new Error("ERROR: Cannot write file");
|
|
123
|
+
} else {
|
|
124
|
+
return originalWriteFileSync(filePath, data, options);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|