@acryldev/harness-runtime 0.0.0-stage → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +49 -0
- package/lib/index.mjs +5693 -0
- package/lib/index.mjs.map +1 -0
- package/lib/types/acryl-home.d.ts +81 -0
- package/lib/types/app/new-app.d.ts +65 -0
- package/lib/types/app/start-source.d.ts +47 -0
- package/lib/types/blueprint/blueprint.d.ts +74 -0
- package/lib/types/blueprint/brand-identity.d.ts +26 -0
- package/lib/types/blueprint/compose.d.ts +53 -0
- package/lib/types/blueprint/definition.d.ts +22 -0
- package/lib/types/blueprint/index.d.ts +7 -0
- package/lib/types/blueprint/manifest.d.ts +35 -0
- package/lib/types/blueprint/selection.d.ts +19 -0
- package/lib/types/cli-market-install.d.ts +97 -0
- package/lib/types/cli-market-plugins.d.ts +81 -0
- package/lib/types/coding-capabilities.d.ts +29 -0
- package/lib/types/durable-message.d.ts +18 -0
- package/lib/types/engine-dsh.d.ts +181 -0
- package/lib/types/engine-files.d.ts +8 -0
- package/lib/types/engine-host.d.ts +32 -0
- package/lib/types/engine-tools.d.ts +11 -0
- package/lib/types/index.d.ts +67 -0
- package/lib/types/instance/announce-self.d.ts +38 -0
- package/lib/types/instance/app-instance.d.ts +125 -0
- package/lib/types/instance/index.d.ts +6 -0
- package/lib/types/instance/offline-lock.d.ts +29 -0
- package/lib/types/instance/online-secret.d.ts +29 -0
- package/lib/types/instance/registry.d.ts +26 -0
- package/lib/types/instance/select.d.ts +43 -0
- package/lib/types/module-hooks.d.ts +19 -0
- package/lib/types/module-resolution.d.ts +31 -0
- package/lib/types/package-overlay.d.ts +41 -0
- package/lib/types/pinned-pnpm.d.ts +15 -0
- package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
- package/lib/types/plugin-doctor.d.ts +49 -0
- package/lib/types/plugin-lifecycle-state.d.ts +92 -0
- package/lib/types/plugin-lifecycle.d.ts +87 -0
- package/lib/types/profile-layout.d.ts +17 -0
- package/lib/types/profile-owner.d.ts +25 -0
- package/lib/types/profile-repair/backup.d.ts +37 -0
- package/lib/types/profile-repair/findings.d.ts +29 -0
- package/lib/types/profile-repair/index.d.ts +9 -0
- package/lib/types/profile-repair/inspector.d.ts +11 -0
- package/lib/types/profile-repair/repair.d.ts +38 -0
- package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
- package/lib/types/profile-resolution/resolver.d.ts +41 -0
- package/lib/types/profile-resolution/service.d.ts +22 -0
- package/lib/types/prompt-budget.d.ts +44 -0
- package/lib/types/session-bridge.d.ts +57 -0
- package/lib/types/session-log-exporter.d.ts +31 -0
- package/lib/types/system-prompt-capture.d.ts +29 -0
- package/lib/types/web-favicon-data.d.ts +5 -0
- package/lib/types/web-favicon.d.ts +23 -0
- package/lib/types/web-market-install.d.ts +114 -0
- package/lib/types/web-market-plugins.d.ts +106 -0
- package/lib/types/web-port.d.ts +15 -0
- package/package.json +211 -3
- package/src/acryl-home.ts +103 -0
- package/src/app/new-app.ts +239 -0
- package/src/app/start-source.ts +110 -0
- package/src/blueprint/blueprint.ts +141 -0
- package/src/blueprint/brand-identity.ts +75 -0
- package/src/blueprint/compose.ts +222 -0
- package/src/blueprint/definition.ts +92 -0
- package/src/blueprint/index.ts +20 -0
- package/src/blueprint/manifest.ts +145 -0
- package/src/blueprint/selection.ts +74 -0
- package/src/cli-market-install.ts +181 -0
- package/src/cli-market-plugins.ts +176 -0
- package/src/coding-capabilities.ts +61 -0
- package/src/durable-message.ts +23 -0
- package/src/engine-dsh.ts +856 -0
- package/src/engine-files.ts +9 -0
- package/src/engine-host.ts +128 -0
- package/src/engine-tools.ts +26 -0
- package/src/index.ts +436 -0
- package/src/instance/announce-self.ts +88 -0
- package/src/instance/app-instance.ts +240 -0
- package/src/instance/index.ts +45 -0
- package/src/instance/offline-lock.ts +71 -0
- package/src/instance/online-secret.ts +55 -0
- package/src/instance/registry.ts +53 -0
- package/src/instance/select.ts +134 -0
- package/src/module-hooks.ts +41 -0
- package/src/module-resolution.ts +187 -0
- package/src/package-overlay.ts +160 -0
- package/src/pinned-pnpm.ts +67 -0
- package/src/plugin-acryl-workspace-status.ts +99 -0
- package/src/plugin-doctor.ts +141 -0
- package/src/plugin-lifecycle-state.ts +347 -0
- package/src/plugin-lifecycle.ts +223 -0
- package/src/profile-layout.ts +97 -0
- package/src/profile-owner.ts +52 -0
- package/src/profile-repair/backup.ts +119 -0
- package/src/profile-repair/findings.ts +43 -0
- package/src/profile-repair/index.ts +10 -0
- package/src/profile-repair/inspector.ts +156 -0
- package/src/profile-repair/repair.ts +137 -0
- package/src/profile-resolution/moved-framework.ts +64 -0
- package/src/profile-resolution/resolver.ts +876 -0
- package/src/profile-resolution/service.ts +99 -0
- package/src/prompt-budget.ts +118 -0
- package/src/session-bridge.ts +350 -0
- package/src/session-log-exporter.ts +68 -0
- package/src/system-prompt-capture.ts +99 -0
- package/src/web-favicon-data.ts +6 -0
- package/src/web-favicon.ts +43 -0
- package/src/web-market-install.ts +206 -0
- package/src/web-market-plugins.ts +215 -0
- package/src/web-port.ts +39 -0
- package/tests/account-callback.spec.ts +173 -0
- package/tests/acryl-home.spec.ts +39 -0
- package/tests/agent-self-hosting.spec.ts +101 -0
- package/tests/announce-self.spec.ts +84 -0
- package/tests/app-lifecycle.spec.ts +99 -0
- package/tests/blank-blueprint.spec.ts +110 -0
- package/tests/blueprint-definition.spec.ts +128 -0
- package/tests/blueprint.spec.ts +138 -0
- package/tests/bulkhead.spec.ts +187 -0
- package/tests/coding-vocabulary.spec.ts +15 -0
- package/tests/dump-system-prompt.spec.ts +65 -0
- package/tests/e2e-real-model.spec.ts +71 -0
- package/tests/e2e-restart-real-model.spec.ts +77 -0
- package/tests/engine-dsh.spec.ts +340 -0
- package/tests/engine-host-mount-root-include.spec.ts +118 -0
- package/tests/engine-host.spec.ts +176 -0
- package/tests/engine-optional.spec.ts +81 -0
- package/tests/extension-examples.spec.ts +261 -0
- package/tests/hooks-thread-stack.ts +27 -0
- package/tests/instance-patches.spec.ts +25 -0
- package/tests/instance.spec.ts +235 -0
- package/tests/live/community-plugins.spec.ts +83 -0
- package/tests/module-hooks.spec.ts +35 -0
- package/tests/module-resolution.spec.ts +265 -0
- package/tests/moved-framework.spec.ts +61 -0
- package/tests/new-app.spec.ts +132 -0
- package/tests/organizer-growth.spec.ts +117 -0
- package/tests/pinned-pnpm.spec.ts +34 -0
- package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
- package/tests/plugin-context.spec.ts +640 -0
- package/tests/plugin-doctor.spec.ts +183 -0
- package/tests/plugin-enablement-one-store.spec.ts +130 -0
- package/tests/plugin-lifecycle-state.spec.ts +169 -0
- package/tests/profile-layout.spec.ts +58 -0
- package/tests/profile-owner.spec.ts +38 -0
- package/tests/profile-repair/profile-repair.spec.ts +231 -0
- package/tests/profile-resolution-port.spec.ts +30 -0
- package/tests/profile-resolution-service.spec.ts +273 -0
- package/tests/profile-resolution-swap.spec.ts +69 -0
- package/tests/profile-resolution.spec.ts +2535 -0
- package/tests/profile.spec.ts +70 -0
- package/tests/project-registry.spec.ts +81 -0
- package/tests/prompt-budget.spec.ts +58 -0
- package/tests/real-home-guard.spec.ts +178 -0
- package/tests/session-bridge.spec.ts +316 -0
- package/tests/start-source.spec.ts +65 -0
- package/tests/system-prompt-shape.spec.ts +95 -0
- package/tests/three-levels.spec.ts +84 -0
- package/tests/tool-gateway.spec.ts +116 -0
- package/tests/tool-schemas.spec.ts +41 -0
- package/tests/web-favicon.spec.ts +42 -0
- package/tests/web-port.spec.ts +38 -0
- package/tests/web-startup-hold.spec.ts +79 -0
- package/tsconfig.json +24 -0
- package/tsdown.config.ts +2 -0
- package/vitest.config.ts +18 -0
- package/README.md +0 -3
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one persistent store of plugin enablement overrides, keyed by profile.
|
|
3
|
+
*
|
|
4
|
+
* Every surface that offers plugin enable/disable - Desktop's Lifecycle tab,
|
|
5
|
+
* the Web panel, `acryl plugin enable` on the CLI - reads and writes the same
|
|
6
|
+
* `plugin-lifecycle/state.json`, so a disable applies to the whole profile the
|
|
7
|
+
* next time it boots no matter which surface asked for it.
|
|
8
|
+
*
|
|
9
|
+
* @module @acryldev/harness-runtime/plugin-lifecycle-state
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync } from 'node:fs'
|
|
13
|
+
import { chmod, lstat, mkdir, readFile } from 'node:fs/promises'
|
|
14
|
+
import { dirname, join } from 'node:path'
|
|
15
|
+
import { PROFILE_PATCH_FILENAME, resolveProfileDir } from '@deepseek-ai/dsh-app-boot'
|
|
16
|
+
import { isMap, isScalar, isSeq, parseDocument } from 'yaml'
|
|
17
|
+
import { withFileLock, writeFileAtomic } from './engine-files.ts'
|
|
18
|
+
import { resolveAcrylDshHome } from './acryl-home.ts'
|
|
19
|
+
|
|
20
|
+
const STATE_VERSION = 1
|
|
21
|
+
const STATE_FILE_MODE = 0o600
|
|
22
|
+
const STATE_DIRECTORY_MODE = 0o700
|
|
23
|
+
const MAX_STATE_BYTES = 64 * 1024
|
|
24
|
+
const MAX_PROFILES = 64
|
|
25
|
+
const MAX_OVERRIDES = 256
|
|
26
|
+
const MAX_PROFILE_NAME_BYTES = 255
|
|
27
|
+
|
|
28
|
+
/** A well-formed runtime Loader entry id (`include:<row>` or a bare row id). */
|
|
29
|
+
const ENTRY_ID_PATTERN = /^(?:include:)?[a-z0-9](?:[a-z0-9._:@/-]{0,190}[a-z0-9])?$/iu
|
|
30
|
+
|
|
31
|
+
/** Rejects a profile name, in the words of the surface that owns the rule. */
|
|
32
|
+
export type ProfileNameValidator = (profileName: string) => void
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The portable rule: a profile name must be usable as one profile directory
|
|
36
|
+
* under the harness home. A surface whose profiles are named by other rules
|
|
37
|
+
* (Desktop's CLI accepts localized names) supplies its own validator instead.
|
|
38
|
+
*/
|
|
39
|
+
export function assertProfileName(name: string): void {
|
|
40
|
+
if (typeof name !== 'string' || name.length === 0
|
|
41
|
+
|| name.includes('/') || name.includes('\\') || name === '.' || name === '..'
|
|
42
|
+
|| name === 'node_modules' || Buffer.byteLength(name, 'utf8') > MAX_PROFILE_NAME_BYTES
|
|
43
|
+
|| /[\0-\x1f\x7f-\x9f]/.test(name)
|
|
44
|
+
|| /[<>:"|?*]/.test(name) || /[. ]$/.test(name)
|
|
45
|
+
|| /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(name)) {
|
|
46
|
+
throw new Error(`invalid profile name ${JSON.stringify(name)}`)
|
|
47
|
+
}
|
|
48
|
+
resolveProfileDir(name, '/')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Persistence inputs: enough to read and write the override file for one
|
|
53
|
+
* profile.
|
|
54
|
+
*/
|
|
55
|
+
export interface PluginLifecycleStatePersistence {
|
|
56
|
+
readonly profileName: string
|
|
57
|
+
readonly statePath: string
|
|
58
|
+
/** Overrides {@link assertProfileName} when a surface names profiles its own way. */
|
|
59
|
+
readonly validateProfileName?: ProfileNameValidator
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The one override file every surface reads and writes, inside the engine home
|
|
64
|
+
* whose profiles these overrides describe.
|
|
65
|
+
*
|
|
66
|
+
* The overrides are a property of a profile, and the profiles themselves live
|
|
67
|
+
* under the engine home - so the store shares their root, their lifetime, and
|
|
68
|
+
* their isolation switch. It is deliberately not a surface's private data
|
|
69
|
+
* directory (the Electron userData path it used to be), because then
|
|
70
|
+
* `acryl plugin disable x` and the Desktop panel would give two different
|
|
71
|
+
* answers about one profile: the defect spec 034 exists to fix.
|
|
72
|
+
*
|
|
73
|
+
* The engine home, not a bare `~/.acryl`, is also what keeps an isolated run
|
|
74
|
+
* isolated: `resolveAcrylHome()` ignores `$DSH_HOME`, so a dev or throwaway
|
|
75
|
+
* `DSH_HOME=~/.acryl-dev/.dsh` would otherwise read and write overrides in the
|
|
76
|
+
* operator's real install. Every surface already agrees on this root - each one
|
|
77
|
+
* boots through `resolveAcrylDshHome()`.
|
|
78
|
+
*
|
|
79
|
+
* @param dshHome - the engine home this process booted; defaults to the one
|
|
80
|
+
* `$ACRYL_HOME` / `$DSH_HOME` resolve to.
|
|
81
|
+
*/
|
|
82
|
+
export function resolvePluginLifecycleStatePath(dshHome: string = resolveAcrylDshHome()): string {
|
|
83
|
+
return join(dshHome, 'plugin-lifecycle', 'state.json')
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Runtime entry id -> the patch-local row id it disables during composition. */
|
|
87
|
+
export function entryPatchId(entryId: string): string {
|
|
88
|
+
return entryId.startsWith('include:') ? entryId.slice('include:'.length) : entryId
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Whether a persisted disabled-entry id is structurally a Loader entry id. */
|
|
92
|
+
export function isPluginLifecycleEntryId(value: unknown): value is string {
|
|
93
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 200 && ENTRY_ID_PATTERN.test(value)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A Loader row that was renamed before this state format settled: a disable kept under the old entry id applies to the row by its current id.
|
|
98
|
+
* The Development Canvas row `desktop-development-canvas` took its package name `acryl-development-canvas` under the row-id rule (spec 048 T014).
|
|
99
|
+
*/
|
|
100
|
+
const RENAMED_ENTRY_IDS: Readonly<Record<string, string>> = Object.freeze({
|
|
101
|
+
'include:desktop-development-canvas': 'include:acryl-development-canvas',
|
|
102
|
+
'desktop-development-canvas': 'acryl-development-canvas',
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
/** Base-template bundles: never user-mutable. Every other profile bundle is. */
|
|
106
|
+
export const BASE_TEMPLATE_BUNDLE_NAMES: ReadonlySet<string> = new Set([
|
|
107
|
+
'@deepseek-ai/dsh-base',
|
|
108
|
+
'@deepseek-ai/dsh-web-app',
|
|
109
|
+
])
|
|
110
|
+
|
|
111
|
+
interface ProfileState {
|
|
112
|
+
readonly profileName: string
|
|
113
|
+
readonly disabledEntries: readonly string[]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface PluginLifecycleStateV1 {
|
|
117
|
+
readonly version: 1
|
|
118
|
+
readonly profiles: readonly ProfileState[]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function emptyState(): PluginLifecycleStateV1 {
|
|
122
|
+
return { version: STATE_VERSION, profiles: [] }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function stableCompare(left: string, right: string): number {
|
|
126
|
+
return left < right ? -1 : left > right ? 1 : 0
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function hasExactKeys(record: Record<string, unknown>, keys: readonly string[]): boolean {
|
|
130
|
+
const actual = Object.keys(record).sort(stableCompare)
|
|
131
|
+
const expected = [...keys].sort(stableCompare)
|
|
132
|
+
return actual.length === expected.length
|
|
133
|
+
&& actual.every((key, index) => key === expected[index])
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function parseState(value: unknown, validateProfileName: ProfileNameValidator): PluginLifecycleStateV1 {
|
|
137
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
138
|
+
throw new Error('plugin lifecycle state root must be an object')
|
|
139
|
+
}
|
|
140
|
+
const root = value as Record<string, unknown>
|
|
141
|
+
if (!hasExactKeys(root, ['version', 'profiles'])
|
|
142
|
+
|| root.version !== STATE_VERSION
|
|
143
|
+
|| !Array.isArray(root.profiles)) {
|
|
144
|
+
throw new Error('plugin lifecycle state version or profiles list is invalid')
|
|
145
|
+
}
|
|
146
|
+
if (root.profiles.length > MAX_PROFILES) {
|
|
147
|
+
throw new Error('plugin lifecycle state contains too many profiles')
|
|
148
|
+
}
|
|
149
|
+
const names = new Set<string>()
|
|
150
|
+
const profiles: ProfileState[] = []
|
|
151
|
+
for (const raw of root.profiles) {
|
|
152
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
153
|
+
throw new Error('plugin lifecycle profile state must be an object')
|
|
154
|
+
}
|
|
155
|
+
const profile = raw as Record<string, unknown>
|
|
156
|
+
if (!hasExactKeys(profile, ['profileName', 'disabledEntries'])
|
|
157
|
+
|| typeof profile.profileName !== 'string') {
|
|
158
|
+
throw new Error('plugin lifecycle profile name is invalid')
|
|
159
|
+
}
|
|
160
|
+
validateProfileName(profile.profileName)
|
|
161
|
+
if (names.has(profile.profileName)) {
|
|
162
|
+
throw new Error(`duplicate plugin lifecycle profile ${JSON.stringify(profile.profileName)}`)
|
|
163
|
+
}
|
|
164
|
+
names.add(profile.profileName)
|
|
165
|
+
if (!Array.isArray(profile.disabledEntries)
|
|
166
|
+
|| profile.disabledEntries.length > MAX_OVERRIDES
|
|
167
|
+
|| profile.disabledEntries.some(entryId => typeof entryId !== 'string')) {
|
|
168
|
+
throw new Error(`disabledEntries for profile ${JSON.stringify(profile.profileName)} is invalid`)
|
|
169
|
+
}
|
|
170
|
+
// Any structurally valid Loader entry id is kept - the mutable set is
|
|
171
|
+
// derived at runtime from the profile bundle list, not this file. A
|
|
172
|
+
// malformed string, or one for an entry that no longer exists, is dropped
|
|
173
|
+
// rather than treated as corruption: composition emits a disable patch by
|
|
174
|
+
// id, and the Loader treats an unknown-id patch as a warning, not a fault.
|
|
175
|
+
profiles.push({
|
|
176
|
+
profileName: profile.profileName,
|
|
177
|
+
disabledEntries: [...new Set((profile.disabledEntries as unknown[]).filter(isPluginLifecycleEntryId).map(entryId => entryId))]
|
|
178
|
+
.sort(stableCompare),
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
profiles.sort((left, right) => stableCompare(left.profileName, right.profileName))
|
|
182
|
+
return { version: STATE_VERSION, profiles }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function validatorOf(persistence: PluginLifecycleStatePersistence): ProfileNameValidator {
|
|
186
|
+
return persistence.validateProfileName ?? assertProfileName
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function readState(persistence: PluginLifecycleStatePersistence): PluginLifecycleStateV1 {
|
|
190
|
+
let source: string
|
|
191
|
+
try {
|
|
192
|
+
source = readFileSync(persistence.statePath, 'utf8')
|
|
193
|
+
} catch (cause) {
|
|
194
|
+
if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return emptyState()
|
|
195
|
+
throw cause
|
|
196
|
+
}
|
|
197
|
+
if (Buffer.byteLength(source, 'utf8') > MAX_STATE_BYTES) {
|
|
198
|
+
throw new Error('plugin lifecycle state is too large')
|
|
199
|
+
}
|
|
200
|
+
return parseState(JSON.parse(source) as unknown, validatorOf(persistence))
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function renderState(state: PluginLifecycleStateV1): string {
|
|
204
|
+
return `${JSON.stringify(state, null, 2)}\n`
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Read disabled Loader entry ids for one profile. */
|
|
208
|
+
export function readDisabledPluginLifecycleEntries(
|
|
209
|
+
persistence: PluginLifecycleStatePersistence,
|
|
210
|
+
): ReadonlySet<string> {
|
|
211
|
+
validatorOf(persistence)(persistence.profileName)
|
|
212
|
+
const profile = readState(persistence).profiles
|
|
213
|
+
.find(candidate => candidate.profileName === persistence.profileName)
|
|
214
|
+
return new Set((profile?.disabledEntries ?? []).map(entry => RENAMED_ENTRY_IDS[entry] ?? entry))
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* User-added profile bundles from `dsh.profile.bundles`, minus the base
|
|
219
|
+
* template. Each such package's inserted Loader row is user-mutable. A missing
|
|
220
|
+
* or malformed manifest yields an empty set (nothing user-mutable by bundle).
|
|
221
|
+
*/
|
|
222
|
+
export function readUserMutableBundleNames(profileDir: string): ReadonlySet<string> {
|
|
223
|
+
let manifest: unknown
|
|
224
|
+
try {
|
|
225
|
+
manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'))
|
|
226
|
+
} catch {
|
|
227
|
+
return new Set()
|
|
228
|
+
}
|
|
229
|
+
const bundles = (manifest as { dsh?: { profile?: { bundles?: unknown } } })?.dsh?.profile?.bundles
|
|
230
|
+
if (!Array.isArray(bundles)) return new Set()
|
|
231
|
+
return new Set(
|
|
232
|
+
bundles.filter((name): name is string =>
|
|
233
|
+
typeof name === 'string' && !BASE_TEMPLATE_BUNDLE_NAMES.has(name)),
|
|
234
|
+
)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function ensurePrivateStateDirectory(statePath: string): Promise<void> {
|
|
238
|
+
const directory = dirname(statePath)
|
|
239
|
+
await mkdir(directory, { recursive: true, mode: STATE_DIRECTORY_MODE })
|
|
240
|
+
const stat = await lstat(directory)
|
|
241
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
242
|
+
throw new Error('plugin lifecycle state directory is not private')
|
|
243
|
+
}
|
|
244
|
+
await chmod(directory, STATE_DIRECTORY_MODE)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Persist one desired entry enablement with locking and atomic replace. */
|
|
248
|
+
export async function setPluginLifecycleEntryEnabled(
|
|
249
|
+
persistence: PluginLifecycleStatePersistence,
|
|
250
|
+
entryId: string,
|
|
251
|
+
enabled: boolean,
|
|
252
|
+
): Promise<void> {
|
|
253
|
+
validatorOf(persistence)(persistence.profileName)
|
|
254
|
+
if (!isPluginLifecycleEntryId(entryId)) throw new Error('plugin lifecycle entry id is malformed')
|
|
255
|
+
await ensurePrivateStateDirectory(persistence.statePath)
|
|
256
|
+
await withFileLock(persistence.statePath, async () => {
|
|
257
|
+
const state = readState(persistence)
|
|
258
|
+
const current = state.profiles.find(profile => profile.profileName === persistence.profileName)
|
|
259
|
+
const disabled = new Set(current?.disabledEntries ?? [])
|
|
260
|
+
if (enabled) disabled.delete(entryId)
|
|
261
|
+
else disabled.add(entryId)
|
|
262
|
+
const profiles = state.profiles.filter(profile => profile.profileName !== persistence.profileName)
|
|
263
|
+
if (disabled.size > 0) {
|
|
264
|
+
profiles.push({
|
|
265
|
+
profileName: persistence.profileName,
|
|
266
|
+
disabledEntries: [...disabled].sort(stableCompare),
|
|
267
|
+
})
|
|
268
|
+
}
|
|
269
|
+
profiles.sort((left, right) => stableCompare(left.profileName, right.profileName))
|
|
270
|
+
const next = parseState({ version: STATE_VERSION, profiles }, validatorOf(persistence))
|
|
271
|
+
const rendered = renderState(next)
|
|
272
|
+
if (Buffer.byteLength(rendered, 'utf8') > MAX_STATE_BYTES) {
|
|
273
|
+
throw new Error('plugin lifecycle state is too large')
|
|
274
|
+
}
|
|
275
|
+
await writeFileAtomic(persistence.statePath, rendered, {
|
|
276
|
+
mode: STATE_FILE_MODE,
|
|
277
|
+
dirMode: STATE_DIRECTORY_MODE,
|
|
278
|
+
})
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Remove a disable DSH's own Plugins page wrote for one row into the profile's patch file (`{ id, disabled: true }`,
|
|
284
|
+
* `plugin-manager/src/patch.ts`), keeping every comment and every other key. Before spec 001 T089 both pages wrote, each
|
|
285
|
+
* to its own store, and a disable in either kept the row off however the other was set; now every toggle of a row ACRYL
|
|
286
|
+
* admits goes through this lifecycle (DSH's page too, through ACRYL's plugin manager), and an enable clears the old
|
|
287
|
+
* page's disable here, so the override file stays the row's only store. An entry left with only `id` (and `name`) is
|
|
288
|
+
* removed; one with other keys keeps them.
|
|
289
|
+
*
|
|
290
|
+
* @returns whether the patch file changed.
|
|
291
|
+
*/
|
|
292
|
+
export async function clearProfilePatchDisable(profileDir: string, patchId: string): Promise<boolean> {
|
|
293
|
+
const path = join(profileDir, PROFILE_PATCH_FILENAME)
|
|
294
|
+
return withFileLock(path, async () => {
|
|
295
|
+
let text: string
|
|
296
|
+
try {
|
|
297
|
+
text = await readFile(path, 'utf8')
|
|
298
|
+
} catch (cause) {
|
|
299
|
+
if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return false
|
|
300
|
+
throw cause
|
|
301
|
+
}
|
|
302
|
+
const document = parseDocument(text, { customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value: string) => value }] })
|
|
303
|
+
if (document.errors.length > 0 || !isSeq(document.contents)) return false
|
|
304
|
+
const items = document.contents.items
|
|
305
|
+
let changed = false
|
|
306
|
+
for (let index = items.length - 1; index >= 0; index -= 1) {
|
|
307
|
+
const item = items[index]
|
|
308
|
+
if (!isMap(item) || item.has('insert') || document.getIn([index, 'id']) !== patchId || document.getIn([index, 'disabled']) !== true) continue
|
|
309
|
+
item.delete('disabled')
|
|
310
|
+
if (item.items.every(pair => ['id', 'name'].includes(String(isScalar(pair.key) ? pair.key.value : pair.key)))) {
|
|
311
|
+
// A comment written above the removed entry stays, above whatever follows it.
|
|
312
|
+
const comment = item.commentBefore
|
|
313
|
+
items.splice(index, 1)
|
|
314
|
+
if (comment !== undefined && comment !== null) {
|
|
315
|
+
const next = items[index] as { commentBefore?: string | null } | undefined
|
|
316
|
+
if (next !== undefined && next !== null && typeof next === 'object') next.commentBefore = next.commentBefore ? `${comment}\n${next.commentBefore}` : comment
|
|
317
|
+
else document.comment = document.comment ? `${document.comment}\n${comment}` : comment
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
changed = true
|
|
321
|
+
}
|
|
322
|
+
if (changed) await writeFileAtomic(path, String(document), { mode: STATE_FILE_MODE })
|
|
323
|
+
return changed
|
|
324
|
+
})
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Convert persisted overrides into profile overlay rows for the rows this
|
|
329
|
+
* composition has. A disable patch matches its target by id only - no `name`,
|
|
330
|
+
* so a row whose id and package name differ (e.g. `dsh-editor` /
|
|
331
|
+
* `acryl-dsh-editor-plugin`) still disables. A disable whose row is not
|
|
332
|
+
* composed (its plugin was uninstalled) yields no patch, so the Loader does not
|
|
333
|
+
* warn on every boot; it stays stored, applies again when the plugin comes
|
|
334
|
+
* back, and `acryl plugin doctor` reports it as a stale override.
|
|
335
|
+
* @param persistence - the override file and profile to read.
|
|
336
|
+
* @param composedRowIds - the Loader row ids the composition already has.
|
|
337
|
+
* @returns one disable patch per stored disable whose row is composed.
|
|
338
|
+
*/
|
|
339
|
+
export function pluginLifecyclePatches(
|
|
340
|
+
persistence: PluginLifecycleStatePersistence,
|
|
341
|
+
composedRowIds: ReadonlySet<string>,
|
|
342
|
+
): readonly { readonly id: string; readonly disabled: true }[] {
|
|
343
|
+
return [...readDisabledPluginLifecycleEntries(persistence)]
|
|
344
|
+
.map(entryPatchId)
|
|
345
|
+
.filter(id => composedRowIds.has(id))
|
|
346
|
+
.map(id => ({ id, disabled: true as const }))
|
|
347
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DSH-profile plugin lifecycle: one host policy, mounted as one Cordis
|
|
3
|
+
* service, for every ACRYL surface (spec 034, T005).
|
|
4
|
+
*
|
|
5
|
+
* The lifecycle mechanics live in `@acryldev/control`'s host-neutral controller.
|
|
6
|
+
* What is left here is the part that is the same on the Desktop, the Web host,
|
|
7
|
+
* and the CLI: which rows a DSH profile admits to user control, where the
|
|
8
|
+
* override file lives, and how a just-installed profile bundle inserts its row.
|
|
9
|
+
* A surface that needs more (Desktop's Blend rows and market bookkeeping)
|
|
10
|
+
* passes it in through the options rather than forking the policy.
|
|
11
|
+
*
|
|
12
|
+
* @module @acryldev/harness-runtime/plugin-lifecycle
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readFileSync } from 'node:fs'
|
|
16
|
+
import { createRequire } from 'node:module'
|
|
17
|
+
import { dirname, join } from 'node:path'
|
|
18
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
19
|
+
import type { EntryGroup } from '@deepseek-ai/cordis-plugin-loader'
|
|
20
|
+
import { loadOverlayPatches } from '@deepseek-ai/dsh-app-boot'
|
|
21
|
+
import {
|
|
22
|
+
AcrPluginLifecycleController,
|
|
23
|
+
AcrPluginLifecycleService,
|
|
24
|
+
PROTECTED_PLUGIN_ENTRY_REASON,
|
|
25
|
+
PluginLifecycleError,
|
|
26
|
+
type PluginLifecycleEntryRef,
|
|
27
|
+
type PluginLifecycleHost,
|
|
28
|
+
} from '@acryldev/control'
|
|
29
|
+
import {
|
|
30
|
+
clearProfilePatchDisable,
|
|
31
|
+
entryPatchId,
|
|
32
|
+
readUserMutableBundleNames,
|
|
33
|
+
setPluginLifecycleEntryEnabled,
|
|
34
|
+
type PluginLifecycleStatePersistence,
|
|
35
|
+
type ProfileNameValidator,
|
|
36
|
+
} from './plugin-lifecycle-state.ts'
|
|
37
|
+
|
|
38
|
+
/** Options every surface's DSH-profile lifecycle host is built from. */
|
|
39
|
+
export interface DshPluginLifecycleOptions {
|
|
40
|
+
/** Profile whose override list this host reads and writes. */
|
|
41
|
+
readonly profileName: string
|
|
42
|
+
/** Profile directory - the source of the user-installed bundle list. */
|
|
43
|
+
readonly profileDir: string
|
|
44
|
+
/** Absolute path of the shared `plugin-lifecycle/state.json`. */
|
|
45
|
+
readonly statePath: string
|
|
46
|
+
/**
|
|
47
|
+
* Loader row ids this surface itself admits to user control, in their runtime
|
|
48
|
+
* spelling (`include:<row>` when the row is composed through an include).
|
|
49
|
+
* Called on every policy read, so a surface may derive it lazily; the rows of
|
|
50
|
+
* the profile's own `dsh.profile.bundles` are admitted on top of it.
|
|
51
|
+
*/
|
|
52
|
+
readonly mutableEntryIds?: () => ReadonlySet<string>
|
|
53
|
+
/** Name this host's bundle-patch diagnostics attribute a failure to. */
|
|
54
|
+
readonly binName?: string
|
|
55
|
+
/** Explanation shown for a non-mutable entry. */
|
|
56
|
+
readonly protectedReason?: string
|
|
57
|
+
/** Bookkeeping after a package leaves the Loader tree. Best effort. */
|
|
58
|
+
readonly afterDeactivate?: (packageName: string) => Promise<void>
|
|
59
|
+
/** Narrower reload-all sweep, when restarting every mutable entry is too much. */
|
|
60
|
+
readonly reloadAllEntryIds?: () => ReadonlySet<string>
|
|
61
|
+
/**
|
|
62
|
+
* Resolves a bare module specifier from the profile's own module base (a
|
|
63
|
+
* profile's `node_modules`, where a user-installed bundle lives) - normally
|
|
64
|
+
* just `require.resolve`/`createRequire(...).resolve` bound to that base.
|
|
65
|
+
* Despite the parameter's own name, `createDshPluginLifecycleHost`'s
|
|
66
|
+
* internal caller always passes the full `"<packageName>/package.json"`
|
|
67
|
+
* specifier already, never the bare package name - do not re-append
|
|
68
|
+
* `/package.json` inside this callback (a real, reproduced bug: doing so
|
|
69
|
+
* throws `ERR_PACKAGE_PATH_NOT_EXPORTED` on a literal
|
|
70
|
+
* `package.json/package.json` subpath). Defaults to the context's base URL,
|
|
71
|
+
* which is the profile directory for a surface that boots the profile
|
|
72
|
+
* itself and is not for one whose root is elsewhere - the CLI composes the
|
|
73
|
+
* profile under its own engine host, so it passes the profile-resolving
|
|
74
|
+
* form explicitly.
|
|
75
|
+
*/
|
|
76
|
+
readonly resolvePackageJson?: (specifier: string) => string
|
|
77
|
+
/** Reports a best-effort failure that must not throw to its caller. */
|
|
78
|
+
readonly warn?: (message: string) => void
|
|
79
|
+
/** Profile-name rule, when this surface names profiles its own way. */
|
|
80
|
+
readonly validateProfileName?: ProfileNameValidator
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface BundleManifest {
|
|
84
|
+
readonly name?: unknown
|
|
85
|
+
readonly dsh?: { readonly bundle?: { readonly patch?: unknown } }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Build the host policy for one DSH profile.
|
|
90
|
+
*
|
|
91
|
+
* @param ctx - the context whose Loader tree is being steered and whose
|
|
92
|
+
* base URL resolves installed packages.
|
|
93
|
+
* @param options - which profile, and whatever this surface adds to the
|
|
94
|
+
* shared bundle policy.
|
|
95
|
+
*/
|
|
96
|
+
export function createDshPluginLifecycleHost(
|
|
97
|
+
ctx: Context,
|
|
98
|
+
options: DshPluginLifecycleOptions,
|
|
99
|
+
): PluginLifecycleHost {
|
|
100
|
+
const binName = options.binName ?? 'acryl'
|
|
101
|
+
const resolveManifest = options.resolvePackageJson
|
|
102
|
+
?? (ctx.baseUrl === undefined ? undefined : createRequire(ctx.baseUrl).resolve)
|
|
103
|
+
const resolvePackageJson = resolveManifest === undefined
|
|
104
|
+
? undefined
|
|
105
|
+
: (packageName: string) => resolveManifest(`${packageName}/package.json`)
|
|
106
|
+
const persistence: PluginLifecycleStatePersistence = {
|
|
107
|
+
profileName: options.profileName,
|
|
108
|
+
statePath: options.statePath,
|
|
109
|
+
...(options.validateProfileName === undefined
|
|
110
|
+
? {}
|
|
111
|
+
: { validateProfileName: options.validateProfileName }),
|
|
112
|
+
}
|
|
113
|
+
// Re-read on every mutation, never cached across one: a package manager
|
|
114
|
+
// writes `dsh.profile.bundles` milliseconds before it asks for a live mount.
|
|
115
|
+
let userBundleNames = readUserMutableBundleNames(options.profileDir)
|
|
116
|
+
|
|
117
|
+
const protectedReason = options.protectedReason ?? PROTECTED_PLUGIN_ENTRY_REASON
|
|
118
|
+
const warn = options.warn ?? ((message: string) => { ctx.logger?.warn?.(message) })
|
|
119
|
+
|
|
120
|
+
const isBundlePackage = (packageName: string): boolean => userBundleNames.has(packageName)
|
|
121
|
+
|
|
122
|
+
/** The `{ id, name }` a profile bundle inserts, read from its own patch. */
|
|
123
|
+
function bundleInsertRow(packageName: string): { readonly id: string; readonly name: string } {
|
|
124
|
+
if (resolvePackageJson === undefined) {
|
|
125
|
+
throw new PluginLifecycleError(
|
|
126
|
+
'lifecycle-failed',
|
|
127
|
+
'Package resolution is unavailable in this context.',
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
const packageDir = dirname(resolvePackageJson(packageName))
|
|
131
|
+
const manifest = JSON.parse(
|
|
132
|
+
readFileSync(join(packageDir, 'package.json'), 'utf8'),
|
|
133
|
+
) as BundleManifest
|
|
134
|
+
const patchRel = manifest.dsh?.bundle?.patch
|
|
135
|
+
if (typeof patchRel !== 'string') {
|
|
136
|
+
throw new PluginLifecycleError(
|
|
137
|
+
'lifecycle-failed',
|
|
138
|
+
`Package ${packageName} declares no dsh.bundle.patch.`,
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
const patches = loadOverlayPatches(binName, join(packageDir, patchRel)) as ReadonlyArray<{
|
|
142
|
+
readonly insert?: ReadonlyArray<{ readonly id?: unknown; readonly name?: unknown }>
|
|
143
|
+
}>
|
|
144
|
+
const row = patches.find(patch => Array.isArray(patch.insert))?.insert?.[0]
|
|
145
|
+
if (typeof row?.id !== 'string' || typeof row.name !== 'string') {
|
|
146
|
+
throw new PluginLifecycleError(
|
|
147
|
+
'lifecycle-failed',
|
|
148
|
+
`Package ${packageName} bundle patch has no insert row.`,
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
return { id: row.id, name: row.name }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
isMutable(entry: PluginLifecycleEntryRef): boolean {
|
|
156
|
+
if (entry.group) return false
|
|
157
|
+
if (options.mutableEntryIds?.().has(entry.entryId) === true) return true
|
|
158
|
+
return isBundlePackage(entry.moduleName)
|
|
159
|
+
},
|
|
160
|
+
protectedReason: () => protectedReason,
|
|
161
|
+
refresh(): void {
|
|
162
|
+
userBundleNames = readUserMutableBundleNames(options.profileDir)
|
|
163
|
+
},
|
|
164
|
+
async setEnabled(entryId: string, enabled: boolean): Promise<void> {
|
|
165
|
+
await setPluginLifecycleEntryEnabled(persistence, entryId, enabled)
|
|
166
|
+
// One store per row (spec 001 T089): a disable DSH's page once wrote into the profile patch would keep the row off.
|
|
167
|
+
if (enabled) await clearProfilePatchDisable(options.profileDir, entryPatchId(entryId))
|
|
168
|
+
},
|
|
169
|
+
bundleRow(packageName: string) {
|
|
170
|
+
if (!isBundlePackage(packageName)) {
|
|
171
|
+
throw new PluginLifecycleError(
|
|
172
|
+
'protected-entry',
|
|
173
|
+
`Package ${packageName} is not a profile bundle in the active profile.`,
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
return bundleInsertRow(packageName)
|
|
177
|
+
},
|
|
178
|
+
bundleGroup(): EntryGroup {
|
|
179
|
+
const sibling = [...ctx.loader.entries()]
|
|
180
|
+
.find(entry => !entry.options.group && entry.id.startsWith('include:'))
|
|
181
|
+
if (sibling === undefined) {
|
|
182
|
+
throw new PluginLifecycleError(
|
|
183
|
+
'lifecycle-failed',
|
|
184
|
+
'The profile include group is not available.',
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
return sibling.parent
|
|
188
|
+
},
|
|
189
|
+
warn,
|
|
190
|
+
...(options.afterDeactivate === undefined ? {} : { afterDeactivate: options.afterDeactivate }),
|
|
191
|
+
...(options.reloadAllEntryIds === undefined ? {} : { reloadAllEntryIds: options.reloadAllEntryIds }),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Build the lifecycle authority for one context: the one controller every
|
|
197
|
+
* surface drives. Publishes nothing, so a surface that composes its own
|
|
198
|
+
* capabilities (Desktop) can build it before deciding what to register.
|
|
199
|
+
*
|
|
200
|
+
* @param ctx - the context whose Loader tree it steers.
|
|
201
|
+
* @param options - that surface's DSH-profile lifecycle host options.
|
|
202
|
+
*/
|
|
203
|
+
export function createAcrylPluginLifecycle(
|
|
204
|
+
ctx: Context,
|
|
205
|
+
options: DshPluginLifecycleOptions,
|
|
206
|
+
): AcrPluginLifecycleController {
|
|
207
|
+
return new AcrPluginLifecycleController(ctx, createDshPluginLifecycleHost(ctx, options))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Publish that authority on `ctx.acrPluginLifecycle` for the caller's fiber
|
|
212
|
+
* lifetime. Every surface renders its own view of the snapshot; none of them
|
|
213
|
+
* re-implements enable, disable, or reload.
|
|
214
|
+
*
|
|
215
|
+
* @param ctx - the plugin context the service belongs to.
|
|
216
|
+
* @param options - that surface's DSH-profile lifecycle host options.
|
|
217
|
+
*/
|
|
218
|
+
export function mountAcrylPluginLifecycle(
|
|
219
|
+
ctx: Context,
|
|
220
|
+
options: DshPluginLifecycleOptions,
|
|
221
|
+
): AcrPluginLifecycleService {
|
|
222
|
+
return new AcrPluginLifecycleService(ctx, createAcrylPluginLifecycle(ctx, options))
|
|
223
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep a profile's recorded pnpm layout authoritative before any pnpm operation.
|
|
3
|
+
*
|
|
4
|
+
* A profile's `node_modules/.modules.yaml` records the `nodeLinker` and
|
|
5
|
+
* `publicHoistPattern` its dependencies were installed with. The profile's
|
|
6
|
+
* `pnpm-workspace.yaml` may say something else (a profile created by pnpm 9
|
|
7
|
+
* ignored `nodeLinker: hoisted`; pnpm >= 10 honors it). When they differ, pnpm
|
|
8
|
+
* silently relinks the whole tree - measured: a hoisted relink exposed stale
|
|
9
|
+
* top-level `@deepseek-ai/*` packages that shadowed the harness's and stopped
|
|
10
|
+
* the app from starting. Pinning the recorded values into the workspace file
|
|
11
|
+
* makes every pnpm (pinned 11.x, or whatever is on PATH) keep the layout that
|
|
12
|
+
* is already on disk. Only a deliberate, human-run reinstall changes layout.
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import { isMap, parse, parseDocument } from 'yaml'
|
|
17
|
+
|
|
18
|
+
const NODE_LINKERS = ['isolated', 'hoisted', 'pnp'] as const
|
|
19
|
+
type NodeLinker = (typeof NODE_LINKERS)[number]
|
|
20
|
+
|
|
21
|
+
/** Which profile a pnpm service operates on. */
|
|
22
|
+
export interface PnpmProfileConfig {
|
|
23
|
+
readonly name: string
|
|
24
|
+
readonly dir: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What a reconcile changed; empty when the workspace file already agreed. */
|
|
28
|
+
export interface LayoutChange {
|
|
29
|
+
readonly key: 'nodeLinker' | 'publicHoistPattern'
|
|
30
|
+
readonly from: unknown
|
|
31
|
+
readonly to: unknown
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface RecordedLayout {
|
|
35
|
+
readonly nodeLinker?: NodeLinker
|
|
36
|
+
readonly publicHoistPattern?: readonly string[]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function readRecorded(modulesFile: string): RecordedLayout {
|
|
40
|
+
let raw: unknown
|
|
41
|
+
try { raw = parse(readFileSync(modulesFile, 'utf8')) } catch { return {} }
|
|
42
|
+
if (raw === null || typeof raw !== 'object') return {}
|
|
43
|
+
const record = raw as Record<string, unknown>
|
|
44
|
+
const linker = NODE_LINKERS.find(value => value === record['nodeLinker'])
|
|
45
|
+
const pattern = record['publicHoistPattern']
|
|
46
|
+
return {
|
|
47
|
+
...(linker === undefined ? {} : { nodeLinker: linker }),
|
|
48
|
+
...(Array.isArray(pattern) && pattern.every(item => typeof item === 'string') ? { publicHoistPattern: pattern as string[] } : {}),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const sameList = (a: unknown, b: readonly string[]): boolean =>
|
|
53
|
+
Array.isArray(a) && a.length === b.length && a.every((item, index) => item === b[index])
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Pin the recorded `nodeLinker` / `publicHoistPattern` into the profile's `pnpm-workspace.yaml`.
|
|
57
|
+
* A profile with no installed `node_modules` (or no workspace file) has no layout to protect and is left alone.
|
|
58
|
+
* @returns the changes made (empty when nothing needed pinning)
|
|
59
|
+
*/
|
|
60
|
+
export function reconcileProfileLayout(profileDir: string): LayoutChange[] {
|
|
61
|
+
const modulesFile = join(profileDir, 'node_modules', '.modules.yaml')
|
|
62
|
+
const workspaceFile = join(profileDir, 'pnpm-workspace.yaml')
|
|
63
|
+
if (!existsSync(modulesFile) || !existsSync(workspaceFile)) return []
|
|
64
|
+
const recorded = readRecorded(modulesFile)
|
|
65
|
+
const document = parseDocument(readFileSync(workspaceFile, 'utf8'))
|
|
66
|
+
if (!isMap(document.contents)) return []
|
|
67
|
+
|
|
68
|
+
const changes: LayoutChange[] = []
|
|
69
|
+
if (recorded.nodeLinker !== undefined) {
|
|
70
|
+
const declared: unknown = document.get('nodeLinker') ?? 'isolated'
|
|
71
|
+
if (declared !== recorded.nodeLinker) {
|
|
72
|
+
changes.push({ key: 'nodeLinker', from: declared, to: recorded.nodeLinker })
|
|
73
|
+
document.set('nodeLinker', recorded.nodeLinker)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (recorded.publicHoistPattern !== undefined) {
|
|
77
|
+
const declared: unknown = document.get('publicHoistPattern')
|
|
78
|
+
// Absent means "pnpm's own default", which differs across majors (9: eslint/prettier, 12: empty).
|
|
79
|
+
if (!sameList(isMapValue(declared), recorded.publicHoistPattern)) {
|
|
80
|
+
changes.push({ key: 'publicHoistPattern', from: isMapValue(declared), to: recorded.publicHoistPattern })
|
|
81
|
+
document.set('publicHoistPattern', recorded.publicHoistPattern)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (changes.length === 0) return []
|
|
85
|
+
const temp = `${workspaceFile}.acryl-tmp`
|
|
86
|
+
writeFileSync(temp, document.toString())
|
|
87
|
+
renameSync(temp, workspaceFile)
|
|
88
|
+
return changes
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `document.get` returns a YAML node wrapper for collections; unwrap to plain JSON. */
|
|
92
|
+
function isMapValue(value: unknown): unknown {
|
|
93
|
+
if (value !== null && typeof value === 'object' && 'toJSON' in value && typeof value.toJSON === 'function') {
|
|
94
|
+
return (value as { toJSON(): unknown }).toJSON()
|
|
95
|
+
}
|
|
96
|
+
return value
|
|
97
|
+
}
|