@acryldev/manifest 0.0.0-stage → 0.1.1

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/lock.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `npm run lock`: write `blend.lock.json` (formatVersion 3, the lock ACRYL writes too) next to the manifest, recording what the app is
3
+ * built from: the manifest's identity and digest, the Blueprint it was resolved over, its resolved parameters and rows, and a content
4
+ * digest of every plugin folder in `plugins/`. Commit it; a diff of the lock is a review of
5
+ * what changed.
6
+ */
7
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
8
+ import { join, resolve } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import {
11
+ type BlendDocument,
12
+ type BlendLock,
13
+ digestFolder,
14
+ generateBlendLock,
15
+ type LockModule,
16
+ manifestDigest,
17
+ parseDefinition,
18
+ resolveDefinition,
19
+ } from '@acryldev/blends-core'
20
+ import { pluginEntry } from './app-plugins.ts'
21
+ import { blueprintsIn } from './index.ts'
22
+
23
+ export const LOCK_FILE = 'blend.lock.json'
24
+
25
+ type LockV3 = Extract<BlendLock, { formatVersion: 3 }>
26
+
27
+ function read(file: string): { text: string; document: BlendDocument } {
28
+ const text = readFileSync(file, 'utf8')
29
+ const { document, diagnostics } = parseDefinition(text)
30
+ if (diagnostics.length > 0)
31
+ throw new Error(`${file}:\n${diagnostics.map((d) => `${d.path}: ${d.message}`).join('\n')}`)
32
+ return { text, document: document as BlendDocument }
33
+ }
34
+
35
+ /**
36
+ * A plugin folder's plugin name, as its entry file declares it (`export const name = '...'`): the library copies keep their pre-T038 plugin names
37
+ * while their folders are the scoped packages' short names (spec 051 T038), so the folder alone no longer names the module a row mounts. A folder
38
+ * without a readable name keeps its folder name, which is the app plugins' contract.
39
+ */
40
+ function moduleNameOf(directory: string, folderName: string): string {
41
+ const entry = pluginEntry(directory)
42
+ if (entry === undefined) return folderName
43
+ try {
44
+ const match = /export const name = '([^']+)'/u.exec(readFileSync(entry, 'utf8'))
45
+ return match?.[1] ?? folderName
46
+ } catch {
47
+ return folderName
48
+ }
49
+ }
50
+
51
+ function localModules(appRoot: string, folder: string): LockModule[] {
52
+ const directory = join(appRoot, folder)
53
+ if (!existsSync(directory)) return []
54
+ return readdirSync(directory, { withFileTypes: true })
55
+ .filter((entry) => entry.isDirectory())
56
+ .map((entry) => ({
57
+ name: moduleNameOf(join(directory, entry.name), entry.name),
58
+ origin: 'local' as const,
59
+ digest: `sha256:${digestFolder(join(directory, entry.name))}`,
60
+ source: `${folder}/${entry.name}`,
61
+ }))
62
+ }
63
+
64
+ export function writeLock(appRoot: string): LockV3 {
65
+ const blendFile = join(appRoot, 'blend.yaml')
66
+ const getBlueprint = blueprintsIn(join(appRoot, 'blueprints'))
67
+ const { text, document } = read(blendFile)
68
+ const resolved = resolveDefinition(document, {
69
+ getDefinition: (id) => {
70
+ const file = getBlueprint(id)
71
+ return file === undefined ? undefined : read(file).document
72
+ },
73
+ })
74
+ if (resolved.definition === null)
75
+ throw new Error(
76
+ `${blendFile}:\n${resolved.diagnostics.map((d) => `${d.path}: ${d.message}`).join('\n')}`,
77
+ )
78
+ // A Blend records the Blueprint file it was resolved over, so an upgrade shows up as a lock diff.
79
+ const lineage = document.spec.lineage
80
+ const blueprintFile = lineage ? getBlueprint(lineage.blueprint) : undefined
81
+ const { lock } = generateBlendLock({
82
+ resolved: resolved.definition,
83
+ origin: {
84
+ id: document.metadata.id,
85
+ kind: document.kind,
86
+ version: document.metadata.version,
87
+ digest: manifestDigest(text),
88
+ },
89
+ modules: [
90
+ ...localModules(appRoot, 'plugins'),
91
+ ...localModules(appRoot, 'src/plugins'),
92
+ ...localModules(appRoot, 'extensions'),
93
+ ],
94
+ ...(lineage
95
+ ? {
96
+ lineage: {
97
+ ...lineage,
98
+ ...(blueprintFile
99
+ ? { digest: manifestDigest(readFileSync(blueprintFile, 'utf8')) }
100
+ : {}),
101
+ },
102
+ }
103
+ : {}),
104
+ })
105
+ writeFileSync(join(appRoot, LOCK_FILE), `${JSON.stringify(lock, null, 2)}\n`)
106
+ return lock as LockV3
107
+ }
108
+
109
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
110
+ const appRoot = resolve(fileURLToPath(new URL('../..', import.meta.url)))
111
+ const locked = writeLock(appRoot)
112
+ console.log(
113
+ `wrote ${LOCK_FILE}: ${locked.rows.length} rows, ${locked.modules.length} local plugins`,
114
+ )
115
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@acryldev/manifest",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "The app as data: blend.yaml lists ordered plugin rows with config, parameters and on/off switches; validated, composed and locked.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/acryldev/acryl.git",
9
+ "directory": "plugins/manifest"
10
+ },
11
+ "homepage": "https://github.com/acryldev/acryl/tree/main/plugins/manifest#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/acryldev/acryl/issues"
14
+ },
15
+ "type": "module",
16
+ "engines": {
17
+ "node": "^22.19.0 || >=24.0.0"
18
+ },
19
+ "main": "./lib/index.js",
20
+ "types": "./lib/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./lib/types/index.d.ts",
24
+ "default": "./lib/index.js"
25
+ },
26
+ "./lock": {
27
+ "types": "./lib/types/lock.d.ts",
28
+ "default": "./lib/lock.js"
29
+ },
30
+ "./snapshot": {
31
+ "types": "./lib/types/snapshot.d.ts",
32
+ "default": "./lib/snapshot.js"
33
+ },
34
+ "./app-plugins": {
35
+ "types": "./lib/types/app-plugins.d.ts",
36
+ "default": "./lib/app-plugins.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "dependencies": {
41
+ "yaml": "2.9.0",
42
+ "@acryldev/blends-core": "^0.6.0"
43
+ },
44
+ "peerDependencies": {
45
+ "@deepseek-ai/cordis": "^4.0.2"
46
+ },
47
+ "devDependencies": {
48
+ "@deepseek-ai/cordis": "4.0.4",
49
+ "@types/node": "^22.20.0",
50
+ "ajv": "^8.20.0",
51
+ "tsdown": "0.22.2",
52
+ "typescript": "6.0.3"
53
+ },
54
+ "scripts": {
55
+ "build": "tsdown && tsc -p tsconfig.json --emitDeclarationOnly"
56
+ }
6
57
  }
