Skip to content

AI-native design editor. Open-source Figma alternative.

fix(tools): run npm packaging guards in package verification

Danila Poyarkove5dd226683cf
diff --git a/AGENTS.md b/AGENTS.md
index 5aed249b6..2fd7bb9bd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -91,7 +91,7 @@ Browser tests use the canonical `playwright.config.ts`; do not create task-speci
For releases, update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; then tag and push `vX.Y.Z`.
-`.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Native release policy and recovery rules live in `tools/release-packages/README.md`; workflow and application source commits are recorded separately. Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it. Release titles are exactly the tag (`vX.Y.Z`), without a product-name prefix. Homebrew's official `openpencil` cask is managed upstream: BrewTestBot proposes version updates, then Homebrew reviews and merges them. Check the upstream cask/PR after publication; do not push to the archived custom tap or create duplicate bump automation. Install the desktop app with `brew install --cask openpencil`; install the CLI separately through npm or Bun.
+`.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Native release policy and recovery rules live in `tools/release-packages/README.md`; workflow and application source commits are recorded separately. Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports continue to use `dist`. Release preparation must preserve resolution maps. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks—do not publish package directories manually. `test:packages` first runs the packaging guards in `tools/package-quality/src/smoke/guards.ts`: fixture manifests packed with the real `npm pack` that must trip the tarball inspector and the Node/Bun consumer checks before those checks vouch for real packages. Keep package-manager invocations out of `bun test` suites; their cold start is not bounded, and raising a test timeout is never the fix. Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title/body and artifacts, then publish it. Release titles are exactly the tag (`vX.Y.Z`), without a product-name prefix. Homebrew's official `openpencil` cask is managed upstream: BrewTestBot proposes version updates, then Homebrew reviews and merges them. Check the upstream cask/PR after publication; do not push to the archived custom tap or create duplicate bump automation. Install the desktop app with `brew install --cask openpencil`; install the CLI separately through npm or Bun.
App/docs production workflows run on `v*` tags or `workflow_dispatch`, not ordinary `master` pushes. `ci.yml` and `heavy-tests.yml` define validation gates.
diff --git a/bun.lock b/bun.lock
index cb170bbb0..46e1b67d7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -428,10 +428,14 @@
"tools/package-artifacts": {
"name": "@open-pencil/package-artifacts",
"dependencies": {
+ "@publint/pack": "^0.1.5",
"pkg-types": "^2.3.1",
"tinyexec": "^1.3.0",
"valibot": "^1.4.2",
},
+ "devDependencies": {
+ "nanotar": "^0.3.0",
+ },
},
"tools/package-quality": {
"name": "@open-pencil/package-quality-tools",
@@ -3475,6 +3479,8 @@
"nanostores": ["[email protected]", "", {}, "sha512-DNIX+HyFpo14fKGe0NsX9/aPzdKGiSZwX5xEMpDwQrDdo2iTiUYunOCCQLYwJrziKVe8ZOtVvcv0dEVI8lMx2g=="],
+ "nanotar": ["[email protected]", "", {}, "sha512-Kv2JYYiCzt16Kt5QwAc9BFG89xfPNBx+oQL4GQXD9nLqPkZBiNaqaCWtwnbk/q7UVsTYevvM1b0UF8zmEI4pCg=="],
+
"napi-build-utils": ["[email protected]", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"natural-compare": ["[email protected]", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
diff --git a/tools/package-artifacts/package.json b/tools/package-artifacts/package.json
index aab422fa4..54904492e 100644
--- a/tools/package-artifacts/package.json
+++ b/tools/package-artifacts/package.json
@@ -2,6 +2,9 @@
"name": "@open-pencil/package-artifacts",
"private": true,
"type": "module",
+ "imports": {
+ "#package-artifacts/*": "./src/*.ts"
+ },
"exports": {
".": "./src/index.ts",
"./tarball": "./src/tarball.ts",
@@ -11,8 +14,12 @@
"test": "bun test tests"
},
"dependencies": {
+ "@publint/pack": "^0.1.5",
"pkg-types": "^2.3.1",
"tinyexec": "^1.3.0",
"valibot": "^1.4.2"
+ },
+ "devDependencies": {
+ "nanotar": "^0.3.0"
}
}
diff --git a/tools/package-artifacts/src/tarball.ts b/tools/package-artifacts/src/tarball.ts
index 08dc5ba2f..fd7aad1bc 100644
--- a/tools/package-artifacts/src/tarball.ts
+++ b/tools/package-artifacts/src/tarball.ts
@@ -1,14 +1,12 @@
-import { execFile } from 'node:child_process'
-import { readdir } from 'node:fs/promises'
+import { readdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'
-import { promisify } from 'node:util'
+
+import { unpack } from '@publint/pack'
import { collectExportTargets } from './manifest/exports'
import { parsePackageManifest } from './manifest/read'
import type { PackageManifest } from './manifest/types'
-const execFileAsync = promisify(execFile)
-
export interface TarballDiagnostic {
field: string
message: string
@@ -32,16 +30,22 @@ export function packageExportTargetPaths(manifest: Pick<PackageManifest, 'export
return collectExportTargets(manifest.exports).map(({ target }) => target)
}
-export async function tarballEntries(tarballPath: string): Promise<Set<string>> {
- const { stdout } = await execFileAsync('tar', ['-tf', tarballPath], { encoding: 'utf8' })
- return new Set(stdout.trim().split('\n').filter(Boolean))
+export interface TarballContents {
+ entries: Set<string>
+ manifest: PackageManifest
}
-export async function tarballPackageJSON(tarballPath: string): Promise<PackageManifest> {
- const { stdout } = await execFileAsync('tar', ['-xOf', tarballPath, 'package/package.json'], {
- encoding: 'utf8'
- })
- return parsePackageManifest(stdout, `${tarballPath}: package/package.json`)
+/** Decompress and read a package tarball in-process; no `tar` executable is involved. */
+export async function readTarball(tarballPath: string): Promise<TarballContents> {
+ const { files } = await unpack(await readFile(tarballPath))
+ const entries = new Set(files.map(({ name }) => name))
+ const manifestFile = files.find(({ name }) => name === 'package/package.json')
+ if (!manifestFile) throw new Error(`${tarballPath}: package/package.json is missing`)
+ const manifest = parsePackageManifest(
+ new TextDecoder().decode(manifestFile.data),
+ `${tarballPath}: package/package.json`
+ )
+ return { entries, manifest }
}
function exportTargetPattern(target: string): RegExp {
@@ -60,10 +64,7 @@ function targetExists(entries: Set<string>, target: string): boolean {
}
export async function inspectTarball(tarballPath: string): Promise<TarballInspection> {
- const [entries, manifest] = await Promise.all([
- tarballEntries(tarballPath),
- tarballPackageJSON(tarballPath)
- ])
+ const { entries, manifest } = await readTarball(tarballPath)
const diagnostics: TarballDiagnostic[] = []
const report = (field: string, message: string) =>
diagnostics.push({ field, message, packageName: manifest.name, tarballPath })
diff --git a/tools/package-artifacts/tests/catalog.test.ts b/tools/package-artifacts/tests/catalog.test.ts
index bbddbe386..f354b4734 100644
--- a/tools/package-artifacts/tests/catalog.test.ts
+++ b/tools/package-artifacts/tests/catalog.test.ts
@@ -3,8 +3,11 @@ import { mkdir, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import type { WorkspacePackage } from '../src/manifest/types'
-import { discoverPublicPackages, orderPackagesByDependencies } from '../src/workspace/catalog'
+import type { WorkspacePackage } from '#package-artifacts/manifest/types'
+import {
+ discoverPublicPackages,
+ orderPackagesByDependencies
+} from '#package-artifacts/workspace/catalog'
function pkg(name: string, dependencies: Record<string, string> = {}): WorkspacePackage {
return { directory: `packages/${name}`, manifest: { name, version: '1.0.0', dependencies } }
diff --git a/tools/package-artifacts/tests/exports.test.ts b/tools/package-artifacts/tests/exports.test.ts
index a5e1db49b..ec9e284d3 100644
--- a/tools/package-artifacts/tests/exports.test.ts
+++ b/tools/package-artifacts/tests/exports.test.ts
@@ -4,8 +4,8 @@ import {
collectExportTargets,
concreteImportSpecifiers,
validateManifest
-} from '../src/manifest/exports'
-import type { PackageManifest } from '../src/manifest/types'
+} from '#package-artifacts/manifest/exports'
+import type { PackageManifest } from '#package-artifacts/manifest/types'
const validManifest: PackageManifest = {
name: '@open-pencil/example',
diff --git a/tools/package-artifacts/tests/npm-output.test.ts b/tools/package-artifacts/tests/npm-output.test.ts
index e9855c2e4..e21386a09 100644
--- a/tools/package-artifacts/tests/npm-output.test.ts
+++ b/tools/package-artifacts/tests/npm-output.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from 'bun:test'
-import { parsePackageManifest } from '../src/manifest/read'
-import { parseNpmPack } from '../src/npm/pack'
+import { parsePackageManifest } from '#package-artifacts/manifest/read'
+import { parseNpmPack } from '#package-artifacts/npm/pack'
test('npm pack parser validates archive names and paths', () => {
expect(
diff --git a/tools/package-artifacts/tests/process.test.ts b/tools/package-artifacts/tests/process.test.ts
index 872884229..cdf53f856 100644
--- a/tools/package-artifacts/tests/process.test.ts
+++ b/tools/package-artifacts/tests/process.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { CommandError, runCommand } from '../src/process'
+import { CommandError, runCommand } from '#package-artifacts/process'
describe('runCommand', () => {
test('captures output', async () => {
diff --git a/tools/package-artifacts/tests/root.test.ts b/tools/package-artifacts/tests/root.test.ts
index 4449cb280..e3c4f9d47 100644
--- a/tools/package-artifacts/tests/root.test.ts
+++ b/tools/package-artifacts/tests/root.test.ts
@@ -3,7 +3,7 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { resolveWorkspaceRoot } from '../src/workspace/root'
+import { resolveWorkspaceRoot } from '#package-artifacts/workspace/root'
test('nearest workspace lockfile isolates nested worktrees from the parent checkout', async () => {
const parent = await mkdtemp(join(tmpdir(), 'workspace-root-'))
diff --git a/tools/package-artifacts/tests/schemas.test.ts b/tools/package-artifacts/tests/schemas.test.ts
index 89ab62ab1..b85ee05ac 100644
--- a/tools/package-artifacts/tests/schemas.test.ts
+++ b/tools/package-artifacts/tests/schemas.test.ts
@@ -1,8 +1,8 @@
import { expect, test } from 'bun:test'
-import { parsePackageManifest } from '../src/manifest/read'
-import { isRegistryNotFound, validateRegistryVersion } from '../src/npm/registry'
-import { parseWorkspace } from '../src/workspace/schema'
+import { parsePackageManifest } from '#package-artifacts/manifest/read'
+import { isRegistryNotFound, validateRegistryVersion } from '#package-artifacts/npm/registry'
+import { parseWorkspace } from '#package-artifacts/workspace/schema'
const identity = { name: 'fixture', version: '1.0.0' }
diff --git a/tools/package-artifacts/tests/tarball.test.ts b/tools/package-artifacts/tests/tarball.test.ts
index 1a8f201bb..29722333e 100644
--- a/tools/package-artifacts/tests/tarball.test.ts
+++ b/tools/package-artifacts/tests/tarball.test.ts
@@ -1,6 +1,14 @@
-import { describe, expect, test } from 'bun:test'
+import { afterEach, describe, expect, test } from 'bun:test'
+import { mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
-import { packageBinTargets, packageExportTargetPaths } from '../src/tarball'
+import {
+ inspectTarball,
+ packageBinTargets,
+ packageExportTargetPaths
+} from '#package-artifacts/tarball'
+import { createTarGzip } from 'nanotar'
describe('tarball metadata', () => {
test('normalizes string and named binaries', () => {
@@ -33,3 +41,68 @@ describe('tarball metadata', () => {
).toEqual(['./dist/*.d.ts', './dist/*.js'])
})
})
+
+describe('inspectTarball', () => {
+ const temporaryDirectories: string[] = []
+
+ afterEach(async () => {
+ await Promise.all(
+ temporaryDirectories.splice(0).map((path) => rm(path, { recursive: true, force: true }))
+ )
+ })
+
+ /** Build the archive in-process, so the test never depends on a tar executable. */
+ async function createTarball(files: Record<string, string>): Promise<string> {
+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-tarball-'))
+ temporaryDirectories.push(root)
+ const tarball = join(root, 'package.tgz')
+ await writeFile(
+ tarball,
+ await createTarGzip(
+ Object.entries(files).map(([file, data]) => ({ name: `package/${file}`, data }))
+ )
+ )
+ return tarball
+ }
+
+ const manifest = (bunTarget: string) =>
+ JSON.stringify({
+ name: '@fixture/resolution',
+ version: '1.0.0',
+ exports: { '.': { bun: bunTarget, import: './dist/index.js' } }
+ })
+
+ test('reads entries and the manifest without a tar executable', async () => {
+ const tarball = await createTarball({
+ 'package.json': manifest('./dist/index.js'),
+ 'dist/index.js': 'export const ready = true\n'
+ })
+ const inspection = await inspectTarball(tarball)
+ expect(inspection.manifest.name).toBe('@fixture/resolution')
+ expect([...inspection.entries].sort()).toEqual([
+ 'package/dist/index.js',
+ 'package/package.json'
+ ])
+ expect(inspection.diagnostics).toEqual([])
+ })
+
+ test('reports export conditions whose targets were not packed', async () => {
+ const tarball = await createTarball({
+ 'package.json': manifest('./src/index.ts'),
+ 'dist/index.js': 'export const ready = true\n'
+ })
+ expect((await inspectTarball(tarball)).diagnostics).toEqual([
+ {
+ field: 'exports["."].bun',
+ message: 'target is missing (./src/index.ts)',
+ packageName: '@fixture/resolution',
+ tarballPath: tarball
+ }
+ ])
+ })
+
+ test('rejects archives without a package manifest', async () => {
+ const tarball = await createTarball({ 'dist/index.js': 'export {}\n' })
+ await expect(inspectTarball(tarball)).rejects.toThrow('package/package.json is missing')
+ })
+})
diff --git a/tools/package-artifacts/tests/workspace-identity.test.ts b/tools/package-artifacts/tests/workspace-identity.test.ts
index 099eeface..5403a5606 100644
--- a/tools/package-artifacts/tests/workspace-identity.test.ts
+++ b/tools/package-artifacts/tests/workspace-identity.test.ts
@@ -3,7 +3,7 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
-import { runCommand } from '../src/process'
+import { runCommand } from '#package-artifacts/process'
describe('workspace module identity', () => {
test('Bun source exports unify imports across different tsconfig scopes', async () => {
diff --git a/tools/package-quality/package.json b/tools/package-quality/package.json
index 0b8028637..56c619e7f 100644
--- a/tools/package-quality/package.json
+++ b/tools/package-quality/package.json
@@ -2,6 +2,9 @@
"name": "@open-pencil/package-quality-tools",
"private": true,
"type": "module",
+ "imports": {
+ "#package-quality/*": "./src/*.ts"
+ },
"exports": {
"./consumer": "./src/smoke/consumer.ts"
},
diff --git a/tools/package-quality/src/smoke/guards.ts b/tools/package-quality/src/smoke/guards.ts
new file mode 100644
index 000000000..8ec1306d8
--- /dev/null
+++ b/tools/package-quality/src/smoke/guards.ts
@@ -0,0 +1,209 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+
+import { isEqual } from 'es-toolkit'
+
+import { CommandError, parseNpmPack, runCommand } from '@open-pencil/package-artifacts'
+import { inspectTarball, type TarballDiagnostic } from '@open-pencil/package-artifacts/tarball'
+
+import { installPackedPackages } from './install'
+import { evaluateRuntime, type RuntimeName } from './runtime'
+
+/** A runtime must import the fixture, or fail with output matching the pattern. */
+export type RuntimeExpectation = 'imports' | { failsWith: RegExp }
+/** What a runtime did: imported, or failed with this output. */
+export type RuntimeObservation = 'imports' | { failed: string }
+
+export interface PackagingGuard {
+ /** The `exports["."].bun` target of the fixture manifest. */
+ bunTarget: string
+ /** Inspector diagnostics the packed fixture must produce, in order. */
+ diagnostics: Array<Pick<TarballDiagnostic, 'field' | 'message'>>
+ /** Manifest `files` entries; the real `npm pack` decides what they ship. */
+ files: string[]
+ name: string
+ /** Which runtimes must import the installed fixture and how the others must fail. */
+ runtimes: Record<RuntimeName, RuntimeExpectation>
+}
+
+export interface PackagingGuardObservation {
+ diagnostics: Array<Pick<TarballDiagnostic, 'field' | 'message'>>
+ runtimes: Record<RuntimeName, RuntimeObservation>
+}
+
+const FIXTURE_NAME = '@fixture/resolution'
+const FIXTURE_SOURCES: Record<string, string> = {
+ 'dist/index.js': 'export const ready = true\n',
+ 'dist/index.d.ts': 'export declare const ready: true\n',
+ 'src/index.ts': "export { ready } from '#fixture/value'\n",
+ 'src/value.ts': 'export const ready = true\n'
+}
+const FIXTURE_IMPORT = `const { ready } = await import(${JSON.stringify(FIXTURE_NAME)}); if (ready !== true) throw new Error('fixture export missing')`
+const RUNTIMES = ['node', 'bun'] as const
+/** Matches the deadline the release workflow gives `npm pack`. */
+const PACK_TIMEOUT_MS = 60_000
+
+/**
+ * Broken manifest shapes that the release checks must catch. Each guard packs a
+ * fixture with the same `npm pack` the release uses, inspects the tarball, installs
+ * it into a consumer, and imports it under Node and Bun. Silence from the inspector
+ * on the real packages only means something once these fail the way they should.
+ */
+export const packagingGuards: PackagingGuard[] = [
+ {
+ name: 'built entrypoints resolve under Node and Bun',
+ files: ['dist'],
+ bunTarget: './dist/index.js',
+ diagnostics: [],
+ runtimes: { node: 'imports', bun: 'imports' }
+ },
+ {
+ name: 'transitive source imports ship with the source directory',
+ files: ['dist', 'src'],
+ bunTarget: './src/index.ts',
+ diagnostics: [],
+ runtimes: { node: 'imports', bun: 'imports' }
+ },
+ {
+ name: 'an entrypoint-only file list does not satisfy transitive imports',
+ files: ['dist', 'src/index.ts'],
+ bunTarget: './src/index.ts',
+ diagnostics: [],
+ runtimes: { node: 'imports', bun: { failsWith: /Cannot find module '#fixture\/value'/ } }
+ },
+ {
+ name: 'a source-only Bun condition is reported before it breaks consumers',
+ files: ['dist'],
+ bunTarget: './src/index.ts',
+ diagnostics: [{ field: 'exports["."].bun', message: 'target is missing (./src/index.ts)' }],
+ runtimes: { node: 'imports', bun: { failsWith: /Cannot find module '@fixture\/resolution'/ } }
+ }
+]
+
+/** Compare what a guard observed with what it requires; each mismatch is one message. */
+export function packagingGuardMismatches(
+ guard: PackagingGuard,
+ observed: PackagingGuardObservation
+): string[] {
+ const mismatches: string[] = []
+ if (!isEqual(guard.diagnostics, observed.diagnostics)) {
+ const describe = (diagnostics: PackagingGuardObservation['diagnostics']) =>
+ diagnostics.map(({ field, message }) => `${field} ${message}`).join(', ')
+ mismatches.push(
+ `${guard.name}: expected diagnostics [${describe(guard.diagnostics)}] but the inspector reported [${describe(observed.diagnostics)}]`
+ )
+ }
+ for (const runtime of RUNTIMES) {
+ const mismatch = runtimeMismatch(guard.runtimes[runtime], observed.runtimes[runtime])
+ if (mismatch) mismatches.push(`${guard.name}: ${runtime} ${mismatch}`)
+ }
+ return mismatches
+}
+
+function firstLine(output: string): string {
+ return output.trim().split('\n')[0] ?? ''
+}
+
+function runtimeMismatch(
+ expected: RuntimeExpectation,
+ observed: RuntimeObservation
+): string | undefined {
+ if (expected === 'imports') {
+ return observed === 'imports'
+ ? undefined
+ : `should import but failed: ${firstLine(observed.failed)}`
+ }
+ if (observed === 'imports') return `should fail with ${expected.failsWith} but imported`
+ return expected.failsWith.test(observed.failed)
+ ? undefined
+ : `should fail with ${expected.failsWith} but failed with: ${firstLine(observed.failed)}`
+}
+
+function fixtureManifest(guard: PackagingGuard): string {
+ return `${JSON.stringify(
+ {
+ name: FIXTURE_NAME,
+ version: '1.0.0',
+ type: 'module',
+ files: guard.files,
+ imports: { '#fixture/*': './src/*.ts' },
+ exports: {
+ '.': {
+ types: './dist/index.d.ts',
+ bun: guard.bunTarget,
+ import: './dist/index.js',
+ default: './dist/index.js'
+ }
+ }
+ },
+ null,
+ 2
+ )}\n`
+}
+
+async function writeFixture(directory: string, guard: PackagingGuard): Promise<void> {
+ const contents = { ...FIXTURE_SOURCES, 'package.json': fixtureManifest(guard) }
+ for (const [file, text] of Object.entries(contents)) {
+ const path = join(directory, file)
+ await mkdir(dirname(path), { recursive: true })
+ await writeFile(path, text)
+ }
+}
+
+async function packFixture(packageDirectory: string, artifacts: string): Promise<string> {
+ await mkdir(artifacts, { recursive: true })
+ const packed = await runCommand({
+ command: 'npm',
+ args: ['pack', '--json', '--ignore-scripts', '--pack-destination', artifacts],
+ cwd: packageDirectory,
+ timeoutMs: PACK_TIMEOUT_MS
+ })
+ return join(artifacts, parseNpmPack(packed.stdout).filename)
+}
+
+async function observeRuntime(runtime: RuntimeName, consumer: string): Promise<RuntimeObservation> {
+ try {
+ await evaluateRuntime(runtime, FIXTURE_IMPORT, consumer)
+ return 'imports'
+ } catch (error) {
+ if (error instanceof CommandError && !error.timedOut) {
+ return { failed: error.stderr.trim() || error.message }
+ }
+ throw error
+ }
+}
+
+async function observeGuard(
+ root: string,
+ guard: PackagingGuard
+): Promise<PackagingGuardObservation> {
+ const packageDirectory = join(root, 'package')
+ await writeFixture(packageDirectory, guard)
+ const tarball = await packFixture(packageDirectory, join(root, 'artifacts'))
+ const { diagnostics } = await inspectTarball(tarball)
+ const consumer = join(root, 'consumer')
+ await installPackedPackages(consumer, [tarball])
+ return {
+ diagnostics: diagnostics.map(({ field, message }) => ({ field, message })),
+ runtimes: {
+ node: await observeRuntime('node', consumer),
+ bun: await observeRuntime('bun', consumer)
+ }
+ }
+}
+
+/** Prove the packaging checks catch broken manifests before trusting them on real packages. */
+export async function verifyPackagingGuards(guards = packagingGuards): Promise<void> {
+ const root = await mkdtemp(join(tmpdir(), 'open-pencil-packaging-guards-'))
+ try {
+ const mismatches: string[] = []
+ for (const [index, guard] of guards.entries()) {
+ const observed = await observeGuard(join(root, String(index)), guard)
+ mismatches.push(...packagingGuardMismatches(guard, observed))
+ }
+ if (mismatches.length > 0) throw new Error(mismatches.join('\n'))
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+}
diff --git a/tools/package-quality/src/smoke/install.ts b/tools/package-quality/src/smoke/install.ts
index 03d9a38b2..a62cd7732 100644
--- a/tools/package-quality/src/smoke/install.ts
+++ b/tools/package-quality/src/smoke/install.ts
@@ -2,16 +2,24 @@ import { mkdir } from 'node:fs/promises'
import { runCommand } from '@open-pencil/package-artifacts'
+const INIT_TIMEOUT_MS = 60_000
+const INSTALL_TIMEOUT_MS = 120_000
+
export async function installPackedPackages(
consumerDirectory: string,
tarballs: string[]
): Promise<void> {
await mkdir(consumerDirectory, { recursive: true })
- await runCommand({ command: 'npm', args: ['init', '-y'], cwd: consumerDirectory })
+ await runCommand({
+ command: 'npm',
+ args: ['init', '-y'],
+ cwd: consumerDirectory,
+ timeoutMs: INIT_TIMEOUT_MS
+ })
await runCommand({
command: 'npm',
args: ['install', '--ignore-scripts', '--no-audit', '--no-fund', ...tarballs],
cwd: consumerDirectory,
- timeoutMs: 120_000
+ timeoutMs: INSTALL_TIMEOUT_MS
})
}
diff --git a/tools/package-quality/src/smoke/verify.ts b/tools/package-quality/src/smoke/verify.ts
index 238f64b3f..0401f19a2 100644
--- a/tools/package-quality/src/smoke/verify.ts
+++ b/tools/package-quality/src/smoke/verify.ts
@@ -6,11 +6,14 @@ import { discoverPublicPackages, orderPackagesByDependencies } from '@open-penci
import { measurePhase } from '../timing'
import { verifyArtifactConsumers } from './consumer'
+import { verifyPackagingGuards } from './guards'
import { packPublicPackages } from './pack'
export async function verifyPackedPackages(root: string): Promise<void> {
const temporaryRoot = await mkdtemp(join(tmpdir(), 'open-pencil-package-smoke-'))
try {
+ // Broken fixture manifests must fail before the same checks vouch for real packages.
+ await measurePhase('packaging guards', () => verifyPackagingGuards())
const packages = orderPackagesByDependencies(await discoverPublicPackages(root))
// Raw npm packing retains workspace:* dependencies. Inspect it without claiming
// installation compatibility; Bun packing normalizes those dependencies.
diff --git a/tools/package-quality/tests/checks.test.ts b/tools/package-quality/tests/checks.test.ts
index 117a3e843..ea95a5e04 100644
--- a/tools/package-quality/tests/checks.test.ts
+++ b/tools/package-quality/tests/checks.test.ts
@@ -1,8 +1,8 @@
import { expect, test } from 'bun:test'
-import { CommandError, type CommandRequest } from '@open-pencil/package-artifacts'
+import { runPackageChecks } from '#package-quality/checks/run'
-import { runPackageChecks } from '../src/checks/run'
+import { CommandError, type CommandRequest } from '@open-pencil/package-artifacts'
test('bounded checks drain after failures and preserve diagnostic order', async () => {
const requests = Array.from({ length: 5 }, (_, index) => ({
diff --git a/tools/package-quality/tests/cli.test.ts b/tools/package-quality/tests/cli.test.ts
index 73edaab8f..dcf29e9c5 100644
--- a/tools/package-quality/tests/cli.test.ts
+++ b/tools/package-quality/tests/cli.test.ts
@@ -1,9 +1,8 @@
import { describe, expect, test } from 'bun:test'
+import { checkCommand, smokeCommand, verifyCommand } from '#package-quality/commands'
import { renderUsage } from 'citty'
-import { checkCommand, smokeCommand, verifyCommand } from '../src/commands'
-
describe('package quality commands', () => {
test('exposes stable check, smoke, and verify workflows', async () => {
expect(checkCommand.meta?.name).toBe('check')
diff --git a/tools/package-quality/tests/guards.test.ts b/tools/package-quality/tests/guards.test.ts
new file mode 100644
index 000000000..970f5a520
--- /dev/null
+++ b/tools/package-quality/tests/guards.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from 'bun:test'
+
+import { packagingGuardMismatches, packagingGuards } from '#package-quality/smoke/guards'
+
+const BUN_MISSING_TARGET =
+ "error: Cannot find module '@fixture/resolution' from '/tmp/consumer/[eval]'\n\nBun v1.4.2"
+const BUN_UNRELATED = "error: Unexpected token '}' in /tmp/consumer/[eval]"
+
+const sourceOnlyGuard = packagingGuards.find(({ name }) =>
+ name.startsWith('a source-only Bun condition')
+)
+
+function requireSourceOnlyGuard() {
+ if (!sourceOnlyGuard) throw new Error('Expected the source-only Bun condition guard')
+ return sourceOnlyGuard
+}
+
+describe('packaging guards', () => {
+ test('cover a source-only Bun condition', () => {
+ const guard = requireSourceOnlyGuard()
+ expect(guard).toMatchObject({
+ files: ['dist'],
+ bunTarget: './src/index.ts',
+ diagnostics: [{ field: 'exports["."].bun', message: 'target is missing (./src/index.ts)' }]
+ })
+ expect(guard.runtimes.node).toBe('imports')
+ const bun = guard.runtimes.bun
+ if (bun === 'imports') throw new Error('Expected Bun to fail')
+ expect(bun.failsWith.test(BUN_MISSING_TARGET)).toBe(true)
+ expect(bun.failsWith.test(BUN_UNRELATED)).toBe(false)
+ })
+
+ test('accept an observation that matches the guard', () => {
+ const guard = requireSourceOnlyGuard()
+ expect(
+ packagingGuardMismatches(guard, {
+ diagnostics: guard.diagnostics,
+ runtimes: { node: 'imports', bun: { failed: BUN_MISSING_TARGET } }
+ })
+ ).toEqual([])
+ })
+
+ test('report a silent inspector and an unexpected import separately', () => {
+ const guard = requireSourceOnlyGuard()
+ const mismatches = packagingGuardMismatches(guard, {
+ diagnostics: [],
+ runtimes: { node: 'imports', bun: 'imports' }
+ })
+ expect(mismatches).toHaveLength(2)
+ expect(mismatches[0]).toContain('expected diagnostics [exports["."].bun target is missing')
+ expect(mismatches[0]).toContain('reported []')
+ expect(mismatches[1]).toContain('bun should fail with')
+ expect(mismatches[1]).toContain('but imported')
+ })
+
+ test('reject a Bun failure that is not the expected resolution failure', () => {
+ const guard = requireSourceOnlyGuard()
+ const bun = guard.runtimes.bun
+ if (bun === 'imports') throw new Error('Expected Bun to fail')
+ expect(
+ packagingGuardMismatches(guard, {
+ diagnostics: guard.diagnostics,
+ runtimes: { node: 'imports', bun: { failed: BUN_UNRELATED } }
+ })
+ ).toEqual([
+ `${guard.name}: bun should fail with ${bun.failsWith} but failed with: ${BUN_UNRELATED}`
+ ])
+ })
+
+ test('report a runtime that should import but failed', () => {
+ const [cleanGuard] = packagingGuards
+ if (!cleanGuard) throw new Error('Expected at least one guard')
+ expect(
+ packagingGuardMismatches(cleanGuard, {
+ diagnostics: [],
+ runtimes: {
+ node: { failed: 'Error: fixture export missing\n at [eval]' },
+ bun: 'imports'
+ }
+ })
+ ).toEqual([`${cleanGuard.name}: node should import but failed: Error: fixture export missing`])
+ })
+
+ test('report diagnostics that appear when none are expected', () => {
+ const [cleanGuard] = packagingGuards
+ if (!cleanGuard) throw new Error('Expected at least one guard')
+ expect(
+ packagingGuardMismatches(cleanGuard, {
+ diagnostics: [{ field: 'main', message: 'target is missing (./index.js)' }],
+ runtimes: { node: 'imports', bun: 'imports' }
+ })
+ ).toEqual([
+ `${cleanGuard.name}: expected diagnostics [] but the inspector reported [main target is missing (./index.js)]`
+ ])
+ })
+})
diff --git a/tools/package-quality/tests/packed-resolution.test.ts b/tools/package-quality/tests/packed-resolution.test.ts
deleted file mode 100644
index 2788ca232..000000000
--- a/tools/package-quality/tests/packed-resolution.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import { afterEach, describe, expect, test } from 'bun:test'
-import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-
-import { runCommand } from '@open-pencil/package-artifacts'
-import { inspectTarball } from '@open-pencil/package-artifacts/tarball'
-
-async function createPackageFixture(
- root: string,
- bunTarget: string,
- files = ['dist']
-): Promise<string> {
- const packageDirectory = join(root, 'package')
- await mkdir(join(packageDirectory, 'dist'), { recursive: true })
- await mkdir(join(packageDirectory, 'src'), { recursive: true })
- await writeFile(join(packageDirectory, 'dist/index.js'), 'export const ready = true\n')
- await writeFile(join(packageDirectory, 'dist/index.d.ts'), 'export declare const ready: true\n')
- await writeFile(
- join(packageDirectory, 'src/index.ts'),
- "export { ready } from '#fixture/value'\n"
- )
- await writeFile(join(packageDirectory, 'src/value.ts'), 'export const ready = true\n')
- await writeFile(
- join(packageDirectory, 'package.json'),
- `${JSON.stringify(
- {
- name: '@fixture/resolution',
- version: '1.0.0',
- type: 'module',
- imports: { '#fixture/*': './src/*.ts' },
- files,
- exports: {
- '.': {
- types: './dist/index.d.ts',
- bun: bunTarget,
- import: './dist/index.js',
- default: './dist/index.js'
- }
- }
- },
- null,
- 2
- )}\n`
- )
- return packageDirectory
-}
-
-import { evaluateRuntime } from '../src/smoke/runtime'
-
-const temporaryDirectories: string[] = []
-
-afterEach(async () => {
- await Promise.all(
- temporaryDirectories.splice(0).map((path) => rm(path, { recursive: true, force: true }))
- )
-})
-
-async function packAndInstall(bunTarget: string, files = ['dist']) {
- const root = await mkdtemp(join(tmpdir(), 'open-pencil-package-resolution-'))
- temporaryDirectories.push(root)
- const packageDirectory = await createPackageFixture(root, bunTarget, files)
- const artifacts = join(root, 'artifacts')
- const consumer = join(root, 'consumer')
- await mkdir(artifacts)
- await mkdir(consumer)
- const packed = await runCommand({
- command: 'npm',
- args: ['pack', '--json', '--pack-destination', artifacts],
- cwd: packageDirectory
- })
- const filename = (JSON.parse(packed.stdout) as Array<{ filename: string }>)[0]?.filename
- if (!filename) throw new Error('Fixture pack did not produce a tarball')
- const tarball = join(artifacts, filename)
- await runCommand({ command: 'npm', args: ['init', '-y'], cwd: consumer })
- await runCommand({
- command: 'npm',
- args: ['install', '--ignore-scripts', '--no-audit', '--no-fund', tarball],
- cwd: consumer
- })
- return { consumer, tarball }
-}
-
-describe('packed runtime resolution', () => {
- test('imports the same packed artifact under Node and Bun', async () => {
- const { consumer, tarball } = await packAndInstall('./dist/index.js')
- expect((await inspectTarball(tarball)).diagnostics).toEqual([])
- for (const runtime of ['node', 'bun'] as const) {
- await evaluateRuntime(
- runtime,
- "const value = await import('@fixture/resolution'); if (!value.ready) throw new Error('not ready')",
- consumer
- )
- }
- })
-
- test('ships transitive source imports with the source directory', async () => {
- const { consumer, tarball } = await packAndInstall('./src/index.ts', ['dist', 'src'])
- expect((await inspectTarball(tarball)).diagnostics).toEqual([])
- for (const runtime of ['node', 'bun'] as const) {
- await evaluateRuntime(
- runtime,
- "const { ready } = await import('@fixture/resolution'); if (!ready) throw new Error('missing value')",
- consumer
- )
- }
- }, 120_000)
-
- test('an entrypoint-only file list does not satisfy transitive imports', async () => {
- const { consumer, tarball } = await packAndInstall('./src/index.ts', ['dist', 'src/index.ts'])
- expect((await inspectTarball(tarball)).diagnostics).toEqual([])
- await expect(
- evaluateRuntime('bun', "await import('@fixture/resolution')", consumer)
- ).rejects.toThrow()
- }, 120_000)
-
- test('detects the source-only Bun condition from issue 663', async () => {
- const { consumer, tarball } = await packAndInstall('./src/index.ts')
- expect((await inspectTarball(tarball)).diagnostics).toEqual([
- expect.objectContaining({
- field: 'exports["."].bun',
- message: 'target is missing (./src/index.ts)'
- })
- ])
- await evaluateRuntime('node', "await import('@fixture/resolution')", consumer)
- await expect(
- evaluateRuntime('bun', "await import('@fixture/resolution')", consumer)
- ).rejects.toThrow('failed: exit code 1')
- })
-})
diff --git a/tools/package-quality/tests/runtime.test.ts b/tools/package-quality/tests/runtime.test.ts
index 27474c646..2e3bfd7ff 100644
--- a/tools/package-quality/tests/runtime.test.ts
+++ b/tools/package-quality/tests/runtime.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
import { setImmediate } from 'node:timers/promises'
-import type { CommandRequest } from '@open-pencil/package-artifacts'
+import { verifyPublicImports } from '#package-quality/smoke/runtime'
+import { measurePhase } from '#package-quality/timing'
-import { verifyPublicImports } from '../src/smoke/runtime'
-import { measurePhase } from '../src/timing'
+import type { CommandRequest } from '@open-pencil/package-artifacts'
test('public imports retain separate bounded Node and Bun invocations and the stdio exclusion', async () => {
const requests: CommandRequest[] = []