feat(sdk): add developer project tooling

docs(rfc): propose SDK developer project tooling

feat: rename / docs

ci: fix windows gates

docs: revert
This commit is contained in:
imccyu
2026-07-15 18:17:38 +08:00
parent 5a8466b774
commit 42b07a7022
115 changed files with 11315 additions and 27 deletions

View File

@@ -0,0 +1,188 @@
/**
* Comment-preserving Cordis YAML document and `!!js` expression value.
*
* @module @deepseek-ai/dsh-helper/documents/cordis-yaml-file
*/
import {
Document, isMap, isSeq, parseDocument, visit, YAMLMap, YAMLSeq,
type ScalarTag,
} from 'yaml'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
/** Explicit JavaScript expression serialized with Cordis' `!!js` YAML tag. */
export class JsExpression {
/** Expression source evaluated by the Cordis include loader. */
readonly source: string
/** Create an expression value. */
constructor(source: string) {
if (source.trim().length === 0) throw new Error('JavaScript expression must not be empty')
this.source = source
}
/** Return expression source for YAML scalar stringification. */
toString(): string {
return this.source
}
}
const JS_EXPRESSION_TAG: ScalarTag = {
tag: 'tag:yaml.org,2002:js',
identify: value => value instanceof JsExpression,
resolve: value => new JsExpression(value),
stringify: item => String(item.value),
}
/** Plain domain representation of one top-level Cordis config entry. */
export interface CordisConfigEntry {
id: string
name: string
config?: Record<string, unknown>
disabled?: boolean
}
function parseYaml(text: string): Document.Parsed {
const document = parseDocument(text, {
customTags: [JS_EXPRESSION_TAG],
keepSourceTokens: true,
prettyErrors: true,
})
if (document.errors.length > 0) {
throw new Error(`invalid cordis.yml: ${document.errors.map(error => error.message).join('; ')}`)
}
if (!isSeq(document.contents)) throw new Error('invalid cordis.yml: root must be a sequence')
visit(document, { Collection: (_key, collection) => { collection.flow = false } })
return document
}
function entryFromValue(value: unknown): CordisConfigEntry {
/* v8 ignore next -- entries() calls this only after requiring a YAMLMap, whose JSON value is an object */
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('invalid cordis.yml entry: expected an object')
}
const entry = value as Record<string, unknown>
if (typeof entry.id !== 'string' || entry.id.length === 0) {
throw new Error('invalid cordis.yml entry: id must be a non-empty string')
}
if (typeof entry.name !== 'string' || entry.name.length === 0) {
throw new Error(`invalid cordis.yml entry ${entry.id}: name must be a non-empty string`)
}
if (entry.config !== undefined
&& (entry.config === null || Array.isArray(entry.config) || typeof entry.config !== 'object')) {
throw new Error(`invalid cordis.yml entry ${entry.id}: plugin config must be an object`)
}
if (entry.disabled !== undefined && typeof entry.disabled !== 'boolean') {
throw new Error(`invalid cordis.yml entry ${entry.id}: disabled must be boolean`)
}
return {
id: entry.id,
name: entry.name,
...entry.config !== undefined ? { config: entry.config as Record<string, unknown> } : {},
...entry.disabled !== undefined ? { disabled: entry.disabled } : {},
}
}
/** Editable top-level cordis.yml using YAML's document API. */
export class CordisYamlFile extends ProjectFile {
private readonly document: Document.Parsed
private constructor(document: Document.Parsed, originalText?: string) {
super('cordis.yml', originalText)
this.document = document
}
/** Create an empty Cordis config entry list. */
static create(): CordisYamlFile {
return new CordisYamlFile(parseYaml('[]\n'))
}
/** Parse an existing cordis.yml while retaining comments and scalar styles. */
static parse(text: string): CordisYamlFile {
return new CordisYamlFile(parseYaml(text), text)
}
/** Clone through YAML text so the edit session owns an independent AST. */
override clone(): CordisYamlFile {
return new CordisYamlFile(parseYaml(this.serialize()), this.originalText)
}
private sequence(): YAMLSeq {
/* v8 ignore next -- parseYaml and create both establish a sequence root */
if (!isSeq(this.document.contents)) throw new Error('cordis.yml root is not a sequence')
return this.document.contents
}
private entryNode(id: string): YAMLMap | undefined {
for (const item of this.sequence().items) {
if (!isMap(item)) continue
if (item.get('id') === id) return item
}
return undefined
}
/** Return defensive plain entry values in file order. */
entries(): CordisConfigEntry[] {
return this.sequence().items.map((item) => {
if (!isMap(item)) throw new Error('invalid cordis.yml: every entry must be a mapping')
return entryFromValue(item.toJSON())
})
}
/** Find one entry by stable id. */
entry(id: string): CordisConfigEntry | undefined {
return this.entries().find(entry => entry.id === id)
}
/** Add one new top-level entry, rejecting duplicate ids. */
addEntry(entry: CordisConfigEntry): void {
if (this.entryNode(entry.id)) throw new Error(`Cordis config entry already exists: ${entry.id}`)
this.sequence().items.push(this.document.createNode(entry))
}
/** Remove an entry by id and report whether it existed. */
removeEntry(id: string): boolean {
const sequence = this.sequence()
const index = sequence.items.findIndex(item => isMap(item) && item.get('id') === id)
if (index < 0) return false
sequence.items.splice(index, 1)
return true
}
/** Enable or disable an entry through the Loader-native field. */
setDisabled(id: string, disabled: boolean): void {
const node = this.entryNode(id)
if (!node) throw new Error(`Cordis config entry does not exist: ${id}`)
if (disabled) node.set('disabled', true)
else node.delete('disabled')
}
/** Replace only owned plugin config keys while retaining unknown user keys. */
updateOwnedConfig(id: string, ownedKeys: readonly string[], next: Record<string, unknown>): void {
const entry = this.entryNode(id)
if (!entry) throw new Error(`Cordis config entry does not exist: ${id}`)
let config: unknown = entry.get('config', true)
if (config === undefined || config === null) {
config = new YAMLMap()
entry.set('config', config)
}
if (!isMap(config)) throw new Error(`Cordis config entry ${id} plugin config is not a mapping`)
for (const key of ownedKeys) config.delete(key)
for (const [key, value] of Object.entries(next)) config.set(key, this.document.createNode(value))
if (config.items.length === 0) entry.delete('config')
}
/** Validate ids, names, plugin config maps, and id uniqueness. */
override validate(): void {
const seen = new Set<string>()
for (const entry of this.entries()) {
if (seen.has(entry.id)) throw new Error(`duplicate Cordis config entry id: ${entry.id}`)
seen.add(entry.id)
}
}
/** Serialize through the YAML document while retaining untouched trivia. */
override serialize(): string {
return withTrailingNewline(this.document.toString({ lineWidth: 0 }))
}
}

