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:
Tianyi Cui
2026-07-30 03:13:49 +08:00
parent 7e445c3a67
commit 3fc35c91ff
351 changed files with 368 additions and 311 deletions

View 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
}

View File

@@ -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]
})),
}
}

View 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')
}
}

View 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)
}
}

View 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[]
}