wrangler 0.0.0-e2a26a0 → 0.0.0-e3a458e

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 (84) hide show
  1. package/package.json +24 -11
  2. package/pages/functions/filepath-routing.test.ts +212 -36
  3. package/pages/functions/filepath-routing.ts +69 -119
  4. package/pages/functions/routes.ts +8 -17
  5. package/pages/functions/template-worker.ts +3 -9
  6. package/src/__tests__/configuration.test.ts +2598 -0
  7. package/src/__tests__/dev.test.tsx +437 -63
  8. package/src/__tests__/dev2.test.tsx +154 -0
  9. package/src/__tests__/guess-worker-format.test.ts +58 -0
  10. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  11. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  12. package/src/__tests__/helpers/mock-bin.ts +4 -1
  13. package/src/__tests__/helpers/mock-cfetch.ts +5 -5
  14. package/src/__tests__/helpers/mock-console.ts +21 -7
  15. package/src/__tests__/helpers/mock-kv.ts +9 -16
  16. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  17. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  18. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  19. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  20. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  21. package/src/__tests__/https-options.test.ts +127 -0
  22. package/src/__tests__/index.test.ts +468 -20
  23. package/src/__tests__/jest.setup.ts +37 -5
  24. package/src/__tests__/kv.test.ts +426 -183
  25. package/src/__tests__/logout.test.ts +15 -13
  26. package/src/__tests__/package-manager.test.ts +2 -2
  27. package/src/__tests__/pages.test.ts +44 -0
  28. package/src/__tests__/parse.test.ts +322 -0
  29. package/src/__tests__/publish.test.ts +1733 -344
  30. package/src/__tests__/r2.test.ts +198 -0
  31. package/src/__tests__/route.test.ts +45 -0
  32. package/src/__tests__/secret.test.ts +301 -86
  33. package/src/__tests__/sentry.test.ts +146 -0
  34. package/src/__tests__/tail.test.ts +564 -0
  35. package/src/__tests__/whoami.test.tsx +21 -7
  36. package/src/bundle.ts +142 -0
  37. package/src/cfetch/index.ts +8 -6
  38. package/src/cfetch/internal.ts +60 -22
  39. package/src/cli.ts +10 -0
  40. package/src/config/README.md +107 -0
  41. package/src/config/config.ts +279 -0
  42. package/src/config/diagnostics.ts +80 -0
  43. package/src/config/environment.ts +305 -0
  44. package/src/config/index.ts +52 -0
  45. package/src/config/validation-helpers.ts +468 -0
  46. package/src/config/validation.ts +1057 -0
  47. package/src/{api/preview.ts → create-worker-preview.ts} +59 -21
  48. package/src/create-worker-upload-form.ts +217 -0
  49. package/src/dev/dev.tsx +362 -0
  50. package/src/dev/local.tsx +247 -0
  51. package/src/dev/remote.tsx +203 -0
  52. package/src/dev/use-esbuild.ts +100 -0
  53. package/src/entry.ts +159 -0
  54. package/src/environment-variables.ts +33 -0
  55. package/src/https-options.ts +122 -0
  56. package/src/index.tsx +1030 -766
  57. package/src/inspect.ts +25 -4
  58. package/src/{kv.tsx → kv.ts} +110 -55
  59. package/src/module-collection.ts +212 -22
  60. package/src/open-in-browser.ts +25 -0
  61. package/src/package-manager.ts +21 -15
  62. package/src/pages.tsx +10 -11
  63. package/src/parse.ts +183 -0
  64. package/src/proxy.ts +115 -45
  65. package/src/publish.ts +273 -329
  66. package/src/r2.ts +50 -0
  67. package/src/reporting.ts +131 -0
  68. package/src/selfsigned.d.ts +29 -0
  69. package/src/sites.tsx +66 -33
  70. package/src/tail/filters.ts +279 -0
  71. package/src/tail/index.ts +299 -0
  72. package/src/tail/printing.ts +62 -0
  73. package/src/user.tsx +223 -124
  74. package/src/{api/worker.ts → worker.ts} +44 -36
  75. package/templates/new-worker.js +1 -1
  76. package/templates/new-worker.ts +1 -1
  77. package/templates/tsconfig.json +105 -0
  78. package/wrangler-dist/cli.js +129900 -113128
  79. package/wrangler-dist/cli.js.map +3 -3
  80. package/src/__tests__/helpers/mock-user.ts +0 -27
  81. package/src/api/form_data.ts +0 -134
  82. package/src/config.ts +0 -641
  83. package/src/dev.tsx +0 -834
  84. package/src/tail.tsx +0 -73