View File

@@ -0,0 +1,111 @@
/**
* Ownership-aware, line-preserving dotenv document.
*
* @module @deepseek-ai/dsh-helper/documents/env-file
*/
import { ProjectFile, withTrailingNewline } from './project-file.ts'
interface ParsedVariable {
index: number
value: string
}
const VARIABLE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/
const VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
/** `.env` appends missing variables; `.env.example` supports managed replacement and removal. */
export class EnvFile extends ProjectFile {
private readonly lines: string[]
private constructor(relativePath: '.env' | '.env.example', lines: string[], originalText?: string) {
super(relativePath, originalText)
this.lines = [...lines]
}
/** Create an empty environment file. */
static create(relativePath: '.env' | '.env.example'): EnvFile {
return new EnvFile(relativePath, [])
}
/** Parse an existing environment file without rewriting unknown lines. */
static parse(relativePath: '.env' | '.env.example', text: string): EnvFile {
const normalized = text.replace(/\n$/, '')
return new EnvFile(relativePath, normalized.length === 0 ? [] : normalized.split('\n'), text)
}
/** Clone the current line model. */
override clone(): EnvFile {
return new EnvFile(this.relativePath as '.env' | '.env.example', this.lines, this.originalText)
}
private variables(): Map<string, ParsedVariable[]> {
const values = new Map<string, ParsedVariable[]>()
this.lines.forEach((line, index) => {
const match = VARIABLE.exec(line)
if (!match) return
const name = match[1]
const value = match[2]
/* v8 ignore next -- both captures are mandatory in VARIABLE */
if (name === undefined || value === undefined) return
const occurrences = values.get(name) ?? []
occurrences.push({ index, value })
values.set(name, occurrences)
})
return values
}
/** Read the effective value; append-only `.env` accepts duplicates and uses the last declaration. */
get(name: string): string | undefined {
const occurrences = this.variables().get(name) ?? []
if (this.relativePath === '.env.example' && occurrences.length > 1) {
throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
}
return occurrences.at(-1)?.value
}
/** Add or replace one SDK-managed `.env.example` variable while preserving unrelated lines. */
set(name: string, value: string): void {
if (this.relativePath !== '.env.example') throw new Error('.env is append-only')
if (!VARIABLE_NAME.test(name)) throw new Error(`invalid environment variable name: ${name}`)
const occurrences = this.variables().get(name) ?? []
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
const line = `${name}=${value}`
if (occurrences[0]) this.lines[occurrences[0].index] = line
else this.lines.push(line)
}
/** Append a missing `.env` variable and optional comment without changing any existing declaration. */
append(name: string, value: string, comment?: string): boolean {
if (this.relativePath !== '.env') throw new Error('.env.example is SDK-managed')
if (!VARIABLE_NAME.test(name)) throw new Error(`invalid environment variable name: ${name}`)
if (comment !== undefined && (!comment || comment.includes('\n'))) {
throw new Error('environment comment must be one non-empty line')
}
if (this.variables().has(name)) return false
if (comment) this.lines.push(`# ${comment}`)
this.lines.push(`${name}=${value}`)
return true
}
/** Remove one SDK-managed `.env.example` variable while retaining every other line. */
remove(name: string): void {
if (this.relativePath !== '.env.example') throw new Error('.env is append-only')
const occurrences = this.variables().get(name) ?? []
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
if (occurrences[0]) this.lines.splice(occurrences[0].index, 1)
}
/** Validate the managed placeholder file; append-only `.env` accepts duplicate declarations. */
override validate(): void {
if (this.relativePath === '.env') return
for (const [name, occurrences] of this.variables()) {
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
}
}
/** Serialize all retained lines with one trailing newline. */
override serialize(): string {
return withTrailingNewline(this.lines.join('\n'))
}
}

