diff --git a/src/cli.ts b/src/cli.ts index 847230d7..85556792 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -2201,6 +2201,15 @@ async function runMarkBuild(args: ParsedArgs): Promise { const buildDirOptions = { framework: stack?.framework ?? null, buildScript: readBuildScript(cwd) }; const dir = resolveBuildDir(cwd, getStringFlag(args.flags, 'dir'), buildDirOptions); + if (dir === null && stack?.framework === 'next' && existsSync(path.join(cwd, '.next'))) { + // A Next.js build that is not a static export writes `.next/`, which holds no page files to mark: + // its documents are produced per request. Said as that, not as a directory that could not be found. + console.warn('mark-build: found .next/, a server-rendered Next.js build with no HTML files to mark.'); + console.warn('mark-build: run `npx @patchstack/connect guide` to see what your main layout needs.'); + await reportBuildStamp(reported, wirePayload, 'no-pages'); + return 0; + } + if (dir === null) { // Loud, and specific: this runs as a postbuild hook whose output scrolls past, and a build that // finished with nothing stamped is exactly what a published site with no production marker looks @@ -2503,15 +2512,28 @@ async function runCommand(args: ParsedArgs): Promise { } } +/** + * Ends the process with `code`. + * + * On Windows the process is left to end on its own once its work is done, because exiting while a + * network connection is still closing aborts Node there with an assertion that reads as a crash. The + * timer is the backstop for anything that would keep it alive, and does not itself keep it alive. + */ +function finish(code: number): void { + if (process.platform !== 'win32') process.exit(code); + process.exitCode = code; + setTimeout(() => process.exit(code), 3000).unref(); +} + main() - .then((code) => process.exit(code)) + .then((code) => finish(code)) .catch((err: unknown) => { if (err instanceof PatchstackError) { const plain = plainErrorMessage(err); console.error(`${plain ?? err.message} (${err.code})`); if (plain !== null && verbose) console.error(`Detail: ${err.message}`); - process.exit(1); + return finish(1); } console.error('Unexpected error:', err); - process.exit(2); + finish(2); }); diff --git a/src/parsers/consistency.ts b/src/parsers/consistency.ts index e1a357f5..3acc204a 100644 --- a/src/parsers/consistency.ts +++ b/src/parsers/consistency.ts @@ -9,7 +9,30 @@ import type { PackageEntry } from '../types.js'; * their absence from a parsed set says nothing about staleness. Returns [] * when package.json is missing or unreadable (nothing to validate against). */ +/** + * A dependency package.json declares. `aliasOf` is the package an npm alias (`"zod4": "npm:zod@^4"`) + * installs: the lockfile and the installed tree name it by its own name, not by the key it is declared + * under, so either name in a source means the dependency is there. + */ +export interface DeclaredDependency { + name: string; + aliasOf?: string; +} + +/** The package an `npm:` alias specifier installs, or null for any other specifier. */ +function aliasTarget(spec: unknown): string | null { + if (typeof spec !== 'string' || !spec.startsWith('npm:')) return null; + const target = spec.slice('npm:'.length); + const versionAt = target.lastIndexOf('@'); + const name = versionAt > 0 ? target.slice(0, versionAt) : target; + return name.length > 0 ? name : null; +} + export async function readDeclaredDependencyNames(cwd: string): Promise { + return (await readDeclaredDependencies(cwd)).map((dependency) => dependency.name); +} + +export async function readDeclaredDependencies(cwd: string): Promise { let raw: string; try { raw = await readFile(path.join(cwd, 'package.json'), 'utf8'); @@ -27,7 +50,7 @@ export async function readDeclaredDependencyNames(cwd: string): Promise(); + const declared = new Map(); // `optionalDependencies` included: they are installed when the platform supports them, they can be // vulnerable, and leaving them out meant a lockfile that omitted one still read as complete. for (const group of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) { @@ -39,11 +62,12 @@ export async function readDeclaredDependencyNames(cwd: string): Promise, packages: PackageEntry[]): string[] { const present = new Set(packages.map((entry) => entry.name)); - return declared.filter((name) => !present.has(name)); + return declared + .map((dependency) => (typeof dependency === 'string' ? { name: dependency } : dependency)) + .filter(({ name, aliasOf }: DeclaredDependency) => !present.has(name) && !(aliasOf !== undefined && present.has(aliasOf))) + .map(({ name }) => name); } /** diff --git a/src/parsers/index.ts b/src/parsers/index.ts index daa230b0..f74ff85e 100644 --- a/src/parsers/index.ts +++ b/src/parsers/index.ts @@ -1,7 +1,7 @@ import { access } from 'node:fs/promises'; import path from 'node:path'; import { PatchstackError, type Manifest, type PackageEntry } from '../types.js'; -import { disagreements, missingDependencies, readDeclaredDependencyNames } from './consistency.js'; +import { disagreements, missingDependencies, readDeclaredDependencies, type DeclaredDependency } from './consistency.js'; import { parseBunLockfile } from './bun.js'; import { parseNpmLockfile } from './npm.js'; import { walkNodeModules } from './node_modules.js'; @@ -87,7 +87,7 @@ export async function scanLockfile(cwd: string): Promise { // package-lock.json once on a bun-managed platform (Lovable), and the native // dependency flow never updates it again. Trusting it would freeze the // manifest and the build fingerprint while the real dependency set drifts. - const declared = await readDeclaredDependencyNames(cwd); + const declared = await readDeclaredDependencies(cwd); const warnings: string[] = []; let firstParsed: { packages: PackageEntry[]; filename: string } | null = null; // The installed tree, if some lockfile already routed us to it (a `bun.lockb` cannot be read, so it @@ -192,7 +192,7 @@ function manifestWith(packages: PackageEntry[], warnings: string[]): Manifest { function otherCompleteSources( all: Array<{ packages: PackageEntry[]; filename: string }>, current: { filename: string }, - declared: string[], + declared: DeclaredDependency[], ): Array<{ packages: PackageEntry[]; filename: string }> { return all.filter( (source) => source.filename !== current.filename && missingDependencies(declared, source.packages).length === 0, diff --git a/src/protect/install/reporting.ts b/src/protect/install/reporting.ts index dd7d7380..ec83b1ef 100644 --- a/src/protect/install/reporting.ts +++ b/src/protect/install/reporting.ts @@ -13,7 +13,7 @@ import { join } from 'node:path'; import { reportingState, explainReportingState } from '../reporting-state.js'; import type { VerifyCheck } from './types.js'; -import { read, hasResolvableCredential, isSiteUuid, findSiteUuidUp } from './util.js'; +import { read, hasResolvableCredential, envFileNamingCredential, isSiteUuid, findSiteUuidUp } from './util.js'; /** * The site identity the guard would run with, resolved the way the guard resolves it. @@ -101,6 +101,19 @@ export function reportingChecks(cwd: string, env: Record { } } + it('says a Next.js server build has no pages to mark, rather than that no build was found', () => { + const dir = mkdtempSync(path.join(tmpdir(), 'ps-next-mark-')); + try { + writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'probe', version: '1.0.0', dependencies: { next: '16.0.0' } })); + writeFileSync( + path.join(dir, 'package-lock.json'), + JSON.stringify({ + name: 'probe', + version: '1.0.0', + lockfileVersion: 3, + packages: { '': { name: 'probe', version: '1.0.0', dependencies: { next: '16.0.0' } }, 'node_modules/next': { version: '16.0.0' } }, + }), + ); + mkdirSync(path.join(dir, '.next')); + + const result = spawnSync(process.execPath, [bin, 'mark-build'], { cwd: dir, encoding: 'utf8' }); + + expect(result.status).toBe(0); + expect(result.stderr).toContain('found .next/, a server-rendered Next.js build'); + expect(result.stderr).not.toContain('no build output directory found'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it('prints its help through a symlinked path', () => { const { stdout } = runThroughSymlink(['--help']); diff --git a/tests/parsers/bun-and-source-selection.test.ts b/tests/parsers/bun-and-source-selection.test.ts index b86854d6..e1c7ffcf 100644 --- a/tests/parsers/bun-and-source-selection.test.ts +++ b/tests/parsers/bun-and-source-selection.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { parseBunLockfile } from '../../src/parsers/bun.js'; import { walkNodeModules } from '../../src/parsers/node_modules.js'; import { scanLockfile } from '../../src/parsers/index.js'; -import { disagreements, readDeclaredDependencyNames } from '../../src/parsers/consistency.js'; +import { disagreements, missingDependencies, readDeclaredDependencies, readDeclaredDependencyNames } from '../../src/parsers/consistency.js'; import { extractName } from '../../src/parsers/yarn.js'; /** @@ -267,6 +267,24 @@ describe('what counts as a declared dependency', () => { expect((await readDeclaredDependencyNames(cwd)).sort()).toEqual(['a', 'b']); }); + it('finds an npm alias under the name of the package it installs', async () => { + // "zod4": "npm:zod@^4" is installed and locked as `zod`, so a list that names `zod` has it. + const cwd = project({ + 'package.json': JSON.stringify({ + name: 'probe', + dependencies: { zod4: 'npm:zod@^4.4.3', scoped: 'npm:@scope/real@1.0.0', a: '^1.0.0' }, + }), + }); + const declared = await readDeclaredDependencies(cwd); + + expect(declared).toEqual([{ name: 'zod4', aliasOf: 'zod' }, { name: 'scoped', aliasOf: '@scope/real' }, { name: 'a' }]); + const entry = (name: string) => ({ name, version: '1.0.0' }); + expect(missingDependencies(declared, [entry('zod'), entry('@scope/real'), entry('a')])).toEqual([]); + // A source that lists the alias under its declared key has it too. + expect(missingDependencies(declared, [entry('zod4'), entry('scoped'), entry('a')])).toEqual([]); + expect(missingDependencies(declared, [entry('a')])).toEqual(['zod4', 'scoped']); + }); + it('still excludes a non-registry specifier', async () => { // The lockfile parsers skip those, so their absence says nothing about staleness. const cwd = project({ diff --git a/tests/protect-check-reporting.test.ts b/tests/protect-check-reporting.test.ts index e4b33b1f..f39ae245 100644 --- a/tests/protect-check-reporting.test.ts +++ b/tests/protect-check-reporting.test.ts @@ -45,6 +45,30 @@ const find = (checks: ReturnType, fragment: string) => { return hit!; }; +describe('a key that lives in an env file', () => { + it('is not called missing, because the app loads that file and this command does not', () => { + const dir = project({ siteUuid: UUID }); + writeFileSync(join(dir, '.env'), 'OTHER=1\nPATCHSTACK_API_KEY=example-not-a-key\n'); + + const checks = reportingChecks(dir, {}); + const reporting = find(checks, 'cannot be judged from here'); + + expect(reporting.ok).toBe(true); + expect(reporting.unverifiable).toBe(true); + expect(reporting.label).toContain('.env'); + // The file is named; what it holds is not. + expect(JSON.stringify(checks)).not.toContain('example-not-a-key'); + expect(checks.some((c) => c.label.includes('reporting is off'))).toBe(false); + }); + + it('still says there is no credential when the env file only mentions the name', () => { + const dir = project({ siteUuid: UUID }); + writeFileSync(join(dir, '.env'), '# PATCHSTACK_API_KEY=\nPATCHSTACK_API_KEY=\n'); + + expect(find(reportingChecks(dir, {}), 'reporting is off').label).toContain('unavailable-no-credential'); + }); +}); + describe('what it can answer', () => { it('says an app is not enrolled, and what that costs', () => { const checks = reportingChecks(project(), {});