wrangler 0.0.0-e978986 → 0.0.0-e981d0be5

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