next-workers-kit 2.0.1 → 2.0.3

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.
package/README.md CHANGED
@@ -63,6 +63,9 @@ export default config;
63
63
  `next.config.ts`, with a Content-Security-Policy added where the project has one:
64
64
 
65
65
  ```ts
66
+ import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare";
67
+ import type { NextConfig } from "next";
68
+ import { PHASE_DEVELOPMENT_SERVER } from "next/constants";
66
69
  import { securityHeaders } from "next-workers-kit/next";
67
70
 
68
71
  const nextConfig: NextConfig = {
@@ -71,6 +74,14 @@ const nextConfig: NextConfig = {
71
74
  headers: () =>
72
75
  Promise.resolve([{ source: "/:path*", headers: securityHeaders }]),
73
76
  };
77
+
78
+ export default function config(phase: string): NextConfig {
79
+ if (phase === PHASE_DEVELOPMENT_SERVER) {
80
+ void initOpenNextCloudflareForDev();
81
+ }
82
+
83
+ return nextConfig;
84
+ }
74
85
  ```
75
86
 
76
87
  **ESLint options**
@@ -105,7 +116,7 @@ Project-specific rules go after the spread, in the same `defineConfig` array.
105
116
  | Starter | `.gitignore`, `.prettierignore`, `knip.json`, `.mcp.json`, ESLint, Prettier and TS configs | Still contain the baseline entries; add your own freely |
106
117
  | Project | `package.json`, `next.config.ts`, `wrangler.jsonc`, `.dev.vars.example` | Baseline scripts, pins and settings; one `.dev.vars.example` line per required secret |
107
118
 
108
- It also reports `.env*` files (OpenNext bundles them into the Worker; keep local secrets in `.dev.vars`) and `src/middleware.ts` (use `proxy.ts`).
119
+ It also requires `AGENTS.md`, `README.md`, `cloudflare-env.d.ts` and `open-next.config.ts`, and reports `.env` and `.env.*` files (OpenNext bundles them into the Worker; keep local secrets in `.dev.vars`) and `src/middleware.ts` (use `proxy.ts`).
109
120
 
110
121
  - `npx next-workers-kit sync` rewrites the synced files and sets `packageManager` to the latest npm. Run it after upgrading this package.
111
122
  - `npx next-workers-kit init` runs `sync` and writes any missing starter files. It never overwrites your files.
package/dist/cli.js CHANGED
@@ -14,10 +14,11 @@ else if (action === "doctor") {
14
14
  const problems = doctor(root);
15
15
  if (problems.length) {
16
16
  console.error(`${command} doctor found ${String(problems.length)} problem(s):\n${problems.map((problem) => ` ${problem}`).join("\n")}`);
17
- process.exit(1);
17
+ // exitCode, not exit(), so piped output is flushed first.
18
+ process.exitCode = 1;
18
19
  }
19
20
  }
20
21
  else {
21
22
  console.error(`Usage: ${command} <init|sync|doctor>`);
22
- process.exit(1);
23
+ process.exitCode = 1;
23
24
  }