package/plugin.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "manifest",
3
+ "description": "The app as data: blend.yaml lists ordered plugin rows with config, parameters and on/off switches; validated, composed and locked.",
4
+ "requires": [],
5
+ "inject": [],
6
+ "provides": [],
7
+ "dependencies": {
8
+ "@deepseek-ai/cordis": "4.0.4",
9
+ "yaml": "2.9.0",
10
+ "@acryldev/blends-core": "0.6.0"
11
+ },
12
+ "mount": "in src/app.ts: const manifest = loadManifest(join(chosen.root, 'blend.yaml')); await compose(root, manifest, registry)",
13
+ "entries": {
14
+ "": "index.ts",
15
+ "/lock": "lock.ts",
16
+ "/snapshot": "snapshot.ts",
17
+ "/app-plugins": "app-plugins.ts"
18
+ }
19
+ }
package/snapshot.ts ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The snapshot verbs: an app folder is its own Blend (`blend.yaml` + `plugins/` + `blend.lock.json`), and these keep it one that can be passed on.
3
+ * Ported from ACRYL's Extension Context Pack (`plugins/plugin-context/lib/blend-capture.js` `captureApp`/`verifyBlend` and
4
+ * `lib/blend-apply.js` `applyBlend`), for an app whose plugins are folders rather than packages installed into a DSH profile.
5
+ *
6
+ * - `captureApp` records the app as it runs: every plugin folder of its own gets a row in `blend.yaml` if it has none yet (a live install becomes
7
+ * part of the composition), the person's text and comments are kept, and `blend.lock.json` is written again (lock.ts).
8
+ * - `verifyApp` checks a snapshot against its own lock, offline: `blend.yaml` still has the digest the lock recorded, and every plugin folder the
9
+ * lock names still hashes to its digest.
10
+ * - `applySnapshot` brings a snapshot into an app: it verifies the snapshot first, refuses the whole apply when a plugin folder of the same name
11
+ * in the app differs from the locked one (somebody's work is never overwritten), then copies the missing folders, writes the snapshot's
12
+ * `blend.yaml` under the app's own `metadata` (its rows come in, its identity stays the app's) and locks
13
+ * the app again. A running app reloads from the change. A plugin folder the snapshot does not have is left where it is, put on the
14
+ * `extensions` row's `off` list so it does not start, and reported.
15
+ *
16
+ * Not ported: ACRYL's registry and pulled modules (an app's lock records local folders only) and its evolution ledger (an app's history is its git
17
+ * versions).
18
+ *
19
+ * node plugins/manifest/snapshot.ts capture | verify [dir] | apply <snapshot dir>
20
+ */
21
+ import { cpSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
22
+ import { basename, join, resolve } from 'node:path'
23
+ import { fileURLToPath } from 'node:url'
24
+ import { digestFolder, FOLDER_DIGEST_SKIPPED, manifestDigest } from '@acryldev/blends-core'
25
+ import { isSeq, parseDocument } from 'yaml'
26
+ import { appPluginNames } from './app-plugins.ts'
27
+ import { LOCK_FILE, writeLock } from './lock.ts'
28
+
29
+ const MANIFEST = 'blend.yaml'
30
+ /** Where a lock may place a plugin folder: one level inside the app's plugin folders, never outside the app. */
31
+ const MODULE_SOURCE = /^(plugins|src\/plugins|extensions)\/[a-z0-9][a-z0-9._-]*$/
32
+
33
+ interface LockedModule {
34
+ readonly name: string
35
+ readonly origin: string
36
+ readonly digest?: string
37
+ readonly source?: string
38
+ }
39
+
40
+ interface LockShape {
41
+ readonly formatVersion?: unknown
42
+ readonly origin?: { readonly digest?: unknown }
43
+ readonly modules?: readonly LockedModule[]
44
+ }
45
+
46
+ export interface CaptureResult {
47
+ /** The rows added to `blend.yaml`, one per plugin folder that had none. */
48
+ readonly addedRows: readonly string[]
49
+ /** How many plugin folders the lock records. */
50
+ readonly modules: number
51
+ }
52
+
53
+ export interface VerifyResult {
54
+ readonly ok: boolean
55
+ readonly problems: readonly string[]
56
+ /** The manifest digest and each plugin folder checked. */
57
+ readonly checked: number
58
+ }
59
+
60
+ export type ApplyStatus = 'added' | 'unchanged' | 'conflict' | 'skipped'
61
+
62
+ export interface ApplyResult {
63
+ readonly ok: boolean
64
+ /** Why nothing was applied: the snapshot does not match its lock, or a folder in the app differs from the locked one. */
65
+ readonly problems: readonly string[]
66
+ readonly modules: ReadonlyArray<{
67
+ readonly name: string
68
+ readonly status: ApplyStatus
69
+ readonly detail?: string
70
+ }>
71
+ readonly manifestChanged: boolean
72
+ /** The app's own plugin folders the snapshot does not have: left in place, and put on the `extensions` row's `off` list so they do not start. */
73
+ readonly extra: readonly string[]
74
+ }
75
+
76
+ /** Replace a file in one step: a reader sees the old text or the new, never half of it. */
77
+ function writeAtomic(file: string, text: string): void {
78
+ writeFileSync(`${file}.tmp`, text)
79
+ renameSync(`${file}.tmp`, file)
80
+ }
81
+
82
+ const folderDigest = (dir: string): string => `sha256:${digestFolder(dir)}`
83
+
84
+ /** The plugin names `blend.yaml`'s rows mount (`name`, the folder a row loads). */
85
+ function rowNames(text: string): Set<string> {
86
+ const rows = parseDocument(text).toJS()?.spec?.rows
87
+ return new Set(
88
+ Array.isArray(rows) ? rows.map((row: { name?: unknown }) => String(row?.name)) : [],
89
+ )
90
+ }
91
+
92
+ /**
93
+ * Record the app as it runs: a row for every plugin folder of its own that has none (before the `extensions` row, else before the server, else
94
+ * last), then `blend.lock.json`. Idempotent: a second capture with nothing new changes nothing in `blend.yaml`.
95
+ */
96
+ export function captureApp(appRoot: string): CaptureResult {
97
+ const file = join(appRoot, MANIFEST)
98
+ const text = readFileSync(file, 'utf8')
99
+ const named = rowNames(text)
100
+ const missing = appPluginNames(join(appRoot, 'plugins')).filter((name) => !named.has(name))
101
+ if (missing.length > 0) {
102
+ const document = parseDocument(text)
103
+ const rows = document.getIn(['spec', 'rows'])
104
+ if (!isSeq(rows)) throw new Error(`${file} has no spec.rows list; it is not an app definition`)
105
+ const names = rows.items.map((row) =>
106
+ String((row as { get?: (key: string) => unknown }).get?.('name')),
107
+ )
108
+ const before =
109
+ names.indexOf('extensions') >= 0
110
+ ? names.indexOf('extensions')
111
+ : names.indexOf('acryl-node-server')
112
+ const at = before >= 0 ? before : rows.items.length
113
+ rows.items.splice(at, 0, ...missing.map((name) => document.createNode({ id: name, name })))
114
+ writeAtomic(file, String(document))
115
+ }
116
+ const lock = writeLock(appRoot)
117
+ return { addedRows: missing, modules: lock.modules.length }
118
+ }
119
+
120
+ /** Check a snapshot (an app folder, or a copy of one) against its own `blend.lock.json`. */
121
+ export function verifyApp(dir: string): VerifyResult {
122
+ const manifestFile = join(dir, MANIFEST)
123
+ const lockFile = join(dir, LOCK_FILE)
124
+ if (!existsSync(manifestFile) || !existsSync(lockFile))
125
+ return { ok: false, problems: [`no ${MANIFEST} and ${LOCK_FILE} in ${dir}`], checked: 0 }
126
+ let lock: LockShape
127
+ try {
128
+ lock = JSON.parse(readFileSync(lockFile, 'utf8')) as LockShape
129
+ } catch {
130
+ return { ok: false, problems: [`${LOCK_FILE} is not valid JSON`], checked: 0 }
131
+ }
132
+ const problems: string[] = []
133
+ if (lock.formatVersion !== 3)
134
+ problems.push(`${LOCK_FILE} formatVersion ${String(lock.formatVersion)} is not 3`)
135
+ let checked = 1
136
+ if (lock.origin?.digest !== manifestDigest(readFileSync(manifestFile, 'utf8')))
137
+ problems.push(
138
+ `${MANIFEST} changed since the lock was written (its digest no longer matches): capture again`,
139
+ )
140
+ for (const module of lock.modules ?? []) {
141
+ if (module.origin !== 'local') continue
142
+ checked += 1
143
+ if (module.source === undefined || !MODULE_SOURCE.test(module.source)) {
144
+ problems.push(
145
+ `${module.name}: the lock places it at ${String(module.source)}, which is not a plugin folder of the app`,
146
+ )
147
+ continue
148
+ }
149
+ const folder = join(dir, module.source)
150
+ if (!existsSync(folder)) problems.push(`${module.name}: ${module.source} is missing`)
151
+ else if (folderDigest(folder) !== module.digest)
152
+ problems.push(
153
+ `${module.name}: ${module.source} differs from the locked digest (edited after the capture)`,
154
+ )
155
+ }
156
+ return { ok: problems.length === 0, problems, checked }
157
+ }
158
+
159
+ /**
160
+ * The snapshot's `blend.yaml` with the app's own `metadata` (its id, name, version and visibility): a snapshot brings its composition, and the app
161
+ * it is applied to stays the app it is. An app with no `blend.yaml` yet takes the snapshot's whole.
162
+ */
163
+ function keepIdentity(text: string, current: string | undefined): string {
164
+ if (current === undefined) return text
165
+ const own = parseDocument(current).get('metadata', true)
166
+ if (own === undefined) return text
167
+ const document = parseDocument(text)
168
+ document.set('metadata', own)
169
+ return String(document)
170
+ }
171
+
172
+ /**
173
+ * `blend.yaml` with `names` on the `extensions` row's `off` list: the row starts every plugin folder that has no row of its own, and a folder the
174
+ * snapshot does not have must stay where it is without starting. Without an `extensions` row no such folder starts, and the text is unchanged.
175
+ */
176
+ function keepOff(text: string, names: readonly string[]): string {
177
+ if (names.length === 0) return text
178
+ const document = parseDocument(text)
179
+ const rows = document.getIn(['spec', 'rows'])
180
+ if (!isSeq(rows)) return text
181
+ const row = rows.items.find(
182
+ (item) => (item as { get?: (key: string) => unknown }).get?.('name') === 'extensions',
183
+ ) as { getIn(path: string[]): unknown; setIn(path: string[], value: unknown): void } | undefined
184
+ if (row === undefined) return text
185
+ const listed = row.getIn(['config', 'off']) as { toJSON?: () => unknown } | undefined
186
+ const before = Array.isArray(listed?.toJSON?.()) ? (listed?.toJSON?.() as string[]) : []
187
+ row.setIn(['config', 'off'], document.createNode([...new Set([...before, ...names])].sort()))
188
+ return String(document)
189
+ }
190
+
191
+ /** Bring the snapshot in `from` into the app at `appRoot` (see the file's doc). Nothing is written unless the whole apply can go through. */
192
+ export function applySnapshot(from: string, appRoot: string): ApplyResult {
193
+ const verified = verifyApp(from)
194
+ const none = { modules: [], manifestChanged: false, extra: [] }
195
+ if (!verified.ok) return { ok: false, problems: verified.problems, ...none }
196
+ const lock = JSON.parse(readFileSync(join(from, LOCK_FILE), 'utf8')) as LockShape
197
+ const modules: Array<{ name: string; status: ApplyStatus; detail?: string; source?: string }> = []
198
+ for (const module of lock.modules ?? []) {
199
+ if (module.origin !== 'local' || module.source === undefined) {
200
+ modules.push({
201
+ name: module.name,
202
+ status: 'skipped',
203
+ detail: `origin "${module.origin}" is not a plugin folder; add it yourself`,
204
+ })
205
+ continue
206
+ }
207
+ const target = join(appRoot, module.source)
208
+ if (!existsSync(target))
209
+ modules.push({ name: module.name, status: 'added', source: module.source })
210
+ else if (folderDigest(target) === module.digest)
211
+ modules.push({ name: module.name, status: 'unchanged' })
212
+ else
213
+ modules.push({
214
+ name: module.name,
215
+ status: 'conflict',
216
+ detail: `${module.source} in the app differs from the snapshot's; move it away or capture the app first`,
217
+ })
218
+ }
219
+ const conflicts = modules.filter((module) => module.status === 'conflict')
220
+ const report = modules.map(({ source: _, ...module }) => module)
221
+ if (conflicts.length > 0)
222
+ return {
223
+ ok: false,
224
+ problems: conflicts.map((module) => `${module.name}: ${module.detail}`),
225
+ modules: report,
226
+ manifestChanged: false,
227
+ extra: [],
228
+ }
229
+ for (const module of modules)
230
+ if (module.status === 'added' && module.source !== undefined)
231
+ cpSync(join(from, module.source), join(appRoot, module.source), {
232
+ recursive: true,
233
+ filter: (path) => !FOLDER_DIGEST_SKIPPED.has(basename(path)),
234
+ })
235
+ const locked = new Set((lock.modules ?? []).map((module) => module.name))
236
+ const extra = appPluginNames(join(appRoot, 'plugins')).filter((name) => !locked.has(name))
237
+ const current = existsSync(join(appRoot, MANIFEST))
238
+ ? readFileSync(join(appRoot, MANIFEST), 'utf8')
239
+ : undefined
240
+ const manifest = keepOff(keepIdentity(readFileSync(join(from, MANIFEST), 'utf8'), current), extra)
241
+ const manifestChanged = current !== manifest
242
+ if (manifestChanged) writeAtomic(join(appRoot, MANIFEST), manifest)
243
+ writeLock(appRoot)
244
+ return { ok: true, problems: [], modules: report, manifestChanged, extra }
245
+ }
246
+
247
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
248
+ const appRoot = resolve(fileURLToPath(new URL('../..', import.meta.url)))
249
+ const [verb, target] = process.argv.slice(2)
250
+ if (verb === 'capture') {
251
+ const { addedRows, modules } = captureApp(appRoot)
252
+ console.log(
253
+ `captured: ${modules} plugin folder(s) locked${addedRows.length > 0 ? `; rows added to blend.yaml: ${addedRows.join(', ')}` : ''}`,
254
+ )
255
+ } else if (verb === 'verify') {
256
+ const result = verifyApp(resolve(target ?? appRoot))
257
+ console.log(result.ok ? `ok: ${result.checked} checked` : result.problems.join('\n'))
258
+ process.exitCode = result.ok ? 0 : 1
259
+ } else if (verb === 'apply' && target !== undefined) {
260
+ const result = applySnapshot(resolve(target), appRoot)
261
+ for (const module of result.modules)
262
+ console.log(`${module.status}: ${module.name}${module.detail ? ` (${module.detail})` : ''}`)
263
+ if (result.manifestChanged)
264
+ console.log("blend.yaml: the snapshot's rows, under this app's own metadata")
265
+ if (result.extra.length > 0)
266
+ console.log(`left in place, not in the snapshot: ${result.extra.join(', ')}`)
267
+ if (!result.ok) console.error(`nothing applied:\n${result.problems.join('\n')}`)
268
+ process.exitCode = result.ok ? 0 : 1
269
+ } else {
270
+ console.error(
271
+ 'usage: node plugins/manifest/snapshot.ts capture | verify [dir] | apply <snapshot dir>',
272
+ )
273
+ process.exitCode = 2
274
+ }
275
+ }