package/src/r2.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { fetchResult } from "./cfetch";
2
+
3
+ /**
4
+ * Information about a bucket, returned from `listR2Buckets()`.
5
+ */
6
+ export interface R2BucketInfo {
7
+ name: string;
8
+ creation_date: string;
9
+ }
10
+
11
+ /**
12
+ * Fetch a list of all the buckets under the given `accountId`.
13
+ */
14
+ export async function listR2Buckets(
15
+ accountId: string
16
+ ): Promise<R2BucketInfo[]> {
17
+ const results = await fetchResult<{
18
+ buckets: R2BucketInfo[];
19
+ }>(`/accounts/${accountId}/r2/buckets`);
20
+ return results.buckets;
21
+ }
22
+
23
+ /**
24
+ * Create a bucket with the given `bucketName` within the account given by `accountId`.
25
+ *
26
+ * A 400 is returned if the account already owns a bucket with this name.
27
+ * A bucket must be explicitly deleted to be replaced.
28
+ */
29
+ export async function createR2Bucket(
30
+ accountId: string,
31
+ bucketName: string
32
+ ): Promise<void> {
33
+ return await fetchResult<void>(
34
+ `/accounts/${accountId}/r2/buckets/${bucketName}`,
35
+ { method: "PUT" }
36
+ );
37
+ }
38
+
39
+ /**
40
+ * Delete a bucket with the given name
41
+ */
42
+ export async function deleteR2Bucket(
43
+ accountId: string,
44
+ bucketName: string
45
+ ): Promise<void> {
46
+ return await fetchResult<void>(
47
+ `/accounts/${accountId}/r2/buckets/${bucketName}`,
48
+ { method: "DELETE" }
49
+ );
50
+ }
@@ -0,0 +1,131 @@
1
+ import * as fs from "node:fs";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import TOML from "@iarna/toml";
6
+ import { RewriteFrames } from "@sentry/integrations";
7
+ import {
8
+ captureException,
9
+ getCurrentHub,
10
+ startTransaction,
11
+ init,
12
+ Integrations,
13
+ setContext,
14
+ } from "@sentry/node";
15
+ import { execaSync } from "execa";
16
+ import prompts from "prompts";
17
+ import * as pkj from "../package.json";
18
+
19
+ export function initReporting() {
20
+ init({
21
+ release: `${pkj.name}@${pkj.version}`,
22
+ initialScope: {
23
+ tags: { [pkj.name]: pkj.version },
24
+ },
25
+ beforeBreadcrumb: (_breadcrumb, _hint) => {
26
+ // eventually, we might want to actually start dropping our own breadcrumbs.
27
+ // until then, we want to just ignore all of them, since sentry will
28
+ // automatically include breadcrumbs for things like console output,
29
+ // which can include unsanitized data that the user logs
30
+ // from their worker during development
31
+ return null;
32
+ },
33
+ dsn: "https://5089b76bf8a64a9c949bf5c2b5e8003c@o51786.ingest.sentry.io/6190959",
34
+ tracesSampleRate: 1.0,
35
+ integrations: [
36
+ new RewriteFrames({
37
+ root: "",
38
+ prefix: "/",
39
+ }),
40
+ new Integrations.Http({ tracing: true }),
41
+ ],
42
+ });
43
+
44
+ setContext("System Information", {
45
+ OS: process.platform,
46
+ node: process.version,
47
+ npm: execaSync("npm", ["--version"]).stdout,
48
+ wrangler: pkj.version,
49
+ });
50
+ }
51
+
52
+ async function appendReportingDecision(userInput: "true" | "false") {
53
+ const homePath = path.join(os.homedir(), ".wrangler/config/");
54
+ const reportingConfigLocation = path.join(homePath, "reporting.toml");
55
+ try {
56
+ fs.mkdirSync(homePath, { recursive: true });
57
+ await writeFile(
58
+ reportingConfigLocation,
59
+ `error_tracking_opt = ${userInput} # Sentry \nerror_tracking_opt_date = ${new Date().toISOString()} # Sentry Date Decision \n`,
60
+ "utf-8"
61
+ );
62
+ } catch (err) {
63
+ console.warn(
64
+ `Unable to create wrangler's error reporting configuration file at ${reportingConfigLocation}: `,
65
+ err
66
+ );
67
+ }
68
+ }
69
+
70
+ function exceptionTransaction(error: Error, origin = "") {
71
+ const transaction = startTransaction({
72
+ op: origin,
73
+ name: error.name,
74
+ });
75
+ captureException(error);
76
+ transaction.finish();
77
+ }
78
+
79
+ export async function reportError(err: Error, origin = "") {
80
+ if (!process.stdout.isTTY) return await appendReportingDecision("false");
81
+
82
+ const errorTrackingOpt = await reportingPermission();
83
+
84
+ if (errorTrackingOpt === undefined) {
85
+ const userInput = await prompts.prompt({
86
+ type: "select",
87
+ name: "sentryDecision",
88
+ message: "Would you like to submit a report when an error occurs?",
89
+ choices: [
90
+ { title: "Always", value: true },
91
+ { title: "Only this time", value: "once" },
92
+ { title: "No", value: false },
93
+ ],
94
+ initial: 2,
95
+ });
96
+
97
+ if (userInput.sentryDecision === "once") {
98
+ exceptionTransaction(err, origin);
99
+ return;
100
+ }
101
+
102
+ userInput.sentryDecision
103
+ ? await appendReportingDecision("true")
104
+ : await appendReportingDecision("false");
105
+ }
106
+
107
+ if (!errorTrackingOpt) {
108
+ const sentryClient = getCurrentHub().getClient();
109
+ if (sentryClient !== undefined) sentryClient.getOptions().enabled = false;
110
+ }
111
+
112
+ exceptionTransaction(err, origin);
113
+ }
114
+
115
+ async function reportingPermission() {
116
+ if (
117
+ !fs.existsSync(path.join(os.homedir(), ".wrangler/config/reporting.toml"))
118
+ )
119
+ return undefined;
120
+
121
+ const reportingTOML = TOML.parse(
122
+ await readFile(path.join(os.homedir(), ".wrangler/config/reporting.toml"), {
123
+ encoding: "utf-8",
124
+ })
125
+ );
126
+ const { error_tracking_opt } = reportingTOML as {
127
+ error_tracking_opt: string | undefined;
128
+ };
129
+
130
+ return error_tracking_opt;
131
+ }
@@ -0,0 +1,29 @@
1
+ declare module "selfsigned" {
2
+ import type { pki } from "node-forge";
3
+
4
+ export type Attributes = pki.CertificateField[];
5
+
6
+ export interface Options {
7
+ days?: number;
8
+ keySize?: number;
9
+ extensions?: unknown[];
10
+ algorithm?: string;
11
+ pkcs7?: boolean;
12
+ clientCertificate?: boolean;
13
+ clientCertificateCN?: string;
14
+ }
15
+
16
+ export interface Certificate {
17
+ private: string;
18
+ public: string;
19
+ cert: string;
20
+ fingerprint: string;
21
+ }
22
+
23
+ export function generate(attrs?: Attributes, options?: Options): Certificate;
24
+ export function generate(
25
+ attrs: Attributes,
26
+ options: Options,
27
+ callback: (err: Error, certificate: Certificate) => void
28
+ ): void;
29
+ }
package/src/sites.tsx CHANGED
@@ -1,33 +1,34 @@
1
1
  import { readdir, readFile, stat } from "node:fs/promises";