package/dist/eslint.js CHANGED
@@ -115,7 +115,7 @@ function imports() {
115
115
  paths: [{ name: "framer-motion", message: "Use motion/react." }],
116
116
  patterns: [
117
117
  {
118
- regex: "^\\.\\./(?!.*/messages/)",
118
+ regex: "^\\.\\./(?!(?:.*/)?messages/)",
119
119
  message: "Import with @/ instead of reaching into parent folders.",
120
120
  },
121
121
  ],
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { command, configKey, packageName } from "../meta.js";
4
- import { synced } from "./files.js";
4
+ import { normalize, render, synced } from "./files.js";
5
5
  import { parseJsonc } from "./jsonc.js";
6
6
  export const scripts = {
7
7
  dev: "next dev",
@@ -50,23 +50,32 @@ const required = [
50
50
  "next.config.ts",
51
51
  "wrangler.jsonc",
52
52
  ];
53
- function normalize(text) {
54
- return text.replace(/\r\n/g, "\n");
53
+ function isObject(value) {
54
+ return typeof value === "object" && value !== null && !Array.isArray(value);
55
55
  }
56
56
  // Ignore-file entries, compared without leading or trailing slashes so
57
- // "dir", "/dir" and "dir/" match.
57
+ // "dir", "/dir" and "dir/" match, and "!dir" and "!/dir" when negated.
58
58
  function ignoreEntry(line) {
59
- return line.trim().replace(/^\/|\/$/g, "");
59
+ return line
60
+ .trim()
61
+ .replace(/^(!?)\//, "$1")
62
+ .replace(/\/$/, "");
60
63
  }
61
64
  function lines(text) {
62
- return new Set(normalize(text).split("\n").map(ignoreEntry));
65
+ return new Set(text.split("\n").map(ignoreEntry));
66
+ }
67
+ // Variable names in a dotenv file such as .dev.vars.
68
+ function variables(text) {
69
+ return new Set(text
70
+ .split("\n")
71
+ .map((line) => /^\s*(?:export\s+)?([^\s=#]+)\s*=/.exec(line)?.[1]));
63
72
  }
64
73
  export function doctor(root) {
65
74
  const problems = [];
66
75
  const report = (file, message) => problems.push(`${file}: ${message}`);
67
76
  const read = (file) => {
68
77
  const path = join(root, file);
69
- return existsSync(path) ? readFileSync(path, "utf8") : undefined;
78
+ return existsSync(path) ? normalize(readFileSync(path, "utf8")) : undefined;
70
79
  };
71
80
  const json = (file) => {
72
81
  const text = read(file);
@@ -89,13 +98,12 @@ export function doctor(root) {
89
98
  }
90
99
  for (const [file, source] of Object.entries(synced)) {
91
100
  const text = read(file);
92
- if (text === undefined ||
93
- normalize(text) !== normalize(readFileSync(source, "utf8"))) {
101
+ if (text === undefined || text !== normalize(render(source))) {
94
102
  report(file, `${text === undefined ? "missing" : "differs from the baseline"}; run npx ${command} sync`);
95
103
  }
96
104
  }
97
105
  for (const entry of readdirSync(root)) {
98
- if (entry.startsWith(".env")) {
106
+ if (/^\.env(?:\..+)?$/.test(entry)) {
99
107
  report(entry, "env files are not used; keep local secrets in .dev.vars");
100
108
  }
101
109
  }
@@ -119,8 +127,20 @@ export function doctor(root) {
119
127
  const pkg = json("package.json");
120
128
  if (pkg) {
121
129
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
122
- const exceptions = (pkg[configKey] ?? {});
123
- const overrides = exceptions.scripts ?? {};
130
+ // Exceptions a project declares, so they stay visible in review.
131
+ const exceptions = pkg[configKey] ?? {};
132
+ let overrides = {};
133
+ if (!isObject(exceptions)) {
134
+ report("package.json", `${configKey} must be an object`);
135
+ }
136
+ else if (exceptions.scripts !== undefined &&
137
+ !(isObject(exceptions.scripts) &&
138
+ Object.values(exceptions.scripts).every((script) => typeof script === "string"))) {
139
+ report("package.json", `${configKey}.scripts must map script names to commands`);
140
+ }
141
+ else {
142
+ overrides = (exceptions.scripts ?? {});
143
+ }
124
144
  if ("check" in overrides) {
125
145
  report("package.json", `${configKey}.scripts can't override check, which runs ${command} doctor`);
126
146
  }
@@ -134,12 +154,15 @@ export function doctor(root) {
134
154
  if (!/^>=24(?:\.\d+){0,2} <25$/.test(pkg.engines?.node ?? "")) {
135
155
  report("package.json", 'engines.node must be ">=24 <25" (or a higher Node 24 minimum)');
136
156
  }
137
- const npm = /^npm@(\d+)\.\d+\.\d+$/.exec(pkg.packageManager ?? "");
157
+ // An exact version, optionally with the hash Corepack adds.
158
+ const npm = /^npm@(\d+)\.\d+\.\d+(?:\+sha\d+\.[\da-f]+)?$/.exec(pkg.packageManager ?? "");
138
159
  if (!npm || Number(npm[1]) < 12) {
139
160
  report("package.json", `packageManager must name an exact npm 12 or later; npx ${command} sync sets the latest`);
140
161
  }
141
- if (deps.typescript !== "6.0.3") {
142
- report("package.json", 'typescript must be exactly "6.0.3"');
162
+ // An exact pin within the peer range: typescript-eslint supports TypeScript below 6.1.
163
+ const typescript = /^6\.0\.(\d+)$/.exec(deps.typescript ?? "");
164
+ if (!typescript || Number(typescript[1]) < 3) {
165
+ report("package.json", "typescript must be an exact 6.0 version, 6.0.3 or later");
143
166
  }
144
167
  if (deps["eslint-config-next"] !== deps.next) {
145
168
  report("package.json", "eslint-config-next must match the next version");
@@ -233,20 +256,22 @@ export function doctor(root) {
233
256
  if (wrangler.observability?.enabled !== true) {
234
257
  report("wrangler.jsonc", "set observability.enabled: true");
235
258
  }
236
- if (!wrangler.routes?.length) {
237
- report("wrangler.jsonc", "declare the site's custom domains in routes");
238
- }
239
- else if (wrangler.dev?.host !== "localhost") {
259
+ if (wrangler.routes?.length && wrangler.dev?.host !== "localhost") {
240
260
  report("wrangler.jsonc", 'set dev.host: "localhost" so local previews do not use the first route');
241
261
  }
242
262
  const secrets = wrangler.secrets?.required ?? [];
243
- if (secrets.length) {
263
+ if (!Array.isArray(secrets) ||
264
+ !secrets.every((secret) => typeof secret === "string")) {
265
+ report("wrangler.jsonc", "secrets.required must be a list of names");
266
+ }
267
+ else if (secrets.length) {
244
268
  const example = read(".dev.vars.example");
245
269
  if (example === undefined) {
246
270
  report(".dev.vars.example", "missing; list the names in secrets.required");
247
271
  }
248
272
  else {
249
- for (const name of secrets.filter((secret) => !new RegExp(`^${secret}=`, "m").test(example))) {
273
+ const present = variables(example);
274
+ for (const name of secrets.filter((secret) => !present.has(secret))) {
250
275
  report(".dev.vars.example", `add ${name}=`);
251
276
  }
252
277
  }
@@ -1,2 +1,4 @@
1
1
  export declare const synced: Record<string, string>;
2
2
  export declare const starters: Record<string, string>;
3
+ export declare function render(source: string): string;
4
+ export declare function normalize(text: string): string;
package/dist/lib/files.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import { join } from "node:path";
2
- import { packageRoot } from "../meta.js";
3
+ import { packageName, packageRoot } from "../meta.js";
3
4
  const templates = join(packageRoot, "templates");
4
5
  // Identical in every project and owned by this package: `sync` writes them,
5
6
  // `doctor` fails when they differ. npm drops dotfiles such as .npmrc from
@@ -14,8 +15,7 @@ export const synced = {
14
15
  ".github/dependabot.yml": join(templates, "synced", "dependabot.yml"),
15
16
  };
16
17
  // Owned by the project, which may add to them. `init` writes them once;
17
- // `doctor` checks that they still contain the baseline. "{{package}}" in a
18
- // starter becomes this package's name.
18
+ // `doctor` checks that they still contain the baseline.
19
19
  export const starters = {
20
20
  ".gitignore": join(templates, "init", "gitignore"),
21
21
  ".prettierignore": join(templates, "init", "prettierignore"),
@@ -25,3 +25,11 @@ export const starters = {
25
25
  "prettier.config.mjs": join(templates, "init", "prettier.config.mjs"),
26
26
  "tsconfig.json": join(templates, "init", "tsconfig.json"),
27
27
  };
28
+ // A template as written into a project: "{{package}}" becomes this package's name.
29
+ export function render(source) {
30
+ return readFileSync(source, "utf8").replaceAll("{{package}}", packageName);
31
+ }
32
+ // Text as compared, without a byte order mark or Windows line endings.
33
+ export function normalize(text) {
34
+ return text.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
35
+ }
package/dist/lib/jsonc.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Parses JSON with comments and trailing commas, as in wrangler.jsonc.
2
2
  export function parseJsonc(text) {
3
3
  let out = "";
4
- let i = 0;
4
+ let i = text.startsWith("\uFEFF") ? 1 : 0;
5
5
  while (i < text.length) {
6
6
  const char = text[i];
7
7
  if (char === '"') {
@@ -23,9 +23,16 @@ export function parseJsonc(text) {
23
23
  i = end === -1 ? text.length : end + 2;
24
24
  }
25
25
  else {
26
+ // Drop a trailing comma; commas inside strings were copied above.
27
+ if (char === "}" || char === "]") {
28
+ const last = out.trimEnd();
29
+ if (last.endsWith(",")) {
30
+ out = last.slice(0, -1);
31
+ }
32
+ }
26
33
  out += char;
27
34
  i += 1;
28
35
  }
29
36
  }
30
- return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
37
+ return JSON.parse(out);
31
38
  }
package/dist/lib/sync.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
- import { packageName } from "../meta.js";
4
- import { starters, synced } from "./files.js";
3
+ import { normalize, render, starters, synced } from "./files.js";
5
4
  function write(root, files, overwrite) {
6
5
  const written = [];
7
6
  for (const [target, source] of Object.entries(files)) {
8
7
  const path = join(root, target);
9
- const content = readFileSync(source, "utf8").replaceAll("{{package}}", packageName);
8
+ const content = render(source);
9
+ // Line endings and a byte order mark don't count, as in doctor.
10
10
  if (existsSync(path) &&
11
- (!overwrite || readFileSync(path, "utf8") === content)) {
11
+ (!overwrite ||
12
+ normalize(readFileSync(path, "utf8")) === normalize(content))) {
12
13
  continue;
13
14
  }
14
15
  mkdirSync(dirname(path), { recursive: true });
@@ -24,22 +25,41 @@ async function latestNpm(root) {
24
25
  if (!existsSync(path)) {
25
26
  return [];
26
27
  }
28
+ let version;
27
29
  try {
28
- const response = await fetch("https://registry.npmjs.org/npm/latest");
29
- const { version } = (await response.json());
30
- const text = readFileSync(path, "utf8");
31
- const pkg = JSON.parse(text);
32
- const packageManager = `npm@${version}`;
33
- if (pkg.packageManager === packageManager) {
34
- return [];
30
+ const response = await fetch("https://registry.npmjs.org/npm/latest", {
31
+ signal: AbortSignal.timeout(15_000),
32
+ });
33
+ if (response.ok) {
34
+ ({ version } = (await response.json()));
35
35
  }
36
- pkg.packageManager = packageManager;
37
- writeFileSync(path, `${JSON.stringify(pkg, null, 2)}\n`);
38
- return [`package.json (packageManager ${packageManager})`];
39
36
  }
40
37
  catch {
38
+ // Offline or the registry is down; reported below.
39
+ }
40
+ if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) {
41
+ console.warn("Couldn't look up the latest npm, so packageManager is unchanged.");
42
+ return [];
43
+ }
44
+ const text = readFileSync(path, "utf8");
45
+ let pkg;
46
+ try {
47
+ pkg = JSON.parse(normalize(text));
48
+ }
49
+ catch {
50
+ console.warn("package.json is not valid JSON, so packageManager is unchanged.");
51
+ return [];
52
+ }
53
+ const packageManager = `npm@${version}`;
54
+ if (pkg.packageManager === packageManager) {
41
55
  return [];
42
56
  }
57
+ // Keep the file's indentation and line endings, as npm does.
58
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
59
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
60
+ pkg.packageManager = packageManager;
61
+ writeFileSync(path, `${JSON.stringify(pkg, null, indent)}\n`.replace(/\n/g, eol));
62
+ return [`package.json (packageManager ${packageManager})`];
43
63
  }
44
64
  export async function sync(root, { packageManager = true } = {}) {
45
65
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-workers-kit",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "Config, structure rules and drift checks for Next.js on Cloudflare Workers (OpenNext): ESLint, TypeScript, Prettier and a project doctor",
5
5
  "license": "MIT",
6
6
  "author": "pnilssson",
@@ -34,7 +34,7 @@
34
34
  "node": ">=24 <25"
35
35
  },
36
36
  "scripts": {
37
- "build": "tsc",
37
+ "build": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\" && tsc",
38
38
  "prepack": "npm run build",
39
39
  "test": "npm run build && node --test test/*.test.js",
40
40
  "format": "prettier --write .",