wrangler 0.0.0-dfa31a7 → 0.0.0-e0d2f35

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 (62) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +75 -24
  5. package/pages/functions/buildWorker.ts +62 -0
  6. package/pages/functions/filepath-routing.test.ts +39 -0
  7. package/pages/functions/filepath-routing.ts +228 -0
  8. package/pages/functions/identifiers.ts +78 -0
  9. package/pages/functions/routes.ts +158 -0
  10. package/pages/functions/template-worker.ts +136 -0
  11. package/src/__tests__/clipboardy-mock.js +4 -0
  12. package/src/__tests__/dev.test.tsx +71 -0
  13. package/src/__tests__/index.test.ts +424 -0
  14. package/src/__tests__/jest.setup.ts +29 -0
  15. package/src/__tests__/kv.test.ts +1224 -0
  16. package/src/__tests__/logout.test.ts +64 -0
  17. package/src/__tests__/mock-cfetch.ts +173 -0
  18. package/src/__tests__/mock-console.ts +34 -0
  19. package/src/__tests__/mock-dialogs.ts +65 -0
  20. package/src/__tests__/mock-kv.ts +40 -0
  21. package/src/__tests__/mock-user.ts +27 -0
  22. package/src/__tests__/publish.test.ts +1206 -0
  23. package/src/__tests__/run-in-tmp.ts +29 -0
  24. package/src/__tests__/run-wrangler.ts +8 -0
  25. package/src/__tests__/secret.test.ts +206 -0
  26. package/src/__tests__/whoami.test.tsx +101 -0
  27. package/src/api/form_data.ts +135 -0
  28. package/src/api/preview.ts +128 -0
  29. package/src/api/worker.ts +155 -0
  30. package/src/cfetch/index.ts +111 -0
  31. package/src/cfetch/internal.ts +71 -0
  32. package/src/cli.ts +9 -0
  33. package/src/config.ts +641 -0
  34. package/src/dev.tsx +830 -0
  35. package/src/dialogs.tsx +77 -0
  36. package/src/index.tsx +2078 -0
  37. package/src/inspect.ts +595 -0
  38. package/src/kv.tsx +276 -0
  39. package/src/module-collection.ts +63 -0
  40. package/src/pages.tsx +1043 -0
  41. package/src/proxy.ts +370 -0
  42. package/src/publish.ts +410 -0
  43. package/src/sites.tsx +240 -0
  44. package/src/tail.tsx +73 -0
  45. package/src/user.tsx +1019 -0
  46. package/src/whoami.tsx +69 -0
  47. package/{facade.js → static-asset-facade.js} +2 -7
  48. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +262 -192
  49. package/vendor/@cloudflare/kv-asset-handler/package.json +1 -1
  50. package/vendor/{mime → wrangler-mime}/CHANGELOG.md +0 -0
  51. package/vendor/{mime → wrangler-mime}/LICENSE +0 -0
  52. package/vendor/{mime → wrangler-mime}/Mime.js +0 -0
  53. package/vendor/{mime → wrangler-mime}/README.md +0 -0
  54. package/vendor/{mime → wrangler-mime}/cli.js +0 -0
  55. package/vendor/{mime → wrangler-mime}/index.js +0 -0
  56. package/vendor/{mime → wrangler-mime}/lite.js +0 -0
  57. package/vendor/{mime → wrangler-mime}/package.json +1 -1
  58. package/vendor/{mime → wrangler-mime}/types/other.js +0 -0
  59. package/vendor/{mime → wrangler-mime}/types/standard.js +0 -0
  60. package/wrangler-dist/{index_node.js → cli.js} +81242 -51503
  61. package/wrangler-dist/cli.js.map +7 -0
  62. package/wrangler-dist/index_node.js.map +0 -7
