fix(typert): satisfy workspace static gates

This commit is contained in:
imccyu
2026-08-05 23:18:35 +08:00
parent 64a963da0b
commit 9a0a9350c4
29 changed files with 986 additions and 74 deletions

View File

@@ -7,7 +7,7 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { join, relative, resolve } from 'node:path'
import { isForbiddenPublicationFile } from './publication-payload.ts'
import { hasTypeRTRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
const root = resolve(import.meta.dirname, '..')
// vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
@@ -122,6 +122,7 @@ function sameStringList(actual: readonly string[] | undefined, expected: readonl
function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
return [
'lib/index.js',
// Every package publishes its invariant ownership companion as a separate
@@ -145,9 +146,37 @@ function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
// declarations.
...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
'lib/types/**/*.d.ts',
...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
? ['lib/typert.host.js', 'lib/typert.host.d.ts']
: [],
...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
? ['lib/typert.client.js', 'lib/typert.client.d.ts']
: [],
...typeRTRemoteNavigation
? [
'lib/typert.remote-client.js',
'lib/typert.remote-client.d.ts',
'lib/typert.remote-client.d.ts.map',
'src',
]
: [],
]
}
/** Whether one conditional export exactly names the generated runtime and declaration pair. */
function hasExportPair(
manifest: PackageManifest,
subpath: string,
types: string,
runtime: string,
): boolean {
const entry = manifest.exports?.[subpath]
return typeof entry === 'object'
&& entry !== null
&& entry.types === types
&& entry.default === runtime
}
/** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
const entry = manifest.exports?.[subpath]
@@ -175,8 +204,9 @@ function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
}
if (manifest.name?.startsWith('@deepseek-ai/')) {
const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
for (const file of manifest.files ?? []) {
if (isForbiddenPublicationFile(file)) {
if (isForbiddenPublicationFile(file, publicationPolicy)) {
errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
}
}

View File

@@ -22,13 +22,7 @@ export default defineConfig({
const bundlePath = join(root, 'lib/client.js')
await writeFile(sourcePath, 'export const version = "watch-v1"\n')
bundles = await watchClientPlugins(root, ['.'], 50)
await expect.poll(async () => {
try {
return (await readFile(bundlePath, 'utf8')).includes('watch-v1')
} catch {
return false
}
}, { timeout: 10_000 }).toBe(true)
expect(await readFile(bundlePath, 'utf8')).toContain('watch-v1')
await new Promise(resolve => setTimeout(resolve, 1_000))
await writeFile(sourcePath, `export const version = "watch-v2-${'x'.repeat(100)}"\n`)

View File

@@ -47,21 +47,40 @@ export function discoverPluginDirs(root = repoRoot): string[] {
* @param root - repository or fixture root passed to tsdown.
* @param pluginDirs - workspace-relative package directories to watch.
* @param pollInterval - optional source-watcher polling interval in milliseconds.
* @returns live bundles whose async disposers stop every watcher.
* @returns live bundles after every watcher has completed its initial build.
*/
export async function watchClientPlugins(
root: string,
pluginDirs: readonly string[],
pollInterval?: number,
): Promise<TsdownBundle[]> {
return build({
let resolveInitialBuilds: (() => void) | undefined
const initialBuilds = new Promise<void>((resolve) => { resolveInitialBuilds = resolve })
const initialized = new WeakSet<object>()
const readiness: { expectedBuilds?: number; initializedBuilds: number } = { initializedBuilds: 0 }
const bundles = await build({
cwd: root,
workspace: [...pluginDirs],
watch: true,
hooks: {
'build:done': ({ options }) => {
if (initialized.has(options)) return
initialized.add(options)
readiness.initializedBuilds += 1
if (
readiness.expectedBuilds !== undefined
&& readiness.initializedBuilds >= readiness.expectedBuilds
) resolveInitialBuilds?.()
},
},
...pollInterval !== undefined
? { inputOptions: { watch: { watcher: { usePolling: true, pollInterval } } } }
: {},
})
readiness.expectedBuilds = bundles.length
if (readiness.initializedBuilds >= readiness.expectedBuilds) resolveInitialBuilds?.()
await initialBuilds
return bundles
}
const invokedPath = process.argv[1]

View File

@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
import { isForbiddenPublicationFile, validateTarballPayload } from './publication-payload.ts'
import {
hasTypeRTRemoteNavigation,
isForbiddenPublicationFile,
validateTarballPayload,
} from './publication-payload.ts'
function validateFixtureTarball(files: readonly string[]): () => void {
return () => {
@@ -51,4 +55,29 @@ describe('publication payload policy', () => {
'package/lib/styles/base.css',
])).not.toThrow()
})
it('allows only the TypeRT declaration map and its navigable source tree when requested', () => {
const policy = { typeRTRemoteNavigation: true }
expect(isForbiddenPublicationFile('src/index.ts', policy)).toBe(false)
expect(isForbiddenPublicationFile('lib/typert.remote-client.d.ts.map', policy)).toBe(false)
expect(isForbiddenPublicationFile('lib/types/index.d.ts.map', policy)).toBe(true)
expect(() => {
validateTarballPayload([
'package/lib/typert.remote-client.d.ts.map',
'package/src/index.ts',
], 'fixture.tgz', policy)
}).not.toThrow()
})
it('recognizes only the canonical Host-for-Client export pair', () => {
expect(hasTypeRTRemoteNavigation({
exports: {
'./remote': {
types: './lib/typert.remote-client.d.ts',
default: './lib/typert.remote-client.js',
},
},
})).toBe(true)
expect(hasTypeRTRemoteNavigation({ exports: { './remote': './lib/remote.js' } })).toBe(false)
})
})

