wrangler 0.0.0-ece06ea → 0.0.0-ed08df4

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 (121) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +34 -2
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +71 -36
  6. package/pages/functions/buildPlugin.ts +92 -0
  7. package/pages/functions/buildWorker.ts +138 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3125 -0
  16. package/src/__tests__/dev.test.tsx +829 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +90 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +221 -132
  38. package/src/__tests__/init.test.ts +1516 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +206 -0
  43. package/src/__tests__/pages.test.ts +327 -0
  44. package/src/__tests__/parse.test.ts +326 -0
  45. package/src/__tests__/publish.test.ts +4996 -0
  46. package/src/__tests__/r2.test.ts +210 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +446 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/bundle.ts +169 -0
  53. package/src/cfetch/index.ts +104 -0
  54. package/src/cfetch/internal.ts +140 -0
  55. package/src/cli.ts +10 -7
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +234 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +394 -0
  60. package/src/config/index.ts +63 -0
  61. package/src/config/validation-helpers.ts +575 -0
  62. package/src/config/validation.ts +1424 -0
  63. package/src/config-cache.ts +45 -0
  64. package/src/create-worker-preview.ts +175 -0
  65. package/src/create-worker-upload-form.ts +240 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +421 -0
  68. package/src/dev/local.tsx +312 -0
  69. package/src/dev/remote.tsx +213 -0
  70. package/src/dev/use-esbuild.ts +118 -0
  71. package/src/dialogs.tsx +22 -20
  72. package/src/entry.ts +322 -0
  73. package/src/environment-variables.ts +35 -0
  74. package/src/errors.ts +11 -0
  75. package/src/https-options.ts +123 -0
  76. package/src/index.tsx +1869 -1020
  77. package/src/inspect.ts +623 -0
  78. package/src/intl-polyfill.d.ts +139 -0
  79. package/src/kv.ts +344 -0
  80. package/src/logger.ts +66 -0
  81. package/src/miniflare-cli/README.md +30 -0
  82. package/src/miniflare-cli/enum-keys.ts +17 -0
  83. package/src/miniflare-cli/index.ts +41 -0
  84. package/src/miniflare-cli/request-context.ts +40 -0
  85. package/src/module-collection.ts +258 -0
  86. package/src/open-in-browser.ts +26 -0
  87. package/src/package-manager.ts +127 -0
  88. package/src/pages.tsx +1756 -218
  89. package/src/parse.ts +185 -0
  90. package/src/paths.ts +26 -0
  91. package/src/proxy.ts +449 -0
  92. package/src/publish.ts +377 -262
  93. package/src/r2.ts +50 -0
  94. package/src/selfsigned.d.ts +29 -0
  95. package/src/sites.tsx +237 -59
  96. package/src/tail/filters.ts +279 -0
  97. package/src/tail/index.ts +299 -0
  98. package/src/tail/printing.ts +67 -0
  99. package/src/update-check.ts +19 -0
  100. package/src/user.tsx +395 -221
  101. package/src/whoami.tsx +70 -0
  102. package/src/worker.ts +172 -0
  103. package/templates/gitignore +171 -0
  104. package/templates/new-worker.js +15 -0
  105. package/templates/new-worker.ts +15 -0
  106. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  107. package/templates/tsconfig.json +105 -0
  108. package/wrangler-dist/cli.js +108921 -132528
  109. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  110. package/src/__tests__/mock-cfetch.js +0 -46
  111. package/src/api/form_data.ts +0 -158
  112. package/src/api/inspect.ts +0 -441
  113. package/src/api/preview.ts +0 -123
  114. package/src/api/worker.ts +0 -161
  115. package/src/cfetch.ts +0 -72
  116. package/src/config.ts +0 -124
  117. package/src/dev.tsx +0 -736
  118. package/src/kv.tsx +0 -211
  119. package/src/tail.tsx +0 -71
  120. package/src/util/fetch.ts +0 -74
  121. package/wrangler-dist/cli.js.map +0 -7
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,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,14 +1,37 @@
1
- import { readdir, readFile } from "node:fs/promises";
2
- import { createReadStream } from "node:fs";
3
- import cfetch from "./cfetch";
4
- import { listNamespaceKeys, listNamespaces, putBulkKeyValue } from "./kv";
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import ignore from "ignore";
4
+ import xxhash from "xxhash-wasm";
5
+ import {
6
+ createKVNamespace,
7
+ listKVNamespaceKeys,
8
+ listKVNamespaces,
9
+ putKVBulkKeyValue,
10
+ deleteKVBulkKeyValue,
11
+ } from "./kv";
12
+ import { logger } from "./logger";
13
+ import type { Config } from "./config";
14
+ import type { KeyValue } from "./kv";
15
+ import type { XXHashAPI } from "xxhash-wasm";
5
16
 