View File

@@ -0,0 +1,159 @@
/**
* Structured package.json document owned by an SDK project.
*
* @module @deepseek-ai/dsh-helper/documents/package-json-file
*/
import { ProjectFile, withTrailingNewline } from './project-file.ts'
/** NPM dependency sections managed by the SDK. */
export type NpmDependencySection = 'dependencies' | 'devDependencies'
/** JSON shape retained by {@link PackageJsonFile}. */
export interface PackageManifest {
name?: string
version?: string
private?: boolean
description?: string
type?: string
packageManager?: string
scripts?: Record<string, string>
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
workspaces?: string[]
resolutions?: Record<string, string>
[key: string]: unknown
}
function parseManifest(text: string): PackageManifest {
let value: unknown
try {
value = JSON.parse(text)
} catch (error) {
throw new Error(`invalid package.json: ${String(error)}`)
}
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('invalid package.json: root must be an object')
}
return value as PackageManifest
}
function sortedRecord(value: Record<string, string>): Record<string, string> {
return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)))
}
/** Editable, deterministic package.json representation. */
export class PackageJsonFile extends ProjectFile {
private readonly manifest: PackageManifest
private constructor(manifest: PackageManifest, originalText?: string) {
super('package.json', originalText)
this.manifest = structuredClone(manifest)
}
/** Create a new package manifest from a complete rendered template. */
static create(text: string): PackageJsonFile {
return new PackageJsonFile(parseManifest(text))
}
/** Parse an existing package.json document. */
static parse(text: string): PackageJsonFile {
return new PackageJsonFile(parseManifest(text), text)
}
/** Clone this document and its nested manifest data. */
override clone(): PackageJsonFile {
return new PackageJsonFile(this.manifest, this.originalText)
}
/** Return a defensive copy of the manifest. */
value(): Readonly<PackageManifest> {
return structuredClone(this.manifest)
}
/** Set one package script. */
setScript(name: string, command: string): void {
this.manifest.scripts ??= {}
this.manifest.scripts[name] = command
}
/** Set one NPM dependency in its runtime or development section. */
setNpmDependency(section: NpmDependencySection, name: string, spec: string): void {
this.manifest[section] ??= {}
this.manifest[section][name] = spec
}
/** Remove one NPM dependency from a section. */
removeNpmDependency(section: NpmDependencySection, name: string): void {
delete this.manifest[section]?.[name]
}
/** Read an NPM dependency spec from either managed section. */
npmDependency(name: string): { section: NpmDependencySection; spec: string } | undefined {
for (const section of ['dependencies', 'devDependencies'] as const) {
const spec = this.manifest[section]?.[name]
if (spec !== undefined) return { section, spec }
}
return undefined
}
/** Return all managed NPM dependency names. */
npmDependencyNames(): string[] {
return [...new Set([
...Object.keys(this.manifest.dependencies ?? {}),
...Object.keys(this.manifest.devDependencies ?? {}),
])].sort()
}
/** Add a package-manager workspace glob. */
addWorkspace(pattern: string): void {
const workspaces = this.manifest.workspaces ??= []
if (!workspaces.includes(pattern)) workspaces.push(pattern)
}
/** Set or remove the packageManager field. */
setPackageManager(value: string | undefined): void {
if (value === undefined) delete this.manifest.packageManager
else this.manifest.packageManager = value
}
/** Pin a Yarn resolution used by live-link projects. */
setResolution(name: string, spec: string): void {
this.manifest.resolutions ??= {}
this.manifest.resolutions[name] = spec
}
/** Validate the fields the SDK relies on. */
override validate(): void {
if (!this.manifest.name || typeof this.manifest.name !== 'string') {
throw new Error('package.json name must be a non-empty string')
}
for (const section of ['scripts', 'dependencies', 'devDependencies'] as const) {
const value: unknown = this.manifest[section]
if (value === undefined) continue
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error(`package.json ${section} must be an object`)
}
for (const [key, item] of Object.entries(value)) {
if (typeof item !== 'string' || item.length === 0) {
throw new Error(`package.json ${section}.${key} must be a non-empty string`)
}
}
}
if (this.manifest.workspaces !== undefined
&& (!Array.isArray(this.manifest.workspaces) || this.manifest.workspaces.some(item => typeof item !== 'string'))) {
throw new Error('package.json workspaces must be an array of strings')
}
}
/** Serialize with deterministic managed maps and two-space JSON formatting. */
override serialize(): string {
const value: PackageManifest = structuredClone(this.manifest)
if (this.manifest.scripts) value.scripts = sortedRecord(this.manifest.scripts)
if (this.manifest.dependencies) value.dependencies = sortedRecord(this.manifest.dependencies)
if (this.manifest.devDependencies) value.devDependencies = sortedRecord(this.manifest.devDependencies)
if (this.manifest.workspaces) value.workspaces = [...this.manifest.workspaces].sort()
if (this.manifest.resolutions) value.resolutions = sortedRecord(this.manifest.resolutions)
return withTrailingNewline(JSON.stringify(value, null, 2))
}
}

