wrangler 0.0.0-e3a458e → 0.0.0-e3a57616

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 (168) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +160 -85
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +32 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +654 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +105 -0
  41. package/templates/tsconfig.json +6 -103
  42. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  43. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  44. package/wrangler-dist/ProxyWorker.js +186 -0
  45. package/wrangler-dist/ProxyWorker.js.map +6 -0
  46. package/wrangler-dist/cli.d.ts +23793 -0
  47. package/wrangler-dist/cli.js +160711 -133928
  48. package/wrangler-dist/wasm-sync.wasm +0 -0
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/pages/functions/buildWorker.ts +0 -62
  54. package/pages/functions/filepath-routing.test.ts +0 -223
  55. package/pages/functions/filepath-routing.ts +0 -181
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -151
  58. package/pages/functions/template-worker.ts +0 -130
  59. package/src/__tests__/configuration.test.ts +0 -2598
  60. package/src/__tests__/dev.test.tsx +0 -445
  61. package/src/__tests__/dev2.test.tsx +0 -154
  62. package/src/__tests__/guess-worker-format.test.ts +0 -58
  63. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  64. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  65. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  66. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  67. package/src/__tests__/helpers/mock-bin.ts +0 -36
  68. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  69. package/src/__tests__/helpers/mock-console.ts +0 -70
  70. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  71. package/src/__tests__/helpers/mock-kv.ts +0 -33
  72. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  73. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  74. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  75. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  76. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  77. package/src/__tests__/https-options.test.ts +0 -127
  78. package/src/__tests__/index.test.ts +0 -991
  79. package/src/__tests__/jest.setup.ts +0 -69
  80. package/src/__tests__/kv.test.ts +0 -1382
  81. package/src/__tests__/logout.test.ts +0 -52
  82. package/src/__tests__/package-manager.test.ts +0 -206
  83. package/src/__tests__/pages.test.ts +0 -44
  84. package/src/__tests__/parse.test.ts +0 -322
  85. package/src/__tests__/publish.test.ts +0 -2611
  86. package/src/__tests__/r2.test.ts +0 -198
  87. package/src/__tests__/route.test.ts +0 -45
  88. package/src/__tests__/secret.test.ts +0 -425
  89. package/src/__tests__/sentry.test.ts +0 -146
  90. package/src/__tests__/tail.test.ts +0 -564
  91. package/src/__tests__/whoami.test.tsx +0 -100
  92. package/src/bundle.ts +0 -142
  93. package/src/cfetch/index.ts +0 -104
  94. package/src/cfetch/internal.ts +0 -139
  95. package/src/cli.ts +0 -19
  96. package/src/config/README.md +0 -107
  97. package/src/config/config.ts +0 -279
  98. package/src/config/diagnostics.ts +0 -80
  99. package/src/config/environment.ts +0 -305
  100. package/src/config/index.ts +0 -52
  101. package/src/config/validation-helpers.ts +0 -468
  102. package/src/config/validation.ts +0 -1057
  103. package/src/create-worker-preview.ts +0 -166
  104. package/src/create-worker-upload-form.ts +0 -217
  105. package/src/dev/dev.tsx +0 -362
  106. package/src/dev/local.tsx +0 -247
  107. package/src/dev/remote.tsx +0 -203
  108. package/src/dev/use-esbuild.ts +0 -100
  109. package/src/dialogs.tsx +0 -77
  110. package/src/entry.ts +0 -159
  111. package/src/environment-variables.ts +0 -33
  112. package/src/https-options.ts +0 -122
  113. package/src/index.tsx +0 -2365
  114. package/src/inspect.ts +0 -617
  115. package/src/kv.ts +0 -339
  116. package/src/module-collection.ts +0 -253
  117. package/src/open-in-browser.ts +0 -25
  118. package/src/package-manager.ts +0 -126
  119. package/src/pages.tsx +0 -1045
  120. package/src/parse.ts +0 -183
  121. package/src/paths.ts +0 -26
  122. package/src/proxy.ts +0 -440
  123. package/src/publish.ts +0 -354
  124. package/src/r2.ts +0 -50
  125. package/src/reporting.ts +0 -131
  126. package/src/selfsigned.d.ts +0 -29
  127. package/src/sites.tsx +0 -273
  128. package/src/tail/filters.ts +0 -279
  129. package/src/tail/index.ts +0 -299
  130. package/src/tail/printing.ts +0 -62
  131. package/src/user.tsx +0 -1118
  132. package/src/whoami.tsx +0 -69
  133. package/src/worker.ts +0 -163
  134. package/templates/static-asset-facade.js +0 -47
  135. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  136. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  137. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  138. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  139. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  140. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  141. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  142. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  148. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  149. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  150. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  151. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  152. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  153. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  156. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  157. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  158. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  159. package/vendor/wrangler-mime/LICENSE +0 -21
  160. package/vendor/wrangler-mime/Mime.js +0 -97
  161. package/vendor/wrangler-mime/README.md +0 -187
  162. package/vendor/wrangler-mime/cli.js +0 -46
  163. package/vendor/wrangler-mime/index.js +0 -4
  164. package/vendor/wrangler-mime/lite.js +0 -4
  165. package/vendor/wrangler-mime/package.json +0 -52
  166. package/vendor/wrangler-mime/types/other.js +0 -1
  167. package/vendor/wrangler-mime/types/standard.js +0 -1
  168. package/wrangler-dist/cli.js.map +0 -7