2
2
  import * as path from "node:path";
3
3
  import ignore from "ignore";
4
- import { XXHash64 } from "xxhash-addon";
4
+ import xxhash from "xxhash-wasm";
5
5
  import {
6
6
  createNamespace,
7
+ getKeyValue,
7
8
  listNamespaceKeys,
8
9
  listNamespaces,
9
10
  putBulkKeyValue,
10
11
  } from "./kv";
11
12
  import type { Config } from "./config";
13
+ import type { KeyValue, NamespaceKeyInfo } from "./kv";
14
+ import type { XXHashAPI } from "xxhash-wasm";
12
15
 
13
16
  /** Paths to always ignore. */
14
- const ALWAYS_IGNORE = ["node_modules"];
15
- const HIDDEN_FILES_TO_INCLUDE = [
17
+ const ALWAYS_IGNORE = new Set(["node_modules"]);
18
+ const HIDDEN_FILES_TO_INCLUDE = new Set([
16
19
  ".well-known", // See https://datatracker.ietf.org/doc/html/rfc8615
17
- ];
20
+ ]);
21
+ const FIVE_MINUTES = 60 * 5; // expressed in seconds, since that's what the api expects
18
22
 
19
23
  async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
20
24
  const files = await readdir(dirPath, { withFileTypes: true });
