wrangler 0.0.0-e492c10 → 0.0.0-e4abed3e

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 (182) hide show
  1. package/README.md +30 -12
  2. package/bin/wrangler.js +90 -39
  3. package/config-schema.json +3059 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -86
  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 +19 -0
  11. package/templates/gitignore +2 -3
  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 +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +17 -0
  26. package/templates/new-worker-scheduled.ts +32 -0
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +22 -4
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +22 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26390 -0
  45. package/wrangler-dist/cli.js +201375 -103384
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4886
  52. package/pages/functions/buildPlugin.ts +0 -92
  53. package/pages/functions/buildWorker.ts +0 -138
  54. package/pages/functions/filepath-routing.test.ts +0 -234
  55. package/pages/functions/filepath-routing.ts +0 -189
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -156
  58. package/pages/functions/template-plugin.ts +0 -146
  59. package/pages/functions/template-worker.ts +0 -143
  60. package/src/__tests__/config-cache.test.ts +0 -36
  61. package/src/__tests__/configuration.test.ts +0 -3125
  62. package/src/__tests__/dev.test.tsx +0 -827
  63. package/src/__tests__/guess-worker-format.test.ts +0 -85
  64. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  65. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  66. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  70. package/src/__tests__/helpers/mock-console.ts +0 -87
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  72. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  73. package/src/__tests__/helpers/mock-istty.ts +0 -27
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  76. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  77. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  78. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  79. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  80. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  81. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  82. package/src/__tests__/https-options.test.ts +0 -130
  83. package/src/__tests__/index.test.ts +0 -242
  84. package/src/__tests__/init.test.ts +0 -1516
  85. package/src/__tests__/jest.setup.ts +0 -77
  86. package/src/__tests__/kv.test.ts +0 -1442
  87. package/src/__tests__/logger.test.ts +0 -115
  88. package/src/__tests__/package-manager.test.ts +0 -206
  89. package/src/__tests__/pages.test.ts +0 -327
  90. package/src/__tests__/parse.test.ts +0 -326
  91. package/src/__tests__/publish.test.ts +0 -4948
  92. package/src/__tests__/r2.test.ts +0 -210
  93. package/src/__tests__/route.test.ts +0 -45
  94. package/src/__tests__/secret.test.ts +0 -446
  95. package/src/__tests__/tail.test.ts +0 -690
  96. package/src/__tests__/user.test.ts +0 -131
  97. package/src/__tests__/whoami.test.tsx +0 -105
  98. package/src/bundle.ts +0 -169
  99. package/src/cfetch/index.ts +0 -104
  100. package/src/cfetch/internal.ts +0 -137
  101. package/src/cli.ts +0 -13
  102. package/src/config/README.md +0 -107
  103. package/src/config/config.ts +0 -234
  104. package/src/config/diagnostics.ts +0 -80
  105. package/src/config/environment.ts +0 -394
  106. package/src/config/index.ts +0 -63
  107. package/src/config/validation-helpers.ts +0 -575
  108. package/src/config/validation.ts +0 -1424
  109. package/src/config-cache.ts +0 -45
  110. package/src/create-worker-preview.ts +0 -175
  111. package/src/create-worker-upload-form.ts +0 -240
  112. package/src/dev/dev-vars.ts +0 -36
  113. package/src/dev/dev.tsx +0 -418
  114. package/src/dev/local.tsx +0 -312
  115. package/src/dev/remote.tsx +0 -213
  116. package/src/dev/use-esbuild.ts +0 -118
  117. package/src/dialogs.tsx +0 -87
  118. package/src/entry.ts +0 -267
  119. package/src/environment-variables.ts +0 -35
  120. package/src/errors.ts +0 -11
  121. package/src/https-options.ts +0 -123
  122. package/src/index.tsx +0 -2698
  123. package/src/inspect.ts +0 -623
  124. package/src/intl-polyfill.d.ts +0 -139
  125. package/src/kv.ts +0 -319
  126. package/src/logger.ts +0 -66
  127. package/src/miniflare-cli/README.md +0 -30
  128. package/src/miniflare-cli/enum-keys.ts +0 -17
  129. package/src/miniflare-cli/index.ts +0 -41
  130. package/src/miniflare-cli/request-context.ts +0 -40
  131. package/src/module-collection.ts +0 -258
  132. package/src/open-in-browser.ts +0 -26
  133. package/src/package-manager.ts +0 -127
  134. package/src/pages.tsx +0 -1875
  135. package/src/parse.ts +0 -185
  136. package/src/paths.ts +0 -26
  137. package/src/proxy.ts +0 -449
  138. package/src/publish.ts +0 -469
  139. package/src/r2.ts +0 -50
  140. package/src/selfsigned.d.ts +0 -29
  141. package/src/sites.tsx +0 -293
  142. package/src/tail/filters.ts +0 -279
  143. package/src/tail/index.ts +0 -299
  144. package/src/tail/printing.ts +0 -67
  145. package/src/update-check.ts +0 -19
  146. package/src/user.tsx +0 -1203
  147. package/src/whoami.tsx +0 -70
  148. package/src/worker.ts +0 -172
  149. package/templates/static-asset-facade.js +0 -47
  150. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  151. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  152. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  153. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  154. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  155. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  156. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  157. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  158. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  159. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  164. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  165. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  166. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  167. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  168. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  169. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  170. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  172. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  173. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  174. package/vendor/wrangler-mime/LICENSE +0 -21
  175. package/vendor/wrangler-mime/Mime.js +0 -97
  176. package/vendor/wrangler-mime/README.md +0 -187
  177. package/vendor/wrangler-mime/cli.js +0 -46
  178. package/vendor/wrangler-mime/index.js +0 -4
  179. package/vendor/wrangler-mime/lite.js +0 -4
  180. package/vendor/wrangler-mime/package.json +0 -52
  181. package/vendor/wrangler-mime/types/other.js +0 -1
  182. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/sites.tsx DELETED
@@ -1,293 +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
- listNamespaceKeys,
8
- listNamespaces,
9
- putBulkKeyValue,
10
- deleteBulkKeyValue,
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";
16
-
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
- ]);
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
- logger.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
- 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
-
128
- const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
129
- title,
130
- accountId
131
- );
132
-
133
- // let's get all the keys in this namespace
134
- const namespaceKeysResponse = await listNamespaceKeys(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
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);
163
-
164
- // now put each of the files into kv
165
- if (!namespaceKeys.has(assetKey)) {
166
- logger.log(`Uploading as ${assetKey}...`);
167
- toUpload.push({
168
- key: assetKey,
169
- value: content,
170
- base64: true,
171
- });
172
- } else {
173
- logger.log(`Skipping - already uploaded.`);
174
- }
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;
179
- }
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
- putBulkKeyValue(accountId, namespace, toUpload, () => {}),
189
- // delete all the unused assets
190
- deleteBulkKeyValue(
191
- accountId,
192
- namespace,
193
- Array.from(namespaceKeys),
194
- () => {}
195
- ),
196
- ]);
197
-
198
- logger.log("↗️ Done syncing assets");
199
-
200
- return { manifest, namespace };
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
- }
@@ -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
- }