package/src/sites.tsx DELETED
@@ -1,273 +0,0 @@
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
- createNamespace,
7
- getKeyValue,
8
- listNamespaceKeys,
9
- listNamespaces,
10
- putBulkKeyValue,
11
- } from "./kv";
12
- import type { Config } from "./config";
13
- import type { KeyValue, NamespaceKeyInfo } from "./kv";
14
- import type { XXHashAPI } from "xxhash-wasm";
15
-
16
- /** Paths to always ignore. */
17
- const ALWAYS_IGNORE = new Set(["node_modules"]);
18
- const HIDDEN_FILES_TO_INCLUDE = new Set([
19
- ".well-known", // See https://datatracker.ietf.org/doc/html/rfc8615
20
- ]);
21
- const FIVE_MINUTES = 60 * 5; // expressed in seconds, since that's what the api expects
22
-
23
- async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
24
- const files = await readdir(dirPath, { withFileTypes: true });
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??
35
- if (file.isDirectory()) {
36
- yield* await getFilesInFolder(path.join(dirPath, file.name));
37
- } else {
38
- yield path.join(dirPath, file.name);
39
- }
40
- }
41
- }
42
-
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);
52
- }
53
-
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) || "";
66
- const baseName = path.basename(filePath, extName);
67
- const directory = path.dirname(filePath);
68
- const hash = hashFileContent(hasher, content);
69
- return urlSafe(path.join(directory, `${baseName}.${hash}${extName}`));
70
- }
71
-
72
- async function createKVNamespaceIfNotAlreadyExisting(
73
- title: string,
74
- accountId: string
75
- ) {
76
- // check if it already exists
77
- // TODO: this is super inefficient, should be made better
78
- const namespaces = await listNamespaces(accountId);
79
- const found = namespaces.find((x) => x.title === title);
80
- if (found) {
81
- return { created: false, id: found.id };
82
- }
83
-
84
- // else we make the namespace
85
- const id = await createNamespace(accountId, title);
86
- console.log(`🌀 Created namespace for Workers Site "${title}"`);
87
-
88
- return {
89
- created: true,
90
- id,
91
- };
92
- }
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
- */
105
- export async function syncAssets(
106
- accountId: string,
107
- scriptName: string,
108
- siteAssets: AssetPaths | undefined,
109
- preview: boolean
110
- ): Promise<{
111
- manifest: { [filePath: string]: string } | undefined;
112
- namespace: string | undefined;
113
- }> {
114
- if (siteAssets === undefined) {
115
- return { manifest: undefined, namespace: undefined };
116
- }
117
-
118
- const title = `__${scriptName}-workers_sites_assets${
119
- preview ? "_preview" : ""
120
- }`;
121
- const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
122
- title,
123
- accountId
124
- );
125
-
126
- // let's get all the keys in this namespace
127
- const result = await listNamespaceKeys(accountId, namespace);
128
- const keyMap = result.reduce<Record<string, NamespaceKeyInfo>>(
129
- (km, key) => Object.assign(km, { [key.name]: key }),
130
- {}
131
- );
132
-
133
- const manifest: Record<string, string> = {};
134
- const toUpload: KeyValue[] = [];
135
-
136
- const include = createPatternMatcher(siteAssets.includePatterns, false);
137
- const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
138
- const hasher = await xxhash();
139
-
140
- for await (const file of getFilesInFolder(siteAssets.baseDirectory)) {
141
- if (!include(file)) {
142
- continue;
143
- }
144
- if (exclude(file)) {
145
- continue;
146
- }
147
-
148
- await validateAssetSize(file);
149
- console.log(`reading ${file}...`);
150
- const content = await readFile(file, "base64");
151
-
152
- const assetKey = hashAsset(hasher, file, content);
153
- validateAssetKey(assetKey);
154
-
155
- // now put each of the files into kv
156
- if (!(assetKey in keyMap) || keyMap[assetKey].expiration) {
157
- console.log(`uploading as ${assetKey}...`);
158
- toUpload.push({
159
- key: assetKey,
160
- value: content,
161
- base64: true,
162
- });
163
- } else {
164
- console.log(`skipping - already uploaded`);
165
- }
166
- // remove the key from the set so we know we've seen it
167
- delete keyMap[assetKey];
168
- manifest[path.relative(siteAssets.baseDirectory, file)] = assetKey;
169
- }
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
- );
203
- return { manifest, namespace };
204
- }
205
-
206
- function createPatternMatcher(
207
- patterns: string[],
208
- exclude: boolean
209
- ): (filePath: string) => boolean {
210
- if (patterns.length === 0) {
211
- return (_filePath) => !exclude;
212
- } else {
213
- const ignorer = ignore().add(patterns);
214
- return (filePath) => ignorer.test(filePath).ignored;
215
- }
216
- }
217
-
218
- async function validateAssetSize(filePath: string) {
219
- const { size } = await stat(filePath);
220
- if (size > 25 * 1024 * 1024) {
221
- throw new Error(
222
- `File ${filePath} 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
- baseDirectory: string;
249
- includePatterns: string[];
250
- excludePatterns: string[];
251
- }
252
-
253
- /**
254
- * Get an object that describes what assets to upload, if any.
255
- *
256
- * Uses the args (passed from the command line) if available,
257
- * falling back to those defined in the config.
258
- *
259
- */
260
- export function getAssetPaths(
261
- config: Config,
262
- baseDirectory = config.site?.bucket,
263
- includePatterns = config.site?.include ?? [],
264
- excludePatterns = config.site?.exclude ?? []
265
- ): undefined | AssetPaths {
266
- return baseDirectory
267
- ? {
268
- baseDirectory,
269
- includePatterns,
270
- excludePatterns,
271
- }
272
- : undefined;
273
- }
@@ -1,279 +0,0 @@
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
- }