21
25
  for (const file of files) {
22
26
  // Skip files that we never want to process.
23
- if (ALWAYS_IGNORE.some((p) => file.name === p)) {
27
+ if (ALWAYS_IGNORE.has(file.name)) {
24
28
  continue;
25
29
  }
26
30
  // Skip hidden files (starting with .) except for some special ones
27
- if (
28
- file.name.startsWith(".") &&
29
- !HIDDEN_FILES_TO_INCLUDE.some((p) => file.name === p)
30
- ) {
31
+ if (file.name.startsWith(".") && !HIDDEN_FILES_TO_INCLUDE.has(file.name)) {
31
32
  continue;
32
33
  }
33
34
  // TODO: follow symlinks??
@@ -46,11 +47,8 @@ async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
46
47
  * the most important thing here is to detect changes of a single file to invalidate the cache and
47
48
  * it's impossible to serve two different files with the same name
48
49
  */
49
- function hashFileContent(content: string): string {
50
- const hasher = new XXHash64();
51
- hasher.update(Buffer.from(content));
52
- const hash = hasher.digest();
53
- return hash.toString("hex").substring(0, 10);
50
+ function hashFileContent(hasher: XXHashAPI, content: string): string {
51
+ return hasher.h64ToString(content).substring(0, 10);
54
52
  }
55
53
 
56
54
  /**
@@ -59,11 +57,15 @@ function hashFileContent(content: string): string {
59
57
  * The key will change if the file path or content of the asset changes.
60
58
  * The algorithm used here matches that of Wrangler 1.
61
59
  */
62
- function hashAsset(filePath: string, content: string): string {
60
+ function hashAsset(
61
+ hasher: XXHashAPI,
62
+ filePath: string,
63
+ content: string
64
+ ): string {
63
65
  const extName = path.extname(filePath) || "";
64
66
  const baseName = path.basename(filePath, extName);
65
67
  const directory = path.dirname(filePath);
66
- const hash = hashFileContent(content);
68
+ const hash = hashFileContent(hasher, content);
67
69
  return urlSafe(path.join(directory, `${baseName}.${hash}${extName}`));
68
70
  }
69
71
 
@@ -97,7 +99,6 @@ async function createKVNamespaceIfNotAlreadyExisting(
97
99
  * @param scriptName the name of the worker whose assets we are uploading.
98
100
  * @param siteAssets an objects describing what assets to upload, or undefined if there are no assets to upload.
99
101
  * @param preview if true then upload to a "preview" KV namespace.
100
- * @param _env (not implemented).
101
102
  * @returns a promise for an object mapping the relative paths of the assets to the key of that
102
103
  * asset in the KV namespace.
103
104
  */
@@ -105,8 +106,7 @@ export async function syncAssets(
105
106
  accountId: string,
106
107
  scriptName: string,
107
108
  siteAssets: AssetPaths | undefined,
108
- preview: boolean,
109
- env: string | undefined
109
+ preview: boolean
110
110
  ): Promise<{
111
111
  manifest: { [filePath: string]: string } | undefined;
112
112
  namespace: string | undefined;
@@ -115,7 +115,7 @@ export async function syncAssets(
115
115
  return { manifest: undefined, namespace: undefined };
116
116
  }
117
117
 
118
- const title = `__${scriptName}${env ? `-${env}` : ""}-workers_sites_assets${
118
+ const title = `__${scriptName}-workers_sites_assets${
119
119
  preview ? "_preview" : ""
120
120
  }`;
121
121
  const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
@@ -125,18 +125,18 @@ export async function syncAssets(
125
125
 
126
126
  // let's get all the keys in this namespace
127
127
  const result = await listNamespaceKeys(accountId, namespace);
128
- const keys = new Set(result.map((x) => x.name));
128
+ const keyMap = result.reduce<Record<string, NamespaceKeyInfo>>(
129
+ (km, key) => Object.assign(km, { [key.name]: key }),
130
+ {}
131
+ );
129
132
 
130
- const manifest = {};
131
- const upload: {
132
- key: string;
133
- value: string;
134
- base64: boolean;
135
- }[] = [];
133
+ const manifest: Record<string, string> = {};
134
+ const toUpload: KeyValue[] = [];
136
135
 
137
136
  const include = createPatternMatcher(siteAssets.includePatterns, false);
138
137
  const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
139
- // TODO: this can be more efficient by parallelising
138
+ const hasher = await xxhash();
139
+
140
140
  for await (const file of getFilesInFolder(siteAssets.baseDirectory)) {
141
141
  if (!include(file)) {
142
142
  continue;
@@ -149,13 +149,13 @@ export async function syncAssets(
149
149
  console.log(`reading ${file}...`);
150
150
  const content = await readFile(file, "base64");
151
151
 
152
- const assetKey = hashAsset(file, content);
152
+ const assetKey = hashAsset(hasher, file, content);
153
153
  validateAssetKey(assetKey);
154
154
 
155
155
  // now put each of the files into kv
156
- if (!keys.has(assetKey)) {
156
+ if (!(assetKey in keyMap) || keyMap[assetKey].expiration) {
157
157
  console.log(`uploading as ${assetKey}...`);
158
- upload.push({
158
+ toUpload.push({
159
159
  key: assetKey,
160
160
  value: content,
161
161
  base64: true,
@@ -163,9 +163,43 @@ export async function syncAssets(
163
163
  } else {
164
164
  console.log(`skipping - already uploaded`);
165
165
  }
166
+ // remove the key from the set so we know we've seen it
167
+ delete keyMap[assetKey];
166
168
  manifest[path.relative(siteAssets.baseDirectory, file)] = assetKey;
167
169
  }
168
- await putBulkKeyValue(accountId, namespace, JSON.stringify(upload));
170
+
171
+ // `keyMap` now contains the assets that we need to expire
172
+
173
+ let toExpire: KeyValue[] = [];
174
+ for (const asset of Object.values(keyMap)) {
175
+ if (!asset.expiration) {
176
+ console.log(`expiring unused ${asset.name}...`);
177
+ toExpire.push({
178
+ key: asset.name,
179
+ value: "", // we'll fill all the values in one go
180
+ // we use expiration_ttl, since we can't trust the time
181
+ // that a deploy source might provide (eg - https://github.com/cloudflare/wrangler/issues/2224)
182
+ expiration_ttl: FIVE_MINUTES,
183
+ base64: true,
184
+ });
185
+ }
186
+ }
187
+
188
+ // TODO: batch these in groups if it causes problems
189
+ toExpire = await Promise.all(
190
+ toExpire.map(async (asset) => ({
191
+ ...asset,
192
+ // it would be great if we didn't have to do this fetch at all
193
+ value: await getKeyValue(accountId, namespace, asset.key),
194
+ }))
195
+ );
196
+
197
+ await putBulkKeyValue(
198
+ accountId,
199
+ namespace,
200
+ toUpload.concat(toExpire),
201
+ () => {}
202
+ );
169
203
  return { manifest, namespace };
170
204
  }
171
205
 
@@ -222,7 +256,6 @@ export interface AssetPaths {
222
256
  * Uses the args (passed from the command line) if available,
223
257
  * falling back to those defined in the config.
224
258
  *
225
- * // TODO: Support for environments
226
259
  */
227
260
  export function getAssetPaths(
228
261
  config: Config,
@@ -0,0 +1,279 @@
1
+ /**
2
+ * When tailing logs from a worker, oftentimes you don't want to see _every
3
+ * single event_. That's where filters come in. We can send a set of filters
4
+ * to the tail worker, and it will pre-filter any logs for us so that we
5
+ * only recieve the ones we care about.
6
+ */
7
+
8
+ /**
9
+ * These are the filters we accept in the CLI. They
10
+ * were copied directly from wrangler 1 in order to
11
+ * maintain compatability, so they aren't actually the exact
12
+ * filters we need to send up to the tail worker. They generally map 1:1,
13
+ * but often require some transformation or
14
+ * renaming to match what it expects.
15
+ *
16
+ * For a full description of each filter, either check the
17
+ * CLI description or see the documentation for `ApiFilter`.
18
+ */
19
+ export type TailCLIFilters = {
20
+ status?: ("ok" | "error" | "canceled")[];
21
+ header?: string;
22
+ method?: string[];
23
+ search?: string;
24
+ samplingRate?: number;
25
+ clientIp?: string[];
26
+ };
27
+
28
+ /**
29
+ * These are the filters we send to the tail worker. We
30
+ * actually send a list of filters (an array of objects),
31
+ * so rather than having a single TailAPIFilters type,
32
+ * each kind of filter gets its own type and we define
33
+ * TailAPIFilter to be the union of those types.
34
+ */
35
+ export type TailAPIFilter =
36
+ | SamplingRateFilter
37
+ | OutcomeFilter
38
+ | MethodFilter
39
+ | HeaderFilter
40
+ | ClientIPFilter
41
+ | QueryFilter;
42
+
43
+ /**
44
+ * Filters logs based on a given sampling rate.
45
+ * For example, a `sampling_rate` of 0.25 will let one-quarter of the
46
+ * logs through.
47
+ */
48
+ type SamplingRateFilter = {
49
+ sampling_rate: number;
50
+ };
51
+
52
+ /**
53
+ * Filters logs based on the outcome of the worker's event handler.
54
+ */
55
+ type OutcomeFilter = {
56
+ outcome: Outcome[];
57
+ };
58
+
59
+ /**
60
+ * There are five possible outcomes we can get, three of which
61
+ * (exception, exceededCpu, and unknown) are considered errors
62
+ */
63
+ export type Outcome =
64
+ | "ok"
65
+ | "canceled"
66
+ | "exception"
67
+ | "exceededCpu"
68
+ | "unknown";
69
+
70
+ /**
71
+ * Filters logs based on the HTTP method used for the request
72
+ * that triggered the worker.
73
+ */
74
+ type MethodFilter = {
75
+ method: string[];
76
+ };
77
+
78
+ /**
79
+ * Filters logs based on an HTTP header on the request that
80
+ * triggered the worker.
81
+ */
82
+ type HeaderFilter = {
83
+ header: {
84
+ /**
85
+ * Filters on the header "key", e.g. "X-CLOUDFLARE-HEADER"
86
+ * or "X-CUSTOM-HEADER"
87
+ */
88
+ key: string;
89
+
90
+ /**
91
+ * Filters on the header "value", e.g. if this is set to
92
+ * "filter-for-me" and the "key" is "X-SHOULD-LOG", only
93
+ * events triggered by requests with the header
94
+ * "X-SHOULD-LOG:filter-for-me" will be logged.
95
+ */
96
+ query?: string;
97
+ };
98
+ };
99
+
100
+ /**
101
+ * Filters on the IP address the request came from that triggered
102
+ * the worker. A value of "self" will be replaced with the IP
103
+ * address that is running `wrangler tail`
104
+ */
105
+ type ClientIPFilter = {
106
+ client_ip: string[];
107
+ };
108
+
109
+ /**
110
+ * Filters logs by a query string. This means only logs that
111
+ * contain the given string will be sent to wrangler, and any
112
+ * that don't will be discarded by the tail worker.
113
+ */
114
+ type QueryFilter = {
115
+ query: string;
116
+ };
117
+
118
+ /**
119
+ * The full message we send to the tail worker includes our
120
+ * filters and a debug flag.
121
+ */
122
+ export type TailFilterMessage = {
123
+ filters: TailAPIFilter[];
124
+ debug: boolean;
125
+ };
126
+
127
+ /**
128
+ * Translate the flags passed in via a CLI invokation of wrangler
129
+ * into a message that we can send to the tail worker.
130
+ *
131
+ * @param cliFilters An object containing all the filters passed in from the CLI
132
+ * @param debug Whether or not we should be in debug mode
133
+ * @returns A filter message ready to be sent to the tail worker
134
+ */
135
+ export function translateCLICommandToFilterMessage(
136
+ cliFilters: TailCLIFilters,
137
+ debug: boolean
138
+ ): TailFilterMessage {
139
+ const apiFilters: TailAPIFilter[] = [];
140
+
141
+ if (cliFilters.samplingRate) {
142
+ apiFilters.push(parseSamplingRate(cliFilters.samplingRate));
143
+ }
144
+
145
+ if (cliFilters.status) {
146
+ apiFilters.push(parseOutcome(cliFilters.status));
147
+ }
148
+
149
+ if (cliFilters.method) {
150
+ apiFilters.push(parseMethod(cliFilters.method));
151
+ }
152
+
153
+ if (cliFilters.header) {
154
+ apiFilters.push(parseHeader(cliFilters.header));
155
+ }
156
+
157
+ if (cliFilters.clientIp) {
158
+ apiFilters.push(parseIP(cliFilters.clientIp));
159
+ }
160
+
161
+ if (cliFilters.search) {
162
+ apiFilters.push(parseQuery(cliFilters.search));
163
+ }
164
+
165
+ return {
166
+ filters: apiFilters,
167
+ debug,
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Parse the sampling rate passed in via command line
173
+ *
174
+ * @param sampling_rate the sampling rate passed in via CLI
175
+ * @throws an Error if the rate doesn't make sense
176
+ * @returns a SamplingRateFilter for use with the API
177
+ */
178
+ function parseSamplingRate(sampling_rate: number): SamplingRateFilter {
179
+ if (sampling_rate <= 0 || sampling_rate >= 1) {
180
+ throw new Error(
181
+ "A sampling rate must be between 0 and 1 in order to have any effect.\nFor example, a sampling rate of 0.25 means 25% of events will be logged."
182
+ );
183
+ }
184
+
185
+ return { sampling_rate };
186
+ }
187
+
188
+ /**
189
+ * Translate from CLI "status"es to API "outcome"s, including
190
+ * broadening "error" into "exception", "exceededCpu", and "unknown".
191
+ *
192
+ * @param statuses statuses passed in via CLI
193
+ * @returns an OutcomeFilter for use with the API
194
+ */
195
+ function parseOutcome(
196
+ statuses: ("ok" | "error" | "canceled")[]
197
+ ): OutcomeFilter {
198
+ const outcomes = new Set<Outcome>();
199
+
200
+ for (const status of statuses) {
201
+ switch (status) {
202
+ case "ok":
203
+ outcomes.add("ok");
204
+ break;
205
+
206
+ case "canceled":
207
+ outcomes.add("canceled");
208
+ break;
209
+
210
+ case "error":
211
+ outcomes.add("exception");
212
+ outcomes.add("exceededCpu");
213
+ outcomes.add("unknown");
214
+ break;
215
+
216
+ default:
217
+ break;
218
+ }
219
+ }
220
+
221
+ return {
222
+ outcome: Array.from(outcomes),
223
+ };
224
+ }
225
+
226
+ /**
227
+ * We just send silly methods through to the API anyway, since they don't
228
+ * cause any harm.
229
+ *
230
+ * @param method an array of HTTP request methods passed in via CLI
231
+ * @returns a MethodFilter for use with the API
232
+ */
233
+ function parseMethod(method: string[]): MethodFilter {
234
+ return { method };
235
+ }
236
+
237
+ /**
238
+ * Header filters can contain either just a key ("X-HEADER-KEY") or both
239
+ * a key and a value ("X-HEADER-KEY:some-value"). This function parses
240
+ * a given string according to that pattern.
241
+ *
242
+ * @param header a header string, "X-HEADER-KEY" or "X-HEADER-KEY:some-value"
243
+ * @returns a HeaderFilter for use with the API
244
+ */
245
+ function parseHeader(header: string): HeaderFilter {
246
+ const [headerKey, headerQuery] = header.split(":", 2);
247
+
248
+ return {
249
+ header: {
250
+ key: headerKey.trim(),
251
+ query: headerQuery?.trim(),
252
+ },
253
+ };
254
+ }
255
+
256
+ /**
257
+ * A list of IPs can be passed in to filter for messages that come from
258
+ * a worker triggered by a request originating from one of those IPs.
259
+ * You can also pass in the string "self" to filter for the IP of the
260
+ * machine running `wrangler tail`.
261
+ *
262
+ * @param client_ip an array of IP addresses to filter
263
+ * @returns a ClientIPFilter for use with the API
264
+ */
265
+ function parseIP(client_ip: string[]): ClientIPFilter {
266
+ return { client_ip };
267
+ }
268
+
269
+ /**
270
+ * Users can filter for logs that contain a "search" or a "query string".
271
+ * For example, if `--search findme` is passed to then we will only
272
+ * receive logs that contain the string "findme".
273
+ *
274
+ * @param query a query string to search for
275
+ * @returns a QueryFilter for use with the API
276
+ */
277
+ function parseQuery(query: string): QueryFilter {
278
+ return { query };
279
+ }