View File

@@ -0,0 +1,76 @@
/**
* Structured pnpm workspace configuration for generated SDK projects.
*
* @module @deepseek-ai/dsh-helper/documents/pnpm-workspace-file
*/
import { parse, stringify } from 'yaml'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
/** Generated pnpm-workspace.yaml model. */
export class PnpmWorkspaceFile extends ProjectFile {
private readonly packages = new Set<string>()
private autoInstallPeers = true
private constructor(originalText?: string) {
super('pnpm-workspace.yaml', originalText)
}
/** Create a pnpm workspace document. */
static create(): PnpmWorkspaceFile {
return new PnpmWorkspaceFile()
}
/** Parse the workspace fields the SDK owns. */
static parse(text: string): PnpmWorkspaceFile {
const value: unknown = parse(text)
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('pnpm-workspace.yaml root must be an object')
}
const input = value as Record<string, unknown>
if (!Array.isArray(input.packages) || input.packages.some(item => typeof item !== 'string')) {
throw new Error('pnpm-workspace.yaml packages must be an array of strings')
}
const document = new PnpmWorkspaceFile(text)
for (const pattern of input.packages) document.packages.add(pattern as string)
if (input.autoInstallPeers !== undefined && typeof input.autoInstallPeers !== 'boolean') {
throw new Error('pnpm-workspace.yaml autoInstallPeers must be boolean')
}
document.autoInstallPeers = input.autoInstallPeers !== false
return document
}
/** Clone workspace globs and peer-install policy. */
override clone(): PnpmWorkspaceFile {
const clone = new PnpmWorkspaceFile(this.originalText)
for (const pattern of this.packages) clone.packages.add(pattern)
clone.autoInstallPeers = this.autoInstallPeers
return clone
}
/** Add one package workspace glob. */
addPackage(pattern: string): void {
this.packages.add(pattern)
}
/** Disable registry peer auto-installation for live-link projects. */
disableAutoInstallPeers(): void {
this.autoInstallPeers = false
}
/** Validate workspace globs. */
override validate(): void {
for (const pattern of this.packages) {
if (pattern.trim().length === 0) throw new Error('pnpm workspace pattern must not be empty')
}
}
/** Serialize pnpm's workspace and peer policy. */
override serialize(): string {
return withTrailingNewline(stringify({
packages: [...this.packages].sort(),
...this.autoInstallPeers ? {} : { autoInstallPeers: false },
allowBuilds: { esbuild: true },
}, { lineWidth: 0 }))
}
}

