@ingram-tech/nk-dev 0.19.0 → 0.21.0

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
@@ -83,11 +83,15 @@ tsc), so versions stay under your control. nk only orchestrates.
83
83
  (superseded deps, config `extends`, package.json scripts, the agent-guide
84
84
  import (from any CLAUDE.md up to the repository root), a stale
85
85
  `.prettierignore`, an unsealed migration chain and the DDL in it drizzle
86
- can't model, a page under `app/auth/` shadowing a Better Auth
86
+ can't model, routes in a root `app/` instead of `src/app/`, a page under
87
+ `src/app/auth/` shadowing a Better Auth
87
88
  endpoint — static segments beat the `[...all]` catch-all, so such a page
88
89
  silently 405s the endpoint, a page or layout whose `openGraph` carries no
89
90
  image — its own object replaces the inherited one, so the card unfurls as a
90
91
  blank placeholder); `--fix` applies the auto-fixable findings.
92
+ In a workspace it judges each package for its role: the root may fan
93
+ `type-check`/`ci` out to members, a member inherits nk-dev and `lint`/`format`
94
+ from the root, and only a Next app is asked for `nk type-check`.
91
95
  - **`nk dev`** — start the Next dev server on the golden-path local database
92
96
  (see [`db-package.md`](https://github.com/ingram-technologies/nextkit/blob/main/docs/db-package.md)):
93
97
  - **PGlite** — if `@ingram-tech/nk-db`'s `nk-pglite-dev` bin resolves, hand off
package/guide.md CHANGED
@@ -7,18 +7,21 @@ package. Stay a thin, standard Next.js app (bun · oxlint + oxfmt · strict TS).
7
7
  ## Hard rules
8
8
 
9
9
  - **Public contact/signup forms MUST use `@ingram-tech/nk-forms`** — one
10
- `createFormsHandler` registry at `app/internal/forms/[form]/route.ts`
10
+ `createFormsHandler` registry at `src/app/internal/forms/[form]/route.ts`
11
11
  (rate-limit → bot gate → validate → escaped-email deliver → uniform 200)
12
12
  and `useFormSubmit(formEndpoint(name))` + `HoneypotInput` client-side.
13
13
  Forms are plumbing, not API: never mount one under `/api/…` (see Route & URL
14
14
  conventions). For guarding a *non-form* endpoint (a checkout, an authed
15
15
  route), call nk-forms' `checkBot` / `verifyHuman` directly instead of the
16
16
  pipeline. Never ship a public form without the bot gate.
17
+ - **Routes live in `src/app/`, never a root `app/`.** Next prefers a root
18
+ `app/` and silently ignores `src/app/` when both exist, and nk's checks and
19
+ lint rules only look in `src/app/`. `nk doctor` rejects a root `app/`.
17
20
  - **Send email only via `@ingram-tech/nk-email`** — never add another mail client.
18
21
  - **Never trust an external request body's shape — validate it with Zod, never
19
22
  `as`-cast it.** Every `/api` route and webhook handler takes untrusted input;
20
23
  an `as` cast is a lie the type-checker can't catch at runtime.
21
- `nextkit/no-unvalidated-request-body` enforces this in `app/**/route.ts`:
24
+ `nextkit/no-unvalidated-request-body` enforces this in `src/app/**/route.ts`:
22
25
  cast the parsed body to `unknown` on the way into a schema, never to a shape.
23
26
  - Format/lint with **oxlint + oxfmt** via `nk` (`@ingram-tech/nk-dev`); don't
24
27
  reintroduce ESLint or Prettier (SQL isn't formatted — it's generated). nk-dev
@@ -39,7 +42,7 @@ package. Stay a thin, standard Next.js app (bun · oxlint + oxfmt · strict TS).
39
42
  Keep the URL namespace honest about **who calls each route**:
40
43
 
41
44
  - **`/auth/…` — sign-in, via `@ingram-tech/nk-auth`.** Better Auth mounts here
42
- through `basePath: authBasePath` (handler at `app/auth/[...all]/route.ts`,
45
+ through `basePath: authBasePath` (handler at `src/app/auth/[...all]/route.ts`,
43
46
  client `createAuthClient({ basePath: authBasePath })`) — **not** the framework
44
47
  default `/api/auth`. So **login / social OAuth callbacks are
45
48
  `<site>/auth/callback/<provider>`** (e.g. Google `…/auth/callback/google`) —
package/lib/app-dir.js ADDED
@@ -0,0 +1,34 @@
1
+ import { statSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+
4
+ // A Next site keeps its routes in `src/app/`, never a root `app/`. Next accepts
5
+ // both and silently prefers the root one when both exist, so a stray `app/`
6
+ // shadows the whole `src/app/` tree. nk's checks and lint rules (the endpoint
7
+ // shadow check, the OG image check, `no-redirect-only-page`, ...) only look in
8
+ // `src/app/`, so a root-`app/` site would also pass them without being checked.
9
+
10
+ const isDirectory = (path) => {
11
+ try {
12
+ return statSync(path).isDirectory();
13
+ } catch {
14
+ return false;
15
+ }
16
+ };
17
+
18
+ const dependsOnNext = (pkg) =>
19
+ Boolean(pkg.dependencies?.next ?? pkg.devDependencies?.next);
20
+
21
+ /** The "routes live in a root app/" finding, or nothing. */
22
+ export function appDirFindings(cwd, pkg) {
23
+ if (!dependsOnNext(pkg) || !isDirectory(resolve(cwd, "app"))) return [];
24
+ const both = isDirectory(resolve(cwd, "src/app"));
25
+ return [
26
+ {
27
+ id: "layout:root-app-dir",
28
+ level: "error",
29
+ message: both
30
+ ? "`app/` and `src/app/` both exist — Next serves `app/` and ignores `src/app/` entirely. Merge the routes into `src/app/` and delete `app/`."
31
+ : "routes live in a root `app/` — nextkit sites keep them in `src/app/`, the only place nk's checks and lint rules look. Move `app/` to `src/app/` and update tsconfig `paths` that point into it.",
32
+ },
33
+ ];
34
+ }
package/lib/auth-next.js CHANGED
@@ -10,7 +10,7 @@ import { join, relative, resolve } from "node:path";
10
10
  // this check catches it before the site is even run. Textual, like the
11
11
  // endpoint-shadow check: we grep the site's sources, never execute them.
12
12
 
13
- const SOURCE_DIRS = ["src", "app", "lib", "proxy.ts", "middleware.ts"];
13
+ const SOURCE_DIRS = ["src", "lib", "proxy.ts", "middleware.ts"];
14
14
  const SOURCE_FILES = /\.(ts|tsx|js|jsx|mjs)$/;
15
15
  const SKIP_DIRS = new Set(["node_modules", ".next", "dist", "build"]);
16
16
 
@@ -15,12 +15,11 @@ const ENDPOINT_RE = /createAuthEndpoint\(\s*"([^"]+)"/g;
15
15
 
16
16
  /** The `app/auth/[...all]` mount dir, or null when the site has no auth mount. */
17
17
  function findMount(cwd) {
18
- for (const appDir of ["src/app", "app"]) {
19
- const catchAll = resolve(cwd, appDir, "auth", "[...all]");
20
- for (const ext of ["ts", "js", "tsx", "jsx"]) {
21
- if (existsSync(join(catchAll, `route.${ext}`))) {
22
- return { appDir, authDir: resolve(cwd, appDir, "auth") };
23
- }
18
+ const appDir = "src/app";
19
+ const catchAll = resolve(cwd, appDir, "auth", "[...all]");
20
+ for (const ext of ["ts", "js", "tsx", "jsx"]) {
21
+ if (existsSync(join(catchAll, `route.${ext}`))) {
22
+ return { appDir, authDir: resolve(cwd, appDir, "auth") };
24
23
  }
25
24
  }
26
25
  return null;
package/lib/doctor.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2
- import { resolve } from "node:path";
2
+ import { dirname, relative, resolve, sep } from "node:path";
3
3
  import { checkAgentGuideImport, ensureGuideImport } from "./agent-guide.js";
4
+ import { appDirFindings } from "./app-dir.js";
4
5
  import { authNextFindings } from "./auth-next.js";
5
6
  import { authShadowFindings } from "./auth-shadow.js";
6
7
  import { authVersionFindings } from "./auth-version.js";
@@ -55,6 +56,59 @@ function readJson(file) {
55
56
  }
56
57
  }
57
58
 
59
+ /** A package.json `workspaces` field as a list of patterns. */
60
+ function workspacePatterns(pkg) {
61
+ const ws = pkg?.workspaces;
62
+ if (Array.isArray(ws)) return ws;
63
+ if (Array.isArray(ws?.packages)) return ws.packages;
64
+ return [];
65
+ }
66
+
67
+ /** True if `rel` (a `/`-separated path) matches a workspace pattern: a `*`
68
+ * segment matches any one segment, `**` any depth. */
69
+ function matchesWorkspace(rel, pattern) {
70
+ const want = pattern.replace(/^\.\//, "").replace(/\/$/, "").split("/");
71
+ const have = rel.split("/");
72
+ if (want.at(-1) === "**") {
73
+ return want.slice(0, -1).every((seg, i) => seg === "*" || seg === have[i]);
74
+ }
75
+ return (
76
+ want.length === have.length &&
77
+ want.every((seg, i) => seg === "*" || seg === have[i])
78
+ );
79
+ }
80
+
81
+ /**
82
+ * The workspace root that lists `cwd` as a member, or null. Walks up from the
83
+ * parent directory: the first package.json declaring `workspaces` decides.
84
+ */
85
+ function workspaceRootOf(cwd) {
86
+ let dir = dirname(cwd);
87
+ for (;;) {
88
+ const pkg = readJson(resolve(dir, "package.json"));
89
+ if (pkg && workspacePatterns(pkg).length > 0) {
90
+ const rel = relative(dir, cwd).split(sep).join("/");
91
+ return workspacePatterns(pkg).some((p) => matchesWorkspace(rel, p))
92
+ ? { dir, pkg }
93
+ : null;
94
+ }
95
+ const parent = dirname(dir);
96
+ if (parent === dir) return null;
97
+ dir = parent;
98
+ }
99
+ }
100
+
101
+ const NEXT_CONFIGS = [
102
+ "next.config.ts",
103
+ "next.config.mjs",
104
+ "next.config.js",
105
+ "next.config.cjs",
106
+ ];
107
+
108
+ /** A script that runs the same script in every workspace member. */
109
+ const DELEGATES_RE =
110
+ /(^|\s)(--filter|-F|--recursive|-r|--workspaces|-ws)(\s|=|$)|\bturbo\s+run\b/;
111
+
58
112
  /** Write JSON in the house style (tabs, trailing newline). */
59
113
  function writeJson(file, value) {
60
114
  writeFileSync(file, `${JSON.stringify(value, null, "\t")}\n`);
@@ -73,8 +127,22 @@ export function findings(cwd) {
73
127
  if (!pkg) return out; // not a package — nothing to reconcile
74
128
 
75
129
  // 1. Scripts point at `nk`. Accept either `type-check` or `typecheck` key.
130
+ // In a workspace: the root may fan `type-check` out to its members; a
131
+ // member leaves `lint`/`format` to a root that runs them; and only a Next
132
+ // app wants `nk type-check` (it runs `next typegen`), a library runs tsc.
76
133
  const scripts = pkg.scripts ?? {};
134
+ const isWorkspaceRoot = workspacePatterns(pkg).length > 0;
135
+ const delegates = (cmd) => isWorkspaceRoot && DELEGATES_RE.test(cmd ?? "");
136
+ const root = workspaceRootOf(cwd);
137
+ const isNextApp = NEXT_CONFIGS.some((f) => existsSync(resolve(cwd, f)));
138
+ const runsTsc = (cmd) => root !== null && !isNextApp && /\btsc\b/.test(cmd ?? "");
77
139
  for (const [name, wanted] of Object.entries(CANONICAL_SCRIPTS)) {
140
+ if (
141
+ (name === "lint" || name === "format") &&
142
+ root?.pkg.scripts?.[name] === wanted
143
+ ) {
144
+ continue;
145
+ }
78
146
  const key =
79
147
  name === "type-check" &&
80
148
  scripts["typecheck"] !== undefined &&
@@ -83,6 +151,7 @@ export function findings(cwd) {
83
151
  : name;
84
152
  const current = scripts[key];
85
153
  if (current === wanted) continue;
154
+ if (name === "type-check" && (delegates(current) || runsTsc(current))) continue;
86
155
  // Only flag `check` as missing if the repo has scripts at all; a repo
87
156
  // truly without a check script still wants one on the nk model.
88
157
  out.push({
@@ -103,9 +172,11 @@ export function findings(cwd) {
103
172
  });
104
173
  }
105
174
 
106
- // 2. Superseded deps still declared.
175
+ // 2. Superseded deps still declared. A workspace member inherits nk-dev
176
+ // from the root that declares it (one toolchain, hoisted).
107
177
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
108
- if (deps["@ingram-tech/nk-dev"]) {
178
+ const rootDeps = { ...root?.pkg.dependencies, ...root?.pkg.devDependencies };
179
+ if (deps["@ingram-tech/nk-dev"] || rootDeps["@ingram-tech/nk-dev"]) {
109
180
  const superseded = SUPERSEDED_DEPS.filter((d) => d in deps);
110
181
  for (const dep of superseded) {
111
182
  out.push({
@@ -225,33 +296,41 @@ export function findings(cwd) {
225
296
  // (even on a clean no-op) and hides journal drift.
226
297
  // `nk-pg-migrate` (@ingram-tech/nk-db) is the one runner that applies:
227
298
  // it surfaces the real Postgres error and pre-flights drift.
299
+ // The autofix rewrites the whole script, so it is only offered when
300
+ // drizzle-kit is the whole script: in a compound one (`build && drizzle-kit
301
+ // push`) the other steps are the site's, and only a human can split them.
228
302
  for (const [name, cmd] of Object.entries(scripts)) {
229
303
  if (typeof cmd !== "string") continue;
304
+ const compound = /[;&|]/.test(cmd);
230
305
  if (/\bdrizzle-kit\s+push\b/.test(cmd)) {
231
306
  out.push({
232
307
  id: `script:drizzle-push:${name}`,
233
308
  level: "error",
234
309
  message: `\`${name}\` runs \`drizzle-kit push\` — it applies schema to the live DB with no migration (drift). Generate a migration and apply it with \`nk-pg-migrate\`.`,
235
- fix: (dir) => {
236
- const p = resolve(dir, "package.json");
237
- const j = readJson(p);
238
- delete j.scripts?.[name];
239
- writeJson(p, j);
240
- return `removed \`${name}\` (drizzle-kit push)`;
241
- },
310
+ fix: compound
311
+ ? undefined
312
+ : (dir) => {
313
+ const p = resolve(dir, "package.json");
314
+ const j = readJson(p);
315
+ delete j.scripts?.[name];
316
+ writeJson(p, j);
317
+ return `removed \`${name}\` (drizzle-kit push)`;
318
+ },
242
319
  });
243
320
  } else if (/\bdrizzle-kit\s+migrate\b/.test(cmd)) {
244
321
  out.push({
245
322
  id: `script:drizzle-migrate:${name}`,
246
323
  level: "error",
247
324
  message: `\`${name}\` runs \`drizzle-kit migrate\` — apply with \`nk-pg-migrate\` instead (it surfaces the real error and pre-flights journal drift).`,
248
- fix: (dir) => {
249
- const p = resolve(dir, "package.json");
250
- const j = readJson(p);
251
- j.scripts[name] = "nk-pg-migrate";
252
- writeJson(p, j);
253
- return `set \`${name}\` → "nk-pg-migrate"`;
254
- },
325
+ fix: compound
326
+ ? undefined
327
+ : (dir) => {
328
+ const p = resolve(dir, "package.json");
329
+ const j = readJson(p);
330
+ j.scripts[name] = "nk-pg-migrate";
331
+ writeJson(p, j);
332
+ return `set \`${name}\` → "nk-pg-migrate"`;
333
+ },
255
334
  });
256
335
  }
257
336
  }
@@ -288,7 +367,9 @@ export function findings(cwd) {
288
367
  // 9. A `ci` script exists and runs the house gate. Its full contents are
289
368
  // the site's call (migrations, i18n, email catalogs, build…), so this only
290
369
  // warns and never writes — but the dep-upgrade flow and pre-push both
291
- // assume `bun run ci` is the one command that proves a change.
370
+ // assume `bun run ci` is the one command that proves a change. A
371
+ // workspace root that fans `ci` out to its members passes: each member's
372
+ // own `ci` is what this checks when doctor runs there.
292
373
  const ci = scripts["ci"];
293
374
  if (ci === undefined) {
294
375
  out.push({
@@ -297,9 +378,12 @@ export function findings(cwd) {
297
378
  message:
298
379
  'missing `ci` script — the one command that proves a change (e.g. "nk check && nk type-check && nk test")',
299
380
  });
300
- } else {
381
+ } else if (!delegates(ci)) {
301
382
  const missing = ["nk check", "nk type-check"].filter(
302
- (cmd) => !ci.includes(cmd) && !ci.includes(`bun run ${cmd.slice(3)}`),
383
+ (cmd) =>
384
+ !ci.includes(cmd) &&
385
+ !ci.includes(`bun run ${cmd.slice(3)}`) &&
386
+ !(cmd === "nk type-check" && runsTsc(ci)),
303
387
  );
304
388
  if (missing.length > 0) {
305
389
  out.push({
@@ -327,6 +411,9 @@ export function findings(cwd) {
327
411
  // 14. No page/layout declares an Open Graph card without an image in reach.
328
412
  out.push(...ogImageFindings(cwd));
329
413
 
414
+ // 15. Routes live in src/app/, never a root app/.
415
+ out.push(...appDirFindings(cwd, pkg));
416
+
330
417
  return out;
331
418
  }
332
419
 
@@ -396,6 +483,15 @@ function migrationFindings(cwd) {
396
483
  return out;
397
484
  }
398
485
 
486
+ /**
487
+ * The exit code for a report-only `nk doctor` run: non-zero only when there are
488
+ * model-breaking (error-level) findings, so `nk doctor` can gate CI while
489
+ * cosmetic warnings don't.
490
+ */
491
+ export function exitCodeFor(results) {
492
+ return results.some((r) => r.level === "error") ? 1 : 0;
493
+ }
494
+
399
495
  /**
400
496
  * `nk doctor [--fix]` — report drift from the canonical nk-dev model (scripts,
401
497
  * dependencies, oxlint/tsconfig extends, the CLAUDE.md guide import, stale knip
@@ -418,7 +514,6 @@ export function doctor(args = []) {
418
514
  }
419
515
 
420
516
  if (!fix) {
421
- const errors = results.filter((r) => r.level === "error").length;
422
517
  console.log(`nk doctor: ${results.length} finding(s):\n`);
423
518
  for (const r of results) {
424
519
  const mark = r.level === "error" ? "✗" : "•";
@@ -427,9 +522,7 @@ export function doctor(args = []) {
427
522
  console.log(
428
523
  `\n Run \`nk doctor --fix\` to apply the ${results.filter((r) => r.fix).length} auto-fixable one(s).`,
429
524
  );
430
- // Exit non-zero only when there are model-breaking findings, so `nk
431
- // doctor` can gate CI while cosmetic warnings don't.
432
- process.exit(errors > 0 ? 1 : 0);
525
+ process.exit(exitCodeFor(results));
433
526
  }
434
527
 
435
528
  let applied = 0;
package/lib/og-image.js CHANGED
@@ -18,11 +18,8 @@ const CARRIES_IMAGE = /\bimages\s*[:,}]|\bogImageMetadata\s*\(/;
18
18
 
19
19
  /** The site's app directory, or null when it has none. */
20
20
  function findAppDir(cwd) {
21
- for (const rel of ["src/app", "app"]) {
22
- const dir = resolve(cwd, rel);
23
- if (existsSync(dir)) return dir;
24
- }
25
- return null;
21
+ const dir = resolve(cwd, "src/app");
22
+ return existsSync(dir) ? dir : null;
26
23
  }
27
24
 
28
25
  /**
@@ -29,13 +29,18 @@
29
29
  // value, or a spread that might carry one, still reports: a spread is not
30
30
  // an explicit `nativeButton={false}`.
31
31
  //
32
- // Which components count: only the ones that actually accept `nativeButton`.
33
- // In @base-ui/react 1.8.0 that is Button, PopoverTrigger, Switch and the menu
34
- // items; every other *Trigger builds on useButton internally but does not
35
- // expose the prop, so demanding it there produces code that does not compile.
36
- // An earlier revision keyed on the `Button`/`Trigger` name suffixes and was
37
- // wrong on both counts: it reported design-system Buttons (which render a
38
- // native <button>) and Triggers that have no such prop.
32
+ // Which components count: only the ones whose `nativeButton` defaults to true.
33
+ // In @base-ui/react 1.8.0 Button and Popover.Trigger extend `NativeButtonProps`
34
+ // (default true). Menu items and Switch take the prop too, but extend
35
+ // `NonNativeButtonProps`: it defaults to false there, they render a <div> or
36
+ // <span> by default, and `render={<Link />}` on a menu item is already correct.
37
+ // Demanding `nativeButton={false}` on those would flag correct code. Other
38
+ // default-true parts (Menu.Trigger, Dialog.Trigger, Tabs.Tab, ...) are not
39
+ // listed yet; the list is exact names, never `Button`/`Trigger` suffixes, which
40
+ // would report design-system Buttons that render a native <button>.
41
+ //
42
+ // Hosts match by their shadcn wrapper name (`PopoverTrigger`) or by Base UI's
43
+ // namespace form (`Popover.Trigger`), which joins to the same name.
39
44
  //
40
45
  // The host must also be Base UI's own component. A locally defined
41
46
  // `SidebarMenuButton` shares the name and takes no such prop, so the name list
@@ -43,21 +48,17 @@
43
48
 
44
49
  import { fileUsesBaseUi } from "./base-ui-project.js";
45
50
 
46
- const NATIVE_BUTTON_PROP_COMPONENTS = new Set([
47
- "Button",
48
- "PopoverTrigger",
49
- "Switch",
50
- "MenuItem",
51
- ]);
51
+ const NATIVE_BUTTON_PROP_COMPONENTS = new Set(["Button", "PopoverTrigger"]);
52
52
 
53
- /** `<Foo>` -> "Foo", `<Menu.Trigger>` -> "Trigger", otherwise null. */
53
+ /** `<Foo>` -> "Foo", `<Popover.Trigger>` -> "Popover.Trigger", otherwise null. */
54
54
  const componentNameOf = (opening) => {
55
- const name = opening.name;
56
- if (name.type === "JSXIdentifier") return name.name;
57
- if (name.type === "JSXMemberExpression" && name.property.type === "JSXIdentifier") {
58
- return name.property.name;
59
- }
60
- return null;
55
+ const jsxName = (name) => {
56
+ if (name.type === "JSXIdentifier") return name.name;
57
+ if (name.type !== "JSXMemberExpression") return null;
58
+ const object = jsxName(name.object);
59
+ return object === null ? null : `${object}.${name.property.name}`;
60
+ };
61
+ return jsxName(opening.name);
61
62
  };
62
63
 
63
64
  /**
@@ -71,10 +72,14 @@ const componentNameOf = (opening) => {
71
72
  * Those set `nativeButton={false}` on their own inner button, so the mistake
72
73
  * is contained in the wrapper rather than at every call site.
73
74
  */
74
- const rendersNativeButton = (name) =>
75
- name === "button" || (/^[A-Z]/.test(name) && name.endsWith("Button"));
75
+ const rendersNativeButton = (name) => {
76
+ const last = name.slice(name.lastIndexOf(".") + 1);
77
+ return last === "button" || (/^[A-Z]/.test(last) && last.endsWith("Button"));
78
+ };
76
79
 
77
- const isButtonLike = (name) => name !== null && NATIVE_BUTTON_PROP_COMPONENTS.has(name);
80
+ /** `Popover.Trigger` and `PopoverTrigger` are the same host. */
81
+ const isButtonLike = (name) =>
82
+ name !== null && NATIVE_BUTTON_PROP_COMPONENTS.has(name.replaceAll(".", ""));
78
83
 
79
84
  /** The JSX element literal passed to `render`, or null. */
80
85
  const renderedElement = (attribute) => {
@@ -34,18 +34,26 @@
34
34
 
35
35
  const NODE_CRYPTO_MODULES = new Set(["crypto", "node:crypto"]);
36
36
 
37
- /** `crypto.randomUUID` or `globalThis.crypto.randomUUID`, and not shadowed. */
38
- const isGlobalCryptoRandomUuid = (callee, scope) => {
37
+ /** Whether a binding is `import crypto from "node:crypto"` / `import * as c`. */
38
+ const isNodeCryptoModuleBinding = (def) =>
39
+ def.type === "ImportBinding" &&
40
+ (def.node.type === "ImportDefaultSpecifier" ||
41
+ def.node.type === "ImportNamespaceSpecifier") &&
42
+ NODE_CRYPTO_MODULES.has(def.parent?.source?.value);
43
+
44
+ /**
45
+ * `crypto.randomUUID` on the global (`crypto`, `globalThis.crypto`) or on the
46
+ * node:crypto module imported whole (`import crypto from "node:crypto"`,
47
+ * `import * as c from "crypto"`): every spelling that mints a v4.
48
+ */
49
+ const isCryptoRandomUuid = (callee, scope) => {
39
50
  if (callee.type !== "MemberExpression") return false;
40
51
  if (callee.computed) return false;
41
52
  if (callee.property.type !== "Identifier") return false;
42
53
  if (callee.property.name !== "randomUUID") return false;
43
54
 
44
55
  const object = callee.object;
45
- let root;
46
- if (object.type === "Identifier" && object.name === "crypto") {
47
- root = object;
48
- } else if (
56
+ if (
49
57
  object.type === "MemberExpression" &&
50
58
  !object.computed &&
51
59
  object.object.type === "Identifier" &&
@@ -55,17 +63,19 @@ const isGlobalCryptoRandomUuid = (callee, scope) => {
55
63
  ) {
56
64
  // `globalThis.crypto` can't be shadowed by a local binding.
57
65
  return true;
58
- } else {
59
- return false;
60
66
  }
67
+ if (object.type !== "Identifier") return false;
61
68
 
62
- // A local `crypto` (a mock, an injected dependency) is not the global one.
63
69
  for (let current = scope; current; current = current.upper) {
64
- const variable = current.variables?.find((v) => v.name === root.name);
70
+ const variable = current.variables?.find((v) => v.name === object.name);
65
71
  if (!variable) continue;
66
- return variable.defs.length === 0;
72
+ // No defs: the implicit global. Otherwise the module imported whole is
73
+ // the same v4 mint; any other local (a mock, an injected dependency) is
74
+ // not.
75
+ if (variable.defs.length === 0) return object.name === "crypto";
76
+ return variable.defs.some(isNodeCryptoModuleBinding);
67
77
  }
68
- return true;
78
+ return object.name === "crypto";
69
79
  };
70
80
 
71
81
  const noCryptoRandomUuid = {
@@ -101,7 +111,7 @@ const noCryptoRandomUuid = {
101
111
  callee.type === "Identifier" && importedNames.has(callee.name);
102
112
  if (
103
113
  !isImported &&
104
- !isGlobalCryptoRandomUuid(callee, sourceCode.getScope(node))
114
+ !isCryptoRandomUuid(callee, sourceCode.getScope(node))
105
115
  ) {
106
116
  return;
107
117
  }
@@ -19,6 +19,18 @@
19
19
 
20
20
  const CLIENT_SAFE = /^NEXT_PUBLIC_/;
21
21
 
22
+ /** The key a destructuring property reads, or null when it is computed. */
23
+ const propertyKeyName = (property) => {
24
+ if (property.type !== "Property" || property.computed) return null;
25
+ if (property.key.type === "Identifier") return property.key.name;
26
+ if (property.key.type === "Literal" && typeof property.key.value === "string") {
27
+ return property.key.value;
28
+ }
29
+ return null;
30
+ };
31
+
32
+ const isClientSafe = (name) => name === "NODE_ENV" || CLIENT_SAFE.test(name);
33
+
22
34
  /** Whether the file opens with the "use client" directive. */
23
35
  const isClientFile = (program) => {
24
36
  for (const statement of program.body) {
@@ -30,16 +42,18 @@ const isClientFile = (program) => {
30
42
  return false;
31
43
  };
32
44
 
45
+ /** Whether `node` is `process.env` itself. */
46
+ const isProcessEnv = (node) =>
47
+ node.type === "MemberExpression" &&
48
+ !node.computed &&
49
+ node.object.type === "Identifier" &&
50
+ node.object.name === "process" &&
51
+ node.property.type === "Identifier" &&
52
+ node.property.name === "env";
53
+
33
54
  /** The variable name in `process.env.FOO` / `process.env["FOO"]`, or null. */
34
55
  const envVarName = (node) => {
35
- const object = node.object;
36
- if (object.type !== "MemberExpression" || object.computed) return null;
37
- if (object.object.type !== "Identifier" || object.object.name !== "process") {
38
- return null;
39
- }
40
- if (object.property.type !== "Identifier" || object.property.name !== "env") {
41
- return null;
42
- }
56
+ if (!isProcessEnv(node.object)) return null;
43
57
  if (!node.computed && node.property.type === "Identifier") {
44
58
  return node.property.name;
45
59
  }
@@ -63,6 +77,8 @@ const noServerEnvInClient = {
63
77
  },
64
78
  create(context) {
65
79
  let client = false;
80
+ const report = (node, name) =>
81
+ context.report({ node, messageId: "serverEnvInClient", data: { name } });
66
82
  return {
67
83
  Program(node) {
68
84
  client = isClientFile(node);
@@ -71,12 +87,18 @@ const noServerEnvInClient = {
71
87
  if (!client) return;
72
88
  const name = envVarName(node);
73
89
  if (name === null) return;
74
- if (name === "NODE_ENV" || CLIENT_SAFE.test(name)) return;
75
- context.report({
76
- node,
77
- messageId: "serverEnvInClient",
78
- data: { name },
79
- });
90
+ if (isClientSafe(name)) return;
91
+ report(node, name);
92
+ },
93
+ // `const { STRIPE_SECRET_KEY } = process.env` reads the same var.
94
+ VariableDeclarator(node) {
95
+ if (!client || node.id.type !== "ObjectPattern") return;
96
+ if (!node.init || !isProcessEnv(node.init)) return;
97
+ for (const property of node.id.properties) {
98
+ const name = propertyKeyName(property);
99
+ if (name === null || isClientSafe(name)) continue;
100
+ report(property.key, name);
101
+ }
80
102
  },
81
103
  };
82
104
  },
@@ -14,7 +14,8 @@
14
14
  // Casting a *column* to an array type is legitimate and indistinguishable
15
15
  // syntactically, so that case takes a justified disable comment.
16
16
 
17
- const ARRAY_CAST = /^::\s*"?[A-Za-z_][\w."]*"?\s*\[\s*\]/;
17
+ // Postgres allows whitespace around `::`, so `${ids} :: uuid[]` is the same cast.
18
+ const ARRAY_CAST = /^\s*::\s*("?[A-Za-z_][\w."]*"?\s*\[\s*\])/;
18
19
 
19
20
  const noSqlArrayCast = {
20
21
  meta: {
@@ -41,7 +42,7 @@ const noSqlArrayCast = {
41
42
  context.report({
42
43
  node: node.quasi.expressions[i - 1] ?? node,
43
44
  messageId: "sqlArrayCast",
44
- data: { type: match[0].slice(2).trim() },
45
+ data: { type: match[1] },
45
46
  });
46
47
  }
47
48
  },
package/lib/run.js CHANGED
@@ -16,9 +16,16 @@ export function run(tool, args = [], opts = {}) {
16
16
  }
17
17
  throw res.error;
18
18
  }
19
- // A signal-killed child (OOM, SIGSEGV) has status null — that's a failure,
20
- // not a pass; `?? 0` would let a crashed linter through the CI gate.
21
- return res.status ?? (res.signal ? 1 : 0);
19
+ return exitStatus(res);
20
+ }
21
+
22
+ /**
23
+ * The exit code of a finished `spawnSync` child. A signal-killed child (OOM,
24
+ * SIGSEGV) has status null — that's a failure, not a pass; `?? 0` would let a
25
+ * crashed linter through the CI gate.
26
+ */
27
+ export function exitStatus({ status, signal }) {
28
+ return status ?? (signal ? 1 : 0);
22
29
  }
23
30
 
24
31
  /**
@@ -47,7 +54,7 @@ export function runCapture(tool, args = [], opts = {}) {
47
54
  throw res.error;
48
55
  }
49
56
  return {
50
- status: res.status ?? (res.signal ? 1 : 0),
57
+ status: exitStatus(res),
51
58
  stdout: res.stdout ?? "",
52
59
  stderr: res.stderr ?? "",
53
60
  output: `${res.stdout ?? ""}${res.stderr ?? ""}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ingram-tech/nk-dev",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "The nextkit dev toolchain in one package: the `nk` CLI plus shared oxlint/oxfmt, TypeScript, and Vitest config, the format-on-commit hook, and the AI agent guide. `nk init` scaffolds a site to use it.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,15 +45,15 @@
45
45
  "test": "vitest run"
46
46
  },
47
47
  "dependencies": {
48
- "@ast-grep/cli": "^0.45.3",
48
+ "@ast-grep/cli": "^0.50.0",
49
49
  "@testing-library/dom": "^10.4.2",
50
50
  "@testing-library/jest-dom": "^7.0.1",
51
51
  "@typescript/native": "npm:typescript@^7.0.2",
52
- "jsdom": "^30.1.1",
53
- "knip": "^6.39.0",
54
- "oxfmt": "^0.71.0",
55
- "oxlint": "^1.86.0",
56
- "oxlint-tsgolint": "^7.0.2003",
52
+ "jsdom": "^30.1.2",
53
+ "knip": "^6.41.0",
54
+ "oxfmt": "^0.72.0",
55
+ "oxlint": "^1.87.0",
56
+ "oxlint-tsgolint": "^7.0.2004",
57
57
  "typescript": "npm:@typescript/typescript6@^6.0.2",
58
58
  "vitest": "^5.0.3"
59
59
  },
@@ -68,7 +68,7 @@ one-off edit in one file, just edit the file.
68
68
  - **`$$$ARGS`** — matches **zero or more** nodes (argument lists, statements,
69
69
  JSX children). This is what makes rewrites arity-agnostic.
70
70
  - **`-l ts` / `-l tsx`** — the language. Use `tsx` for anything with JSX (most of
71
- a Next.js `app/`), `ts` for plain `.ts`. Getting this wrong makes patterns
71
+ a Next.js `src/app/`), `ts` for plain `.ts`. Getting this wrong makes patterns
72
72
  silently fail to parse.
73
73
  - **`-p` pattern**, **`-r` rewrite**, **`-U`** apply, **`-i`** interactive
74
74
  (approve each edit). Scope by passing paths: `nk ast-grep run ... src/app`.