refactor(packages): dissolve ui/ and rename sdk/ to scaffold/
git mv per the regrouping RFC: the five human-collaboration seams and tui join packages/interaction/, app-boot becomes packages/boot/, and jsonrpc joins the renamed scaffold/ (formerly sdk/) as its server half beside client/protocol/create-sdk/helper/scripts/telemetry, whose folders drop the legacy sdk- prefix. Three new group README triplets replace the ui/ and sdk/ ones; tsconfig references/paths/globs, knip keys, vitest globs, gate scripts, catalogs, docs, and the lockfile follow. Adds the four settled FIXME rename markers (dsh-sdk-server, dsh-sdk-telemetry, dsh-sdk-helper, dsh-sdk-scripts). The scaffold folders diverge from their npm names until those renames land, so tsconfig.base.json maps the three affected names explicitly beside the group wildcard. Also repairs two pre-existing stale-path classes the strengthened sweep surfaced: docs/web-styling.md's retired web-ui host package and type-model spec fixture-literal joins. app-boot's three Loader-composition specs time out at the default 5s under full-suite parallel load on this filesystem (pre-existing; pass isolated with --testTimeout=30000); interaction/scaffold/boot suites otherwise green (687 passed).
This commit is contained in:
190
packages/scaffold/helper/src/documents/cordis-yaml-file.ts
Normal file
190
packages/scaffold/helper/src/documents/cordis-yaml-file.ts
Normal file
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* 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, commentedExample?: string): void {
|
||||
if (this.entryNode(entry.id)) throw new Error(`Cordis config entry already exists: ${entry.id}`)
|
||||
const node = this.document.createNode(entry)
|
||||
if (commentedExample) node.comment = commentedExample.split('\n').map(line => ` ${line}`).join('\n')
|
||||
this.sequence().items.push(node)
|
||||
}
|
||||
|
||||
/** 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 }))
|
||||
}
|
||||
}
|
||||
111
packages/scaffold/helper/src/documents/env-file.ts
Normal file
111
packages/scaffold/helper/src/documents/env-file.ts
Normal 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, relativePath === '.env' ? 0o600 : undefined)
|
||||
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'))
|
||||
}
|
||||
}
|
||||
169
packages/scaffold/helper/src/documents/package-json-file.ts
Normal file
169
packages/scaffold/helper/src/documents/package-json-file.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/** Read one package script. */
|
||||
script(name: string): string | undefined {
|
||||
return this.manifest.scripts?.[name]
|
||||
}
|
||||
|
||||
/** Remove one package script. */
|
||||
removeScript(name: string): void {
|
||||
delete this.manifest.scripts?.[name]
|
||||
}
|
||||
|
||||
/** 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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Structured pnpm workspace configuration for generated SDK projects.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/documents/pnpm-workspace-file
|
||||
*/
|
||||
|
||||
import {
|
||||
isMap, isScalar, isSeq, parseDocument,
|
||||
type Document, type Scalar, type YAMLMap, type YAMLSeq,
|
||||
} from 'yaml'
|
||||
import { ProjectFile, withTrailingNewline } from './project-file.ts'
|
||||
|
||||
function parseYaml(text: string): Document.Parsed {
|
||||
const document = parseDocument(text, { keepSourceTokens: true, prettyErrors: true })
|
||||
if (document.errors.length > 0) {
|
||||
throw new Error(`invalid pnpm-workspace.yaml: ${document.errors.map(error => error.message).join('; ')}`)
|
||||
}
|
||||
if (!isMap(document.contents)) throw new Error('pnpm-workspace.yaml root must be an object')
|
||||
return document
|
||||
}
|
||||
|
||||
/** Generated pnpm-workspace.yaml model. */
|
||||
export class PnpmWorkspaceFile extends ProjectFile {
|
||||
private readonly document: Document.Parsed
|
||||
|
||||
private constructor(document: Document.Parsed, originalText?: string) {
|
||||
super('pnpm-workspace.yaml', originalText)
|
||||
this.document = document
|
||||
}
|
||||
|
||||
/** Create a pnpm workspace document. */
|
||||
static create(): PnpmWorkspaceFile {
|
||||
const document = new PnpmWorkspaceFile(parseYaml('{}\n'))
|
||||
document.mapping().set('packages', document.document.createNode([]))
|
||||
document.mapping().set('allowBuilds', document.document.createNode({ esbuild: true }))
|
||||
return document
|
||||
}
|
||||
|
||||
/** Parse the workspace fields the SDK owns while retaining all other YAML. */
|
||||
static parse(text: string): PnpmWorkspaceFile {
|
||||
const document = new PnpmWorkspaceFile(parseYaml(text), text)
|
||||
document.packageSequence()
|
||||
const autoInstallPeers = document.mapping().get('autoInstallPeers')
|
||||
if (autoInstallPeers !== undefined && typeof autoInstallPeers !== 'boolean') {
|
||||
throw new Error('pnpm-workspace.yaml autoInstallPeers must be boolean')
|
||||
}
|
||||
return document
|
||||
}
|
||||
|
||||
/** Clone the complete comment-preserving workspace document. */
|
||||
override clone(): PnpmWorkspaceFile {
|
||||
return new PnpmWorkspaceFile(parseYaml(this.serialize()), this.originalText)
|
||||
}
|
||||
|
||||
/** Add one package workspace glob. */
|
||||
addPackage(pattern: string): void {
|
||||
const packages = this.packageSequence()
|
||||
if (packages.items.some(item => item.value === pattern)) return
|
||||
packages.add(this.document.createNode(pattern))
|
||||
}
|
||||
|
||||
/** Disable registry peer auto-installation for live-link projects. */
|
||||
disableAutoInstallPeers(): void {
|
||||
this.mapping().set('autoInstallPeers', false)
|
||||
}
|
||||
|
||||
/** Validate workspace globs. */
|
||||
override validate(): void {
|
||||
for (const pattern of this.packageValues()) {
|
||||
if (pattern.trim().length === 0) throw new Error('pnpm workspace pattern must not be empty')
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialize the workspace while retaining unknown settings and comments. */
|
||||
override serialize(): string {
|
||||
return withTrailingNewline(this.document.toString({ lineWidth: 0 }))
|
||||
}
|
||||
|
||||
private mapping(): YAMLMap {
|
||||
/* v8 ignore next -- parseYaml and create both establish a mapping root */
|
||||
if (!isMap(this.document.contents)) throw new Error('pnpm-workspace.yaml root must be an object')
|
||||
return this.document.contents
|
||||
}
|
||||
|
||||
private packageSequence(): YAMLSeq<Scalar<string>> {
|
||||
const packages = this.mapping().get('packages', true)
|
||||
if (!isSeq(packages) || packages.items.some(item => !isScalar(item) || typeof item.value !== 'string')) {
|
||||
throw new Error('pnpm-workspace.yaml packages must be an array of strings')
|
||||
}
|
||||
return packages as YAMLSeq<Scalar<string>>
|
||||
}
|
||||
|
||||
private packageValues(): string[] {
|
||||
return this.packageSequence().items.map(item => item.value)
|
||||
}
|
||||
}
|
||||
64
packages/scaffold/helper/src/documents/project-file.ts
Normal file
64
packages/scaffold/helper/src/documents/project-file.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 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
|
||||
|
||||
/** Permission bits used only when the file is first created. */
|
||||
readonly createMode: number | undefined
|
||||
|
||||
protected constructor(relativePath: string, originalText?: string, createMode?: number) {
|
||||
if (relativePath.startsWith('/') || relativePath.split('/').includes('..')) {
|
||||
throw new Error(`project document path must stay inside the project: ${relativePath}`)
|
||||
}
|
||||
this.relativePath = relativePath
|
||||
this.originalText = originalText
|
||||
this.createMode = createMode
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
}
|
||||
89
packages/scaffold/helper/src/documents/tsconfig-file.ts
Normal file
89
packages/scaffold/helper/src/documents/tsconfig-file.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
100
packages/scaffold/helper/src/features/builtin/app.ts
Normal file
100
packages/scaffold/helper/src/features/builtin/app.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Required run-interface app feature.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/builtin/app
|
||||
*/
|
||||
|
||||
import { featureId } from '../../ids.ts'
|
||||
import type { ProjectProfile, RunInterface } from '../../project/types.ts'
|
||||
import {
|
||||
createAppPackageScripts,
|
||||
createAppProjectArtifacts,
|
||||
createProjectTemplateContext,
|
||||
} from '../../templates/project-template.ts'
|
||||
import {
|
||||
FeatureOption,
|
||||
ExclusiveOptionFeature,
|
||||
} from '../feature.ts'
|
||||
import { ProjectContribution, type ProjectResource } from '../resources.ts'
|
||||
import {
|
||||
npmCordisConfigEntry,
|
||||
ownedTextFile,
|
||||
packageScript,
|
||||
requiredString,
|
||||
} from './helpers.ts'
|
||||
|
||||
const ID = featureId('app')
|
||||
|
||||
function appProjectResources(
|
||||
profile: ProjectProfile,
|
||||
runInterface: RunInterface,
|
||||
): readonly ProjectResource[] {
|
||||
const context = createProjectTemplateContext(profile, runInterface)
|
||||
const scripts = createAppPackageScripts()
|
||||
return [
|
||||
...createAppProjectArtifacts(context).map(document => (
|
||||
ownedTextFile(ID, document.relativePath, document.serialize())
|
||||
)),
|
||||
packageScript(ID, 'dev', scripts.dev),
|
||||
packageScript(ID, 'start', scripts.start),
|
||||
]
|
||||
}
|
||||
|
||||
class AppOption extends FeatureOption {
|
||||
override readonly id: RunInterface
|
||||
override readonly label: string
|
||||
|
||||
constructor(id: RunInterface, label: string) {
|
||||
super()
|
||||
this.id = id
|
||||
this.label = label
|
||||
}
|
||||
|
||||
/** Identify options by their unique front door, not the shared interaction service. */
|
||||
override markerConfigEntries(): readonly { id: string; name: string }[] {
|
||||
switch (this.id) {
|
||||
case 'acp': return [{ id: 'acp', name: '@deepseek-ai/dsh-acp' }]
|
||||
case 'embed': return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Embed is identified by the configured loop with no external front door. */
|
||||
override matchesConfigEntries(entries: readonly { id: string; name: string }[], profile: ProjectProfile): boolean {
|
||||
if (this.id !== 'embed') return super.matchesConfigEntries(entries, profile)
|
||||
return entries.some(entry => entry.id === 'agent-loop' && entry.name === '@deepseek-ai/dsh-agent-loop')
|
||||
&& !entries.some(entry => entry.name === '@deepseek-ai/dsh-acp')
|
||||
}
|
||||
|
||||
override contribution(profile: ProjectProfile): ProjectContribution {
|
||||
switch (this.id) {
|
||||
case 'acp':
|
||||
return new ProjectContribution([
|
||||
...appProjectResources(profile, this.id),
|
||||
...npmCordisConfigEntry(ID, {
|
||||
id: 'acp',
|
||||
name: '@deepseek-ai/dsh-acp',
|
||||
config: { model: profile.runtime.model },
|
||||
}, ['model'], config => requiredString(config, 'model')),
|
||||
])
|
||||
case 'embed':
|
||||
return new ProjectContribution(appProjectResources(profile, this.id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Required app selection represented by ACP or embed options. */
|
||||
export class AppFeature extends ExclusiveOptionFeature {
|
||||
override readonly id = ID
|
||||
override readonly summary = 'Run interface'
|
||||
override readonly required = true
|
||||
override readonly requires = [featureId('spine')]
|
||||
override readonly options = [
|
||||
new AppOption('acp', 'ACP automation server'),
|
||||
new AppOption('embed', 'Embedded context'),
|
||||
]
|
||||
|
||||
/** Default to the profile's already selected front door. */
|
||||
override defaultOptions(profile: ProjectProfile): readonly string[] {
|
||||
return [profile.runInterface]
|
||||
}
|
||||
}
|
||||
122
packages/scaffold/helper/src/features/builtin/helpers.ts
Normal file
122
packages/scaffold/helper/src/features/builtin/helpers.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Small resource constructors shared by builtin feature modules.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/builtin/helpers
|
||||
*/
|
||||
|
||||
import type { CordisConfigEntry } from '../../documents/cordis-yaml-file.ts'
|
||||
import { TextProjectFile } from '../../documents/project-file.ts'
|
||||
import { resourceKey } from '../../ids.ts'
|
||||
import type {
|
||||
CordisConfigEntryResource,
|
||||
EnvironmentResource,
|
||||
OwnedFileResource,
|
||||
NpmDependencyResource,
|
||||
PackageScriptResource,
|
||||
} from '../resources.ts'
|
||||
|
||||
/** Return the installable package name for a bare package or package subpath. */
|
||||
function installablePackageName(specifier: string): string {
|
||||
const segments = specifier.split('/')
|
||||
const expectedSegments = specifier.startsWith('@') ? 2 : 1
|
||||
if (segments.length < expectedSegments || segments.slice(0, expectedSegments).some(segment => segment.length === 0)) {
|
||||
throw new Error(`invalid bare package specifier: ${JSON.stringify(specifier)}`)
|
||||
}
|
||||
return segments.slice(0, expectedSegments).join('/')
|
||||
}
|
||||
|
||||
/** Create a runtime NPM dependency resource. */
|
||||
function npmDependency(_owner: string, specifier: string): NpmDependencyResource {
|
||||
const name = installablePackageName(specifier)
|
||||
return {
|
||||
kind: 'npm-dependency',
|
||||
key: resourceKey(`npm-dependency:${name}`),
|
||||
name,
|
||||
section: 'dependencies',
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a feature-owned package script that is replaceable only while unchanged. */
|
||||
export function packageScript(_owner: string, name: string, command: string): PackageScriptResource {
|
||||
return {
|
||||
kind: 'package-script',
|
||||
key: resourceKey(`package-script:${name}`),
|
||||
name,
|
||||
command,
|
||||
removeOnlyWhenUnchanged: true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a Cordis config entry resource with explicitly owned config keys. */
|
||||
export function cordisConfigEntry(
|
||||
_owner: string,
|
||||
value: CordisConfigEntry,
|
||||
ownedConfigKeys: readonly string[] = Object.keys(value.config ?? {}),
|
||||
validateConfig?: CordisConfigEntryResource['validateConfig'],
|
||||
): CordisConfigEntryResource {
|
||||
return {
|
||||
kind: 'cordis-config-entry',
|
||||
key: resourceKey(`cordis-config-entry:${value.id}`),
|
||||
entry: value,
|
||||
ownedConfigKeys,
|
||||
...validateConfig ? { validateConfig } : {},
|
||||
}
|
||||
}
|
||||
|
||||
/** Couple one bare-package or subpath Cordis entry to its installable NPM package. */
|
||||
export function npmCordisConfigEntry(
|
||||
owner: string,
|
||||
value: CordisConfigEntry,
|
||||
ownedConfigKeys: readonly string[] = Object.keys(value.config ?? {}),
|
||||
validateConfig?: CordisConfigEntryResource['validateConfig'],
|
||||
): readonly [NpmDependencyResource, CordisConfigEntryResource] {
|
||||
return [
|
||||
npmDependency(owner, value.name),
|
||||
cordisConfigEntry(owner, value, ownedConfigKeys, validateConfig),
|
||||
]
|
||||
}
|
||||
|
||||
/** Create a secret/environment binding resource. */
|
||||
export function environment(
|
||||
_owner: string,
|
||||
name: string,
|
||||
value: string | undefined,
|
||||
comment?: string,
|
||||
): EnvironmentResource {
|
||||
return {
|
||||
kind: 'environment',
|
||||
key: resourceKey(`environment:${name}`),
|
||||
name,
|
||||
...value === undefined ? {} : { value },
|
||||
exampleValue: '',
|
||||
...comment === undefined ? {} : { comment },
|
||||
}
|
||||
}
|
||||
|
||||
/** Create an owned complete-text file that is removable only while unchanged. */
|
||||
export function ownedTextFile(_owner: string, path: string, text: string): OwnedFileResource {
|
||||
return {
|
||||
kind: 'owned-file',
|
||||
key: resourceKey(`file:${path}`),
|
||||
document: new TextProjectFile(path, text),
|
||||
removeOnlyWhenUnchanged: true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate a config key as a string when present. */
|
||||
export function optionalString(config: Readonly<Record<string, unknown>>, key: string): string[] {
|
||||
return config[key] === undefined || typeof config[key] === 'string' ? [] : [`${key} must be a string`]
|
||||
}
|
||||
|
||||
/** Validate a config key as a non-empty string when required. */
|
||||
export function requiredString(config: Readonly<Record<string, unknown>>, key: string): string[] {
|
||||
return typeof config[key] === 'string' && config[key].length > 0 ? [] : [`${key} must be a non-empty string`]
|
||||
}
|
||||
|
||||
/** Validate a config key as an array of strings. */
|
||||
export function stringArray(config: Readonly<Record<string, unknown>>, key: string): string[] {
|
||||
const value = config[key]
|
||||
return Array.isArray(value) && value.every(item => typeof item === 'string')
|
||||
? []
|
||||
: [`${key} must be an array of strings`]
|
||||
}
|
||||
368
packages/scaffold/helper/src/features/builtin/index.ts
Normal file
368
packages/scaffold/helper/src/features/builtin/index.ts
Normal file
@@ -0,0 +1,368 @@
|
||||
/**
|
||||
* Ordered builtin feature catalog: behavior entities only where project
|
||||
* context changes the contribution, typed specs everywhere else.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/builtin
|
||||
*/
|
||||
|
||||
import type { Config as ClaudeHooksConfig } from '@deepseek-ai/dsh-hooks-claude'
|
||||
import type { Config as CodexHooksConfig } from '@deepseek-ai/dsh-hooks-codex'
|
||||
import type { Config as JsonlConfig } from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
import type { Config as SqliteConfig } from '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
import type { Config as ToolSubagentConfig } from '@deepseek-ai/dsh-tool-subagent'
|
||||
import type { Config as ToolTodoConfig } from '@deepseek-ai/dsh-tool-todo'
|
||||
import type { Config as ToolWebConfig } from '@deepseek-ai/dsh-tool-web'
|
||||
import type { ProjectProfile } from '../../project/types.ts'
|
||||
import { defineFeatures } from '../define-feature.ts'
|
||||
import { FeatureRegistry } from '../registry.ts'
|
||||
import { AppFeature } from './app.ts'
|
||||
import { ProviderFeature } from './provider.ts'
|
||||
import { SpineFeature } from './spine.ts'
|
||||
|
||||
/**
|
||||
* Build and definition-check the complete builtin set for one project profile.
|
||||
* @param profile - project context used to validate conditional contributions.
|
||||
* @returns ordered builtin feature registry.
|
||||
*/
|
||||
export function createBuiltinRegistry(profile: ProjectProfile): FeatureRegistry {
|
||||
return new FeatureRegistry(defineFeatures([
|
||||
new ProviderFeature(),
|
||||
new SpineFeature(),
|
||||
{
|
||||
id: 'bash',
|
||||
summary: 'Command execution',
|
||||
mode: 'exclusive',
|
||||
required: true,
|
||||
baseResources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'subprocess', package: '@deepseek-ai/dsh-subprocess-local' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'bash-env', package: '@deepseek-ai/dsh-bash-env' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-bash', package: '@deepseek-ai/dsh-tool-bash' },
|
||||
],
|
||||
options: [
|
||||
{
|
||||
id: 'local',
|
||||
label: 'Local executor',
|
||||
default: true,
|
||||
resources: [{ kind: 'npm-cordis-config-entry', id: 'bash', package: '@deepseek-ai/dsh-bash-local' }],
|
||||
},
|
||||
{
|
||||
id: 'sandbox',
|
||||
label: 'Sandboxed executor',
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'sandbox', package: '@deepseek-ai/dsh-sandbox-local' },
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'bash',
|
||||
package: '@deepseek-ai/dsh-bash-sandbox',
|
||||
commentedExample: `Uncomment to allow writes under the project workspace.
|
||||
config:
|
||||
mode: workspace-write
|
||||
workspaceRoot: !!js process.cwd()`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
new AppFeature(),
|
||||
{
|
||||
id: 'persistence',
|
||||
summary: 'Durable session storage',
|
||||
mode: 'exclusive',
|
||||
required: true,
|
||||
options: [
|
||||
{
|
||||
id: 'jsonl',
|
||||
label: 'JSONL files',
|
||||
default: true,
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'session-persistence',
|
||||
package: '@deepseek-ai/dsh-session-persistence-jsonl',
|
||||
config: { root: './.sessions' } satisfies JsonlConfig,
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'sqlite',
|
||||
label: 'SQLite database',
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'session-persistence',
|
||||
package: '@deepseek-ai/dsh-session-persistence-sqlite',
|
||||
config: { path: './.sessions/sessions.sqlite' } satisfies SqliteConfig,
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'hmr',
|
||||
summary: 'Hot-module reload',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'default',
|
||||
label: 'Cordis HMR',
|
||||
default: true,
|
||||
resources: [{ kind: 'npm-cordis-config-entry', id: 'hmr', package: '@cordisjs/plugin-hmr' }],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'fs',
|
||||
summary: 'Read, write, and edit local files',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'local',
|
||||
label: 'Local filesystem',
|
||||
default: true,
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'fs-local', package: '@deepseek-ai/dsh-fs-local' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'fs-policy', package: '@deepseek-ai/dsh-fs-policy' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-fs', package: '@deepseek-ai/dsh-tool-fs' },
|
||||
],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'todo',
|
||||
summary: 'Model-facing task tracking',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'default',
|
||||
label: 'todo_write tool',
|
||||
default: true,
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'tool-todo',
|
||||
package: '@deepseek-ai/dsh-tool-todo',
|
||||
config: { allowParallelInProgress: true } satisfies ToolTodoConfig,
|
||||
}],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'skill',
|
||||
summary: 'Local skill discovery',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'default',
|
||||
label: 'Local skills and skill tool',
|
||||
default: true,
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'skill', package: '@deepseek-ai/dsh-skill' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'skill-local', package: '@deepseek-ai/dsh-skill-local' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-skill', package: '@deepseek-ai/dsh-tool-skill' },
|
||||
],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'web',
|
||||
summary: 'Web search and fetch tools',
|
||||
mode: 'exclusive',
|
||||
suggests: ['timeout-policy'],
|
||||
baseResources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'web', package: '@deepseek-ai/dsh-web' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'web-fetch-local', package: '@deepseek-ai/dsh-web-fetch-local' },
|
||||
],
|
||||
options: [
|
||||
{
|
||||
id: 'deepseek-official',
|
||||
label: 'DeepSeek search',
|
||||
default: true,
|
||||
markers: [{ id: 'web-search-deepseek', name: '@deepseek-ai/dsh-web-search-deepseek' }],
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'web-search-deepseek', package: '@deepseek-ai/dsh-web-search-deepseek' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'exa',
|
||||
label: 'Exa search',
|
||||
secrets: [{ id: 'apiKey', environment: 'EXA_API_KEY', message: 'Exa API key', required: true }],
|
||||
markers: [{ id: 'web-search-exa', name: '@deepseek-ai/dsh-web-search-exa' }],
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'web-search-exa', package: '@deepseek-ai/dsh-web-search-exa' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'perplexity',
|
||||
label: 'Perplexity search',
|
||||
secrets: [{
|
||||
id: 'apiKey',
|
||||
environment: 'PERPLEXITY_API_KEY',
|
||||
message: 'Perplexity API key',
|
||||
required: true,
|
||||
}],
|
||||
markers: [{ id: 'web-search-perplexity', name: '@deepseek-ai/dsh-web-search-perplexity' }],
|
||||
resources: [
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'web-search-perplexity',
|
||||
package: '@deepseek-ai/dsh-web-search-perplexity',
|
||||
},
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fetch-only',
|
||||
label: 'Fetch only',
|
||||
markers: [{ id: 'tool-web', name: '@deepseek-ai/dsh-tool-web', config: { search: false } }],
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'tool-web',
|
||||
package: '@deepseek-ai/dsh-tool-web',
|
||||
config: { search: false } satisfies ToolWebConfig,
|
||||
}],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'subagent',
|
||||
summary: 'Delegate work to child agents',
|
||||
mode: 'multiple',
|
||||
// In-process options select continuable background delegation; the
|
||||
// follow-up adapter remains an independently loadable global tool.
|
||||
baseResources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tasks', package: '@deepseek-ai/dsh-tasks-local' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-tasks', package: '@deepseek-ai/dsh-tool-tasks' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'subagent', package: '@deepseek-ai/dsh-subagent' },
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-subagent-control', package: '@deepseek-ai/dsh-tool-subagent-control' },
|
||||
],
|
||||
options: [
|
||||
{
|
||||
id: 'spawn',
|
||||
label: 'Fresh child agent',
|
||||
default: true,
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'subagent-spawn', package: '@deepseek-ai/dsh-subagent-spawn' },
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'tool-subagent',
|
||||
package: '@deepseek-ai/dsh-tool-subagent',
|
||||
config: { provider: 'spawn', backgroundMode: 'continuable' } satisfies ToolSubagentConfig,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fork',
|
||||
label: 'Fork parent history',
|
||||
resources: [
|
||||
{ kind: 'npm-cordis-config-entry', id: 'subagent-fork', package: '@deepseek-ai/dsh-subagent-fork' },
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'tool-subagent-fork',
|
||||
package: '@deepseek-ai/dsh-tool-subagent',
|
||||
config: {
|
||||
provider: 'fork',
|
||||
toolName: 'subagent_fork',
|
||||
backgroundMode: 'continuable',
|
||||
} satisfies ToolSubagentConfig,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'workflow',
|
||||
summary: 'Scripted multi-agent workflows',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'workerthread',
|
||||
label: 'Worker thread engine',
|
||||
default: true,
|
||||
requires: [{ id: 'subagent', options: ['spawn'] }],
|
||||
resources: [
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'workflow-workerthread',
|
||||
package: '@deepseek-ai/dsh-workflow-workerthread',
|
||||
},
|
||||
{ kind: 'npm-cordis-config-entry', id: 'tool-workflow', package: '@deepseek-ai/dsh-tool-workflow' },
|
||||
],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'compact',
|
||||
summary: 'Automatic context compaction',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'basic',
|
||||
label: 'Basic compaction',
|
||||
default: true,
|
||||
resources: [
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'token-meter',
|
||||
package: '@deepseek-ai/dsh-token-meter',
|
||||
},
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'compact-basic',
|
||||
package: '@deepseek-ai/dsh-compact-basic',
|
||||
},
|
||||
],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'hooks',
|
||||
summary: 'Run Claude Code or Codex hooks',
|
||||
mode: 'multiple',
|
||||
requires: [{ id: 'bash' }],
|
||||
options: [
|
||||
{
|
||||
id: 'claude',
|
||||
label: 'Claude Code hooks',
|
||||
default: true,
|
||||
resources: [
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'hooks-claude',
|
||||
package: '@deepseek-ai/dsh-hooks-claude',
|
||||
config: { configPath: './hooks.json' } satisfies ClaudeHooksConfig,
|
||||
},
|
||||
{ kind: 'owned-file', path: 'hooks.json', text: '{}' },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'codex',
|
||||
label: 'Codex hooks',
|
||||
resources: [
|
||||
{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'hooks-codex',
|
||||
package: '@deepseek-ai/dsh-hooks-codex',
|
||||
config: { configPath: './codex-hooks.json' } satisfies CodexHooksConfig,
|
||||
},
|
||||
{ kind: 'owned-file', path: 'codex-hooks.json', text: '{}' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'guard',
|
||||
summary: 'Loop-hygiene reminders',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'repeat-tool',
|
||||
label: 'Repeat-tool reminders',
|
||||
default: true,
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'repeat-tool-guard',
|
||||
package: '@deepseek-ai/dsh-repeat-tool-guard',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
{
|
||||
id: 'timeout-policy',
|
||||
summary: 'Tool timeout policy',
|
||||
mode: 'single',
|
||||
options: [{
|
||||
id: 'default',
|
||||
label: 'Timeout policy',
|
||||
default: true,
|
||||
resources: [{
|
||||
kind: 'npm-cordis-config-entry',
|
||||
id: 'timeout-policy',
|
||||
package: '@deepseek-ai/dsh-timeout-policy',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
]), profile)
|
||||
}
|
||||
108
packages/scaffold/helper/src/features/builtin/provider.ts
Normal file
108
packages/scaffold/helper/src/features/builtin/provider.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Required direct-fetch DeepSeek and custom pi-ai provider behavior.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/builtin/provider
|
||||
*/
|
||||
|
||||
import { featureId } from '../../ids.ts'
|
||||
import type { FeatureSelection, ProjectProfile } from '../../project/types.ts'
|
||||
import {
|
||||
FeatureOption,
|
||||
ExclusiveOptionFeature,
|
||||
type FeatureProjectView,
|
||||
} from '../feature.ts'
|
||||
import { ProjectContribution } from '../resources.ts'
|
||||
import { npmCordisConfigEntry, environment } from './helpers.ts'
|
||||
|
||||
const ID = featureId('provider')
|
||||
const DEFAULT_MODEL = 'deepseek-v4-flash'
|
||||
const API_KEY_COMMENT = 'Required before the first model request.'
|
||||
|
||||
class DeepSeekOption extends FeatureOption {
|
||||
override readonly id = 'deepseek-official'
|
||||
override readonly label = 'DeepSeek'
|
||||
override readonly secrets = [{
|
||||
id: 'apiKey',
|
||||
environment: 'DEEPSEEK_API_KEY',
|
||||
message: 'DeepSeek API key',
|
||||
required: true,
|
||||
}]
|
||||
|
||||
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
|
||||
return new ProjectContribution([
|
||||
...npmCordisConfigEntry(ID, {
|
||||
id: 'llm-deepseek',
|
||||
name: '@deepseek-ai/dsh-llm-deepseek',
|
||||
}, ['baseURL', 'models']),
|
||||
environment(ID, 'DEEPSEEK_API_KEY', secrets.apiKey, API_KEY_COMMENT),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
class CustomOption extends FeatureOption {
|
||||
override readonly id = 'custom'
|
||||
override readonly label = 'Custom endpoint (pi-ai)'
|
||||
override readonly secrets = [{
|
||||
id: 'apiKey',
|
||||
environment: 'DEEPSEEK_API_KEY',
|
||||
message: 'Custom provider API key',
|
||||
required: true,
|
||||
}]
|
||||
override readonly inputs = [{
|
||||
id: 'baseURL',
|
||||
message: 'Custom provider base URL',
|
||||
}]
|
||||
|
||||
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
|
||||
return new ProjectContribution([
|
||||
...npmCordisConfigEntry(ID, {
|
||||
id: 'llm-pi-ai',
|
||||
name: '@deepseek-ai/dsh-llm-pi-ai',
|
||||
}, ['baseURL', 'models']),
|
||||
environment(ID, 'DEEPSEEK_API_KEY', secrets.apiKey, API_KEY_COMMENT),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
/** Required provider feature with DeepSeek and custom pi-ai options. */
|
||||
export class ProviderFeature extends ExclusiveOptionFeature {
|
||||
override readonly id = ID
|
||||
override readonly summary = 'Model provider'
|
||||
override readonly required = true
|
||||
override readonly options = [new DeepSeekOption(), new CustomOption()]
|
||||
|
||||
/** Prefer the direct-fetch adapter and its public endpoint defaults. */
|
||||
override defaultOptions(): readonly string[] {
|
||||
return ['deepseek-official']
|
||||
}
|
||||
|
||||
/** Recover literal endpoint overrides from either provider entry. */
|
||||
override readSelection(project: FeatureProjectView, selection: FeatureSelection): FeatureSelection {
|
||||
const base = super.readSelection(project, selection)
|
||||
const entry = project.cordisConfigEntries().find(item => item.id === 'llm-deepseek' || item.id === 'llm-pi-ai')
|
||||
const baseURL = entry?.config?.baseURL
|
||||
return typeof baseURL === 'string' ? { ...base, values: { baseURL } } : base
|
||||
}
|
||||
|
||||
/** Apply explicit endpoint/model overrides while omitting provider defaults. */
|
||||
override contribution(selection: FeatureSelection, profile: ProjectProfile): ProjectContribution {
|
||||
const contribution = super.contribution(selection, profile)
|
||||
const baseURL = selection.values?.baseURL
|
||||
if (baseURL !== undefined && typeof baseURL !== 'string') throw new Error('provider baseURL must be a string')
|
||||
return new ProjectContribution(contribution.resources.map((resource) => {
|
||||
if (resource.kind !== 'cordis-config-entry' || (resource.entry.id !== 'llm-deepseek'
|
||||
&& resource.entry.id !== 'llm-pi-ai')) return resource
|
||||
return {
|
||||
...resource,
|
||||
entry: {
|
||||
...resource.entry,
|
||||
config: {
|
||||
...resource.entry.config,
|
||||
...baseURL ? { baseURL } : {},
|
||||
...profile.runtime.model === DEFAULT_MODEL ? {} : { models: [profile.runtime.model] },
|
||||
},
|
||||
},
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
59
packages/scaffold/helper/src/features/builtin/spine.ts
Normal file
59
packages/scaffold/helper/src/features/builtin/spine.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Required agent-spine feature expressed as top-level Cordis config entries.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/builtin/spine
|
||||
*/
|
||||
|
||||
import { featureId } from '../../ids.ts'
|
||||
import type { ProjectProfile } from '../../project/types.ts'
|
||||
import { loadHelperTemplate } from '../../templates/template-assets.ts'
|
||||
import { FeatureOption, FixedFeature } from '../feature.ts'
|
||||
import { ProjectContribution } from '../resources.ts'
|
||||
import { cordisConfigEntry, npmCordisConfigEntry, requiredString } from './helpers.ts'
|
||||
|
||||
const ID = featureId('spine')
|
||||
const PERSONA = loadHelperTemplate<Record<string, never>>('persona.txt.tpl').render({}).trimEnd()
|
||||
|
||||
function emptyAgentsDiagnostics(config: Readonly<Record<string, unknown>>): string[] {
|
||||
const agents = config.agents
|
||||
if (!Array.isArray(agents)) return ['agents must be an array']
|
||||
return agents.length === 0 ? [] : ['agents must be empty']
|
||||
}
|
||||
|
||||
class SpineOption extends FeatureOption {
|
||||
override readonly id = 'default'
|
||||
override readonly label = 'Default agent spine'
|
||||
|
||||
override contribution(_profile: ProjectProfile): ProjectContribution {
|
||||
return new ProjectContribution([
|
||||
...npmCordisConfigEntry(ID, { id: 'timer', name: '@cordisjs/plugin-timer' }),
|
||||
...npmCordisConfigEntry(ID, { id: 'llm', name: '@deepseek-ai/dsh-llm' }),
|
||||
...npmCordisConfigEntry(ID, { id: 'session', name: '@deepseek-ai/dsh-session' }),
|
||||
...npmCordisConfigEntry(ID, {
|
||||
id: 'system-prompt',
|
||||
name: '@deepseek-ai/dsh-system-prompt',
|
||||
config: { persona: PERSONA },
|
||||
}, ['persona'], config => requiredString(config, 'persona')),
|
||||
...npmCordisConfigEntry(ID, { id: 'tools', name: '@deepseek-ai/dsh-tools' }, []),
|
||||
...npmCordisConfigEntry(ID, { id: 'agent', name: '@deepseek-ai/dsh-agent' }),
|
||||
...npmCordisConfigEntry(ID, { id: 'invariants', name: '@deepseek-ai/dsh-invariants' }),
|
||||
cordisConfigEntry(ID, { id: 'session-invariant', name: '@deepseek-ai/dsh-session/invariant' }),
|
||||
cordisConfigEntry(ID, { id: 'agent-invariant', name: '@deepseek-ai/dsh-agent/invariant' }),
|
||||
...npmCordisConfigEntry(ID, { id: 'scope-invariant', name: '@deepseek-ai/dsh-scope/invariant' }),
|
||||
cordisConfigEntry(ID, { id: 'agent-loop-invariant', name: '@deepseek-ai/dsh-agent-loop/invariant' }),
|
||||
...npmCordisConfigEntry(ID, {
|
||||
id: 'agent-loop',
|
||||
name: '@deepseek-ai/dsh-agent-loop',
|
||||
config: { agents: [] },
|
||||
}, ['agents'], emptyAgentsDiagnostics),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
/** Required providerless agent spine without a composition bundle entry. */
|
||||
export class SpineFeature extends FixedFeature {
|
||||
override readonly id = ID
|
||||
override readonly summary = 'Agent runtime spine'
|
||||
override readonly required = true
|
||||
override readonly options = [new SpineOption()]
|
||||
}
|
||||
286
packages/scaffold/helper/src/features/define-feature.ts
Normal file
286
packages/scaffold/helper/src/features/define-feature.ts
Normal file
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* Typed declarative definitions for features whose behavior is entirely
|
||||
* the shared resource lifecycle.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/define-feature
|
||||
*/
|
||||
|
||||
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import { TextProjectFile } from '../documents/project-file.ts'
|
||||
import { featureId, resourceKey, type FeatureId } from '../ids.ts'
|
||||
import type { FeatureSelection, ProjectProfile, RunInterface } from '../project/types.ts'
|
||||
import {
|
||||
Feature,
|
||||
FeatureOption,
|
||||
type FeatureRequirement,
|
||||
type FeatureSecret,
|
||||
} from './feature.ts'
|
||||
import { ProjectContribution, type ProjectResource } from './resources.ts'
|
||||
|
||||
/** Static NPM dependency in a declarative feature. */
|
||||
interface NpmDependencySpec {
|
||||
kind: 'npm-dependency'
|
||||
name: string
|
||||
section?: 'dependencies' | 'devDependencies'
|
||||
}
|
||||
|
||||
/** Bare-package Cordis config entry that also contributes its NPM dependency. */
|
||||
interface NpmCordisConfigEntrySpec {
|
||||
kind: 'npm-cordis-config-entry'
|
||||
id: string
|
||||
package: string
|
||||
config?: Readonly<Record<string, unknown>>
|
||||
ownedConfigKeys?: readonly string[]
|
||||
commentedExample?: string
|
||||
}
|
||||
|
||||
/** Relative or absolute file Cordis config entry with no NPM dependency. */
|
||||
interface FileCordisConfigEntrySpec {
|
||||
kind: 'file-cordis-config-entry'
|
||||
id: string
|
||||
path: string
|
||||
config?: Readonly<Record<string, unknown>>
|
||||
ownedConfigKeys?: readonly string[]
|
||||
commentedExample?: string
|
||||
}
|
||||
|
||||
/** Static complete file owned by one feature option. */
|
||||
interface OwnedFileSpec {
|
||||
kind: 'owned-file'
|
||||
path: string
|
||||
text: string
|
||||
removeOnlyWhenUnchanged?: boolean
|
||||
}
|
||||
|
||||
/** Resource forms that require no feature-specific imperative code. */
|
||||
type FeatureResourceSpec =
|
||||
| NpmDependencySpec
|
||||
| NpmCordisConfigEntrySpec
|
||||
| FileCordisConfigEntrySpec
|
||||
| OwnedFileSpec
|
||||
|
||||
/** Cordis config entry identity and optional plugin-config subset that identifies an option. */
|
||||
interface FeatureOptionMarkerSpec {
|
||||
id: string
|
||||
name: string
|
||||
config?: Readonly<Record<string, unknown>>
|
||||
}
|
||||
|
||||
/** Declarative requirement converted to branded domain identity at the boundary. */
|
||||
interface FeatureRequirementSpec {
|
||||
id: string
|
||||
options?: readonly string[]
|
||||
}
|
||||
|
||||
/** One static option inside a typed feature definition. */
|
||||
interface FeatureOptionSpec {
|
||||
id: string
|
||||
label: string
|
||||
default?: boolean
|
||||
resources: readonly FeatureResourceSpec[]
|
||||
secrets?: readonly FeatureSecret[]
|
||||
markers?: readonly FeatureOptionMarkerSpec[]
|
||||
requires?: readonly FeatureRequirementSpec[]
|
||||
}
|
||||
|
||||
/** Complete declarative feature definition. */
|
||||
export interface FeatureSpec {
|
||||
id: string
|
||||
summary: string
|
||||
mode: 'single' | 'exclusive' | 'multiple'
|
||||
options: readonly FeatureOptionSpec[]
|
||||
baseResources?: readonly FeatureResourceSpec[]
|
||||
required?: boolean
|
||||
requires?: readonly FeatureRequirementSpec[]
|
||||
suggests?: readonly string[]
|
||||
supportedInterfaces?: readonly RunInterface[]
|
||||
}
|
||||
|
||||
function sameShape(expected: unknown, actual: unknown): boolean {
|
||||
if (expected === null || actual === null) return expected === actual
|
||||
if (Array.isArray(expected)) {
|
||||
return Array.isArray(actual) && (expected.length === 0 || actual.every(item => sameShape(expected[0], item)))
|
||||
}
|
||||
if (typeof expected !== 'object') return typeof expected === typeof actual
|
||||
if (typeof actual !== 'object' || Array.isArray(actual)) return false
|
||||
return Object.entries(expected as Record<string, unknown>).every(
|
||||
([key, value]) => sameShape(value, (actual as Record<string, unknown>)[key]),
|
||||
)
|
||||
}
|
||||
|
||||
function configDiagnostics(
|
||||
expected: Readonly<Record<string, unknown>> | undefined,
|
||||
): ((config: Readonly<Record<string, unknown>>) => readonly string[]) | undefined {
|
||||
if (!expected || Object.keys(expected).length === 0) return undefined
|
||||
return config => Object.entries(expected).flatMap(([key, value]) => sameShape(value, config[key])
|
||||
? []
|
||||
: [`${key} has an incompatible value shape`])
|
||||
}
|
||||
|
||||
function resourcesFromSpec(spec: FeatureResourceSpec): ProjectResource[] {
|
||||
switch (spec.kind) {
|
||||
case 'npm-dependency':
|
||||
return [{
|
||||
kind: 'npm-dependency',
|
||||
key: resourceKey(`npm-dependency:${spec.name}`),
|
||||
name: spec.name,
|
||||
section: spec.section ?? 'dependencies',
|
||||
}]
|
||||
case 'npm-cordis-config-entry':
|
||||
case 'file-cordis-config-entry': {
|
||||
const config = spec.config ? { ...spec.config } : undefined
|
||||
const validateConfig = configDiagnostics(config)
|
||||
const name = spec.kind === 'npm-cordis-config-entry' ? spec.package : spec.path
|
||||
return [
|
||||
...spec.kind === 'npm-cordis-config-entry'
|
||||
? [{
|
||||
kind: 'npm-dependency' as const,
|
||||
key: resourceKey(`npm-dependency:${spec.package}`),
|
||||
name: spec.package,
|
||||
section: 'dependencies' as const,
|
||||
}]
|
||||
: [],
|
||||
{
|
||||
kind: 'cordis-config-entry',
|
||||
key: resourceKey(`cordis-config-entry:${spec.id}`),
|
||||
entry: {
|
||||
id: spec.id,
|
||||
name,
|
||||
...config ? { config } : {},
|
||||
},
|
||||
ownedConfigKeys: spec.ownedConfigKeys ?? Object.keys(config ?? {}),
|
||||
...spec.commentedExample ? { commentedExample: spec.commentedExample } : {},
|
||||
...validateConfig ? { validateConfig } : {},
|
||||
},
|
||||
]
|
||||
}
|
||||
case 'owned-file':
|
||||
return [{
|
||||
kind: 'owned-file',
|
||||
key: resourceKey(`file:${spec.path}`),
|
||||
document: new TextProjectFile(spec.path, spec.text),
|
||||
removeOnlyWhenUnchanged: spec.removeOnlyWhenUnchanged ?? true,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
function isSubset(expected: Readonly<Record<string, unknown>>, actual: Readonly<Record<string, unknown>>): boolean {
|
||||
return Object.entries(expected).every(([key, value]) => Object.is(actual[key], value))
|
||||
}
|
||||
|
||||
class DefinedFeatureOption extends FeatureOption {
|
||||
override readonly id: string
|
||||
override readonly label: string
|
||||
override readonly secrets: readonly FeatureSecret[]
|
||||
private readonly spec: FeatureOptionSpec
|
||||
|
||||
constructor(spec: FeatureOptionSpec) {
|
||||
super()
|
||||
this.spec = spec
|
||||
this.id = spec.id
|
||||
this.label = spec.label
|
||||
this.secrets = spec.secrets ?? []
|
||||
}
|
||||
|
||||
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
|
||||
return new ProjectContribution([
|
||||
...this.spec.resources.flatMap(resourcesFromSpec),
|
||||
...this.secrets.map(secret => ({
|
||||
kind: 'environment' as const,
|
||||
key: resourceKey(`environment:${secret.environment}`),
|
||||
name: secret.environment,
|
||||
...secrets[secret.id] === undefined ? {} : { value: secrets[secret.id] },
|
||||
exampleValue: '',
|
||||
})),
|
||||
])
|
||||
}
|
||||
|
||||
override markerConfigEntries(): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
|
||||
const markers = this.spec.markers ?? this.spec.resources.flatMap((resource) => {
|
||||
switch (resource.kind) {
|
||||
case 'npm-cordis-config-entry': return [{ id: resource.id, name: resource.package }]
|
||||
case 'file-cordis-config-entry': return [{ id: resource.id, name: resource.path }]
|
||||
default: return []
|
||||
}
|
||||
})
|
||||
return markers.map(marker => ({ id: marker.id, name: marker.name }))
|
||||
}
|
||||
|
||||
override matchesConfigEntries(entries: readonly CordisConfigEntry[]): boolean {
|
||||
const markers = this.spec.markers
|
||||
if (!markers) return this.markerConfigEntries().some(marker => entries.some(
|
||||
entry => entry.id === marker.id && entry.name === marker.name,
|
||||
))
|
||||
return markers.some(marker => entries.some(entry => entry.id === marker.id
|
||||
&& entry.name === marker.name
|
||||
&& (!marker.config || isSubset(marker.config, entry.config ?? {}))))
|
||||
}
|
||||
}
|
||||
|
||||
/** Feature entity backed by a typed static definition. */
|
||||
class DefinedFeature extends Feature {
|
||||
override readonly id: FeatureId
|
||||
override readonly summary: string
|
||||
override readonly mode: FeatureSpec['mode']
|
||||
override readonly options: readonly FeatureOption[]
|
||||
override readonly required: boolean
|
||||
override readonly requires: readonly FeatureId[]
|
||||
override readonly suggests: readonly FeatureId[]
|
||||
override readonly supportedInterfaces: readonly RunInterface[]
|
||||
private readonly spec: FeatureSpec
|
||||
|
||||
/** Validate and materialize one declarative definition. */
|
||||
constructor(spec: FeatureSpec) {
|
||||
super()
|
||||
this.spec = spec
|
||||
this.id = featureId(spec.id)
|
||||
this.summary = spec.summary
|
||||
this.mode = spec.mode
|
||||
this.options = spec.options.map(option => new DefinedFeatureOption(option))
|
||||
const defaultCount = spec.options.filter(option => option.default).length
|
||||
if (spec.mode === 'single' && (spec.options.length !== 1 || defaultCount !== 1)) {
|
||||
throw new Error(`single feature ${spec.id} requires one default option`)
|
||||
}
|
||||
if (spec.mode === 'exclusive' && defaultCount !== 1) {
|
||||
throw new Error(`exclusive feature ${spec.id} requires exactly one default option`)
|
||||
}
|
||||
if (spec.mode === 'multiple' && defaultCount === 0) {
|
||||
throw new Error(`multiple feature ${spec.id} requires at least one default option`)
|
||||
}
|
||||
this.required = spec.required ?? false
|
||||
this.requires = (spec.requires ?? []).map(requirement => featureId(requirement.id))
|
||||
this.suggests = (spec.suggests ?? []).map(featureId)
|
||||
this.supportedInterfaces = spec.supportedInterfaces ?? ['acp', 'embed']
|
||||
}
|
||||
|
||||
override defaultOptions(): readonly string[] {
|
||||
return this.spec.options.filter(option => option.default).map(option => option.id)
|
||||
}
|
||||
|
||||
override baseContribution(): ProjectContribution {
|
||||
return new ProjectContribution((this.spec.baseResources ?? []).flatMap(resourcesFromSpec))
|
||||
}
|
||||
|
||||
override requirements(selection: FeatureSelection): readonly FeatureRequirement[] {
|
||||
const selected = new Set(selection.options)
|
||||
return [
|
||||
...(this.spec.requires ?? []),
|
||||
...this.spec.options.filter(option => selected.has(option.id)).flatMap(option => option.requires ?? []),
|
||||
].map(requirement => ({
|
||||
id: featureId(requirement.id),
|
||||
...requirement.options ? { options: requirement.options } : {},
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/** Construct the shared lifecycle entity from a typed declarative definition. */
|
||||
export function defineFeature(spec: FeatureSpec): Feature {
|
||||
return new DefinedFeature(spec)
|
||||
}
|
||||
|
||||
/** Materialize one ordered catalog containing static specs and behavior entities. */
|
||||
export function defineFeatures(definitions: readonly (Feature | FeatureSpec)[]): Feature[] {
|
||||
return definitions.map(definition => definition instanceof Feature
|
||||
? definition
|
||||
: defineFeature(definition))
|
||||
}
|
||||
111
packages/scaffold/helper/src/features/feature-configurator.ts
Normal file
111
packages/scaffold/helper/src/features/feature-configurator.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Shared option and secret question flow for create and config.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/feature-configurator
|
||||
*/
|
||||
|
||||
import type { Feature } from './feature.ts'
|
||||
import type { FeatureSelection, ProjectProfile } from '../project/types.ts'
|
||||
import type { PromptPort } from '../questions/prompt-port.ts'
|
||||
import { requireAnswer } from '../questions/prompt-port.ts'
|
||||
import { MultiSelectQuestion, SecretQuestion, SelectQuestion, TextQuestion } from '../questions/question.ts'
|
||||
|
||||
/** Resolve one feature selection without knowing which workflow requested it. */
|
||||
export class FeatureConfigurator {
|
||||
private readonly port: PromptPort
|
||||
|
||||
/** Bind the configurator to the shared prompt boundary. */
|
||||
constructor(port: PromptPort) {
|
||||
this.port = port
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask option and input questions, preserving current secrets on empty input.
|
||||
* @param feature - feature whose options and inputs are collected.
|
||||
* @param profile - target project context.
|
||||
* @param current - currently installed selection, when configuring.
|
||||
* @param prefilledOptions - options already chosen by a tree picker.
|
||||
* @param prefilledSecrets - non-interactive secret values supplied by creation.
|
||||
* @param prefilledValues - non-interactive value inputs supplied by a headless spec.
|
||||
* @returns normalized selection with captured values and secrets.
|
||||
*/
|
||||
async configure(
|
||||
feature: Feature,
|
||||
profile: ProjectProfile,
|
||||
current?: FeatureSelection,
|
||||
prefilledOptions?: readonly string[],
|
||||
prefilledSecrets: Readonly<Record<string, string>> = {},
|
||||
prefilledValues: Readonly<Record<string, unknown>> = {},
|
||||
): Promise<FeatureSelection> {
|
||||
let options: readonly string[]
|
||||
switch (feature.mode) {
|
||||
case 'single':
|
||||
options = feature.defaultOptions(profile)
|
||||
break
|
||||
case 'exclusive': {
|
||||
const initialValue = current?.options[0] ?? feature.defaultOptions(profile)[0]
|
||||
if (initialValue === undefined) throw new Error(`feature ${feature.id} has no default option`)
|
||||
const question = new SelectQuestion({
|
||||
id: `${feature.id}.option`,
|
||||
message: `Choose ${feature.summary.toLowerCase()}`,
|
||||
options: feature.options.map(option => ({ value: option.id, label: option.label })),
|
||||
initialValue,
|
||||
})
|
||||
const prefilled = prefilledOptions?.[0]
|
||||
options = [requireAnswer(await question.resolve(this.port, prefilled))]
|
||||
break
|
||||
}
|
||||
case 'multiple': {
|
||||
const question = new MultiSelectQuestion({
|
||||
id: `${feature.id}.options`,
|
||||
message: `Choose ${feature.summary.toLowerCase()}`,
|
||||
options: feature.options.map(option => ({ value: option.id, label: option.label })),
|
||||
initialValues: current?.options ?? feature.defaultOptions(profile),
|
||||
required: true,
|
||||
})
|
||||
options = requireAnswer(await question.resolve(this.port, prefilledOptions))
|
||||
break
|
||||
}
|
||||
}
|
||||
const selected: FeatureSelection = {
|
||||
id: feature.id,
|
||||
options,
|
||||
}
|
||||
const coercedPrefilled: Record<string, string> = {}
|
||||
for (const [key, value] of Object.entries(prefilledValues)) {
|
||||
if (typeof value !== 'string') throw new Error(`${feature.id}.${key} value must be a string`)
|
||||
coercedPrefilled[key] = value
|
||||
}
|
||||
const values: Record<string, string> = {}
|
||||
for (const input of feature.valueInputs(selected, profile)) {
|
||||
const existing = current?.values?.[input.id]
|
||||
if (existing !== undefined && typeof existing !== 'string') {
|
||||
throw new Error(`${feature.id}.${input.id} current value must be a string`)
|
||||
}
|
||||
const question = new TextQuestion({
|
||||
id: `${feature.id}.${input.id}`,
|
||||
message: input.message,
|
||||
...existing === undefined ? {} : { initialValue: existing },
|
||||
validate: value => value.trim().length === 0 ? 'A value is required' : undefined,
|
||||
})
|
||||
values[input.id] = requireAnswer(await question.resolve(this.port, coercedPrefilled[input.id]))
|
||||
}
|
||||
const base: FeatureSelection = Object.keys(values).length === 0
|
||||
? selected
|
||||
: { ...selected, values }
|
||||
const secrets = { ...current?.secrets }
|
||||
for (const secret of feature.secrets(base, profile)) {
|
||||
const existing = secrets[secret.id]
|
||||
const question = new SecretQuestion({
|
||||
id: `${feature.id}.${secret.id}`,
|
||||
message: existing === undefined ? secret.message : `${secret.message} (leave empty to keep current)`,
|
||||
validate: value => secret.required && existing === undefined && value.length === 0
|
||||
? 'A value is required'
|
||||
: undefined,
|
||||
})
|
||||
const answer = requireAnswer(await question.resolve(this.port, prefilledSecrets[secret.id]))
|
||||
if (answer.length > 0) secrets[secret.id] = answer
|
||||
}
|
||||
return Object.keys(secrets).length === 0 ? base : { ...base, secrets }
|
||||
}
|
||||
}
|
||||
345
packages/scaffold/helper/src/features/feature.ts
Normal file
345
packages/scaffold/helper/src/features/feature.ts
Normal file
@@ -0,0 +1,345 @@
|
||||
/**
|
||||
* Stateful builtin feature and option domain objects.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/feature
|
||||
*/
|
||||
|
||||
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import type { PackageManifest } from '../documents/package-json-file.ts'
|
||||
import type { FeatureId } from '../ids.ts'
|
||||
import type { FeatureSelection, ProjectProfile, RunInterface } from '../project/types.ts'
|
||||
import { ProjectContribution, type CordisConfigEntryResource, type ProjectResource } from './resources.ts'
|
||||
|
||||
/** Read-only project surface used by feature inspection. */
|
||||
export interface FeatureProjectView {
|
||||
readonly profile: ProjectProfile
|
||||
cordisConfigEntries(): readonly CordisConfigEntry[]
|
||||
packageManifest(): Readonly<PackageManifest>
|
||||
hasDocument(path: string): boolean
|
||||
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined
|
||||
}
|
||||
|
||||
/** Installation state visible to create/config workflows. */
|
||||
type FeatureInstallationState = 'absent' | 'enabled' | 'disabled' | 'inconsistent'
|
||||
|
||||
/** Result of round-tripping one feature from a project snapshot. */
|
||||
export interface FeatureInstallation {
|
||||
id: FeatureId
|
||||
state: FeatureInstallationState
|
||||
options: readonly string[]
|
||||
selection?: FeatureSelection
|
||||
diagnostics: readonly string[]
|
||||
}
|
||||
|
||||
/** One final-state requirement on another builtin feature. */
|
||||
export interface FeatureRequirement {
|
||||
id: FeatureId
|
||||
options?: readonly string[]
|
||||
}
|
||||
|
||||
/** One secret captured into an environment binding rather than Cordis plugin config. */
|
||||
export interface FeatureSecret {
|
||||
id: string
|
||||
environment: string
|
||||
message: string
|
||||
required: boolean
|
||||
}
|
||||
|
||||
/** One visible string value requested only by options that own it. */
|
||||
export interface FeatureValueInput {
|
||||
id: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** One selectable behavior option owned by a feature. */
|
||||
export abstract class FeatureOption {
|
||||
abstract readonly id: string
|
||||
abstract readonly label: string
|
||||
readonly secrets: readonly FeatureSecret[] = []
|
||||
readonly inputs: readonly FeatureValueInput[] = []
|
||||
|
||||
/** Contribute this option's project resources. */
|
||||
abstract contribution(profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution
|
||||
|
||||
/** Every Cordis config entry package owned by this option during inspection. */
|
||||
ownedConfigEntries(profile: ProjectProfile): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
|
||||
return this.contribution(profile, {}).resources
|
||||
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
|
||||
.map(resource => ({ id: resource.entry.id, name: resource.entry.name }))
|
||||
}
|
||||
|
||||
/** Cordis config entry identities that distinguish this option during inspection. */
|
||||
markerConfigEntries(profile: ProjectProfile): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
|
||||
return this.ownedConfigEntries(profile)
|
||||
}
|
||||
|
||||
/** Whether current owned Cordis config entries identify this option. */
|
||||
matchesConfigEntries(entries: readonly CordisConfigEntry[], profile: ProjectProfile): boolean {
|
||||
return this.markerConfigEntries(profile).some(marker => entries.some(
|
||||
entry => entry.id === marker.id && entry.name === marker.name,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/** How a feature's options compose. */
|
||||
export type FeatureOptionMode = 'single' | 'exclusive' | 'multiple'
|
||||
|
||||
function packageNames(resources: readonly ProjectResource[]): Set<string> {
|
||||
return new Set(resources
|
||||
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
|
||||
.map(resource => resource.entry.name))
|
||||
}
|
||||
|
||||
function configDiagnostics(resource: CordisConfigEntryResource, entry: CordisConfigEntry): string[] {
|
||||
/* v8 ignore next -- entries without validators have no diagnostics to compute */
|
||||
if (!resource.validateConfig) return []
|
||||
return [...resource.validateConfig(entry.config ?? {})].map(message => `${entry.id}: ${message}`)
|
||||
}
|
||||
|
||||
/** A behavior-owning builtin feature with shallow option composition. */
|
||||
export abstract class Feature {
|
||||
/** Stable registry identity. */
|
||||
abstract readonly id: FeatureId
|
||||
/** User-facing feature summary. */
|
||||
abstract readonly summary: string
|
||||
/** Option-selection rule. */
|
||||
abstract readonly mode: FeatureOptionMode
|
||||
/** Available behavior options. */
|
||||
abstract readonly options: readonly FeatureOption[]
|
||||
/** Whether every valid project must enable this feature. */
|
||||
readonly required: boolean = false
|
||||
/** Unconditional feature requirements. */
|
||||
readonly requires: readonly FeatureId[] = []
|
||||
/** Features recommended during creation. */
|
||||
readonly suggests: readonly FeatureId[] = []
|
||||
/** Front doors under which this feature is meaningful. */
|
||||
readonly supportedInterfaces: readonly RunInterface[] = ['acp', 'embed']
|
||||
|
||||
/**
|
||||
* Options selected when installation has no override.
|
||||
* @param profile - project context controlling applicable defaults.
|
||||
* @returns selected option ids.
|
||||
*/
|
||||
abstract defaultOptions(profile: ProjectProfile): readonly string[]
|
||||
|
||||
/**
|
||||
* Shared resources present for every installed option set.
|
||||
* @param _profile - project context available to behavior features.
|
||||
* @returns shared project contribution.
|
||||
*/
|
||||
baseContribution(_profile: ProjectProfile): ProjectContribution {
|
||||
return new ProjectContribution([])
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional final-state requirements depending on selected options.
|
||||
* @param _selection - normalized feature selection.
|
||||
* @returns required features and option constraints.
|
||||
*/
|
||||
requirements(_selection: FeatureSelection): readonly FeatureRequirement[] {
|
||||
return this.requires.map(id => ({ id }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the feature may be selected for this project front door.
|
||||
* @param profile - project context to check.
|
||||
* @returns whether the feature applies.
|
||||
*/
|
||||
isApplicable(profile: ProjectProfile): boolean {
|
||||
return this.supportedInterfaces.includes(profile.runInterface)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate and normalize one requested option set.
|
||||
* @param selection - requested feature and options.
|
||||
* @param profile - project context for applicability and defaults.
|
||||
* @returns deduplicated, sorted selection.
|
||||
*/
|
||||
normalizeSelection(selection: FeatureSelection, profile: ProjectProfile): FeatureSelection {
|
||||
if (selection.id !== this.id) throw new Error(`selection ${selection.id} does not belong to feature ${this.id}`)
|
||||
if (!this.isApplicable(profile)) {
|
||||
throw new Error(`feature ${this.id} is not available for ${profile.runInterface}`)
|
||||
}
|
||||
const available = new Set(this.options.map(option => option.id))
|
||||
const options = [...new Set(selection.options.length > 0 ? selection.options : this.defaultOptions(profile))]
|
||||
for (const option of options) {
|
||||
if (!available.has(option)) throw new Error(`unknown ${this.id} option: ${option}`)
|
||||
}
|
||||
if (this.mode === 'single' && (options.length !== 1 || this.options.length !== 1)) {
|
||||
throw new Error(`feature ${this.id} has one fixed option`)
|
||||
}
|
||||
if (this.mode === 'exclusive' && options.length !== 1) {
|
||||
throw new Error(`feature ${this.id} requires exactly one option`)
|
||||
}
|
||||
if (this.mode === 'multiple' && options.length === 0) {
|
||||
throw new Error(`feature ${this.id} requires at least one option`)
|
||||
}
|
||||
return { ...selection, options: options.sort() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the complete selected resource contribution.
|
||||
* @param selection - selected options and captured inputs.
|
||||
* @param profile - target project context.
|
||||
* @returns merged base and option resources.
|
||||
*/
|
||||
contribution(selection: FeatureSelection, profile: ProjectProfile): ProjectContribution {
|
||||
const normalized = this.normalizeSelection(selection, profile)
|
||||
const selected = this.selectedOptions(normalized)
|
||||
.map(option => option.contribution(profile, normalized.secrets ?? {}))
|
||||
return ProjectContribution.merge(this.baseContribution(profile), ...selected)
|
||||
}
|
||||
|
||||
/**
|
||||
* All secret definitions required by one selected option set.
|
||||
* @param selection - selected options.
|
||||
* @param profile - target project context.
|
||||
* @returns selected secret definitions.
|
||||
*/
|
||||
secrets(selection: FeatureSelection, profile: ProjectProfile): readonly FeatureSecret[] {
|
||||
const normalized = this.normalizeSelection(selection, profile)
|
||||
return this.selectedOptions(normalized).flatMap(option => option.secrets)
|
||||
}
|
||||
|
||||
/**
|
||||
* All visible value definitions required by one selected option set.
|
||||
* @param selection - selected options.
|
||||
* @param profile - target project context.
|
||||
* @returns selected visible-input definitions.
|
||||
*/
|
||||
valueInputs(selection: FeatureSelection, profile: ProjectProfile): readonly FeatureValueInput[] {
|
||||
const normalized = this.normalizeSelection(selection, profile)
|
||||
return this.selectedOptions(normalized).flatMap(option => option.inputs)
|
||||
}
|
||||
|
||||
private selectedOptions(selection: FeatureSelection): readonly FeatureOption[] {
|
||||
return selection.options.map((id) => {
|
||||
const option = this.options.find(candidate => candidate.id === id)
|
||||
/* v8 ignore next -- normalizeSelection already membership-checks every selected id */
|
||||
if (!option) throw new Error(`unknown ${this.id} option: ${id}`)
|
||||
return option
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Recover input and secret values after structural inspection.
|
||||
* @param project - project snapshot being inspected.
|
||||
* @param selection - structurally detected selection.
|
||||
* @returns selection enriched with readable values.
|
||||
*/
|
||||
readSelection(project: FeatureProjectView, selection: FeatureSelection): FeatureSelection {
|
||||
const secrets = Object.fromEntries(this.secrets(selection, project.profile).flatMap((secret) => {
|
||||
const value = project.readEnvironment('.env', secret.environment)
|
||||
return value === undefined ? [] : [[secret.id, value]]
|
||||
}))
|
||||
return Object.keys(secrets).length === 0 ? selection : { ...selection, secrets }
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect current files and reject any partial or ambiguous owned shape.
|
||||
* @param project - project snapshot to inspect.
|
||||
* @returns installation state, selection, and diagnostics.
|
||||
*/
|
||||
inspect(project: FeatureProjectView): FeatureInstallation {
|
||||
const profile = project.profile
|
||||
const allPackages = new Set<string>()
|
||||
for (const option of this.options) {
|
||||
for (const entry of option.ownedConfigEntries(profile)) allPackages.add(entry.name)
|
||||
}
|
||||
for (const name of packageNames(this.baseContribution(profile).resources)) allPackages.add(name)
|
||||
const configEntries = project.cordisConfigEntries()
|
||||
const ownedConfigEntries = configEntries.filter(entry => allPackages.has(entry.name))
|
||||
|
||||
const options = this.options
|
||||
.filter(option => option.matchesConfigEntries(configEntries, profile))
|
||||
.map(option => option.id)
|
||||
if (ownedConfigEntries.length === 0 && options.length === 0) {
|
||||
return { id: this.id, state: 'absent', options: [], diagnostics: [] }
|
||||
}
|
||||
let selection: FeatureSelection
|
||||
try {
|
||||
selection = this.normalizeSelection({ id: this.id, options }, profile)
|
||||
} catch (error) {
|
||||
return { id: this.id, state: 'inconsistent', options, diagnostics: [String(error)] }
|
||||
}
|
||||
selection = this.readSelection(project, selection)
|
||||
const expected = this.contribution(selection, profile)
|
||||
const expectedEntries = expected.resources
|
||||
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
|
||||
const diagnostics: string[] = []
|
||||
for (const resource of expectedEntries) {
|
||||
const actual = ownedConfigEntries.find(entry => entry.id === resource.entry.id && entry.name === resource.entry.name)
|
||||
if (!actual) diagnostics.push(`missing Cordis config entry ${resource.entry.id} (${resource.entry.name})`)
|
||||
else diagnostics.push(...configDiagnostics(resource, actual))
|
||||
}
|
||||
for (const actual of ownedConfigEntries) {
|
||||
if (!expectedEntries.some(resource => resource.entry.id === actual.id && resource.entry.name === actual.name)) {
|
||||
diagnostics.push(`unexpected owned Cordis config entry ${actual.id} (${actual.name})`)
|
||||
}
|
||||
}
|
||||
const manifest = project.packageManifest()
|
||||
for (const resource of expected.resources) {
|
||||
switch (resource.kind) {
|
||||
case 'npm-dependency':
|
||||
if (!manifest[resource.section]?.[resource.name]) {
|
||||
diagnostics.push(`missing package.json ${resource.section} entry ${resource.name}`)
|
||||
}
|
||||
break
|
||||
case 'package-script':
|
||||
if (!manifest.scripts?.[resource.name]) {
|
||||
diagnostics.push(`missing package.json script ${resource.name}`)
|
||||
}
|
||||
break
|
||||
case 'owned-file':
|
||||
if (!project.hasDocument(resource.document.relativePath)) diagnostics.push(`missing owned file ${resource.document.relativePath}`)
|
||||
break
|
||||
case 'environment':
|
||||
try {
|
||||
if (project.readEnvironment('.env.example', resource.name) === undefined) {
|
||||
diagnostics.push(`missing .env.example variable ${resource.name}`)
|
||||
}
|
||||
} catch (error) {
|
||||
diagnostics.push(String(error))
|
||||
}
|
||||
break
|
||||
case 'cordis-config-entry': break
|
||||
}
|
||||
}
|
||||
const disabled = ownedConfigEntries.map(entry => entry.disabled === true)
|
||||
if (disabled.some(Boolean) && disabled.some(value => !value)) {
|
||||
diagnostics.push('owned Cordis config entries have mixed enabled states')
|
||||
}
|
||||
if (diagnostics.length > 0) {
|
||||
return { id: this.id, state: 'inconsistent', options, diagnostics }
|
||||
}
|
||||
return {
|
||||
id: this.id,
|
||||
state: ownedConfigEntries.length > 0 && disabled.every(Boolean) ? 'disabled' : 'enabled',
|
||||
options,
|
||||
selection,
|
||||
diagnostics: [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Fixed one-option feature base. */
|
||||
export abstract class FixedFeature extends Feature {
|
||||
override readonly mode = 'single'
|
||||
|
||||
/** Select the sole option. */
|
||||
override defaultOptions(): readonly string[] {
|
||||
const option = this.options[0]
|
||||
if (!option) throw new Error(`simple feature ${this.id} has no option`)
|
||||
return [option.id]
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutually exclusive option feature base. */
|
||||
export abstract class ExclusiveOptionFeature extends Feature {
|
||||
override readonly mode = 'exclusive'
|
||||
}
|
||||
|
||||
/** Additive multi-option feature base. */
|
||||
export abstract class MultiOptionFeature extends Feature {
|
||||
override readonly mode = 'multiple'
|
||||
}
|
||||
87
packages/scaffold/helper/src/features/registry.ts
Normal file
87
packages/scaffold/helper/src/features/registry.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Builtin feature registry and definition-time conflict checks.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/registry
|
||||
*/
|
||||
|
||||
import type { FeatureId, ResourceKey } from '../ids.ts'
|
||||
import type { ProjectProfile } from '../project/types.ts'
|
||||
import type { Feature, FeatureProjectView } from './feature.ts'
|
||||
import type { CordisConfigEntryResource } from './resources.ts'
|
||||
|
||||
/** Compile-time builtin feature collection. */
|
||||
export class FeatureRegistry {
|
||||
private readonly features = new Map<FeatureId, Feature>()
|
||||
|
||||
/** Register and validate a complete builtin set. */
|
||||
constructor(features: readonly Feature[], validationProfile: ProjectProfile) {
|
||||
const owners = new Map<ResourceKey, FeatureId>()
|
||||
for (const feature of features) {
|
||||
if (this.features.has(feature.id)) throw new Error(`duplicate feature id: ${feature.id}`)
|
||||
this.features.set(feature.id, feature)
|
||||
const validationInterface = feature.supportedInterfaces[0]
|
||||
if (!validationInterface) throw new Error(`feature ${feature.id} supports no run interface`)
|
||||
const selections = feature.options.map(option => ({ id: feature.id, options: [option.id] }))
|
||||
for (const selection of selections) {
|
||||
const contribution = feature.contribution(selection, {
|
||||
...validationProfile,
|
||||
runInterface: validationInterface,
|
||||
})
|
||||
for (const resource of contribution.resources) {
|
||||
const owner = owners.get(resource.key)
|
||||
if (owner && owner !== feature.id) {
|
||||
throw new Error(`resource ${resource.key} is declared by both ${owner} and ${feature.id}`)
|
||||
}
|
||||
owners.set(resource.key, feature.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all builtins in display order.
|
||||
* @returns all registered features.
|
||||
*/
|
||||
all(): readonly Feature[] {
|
||||
return [...this.features.values()]
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one builtin or fail loud.
|
||||
* @param id - stable feature identity.
|
||||
* @returns registered feature.
|
||||
*/
|
||||
get(id: FeatureId): Feature {
|
||||
const feature = this.features.get(id)
|
||||
if (!feature) throw new Error(`unknown feature: ${id}`)
|
||||
return feature
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect every applicable builtin in display order.
|
||||
* @param project - project view to inspect.
|
||||
* @returns installation snapshots for applicable features.
|
||||
*/
|
||||
inspect(project: FeatureProjectView): ReturnType<Feature['inspect']>[] {
|
||||
return this.all()
|
||||
.filter(feature => feature.isApplicable(project.profile))
|
||||
.map(feature => feature.inspect(project))
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the builtin that owns a Cordis package name for this profile.
|
||||
* @param name - Loader package name.
|
||||
* @param profile - project context controlling applicability.
|
||||
* @returns owning feature, if the package is builtin-owned.
|
||||
*/
|
||||
ownerOfPackage(name: string, profile: ProjectProfile): Feature | undefined {
|
||||
return this.all().find((feature) => {
|
||||
if (!feature.isApplicable(profile)) return false
|
||||
const selections = feature.options.map(option => ({ id: feature.id, options: [option.id] }))
|
||||
return selections.some(selection => feature.contribution(selection, profile).resources.some(
|
||||
(resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry'
|
||||
&& resource.entry.name === name,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
97
packages/scaffold/helper/src/features/resources.ts
Normal file
97
packages/scaffold/helper/src/features/resources.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Resource vocabulary contributed by builtin SDK features.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/features/resources
|
||||
*/
|
||||
|
||||
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import type { ProjectFile } from '../documents/project-file.ts'
|
||||
import type { ResourceKey } from '../ids.ts'
|
||||
|
||||
/** Runtime or development NPM dependency contribution. */
|
||||
export interface NpmDependencyResource {
|
||||
kind: 'npm-dependency'
|
||||
key: ResourceKey
|
||||
name: string
|
||||
section: 'dependencies' | 'devDependencies'
|
||||
}
|
||||
|
||||
/** Feature-owned package script. */
|
||||
export interface PackageScriptResource {
|
||||
kind: 'package-script'
|
||||
key: ResourceKey
|
||||
name: string
|
||||
command: string
|
||||
removeOnlyWhenUnchanged: boolean
|
||||
}
|
||||
|
||||
/** Owned Cordis config entry plus the config keys safe to update in place. */
|
||||
export interface CordisConfigEntryResource {
|
||||
kind: 'cordis-config-entry'
|
||||
key: ResourceKey
|
||||
entry: CordisConfigEntry
|
||||
ownedConfigKeys: readonly string[]
|
||||
commentedExample?: string
|
||||
validateConfig?: (config: Readonly<Record<string, unknown>>) => readonly string[]
|
||||
}
|
||||
|
||||
/** Environment variable reference and dotenv material. */
|
||||
export interface EnvironmentResource {
|
||||
kind: 'environment'
|
||||
key: ResourceKey
|
||||
name: string
|
||||
value?: string
|
||||
exampleValue: string
|
||||
comment?: string
|
||||
}
|
||||
|
||||
/** Feature-exclusive complete file. */
|
||||
export interface OwnedFileResource {
|
||||
kind: 'owned-file'
|
||||
key: ResourceKey
|
||||
document: ProjectFile
|
||||
removeOnlyWhenUnchanged: boolean
|
||||
}
|
||||
|
||||
/** Any resource a feature can add to a project. */
|
||||
export type ProjectResource =
|
||||
| NpmDependencyResource
|
||||
| PackageScriptResource
|
||||
| CordisConfigEntryResource
|
||||
| EnvironmentResource
|
||||
| OwnedFileResource
|
||||
|
||||
/** Complete resource contribution for one selected feature state. */
|
||||
export class ProjectContribution {
|
||||
readonly resources: readonly ProjectResource[]
|
||||
|
||||
/** Validate and retain one feature-owned resource set. */
|
||||
constructor(resources: readonly ProjectResource[]) {
|
||||
const seen = new Set<ResourceKey>()
|
||||
for (const resource of resources) {
|
||||
if (seen.has(resource.key)) throw new Error(`duplicate contribution resource key: ${resource.key}`)
|
||||
seen.add(resource.key)
|
||||
}
|
||||
this.resources = resources
|
||||
}
|
||||
|
||||
/** Merge base and option contributions by stable key. */
|
||||
static merge(...contributions: readonly ProjectContribution[]): ProjectContribution {
|
||||
const resources = new Map<ResourceKey, ProjectResource>()
|
||||
for (const contribution of contributions) {
|
||||
for (const resource of contribution.resources) {
|
||||
const previous = resources.get(resource.key)
|
||||
if (previous && JSON.stringify(previous) !== JSON.stringify(resource)) {
|
||||
throw new Error(`resource ${resource.key} has conflicting definitions inside one feature`)
|
||||
}
|
||||
resources.set(resource.key, resource)
|
||||
}
|
||||
}
|
||||
return new ProjectContribution([...resources.values()])
|
||||
}
|
||||
|
||||
/** Index resources by stable key. */
|
||||
byKey(): ReadonlyMap<ResourceKey, ProjectResource> {
|
||||
return new Map(this.resources.map(resource => [resource.key, resource]))
|
||||
}
|
||||
}
|
||||
31
packages/scaffold/helper/src/ids.ts
Normal file
31
packages/scaffold/helper/src/ids.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Branded identities owned by the SDK project domain.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/ids
|
||||
*/
|
||||
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
/** Stable identity of a builtin SDK feature. */
|
||||
export type FeatureId = Branded<'FeatureId'>
|
||||
|
||||
/**
|
||||
* Construct a feature identity from its registry key.
|
||||
* @param value - lowercase kebab-case registry key.
|
||||
* @returns branded feature identity.
|
||||
*/
|
||||
export function featureId(value: string): FeatureId {
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(value)) {
|
||||
throw new Error(`invalid feature id: ${JSON.stringify(value)}`)
|
||||
}
|
||||
return value as FeatureId
|
||||
}
|
||||
|
||||
/** Stable identity of a resource contributed to an SDK project. */
|
||||
export type ResourceKey = Branded<'ResourceKey'>
|
||||
|
||||
/** Construct a resource key from its owner-qualified value. */
|
||||
export function resourceKey(value: string): ResourceKey {
|
||||
if (value.length === 0) throw new Error('resource key must not be empty')
|
||||
return value as ResourceKey
|
||||
}
|
||||
50
packages/scaffold/helper/src/index.ts
Normal file
50
packages/scaffold/helper/src/index.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Shared domain and infrastructure for DeepSeek Harness SDK project tooling.
|
||||
*
|
||||
* FIXME: rename to `@deepseek-ai/dsh-sdk-helper` before the first tagged release —
|
||||
* the current name is indefensibly generic as a published name
|
||||
* ([regrouping Agent Note](../../../../.agents/notes/proposed/architecture/2026-07-29-package-regrouping.md)).
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper
|
||||
*/
|
||||
|
||||
export { featureId } from './ids.ts'
|
||||
export { TextTemplate } from './templates/text-template.ts'
|
||||
export type {
|
||||
FeatureSelection,
|
||||
ProjectCreationRequest,
|
||||
ProjectProfile,
|
||||
RunInterface,
|
||||
} from './project/types.ts'
|
||||
export type { ChangeSet, ProjectCommitResult } from './project/change-set.ts'
|
||||
export { SdkProject } from './project/sdk-project.ts'
|
||||
export {
|
||||
NodeCommandRunner,
|
||||
NpmPackageManager,
|
||||
createPackageManager,
|
||||
inferPackageManagerName,
|
||||
probePackageManagerVersion,
|
||||
} from './package-managers/package-manager.ts'
|
||||
export type {
|
||||
CommandRunner,
|
||||
PackageManager,
|
||||
PackageManagerName,
|
||||
PackageManagerVersionProbe,
|
||||
} from './package-managers/package-manager.ts'
|
||||
export { LocalPluginBlueprint } from './plugins/local-plugin-blueprint.ts'
|
||||
export type { LocalPluginKind } from './plugins/local-plugin-blueprint.ts'
|
||||
export type { Feature, FeatureInstallation } from './features/feature.ts'
|
||||
export type { FeatureRegistry } from './features/registry.ts'
|
||||
export { FeatureConfigurator } from './features/feature-configurator.ts'
|
||||
export { createBuiltinRegistry } from './features/builtin/index.ts'
|
||||
export { PromptCancelledError, requireAnswer } from './questions/prompt-port.ts'
|
||||
export type { NestedMultiSelectValue, PromptPort } from './questions/prompt-port.ts'
|
||||
export {
|
||||
ConfirmQuestion,
|
||||
SecretQuestion,
|
||||
SelectQuestion,
|
||||
TextQuestion,
|
||||
} from './questions/question.ts'
|
||||
export type { Question } from './questions/question.ts'
|
||||
export { ClackPromptPort } from './questions/clack-prompt-port.ts'
|
||||
export { HeadlessPromptError, HeadlessPromptPort } from './questions/headless-prompt-port.ts'
|
||||
30
packages/scaffold/helper/src/invariant.ts
Normal file
30
packages/scaffold/helper/src/invariant.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Package-owned invariant companion for `@deepseek-ai/dsh-helper`.
|
||||
* @module @deepseek-ai/dsh-helper/invariant
|
||||
*/
|
||||
|
||||
/* jscpd:ignore-start */
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-helper'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'helper-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/**
|
||||
* No runtime invariant: this SDK build-time package owns no live event stream or mutable data;
|
||||
* generated output and consumer tests cover its contract.
|
||||
*/
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register this package's invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
/* jscpd:ignore-end */
|
||||
137
packages/scaffold/helper/src/package-managers/link-workspace.ts
Normal file
137
packages/scaffold/helper/src/package-managers/link-workspace.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Repository package discovery and NPM dependency-closure rewriting for live links.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/package-managers/link-workspace
|
||||
*/
|
||||
|
||||
import { readFile, readdir } from 'node:fs/promises'
|
||||
import { existsSync, realpathSync } from 'node:fs'
|
||||
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
|
||||
import type { PackageJsonFile, PackageManifest } from '../documents/package-json-file.ts'
|
||||
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
|
||||
import type { ProjectFile } from '../documents/project-file.ts'
|
||||
import type { PackageManager } from './package-manager.ts'
|
||||
|
||||
interface WorkspacePackage {
|
||||
directory: string
|
||||
manifest: PackageManifest
|
||||
}
|
||||
|
||||
function posixPath(path: string): string {
|
||||
return path.split(sep).join('/')
|
||||
}
|
||||
|
||||
function canonicalPath(path: string): string {
|
||||
let existing = resolve(path)
|
||||
const suffix: string[] = []
|
||||
while (!existsSync(existing)) {
|
||||
const parent = dirname(existing)
|
||||
/* v8 ignore next -- every absolute path reaches the existing filesystem root */
|
||||
if (parent === existing) throw new Error(`cannot resolve an existing ancestor for ${path}`)
|
||||
suffix.unshift(basename(existing))
|
||||
existing = parent
|
||||
}
|
||||
return resolve(realpathSync(existing), ...suffix)
|
||||
}
|
||||
|
||||
async function packageDirectories(root: string): Promise<string[]> {
|
||||
const result: string[] = []
|
||||
for (const vendor of await readdir(join(root, 'vendor'), { withFileTypes: true })) {
|
||||
if (vendor.isDirectory()) result.push(join(root, 'vendor', vendor.name))
|
||||
}
|
||||
for (const group of await readdir(join(root, 'packages'), { withFileTypes: true })) {
|
||||
if (!group.isDirectory()) continue
|
||||
for (const pkg of await readdir(join(root, 'packages', group.name), { withFileTypes: true })) {
|
||||
if (pkg.isDirectory()) result.push(join(root, 'packages', group.name, pkg.name))
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/** Index of repository packages used by `--link-workspace`. */
|
||||
export class LinkWorkspace {
|
||||
readonly root: string
|
||||
private readonly packages: Map<string, WorkspacePackage>
|
||||
|
||||
private constructor(root: string, packages: Map<string, WorkspacePackage>) {
|
||||
this.root = root
|
||||
this.packages = packages
|
||||
}
|
||||
|
||||
/** Scan vendor and package workspaces from a repository root. */
|
||||
static async open(root: string): Promise<LinkWorkspace> {
|
||||
const absolute = resolve(root)
|
||||
const packages = new Map<string, WorkspacePackage>()
|
||||
for (const directory of await packageDirectories(absolute)) {
|
||||
let manifest: PackageManifest
|
||||
try {
|
||||
manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')) as PackageManifest
|
||||
} catch (error) {
|
||||
throw new Error(`cannot read linked package at ${directory}: ${String(error)}`)
|
||||
}
|
||||
if (!manifest.name || typeof manifest.name !== 'string') continue
|
||||
if (packages.has(manifest.name)) throw new Error(`duplicate linked package name: ${manifest.name}`)
|
||||
packages.set(manifest.name, { directory, manifest })
|
||||
}
|
||||
if (!packages.has('cordis') || !packages.has('@deepseek-ai/dsh-scripts')) {
|
||||
throw new Error(`not a DeepSeek Harness repository root: ${absolute}`)
|
||||
}
|
||||
return new LinkWorkspace(absolute, packages)
|
||||
}
|
||||
|
||||
/** Expand direct NPM dependencies through all repository-local NPM dependency edges. */
|
||||
closure(names: Iterable<string>): string[] {
|
||||
const pending = [...names]
|
||||
const result = new Set<string>()
|
||||
while (pending.length > 0) {
|
||||
const name = pending.pop()
|
||||
if (!name || result.has(name)) continue
|
||||
const pkg = this.packages.get(name)
|
||||
/* v8 ignore next -- closure() only returns names present in this package map */
|
||||
if (!pkg) continue
|
||||
result.add(name)
|
||||
const edges = {
|
||||
...pkg.manifest.dependencies,
|
||||
...pkg.manifest.peerDependencies as Record<string, string> | undefined,
|
||||
}
|
||||
for (const dependencyName of Object.keys(edges)) {
|
||||
if (this.packages.has(dependencyName) && !result.has(dependencyName)) pending.push(dependencyName)
|
||||
}
|
||||
}
|
||||
return [...result].sort()
|
||||
}
|
||||
|
||||
/** Rewrite the full local closure to manager-specific live-link specs. */
|
||||
apply(
|
||||
projectRoot: string,
|
||||
manifest: PackageJsonFile,
|
||||
manager: PackageManager,
|
||||
documents: readonly ProjectFile[],
|
||||
): void {
|
||||
const canonicalProjectRoot = canonicalPath(projectRoot)
|
||||
const names = this.closure(manifest.npmDependencyNames())
|
||||
for (const name of names) {
|
||||
const pkg = this.packages.get(name)
|
||||
/* v8 ignore next -- closure() only returns names present in this package map */
|
||||
if (!pkg) continue
|
||||
const relativePath = posixPath(relative(canonicalProjectRoot, realpathSync(pkg.directory)))
|
||||
const spec = manager.linkSpec(relativePath)
|
||||
const current = manifest.npmDependency(name)
|
||||
manifest.setNpmDependency(current?.section ?? 'dependencies', name, spec)
|
||||
if (manager.name === 'yarn') manifest.setResolution(name, spec)
|
||||
}
|
||||
if (manager.name === 'pnpm') {
|
||||
const workspace = documents.find((item): item is PnpmWorkspaceFile => item instanceof PnpmWorkspaceFile)
|
||||
if (!workspace) throw new Error('pnpm link mode requires pnpm-workspace.yaml')
|
||||
workspace.disableAutoInstallPeers()
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve a package directory for diagnostics and tests. */
|
||||
packageDirectory(name: string): string | undefined {
|
||||
const directory = this.packages.get(name)?.directory
|
||||
return directory
|
||||
? resolve(dirname(directory), directory.split(sep).at(-1) as string)
|
||||
: undefined
|
||||
}
|
||||
}
|
||||
332
packages/scaffold/helper/src/package-managers/package-manager.ts
Normal file
332
packages/scaffold/helper/src/package-managers/package-manager.ts
Normal file
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* Package-manager strategies for SDK project workspaces and child commands.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/package-managers/package-manager
|
||||
*/
|
||||
|
||||
import { execFile, spawn } from 'node:child_process'
|
||||
import { scrubbedParentEnv, SENSITIVE_ENV_PATTERN } from '@deepseek-ai/dsh-subprocess'
|
||||
import { promisify } from 'node:util'
|
||||
import type { PackageJsonFile } from '../documents/package-json-file.ts'
|
||||
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
|
||||
import type { ProjectFile } from '../documents/project-file.ts'
|
||||
|
||||
/** Supported generated-project package managers. */
|
||||
export type PackageManagerName = 'npm' | 'pnpm' | 'yarn'
|
||||
|
||||
/** Result from one child package-manager process. */
|
||||
export interface CommandResult {
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
}
|
||||
|
||||
/** Injectable subprocess boundary used by package-manager strategies. */
|
||||
export interface CommandRunner {
|
||||
/** Run one executable without a shell and await process exit. */
|
||||
run(command: string, args: readonly string[], cwd: string): Promise<CommandResult>
|
||||
}
|
||||
|
||||
/** Injectable package-manager version probe used by project creation. */
|
||||
export type PackageManagerVersionProbe = (name: PackageManagerName, cwd: string) => Promise<string>
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/**
|
||||
* Read a manager version without forwarding ambient credentials.
|
||||
* @param name - package-manager executable.
|
||||
* @param cwd - working directory used for resolution.
|
||||
* @returns trimmed version output.
|
||||
*/
|
||||
export async function probePackageManagerVersion(name: PackageManagerName, cwd: string): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(name, ['--version'], {
|
||||
cwd,
|
||||
env: scrubEnvironment(),
|
||||
encoding: 'utf8',
|
||||
})
|
||||
const version = stdout.trim()
|
||||
if (!version) throw new Error('empty version output')
|
||||
return version
|
||||
} catch (error) {
|
||||
throw new Error(`cannot run ${name} --version: ${String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove credential-shaped environment variables from spawned commands.
|
||||
* @param environment - source environment (injectable for tests); the default
|
||||
* path shares the subprocess seam's scrub so every harness spawner drops the
|
||||
* same names.
|
||||
*/
|
||||
export function scrubEnvironment(environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
if (environment === undefined) return scrubbedParentEnv()
|
||||
return Object.fromEntries(Object.entries(environment).filter(([name]) => !SENSITIVE_ENV_PATTERN.test(name)))
|
||||
}
|
||||
|
||||
/** Node child-process command runner with inherited stdio and quiescent completion. */
|
||||
export class NodeCommandRunner implements CommandRunner {
|
||||
private readonly output: NodeJS.WritableStream | undefined
|
||||
|
||||
/**
|
||||
* @param output - redirect target for child stdout+stderr; the child inherits
|
||||
* this process's stdio when absent. Callers whose own stdout carries a machine
|
||||
* protocol (create-sdk --json NDJSON) redirect child output to keep the
|
||||
* protocol stream pure.
|
||||
*/
|
||||
constructor(output?: NodeJS.WritableStream) {
|
||||
this.output = output
|
||||
}
|
||||
|
||||
/** Spawn one child and settle only after exit, with redirected stdio drained. */
|
||||
run(command: string, args: readonly string[], cwd: string): Promise<CommandResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const output = this.output
|
||||
if (output === undefined) {
|
||||
const child = spawn(command, [...args], { cwd, env: scrubEnvironment(), stdio: 'inherit', shell: false })
|
||||
child.once('error', reject)
|
||||
child.once('exit', (exitCode, signal) => { resolve({ exitCode, signal }) })
|
||||
return
|
||||
}
|
||||
const child = spawn(command, [...args], {
|
||||
cwd,
|
||||
env: scrubEnvironment(),
|
||||
stdio: ['inherit', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
})
|
||||
child.stdout.pipe(output, { end: false })
|
||||
child.stderr.pipe(output, { end: false })
|
||||
child.once('error', reject)
|
||||
child.once('close', (exitCode, signal) => { resolve({ exitCode, signal }) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function major(version: string): number {
|
||||
const match = /^(\d+)/.exec(version)
|
||||
if (!match?.[1]) throw new Error(`invalid package manager version: ${JSON.stringify(version)}`)
|
||||
return Number(match[1])
|
||||
}
|
||||
|
||||
/** Behavior owned by one generated-project package manager. */
|
||||
export abstract class PackageManager {
|
||||
/** Manager executable and project identity. */
|
||||
abstract readonly name: PackageManagerName
|
||||
|
||||
/** Detected concrete manager version. */
|
||||
readonly version: string
|
||||
|
||||
constructor(version: string) {
|
||||
this.version = version
|
||||
}
|
||||
|
||||
/** Validate the detected version against this SDK's supported floor. */
|
||||
abstract validateVersion(): void
|
||||
|
||||
/**
|
||||
* Configure root manifest fields and return manager-specific files.
|
||||
* @param manifest - generated root manifest to update.
|
||||
* @returns manager-specific companion documents.
|
||||
*/
|
||||
abstract configureWorkspace(manifest: PackageJsonFile): ProjectFile[]
|
||||
|
||||
/**
|
||||
* Build the NPM dependency spec for a local workspace plugin.
|
||||
* @returns manager-specific local NPM dependency spec.
|
||||
*/
|
||||
abstract localPluginSpec(): string
|
||||
|
||||
/**
|
||||
* Resolve a repository live-link NPM dependency.
|
||||
* @param relativePath - relative path from generated project to package.
|
||||
* @returns manager-specific NPM dependency spec.
|
||||
*/
|
||||
abstract linkSpec(relativePath: string): string
|
||||
|
||||
/**
|
||||
* Build install command arguments.
|
||||
* @returns arguments following the manager executable.
|
||||
*/
|
||||
installCommand(): readonly string[] {
|
||||
return ['install']
|
||||
}
|
||||
|
||||
/**
|
||||
* Build project-build command arguments.
|
||||
* @returns arguments following the manager executable.
|
||||
*/
|
||||
buildCommand(): readonly string[] {
|
||||
return ['run', 'build']
|
||||
}
|
||||
|
||||
/**
|
||||
* Run NPM dependency installation and fail on non-zero or signalled exit.
|
||||
* @param cwd - generated project directory.
|
||||
* @param runner - optional subprocess boundary.
|
||||
*/
|
||||
async install(cwd: string, runner: CommandRunner = new NodeCommandRunner()): Promise<void> {
|
||||
await this.runChecked(runner, this.installCommand(), cwd, 'install')
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the project build and fail on non-zero or signalled exit.
|
||||
* @param cwd - generated project directory.
|
||||
* @param runner - optional subprocess boundary.
|
||||
*/
|
||||
async build(cwd: string, runner: CommandRunner = new NodeCommandRunner()): Promise<void> {
|
||||
await this.runChecked(runner, this.buildCommand(), cwd, 'build')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build add-dependency command arguments for one already-normalized source spec.
|
||||
* @param spec - a package-manager-native dependency source (`pkg@version` or `github:owner/repo#ref`).
|
||||
* @returns arguments following the manager executable.
|
||||
*/
|
||||
addCommand(spec: string): readonly string[] {
|
||||
return ['add', spec]
|
||||
}
|
||||
|
||||
/**
|
||||
* Add one dependency from a native source spec and fail on non-zero or signalled exit.
|
||||
* @param spec - a package-manager-native dependency source.
|
||||
* @param cwd - project directory.
|
||||
* @param runner - optional subprocess boundary.
|
||||
*/
|
||||
async add(spec: string, cwd: string, runner: CommandRunner = new NodeCommandRunner()): Promise<void> {
|
||||
await this.runChecked(runner, this.addCommand(spec), cwd, 'add')
|
||||
}
|
||||
|
||||
private async runChecked(runner: CommandRunner, args: readonly string[], cwd: string, operation: string): Promise<void> {
|
||||
const result = await runner.run(this.name, args, cwd)
|
||||
if (result.signal !== null) {
|
||||
throw new Error(`${this.name} ${operation} was killed by ${result.signal}`)
|
||||
}
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`${this.name} ${operation} exited with code ${String(result.exitCode)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** npm workspace behavior. */
|
||||
export class NpmPackageManager extends PackageManager {
|
||||
override readonly name = 'npm'
|
||||
|
||||
/** npm 10 is the supported floor at the repository's Node floor. */
|
||||
override validateVersion(): void {
|
||||
if (major(this.version) < 10) throw new Error(`npm >=10 is required, got ${this.version}`)
|
||||
}
|
||||
|
||||
/** Configure package.json workspaces; npm needs no companion file. */
|
||||
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
|
||||
manifest.addWorkspace('plugins/*')
|
||||
manifest.setPackageManager(undefined)
|
||||
return []
|
||||
}
|
||||
|
||||
/** npm resolves workspace packages through its ordinary wildcard. */
|
||||
override localPluginSpec(): string {
|
||||
return '*'
|
||||
}
|
||||
|
||||
/** npm live links use file NPM dependencies. */
|
||||
override linkSpec(relativePath: string): string {
|
||||
return `file:${relativePath}`
|
||||
}
|
||||
|
||||
/** npm adds a dependency through `install <spec>` rather than an `add` verb. */
|
||||
override addCommand(spec: string): readonly string[] {
|
||||
return ['install', spec]
|
||||
}
|
||||
}
|
||||
|
||||
/** pnpm workspace behavior. */
|
||||
export class PnpmPackageManager extends PackageManager {
|
||||
override readonly name = 'pnpm'
|
||||
|
||||
/** pnpm 10 is the supported floor for strict NPM dependency-build policy. */
|
||||
override validateVersion(): void {
|
||||
if (major(this.version) < 10) throw new Error(`pnpm >=10 is required, got ${this.version}`)
|
||||
}
|
||||
|
||||
/** Configure packageManager and a structured pnpm workspace file. */
|
||||
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
|
||||
manifest.setPackageManager(`pnpm@${this.version}`)
|
||||
const workspace = PnpmWorkspaceFile.create()
|
||||
workspace.addPackage('plugins/*')
|
||||
return [workspace]
|
||||
}
|
||||
|
||||
/** pnpm uses its explicit workspace protocol. */
|
||||
override localPluginSpec(): string {
|
||||
return 'workspace:*'
|
||||
}
|
||||
|
||||
/** pnpm live links use link NPM dependencies. */
|
||||
override linkSpec(relativePath: string): string {
|
||||
return `link:${relativePath}`
|
||||
}
|
||||
}
|
||||
|
||||
/** Yarn Berry-compatible workspace behavior. */
|
||||
export class YarnPackageManager extends PackageManager {
|
||||
override readonly name = 'yarn'
|
||||
|
||||
/** Yarn classic is excluded because the generated project relies on modern workspaces. */
|
||||
override validateVersion(): void {
|
||||
if (major(this.version) < 2) throw new Error(`Yarn >=2 is required, got ${this.version}`)
|
||||
}
|
||||
|
||||
/** Configure packageManager and package.json workspaces. */
|
||||
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
|
||||
manifest.addWorkspace('plugins/*')
|
||||
manifest.setPackageManager(`yarn@${this.version}`)
|
||||
return []
|
||||
}
|
||||
|
||||
/** Modern Yarn uses the workspace protocol. */
|
||||
override localPluginSpec(): string {
|
||||
return 'workspace:*'
|
||||
}
|
||||
|
||||
/** Yarn live links use portal NPM dependencies to preserve package identity. */
|
||||
override linkSpec(relativePath: string): string {
|
||||
return `portal:${relativePath}`
|
||||
}
|
||||
|
||||
/** Yarn runs scripts without the `run` token. */
|
||||
override buildCommand(): readonly string[] {
|
||||
return ['build']
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct and validate one package-manager strategy.
|
||||
* @param name - selected manager.
|
||||
* @param version - detected concrete version.
|
||||
* @returns validated strategy.
|
||||
*/
|
||||
export function createPackageManager(name: PackageManagerName, version: string): PackageManager {
|
||||
let manager: PackageManager
|
||||
switch (name) {
|
||||
case 'npm': manager = new NpmPackageManager(version); break
|
||||
case 'pnpm': manager = new PnpmPackageManager(version); break
|
||||
case 'yarn': manager = new YarnPackageManager(version); break
|
||||
}
|
||||
manager.validateVersion()
|
||||
return manager
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer a package manager from an explicit choice or npm user-agent value.
|
||||
* @param explicit - explicit CLI selection.
|
||||
* @param userAgent - npm-compatible user-agent string.
|
||||
* @returns selected or inferred manager name.
|
||||
*/
|
||||
export function inferPackageManagerName(
|
||||
explicit: PackageManagerName | undefined,
|
||||
userAgent: string | undefined = process.env.npm_config_user_agent,
|
||||
): PackageManagerName | undefined {
|
||||
if (explicit) return explicit
|
||||
const token = userAgent?.split(' ')[0]?.split('/')[0]
|
||||
if (token === 'npm' || token === 'pnpm' || token === 'yarn') return token
|
||||
return undefined
|
||||
}
|
||||
123
packages/scaffold/helper/src/plugins/local-plugin-blueprint.ts
Normal file
123
packages/scaffold/helper/src/plugins/local-plugin-blueprint.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Source blueprints for local Cordis plugins generated under `plugins/*`.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/plugins/local-plugin-blueprint
|
||||
*/
|
||||
|
||||
import { TextProjectFile } from '../documents/project-file.ts'
|
||||
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import { resolveNpmDependency } from '../project/npm-dependency-policy.ts'
|
||||
import { loadHelperTemplate } from '../templates/template-assets.ts'
|
||||
|
||||
/** Supported generated local-plugin shapes. */
|
||||
export type LocalPluginKind = 'plugin' | 'tool'
|
||||
|
||||
function kebab(value: string): string {
|
||||
const result = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
|
||||
if (!result || !/^[a-z]/.test(result)) throw new Error(`invalid local plugin name: ${JSON.stringify(value)}`)
|
||||
return result
|
||||
}
|
||||
|
||||
function packageName(projectName: string, pluginName: string): string {
|
||||
if (projectName.startsWith('@')) {
|
||||
const separator = projectName.indexOf('/')
|
||||
if (separator > 1 && separator < projectName.length - 1) {
|
||||
return `${projectName.slice(0, separator)}/${projectName.slice(separator + 1)}-${pluginName}`
|
||||
}
|
||||
}
|
||||
return `${projectName}-${pluginName}`
|
||||
}
|
||||
|
||||
interface LocalPluginTemplateContext {
|
||||
pluginName: string
|
||||
toolName: string
|
||||
toolTitle: string
|
||||
}
|
||||
|
||||
const PLUGIN_SOURCE = loadHelperTemplate<LocalPluginTemplateContext>('local-plugin.ts.tpl')
|
||||
const TOOL_SOURCE = loadHelperTemplate<LocalPluginTemplateContext>('local-tool.ts.tpl')
|
||||
const PLUGIN_TSDOWN = loadHelperTemplate<LocalPluginTemplateContext>('local-plugin-tsdown.config.ts.tpl')
|
||||
|
||||
/** One local plugin's derived package, source, build, and runtime entry. */
|
||||
export class LocalPluginBlueprint {
|
||||
/** Normalized local package and Cordis config entry name. */
|
||||
readonly name: string
|
||||
/** Generated plugin source shape. */
|
||||
readonly kind: LocalPluginKind
|
||||
|
||||
/** Normalize and validate one local plugin request. */
|
||||
constructor(name: string, kind: LocalPluginKind) {
|
||||
this.name = kebab(name)
|
||||
this.kind = kind
|
||||
}
|
||||
|
||||
/** Root-relative plugin directory. */
|
||||
get directory(): string {
|
||||
return `plugins/${this.name}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive an npm package name from the root project identity.
|
||||
* @param projectName - generated root package name.
|
||||
* @returns local plugin package name.
|
||||
*/
|
||||
packageName(projectName: string): string {
|
||||
return packageName(projectName, this.name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the runtime Cordis config entry for this local package.
|
||||
* @param projectName - generated root package name.
|
||||
* @returns Loader entry referencing the local package.
|
||||
*/
|
||||
cordisConfigEntry(projectName: string): CordisConfigEntry {
|
||||
return { id: this.name, name: this.packageName(projectName) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the complete local package files.
|
||||
* @param projectName - generated root package name.
|
||||
* @param releaseVersion - SDK dependency version.
|
||||
* @returns local manifest, configs, and source documents.
|
||||
*/
|
||||
documents(projectName: string, releaseVersion: string): TextProjectFile[] {
|
||||
const name = this.packageName(projectName)
|
||||
const toolName = this.name.replaceAll('-', '_')
|
||||
const cordisSpec = resolveNpmDependency('cordis', 'devDependencies', releaseVersion).spec
|
||||
const manifest = {
|
||||
name,
|
||||
version: '0.0.0',
|
||||
private: true,
|
||||
type: 'module',
|
||||
main: 'lib/index.js',
|
||||
types: 'lib/index.d.ts',
|
||||
exports: { '.': { types: './lib/index.d.ts', default: './lib/index.js' } },
|
||||
peerDependencies: {
|
||||
...this.kind === 'tool' ? { '@deepseek-ai/dsh-tools': `^${releaseVersion}` } : {},
|
||||
cordis: cordisSpec,
|
||||
},
|
||||
devDependencies: {
|
||||
cordis: cordisSpec,
|
||||
},
|
||||
}
|
||||
const tsconfig = {
|
||||
extends: '../../tsconfig.base.json',
|
||||
compilerOptions: { rootDir: 'src', outDir: 'lib/types' },
|
||||
include: ['src'],
|
||||
}
|
||||
const context: LocalPluginTemplateContext = {
|
||||
pluginName: this.name,
|
||||
toolName,
|
||||
toolTitle: toolName.replaceAll('_', ' '),
|
||||
}
|
||||
return [
|
||||
new TextProjectFile(`${this.directory}/package.json`, JSON.stringify(manifest, null, 2)),
|
||||
new TextProjectFile(`${this.directory}/tsconfig.json`, JSON.stringify(tsconfig, null, 2)),
|
||||
new TextProjectFile(`${this.directory}/tsdown.config.ts`, PLUGIN_TSDOWN.render(context)),
|
||||
new TextProjectFile(
|
||||
`${this.directory}/src/index.ts`,
|
||||
(this.kind === 'tool' ? TOOL_SOURCE : PLUGIN_SOURCE).render(context),
|
||||
),
|
||||
]
|
||||
}
|
||||
}
|
||||
26
packages/scaffold/helper/src/project/change-set.ts
Normal file
26
packages/scaffold/helper/src/project/change-set.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Result summary for one SDK project edit session.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/project/change-set
|
||||
*/
|
||||
|
||||
import type { FeatureId } from '../ids.ts'
|
||||
|
||||
/** Immutable description of committed or pending project changes. */
|
||||
export interface ChangeSet {
|
||||
addedFeatures: readonly FeatureId[]
|
||||
enabledFeatures: readonly FeatureId[]
|
||||
disabledFeatures: readonly FeatureId[]
|
||||
configuredFeatures: readonly FeatureId[]
|
||||
addedPlugins: readonly string[]
|
||||
enabledPlugins: readonly string[]
|
||||
disabledPlugins: readonly string[]
|
||||
changedFiles: readonly string[]
|
||||
npmDependenciesChanged: boolean
|
||||
}
|
||||
|
||||
/** Result of committing one project edit session. */
|
||||
export interface ProjectCommitResult<TProject> {
|
||||
project: TProject
|
||||
changes: ChangeSet
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* NPM dependency baseline and version policy for generated SDK projects.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/project/npm-dependency-policy
|
||||
*/
|
||||
|
||||
import type { NpmDependencySection } from '../documents/package-json-file.ts'
|
||||
|
||||
/** One NPM dependency spec selected by the SDK release policy. */
|
||||
export interface ResolvedNpmDependency {
|
||||
section: NpmDependencySection
|
||||
spec: string
|
||||
}
|
||||
|
||||
/** NPM dependency maps rendered into a newly created root package.json. */
|
||||
export interface BaselineNpmDependencies {
|
||||
dependencies: Readonly<Record<string, string>>
|
||||
devDependencies: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
const EXTERNAL_NPM_DEPENDENCY_SPECS: Readonly<Record<string, string>> = {
|
||||
'@cordisjs/plugin-hmr': '^1.0.15',
|
||||
'@cordisjs/plugin-timer': '^1.1.2',
|
||||
'@types/node': '^22.20.0',
|
||||
cordis: '^4.0.0-rc.7',
|
||||
tsdown: '0.22.2',
|
||||
tsx: '^4.22.4',
|
||||
typescript: '^6.0.3',
|
||||
}
|
||||
|
||||
const BASELINE_NPM_DEPENDENCY_NAMES: Readonly<Record<NpmDependencySection, readonly string[]>> = {
|
||||
dependencies: ['@deepseek-ai/dsh-scripts', 'cordis'],
|
||||
devDependencies: ['@types/node', 'tsdown', 'tsx', 'typescript'],
|
||||
}
|
||||
|
||||
/** Resolve one package to its generated-project section and version spec. */
|
||||
export function resolveNpmDependency(
|
||||
name: string,
|
||||
requestedSection: NpmDependencySection,
|
||||
releaseVersion: string,
|
||||
): ResolvedNpmDependency {
|
||||
if (name.startsWith('@deepseek-ai/dsh-')) {
|
||||
return { section: requestedSection, spec: `^${releaseVersion}` }
|
||||
}
|
||||
const spec = EXTERNAL_NPM_DEPENDENCY_SPECS[name]
|
||||
if (spec) return { section: requestedSection, spec }
|
||||
throw new Error(`no generated-project NPM dependency policy for ${name}`)
|
||||
}
|
||||
|
||||
/** Build the root package.json NPM dependency maps from the shared version policy. */
|
||||
export function baselineNpmDependencies(releaseVersion: string): BaselineNpmDependencies {
|
||||
return {
|
||||
dependencies: Object.fromEntries(BASELINE_NPM_DEPENDENCY_NAMES.dependencies.map((name) => {
|
||||
const dependency = resolveNpmDependency(name, 'dependencies', releaseVersion)
|
||||
return [name, dependency.spec]
|
||||
})),
|
||||
devDependencies: Object.fromEntries(BASELINE_NPM_DEPENDENCY_NAMES.devDependencies.map((name) => {
|
||||
const dependency = resolveNpmDependency(name, 'devDependencies', releaseVersion)
|
||||
return [name, dependency.spec]
|
||||
})),
|
||||
}
|
||||
}
|
||||
616
packages/scaffold/helper/src/project/project-edit-session.ts
Normal file
616
packages/scaffold/helper/src/project/project-edit-session.ts
Normal file
@@ -0,0 +1,616 @@
|
||||
/**
|
||||
* Isolated domain-command and commit boundary for SDK project changes.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/project/project-edit-session
|
||||
*/
|
||||
|
||||
import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import type {
|
||||
Feature,
|
||||
FeatureInstallation,
|
||||
FeatureProjectView,
|
||||
FeatureRequirement,
|
||||
} from '../features/feature.ts'
|
||||
import type { FeatureRegistry } from '../features/registry.ts'
|
||||
import type { ProjectResource } from '../features/resources.ts'
|
||||
import { CordisYamlFile, type CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import { EnvFile } from '../documents/env-file.ts'
|
||||
import { PackageJsonFile, type PackageManifest } from '../documents/package-json-file.ts'
|
||||
import { ProjectFile } from '../documents/project-file.ts'
|
||||
import { TsConfigFile } from '../documents/tsconfig-file.ts'
|
||||
import { featureId, type FeatureId, type ResourceKey } from '../ids.ts'
|
||||
import { LinkWorkspace } from '../package-managers/link-workspace.ts'
|
||||
import type { LocalPluginBlueprint } from '../plugins/local-plugin-blueprint.ts'
|
||||
import type { FeatureSelection, ProjectProfile } from './types.ts'
|
||||
import { resolveNpmDependency } from './npm-dependency-policy.ts'
|
||||
import type { ChangeSet, ProjectCommitResult } from './change-set.ts'
|
||||
import type { SdkProject } from './sdk-project.ts'
|
||||
|
||||
interface MutableFeatureState {
|
||||
selection?: FeatureSelection
|
||||
state: FeatureInstallation['state']
|
||||
}
|
||||
|
||||
function sameText(left: ProjectFile, right: ProjectFile | undefined): boolean {
|
||||
return right !== undefined && left.serialize() === right.serialize()
|
||||
}
|
||||
|
||||
function npmDependencyShape(manifest: Readonly<PackageManifest>): string {
|
||||
return JSON.stringify({
|
||||
/* v8 ignore next -- generated manifests always carry the managed dependency maps */
|
||||
dependencies: manifest.dependencies ?? {},
|
||||
/* v8 ignore next -- generated manifests always carry the managed dependency maps */
|
||||
devDependencies: manifest.devDependencies ?? {},
|
||||
})
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error {
|
||||
/* v8 ignore else -- node:fs promise APIs reject Error objects */
|
||||
if (error instanceof Error) return error
|
||||
/* v8 ignore next -- node:fs promise APIs reject Error objects */
|
||||
return new Error(String(error))
|
||||
}
|
||||
|
||||
function canUpdateResource(previous: ProjectResource, next: ProjectResource): boolean {
|
||||
if (previous.kind !== next.kind) return false
|
||||
switch (previous.kind) {
|
||||
case 'npm-dependency': return previous.name === (next as typeof previous).name
|
||||
case 'package-script': return previous.name === (next as typeof previous).name
|
||||
case 'cordis-config-entry': {
|
||||
const candidate = next as typeof previous
|
||||
return previous.entry.name === candidate.entry.name
|
||||
}
|
||||
case 'environment': return previous.name === (next as typeof previous).name
|
||||
case 'owned-file': return previous.document.relativePath === (next as typeof previous).document.relativePath
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutable working copy that applies feature and local-plugin domain commands. */
|
||||
export class ProjectEditSession implements FeatureProjectView {
|
||||
readonly profile: ProjectProfile
|
||||
private readonly source: SdkProject
|
||||
private readonly registry: FeatureRegistry
|
||||
private readonly documents: Map<string, ProjectFile>
|
||||
private readonly removed = new Map<string, ProjectFile>()
|
||||
private readonly states = new Map<FeatureId, MutableFeatureState>()
|
||||
private readonly added = new Set<FeatureId>()
|
||||
private readonly enabled = new Set<FeatureId>()
|
||||
private readonly disabled = new Set<FeatureId>()
|
||||
private readonly configured = new Set<FeatureId>()
|
||||
private readonly addedPlugins = new Set<string>()
|
||||
private readonly enabledPlugins = new Set<string>()
|
||||
private readonly disabledPlugins = new Set<string>()
|
||||
private committed = false
|
||||
|
||||
/** Clone one project snapshot into an isolated working copy. */
|
||||
constructor(source: SdkProject, registry: FeatureRegistry) {
|
||||
this.source = source
|
||||
this.registry = registry
|
||||
this.profile = source.profile
|
||||
this.documents = source.cloneDocuments()
|
||||
for (const feature of registry.all()) {
|
||||
/* v8 ignore next -- no current built-in feature is interface-specific */
|
||||
if (!feature.isApplicable(this.profile)) continue
|
||||
const installation = feature.inspect(this)
|
||||
this.states.set(feature.id, {
|
||||
state: installation.state,
|
||||
...installation.selection ? { selection: installation.selection } : {},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Root manifest value for feature inspection. */
|
||||
packageManifest(): Readonly<PackageManifest> {
|
||||
return this.manifest().value()
|
||||
}
|
||||
|
||||
/** Cordis config entries for feature and custom-plugin inspection. */
|
||||
cordisConfigEntries(): readonly CordisConfigEntry[] {
|
||||
return this.cordis().entries()
|
||||
}
|
||||
|
||||
/** Whether one managed document exists in the working copy. */
|
||||
/* jscpd:ignore-start -- FeatureProjectView deliberately has symmetric snapshot/edit implementations. */
|
||||
hasDocument(path: string): boolean {
|
||||
return this.documents.has(path)
|
||||
}
|
||||
|
||||
/** Read one unique working-copy environment variable. */
|
||||
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined {
|
||||
const document = this.documents.get(path)
|
||||
if (!document) return undefined
|
||||
if (!(document instanceof EnvFile)) throw new Error(`${path} is not an environment document`)
|
||||
return document.get(name)
|
||||
}
|
||||
/* jscpd:ignore-end */
|
||||
|
||||
/** Inspect every applicable builtin against the current working copy. */
|
||||
inspections(): readonly FeatureInstallation[] {
|
||||
return this.registry.inspect(this)
|
||||
}
|
||||
|
||||
/** Install a builtin and recursively satisfy its declared requirements. */
|
||||
installFeature(feature: Feature, selection: FeatureSelection): void {
|
||||
this.assertOpen()
|
||||
this.installFeatureRecursive(feature, selection, new Set())
|
||||
}
|
||||
|
||||
/** Replace one installed builtin's feature-option and captured-input selection. */
|
||||
configureFeature(feature: Feature, selection: FeatureSelection): void {
|
||||
this.assertOpen()
|
||||
const current = this.state(feature)
|
||||
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
|
||||
if (current.state === 'absent' || !current.selection) {
|
||||
this.installFeature(feature, selection)
|
||||
return
|
||||
}
|
||||
const normalized = feature.normalizeSelection(selection, this.profile)
|
||||
this.ensureRequirements(feature, normalized, new Set([feature.id]))
|
||||
this.replaceContribution(
|
||||
feature.contribution(current.selection, this.profile),
|
||||
feature.contribution(normalized, this.profile),
|
||||
)
|
||||
current.selection = normalized
|
||||
current.state = current.state === 'disabled' ? 'disabled' : 'enabled'
|
||||
if (current.state === 'disabled') this.setFeatureDisabled(feature, normalized, true)
|
||||
this.assertFeatureConsistent(feature)
|
||||
this.configured.add(feature.id)
|
||||
}
|
||||
|
||||
/** Enable all entries owned by one installed feature. */
|
||||
enableFeature(feature: Feature): void {
|
||||
this.assertOpen()
|
||||
const current = this.state(feature)
|
||||
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
|
||||
if (current.state === 'absent' || !current.selection) {
|
||||
throw new Error(`feature ${feature.id} is not installed`)
|
||||
}
|
||||
this.setFeatureDisabled(feature, current.selection, false)
|
||||
current.state = 'enabled'
|
||||
this.assertFeatureConsistent(feature)
|
||||
this.disabled.delete(feature.id)
|
||||
this.enabled.add(feature.id)
|
||||
}
|
||||
|
||||
/** Disable an optional feature without removing its configuration. */
|
||||
disableFeature(feature: Feature): void {
|
||||
this.assertOpen()
|
||||
if (feature.required) throw new Error(`required feature ${feature.id} cannot be disabled`)
|
||||
const current = this.state(feature)
|
||||
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
|
||||
if (current.state === 'absent' || !current.selection) {
|
||||
throw new Error(`feature ${feature.id} is not installed`)
|
||||
}
|
||||
const dependent = this.registry.all().find((candidate) => {
|
||||
const state = this.states.get(candidate.id)
|
||||
return state?.state === 'enabled' && state.selection
|
||||
&& candidate.requirements(state.selection).some(requirement => requirement.id === feature.id)
|
||||
})
|
||||
if (dependent) throw new Error(`feature ${feature.id} is required by ${dependent.id}`)
|
||||
this.setFeatureDisabled(feature, current.selection, true)
|
||||
current.state = 'disabled'
|
||||
this.assertFeatureConsistent(feature)
|
||||
this.enabled.delete(feature.id)
|
||||
this.disabled.add(feature.id)
|
||||
}
|
||||
|
||||
/** Add a generated local plugin and all four of its project registrations. */
|
||||
addPlugin(blueprint: LocalPluginBlueprint): void {
|
||||
this.assertOpen()
|
||||
const manifest = this.manifest()
|
||||
const cordis = this.cordis()
|
||||
const tsconfig = this.documents.get('tsconfig.json')
|
||||
if (!(tsconfig instanceof TsConfigFile)) {
|
||||
throw new Error('adding a local plugin requires a valid tsconfig.json')
|
||||
}
|
||||
const packageName = blueprint.packageName(this.profile.name)
|
||||
if (manifest.npmDependency(packageName)) throw new Error(`root NPM dependency already exists: ${packageName}`)
|
||||
const entry = blueprint.cordisConfigEntry(this.profile.name)
|
||||
if (cordis.entry(entry.id)) throw new Error(`Cordis config entry already exists: ${entry.id}`)
|
||||
const documents = blueprint.documents(this.profile.name, this.profile.releaseVersion)
|
||||
for (const document of documents) {
|
||||
if (this.documents.has(document.relativePath)) {
|
||||
throw new Error(`local plugin file already exists: ${document.relativePath}`)
|
||||
}
|
||||
}
|
||||
for (const document of documents) this.documents.set(document.relativePath, document)
|
||||
manifest.setNpmDependency('dependencies', packageName, this.profile.packageManager.localPluginSpec())
|
||||
tsconfig.addReference(`./${blueprint.directory}`)
|
||||
cordis.addEntry(entry)
|
||||
this.addedPlugins.add(entry.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount a Cordis entry for an external dependency the package manager has already
|
||||
* added (github or npm), without generating files or re-adding the dependency.
|
||||
* @param id - stable Cordis config entry id.
|
||||
* @param packageName - the installed dependency's package name.
|
||||
*/
|
||||
addExternalPlugin(id: string, packageName: string): void {
|
||||
this.assertOpen()
|
||||
if (!this.manifest().npmDependency(packageName)) {
|
||||
throw new Error(`external plugin dependency is not installed: ${packageName}`)
|
||||
}
|
||||
const cordis = this.cordis()
|
||||
if (cordis.entry(id)) throw new Error(`Cordis config entry already exists: ${id}`)
|
||||
cordis.addEntry({ id, name: packageName })
|
||||
this.addedPlugins.add(id)
|
||||
}
|
||||
|
||||
/** Enable or disable one custom/manual Cordis config entry by stable id. */
|
||||
setCustomPluginDisabled(id: string, disabled: boolean): void {
|
||||
this.assertOpen()
|
||||
const entry = this.cordis().entry(id)
|
||||
if (!entry) throw new Error(`Cordis config entry does not exist: ${id}`)
|
||||
if (this.registry.ownerOfPackage(entry.name, this.profile)) {
|
||||
throw new Error(`Cordis config entry ${id} belongs to a builtin feature`)
|
||||
}
|
||||
this.cordis().setDisabled(id, disabled)
|
||||
if (disabled) {
|
||||
this.enabledPlugins.delete(id)
|
||||
this.disabledPlugins.add(id)
|
||||
} else {
|
||||
this.disabledPlugins.delete(id)
|
||||
this.enabledPlugins.add(id)
|
||||
}
|
||||
}
|
||||
|
||||
/** Summarize all pending domain and file changes. */
|
||||
changes(): ChangeSet {
|
||||
const changedFiles = new Set<string>()
|
||||
for (const [path, document] of this.documents) {
|
||||
if (this.source.origin === 'create' || !sameText(document, this.source.document(path))) changedFiles.add(path)
|
||||
}
|
||||
for (const path of this.removed.keys()) changedFiles.add(path)
|
||||
return {
|
||||
addedFeatures: [...this.added].sort(),
|
||||
enabledFeatures: [...this.enabled].sort(),
|
||||
disabledFeatures: [...this.disabled].sort(),
|
||||
configuredFeatures: [...this.configured].sort(),
|
||||
addedPlugins: [...this.addedPlugins].sort(),
|
||||
enabledPlugins: [...this.enabledPlugins].sort(),
|
||||
disabledPlugins: [...this.disabledPlugins].sort(),
|
||||
changedFiles: [...changedFiles].sort(),
|
||||
npmDependenciesChanged: npmDependencyShape(this.manifest().value())
|
||||
!== npmDependencyShape(this.source.packageManifest()),
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate, detect external edits, write affected files, and return a fresh snapshot. */
|
||||
async commit(): Promise<ProjectCommitResult<SdkProject>> {
|
||||
this.assertOpen()
|
||||
if (this.profile.linkWorkspaceRoot) {
|
||||
const workspace = await LinkWorkspace.open(this.profile.linkWorkspaceRoot)
|
||||
workspace.apply(
|
||||
this.source.root,
|
||||
this.manifest(),
|
||||
this.profile.packageManager,
|
||||
[...this.documents.values()],
|
||||
)
|
||||
}
|
||||
this.validateFinalState()
|
||||
const changes = this.changes()
|
||||
await this.assertUnchanged(changes.changedFiles)
|
||||
await mkdir(this.source.root, { recursive: true })
|
||||
for (const path of changes.changedFiles) {
|
||||
const document = this.documents.get(path)
|
||||
const absolute = resolve(this.source.root, path)
|
||||
if (!document) {
|
||||
await unlink(absolute)
|
||||
continue
|
||||
}
|
||||
await mkdir(dirname(absolute), { recursive: true })
|
||||
await writeFile(absolute, document.serialize(), {
|
||||
encoding: 'utf8',
|
||||
...document.createMode === undefined ? {} : { mode: document.createMode },
|
||||
})
|
||||
}
|
||||
this.committed = true
|
||||
return { project: await this.source.reopen(), changes }
|
||||
}
|
||||
|
||||
private installFeatureRecursive(
|
||||
feature: Feature,
|
||||
selection: FeatureSelection,
|
||||
stack: Set<FeatureId>,
|
||||
): void {
|
||||
if (stack.has(feature.id)) throw new Error(`cyclic feature requirement involving ${feature.id}`)
|
||||
const current = this.state(feature)
|
||||
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
|
||||
if (current.state !== 'absent' && current.selection) {
|
||||
this.configureFeature(feature, selection)
|
||||
if (current.state === 'disabled') this.enableFeature(feature)
|
||||
return
|
||||
}
|
||||
const normalized = feature.normalizeSelection(selection, this.profile)
|
||||
const nextStack = new Set(stack).add(feature.id)
|
||||
this.ensureRequirements(feature, normalized, nextStack)
|
||||
this.replaceContribution(undefined, feature.contribution(normalized, this.profile))
|
||||
current.selection = normalized
|
||||
current.state = 'enabled'
|
||||
this.assertFeatureConsistent(feature)
|
||||
this.added.add(feature.id)
|
||||
}
|
||||
|
||||
private ensureRequirements(feature: Feature, selection: FeatureSelection, stack: Set<FeatureId>): void {
|
||||
for (const requirement of feature.requirements(selection)) {
|
||||
const required = this.registry.get(requirement.id)
|
||||
const state = this.state(required)
|
||||
if (state.state === 'inconsistent') throw new Error(`required feature ${required.id} is inconsistent`)
|
||||
if (state.state === 'absent' || !state.selection) {
|
||||
this.installFeatureRecursive(required, {
|
||||
id: required.id,
|
||||
options: requirement.options ?? required.defaultOptions(this.profile),
|
||||
}, stack)
|
||||
} else {
|
||||
const next = this.selectionWithRequiredOptions(required, state.selection, requirement)
|
||||
if (next !== state.selection) this.configureFeature(required, next)
|
||||
if (state.state === 'disabled') this.enableFeature(required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private selectionWithRequiredOptions(
|
||||
feature: Feature,
|
||||
selection: FeatureSelection,
|
||||
requirement: FeatureRequirement,
|
||||
): FeatureSelection {
|
||||
if (!requirement.options || requirement.options.every(option => selection.options.includes(option))) {
|
||||
return selection
|
||||
}
|
||||
if (feature.mode !== 'multiple') {
|
||||
throw new Error(`${feature.id} does not satisfy the option requirement from another feature`)
|
||||
}
|
||||
return { ...selection, options: [...new Set([...selection.options, ...requirement.options])] }
|
||||
}
|
||||
|
||||
private replaceContribution(
|
||||
previous: ReturnType<Feature['contribution']> | undefined,
|
||||
next: ReturnType<Feature['contribution']>,
|
||||
): void {
|
||||
const previousByKey = previous?.byKey() ?? new Map<ResourceKey, ProjectResource>()
|
||||
const nextByKey = next.byKey()
|
||||
for (const [key, resource] of previousByKey) {
|
||||
const replacement = nextByKey.get(key)
|
||||
if (!replacement || !canUpdateResource(resource, replacement)) this.removeResource(resource)
|
||||
}
|
||||
for (const [key, resource] of nextByKey) {
|
||||
const previousResource = previousByKey.get(key)
|
||||
this.applyResource(
|
||||
resource,
|
||||
previousResource && canUpdateResource(previousResource, resource) ? previousResource : undefined,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private applyResource(resource: ProjectResource, previous: ProjectResource | undefined): void {
|
||||
switch (resource.kind) {
|
||||
case 'npm-dependency': {
|
||||
const dependency = resolveNpmDependency(resource.name, resource.section, this.profile.releaseVersion)
|
||||
this.manifest().setNpmDependency(dependency.section, resource.name, dependency.spec)
|
||||
return
|
||||
}
|
||||
case 'package-script': {
|
||||
const manifest = this.manifest()
|
||||
const current = manifest.script(resource.name)
|
||||
if (!previous || previous.kind !== 'package-script') {
|
||||
if (current !== undefined) throw new Error(`feature-owned package script already exists: ${resource.name}`)
|
||||
manifest.setScript(resource.name, resource.command)
|
||||
return
|
||||
}
|
||||
if (current === resource.command) return
|
||||
if (current !== previous.command) {
|
||||
throw new Error(`feature-owned package script was modified: ${resource.name}`)
|
||||
}
|
||||
manifest.setScript(resource.name, resource.command)
|
||||
return
|
||||
}
|
||||
case 'cordis-config-entry': {
|
||||
const current = this.cordis().entry(resource.entry.id)
|
||||
if (!current) this.cordis().addEntry(resource.entry, resource.commentedExample)
|
||||
else {
|
||||
if (current.name !== resource.entry.name) {
|
||||
throw new Error(`Cordis config entry ${resource.entry.id} is owned by ${current.name}, not ${resource.entry.name}`)
|
||||
}
|
||||
this.cordis().updateOwnedConfig(
|
||||
resource.entry.id,
|
||||
resource.ownedConfigKeys,
|
||||
resource.entry.config ?? {},
|
||||
)
|
||||
this.cordis().setDisabled(resource.entry.id, false)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'environment': {
|
||||
this.environment('.env.example').set(resource.name, resource.exampleValue)
|
||||
/* v8 ignore else -- an omitted secret intentionally materializes only its example placeholder */
|
||||
if (resource.value !== undefined) {
|
||||
const environment = this.environment('.env')
|
||||
environment.append(
|
||||
resource.name,
|
||||
resource.value,
|
||||
resource.value === '' ? resource.comment : undefined,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'owned-file': {
|
||||
const existing = this.documents.get(resource.document.relativePath)
|
||||
if (!existing) {
|
||||
this.documents.set(resource.document.relativePath, resource.document.clone())
|
||||
this.removed.delete(resource.document.relativePath)
|
||||
return
|
||||
}
|
||||
if (!previous || previous.kind !== 'owned-file') {
|
||||
throw new Error(`feature-owned file already exists: ${resource.document.relativePath}`)
|
||||
}
|
||||
if (previous.document.serialize() === resource.document.serialize()) return
|
||||
if (existing.serialize() !== previous.document.serialize()) {
|
||||
throw new Error(`feature-owned file was modified: ${resource.document.relativePath}`)
|
||||
}
|
||||
this.documents.set(resource.document.relativePath, resource.document.clone())
|
||||
this.removed.delete(resource.document.relativePath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private removeResource(resource: ProjectResource): void {
|
||||
switch (resource.kind) {
|
||||
case 'npm-dependency':
|
||||
this.manifest().removeNpmDependency(resource.section, resource.name)
|
||||
return
|
||||
case 'package-script': {
|
||||
const manifest = this.manifest()
|
||||
const current = manifest.script(resource.name)
|
||||
if (current === undefined) throw new Error(`owned package script is missing: ${resource.name}`)
|
||||
if (resource.removeOnlyWhenUnchanged && current !== resource.command) {
|
||||
throw new Error(`feature-owned package script was modified: ${resource.name}`)
|
||||
}
|
||||
manifest.removeScript(resource.name)
|
||||
return
|
||||
}
|
||||
case 'cordis-config-entry': {
|
||||
const entry = this.cordis().entry(resource.entry.id)
|
||||
if (!entry || entry.name !== resource.entry.name) {
|
||||
throw new Error(`cannot confirm old Cordis resource ${resource.entry.id}`)
|
||||
}
|
||||
this.cordis().removeEntry(resource.entry.id)
|
||||
return
|
||||
}
|
||||
case 'environment':
|
||||
this.environment('.env.example').remove(resource.name)
|
||||
return
|
||||
case 'owned-file': {
|
||||
const document = this.documents.get(resource.document.relativePath)
|
||||
if (!document) throw new Error(`owned file is missing: ${resource.document.relativePath}`)
|
||||
if (resource.removeOnlyWhenUnchanged && document.serialize() !== resource.document.serialize()) {
|
||||
throw new Error(`owned file was modified: ${resource.document.relativePath}`)
|
||||
}
|
||||
this.documents.delete(resource.document.relativePath)
|
||||
if (this.source.document(resource.document.relativePath)) {
|
||||
this.removed.set(resource.document.relativePath, document)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private setFeatureDisabled(feature: Feature, selection: FeatureSelection, disabled: boolean): void {
|
||||
for (const resource of feature.contribution(selection, this.profile).resources) {
|
||||
if (resource.kind === 'cordis-config-entry') this.cordis().setDisabled(resource.entry.id, disabled)
|
||||
}
|
||||
}
|
||||
|
||||
private validateFinalState(): void {
|
||||
for (const document of this.documents.values()) document.validate()
|
||||
const profile = this.finalProfile()
|
||||
const view = this.projectView(profile)
|
||||
for (const feature of this.registry.all()) {
|
||||
const state = this.states.get(feature.id)
|
||||
/* v8 ignore next 5 -- no current built-in feature is interface-specific */
|
||||
if (!feature.isApplicable(profile)) {
|
||||
if (state?.state === 'enabled') {
|
||||
throw new Error(`feature ${feature.id} is not available for ${profile.runInterface}`)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const installation = feature.inspect(view)
|
||||
/* v8 ignore next 3 -- public domain commands assert feature consistency before final validation */
|
||||
if (installation.state === 'inconsistent') {
|
||||
throw new Error(`feature ${feature.id} is inconsistent: ${installation.diagnostics.join('; ')}`)
|
||||
}
|
||||
/* v8 ignore next 3 -- required features are installed by creation and cannot be disabled by public commands */
|
||||
if (feature.required && installation.state !== 'enabled') {
|
||||
throw new Error(`required feature ${feature.id} must be installed and enabled`)
|
||||
}
|
||||
if (installation.state !== 'enabled' || !installation.selection) continue
|
||||
for (const requirement of feature.requirements(installation.selection)) {
|
||||
const required = this.registry.get(requirement.id).inspect(view)
|
||||
/* v8 ignore next 3 -- ensureRequirements establishes enabled requirements before contributions change */
|
||||
if (required.state !== 'enabled') {
|
||||
throw new Error(`feature ${feature.id} requires enabled ${requirement.id}`)
|
||||
}
|
||||
for (const option of requirement.options ?? []) {
|
||||
/* v8 ignore next 3 -- selectionWithRequiredOptions establishes required options before commit */
|
||||
if (!required.options.includes(option)) {
|
||||
throw new Error(`feature ${feature.id} requires ${requirement.id} option ${option}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private assertFeatureConsistent(feature: Feature): void {
|
||||
const installation = feature.inspect(this)
|
||||
/* v8 ignore next 3 -- resource application either succeeds completely or throws at the owning operation */
|
||||
if (installation.state === 'inconsistent') {
|
||||
throw new Error(`feature ${feature.id} is inconsistent: ${installation.diagnostics.join('; ')}`)
|
||||
}
|
||||
}
|
||||
|
||||
private finalProfile(): ProjectProfile {
|
||||
const runInterface = this.states.get(featureId('app'))?.selection?.options[0]
|
||||
if (runInterface !== 'acp' && runInterface !== 'embed') return this.profile
|
||||
return { ...this.profile, runInterface }
|
||||
}
|
||||
|
||||
private projectView(profile: ProjectProfile): FeatureProjectView {
|
||||
return {
|
||||
profile,
|
||||
cordisConfigEntries: () => this.cordisConfigEntries(),
|
||||
packageManifest: () => this.packageManifest(),
|
||||
hasDocument: path => this.hasDocument(path),
|
||||
readEnvironment: (path, name) => this.readEnvironment(path, name),
|
||||
}
|
||||
}
|
||||
|
||||
private async assertUnchanged(paths: readonly string[]): Promise<void> {
|
||||
for (const path of paths) {
|
||||
const source = this.source.document(path)
|
||||
const absolute = resolve(this.source.root, path)
|
||||
try {
|
||||
const current = await readFile(absolute, 'utf8')
|
||||
if (source?.originalText === undefined || current !== source.originalText) {
|
||||
throw new Error(`project file changed outside this edit session: ${path}`)
|
||||
}
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code
|
||||
if (code === 'ENOENT' && source?.originalText === undefined) continue
|
||||
if (error instanceof Error && error.message.startsWith('project file changed outside')) throw error
|
||||
throw new Error(`cannot verify project file ${path}: ${asError(error).message}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private state(feature: Feature): MutableFeatureState {
|
||||
const state = this.states.get(feature.id)
|
||||
if (!state) throw new Error(`feature ${feature.id} is not applicable to this project`)
|
||||
return state
|
||||
}
|
||||
|
||||
private manifest(): PackageJsonFile {
|
||||
const document = this.documents.get('package.json')
|
||||
if (!(document instanceof PackageJsonFile)) throw new Error('project package.json is missing')
|
||||
return document
|
||||
}
|
||||
|
||||
private cordis(): CordisYamlFile {
|
||||
const document = this.documents.get('cordis.yml')
|
||||
if (!(document instanceof CordisYamlFile)) throw new Error('project cordis.yml is missing')
|
||||
return document
|
||||
}
|
||||
|
||||
private environment(path: '.env' | '.env.example'): EnvFile {
|
||||
const existing = this.documents.get(path)
|
||||
if (existing instanceof EnvFile) return existing
|
||||
if (existing) throw new Error(`${path} is not an environment document`)
|
||||
const document = EnvFile.create(path)
|
||||
this.documents.set(path, document)
|
||||
return document
|
||||
}
|
||||
|
||||
private assertOpen(): void {
|
||||
if (this.committed) throw new Error('project edit session has already committed')
|
||||
}
|
||||
}
|
||||
309
packages/scaffold/helper/src/project/sdk-project.ts
Normal file
309
packages/scaffold/helper/src/project/sdk-project.ts
Normal file
@@ -0,0 +1,309 @@
|
||||
/**
|
||||
* Read-only aggregate for one generated or existing SDK project.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/project/sdk-project
|
||||
*/
|
||||
|
||||
import { access, readFile } from 'node:fs/promises'
|
||||
import { basename, resolve } from 'node:path'
|
||||
import { CordisYamlFile, type CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
|
||||
import { EnvFile } from '../documents/env-file.ts'
|
||||
import { PackageJsonFile, type PackageManifest } from '../documents/package-json-file.ts'
|
||||
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
|
||||
import { ProjectFile, TextProjectFile } from '../documents/project-file.ts'
|
||||
import { TsConfigFile } from '../documents/tsconfig-file.ts'
|
||||
import {
|
||||
createPackageManager,
|
||||
type PackageManager,
|
||||
type PackageManagerName,
|
||||
} from '../package-managers/package-manager.ts'
|
||||
import {
|
||||
createBaselineProjectArtifacts,
|
||||
createPackageJsonDoc,
|
||||
createProjectTemplateContext,
|
||||
} from '../templates/project-template.ts'
|
||||
import type { ProjectCreationRequest, ProjectProfile, RunInterface } from './types.ts'
|
||||
import type { FeatureRegistry } from '../features/registry.ts'
|
||||
import { ProjectEditSession } from './project-edit-session.ts'
|
||||
|
||||
/** Whether a project snapshot describes uncommitted creation or files on disk. */
|
||||
export type ProjectOrigin = 'create' | 'disk'
|
||||
|
||||
const OPTIONAL_DOCUMENTS = [
|
||||
'.env',
|
||||
'.env.example',
|
||||
'tsconfig.json',
|
||||
'pnpm-workspace.yaml',
|
||||
'hooks.json',
|
||||
'codex-hooks.json',
|
||||
'README.md',
|
||||
'index.ts',
|
||||
] as const
|
||||
|
||||
function runInterface(entries: readonly CordisConfigEntry[]): RunInterface {
|
||||
if (entries.some(entry => entry.name === '@deepseek-ai/dsh-tui'
|
||||
|| entry.name.startsWith('@deepseek-ai/dsh-tui/'))) {
|
||||
throw new Error('unsupported run interface: @deepseek-ai/dsh-tui has been removed')
|
||||
}
|
||||
if (entries.some(entry => entry.name === '@deepseek-ai/dsh-acp')) return 'acp'
|
||||
return 'embed'
|
||||
}
|
||||
|
||||
function runtimeModel(entries: readonly CordisConfigEntry[]): string {
|
||||
const acp = entries.find(entry => entry.name === '@deepseek-ai/dsh-acp')
|
||||
if (typeof acp?.config?.model === 'string' && acp.config.model.length > 0) return acp.config.model
|
||||
const provider = entries.find(entry => entry.name === '@deepseek-ai/dsh-llm-deepseek'
|
||||
|| entry.name === '@deepseek-ai/dsh-llm-pi-ai')
|
||||
const models = provider?.config?.models
|
||||
if (Array.isArray(models) && typeof models[0] === 'string') return models[0]
|
||||
return 'deepseek-v4-flash'
|
||||
}
|
||||
|
||||
function releaseVersion(manifest: Readonly<PackageManifest>): string {
|
||||
const spec = manifest.dependencies?.['@deepseek-ai/dsh-scripts']
|
||||
const match = spec && /(?:^|[^0-9])(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(spec)
|
||||
return match?.[1] ?? '0.0.1'
|
||||
}
|
||||
|
||||
async function pathExists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path)
|
||||
return true
|
||||
} catch (error) {
|
||||
/* v8 ignore else -- the other arm requires a filesystem permission/IO fault from access */
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
|
||||
/* v8 ignore next -- paired with the ignored defensive access-error arm above */
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function detectPackageManager(root: string, manifest: Readonly<PackageManifest>): Promise<PackageManager> {
|
||||
let name: PackageManagerName = 'npm'
|
||||
let version = '10.0.0'
|
||||
const field = manifest.packageManager
|
||||
if (field) {
|
||||
const match = /^(npm|pnpm|yarn)@(.+)$/.exec(field)
|
||||
if (!match?.[1] || !match[2]) throw new Error(`invalid packageManager field: ${field}`)
|
||||
name = match[1] as PackageManagerName
|
||||
version = match[2]
|
||||
} else if (await pathExists(resolve(root, 'pnpm-lock.yaml'))) {
|
||||
name = 'pnpm'
|
||||
version = '10.0.0'
|
||||
} else if (await pathExists(resolve(root, 'yarn.lock'))) {
|
||||
name = 'yarn'
|
||||
version = '2.0.0'
|
||||
}
|
||||
return createPackageManager(name, version)
|
||||
}
|
||||
|
||||
function linkedRepositoryRoot(root: string, manifest: Readonly<PackageManifest>): string | undefined {
|
||||
const spec = manifest.dependencies?.['@deepseek-ai/dsh-scripts']
|
||||
const match = /^(?:file|link|portal):(.+)\/packages\/scaffold\/scripts\/?$/.exec(spec ?? '')
|
||||
return match?.[1] ? resolve(root, match[1]) : undefined
|
||||
}
|
||||
|
||||
function parseOptionalDocument(path: string, text: string): ProjectFile {
|
||||
try {
|
||||
switch (path) {
|
||||
case '.env': return EnvFile.parse('.env', text)
|
||||
case '.env.example': return EnvFile.parse('.env.example', text)
|
||||
case 'tsconfig.json': return TsConfigFile.parse(text)
|
||||
case 'pnpm-workspace.yaml': return PnpmWorkspaceFile.parse(text)
|
||||
default: return new TextProjectFile(path, text, text)
|
||||
}
|
||||
} catch {
|
||||
// Optional malformed resources do not invalidate the project aggregate;
|
||||
// an operation that needs their structure checks the concrete document type.
|
||||
return new TextProjectFile(path, text, text)
|
||||
}
|
||||
}
|
||||
|
||||
/** A project snapshot whose documents can only be changed through {@link ProjectEditSession}. */
|
||||
export class SdkProject {
|
||||
/** Absolute project directory. */
|
||||
readonly root: string
|
||||
/** Whether this snapshot is an uncommitted blueprint or disk state. */
|
||||
readonly origin: ProjectOrigin
|
||||
/** Project identity, runtime, interface, and package-manager context. */
|
||||
readonly profile: ProjectProfile
|
||||
private readonly documents: ReadonlyMap<string, ProjectFile>
|
||||
|
||||
private constructor(
|
||||
root: string,
|
||||
origin: ProjectOrigin,
|
||||
profile: ProjectProfile,
|
||||
documents: ReadonlyMap<string, ProjectFile>,
|
||||
) {
|
||||
this.root = resolve(root)
|
||||
this.origin = origin
|
||||
this.profile = profile
|
||||
this.documents = documents
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an in-memory project blueprint without touching the target directory.
|
||||
* @param root - target project directory.
|
||||
* @param request - complete creation request.
|
||||
* @returns uncommitted project snapshot.
|
||||
*/
|
||||
static create(root: string, request: ProjectCreationRequest): SdkProject {
|
||||
const app = request.features.find(selection => selection.id === 'app')
|
||||
const selectedInterface = app?.options[0]
|
||||
if (selectedInterface !== 'acp' && selectedInterface !== 'embed') {
|
||||
throw new Error('project creation requires one app feature option')
|
||||
}
|
||||
const profile: ProjectProfile = {
|
||||
name: request.name,
|
||||
description: request.description,
|
||||
runtime: request.runtime,
|
||||
runInterface: selectedInterface,
|
||||
packageManager: request.packageManager,
|
||||
releaseVersion: request.releaseVersion,
|
||||
...request.linkWorkspaceRoot ? { linkWorkspaceRoot: resolve(request.linkWorkspaceRoot) } : {},
|
||||
}
|
||||
const templates = createProjectTemplateContext(profile)
|
||||
const manifest = createPackageJsonDoc(templates)
|
||||
const documents = new Map<string, ProjectFile>()
|
||||
documents.set(manifest.relativePath, manifest)
|
||||
documents.set('cordis.yml', CordisYamlFile.create())
|
||||
documents.set('.env.example', EnvFile.create('.env.example'))
|
||||
documents.set('tsconfig.json', TsConfigFile.create())
|
||||
for (const document of request.packageManager.configureWorkspace(manifest)) {
|
||||
documents.set(document.relativePath, document)
|
||||
}
|
||||
for (const document of createBaselineProjectArtifacts(templates)) {
|
||||
documents.set(document.relativePath, document)
|
||||
}
|
||||
return new SdkProject(root, 'create', profile, documents)
|
||||
}
|
||||
|
||||
/**
|
||||
* Load an existing project from required and SDK-managed optional files.
|
||||
* @param root - existing project directory.
|
||||
* @returns disk-backed project snapshot.
|
||||
* @throws When the config references the removed `@deepseek-ai/dsh-tui` root or a subpath.
|
||||
*/
|
||||
static async open(root: string): Promise<SdkProject> {
|
||||
const absolute = resolve(root)
|
||||
const [manifestText, cordisText] = await Promise.all([
|
||||
readFile(resolve(absolute, 'package.json'), 'utf8'),
|
||||
readFile(resolve(absolute, 'cordis.yml'), 'utf8'),
|
||||
])
|
||||
const manifest = PackageJsonFile.parse(manifestText)
|
||||
const cordis = CordisYamlFile.parse(cordisText)
|
||||
const value = manifest.value()
|
||||
const manager = await detectPackageManager(absolute, value)
|
||||
const entries = cordis.entries()
|
||||
const linkWorkspaceRoot = linkedRepositoryRoot(absolute, value)
|
||||
const profile: ProjectProfile = {
|
||||
name: value.name ?? basename(absolute),
|
||||
description: typeof value.description === 'string' ? value.description : '',
|
||||
runtime: { model: runtimeModel(entries) },
|
||||
runInterface: runInterface(entries),
|
||||
packageManager: manager,
|
||||
releaseVersion: releaseVersion(value),
|
||||
...linkWorkspaceRoot ? { linkWorkspaceRoot } : {},
|
||||
}
|
||||
const documents = new Map<string, ProjectFile>([
|
||||
['package.json', manifest],
|
||||
['cordis.yml', cordis],
|
||||
])
|
||||
await Promise.all(OPTIONAL_DOCUMENTS.map(async (path) => {
|
||||
try {
|
||||
const text = await readFile(resolve(absolute, path), 'utf8')
|
||||
documents.set(path, parseOptionalDocument(path, text))
|
||||
} catch (error) {
|
||||
/* v8 ignore next -- optional-file reads fail normally only with ENOENT; other IO faults surface */
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
}
|
||||
}))
|
||||
return new SdkProject(absolute, 'disk', profile, documents)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the root package manifest defensively.
|
||||
* @returns cloned manifest value.
|
||||
*/
|
||||
packageManifest(): Readonly<PackageManifest> {
|
||||
return this.packageJson.value()
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Cordis config entries defensively in file order.
|
||||
* @returns cloned Cordis config entries.
|
||||
*/
|
||||
cordisConfigEntries(): readonly CordisConfigEntry[] {
|
||||
return this.cordis.entries()
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this snapshot contains one managed document.
|
||||
* @param path - project-relative document path.
|
||||
* @returns whether the document is loaded.
|
||||
*/
|
||||
hasDocument(path: string): boolean {
|
||||
return this.documents.has(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one environment variable from a loaded dotenv document.
|
||||
* @param path - environment file to read.
|
||||
* @param name - variable name.
|
||||
* @returns variable value when present.
|
||||
*/
|
||||
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined {
|
||||
const document = this.documents.get(path)
|
||||
if (!document) return undefined
|
||||
if (!(document instanceof EnvFile)) throw new Error(`${path} is not an environment document`)
|
||||
return document.get(name)
|
||||
}
|
||||
|
||||
/** Read the root package document. */
|
||||
get packageJson(): PackageJsonFile {
|
||||
const document = this.documents.get('package.json')
|
||||
if (!(document instanceof PackageJsonFile)) throw new Error('project package.json is missing or invalid')
|
||||
return document
|
||||
}
|
||||
|
||||
/** Read the root Cordis document. */
|
||||
get cordis(): CordisYamlFile {
|
||||
const document = this.documents.get('cordis.yml')
|
||||
if (!(document instanceof CordisYamlFile)) throw new Error('project cordis.yml is missing or invalid')
|
||||
return document
|
||||
}
|
||||
|
||||
/**
|
||||
* Return one managed document without exposing the aggregate map.
|
||||
* @param path - project-relative document path.
|
||||
* @returns loaded document when present.
|
||||
*/
|
||||
document(path: string): ProjectFile | undefined {
|
||||
return this.documents.get(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the only mutable boundary for this snapshot.
|
||||
* @param registry - feature catalog governing edits.
|
||||
* @returns isolated edit session.
|
||||
*/
|
||||
edit(registry: FeatureRegistry): ProjectEditSession {
|
||||
return new ProjectEditSession(this, registry)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone every managed document for an isolated edit session.
|
||||
* @returns project-relative document map.
|
||||
*/
|
||||
cloneDocuments(): Map<string, ProjectFile> {
|
||||
return new Map([...this.documents].map(([path, document]) => [path, document.clone()]))
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload this aggregate from committed disk state.
|
||||
* @returns fresh disk-backed snapshot.
|
||||
*/
|
||||
reopen(): Promise<SdkProject> {
|
||||
return SdkProject.open(this.root)
|
||||
}
|
||||
|
||||
}
|
||||
48
packages/scaffold/helper/src/project/types.ts
Normal file
48
packages/scaffold/helper/src/project/types.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared creation and project-profile values for SDK project editing.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/project/types
|
||||
*/
|
||||
|
||||
import type { PackageManager } from '../package-managers/package-manager.ts'
|
||||
import type { LocalPluginBlueprint } from '../plugins/local-plugin-blueprint.ts'
|
||||
import type { FeatureId } from '../ids.ts'
|
||||
|
||||
/** Runtime front door selected for a generated project. */
|
||||
export type RunInterface = 'acp' | 'embed'
|
||||
|
||||
/** Values shared by the required provider and app features. */
|
||||
interface ProjectRuntimeOptions {
|
||||
model: string
|
||||
}
|
||||
|
||||
/** Selected options and captured secrets for one feature. */
|
||||
export interface FeatureSelection {
|
||||
id: FeatureId
|
||||
options: readonly string[]
|
||||
values?: Readonly<Record<string, unknown>>
|
||||
secrets?: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/** Stable context available to project and feature objects. */
|
||||
export interface ProjectProfile {
|
||||
name: string
|
||||
description: string
|
||||
runtime: ProjectRuntimeOptions
|
||||
runInterface: RunInterface
|
||||
packageManager: PackageManager
|
||||
releaseVersion: string
|
||||
linkWorkspaceRoot?: string
|
||||
}
|
||||
|
||||
/** Fully collected create request; it contains intent, never rendered file text. */
|
||||
export interface ProjectCreationRequest {
|
||||
name: string
|
||||
description: string
|
||||
runtime: ProjectRuntimeOptions
|
||||
packageManager: PackageManager
|
||||
releaseVersion: string
|
||||
linkWorkspaceRoot?: string
|
||||
features: readonly FeatureSelection[]
|
||||
localPlugins: readonly LocalPluginBlueprint[]
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Tree-shaped Clack picker for root checkboxes with finite child options.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/questions/clack-nested-multiselect
|
||||
*/
|
||||
|
||||
import { styleText } from 'node:util'
|
||||
import type { Readable, Writable } from 'node:stream'
|
||||
import { Prompt, isCancel } from '@clack/core'
|
||||
import {
|
||||
S_BAR,
|
||||
S_BAR_END,
|
||||
S_CHECKBOX_ACTIVE,
|
||||
S_CHECKBOX_INACTIVE,
|
||||
S_CHECKBOX_SELECTED,
|
||||
S_RADIO_ACTIVE,
|
||||
S_RADIO_INACTIVE,
|
||||
symbol,
|
||||
symbolBar,
|
||||
} from '@clack/prompts'
|
||||
import type {
|
||||
NestedMultiSelectOption,
|
||||
NestedMultiSelectRequest,
|
||||
NestedMultiSelectValue,
|
||||
PromptOutcome,
|
||||
} from './prompt-port.ts'
|
||||
|
||||
interface NestedPromptOptions<TValue, TChoice> extends NestedMultiSelectRequest<TValue, TChoice> {
|
||||
input: Readable
|
||||
output: Writable
|
||||
}
|
||||
|
||||
class NestedPrompt<TValue, TChoice> extends Prompt<readonly NestedMultiSelectValue<TValue, TChoice>[]> {
|
||||
readonly options: readonly NestedMultiSelectOption<TValue, TChoice>[]
|
||||
private readonly selected = new Set<TValue>()
|
||||
private readonly selectedChoices = new Map<TValue, Set<TChoice>>()
|
||||
private readonly initialSelected: Set<TValue>
|
||||
private readonly initialChoices: Map<TValue, Set<TChoice>>
|
||||
private readonly showChanges: boolean
|
||||
private layer: 'root' | 'choices' = 'root'
|
||||
private rootCursor = 0
|
||||
private choiceCursor = 0
|
||||
|
||||
constructor(options: NestedPromptOptions<TValue, TChoice>) {
|
||||
super({
|
||||
input: options.input,
|
||||
output: options.output,
|
||||
validate: value => NestedPrompt.validate(options.options, value),
|
||||
render(this: Prompt<readonly NestedMultiSelectValue<TValue, TChoice>[]>) {
|
||||
return (this as NestedPrompt<TValue, TChoice>).renderFrame(options.message)
|
||||
},
|
||||
}, false)
|
||||
this.options = options.options
|
||||
this.showChanges = options.showChanges ?? false
|
||||
for (const option of options.options) {
|
||||
if (option.required || option.default) this.selected.add(option.value)
|
||||
this.selectedChoices.set(option.value, new Set(
|
||||
option.choices?.filter(choice => choice.default).map(choice => choice.value) ?? [],
|
||||
))
|
||||
}
|
||||
this.initialSelected = new Set(this.selected)
|
||||
this.initialChoices = new Map([...this.selectedChoices].map(([value, choices]) => [
|
||||
value, new Set(choices),
|
||||
]))
|
||||
this.updateValue()
|
||||
this.on('cursor', (action) => { this.handleAction(action) })
|
||||
}
|
||||
|
||||
private static validate<TValue, TChoice>(
|
||||
options: readonly NestedMultiSelectOption<TValue, TChoice>[],
|
||||
value: readonly NestedMultiSelectValue<TValue, TChoice>[] | undefined,
|
||||
): string | undefined {
|
||||
/* v8 ignore next -- NestedPrompt initializes its value before submission validation */
|
||||
const selected = new Map(value?.map(item => [item.value, item.choices]) ?? [])
|
||||
for (const option of options) {
|
||||
if (option.disabled) continue
|
||||
/* v8 ignore next -- required options initialize selected and cannot be toggled off */
|
||||
if (option.required && !selected.has(option.value)) return `${option.label} is required`
|
||||
if (!selected.has(option.value) || !option.choiceMode) continue
|
||||
const choices = selected.get(option.value)
|
||||
/* v8 ignore next -- selected.has above guarantees the map value exists */
|
||||
if (!choices) continue
|
||||
const count = choices.length
|
||||
if (option.choiceMode === 'exclusive' && count !== 1) return `Choose one ${option.label} option`
|
||||
if (option.choiceMode === 'multiple' && count === 0) return `Choose at least one ${option.label} option`
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
protected override _shouldSubmit(): boolean {
|
||||
if (this.layer === 'choices') {
|
||||
this.leaveChoices()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private handleAction(action: string | undefined): void {
|
||||
if (this.layer === 'root') this.handleRootAction(action)
|
||||
else this.handleChoiceAction(action)
|
||||
this.updateValue()
|
||||
}
|
||||
|
||||
private handleRootAction(action: string | undefined): void {
|
||||
if (action === 'up') this.rootCursor = this.move(this.rootCursor, -1, this.options.length)
|
||||
if (action === 'down') this.rootCursor = this.move(this.rootCursor, 1, this.options.length)
|
||||
const option = this.options[this.rootCursor]
|
||||
/* v8 ignore next -- Clack cannot emit a cursor action when the option list is empty */
|
||||
if (!option) return
|
||||
if (action === 'space' && !option.required && !option.disabled) {
|
||||
if (this.selected.has(option.value)) this.selected.delete(option.value)
|
||||
else this.selected.add(option.value)
|
||||
}
|
||||
if (action === 'right' && !option.disabled && option.choices && option.choices.length > 0) {
|
||||
this.selected.add(option.value)
|
||||
this.layer = 'choices'
|
||||
const selected = this.selectedChoices.get(option.value)
|
||||
const selectedIndex = option.choices.findIndex(choice => selected?.has(choice.value))
|
||||
this.choiceCursor = Math.max(selectedIndex, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private handleChoiceAction(action: string | undefined): void {
|
||||
const rootOption = this.options[this.rootCursor]
|
||||
/* v8 ignore next -- the choices layer is entered only from a concrete root option */
|
||||
if (!rootOption) return
|
||||
/* v8 ignore next -- the choices layer is entered only for a non-empty choices array */
|
||||
const choices = rootOption.choices ?? []
|
||||
if (action === 'left') {
|
||||
this.leaveChoices()
|
||||
return
|
||||
}
|
||||
if (action === 'up') this.choiceCursor = this.move(this.choiceCursor, -1, choices.length)
|
||||
if (action === 'down') this.choiceCursor = this.move(this.choiceCursor, 1, choices.length)
|
||||
if ((action === 'up' || action === 'down') && rootOption.choiceMode === 'exclusive') {
|
||||
const choice = choices[this.choiceCursor]
|
||||
/* v8 ignore else -- a cursor in the non-empty choices layer always addresses a choice */
|
||||
if (choice) this.selectedChoices.set(rootOption.value, new Set([choice.value]))
|
||||
}
|
||||
if (action !== 'space' && action !== 'right') return
|
||||
const choice = choices[this.choiceCursor]
|
||||
/* v8 ignore next -- the choices layer requires a non-empty choice list */
|
||||
if (!choice) return
|
||||
/* v8 ignore next -- every root option initializes its choice set in the constructor */
|
||||
const selected = this.selectedChoices.get(rootOption.value) ?? new Set<TChoice>()
|
||||
if (rootOption.choiceMode === 'exclusive') {
|
||||
selected.clear()
|
||||
selected.add(choice.value)
|
||||
} else if (selected.has(choice.value)) selected.delete(choice.value)
|
||||
else selected.add(choice.value)
|
||||
this.selectedChoices.set(rootOption.value, selected)
|
||||
}
|
||||
|
||||
private move(cursor: number, offset: number, length: number): number {
|
||||
/* v8 ignore next -- cursor movement is emitted only for a non-empty displayed list */
|
||||
if (length === 0) return 0
|
||||
return (cursor + offset + length) % length
|
||||
}
|
||||
|
||||
private updateValue(): void {
|
||||
this._setValue(this.options.filter(option => this.selected.has(option.value)).map(option => ({
|
||||
value: option.value,
|
||||
/* v8 ignore next -- every root option initializes its choice set in the constructor */
|
||||
choices: [...this.selectedChoices.get(option.value) ?? []],
|
||||
})))
|
||||
}
|
||||
|
||||
private renderFrame(message: string): string {
|
||||
const header = `${symbolBar(this.state)} ${message}`
|
||||
if (this.state === 'submit') {
|
||||
/* v8 ignore next -- NestedPrompt initializes its value before it can submit */
|
||||
const summary = (this.value ?? []).map(item => this.options.find(option => option.value === item.value)?.label)
|
||||
.filter(Boolean).join(', ') || 'none'
|
||||
return `${symbol(this.state)} ${message}\n${styleText('gray', S_BAR)} ${styleText('dim', summary)}`
|
||||
}
|
||||
if (this.state === 'cancel') return `${symbol(this.state)} ${message}`
|
||||
const body = this.layer === 'root' ? this.renderRoot() : this.renderChoices()
|
||||
const instructions = this.layer === 'root'
|
||||
? `${styleText('dim', '↑/↓')} navigate ${styleText('dim', 'Space')} select ${styleText('dim', '→')} configure ${styleText('dim', 'Enter')} confirm`
|
||||
: `${styleText('dim', '↑/↓')} navigate ${styleText('dim', 'Space/→')} select ${styleText('dim', '←/Enter')} back`
|
||||
const error = this.state === 'error' ? `\n${styleText('yellow', `${S_BAR_END} ${this.error}`)}` : ''
|
||||
return `${header}\n${styleText('cyan', S_BAR)} ${body.join(`\n${styleText('cyan', S_BAR)} `)}\n${styleText('cyan', S_BAR_END)} ${instructions}${error}`
|
||||
}
|
||||
|
||||
private renderRoot(): string[] {
|
||||
return this.options.map((option, index) => {
|
||||
const active = index === this.rootCursor
|
||||
const selected = this.selected.has(option.value)
|
||||
const focus = active ? styleText('cyan', '›') : ' '
|
||||
const checkbox = selected
|
||||
? styleText('green', S_CHECKBOX_SELECTED)
|
||||
: styleText('dim', active ? S_CHECKBOX_ACTIVE : S_CHECKBOX_INACTIVE)
|
||||
const choices = option.choices?.filter(choice => this.selectedChoices.get(option.value)?.has(choice.value))
|
||||
.map(choice => choice.label).join(', ')
|
||||
const suffix = option.choices?.length
|
||||
? ` ${styleText('dim', `* →${choices ? ` ${choices}` : ''}`)}`
|
||||
: ''
|
||||
const required = option.required ? ` ${styleText('yellow', '(required)')}` : ''
|
||||
const issue = this.choiceIssue(option)
|
||||
const warningText = option.warning ?? issue
|
||||
const warning = warningText ? ` ${styleText('yellow', `▲ ${warningText}`)}` : ''
|
||||
const changed = this.optionChanged(option)
|
||||
const change = changed ? ` ${styleText('yellow', '● changed')}` : ''
|
||||
const label = active
|
||||
? styleText('cyan', option.label)
|
||||
: changed
|
||||
? styleText('yellow', option.label)
|
||||
: selected ? styleText('green', option.label) : styleText('dim', option.label)
|
||||
const line = `${focus} ${checkbox} ${label}${required}${suffix}${warning}${change}`
|
||||
return option.disabled ? styleText('gray', line) : line
|
||||
})
|
||||
}
|
||||
|
||||
private renderChoices(): string[] {
|
||||
const rootOption = this.options[this.rootCursor]
|
||||
/* v8 ignore next -- renderChoices runs only after entering from a concrete root option */
|
||||
if (!rootOption) return []
|
||||
/* v8 ignore next -- every root option initializes its choice set in the constructor */
|
||||
const selected = this.selectedChoices.get(rootOption.value) ?? new Set<TChoice>()
|
||||
const issue = this.choiceIssue(rootOption)
|
||||
const changed = this.optionChanged(rootOption)
|
||||
const header = styleText('dim', `${rootOption.label} options`)
|
||||
+ (issue ? ` ${styleText('yellow', `▲ ${issue}`)}` : '')
|
||||
+ (changed ? ` ${styleText('yellow', '● changed')}` : '')
|
||||
const choices = rootOption.choices
|
||||
/* v8 ignore next -- the choices layer is entered only for a non-empty choices array */
|
||||
if (!choices) return [header]
|
||||
return [
|
||||
header,
|
||||
...choices.map((choice, index) => {
|
||||
const active = index === this.choiceCursor
|
||||
const checked = selected.has(choice.value)
|
||||
const choiceChanged = this.choiceChanged(rootOption.value, choice.value)
|
||||
const focus = active ? styleText('cyan', '›') : ' '
|
||||
const marker = rootOption.choiceMode === 'exclusive'
|
||||
? checked ? styleText('green', S_RADIO_ACTIVE) : styleText('dim', S_RADIO_INACTIVE)
|
||||
: checked ? styleText('green', S_CHECKBOX_SELECTED) : styleText('dim', S_CHECKBOX_INACTIVE)
|
||||
const label = active
|
||||
? styleText('cyan', choice.label)
|
||||
: choiceChanged
|
||||
? styleText('yellow', choice.label)
|
||||
: checked ? styleText('green', choice.label) : styleText('dim', choice.label)
|
||||
const change = choiceChanged ? ` ${styleText('yellow', '●')}` : ''
|
||||
return `${focus} ${marker} ${label}${change}`
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
private optionChanged(option: NestedMultiSelectOption<TValue, TChoice>): boolean {
|
||||
if (!this.showChanges) return false
|
||||
const selected = this.selected.has(option.value)
|
||||
const initiallySelected = this.initialSelected.has(option.value)
|
||||
if (selected !== initiallySelected) return true
|
||||
if (!selected) return false
|
||||
/* v8 ignore next -- every root option initializes both current and baseline option sets */
|
||||
const current = this.selectedChoices.get(option.value) ?? new Set<TChoice>()
|
||||
/* v8 ignore next -- every root option initializes both current and baseline option sets */
|
||||
const initial = this.initialChoices.get(option.value) ?? new Set<TChoice>()
|
||||
return current.size !== initial.size || [...current].some(value => !initial.has(value))
|
||||
}
|
||||
|
||||
private choiceChanged(value: TValue, choice: TChoice): boolean {
|
||||
if (!this.showChanges) return false
|
||||
return this.selectedChoices.get(value)?.has(choice) !== this.initialChoices.get(value)?.has(choice)
|
||||
}
|
||||
|
||||
private choiceIssue(option: NestedMultiSelectOption<TValue, TChoice>): string | undefined {
|
||||
if (option.disabled || !this.selected.has(option.value) || !option.choiceMode) return undefined
|
||||
/* v8 ignore next -- every root option initializes its choice set in the constructor */
|
||||
const count = this.selectedChoices.get(option.value)?.size ?? 0
|
||||
if (option.choiceMode === 'exclusive' && count !== 1) return 'choose one'
|
||||
if (option.choiceMode === 'multiple' && count === 0) return 'choose at least one'
|
||||
return undefined
|
||||
}
|
||||
|
||||
private leaveChoices(): boolean {
|
||||
const option = this.options[this.rootCursor]
|
||||
/* v8 ignore next -- leaveChoices runs only after entering from a concrete root option */
|
||||
if (!option) return false
|
||||
const issue = this.choiceIssue(option)
|
||||
if (issue) {
|
||||
this.error = `${option.label}: ${issue}`
|
||||
this.state = 'error'
|
||||
return false
|
||||
}
|
||||
this.error = ''
|
||||
this.layer = 'root'
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** Run the nested picker with Clack's standard cancellation symbol. */
|
||||
export async function clackNestedMultiselect<TValue, TChoice>(
|
||||
request: NestedPromptOptions<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
|
||||
const value = await new NestedPrompt(request).prompt()
|
||||
return isCancel(value)
|
||||
? { status: 'cancelled' }
|
||||
: {
|
||||
status: 'answered',
|
||||
/* v8 ignore next -- NestedPrompt initializes its value before it can submit */
|
||||
value: value ?? [],
|
||||
}
|
||||
}
|
||||
127
packages/scaffold/helper/src/questions/clack-prompt-port.ts
Normal file
127
packages/scaffold/helper/src/questions/clack-prompt-port.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Thin @clack/prompts adapter for the shared prompt port.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/questions/clack-prompt-port
|
||||
*/
|
||||
|
||||
import type { Readable, Writable } from 'node:stream'
|
||||
import { styleText } from 'node:util'
|
||||
import {
|
||||
confirm,
|
||||
isCancel,
|
||||
multiselect,
|
||||
password,
|
||||
select,
|
||||
text,
|
||||
S_WARN,
|
||||
} from '@clack/prompts'
|
||||
import type { Option } from '@clack/prompts'
|
||||
import type {
|
||||
ConfirmPromptRequest,
|
||||
MultiSelectPromptRequest,
|
||||
NestedMultiSelectRequest,
|
||||
NestedMultiSelectValue,
|
||||
PromptOutcome,
|
||||
PromptPort,
|
||||
SecretPromptRequest,
|
||||
SelectPromptRequest,
|
||||
TextPromptRequest,
|
||||
} from './prompt-port.ts'
|
||||
import { clackNestedMultiselect } from './clack-nested-multiselect.ts'
|
||||
|
||||
function outcome<T>(value: T | symbol): PromptOutcome<T> {
|
||||
return isCancel(value) ? { status: 'cancelled' } : { status: 'answered', value }
|
||||
}
|
||||
|
||||
function clackOptions<T>(values: readonly import('./prompt-port.ts').PromptOption<T>[]): Option<T>[] {
|
||||
return values.map(value => ({
|
||||
value: value.value,
|
||||
label: value.label,
|
||||
...value.hint === undefined ? {} : { hint: value.hint },
|
||||
...value.disabled === undefined ? {} : { disabled: value.disabled },
|
||||
})) as Option<T>[]
|
||||
}
|
||||
|
||||
/** Clack-backed prompt adapter with injectable streams for snapshots and tests. */
|
||||
export class ClackPromptPort implements PromptPort {
|
||||
private readonly input: Readable
|
||||
private readonly output: Writable
|
||||
|
||||
/** Bind all prompts to one input/output pair. */
|
||||
constructor(input: Readable = process.stdin, output: Writable = process.stdout) {
|
||||
this.input = input
|
||||
this.output = output
|
||||
}
|
||||
|
||||
/** Ask for visible text through clack. */
|
||||
async text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
|
||||
return outcome(await text({
|
||||
message: request.message,
|
||||
...request.placeholder === undefined ? {} : { placeholder: request.placeholder },
|
||||
...request.initialValue === undefined ? {} : { initialValue: request.initialValue },
|
||||
...request.defaultValue === undefined ? {} : { defaultValue: request.defaultValue },
|
||||
...request.validate === undefined
|
||||
? {}
|
||||
: {
|
||||
/* v8 ignore next -- value/default precedence is exercised through the adapter contract tests */
|
||||
validate: value => request.validate?.(value || request.defaultValue || ''),
|
||||
},
|
||||
input: this.input,
|
||||
output: this.output,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Ask for a masked secret through clack. */
|
||||
async secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> {
|
||||
return outcome(await password({
|
||||
message: request.message,
|
||||
...request.validate === undefined ? {} : {
|
||||
/* v8 ignore next -- @clack/password always calls validation with a string; fallback is defensive */
|
||||
validate: value => request.validate?.(value ?? ''),
|
||||
},
|
||||
input: this.input,
|
||||
output: this.output,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Ask for one option through clack. */
|
||||
async select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> {
|
||||
return outcome(await select({
|
||||
...request,
|
||||
options: clackOptions(request.options),
|
||||
input: this.input,
|
||||
output: this.output,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Ask for multiple options through clack. */
|
||||
async multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
|
||||
return outcome(await multiselect({
|
||||
message: request.message,
|
||||
options: clackOptions(request.options),
|
||||
...request.initialValues === undefined ? {} : { initialValues: [...request.initialValues] },
|
||||
...request.required === undefined ? {} : { required: request.required },
|
||||
input: this.input,
|
||||
output: this.output,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Ask for confirmation through clack. */
|
||||
async confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> {
|
||||
return outcome(await confirm({
|
||||
message: request.tone === 'warning'
|
||||
? styleText('yellow', `${S_WARN} ${request.message}`)
|
||||
: request.message,
|
||||
...request.initialValue === undefined ? {} : { initialValue: request.initialValue },
|
||||
input: this.input,
|
||||
output: this.output,
|
||||
}))
|
||||
}
|
||||
|
||||
/** Select root values and finite child options in one tree prompt. */
|
||||
nestedMultiselect<TValue, TChoice>(
|
||||
request: NestedMultiSelectRequest<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
|
||||
return clackNestedMultiselect({ ...request, input: this.input, output: this.output })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Non-interactive prompt port for headless create/config and skill-driven runs.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/questions/headless-prompt-port
|
||||
*/
|
||||
|
||||
import type {
|
||||
ConfirmPromptRequest,
|
||||
MultiSelectPromptRequest,
|
||||
NestedMultiSelectRequest,
|
||||
NestedMultiSelectValue,
|
||||
PromptOutcome,
|
||||
PromptPort,
|
||||
SecretPromptRequest,
|
||||
SelectPromptRequest,
|
||||
TextPromptRequest,
|
||||
} from './prompt-port.ts'
|
||||
|
||||
/**
|
||||
* Raised when a headless run reaches a decision that was neither prefilled nor
|
||||
* carries a usable default. The message names the unanswered prompt so an agent
|
||||
* or CI caller can see exactly which input the spec must supply.
|
||||
*/
|
||||
export class HeadlessPromptError extends Error {
|
||||
/** The unanswered prompt's user-facing message. */
|
||||
readonly prompt: string
|
||||
|
||||
/** Build an error naming the unanswered prompt. */
|
||||
constructor(prompt: string) {
|
||||
super(`headless run needs an answer for: ${prompt}`)
|
||||
this.name = 'HeadlessPromptError'
|
||||
this.prompt = prompt
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve an answered outcome. */
|
||||
function answered<T>(value: T): Promise<PromptOutcome<T>> {
|
||||
return Promise.resolve({ status: 'answered', value })
|
||||
}
|
||||
|
||||
/** Reject with a named unanswered-prompt error. */
|
||||
function unanswered<T>(message: string): Promise<PromptOutcome<T>> {
|
||||
return Promise.reject(new HeadlessPromptError(message))
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link PromptPort} that never blocks on a terminal.
|
||||
*
|
||||
* Answers are expected to arrive as prefilled values through the `Question` /
|
||||
* `FeatureConfigurator` layers, so in a fully specified run this port is never
|
||||
* reached. When it *is* reached, it takes the prompt's own declared default
|
||||
* (`defaultValue` / `initialValue`) if one exists; otherwise it fails loud with
|
||||
* {@link HeadlessPromptError}. Nested feature selection has no scalar default,
|
||||
* so it always fails loud — headless callers must supply the feature set through
|
||||
* the spec rather than the tree picker.
|
||||
*/
|
||||
export class HeadlessPromptPort implements PromptPort {
|
||||
/** Answer visible text from its default, or fail loud. */
|
||||
text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
|
||||
const fallback = request.initialValue ?? request.defaultValue
|
||||
if (fallback === undefined) return unanswered(request.message)
|
||||
const diagnostic = request.validate?.(fallback)
|
||||
if (diagnostic) return unanswered(`${request.message} (${diagnostic})`)
|
||||
return answered(fallback)
|
||||
}
|
||||
|
||||
/** A secret has no safe default: always fail loud. */
|
||||
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> {
|
||||
return unanswered(request.message)
|
||||
}
|
||||
|
||||
/** Answer a single choice from its initial value, or fail loud. */
|
||||
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> {
|
||||
if (request.initialValue === undefined) return unanswered(request.message)
|
||||
return answered(request.initialValue)
|
||||
}
|
||||
|
||||
/** Answer a multi-choice from its initial values, or fail loud when required. */
|
||||
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
|
||||
const initial = request.initialValues ?? []
|
||||
if (request.required && initial.length === 0) return unanswered(request.message)
|
||||
return answered(initial)
|
||||
}
|
||||
|
||||
/** Answer a confirmation from its initial value, or fail loud. */
|
||||
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> {
|
||||
if (request.initialValue === undefined) return unanswered(request.message)
|
||||
return answered(request.initialValue)
|
||||
}
|
||||
|
||||
/** Nested feature selection has no scalar default: always fail loud. */
|
||||
nestedMultiselect<TValue, TChoice>(
|
||||
request: NestedMultiSelectRequest<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
|
||||
return unanswered(request.message)
|
||||
}
|
||||
}
|
||||
124
packages/scaffold/helper/src/questions/prompt-port.ts
Normal file
124
packages/scaffold/helper/src/questions/prompt-port.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Terminal-prompt port shared by create and config workflows.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/questions/prompt-port
|
||||
*/
|
||||
|
||||
/** One selectable prompt option. */
|
||||
export interface PromptOption<T> {
|
||||
value: T
|
||||
label: string
|
||||
hint?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
/** Answer or explicit cancellation returned by every prompt. */
|
||||
export type PromptOutcome<T> =
|
||||
| { status: 'answered'; value: T }
|
||||
| { status: 'cancelled' }
|
||||
|
||||
/** Input for one text prompt. */
|
||||
export interface TextPromptRequest {
|
||||
message: string
|
||||
placeholder?: string
|
||||
initialValue?: string
|
||||
defaultValue?: string
|
||||
validate?: (value: string) => string | undefined
|
||||
}
|
||||
|
||||
/** Input for one masked secret prompt. */
|
||||
export interface SecretPromptRequest {
|
||||
message: string
|
||||
validate?: (value: string) => string | undefined
|
||||
}
|
||||
|
||||
/** Input for one single-choice prompt. */
|
||||
export interface SelectPromptRequest<T> {
|
||||
message: string
|
||||
options: readonly PromptOption<T>[]
|
||||
initialValue?: T
|
||||
}
|
||||
|
||||
/** Input for one additive multi-choice prompt. */
|
||||
export interface MultiSelectPromptRequest<T> {
|
||||
message: string
|
||||
options: readonly PromptOption<T>[]
|
||||
initialValues?: readonly T[]
|
||||
required?: boolean
|
||||
}
|
||||
|
||||
/** Input for one yes/no prompt. */
|
||||
export interface ConfirmPromptRequest {
|
||||
message: string
|
||||
initialValue?: boolean
|
||||
tone?: 'default' | 'warning'
|
||||
}
|
||||
|
||||
/** One nested choice under a multi-select option. */
|
||||
interface NestedSelectChoice<T> {
|
||||
value: T
|
||||
label: string
|
||||
default?: boolean
|
||||
}
|
||||
|
||||
/** One root option with optional child option configuration. */
|
||||
export interface NestedMultiSelectOption<TValue, TChoice> {
|
||||
value: TValue
|
||||
label: string
|
||||
required?: boolean
|
||||
default?: boolean
|
||||
disabled?: boolean
|
||||
warning?: string
|
||||
choiceMode?: 'exclusive' | 'multiple'
|
||||
choices?: readonly NestedSelectChoice<TChoice>[]
|
||||
}
|
||||
|
||||
/** Input for a tree-shaped feature-style picker. */
|
||||
export interface NestedMultiSelectRequest<TValue, TChoice> {
|
||||
message: string
|
||||
options: readonly NestedMultiSelectOption<TValue, TChoice>[]
|
||||
showChanges?: boolean
|
||||
}
|
||||
|
||||
/** One selected root option and its child options. */
|
||||
export interface NestedMultiSelectValue<TValue, TChoice> {
|
||||
value: TValue
|
||||
choices: readonly TChoice[]
|
||||
}
|
||||
|
||||
/** Interaction boundary consumed by typed question objects. */
|
||||
export interface PromptPort {
|
||||
/** Ask for one line of visible text. */
|
||||
text(request: TextPromptRequest): Promise<PromptOutcome<string>>
|
||||
/** Ask for one masked value. */
|
||||
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>>
|
||||
/** Ask for exactly one option. */
|
||||
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>>
|
||||
/** Ask for zero or more options. */
|
||||
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>>
|
||||
/** Ask for a boolean confirmation. */
|
||||
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>>
|
||||
/** Select root options and configure finite child options in one tree prompt. */
|
||||
nestedMultiselect<TValue, TChoice>(
|
||||
request: NestedMultiSelectRequest<TValue, TChoice>,
|
||||
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>>
|
||||
}
|
||||
|
||||
/** Error used when a workflow chooses to turn prompt cancellation into command cancellation. */
|
||||
export class PromptCancelledError extends Error {
|
||||
/** Create a stable cancellation error. */
|
||||
constructor(message = 'operation cancelled') {
|
||||
super(message)
|
||||
this.name = 'PromptCancelledError'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an answered value or throw the shared cancellation error.
|
||||
* @param outcome - prompt result to unwrap.
|
||||
* @returns answered value.
|
||||
*/
|
||||
export function requireAnswer<T>(outcome: PromptOutcome<T>): T {
|
||||
if (outcome.status === 'cancelled') throw new PromptCancelledError()
|
||||
return outcome.value
|
||||
}
|
||||
206
packages/scaffold/helper/src/questions/question.ts
Normal file
206
packages/scaffold/helper/src/questions/question.ts
Normal file
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* Typed question objects with prefill, validation, and prompt behavior together.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/questions/question
|
||||
*/
|
||||
|
||||
import type { PromptOption, PromptOutcome, PromptPort } from './prompt-port.ts'
|
||||
|
||||
function resolvePrefilled(
|
||||
id: string,
|
||||
value: string | undefined,
|
||||
validate: ((value: string) => string | undefined) | undefined,
|
||||
): PromptOutcome<string> | undefined {
|
||||
if (value === undefined) return undefined
|
||||
const diagnostic = validate?.(value)
|
||||
if (diagnostic) throw new Error(`${id}: ${diagnostic}`)
|
||||
return { status: 'answered', value }
|
||||
}
|
||||
|
||||
/** A typed business question resolved from prefilled input or one prompt call. */
|
||||
export abstract class Question<T> {
|
||||
/** Stable question identity used in diagnostics. */
|
||||
readonly id: string
|
||||
/** User-facing prompt text. */
|
||||
readonly message: string
|
||||
|
||||
protected constructor(id: string, message: string) {
|
||||
this.id = id
|
||||
this.message = message
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a prefilled answer without prompting, or ask through the port.
|
||||
* @param port - prompt interaction boundary.
|
||||
* @param prefilled - optional value supplied by CLI or current project state.
|
||||
* @returns answered or cancelled prompt outcome.
|
||||
*/
|
||||
abstract resolve(port: PromptPort, prefilled?: T): Promise<PromptOutcome<T>>
|
||||
}
|
||||
|
||||
/** Visible single-line text question. */
|
||||
export class TextQuestion extends Question<string> {
|
||||
/** Light hint displayed when no text has been entered. */
|
||||
readonly placeholder: string | undefined
|
||||
/** Editable value displayed in the input. */
|
||||
readonly initialValue: string | undefined
|
||||
/** Value accepted when the user submits an empty input. */
|
||||
readonly defaultValue: string | undefined
|
||||
private readonly validate: ((value: string) => string | undefined) | undefined
|
||||
|
||||
/** Configure one text question. */
|
||||
constructor(options: {
|
||||
id: string
|
||||
message: string
|
||||
placeholder?: string
|
||||
initialValue?: string
|
||||
defaultValue?: string
|
||||
validate?: (value: string) => string | undefined
|
||||
}) {
|
||||
super(options.id, options.message)
|
||||
this.placeholder = options.placeholder
|
||||
this.initialValue = options.initialValue
|
||||
this.defaultValue = options.defaultValue
|
||||
this.validate = options.validate
|
||||
}
|
||||
|
||||
/** Validate prefilled text or ask for it. */
|
||||
override async resolve(port: PromptPort, prefilled?: string): Promise<PromptOutcome<string>> {
|
||||
const resolved = resolvePrefilled(this.id, prefilled, this.validate)
|
||||
if (resolved) return resolved
|
||||
return port.text({
|
||||
message: this.message,
|
||||
...this.placeholder === undefined ? {} : { placeholder: this.placeholder },
|
||||
...this.initialValue === undefined ? {} : { initialValue: this.initialValue },
|
||||
...this.defaultValue === undefined ? {} : { defaultValue: this.defaultValue },
|
||||
...this.validate === undefined ? {} : { validate: this.validate },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Masked secret question whose empty-input semantics are set by its caller. */
|
||||
export class SecretQuestion extends Question<string> {
|
||||
private readonly validate: ((value: string) => string | undefined) | undefined
|
||||
|
||||
/** Configure one secret question. */
|
||||
constructor(options: {
|
||||
id: string
|
||||
message: string
|
||||
validate?: (value: string) => string | undefined
|
||||
}) {
|
||||
super(options.id, options.message)
|
||||
this.validate = options.validate
|
||||
}
|
||||
|
||||
/** Validate a prefilled secret or ask for a masked value. */
|
||||
override async resolve(port: PromptPort, prefilled?: string): Promise<PromptOutcome<string>> {
|
||||
const resolved = resolvePrefilled(this.id, prefilled, this.validate)
|
||||
if (resolved) return resolved
|
||||
return port.secret({
|
||||
message: this.message,
|
||||
...this.validate === undefined ? {} : { validate: this.validate },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Single-choice question. */
|
||||
export class SelectQuestion<T> extends Question<T> {
|
||||
/** Available choices in display order. */
|
||||
readonly options: readonly PromptOption<T>[]
|
||||
/** Initially focused choice. */
|
||||
readonly initialValue: T | undefined
|
||||
|
||||
/** Configure one single-choice question. */
|
||||
constructor(options: {
|
||||
id: string
|
||||
message: string
|
||||
options: readonly PromptOption<T>[]
|
||||
initialValue?: T
|
||||
}) {
|
||||
super(options.id, options.message)
|
||||
this.options = options.options
|
||||
this.initialValue = options.initialValue
|
||||
}
|
||||
|
||||
/** Validate a prefilled option or ask for one choice. */
|
||||
override async resolve(port: PromptPort, prefilled?: T): Promise<PromptOutcome<T>> {
|
||||
if (prefilled !== undefined) {
|
||||
if (!this.options.some(option => Object.is(option.value, prefilled) && !option.disabled)) {
|
||||
throw new Error(`${this.id}: unknown or disabled option ${String(prefilled)}`)
|
||||
}
|
||||
return { status: 'answered', value: prefilled }
|
||||
}
|
||||
return port.select({
|
||||
message: this.message,
|
||||
options: this.options,
|
||||
...this.initialValue === undefined ? {} : { initialValue: this.initialValue },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Additive multi-choice question. */
|
||||
export class MultiSelectQuestion<T> extends Question<readonly T[]> {
|
||||
readonly options: readonly PromptOption<T>[]
|
||||
readonly initialValues: readonly T[]
|
||||
readonly required: boolean
|
||||
|
||||
/** Configure one multi-choice question. */
|
||||
constructor(options: {
|
||||
id: string
|
||||
message: string
|
||||
options: readonly PromptOption<T>[]
|
||||
initialValues?: readonly T[]
|
||||
required?: boolean
|
||||
}) {
|
||||
super(options.id, options.message)
|
||||
this.options = options.options
|
||||
this.initialValues = options.initialValues ?? []
|
||||
this.required = options.required ?? false
|
||||
}
|
||||
|
||||
/** Validate prefilled values or ask for an additive selection. */
|
||||
override async resolve(port: PromptPort, prefilled?: readonly T[]): Promise<PromptOutcome<readonly T[]>> {
|
||||
if (prefilled !== undefined) {
|
||||
for (const value of prefilled) {
|
||||
/* v8 ignore next -- unknown, disabled, and accepted values are each pinned by the question tests */
|
||||
if (!this.options.some(option => Object.is(option.value, value) && option.disabled !== true)) {
|
||||
throw new Error(`${this.id}: unknown or disabled option ${String(value)}`)
|
||||
}
|
||||
}
|
||||
if (this.required && prefilled.length === 0) throw new Error(`${this.id}: choose at least one option`)
|
||||
return { status: 'answered', value: prefilled }
|
||||
}
|
||||
return port.multiselect({
|
||||
message: this.message,
|
||||
options: this.options,
|
||||
initialValues: this.initialValues,
|
||||
required: this.required,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Boolean confirmation question. */
|
||||
export class ConfirmQuestion extends Question<boolean> {
|
||||
/** Answer selected by pressing Enter. */
|
||||
readonly initialValue: boolean
|
||||
/** Visual severity used by the prompt adapter. */
|
||||
readonly tone: 'default' | 'warning'
|
||||
|
||||
/** Configure one confirmation question. */
|
||||
constructor(options: {
|
||||
id: string
|
||||
message: string
|
||||
initialValue?: boolean
|
||||
tone?: 'default' | 'warning'
|
||||
}) {
|
||||
super(options.id, options.message)
|
||||
this.initialValue = options.initialValue ?? true
|
||||
this.tone = options.tone ?? 'default'
|
||||
}
|
||||
|
||||
/** Return a prefilled boolean or ask for confirmation. */
|
||||
override async resolve(port: PromptPort, prefilled?: boolean): Promise<PromptOutcome<boolean>> {
|
||||
if (prefilled !== undefined) return { status: 'answered', value: prefilled }
|
||||
return port.confirm({ message: this.message, initialValue: this.initialValue, tone: this.tone })
|
||||
}
|
||||
}
|
||||
27
packages/scaffold/helper/src/templates/assets/README.md.tpl
Normal file
27
packages/scaffold/helper/src/templates/assets/README.md.tpl
Normal file
@@ -0,0 +1,27 @@
|
||||
# {{name}}
|
||||
|
||||
{{description}}
|
||||
|
||||
Built with the DeepSeek Harness SDK using the {{model}} model.
|
||||
|
||||
{{#if isAcp}}
|
||||
## Run as an ACP automation server
|
||||
|
||||
Run `{{packageManager}} start` and configure a programmatic ACP client to launch this project. Standard output is reserved for ACP JSON-RPC.
|
||||
{{else}}
|
||||
## Embed the harness
|
||||
|
||||
Import and call the exported `main()` from `index.ts` in your host application.
|
||||
{{/if}}
|
||||
|
||||
## Development
|
||||
|
||||
Install NPM dependencies with `{{packageManager}} {{installArgs}}`, then use:
|
||||
|
||||
- `dev`: `{{packageManager}} run dev`
|
||||
- `build`: `{{packageManager}} {{buildArgs}}`
|
||||
- `typecheck`: `{{packageManager}} run typecheck`
|
||||
- `start`: `{{packageManager}} start`
|
||||
- `config`: `{{packageManager}} run config`
|
||||
|
||||
Edit `cordis.yml` to change the runtime plugin tree. Add or remove builtin features with `{{packageManager}} exec dsh-sdk config`.
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
lib/
|
||||
.env
|
||||
.sessions/
|
||||
*.tsbuildinfo
|
||||
20
packages/scaffold/helper/src/templates/assets/index.ts.tpl
Normal file
20
packages/scaffold/helper/src/templates/assets/index.ts.tpl
Normal file
@@ -0,0 +1,20 @@
|
||||
{{#if isAcp}}
|
||||
import { startSDK, type SdkBootContext } from '@deepseek-ai/dsh-scripts'
|
||||
{{else}}
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { startSDK, type SdkBootContext } from '@deepseek-ai/dsh-scripts'
|
||||
{{/if}}
|
||||
|
||||
/** Boot this project's cordis.yml when invoked by dsh-scripts. */
|
||||
export async function main(boot: SdkBootContext) {
|
||||
const ctx = await startSDK(new URL('./cordis.yml', import.meta.url))
|
||||
{{#if isEmbed}}
|
||||
await ctx.agents.create({
|
||||
sessionId: SessionId(`main-session-${randomUUID()}`),
|
||||
meta: { cwd: boot.cwd },
|
||||
agentOptions: { model: {{modelLiteral}} },
|
||||
})
|
||||
{{/if}}
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
import { PluginBuild } from '@deepseek-ai/dsh-scripts/dev/tsdown-config'
|
||||
|
||||
export default defineConfig(PluginBuild({
|
||||
entry: ['src/index.ts'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: true,
|
||||
clean: false,
|
||||
}))
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Local Cordis plugin. */
|
||||
import type { Context } from 'cordis'
|
||||
|
||||
export const name = '{{pluginName}}'
|
||||
|
||||
/** Register this plugin's project-local behavior. */
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.effect(() => () => {})
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/** Project-local model-facing tool. */
|
||||
import type { Context } from 'cordis'
|
||||
import { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
|
||||
export const name = '{{pluginName}}'
|
||||
export const inject = ['tools']
|
||||
|
||||
/** Register the {{toolName}} tool. */
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.tools.register(defineTool({
|
||||
name: '{{toolName}}',
|
||||
description: 'Project-local {{toolTitle}} tool.',
|
||||
parameters: {},
|
||||
execute: async () => [{ type: 'text', text: '{{toolName}} completed.' }],
|
||||
presentCall: args => ({ card: 'generic', title: '{{toolTitle}}', kind: 'other', rawInput: args }),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": {{name}},
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": {{description}},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "dsh-sdk build",
|
||||
"typecheck": "tsc -b",
|
||||
"config": "dsh-sdk config"
|
||||
},
|
||||
"dependencies": {{dependencies}},
|
||||
"devDependencies": {{devDependencies}}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
You are a coding assistant powered by the \{{model}} model. Your working directory is \{{cwd}}.
|
||||
|
||||
Verify your work by running the code or tests. Keep answers brief and factual.
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2024",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"declaration": true,
|
||||
"composite": true,
|
||||
"outDir": "lib",
|
||||
"rootDir": ".",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
import { ProjectBuild } from '@deepseek-ai/dsh-scripts/dev/tsdown-config'
|
||||
|
||||
export default defineConfig(ProjectBuild({
|
||||
entry: ['index.ts'],
|
||||
outDir: '.',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
}))
|
||||
@@ -0,0 +1 @@
|
||||
nodeLinker: node-modules
|
||||
110
packages/scaffold/helper/src/templates/project-template.ts
Normal file
110
packages/scaffold/helper/src/templates/project-template.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Strict Handlebars wrapper and complete-file SDK project artifacts.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/templates/project-template
|
||||
*/
|
||||
|
||||
import { PackageJsonFile } from '../documents/package-json-file.ts'
|
||||
import { TextProjectFile } from '../documents/project-file.ts'
|
||||
import type { PackageManagerName } from '../package-managers/package-manager.ts'
|
||||
import { baselineNpmDependencies } from '../project/npm-dependency-policy.ts'
|
||||
import type { ProjectProfile, RunInterface } from '../project/types.ts'
|
||||
import { loadHelperTemplate } from './template-assets.ts'
|
||||
import type { TextTemplate } from './text-template.ts'
|
||||
|
||||
/** Stable typed view consumed by all generated text artifacts. */
|
||||
export interface ProjectTemplateContext {
|
||||
name: string
|
||||
description: string
|
||||
releaseVersion: string
|
||||
model: string
|
||||
modelLiteral: string
|
||||
isAcp: boolean
|
||||
isEmbed: boolean
|
||||
packageManager: PackageManagerName
|
||||
installArgs: string
|
||||
buildArgs: string
|
||||
}
|
||||
|
||||
/** Complete project-file template artifact. */
|
||||
export class TemplateArtifact<TModel extends object> extends TextProjectFile {
|
||||
/** Render and own one complete project file. */
|
||||
constructor(relativePath: string, template: TextTemplate<TModel>, model: TModel) {
|
||||
super(relativePath, template.render(model))
|
||||
}
|
||||
}
|
||||
|
||||
const README_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('README.md.tpl')
|
||||
const PACKAGE_JSON_TEMPLATE = loadHelperTemplate<{
|
||||
name: string
|
||||
description: string
|
||||
dependencies: string
|
||||
devDependencies: string
|
||||
}>('package.json.tpl')
|
||||
const INDEX_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('index.ts.tpl')
|
||||
const TSDOWN_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('tsdown.config.ts.tpl')
|
||||
const TSCONFIG_BASE_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('tsconfig.base.json.tpl')
|
||||
const GITIGNORE_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('gitignore.tpl')
|
||||
const YARNRC_TEMPLATE = loadHelperTemplate<ProjectTemplateContext>('yarnrc.yml.tpl')
|
||||
|
||||
/** Build the template model for one project and selected run interface. */
|
||||
export function createProjectTemplateContext(
|
||||
profile: ProjectProfile,
|
||||
runInterface: RunInterface = profile.runInterface,
|
||||
): ProjectTemplateContext {
|
||||
return {
|
||||
name: profile.name,
|
||||
description: profile.description,
|
||||
releaseVersion: profile.releaseVersion,
|
||||
model: profile.runtime.model,
|
||||
modelLiteral: JSON.stringify(profile.runtime.model),
|
||||
isAcp: runInterface === 'acp',
|
||||
isEmbed: runInterface === 'embed',
|
||||
packageManager: profile.packageManager.name,
|
||||
installArgs: profile.packageManager.installCommand().join(' '),
|
||||
buildArgs: profile.packageManager.buildCommand().join(' '),
|
||||
}
|
||||
}
|
||||
|
||||
/** Render the complete root package defaults before structured contributions merge. */
|
||||
export function createPackageJsonDoc(context: ProjectTemplateContext): PackageJsonFile {
|
||||
const npmDependencies = baselineNpmDependencies(context.releaseVersion)
|
||||
return PackageJsonFile.create(PACKAGE_JSON_TEMPLATE.render({
|
||||
name: JSON.stringify(context.name),
|
||||
description: JSON.stringify(context.description),
|
||||
dependencies: JSON.stringify(npmDependencies.dependencies),
|
||||
devDependencies: JSON.stringify(npmDependencies.devDependencies),
|
||||
}))
|
||||
}
|
||||
|
||||
/** Build interface-independent one-shot project artifacts. */
|
||||
export function createBaselineProjectArtifacts(
|
||||
context: ProjectTemplateContext,
|
||||
): TemplateArtifact<ProjectTemplateContext>[] {
|
||||
return [
|
||||
new TemplateArtifact('tsdown.config.ts', TSDOWN_TEMPLATE, context),
|
||||
new TemplateArtifact('tsconfig.base.json', TSCONFIG_BASE_TEMPLATE, context),
|
||||
new TemplateArtifact('.gitignore', GITIGNORE_TEMPLATE, context),
|
||||
...context.packageManager === 'yarn'
|
||||
? [new TemplateArtifact('.yarnrc.yml', YARNRC_TEMPLATE, context)]
|
||||
: [],
|
||||
]
|
||||
}
|
||||
|
||||
/** Build files owned by the selected app feature option. */
|
||||
export function createAppProjectArtifacts(
|
||||
context: ProjectTemplateContext,
|
||||
): TemplateArtifact<ProjectTemplateContext>[] {
|
||||
return [
|
||||
new TemplateArtifact('README.md', README_TEMPLATE, context),
|
||||
new TemplateArtifact('index.ts', INDEX_TEMPLATE, context),
|
||||
]
|
||||
}
|
||||
|
||||
/** Build package scripts owned by the selected app feature option. */
|
||||
export function createAppPackageScripts(): Readonly<Record<'dev' | 'start', string>> {
|
||||
return {
|
||||
dev: 'dsh-sdk dev index.ts',
|
||||
start: 'dsh-sdk start index.js',
|
||||
}
|
||||
}
|
||||
19
packages/scaffold/helper/src/templates/template-assets.ts
Normal file
19
packages/scaffold/helper/src/templates/template-assets.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Asset loader for templates owned by dsh-helper.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/templates/template-assets
|
||||
*/
|
||||
|
||||
import { TextTemplate } from './text-template.ts'
|
||||
|
||||
/**
|
||||
* Load one helper-owned template in source and bundled layouts.
|
||||
* @param filename - basename under the helper template asset directory.
|
||||
* @returns compiled typed template.
|
||||
*/
|
||||
export function loadHelperTemplate<TModel extends object>(filename: string): TextTemplate<TModel> {
|
||||
if (filename.includes('/') || filename.includes('\\')) {
|
||||
throw new Error(`helper template filename must not contain a directory: ${filename}`)
|
||||
}
|
||||
return TextTemplate.fromFile<TModel>(new URL(`./assets/${filename}`, import.meta.url))
|
||||
}
|
||||
44
packages/scaffold/helper/src/templates/text-template.ts
Normal file
44
packages/scaffold/helper/src/templates/text-template.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Strict typed rendering for package-owned text templates.
|
||||
*
|
||||
* @module @deepseek-ai/dsh-helper/templates/text-template
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import Handlebars from 'handlebars'
|
||||
|
||||
/** Strict Handlebars template with no HTML escaping or custom extensions. */
|
||||
export class TextTemplate<TModel extends object> {
|
||||
private readonly renderer: Handlebars.TemplateDelegate<TModel>
|
||||
|
||||
/**
|
||||
* Compile one template under the SDK's fixed rendering policy.
|
||||
* @param source - complete template source.
|
||||
*/
|
||||
constructor(source: string) {
|
||||
const handlebars = Handlebars.create()
|
||||
this.renderer = handlebars.compile<TModel>(source, {
|
||||
strict: true,
|
||||
noEscape: true,
|
||||
preventIndent: true,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a template asset owned by the calling package.
|
||||
* @param url - source or bundled asset URL.
|
||||
* @returns compiled template.
|
||||
*/
|
||||
static fromFile<T extends object>(url: URL): TextTemplate<T> {
|
||||
return new TextTemplate<T>(readFileSync(url, 'utf8'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Render text from one complete typed model.
|
||||
* @param model - values referenced by the template.
|
||||
* @returns rendered text.
|
||||
*/
|
||||
render(model: TModel): string {
|
||||
return this.renderer(model)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user