@@ -0,0 +1,158 @@
1
+ import path from "path";
2
+ import fs from "fs/promises";
3
+ import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
+
5
+ export const HTTP_METHODS = [
6
+ "HEAD",
7
+ "OPTIONS",
8
+ "GET",
9
+ "POST",
10
+ "PUT",
11
+ "PATCH",
12
+ "DELETE",
13
+ ] as const;
14
+ export type HTTPMethod = typeof HTTP_METHODS[number];
15
+ export function isHTTPMethod(
16
+ maybeHTTPMethod: string
17
+ ): maybeHTTPMethod is HTTPMethod {
18
+ return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
19
+ }
20
+
21
+ export type RoutesCollection = Array<{
22
+ routePath: string;
23
+ methods: HTTPMethod[];
24
+ modules: string[];
25
+ middlewares: string[];
26
+ }>;
27
+
28
+ export type Config = {
29
+ routes?: RoutesConfig;
30
+ schedules?: unknown;
31
+ };
32
+
33
+ export type RoutesConfig = {
34
+ [route: string]: RouteConfig;
35
+ };
36
+
37
+ export type RouteConfig = {
38
+ middleware?: string | string[];
39
+ module?: string | string[];
40
+ };
41
+
42
+ type ImportMap = Map<
43
+ string,
44
+ {
45
+ filepath: string;
46
+ name: string;
47
+ identifier: string;
48
+ }
49
+ >;
50
+
51
+ type Arguments = {
52
+ config: Config;
53
+ outfile: string;
54
+ srcDir: string;
55
+ };
56
+
57
+ export async function writeRoutesModule({
58
+ config,
59
+ srcDir,
60
+ outfile = "_routes.js",
61
+ }: Arguments) {
62
+ const { importMap, routes } = parseConfig(config, srcDir);
63
+ const routesModule = generateRoutesModule(importMap, routes);
64
+
65
+ await fs.writeFile(outfile, routesModule);
66
+
67
+ return outfile;
68
+ }
69
+
70
+ export function parseConfig(config: Config, baseDir: string) {
71
+ const routes: RoutesCollection = [];
72
+ const importMap: ImportMap = new Map();
73
+ const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
74
+
75
+ function parseModuleIdentifiers(paths: string | string[] | undefined) {
76
+ if (typeof paths === "undefined") {
77
+ paths = [];
78
+ }
79
+
80
+ if (typeof paths === "string") {
81
+ paths = [paths];
82
+ }
83
+
84
+ return paths.map((modulePath) => {
85
+ const [filepath, name = "default"] = modulePath.split(":");
86
+ let { identifier } = importMap.get(modulePath) ?? {};
87
+
88
+ const resolvedPath = path.resolve(baseDir, filepath);
89
+
90
+ // ensure the filepath isn't attempting to resolve to anything outside of the project
91
+ if (path.relative(baseDir, resolvedPath).startsWith("..")) {
92
+ throw new Error(`Invalid module path "${filepath}"`);
93
+ }
94
+
95
+ // ensure the module name (if provided) is a valid identifier to guard against injection attacks
96
+ if (name !== "default" && !isValidIdentifier(name)) {
97
+ throw new Error(`Invalid module identifier "${name}"`);
98
+ }
99
+
100
+ if (!identifier) {
101
+ identifier = normalizeIdentifier(`__${filepath}_${name}`);
102
+
103
+ let count = identifierCount.get(identifier) ?? 0;
104
+ identifierCount.set(identifier, ++count);
105
+
106
+ if (count > 1) {
107
+ identifier += `_${count}`;
108
+ }
109
+
110
+ importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
111
+ }
112
+
113
+ return identifier;
114
+ });
115
+ }
116
+
117
+ for (const [route, props] of Object.entries(config.routes ?? {})) {
118
+ let [_methods, routePath] = route.split(" ");
119
+ if (!routePath) {
120
+ routePath = _methods;
121
+ _methods = "";
122
+ }
123
+
124
+ routes.push({
125
+ routePath,
126
+ methods: _methods.split("|").filter(isHTTPMethod),
127
+ middlewares: parseModuleIdentifiers(props.middleware),
128
+ modules: parseModuleIdentifiers(props.module),
129
+ });
130
+ }
131
+
132
+ return { routes, importMap };
133
+ }
134
+
135
+ export function generateRoutesModule(
136
+ importMap: ImportMap,
137
+ routes: RoutesCollection
138
+ ) {
139
+ return `${[...importMap.values()]
140
+ .map(
141
+ ({ filepath, name, identifier }) =>
142
+ `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
143
+ )
144
+ .join("\n")}
145
+
146
+ export const routes = [
147
+ ${routes
148
+ .map(
149
+ (route) => ` {
150
+ routePath: "${route.routePath}",
151
+ methods: ${JSON.stringify(route.methods)},
152
+ middlewares: [${route.middlewares.join(", ")}],
153
+ modules: [${route.modules.join(", ")}],
154
+ },`
155
+ )
156
+ .join("\n")}
157
+ ]`;
158
+ }
@@ -0,0 +1,136 @@
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
+ methods: 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 (
51
+ route.methods.length &&
52
+ !route.methods.includes(request.method as HTTPMethod)
53
+ ) {
54
+ continue;
55
+ }
56
+
57
+ const routeMatcher = match(route.routePath, { end: false });
58
+ const matchResult = routeMatcher(requestPath);
59
+ if (matchResult) {
60
+ for (const handler of route.middlewares.flat()) {
61
+ yield {
62
+ handler,
63
+ params: matchResult.params as Params,
64
+ };
65
+ }
66
+ }
67
+ }
68
+
69
+ // Then look for the first exact route match and execute its "modules"
70
+ for (const route of routes) {
71
+ if (
72
+ route.methods.length &&
73
+ !route.methods.includes(request.method as HTTPMethod)
74
+ ) {
75
+ continue;
76
+ }
77
+
78
+ const routeMatcher = match(route.routePath, { end: true });
79
+ const matchResult = routeMatcher(requestPath);
80
+ if (matchResult && route.modules.length) {
81
+ for (const handler of route.modules.flat()) {
82
+ yield {
83
+ handler,
84
+ params: matchResult.params as Params,
85
+ };
86
+ }
87
+ break;
88
+ }
89
+ }
90
+ }
91
+
92
+ export default {
93
+ async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
94
+ const handlerIterator = executeRequest(request, env);
95
+ const data = {}; // arbitrary data the user can set between functions
96
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
97
+ if (input !== undefined) {
98
+ request = new Request(input, init);
99
+ }
100
+
101
+ const result = handlerIterator.next();
102
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
103
+ if (result.done == false) {
104
+ const { handler, params } = result.value;
105
+ const context = {
106
+ request: new Request(request.clone()),
107
+ next,
108
+ params,
109
+ data,
110
+ env,
111
+ waitUntil: workerContext.waitUntil.bind(workerContext),
112
+ };
113
+
114
+ const response = await handler(context);
115
+
116
+ // https://fetch.spec.whatwg.org/#null-body-status
117
+ return new Response(
118
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
119
+ response
120
+ );
121
+ } else if (__FALLBACK_SERVICE__) {
122
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
123
+ return env[__FALLBACK_SERVICE__].fetch(request);
124
+ } else {
125
+ // There was not fallback service so actually make the request to the origin.
126
+ return fetch(request);
127
+ }
128
+ };
129
+
130
+ try {
131
+ return next();
132
+ } catch (err) {
133
+ return new Response("Internal Error", { status: 500 });
134
+ }
135
+ },
136
+ };
@@ -0,0 +1,4 @@
1
+ // We use this mock during tests because we're having trouble
2
+ // properly compiling clipboardy for jest
3
+ // We can revisit this if and when we write tests that test
4
+ // the copying part of `dev`
@@ -0,0 +1,71 @@
1
+ import { render } from "ink-testing-library";
2
+ import patchConsole from "patch-console";
3
+ import React from "react";
4
+ import Dev from "../dev";
5
+ import type { DevProps } from "../dev";
6
+
7
+ describe("Dev component", () => {
8
+ let restoreConsole;
9
+ beforeEach(() => (restoreConsole = patchConsole(() => {})));
10
+ afterEach(() => restoreConsole());
11
+
12
+ it("should throw if format is service-worker and there is a public directory", () => {
13
+ const { lastFrame } = renderDev({
14
+ format: "service-worker",
15
+ accountId: "some-account-id",
16
+ public: "some/public/path",
17
+ });
18
+ expect(lastFrame()?.split("\n").slice(0, 2).join("\n"))
19
+ .toMatchInlineSnapshot(`
20
+ "Something went wrong:
21
+ Error: You cannot use the service worker format with a \`public\` directory."
22
+ `);
23
+ });
24
+ });
25
+
26
+ /**
27
+ * Helper function to make it easier to setup and render the `Dev` component.
28
+ *
29
+ * All the `Dev` props are optional here, with sensible defaults for testing.
30
+ */
31
+ function renderDev({
32
+ name,
33
+ entry = "some/entry.ts",
34
+ port,
35
+ format,
36
+ accountId,
37
+ initialMode = "remote",
38
+ jsxFactory,
39
+ jsxFragment,
40
+ bindings = {},
41
+ public: publicDir,
42
+ assetPaths,
43
+ compatibilityDate,
44
+ compatibilityFlags,
45
+ usageModel,
46
+ buildCommand = {},
47
+ enableLocalPersistence = false,
48
+ env = undefined,
49
+ }: Partial<DevProps>) {
50
+ return render(
51
+ <Dev
52
+ name={name}
53
+ entry={entry}
54
+ env={env}
55
+ port={port}
56
+ buildCommand={buildCommand}
57
+ format={format}
58
+ initialMode={initialMode}
59
+ jsxFactory={jsxFactory}
60
+ jsxFragment={jsxFragment}
61
+ accountId={accountId}
62
+ assetPaths={assetPaths}
63
+ public={publicDir}
64
+ compatibilityDate={compatibilityDate}
65
+ compatibilityFlags={compatibilityFlags}
66
+ usageModel={usageModel}
67
+ bindings={bindings}
68
+ enableLocalPersistence={enableLocalPersistence}
69
+ />
70
+ );
71
+ }