View File

@@ -1,5 +1,22 @@
/** Publication payload policy shared by static manifests and packed tarballs. */
/** Publication exceptions required for TypeRT declaration-map navigation. */
export interface PublicationPayloadPolicy {
readonly typeRTRemoteNavigation?: boolean
}
/** Whether a package manifest exports generated Host-for-Client metadata with source navigation. */
export function hasTypeRTRemoteNavigation(manifest: unknown): boolean {
if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) return false
const exportsField = (manifest as Record<string, unknown>).exports
if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField)) return false
const remote = (exportsField as Record<string, unknown>)['./remote']
if (remote === null || typeof remote !== 'object' || Array.isArray(remote)) return false
const entry = remote as Record<string, unknown>
return entry.types === './lib/typert.remote-client.d.ts'
&& entry.default === './lib/typert.remote-client.js'
}
/** Normalize a package manifest path or npm tarball member to its payload-relative path. */
function payloadPath(file: string): string {
const normalized = file.replaceAll('\\', '/').replace(/^\.\/+/, '').replace(/\/+$/, '')
@@ -7,17 +24,30 @@ function payloadPath(file: string): string {
}
/** Whether a package payload path exposes source or declaration-map intermediates. */
export function isForbiddenPublicationFile(file: string): boolean {
export function isForbiddenPublicationFile(
file: string,
policy: PublicationPayloadPolicy = {},
): boolean {
const normalized = payloadPath(file)
if (policy.typeRTRemoteNavigation === true
&& (normalized === 'src'
|| normalized.startsWith('src/')
|| normalized === 'lib/typert.remote-client.d.ts.map')) {
return false
}
return normalized === 'src'
|| normalized.startsWith('src/')
|| normalized.endsWith('.d.ts.map')
}
/** Reject source and declaration-map members in a packed npm tarball. */
export function validateTarballPayload(files: readonly string[], context: string): void {
export function validateTarballPayload(
files: readonly string[],
context: string,
policy: PublicationPayloadPolicy = {},
): void {
for (const file of files) {
if (!isForbiddenPublicationFile(file)) continue
if (!isForbiddenPublicationFile(file, policy)) continue
const normalized = payloadPath(file)
if (normalized === 'src' || normalized.startsWith('src/')) {
throw new Error(`${context} publishes source file ${file}`)

View File

@@ -18,7 +18,7 @@ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep
import { createInterface } from 'node:readline/promises'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'
import { validateTarballPayload } from './publication-payload.ts'
import { hasTypeRTRemoteNavigation, validateTarballPayload } from './publication-payload.ts'
const DEFAULT_REGISTRY = 'https://registry.npm.harnessment.com'
const DEFAULT_OUTPUT_DIRECTORY = '.artifacts/npm-baseline'
@@ -320,7 +320,11 @@ class ReleaseBundle {
if (expected === undefined || !missingNames.delete(artifact.name)) {
throw new Error(`unexpected or duplicate packed package: ${artifact.name}`)
}
if (expected.origin === 'harness') validateTarballPayload(artifact.files, tarball)
if (expected.origin === 'harness') {
validateTarballPayload(artifact.files, tarball, {
typeRTRemoteNavigation: hasTypeRTRemoteNavigation(artifact.manifest),
})
}
if (artifact.version !== version) {
throw new Error(`${tarball} has version ${artifact.version}; expected ${version}`)
}
@@ -394,7 +398,11 @@ class ReleaseBundle {
throw new Error(`tarball checksum mismatch: ${pkg.tarball}`)
}
const artifact = inspectTarball(path, runner)
if (pkg.origin === 'harness') validateTarballPayload(artifact.files, pkg.tarball)
if (pkg.origin === 'harness') {
validateTarballPayload(artifact.files, pkg.tarball, {
typeRTRemoteNavigation: hasTypeRTRemoteNavigation(artifact.manifest),
})
}
if (artifact.name !== pkg.name || artifact.version !== this.manifest.version) {
throw new Error(`tarball identity mismatch: ${pkg.tarball}`)
}