wrangler 0.0.0-fb43821 → 0.0.0-fb53fda

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 (104) hide show
  1. package/README.md +1 -1
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +46 -17
  6. package/pages/functions/buildWorker.ts +62 -0
  7. package/pages/functions/filepath-routing.test.ts +223 -0
  8. package/pages/functions/filepath-routing.ts +181 -0
  9. package/pages/functions/identifiers.ts +78 -0
  10. package/pages/functions/routes.ts +151 -0
  11. package/pages/functions/template-worker.ts +130 -0
  12. package/src/__tests__/configuration.test.ts +2790 -0
  13. package/src/__tests__/dev.test.tsx +532 -0
  14. package/src/__tests__/guess-worker-format.test.ts +68 -0
  15. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +33 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +127 -0
  30. package/src/__tests__/index.test.ts +770 -209
  31. package/src/__tests__/jest.setup.ts +69 -0
  32. package/src/__tests__/kv.test.ts +1380 -0
  33. package/src/__tests__/logout.test.ts +52 -0
  34. package/src/__tests__/package-manager.test.ts +206 -0
  35. package/src/__tests__/pages.test.ts +82 -0
  36. package/src/__tests__/parse.test.ts +322 -0
  37. package/src/__tests__/publish.test.ts +3431 -0
  38. package/src/__tests__/r2.test.ts +198 -0
  39. package/src/__tests__/route.test.ts +45 -0
  40. package/src/__tests__/secret.test.ts +425 -0
  41. package/src/__tests__/sentry.test.ts +146 -0
  42. package/src/__tests__/tail.test.ts +562 -0
  43. package/src/__tests__/whoami.test.tsx +100 -0
  44. package/src/bundle.ts +142 -0
  45. package/src/cfetch/index.ts +104 -0
  46. package/src/cfetch/internal.ts +139 -0
  47. package/src/cli.ts +16 -7
  48. package/src/config/README.md +107 -0
  49. package/src/config/config.ts +218 -0
  50. package/src/config/diagnostics.ts +80 -0
  51. package/src/config/environment.ts +366 -0
  52. package/src/config/index.ts +62 -0
  53. package/src/config/validation-helpers.ts +554 -0
  54. package/src/config/validation.ts +1191 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +63 -25
  56. package/src/create-worker-upload-form.ts +217 -0
  57. package/src/dev/dev.tsx +390 -0
  58. package/src/dev/local.tsx +232 -0
  59. package/src/dev/remote.tsx +203 -0
  60. package/src/dev/use-esbuild.ts +100 -0
  61. package/src/dialogs.tsx +4 -4
  62. package/src/entry.ts +237 -0
  63. package/src/environment-variables.ts +33 -0
  64. package/src/https-options.ts +122 -0
  65. package/src/index.tsx +1417 -915
  66. package/src/inspect.ts +617 -0
  67. package/src/intl-polyfill.d.ts +139 -0
  68. package/src/kv.ts +319 -0
  69. package/src/miniflare-cli/README.md +30 -0
  70. package/src/miniflare-cli/enum-keys.ts +17 -0
  71. package/src/miniflare-cli/index.ts +37 -0
  72. package/src/module-collection.ts +229 -35
  73. package/src/open-in-browser.ts +25 -0
  74. package/src/package-manager.ts +126 -0
  75. package/src/pages.tsx +470 -227
  76. package/src/parse.ts +183 -0
  77. package/src/paths.ts +26 -0
  78. package/src/proxy.ts +440 -0
  79. package/src/publish.ts +292 -290
  80. package/src/r2.ts +50 -0
  81. package/src/reporting.ts +131 -0
  82. package/src/selfsigned.d.ts +29 -0
  83. package/src/sites.tsx +224 -59
  84. package/src/tail/filters.ts +279 -0
  85. package/src/tail/index.ts +299 -0
  86. package/src/tail/printing.ts +62 -0
  87. package/src/user.tsx +301 -203
  88. package/src/whoami.tsx +69 -0
  89. package/src/worker.ts +163 -0
  90. package/templates/new-worker.js +15 -0
  91. package/templates/new-worker.ts +15 -0
  92. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  93. package/templates/tsconfig.json +105 -0
  94. package/wrangler-dist/cli.js +134241 -116339
  95. package/wrangler-dist/cli.js.map +3 -3
  96. package/src/__tests__/mock-cfetch.js +0 -42
  97. package/src/api/form_data.ts +0 -141
  98. package/src/api/inspect.ts +0 -430
  99. package/src/api/worker.ts +0 -161
  100. package/src/cfetch.ts +0 -72
  101. package/src/config.ts +0 -122
  102. package/src/dev.tsx +0 -776
  103. package/src/kv.tsx +0 -211
  104. package/src/tail.tsx +0 -71
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
+ import type { UrlPath } from "../../src/paths";
5
+
6
+ export const HTTP_METHODS = [
7
+ "HEAD",
8
+ "OPTIONS",
9
+ "GET",
10
+ "POST",
11
+ "PUT",
12
+ "PATCH",
13
+ "DELETE",
14
+ ] as const;
15
+ export type HTTPMethod = typeof HTTP_METHODS[number];
16
+ export function isHTTPMethod(
17
+ maybeHTTPMethod: string
18
+ ): maybeHTTPMethod is HTTPMethod {
19
+ return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
20
+ }
21
+
22
+ export type RoutesCollection = Array<{
23
+ routePath: UrlPath;
24
+ method?: HTTPMethod;
25
+ modules: string[];
26
+ middlewares: string[];
27
+ }>;
28
+
29
+ export type Config = {
30
+ routes?: RouteConfig[];
31
+ schedules?: unknown;
32
+ };
33
+
34
+ export type RouteConfig = {
35
+ routePath: UrlPath;
36
+ method?: HTTPMethod;
37
+ middleware?: string | string[];
38
+ module?: string | string[];
39
+ };
40
+
41
+ type ImportMap = Map<
42
+ string,
43
+ {
44
+ filepath: string;
45
+ name: string;
46
+ identifier: string;
47
+ }
48
+ >;
49
+
50
+ type Arguments = {
51
+ config: Config;
52
+ outfile: string;
53
+ srcDir: string;
54
+ };
55
+
56
+ export async function writeRoutesModule({
57
+ config,
58
+ srcDir,
59
+ outfile = "_routes.js",
60
+ }: Arguments) {
61
+ const { importMap, routes } = parseConfig(config, srcDir);
62
+ const routesModule = generateRoutesModule(importMap, routes);
63
+
64
+ await fs.writeFile(outfile, routesModule);
65
+
66
+ return outfile;
67
+ }
68
+
69
+ export function parseConfig(config: Config, baseDir: string) {
70
+ const routes: RoutesCollection = [];
71
+ const importMap: ImportMap = new Map();
72
+ const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
73
+
74
+ function parseModuleIdentifiers(paths: string | string[] | undefined) {
75
+ if (typeof paths === "undefined") {
76
+ paths = [];
77
+ }
78
+
79
+ if (typeof paths === "string") {
80
+ paths = [paths];
81
+ }
82
+
83
+ return paths.map((modulePath) => {
84
+ const [filepath, name = "default"] = modulePath.split(":");
85
+ let { identifier } = importMap.get(modulePath) ?? {};
86
+
87
+ const resolvedPath = path.resolve(baseDir, filepath);
88
+
89
+ // ensure the filepath isn't attempting to resolve to anything outside of the project
90
+ if (path.relative(baseDir, resolvedPath).startsWith("..")) {
91
+ throw new Error(`Invalid module path "${filepath}"`);
92
+ }
93
+
94
+ // ensure the module name (if provided) is a valid identifier to guard against injection attacks
95
+ if (name !== "default" && !isValidIdentifier(name)) {
96
+ throw new Error(`Invalid module identifier "${name}"`);
97
+ }
98
+
99
+ if (!identifier) {
100
+ identifier = normalizeIdentifier(`__${filepath}_${name}`);
101
+
102
+ let count = identifierCount.get(identifier) ?? 0;
103
+ identifierCount.set(identifier, ++count);
104
+
105
+ if (count > 1) {
106
+ identifier += `_${count}`;
107
+ }
108
+
109
+ importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
110
+ }
111
+
112
+ return identifier;
113
+ });
114
+ }
115
+
116
+ for (const { routePath, method, ...props } of config.routes ?? []) {
117
+ routes.push({
118
+ routePath,
119
+ method,
120
+ middlewares: parseModuleIdentifiers(props.middleware),
121
+ modules: parseModuleIdentifiers(props.module),
122
+ });
123
+ }
124
+
125
+ return { routes, importMap };
126
+ }
127
+
128
+ export function generateRoutesModule(
129
+ importMap: ImportMap,
130
+ routes: RoutesCollection
131
+ ) {
132
+ return `${[...importMap.values()]
133
+ .map(
134
+ ({ filepath, name, identifier }) =>
135
+ `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
136
+ )
137
+ .join("\n")}
138
+
139
+ export const routes = [
140
+ ${routes
141
+ .map(
142
+ (route) => ` {
143
+ routePath: "${route.routePath}",
144
+ method: "${route.method}",
145
+ middlewares: [${route.middlewares.join(", ")}],
146
+ modules: [${route.modules.join(", ")}],
147
+ },`
148
+ )
149
+ .join("\n")}
150
+ ]`;
151
+ }
@@ -0,0 +1,130 @@
1
+ import { match } from "path-to-regexp";
2
+ import type { HTTPMethod } from "./routes";
3
+
4
+ /* TODO: Grab these from @cloudflare/workers-types instead */
5
+ type Params<P extends string = string> = Record<P, string | string[]>;
6
+
7
+ type EventContext<Env, P extends string, Data> = {
8
+ request: Request;
9
+ waitUntil: (promise: Promise<unknown>) => void;
10
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
+ env: Env & { ASSETS: { fetch: typeof fetch } };
12
+ params: Params<P>;
13
+ data: Data;
14
+ };
15
+
16
+ declare type PagesFunction<
17
+ Env = unknown,
18
+ P extends string = string,
19
+ Data extends Record<string, unknown> = Record<string, unknown>
20
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
21
+ /* end @cloudflare/workers-types */
22
+
23
+ type RouteHandler = {
24
+ routePath: string;
25
+ method?: HTTPMethod;
26
+ modules: PagesFunction[];
27
+ middlewares: PagesFunction[];
28
+ };
29
+
30
+ // inject `routes` via ESBuild
31
+ declare const routes: RouteHandler[];
32
+ // define `__FALLBACK_SERVICE__` via ESBuild
33
+ declare const __FALLBACK_SERVICE__: string;
34
+
35
+ // expect an ASSETS fetcher binding pointing to the asset-server stage
36
+ type FetchEnv = {
37
+ [name: string]: { fetch: typeof fetch };
38
+ ASSETS: { fetch: typeof fetch };
39
+ };
40
+
41
+ type WorkerContext = {
42
+ waitUntil: (promise: Promise<unknown>) => void;
43
+ };
44
+
45
+ function* executeRequest(request: Request, _env: FetchEnv) {
46
+ const requestPath = new URL(request.url).pathname;
47
+
48
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
49
+ for (const route of [...routes].reverse()) {
50
+ if (route.method && route.method !== request.method) {
51
+ continue;
52
+ }
53
+
54
+ const routeMatcher = match(route.routePath, { end: false });
55
+ const matchResult = routeMatcher(requestPath);
56
+ if (matchResult) {
57
+ for (const handler of route.middlewares.flat()) {
58
+ yield {
59
+ handler,
60
+ params: matchResult.params as Params,
61
+ };
62
+ }
63
+ }
64
+ }
65
+
66
+ // Then look for the first exact route match and execute its "modules"
67
+ for (const route of routes) {
68
+ if (route.method && route.method !== request.method) {
69
+ continue;
70
+ }
71
+
72
+ const routeMatcher = match(route.routePath, { end: true });
73
+ const matchResult = routeMatcher(requestPath);
74
+ if (matchResult && route.modules.length) {
75
+ for (const handler of route.modules.flat()) {
76
+ yield {
77
+ handler,
78
+ params: matchResult.params as Params,
79
+ };
80
+ }
81
+ break;
82
+ }
83
+ }
84
+ }
85
+
86
+ export default {
87
+ async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
88
+ const handlerIterator = executeRequest(request, env);
89
+ const data = {}; // arbitrary data the user can set between functions
90
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
91
+ if (input !== undefined) {
92
+ request = new Request(input, init);
93
+ }
94
+
95
+ const result = handlerIterator.next();
96
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
97
+ if (result.done == false) {
98
+ const { handler, params } = result.value;
99
+ const context = {
100
+ request: new Request(request.clone()),
101
+ next,
102
+ params,
103
+ data,
104
+ env,
105
+ waitUntil: workerContext.waitUntil.bind(workerContext),
106
+ };
107
+
108
+ const response = await handler(context);
109
+
110
+ // https://fetch.spec.whatwg.org/#null-body-status
111
+ return new Response(
112
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
113
+ response
114
+ );
115
+ } else if (__FALLBACK_SERVICE__) {
116
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
117
+ return env[__FALLBACK_SERVICE__].fetch(request);
118
+ } else {
119
+ // There was not fallback service so actually make the request to the origin.
120
+ return fetch(request);
121
+ }
122
+ };
123
+
124
+ try {
125
+ return next();
126
+ } catch (err) {
127
+ return new Response("Internal Error", { status: 500 });
128
+ }
129
+ },
130
+ };