View File

@@ -0,0 +1,60 @@
/**
* Base abstraction for one file in an SDK project snapshot.
*
* @module @deepseek-ai/dsh-helper/documents/project-file
*/
/** Return text with exactly one trailing newline. */
export function withTrailingNewline(text: string): string {
return text.replace(/\n*$/, '') + '\n'
}
/** One cloneable, validatable project file. */
export abstract class ProjectFile {
/** Project-relative POSIX path. */
readonly relativePath: string
/** Text observed when the document entered the snapshot; absent for a new file. */
readonly originalText: string | undefined
protected constructor(relativePath: string, originalText?: string) {
if (relativePath.startsWith('/') || relativePath.split('/').includes('..')) {
throw new Error(`project document path must stay inside the project: ${relativePath}`)
}
this.relativePath = relativePath
this.originalText = originalText
}
/** Clone the document for an isolated edit session. */
abstract clone(): ProjectFile
/** Validate the document's complete current state. */
abstract validate(): void
/** Serialize the complete current file. */
abstract serialize(): string
}
/** Immutable complete-text file used by one-shot artifacts. */
export class TextProjectFile extends ProjectFile {
private readonly text: string
/** Create a complete-text project document. */
constructor(relativePath: string, text: string, originalText?: string) {
super(relativePath, originalText)
this.text = withTrailingNewline(text)
}
/** Clone this immutable document. */
override clone(): TextProjectFile {
return new TextProjectFile(this.relativePath, this.text, this.originalText)
}
/** Complete text artifacts have no extra structural validation. */
override validate(): void {}
/** Return the complete artifact text. */
override serialize(): string {
return this.text
}
}

View File

@@ -0,0 +1,89 @@
/**
* Comment-preserving root tsconfig editor for local plugin references.
*
* @module @deepseek-ai/dsh-helper/documents/tsconfig-file
*/
import { applyEdits, modify, parse, type ParseError } from 'jsonc-parser'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
const FORMAT = { insertSpaces: true, tabSize: 2, eol: '\n' }
function parseConfig(text: string): Record<string, unknown> {
const errors: ParseError[] = []
const value: unknown = parse(text, errors, { allowTrailingComma: true, disallowComments: false })
if (errors.length > 0 || value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('tsconfig.json is not a valid JSONC object')
}
return value as Record<string, unknown>
}
/** Root tsconfig document edited with jsonc-parser patches. */
export class TsConfigFile extends ProjectFile {
private text: string
private constructor(text: string, originalText?: string) {
super('tsconfig.json', originalText)
this.text = withTrailingNewline(text)
}
/** Create the root project-reference config. */
static create(): TsConfigFile {
return new TsConfigFile(JSON.stringify({
extends: './tsconfig.base.json',
compilerOptions: { noEmit: true },
include: ['index.ts'],
references: [],
}, null, 2))
}
/** Parse an existing root tsconfig. */
static parse(text: string): TsConfigFile {
parseConfig(text)
return new TsConfigFile(text, text)
}
/** Clone the current JSONC text. */
override clone(): TsConfigFile {
return new TsConfigFile(this.text, this.originalText)
}
/** Add one project reference while retaining comments and formatting. */
addReference(path: string): void {
const value = parseConfig(this.text)
const references = value.references
if (references !== undefined && !Array.isArray(references)) {
throw new Error('tsconfig.json references must be an array')
}
const typed = (references ?? []) as unknown[]
for (const item of typed) {
if (item === null || Array.isArray(item) || typeof item !== 'object' || typeof (item as { path?: unknown }).path !== 'string') {
throw new Error('tsconfig.json references must contain { path: string } objects')
}
}
if (typed.some(item => (item as { path: string }).path === path)) return
this.text = applyEdits(this.text, modify(
this.text,
['references', typed.length],
{ path },
{ formattingOptions: FORMAT, isArrayInsertion: true },
))
}
/** Validate JSONC and the project-reference shape. */
override validate(): void {
const value = parseConfig(this.text)
if (value.references === undefined) return
if (!Array.isArray(value.references)) throw new Error('tsconfig.json references must be an array')
for (const item of value.references) {
if (item === null || Array.isArray(item) || typeof item !== 'object' || typeof (item as { path?: unknown }).path !== 'string') {
throw new Error('tsconfig.json references must contain { path: string } objects')
}
}
}
/** Return patched JSONC text. */
override serialize(): string {
return withTrailingNewline(this.text)
}
}