6
- import * as path from "path";
7
- import crypto from "node:crypto";
17
+ /** Paths to always ignore. */
18
+ const ALWAYS_IGNORE = new Set(["node_modules"]);
19
+ const HIDDEN_FILES_TO_INCLUDE = new Set([
20
+ ".well-known", // See https://datatracker.ietf.org/doc/html/rfc8615
21
+ ]);
8
22
 
9
23
  async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
10
24
  const files = await readdir(dirPath, { withFileTypes: true });
11
25
  for (const file of files) {
26
+ // Skip files that we never want to process.
27
+ if (ALWAYS_IGNORE.has(file.name)) {
28
+ continue;
29
+ }
30
+ // Skip hidden files (starting with .) except for some special ones
31
+ if (file.name.startsWith(".") && !HIDDEN_FILES_TO_INCLUDE.has(file.name)) {
32
+ continue;
33
+ }
34
+ // TODO: follow symlinks??
12
35
  if (file.isDirectory()) {
13
36
  yield* await getFilesInFolder(path.join(dirPath, file.name));
14
37
  } else {
@@ -17,27 +40,33 @@ async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
17
40
  }
18
41
  }
19
42
 
20
- async function hashFileContent(filePath: string): Promise<string> {
21
- return new Promise((resolve, reject) => {
22
- const hash = crypto.createHash("sha1");
23
- const rs = createReadStream(filePath);
24
- rs.on("error", reject);
25
- rs.on("data", (chunk) => hash.update(chunk));
26
- rs.on("end", () => resolve(hash.digest("hex")));
27
- });
43
+ /**
44
+ * Create a hash key for the given content using the xxhash algorithm.
45
+ *
46
+ * Note we only return the first 10 characters, since we will also include the file name in the asset manifest key
47
+ * the most important thing here is to detect changes of a single file to invalidate the cache and
48
+ * it's impossible to serve two different files with the same name
49
+ */
50
+ function hashFileContent(hasher: XXHashAPI, content: string): string {
51
+ return hasher.h64ToString(content).substring(0, 10);
28
52
  }
29
53
 
30
- async function hashFile(filePath: string): Promise<{
31
- filePath: string;
32
- hash: string;
33
- }> {
34
- const extName = path.extname(filePath);
54
+ /**
55
+ * Create a hashed asset key for the given asset.
56
+ *
57
+ * The key will change if the file path or content of the asset changes.
58
+ * The algorithm used here matches that of Wrangler 1.
59
+ */
60
+ function hashAsset(
61
+ hasher: XXHashAPI,
62
+ filePath: string,
63
+ content: string
64
+ ): string {
65
+ const extName = path.extname(filePath) || "";
35
66
  const baseName = path.basename(filePath, extName);
36
- const hash = await hashFileContent(filePath);
37
- return {
38
- filePath: `${baseName}.${hash}${extName || ""}`,
39
- hash,
40
- };
67
+ const directory = path.dirname(filePath);
68
+ const hash = hashFileContent(hasher, content);
69
+ return urlSafe(path.join(directory, `${baseName}.${hash}${extName}`));
41
70
  }
42
71
 
43
72
  async function createKVNamespaceIfNotAlreadyExisting(
@@ -46,70 +75,219 @@ async function createKVNamespaceIfNotAlreadyExisting(
46
75
  ) {
47
76
  // check if it already exists
48
77
  // TODO: this is super inefficient, should be made better
49
- const namespaces = await listNamespaces(accountId);
78
+ const namespaces = await listKVNamespaces(accountId);
50
79
  const found = namespaces.find((x) => x.title === title);
51
80
  if (found) {
52
81
  return { created: false, id: found.id };
53
82
  }
54
83
 
55
84
  // else we make the namespace
56
- // TODO: use an export from ./kv
57
- const json = await cfetch<{ id: string }>(
58
- `/accounts/${accountId}/storage/kv/namespaces`,
59
- {
60
- method: "POST",
61
- headers: {
62
- "Content-Type": "application/json",
63
- },
64
- body: JSON.stringify({ title }),
65
- }
66
- );
85
+ const id = await createKVNamespace(accountId, title);
86
+ logger.log(`🌀 Created namespace for Workers Site "${title}"`);
67
87
 
68
88
  return {
69
89
  created: true,
70
- id: json.id,
90
+ id,
71
91
  };
72
92
  }
73
93
 
94
+ /**
95
+ * Upload the assets found within the `dirPath` directory to the sites assets KV namespace for
96
+ * the worker given by `scriptName`.
97
+ *
98
+ * @param accountId the account to upload to.
99
+ * @param scriptName the name of the worker whose assets we are uploading.
100
+ * @param siteAssets an objects describing what assets to upload, or undefined if there are no assets to upload.
101
+ * @param preview if true then upload to a "preview" KV namespace.
102
+ * @returns a promise for an object mapping the relative paths of the assets to the key of that
103
+ * asset in the KV namespace.
104
+ */
74
105
  export async function syncAssets(
75
106
  accountId: string,
76
107
  scriptName: string,
77
- dirPath: string,
108
+ siteAssets: AssetPaths | undefined,
78
109
  preview: boolean,
79
- _env?: string
80
- ) {
81
- const title = `__${scriptName}_sites_assets${preview ? "_preview" : ""}`;
110
+ dryRun: boolean | undefined
111
+ ): Promise<{
112
+ manifest: { [filePath: string]: string } | undefined;
113
+ namespace: string | undefined;
114
+ }> {
115
+ if (siteAssets === undefined) {
116
+ return { manifest: undefined, namespace: undefined };
117
+ }
118
+
119
+ if (dryRun) {
120
+ logger.log("(Note: doing a dry run, not uploading or deleting anything.)");
121
+ return { manifest: undefined, namespace: undefined };
122
+ }
123
+
124
+ const title = `__${scriptName}-workers_sites_assets${
125
+ preview ? "_preview" : ""
126
+ }`;
127
+
82
128
  const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
83
129
  title,
84
130
  accountId
85
131
  );
86
132
 
87
133
  // let's get all the keys in this namespace
88
- const keys = new Set(
89
- (await listNamespaceKeys(accountId, namespace)).map((x) => x.name)
134
+ const namespaceKeysResponse = await listKVNamespaceKeys(accountId, namespace);
135
+ const namespaceKeys = new Set(namespaceKeysResponse.map((x) => x.name));
136
+
137
+ const manifest: Record<string, string> = {};
138
+ const toUpload: KeyValue[] = [];
139
+
140
+ const include = createPatternMatcher(siteAssets.includePatterns, false);
141
+ const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
142
+ const hasher = await xxhash();
143
+
144
+ const assetDirectory = path.join(
145
+ siteAssets.baseDirectory,
146
+ siteAssets.assetDirectory
90
147
  );
148
+ for await (const absAssetFile of getFilesInFolder(assetDirectory)) {
149
+ const assetFile = path.relative(siteAssets.baseDirectory, absAssetFile);
150
+ if (!include(assetFile)) {
151
+ continue;
152
+ }
153
+ if (exclude(assetFile)) {
154
+ continue;
155
+ }
156
+
157
+ await validateAssetSize(absAssetFile, assetFile);
158
+ logger.log(`Reading ${assetFile}...`);
159
+ const content = await readFile(absAssetFile, "base64");
160
+
161
+ const assetKey = hashAsset(hasher, assetFile, content);
162
+ validateAssetKey(assetKey);
91
163
 
92
- const manifest = {};
93
- const upload = [];
94
- // TODO: this can be more efficient by parallelising
95
- for await (const file of getFilesInFolder(dirPath)) {
96
- // TODO: "exclude:" config
97
- const { filePath } = await hashFile(file);
98
164
  // now put each of the files into kv
99
- if (!keys.has(filePath)) {
100
- console.log(`uploading ${file}...`);
101
- const content = await readFile(file, "base64");
102
- if (content.length > 25 * 1024 * 1024) {
103
- throw new Error(`File ${file} is too big, it should be under 25 mb.`);
104
- }
105
- upload.push({
106
- key: filePath,
165
+ if (!namespaceKeys.has(assetKey)) {
166
+ logger.log(`Uploading as ${assetKey}...`);
167
+ toUpload.push({
168
+ key: assetKey,
107
169
  value: content,
108
170
  base64: true,
109
171
  });
172
+ } else {
173
+ logger.log(`Skipping - already uploaded.`);
110
174
  }
111
- manifest[path.relative(dirPath, file)] = filePath;
175
+
176
+ // remove the key from the set so we know what we've already uploaded
177
+ namespaceKeys.delete(assetKey);
178
+ manifest[path.relative(siteAssets.assetDirectory, absAssetFile)] = assetKey;
112
179
  }
113
- await putBulkKeyValue(accountId, namespace, JSON.stringify(upload));
180
+
181
+ // keys now contains all the files we're deleting
182
+ for (const key of namespaceKeys) {
183
+ logger.log(`Deleting ${key} from the asset store...`);
184
+ }
185
+
186
+ await Promise.all([
187
+ // upload all the new assets
188
+ putKVBulkKeyValue(accountId, namespace, toUpload, () => {}),
189
+ // delete all the unused assets
190
+ deleteKVBulkKeyValue(
191
+ accountId,
192
+ namespace,
193
+ Array.from(namespaceKeys),
194
+ () => {}
195
+ ),
196
+ ]);
197
+
198
+ logger.log("↗️ Done syncing assets");
199
+
114
200
  return { manifest, namespace };
115
201
  }
202
+
203
+ function createPatternMatcher(
204
+ patterns: string[],
205
+ exclude: boolean
206
+ ): (filePath: string) => boolean {
207
+ if (patterns.length === 0) {
208
+ return (_filePath) => !exclude;
209
+ } else {
210
+ const ignorer = ignore().add(patterns);
211
+ return (filePath) => ignorer.test(filePath).ignored;
212
+ }
213
+ }
214
+
215
+ async function validateAssetSize(
216
+ absFilePath: string,
217
+ relativeFilePath: string
218
+ ) {
219
+ const { size } = await stat(absFilePath);
220
+ if (size > 25 * 1024 * 1024) {
221
+ throw new Error(
222
+ `File ${relativeFilePath} is too big, it should be under 25 MiB. See https://developers.cloudflare.com/workers/platform/limits#kv-limits`
223
+ );
224
+ }
225
+ }
226
+
227
+ function validateAssetKey(assetKey: string) {
228
+ if (assetKey.length > 512) {
229
+ throw new Error(
230
+ `The asset path key "${assetKey}" exceeds the maximum key size limit of 512. See https://developers.cloudflare.com/workers/platform/limits#kv-limits",`
231
+ );
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Convert a filePath to be safe to use as a relative URL.
237
+ *
238
+ * Primarily this involves converting Windows backslashes to forward slashes.
239
+ */
240
+ function urlSafe(filePath: string): string {
241
+ return filePath.replace(/\\/g, "/");
242
+ }
243
+
244
+ /**
245
+ * Information about the assets that should be uploaded
246
+ */
247
+ export interface AssetPaths {
248
+ /**
249
+ * Absolute path to the root of the project.
250
+ *
251
+ * This is the directory containing wrangler.toml or cwd if no config.
252
+ */
253
+ baseDirectory: string;
254
+ /**
255
+ * The path to the assets directory, relative to the `baseDirectory`.
256
+ */
257
+ assetDirectory: string;
258
+ /**
259
+ * An array of patterns that match files that should be uploaded.
260
+ */
261
+ includePatterns: string[];
262
+ /**
263
+ * An array of patterns that match files that should not be uploaded.
264
+ */
265
+ excludePatterns: string[];
266
+ }
267
+
268
+ /**
269
+ * Get an object that describes what assets to upload, if any.
270
+ *
271
+ * Uses the args (passed from the command line) if available,
272
+ * falling back to those defined in the config.
273
+ *
274
+ */
275
+ export function getAssetPaths(
276
+ config: Config,
277
+ assetDirectory = config.site?.bucket,
278
+ includePatterns = config.site?.include ?? [],
279
+ excludePatterns = config.site?.exclude ?? []
280
+ ): AssetPaths | undefined {
281
+ const baseDirectory = path.resolve(
282
+ path.dirname(config.configPath ?? "wrangler.toml")
283
+ );
284
+
285
+ return assetDirectory
286
+ ? {
287
+ baseDirectory,
288
+ assetDirectory,
289
+ includePatterns,
290
+ excludePatterns,
291
+ }
292
+ : undefined;
293
+ }
@@ -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
+ }