Skip to content

Commit 3723079

Browse files
committed
pr feedback
1 parent 74f28ea commit 3723079

File tree

4 files changed

+76
-31
lines changed

4 files changed

+76
-31
lines changed

packages/create-cloudflare/e2e-tests/frameworks.test.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,12 @@ describe.concurrent(
8080
});
8181

8282
Object.entries(frameworkTests).forEach(([frameworkKey, testConfig]) => {
83-
const frameworkConfig = getFrameworkConfig(frameworkKey);
84-
frameworkConfig.workersTypes ??= "generated";
85-
frameworkConfig.typesPath ??= "worker-configuration.d.ts";
86-
frameworkConfig.envInterfaceName ??= "Env";
83+
const frameworkConfig = {
84+
workersTypes: "generated" as const,
85+
typesPath: "worker-configuration.d.ts",
86+
envInterfaceName: "Env",
87+
...getFrameworkConfig(frameworkKey),
88+
};
8789
test({ experimental }).runIf(
8890
shouldRunTest(frameworkConfig.id, testConfig),
8991
)(

packages/create-cloudflare/src/__tests__/workers.test.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ describe("updateTsConfig", () => {
3838
test("installing workers types", async () => {
3939
ctx.template.workersTypes = "installed";
4040

41-
await updateTsConfig(ctx);
41+
await updateTsConfig(ctx, false);
4242

4343
expect(writeFile).toHaveBeenCalled();
4444

@@ -49,15 +49,15 @@ describe("updateTsConfig", () => {
4949

5050
test("tsconfig.json not found", async () => {
5151
vi.mocked(existsSync).mockImplementation(() => false);
52-
await updateTsConfig(ctx);
52+
await updateTsConfig(ctx, false);
5353
expect(writeFile).not.toHaveBeenCalled();
5454
});
5555

5656
test("latest entrypoint not found", async () => {
5757
ctx.template.workersTypes = "installed";
5858

5959
vi.mocked(getLatestTypesEntrypoint).mockReturnValue(null);
60-
await updateTsConfig(ctx);
60+
await updateTsConfig(ctx, false);
6161

6262
expect(writeFile).not.toHaveBeenCalled();
6363
});
@@ -68,7 +68,7 @@ describe("updateTsConfig", () => {
6868
() =>
6969
`{ "compilerOptions": { "types" : ["@cloudflare/workers-types/2021-03-20"]} }`,
7070
);
71-
await updateTsConfig(ctx);
71+
await updateTsConfig(ctx, false);
7272

7373
expect(vi.mocked(writeFile).mock.calls[0][1]).toContain(
7474
`"@cloudflare/workers-types/2021-03-20"`,
@@ -77,14 +77,13 @@ describe("updateTsConfig", () => {
7777

7878
test("will remove workers-types when generating types, if generated types include runtime types", async () => {
7979
vi.mocked(readFile).mockImplementation((path) => {
80-
console.log("path", path);
8180
if (path.includes("tsconfig.json")) {
8281
return `{ "compilerOptions": { "types" : ["@cloudflare/workers-types/2021-03-20"]} }`;
8382
} else {
8483
return "// Runtime types generated with workerd";
8584
}
8685
});
87-
await updateTsConfig(ctx);
86+
await updateTsConfig(ctx, false);
8887
expect(vi.mocked(writeFile).mock.calls[0][1]).not.toContain(
8988
`"@cloudflare/workers-types/2021-03-20"`,
9089
);
@@ -98,15 +97,15 @@ describe("updateTsConfig", () => {
9897
return "no runtime types here";
9998
}
10099
});
101-
await updateTsConfig(ctx);
100+
await updateTsConfig(ctx, false);
102101

103102
expect(vi.mocked(writeFile).mock.calls[0][1]).toContain(
104103
`"@cloudflare/workers-types/2021-03-20"`,
105104
);
106105
});
107106

108107
test("will add generated types file", async () => {
109-
await updateTsConfig(ctx);
108+
await updateTsConfig(ctx, false);
110109
expect(vi.mocked(writeFile).mock.calls[0][1]).toContain(
111110
`./worker-configuration.d.ts`,
112111
);

packages/create-cloudflare/src/templates.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export type TemplateConfig = {
142142
/** The key of the package.json "scripts" entry for previewing the project. Defaults to undefined (there might not be such script) */
143143
previewScript?: string;
144144

145-
/** The file path to the generated types file. Defaults to worker-configuration.d.ts*/
145+
/** The path to the generated types file. Defaults to `worker-configuration.d.ts` */
146146
typesPath?: string;
147147
/** The name of the Env type generated by wrangler types. Defaults to `Env`*/
148148
envInterfaceName?: string;
@@ -152,7 +152,12 @@ export type TemplateConfig = {
152152

153153
bindings?: Record<string, unknown>;
154154

155-
/** Default false. To accomodate SSG frameworks etc. */
155+
/**
156+
* Source for runtime types:
157+
* "generated" = types are generated by wrangler types. Default.
158+
* "installed" = types are installed from @cloudflare/workers-types.
159+
* "none" = no runtime types are provided (e.g. framework for purely static sites).
160+
*/
156161
workersTypes?: "generated" | "installed" | "none";
157162
};
158163

@@ -565,6 +570,13 @@ export const createContext = async (
565570
}
566571
}
567572

573+
template = {
574+
workersTypes: "generated",
575+
typesPath: "worker-configuration.d.ts",
576+
envInterfaceName: "Env",
577+
...template,
578+
};
579+
568580
const path = resolve(projectName);
569581
const languageVariants =
570582
template.copyFiles &&
@@ -613,10 +625,6 @@ export const createContext = async (
613625
const directory = dirname(path);
614626
const originalCWD = process.cwd();
615627

616-
// set default to generate types
617-
template.workersTypes ??= "generated";
618-
template.typesPath ??= "worker-configuration.d.ts";
619-
template.envInterfaceName ??= "Env";
620628
return {
621629
project: { name, path },
622630
// We need to maintain a reference to the original args

packages/create-cloudflare/src/workers.ts

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
import { existsSync } from "fs";
2-
import { join, resolve } from "path";
2+
import { join } from "path";
33
import { warn } from "@cloudflare/cli";
44
import { brandColor, dim } from "@cloudflare/cli/colors";
5+
import TOML from "@iarna/toml";
56
import { runCommand } from "helpers/command";
67
import { getLatestTypesEntrypoint } from "helpers/compatDate";
78
import { readFile, readJSON, usesTypescript, writeFile } from "helpers/files";
89
import { detectPackageManager } from "helpers/packageManagers";
910
import { installPackages } from "helpers/packages";
11+
import { parse as jsoncParse } from "jsonc-parser";
1012
import * as jsonc from "jsonc-parser";
13+
import {
14+
readWranglerJson,
15+
readWranglerToml,
16+
wranglerJsonExists,
17+
wranglerTomlExists,
18+
} from "./wrangler/config";
1119
import type { C3Context, PackageJson } from "types";
1220

1321
/**
@@ -18,9 +26,12 @@ export async function generateWorkersTypes(ctx: C3Context) {
1826
if (!usesTypescript(ctx)) {
1927
return;
2028
}
21-
const packageJsonPath = resolve("package.json");
29+
const packageJsonPath = join(ctx.project.path, "package.json");
30+
if (!existsSync(packageJsonPath)) {
31+
return;
32+
}
2233
const packageManifest = readJSON(packageJsonPath) as PackageJson;
23-
if (!Object.keys(packageManifest.scripts ?? {}).includes("cf-typegen")) {
34+
if (!packageManifest.scripts?.["cf-typegen"]) {
2435
return;
2536
}
2637

@@ -35,19 +46,43 @@ export async function generateWorkersTypes(ctx: C3Context) {
3546
doneText: `${brandColor("generated")} ${dim(`to \`${ctx.template.typesPath}\` via \`${typesCmd.join(" ")}\``)}`,
3647
});
3748

38-
if (ctx.template.compatibilityFlags?.includes("nodejs_compat")) {
49+
const usesNodeCompat = await maybeInstallNodeTypes(ctx, npm);
50+
51+
delete packageManifest["devDependencies"]?.["@cloudflare/workers-types"];
52+
53+
writeFile(packageJsonPath, JSON.stringify(packageManifest, null, 2));
54+
await updateTsConfig(ctx, usesNodeCompat);
55+
}
56+
57+
const maybeInstallNodeTypes = async (ctx: C3Context, npm: string) => {
58+
let parsedConfig: Record<string, unknown> = {};
59+
if (wranglerJsonExists(ctx)) {
60+
const wranglerJsonStr = readWranglerJson(ctx);
61+
parsedConfig = jsoncParse(wranglerJsonStr, undefined, {
62+
allowTrailingComma: true,
63+
});
64+
} else if (wranglerTomlExists(ctx)) {
65+
const wranglerTomlStr = readWranglerToml(ctx);
66+
parsedConfig = TOML.parse(wranglerTomlStr);
67+
}
68+
69+
const compatibility_flags = Array.isArray(parsedConfig["compatibility_flags"])
70+
? parsedConfig["compatibility_flags"]
71+
: [];
72+
73+
if (
74+
compatibility_flags.includes("nodejs_compat") ||
75+
compatibility_flags.includes("nodejs_compat_v2")
76+
) {
3977
await installPackages(["@types/node"], {
4078
dev: true,
4179
startText: "Installing @types/node",
4280
doneText: `${brandColor("installed")} ${dim(`via ${npm}`)}`,
4381
});
82+
return true;
4483
}
45-
46-
delete packageManifest["devDependencies"]?.["@cloudflare/workers-types"];
47-
48-
writeFile(packageJsonPath, JSON.stringify(packageManifest, null, 2));
49-
await updateTsConfig(ctx);
50-
}
84+
return false;
85+
};
5186

5287
/**
5388
* update `types` in tsconfig:
@@ -56,7 +91,7 @@ export async function generateWorkersTypes(ctx: C3Context) {
5691
* - add generated types file if types were generated
5792
* - add node if node compat
5893
*/
59-
export async function updateTsConfig(ctx: C3Context) {
94+
export async function updateTsConfig(ctx: C3Context, usesNodeCompat: boolean) {
6095
const tsconfigPath = join(ctx.project.path, "tsconfig.json");
6196
if (!existsSync(tsconfigPath)) {
6297
return;
@@ -99,7 +134,7 @@ export async function updateTsConfig(ctx: C3Context) {
99134
);
100135
}
101136
// add node types if nodejs_compat is enabled
102-
if (ctx.template.compatibilityFlags?.includes("nodejs_compat")) {
137+
if (usesNodeCompat) {
103138
newTypes.push("node");
104139
}
105140
}
@@ -143,5 +178,6 @@ export async function installWorkersTypes(ctx: C3Context) {
143178
startText: "Installing @cloudflare/workers-types",
144179
doneText: `${brandColor("installed")} ${dim(`via ${npm}`)}`,
145180
});
146-
await updateTsConfig(ctx);
181+
const usesNodeCompat = await maybeInstallNodeTypes(ctx, npm);
182+
await updateTsConfig(ctx, usesNodeCompat);
147183
}

0 commit comments

Comments
 (0)