@mearl/daemon-core 3.0.0-beta.8 → 3.0.0-beta.9

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/dist/command.js CHANGED
@@ -6,7 +6,16 @@ import { isProcessGroupAlive, isProcessOwnerAlive, processIdentity } from './pro
6
6
  const ownedCommands = new AsyncLocalStorage();
7
7
  /** Accepted installation commands retain process ownership until their complete process group exits. */
8
8
  export function withOwnedCommands(lifecycle, operation) {
9
- return ownedCommands.run(lifecycle, operation);
9
+ const parent = ownedCommands.getStore();
10
+ return ownedCommands.run(parent ? {
11
+ started(owner) { parent.started(owner); lifecycle.started(owner); },
12
+ finished(owner) { try {
13
+ lifecycle.finished(owner);
14
+ }
15
+ finally {
16
+ parent.finished(owner);
17
+ } },
18
+ } : lifecycle, operation);
10
19
  }
11
20
  export function isCommandProcessAlive(owner) {
12
21
  if (!owner.group || process.platform === 'win32')
@@ -0,0 +1,55 @@
1
+ import { type JsonObject, type CapabilityActivation, type ResolvedPreset } from '@mearl/preset';
2
+ import { type PreparedBundle, type PreparedPreset, type PresetSnapshot } from '@mearl/preset/bundles';
3
+ export interface PresetInstallReceipt {
4
+ schemaVersion: 1;
5
+ snapshot: PresetSnapshot;
6
+ bundles: Array<Omit<PreparedBundle, 'resources'>>;
7
+ browserRevision: string;
8
+ nodeRevision: string;
9
+ managedModules: string[];
10
+ nodeSyncRequired: boolean;
11
+ browserSyncRequired?: boolean;
12
+ overrides: JsonObject;
13
+ revision: string;
14
+ }
15
+ interface SelectionState {
16
+ rawHash: string | null;
17
+ activation?: CapabilityActivation;
18
+ receipt?: PresetInstallReceipt;
19
+ prepared?: PreparedPreset;
20
+ preset?: ResolvedPreset;
21
+ }
22
+ /** One pointer binds the desired preset, user overrides and exact Node selection. */
23
+ export declare class PresetInstallationStore {
24
+ readonly directory: string;
25
+ readonly mearlApiVersion: string;
26
+ private readonly pointer;
27
+ constructor(options?: {
28
+ directory?: string;
29
+ mearlApiVersion?: string;
30
+ });
31
+ private assertCurrent;
32
+ current(options?: {
33
+ verifyResources?: boolean;
34
+ }): Promise<SelectionState>;
35
+ apply(input: Pick<PreparedPreset, 'snapshot' | 'bundles'>, options: {
36
+ expectedRevision: string | null;
37
+ overrides?: JsonObject;
38
+ signal?: AbortSignal;
39
+ confirm?: () => Promise<void>;
40
+ }): Promise<PresetInstallReceipt>;
41
+ rollback(expectedRevision: string): Promise<void>;
42
+ collectGarbage(): Promise<void>;
43
+ private collectLocked;
44
+ }
45
+ export declare function presetSelectionRevision(state: SelectionState): string | null;
46
+ /** Reads accepted local metadata without loading capability factories, browsers or network sources. */
47
+ export declare function readInstallationManagement(options?: {
48
+ directory?: string;
49
+ }): Promise<{
50
+ setup: import("@mearl/preset").SetupManagement | undefined;
51
+ source: string | undefined;
52
+ revision: string | undefined;
53
+ }>;
54
+ export { setupManagementCommand, setupRuntimeCompatible } from '@mearl/preset';
55
+ export type { SetupManagement } from '@mearl/preset';
@@ -0,0 +1,260 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { constants, closeSync, fstatSync, lstatSync, linkSync, mkdirSync, openSync, readSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { withRecordLock } from './registry.js';
6
+ import { mergePresetDefaults, prepareNodeBundleSnapshot, prepareCapabilitySnapshot, verifyCapabilityActivation, resolveCapabilityConfig, MAX_CAPABILITY_SELECTION_BYTES, parseSetupManagement } from '@mearl/preset';
7
+ import { BundleError, MAX_BROWSER_STORAGE_BYTES, presetRequiresBrowser, validateBundleManifest, verifyPreset, verifyBrowserPreset, verifyPreparedPreset } from '@mearl/preset/bundles';
8
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
+ const hashPattern = /^[a-f0-9]{64}$/;
10
+ const MAX_RECEIPT_BYTES = 16 * 1024 * 1024;
11
+ const MAX_OVERRIDES_BYTES = 262_144;
12
+ const POINTER_BYTES = MAX_CAPABILITY_SELECTION_BYTES + 128;
13
+ function readBounded(file, limit) {
14
+ const before = lstatSync(file);
15
+ if (!before.isFile() || before.isSymbolicLink() || before.size > limit)
16
+ throw new Error('Invalid preset resource file or size');
17
+ const descriptor = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
18
+ try {
19
+ const stat = fstatSync(descriptor);
20
+ if (!stat.isFile() || stat.size > limit)
21
+ throw new Error('Invalid preset resource file or size');
22
+ const bytes = Buffer.alloc(Math.min(stat.size, limit) + 1);
23
+ let length = 0;
24
+ while (length < bytes.byteLength) {
25
+ const count = readSync(descriptor, bytes, length, bytes.byteLength - length, null);
26
+ if (count === 0)
27
+ break;
28
+ length += count;
29
+ }
30
+ if (length > stat.size)
31
+ throw new Error('Preset resource changed while reading');
32
+ return bytes.subarray(0, length);
33
+ }
34
+ finally {
35
+ closeSync(descriptor);
36
+ }
37
+ }
38
+ function optionalFile(file, limit) {
39
+ try {
40
+ return readBounded(file, limit);
41
+ }
42
+ catch (error) {
43
+ if (error.code === 'ENOENT')
44
+ return undefined;
45
+ throw error;
46
+ }
47
+ }
48
+ function atomicWrite(file, bytes) {
49
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
50
+ try {
51
+ writeFileSync(temporary, bytes, { flag: 'wx', mode: 0o600 });
52
+ renameSync(temporary, file);
53
+ }
54
+ finally {
55
+ rmSync(temporary, { force: true });
56
+ }
57
+ }
58
+ function revision(state) {
59
+ return state.activation?.installationRevision ?? (state.activation ? `node:${state.activation.revision}` : null);
60
+ }
61
+ function overrides(value) {
62
+ if (Object.hasOwn(value, 'management'))
63
+ throw new BundleError('BUNDLE_INVALID', 'Installation management cannot be overridden');
64
+ const accepted = mergePresetDefaults({}, value);
65
+ if (Buffer.byteLength(JSON.stringify(accepted)) > MAX_OVERRIDES_BYTES)
66
+ throw new BundleError('BUNDLE_QUOTA', 'User overrides exceed 256 KiB');
67
+ return accepted;
68
+ }
69
+ /** One pointer binds the desired preset, user overrides and exact Node selection. */
70
+ export class PresetInstallationStore {
71
+ directory;
72
+ mearlApiVersion;
73
+ pointer;
74
+ constructor(options = {}) {
75
+ this.directory = resolve(options.directory ?? (process.env.MEARL_CAPABILITY_DIR || join(homedir(), '.mearl/capabilities')));
76
+ this.mearlApiVersion = options.mearlApiVersion ?? '1.0.0';
77
+ this.pointer = join(this.directory, 'active-node.json');
78
+ }
79
+ assertCurrent(expected) {
80
+ const bytes = optionalFile(this.pointer, POINTER_BYTES);
81
+ if ((bytes ? digest(bytes) : null) !== expected)
82
+ throw new BundleError('BUNDLE_CONFLICT', 'The installed preset changed during preparation');
83
+ }
84
+ async current(options = {}) {
85
+ const raw = optionalFile(this.pointer, POINTER_BYTES);
86
+ if (!raw)
87
+ return { rawHash: null };
88
+ const rawHash = digest(raw);
89
+ const activation = await verifyCapabilityActivation(JSON.parse(raw.toString('utf8')));
90
+ if (!activation.installationRevision)
91
+ return { rawHash, activation };
92
+ const captured = withRecordLock(this.pointer, () => {
93
+ this.assertCurrent(rawHash);
94
+ const receiptBytes = readBounded(join(this.directory, 'installations', `${activation.installationRevision}.json`), MAX_RECEIPT_BYTES);
95
+ const receipt = JSON.parse(receiptBytes.toString('utf8'));
96
+ const { revision: receiptRevision, ...data } = receipt;
97
+ if (receiptRevision !== activation.installationRevision || digest(JSON.stringify(data)) !== receiptRevision || data.schemaVersion !== 1 ||
98
+ Object.keys(data).some(key => !['schemaVersion', 'snapshot', 'bundles', 'browserRevision', 'nodeRevision', 'managedModules', 'nodeSyncRequired', 'browserSyncRequired', 'overrides'].includes(key)) || typeof data.nodeSyncRequired !== 'boolean' || (data.browserSyncRequired !== undefined && typeof data.browserSyncRequired !== 'boolean') ||
99
+ data.nodeRevision !== activation.revision || !Array.isArray(data.bundles) || data.bundles.length > 64 ||
100
+ !Array.isArray(data.managedModules) || new Set(data.managedModules).size !== data.managedModules.length || data.managedModules.some(id => typeof id !== 'string' || !Object.hasOwn(activation.modules, id))) {
101
+ throw new BundleError('BUNDLE_INTEGRITY', 'Installed preset receipt does not match its selection');
102
+ }
103
+ const acceptedOverrides = overrides(data.overrides);
104
+ let total = 0;
105
+ const metadata = data.bundles.map(bundle => {
106
+ if (Object.keys(bundle).some(key => !['source', 'manifest', 'revision'].includes(key)))
107
+ throw new BundleError('BUNDLE_INVALID', 'Invalid installed package metadata');
108
+ const manifest = validateBundleManifest(bundle.manifest, this.mearlApiVersion);
109
+ total += Object.values(manifest.resources).reduce((sum, entry) => sum + entry.byteLength, 0);
110
+ return { ...bundle, manifest };
111
+ });
112
+ if (total > MAX_BROWSER_STORAGE_BYTES)
113
+ throw new BundleError('BUNDLE_QUOTA', 'Installed preset resources exceed 64 MiB');
114
+ const bundles = options.verifyResources === false ? [] : metadata.map(bundle => ({ ...bundle, resources: Object.fromEntries(Object.entries(bundle.manifest.resources).map(([name, entry]) => [name, readBounded(join(this.directory, 'blobs', `${entry.sha256}.bin`), entry.byteLength)])) }));
115
+ for (const entry of options.verifyResources === false ? [] : Object.values(activation.modules)) {
116
+ const bytes = readBounded(join(this.directory, 'objects', `${entry.sha256}.cjs`), entry.byteLength);
117
+ if (bytes.byteLength !== entry.byteLength || digest(bytes) !== entry.sha256)
118
+ throw new BundleError('BUNDLE_INTEGRITY', 'Installed Node object is missing or corrupt');
119
+ }
120
+ return { receipt: { ...receipt, overrides: acceptedOverrides }, bundles };
121
+ });
122
+ if (options.verifyResources === false) {
123
+ const graph = await verifyPreset(captured.receipt.snapshot, this.mearlApiVersion);
124
+ await verifyBrowserPreset({ source: graph.snapshot.source, manifests: graph.snapshot.manifests, packageTargets: graph.snapshot.packageTargets,
125
+ bundleRevisions: Object.fromEntries(Object.entries(graph.snapshot.bundleRevisions).filter(([id]) => graph.preset.packages[id].targets?.includes('browser'))), revision: captured.receipt.browserRevision }, this.mearlApiVersion);
126
+ return { rawHash, activation, receipt: captured.receipt, preset: graph.preset };
127
+ }
128
+ const prepared = await verifyPreparedPreset({ snapshot: captured.receipt.snapshot, bundles: captured.bundles }, this.mearlApiVersion);
129
+ if (prepared.browser.snapshot.revision !== captured.receipt.browserRevision)
130
+ throw new BundleError('BUNDLE_INTEGRITY', 'Installed browser projection does not match');
131
+ const selected = await prepareNodeBundleSnapshot(prepared.bundles.filter(bundle => prepared.preset.packages[bundle.manifest.id].targets?.includes('node')), 'native-host', this.mearlApiVersion, resolveCapabilityConfig(mergePresetDefaults(prepared.preset.defaults, captured.receipt.overrides)));
132
+ if (Object.keys(selected.snapshot.modules).length !== captured.receipt.managedModules.length || captured.receipt.managedModules.some(id => !Object.hasOwn(selected.snapshot.modules, id)) ||
133
+ Object.entries(selected.snapshot.modules).some(([id, entry]) => JSON.stringify(entry) !== JSON.stringify(activation.modules[id])) ||
134
+ Object.entries(selected.snapshot.bindings).some(([hook, entry]) => JSON.stringify(entry) !== JSON.stringify(activation.bindings[hook])) ||
135
+ Object.values(activation.bindings).filter(entry => captured.receipt.managedModules.includes(entry.module)).length !== Object.keys(selected.snapshot.bindings).length) {
136
+ throw new BundleError('BUNDLE_INTEGRITY', 'Installed managed Node selection does not match its packages');
137
+ }
138
+ return { rawHash, activation, prepared, receipt: captured.receipt, preset: prepared.preset };
139
+ }
140
+ async apply(input, options) {
141
+ options.signal?.throwIfAborted();
142
+ const acceptedOverrides = options.overrides === undefined ? undefined : overrides(options.overrides);
143
+ const [current, prepared] = await Promise.all([this.current({ verifyResources: false }), verifyPreparedPreset(input, this.mearlApiVersion)]);
144
+ if (revision(current) !== options.expectedRevision)
145
+ throw new BundleError('BUNDLE_CONFLICT', 'The installed preset changed');
146
+ const selected = await prepareNodeBundleSnapshot(prepared.bundles.filter(bundle => prepared.preset.packages[bundle.manifest.id].targets?.includes('node')), 'native-host', this.mearlApiVersion, resolveCapabilityConfig(mergePresetDefaults(prepared.preset.defaults, acceptedOverrides ?? current.receipt?.overrides ?? {})));
147
+ const previousManaged = new Set(current.receipt?.managedModules ?? []);
148
+ const unmanaged = Object.fromEntries(Object.entries(current.activation?.modules ?? {}).filter(([id]) => !previousManaged.has(id)));
149
+ for (const entry of Object.values(unmanaged)) {
150
+ const bytes = readBounded(join(this.directory, 'objects', `${entry.sha256}.cjs`), entry.byteLength);
151
+ if (bytes.byteLength !== entry.byteLength || digest(bytes) !== entry.sha256)
152
+ throw new BundleError('BUNDLE_INTEGRITY', 'An independent Node module is corrupt');
153
+ }
154
+ if (Object.keys(selected.snapshot.modules).some(id => Object.hasOwn(unmanaged, id)))
155
+ throw new BundleError('BUNDLE_CONFLICT', 'A preset module conflicts with an independently installed Node module');
156
+ const bindings = Object.fromEntries(Object.entries(current.activation?.bindings ?? {}).filter(([, entry]) => Object.hasOwn(unmanaged, entry.module)));
157
+ if (Object.keys(selected.snapshot.bindings).some(hook => Object.hasOwn(bindings, hook)))
158
+ throw new BundleError('BUNDLE_CONFLICT', 'A preset hook conflicts with an independently installed Node module');
159
+ const snapshot = await prepareCapabilitySnapshot({ schemaVersion: 1, modules: { ...unmanaged, ...selected.snapshot.modules }, bindings: { ...bindings, ...selected.snapshot.bindings } });
160
+ const data = {
161
+ schemaVersion: 1, snapshot: prepared.snapshot,
162
+ bundles: prepared.bundles.map(({ source, revision, manifest }) => ({ source, revision, manifest })),
163
+ browserRevision: prepared.browser.snapshot.revision, nodeRevision: snapshot.revision,
164
+ managedModules: Object.keys(selected.snapshot.modules), overrides: acceptedOverrides ?? current.receipt?.overrides ?? {},
165
+ nodeSyncRequired: Boolean(current.receipt?.nodeSyncRequired || current.receipt?.managedModules.length || Object.values(prepared.preset.packages).some(entry => entry.enabled !== false && entry.targets?.includes('node'))),
166
+ browserSyncRequired: Boolean(current.receipt?.browserSyncRequired || presetRequiresBrowser(prepared.preset)),
167
+ };
168
+ const receipt = { ...data, revision: digest(JSON.stringify(data)) };
169
+ const receiptBytes = JSON.stringify(receipt);
170
+ if (Buffer.byteLength(receiptBytes) > MAX_RECEIPT_BYTES)
171
+ throw new BundleError('BUNDLE_QUOTA', 'Preset installation receipt exceeds 16 MiB');
172
+ const activation = { ...snapshot, installationRevision: receipt.revision };
173
+ await options.confirm?.();
174
+ withRecordLock(this.pointer, () => {
175
+ this.assertCurrent(current.rawHash);
176
+ options.signal?.throwIfAborted();
177
+ for (const child of ['blobs', 'objects', 'installations'])
178
+ mkdirSync(join(this.directory, child), { recursive: true, mode: 0o700 });
179
+ for (const bundle of prepared.bundles)
180
+ for (const [name, entry] of Object.entries(bundle.manifest.resources)) {
181
+ atomicWrite(join(this.directory, 'blobs', `${entry.sha256}.bin`), bundle.resources[name]);
182
+ }
183
+ for (const entry of Object.values(selected.snapshot.modules)) {
184
+ const destination = join(this.directory, 'objects', `${entry.sha256}.cjs`);
185
+ const temporary = `${destination}.${randomUUID()}.tmp`;
186
+ try {
187
+ linkSync(join(this.directory, 'blobs', `${entry.sha256}.bin`), temporary);
188
+ renameSync(temporary, destination);
189
+ }
190
+ finally {
191
+ rmSync(temporary, { force: true });
192
+ }
193
+ }
194
+ atomicWrite(join(this.directory, 'installations', `${receipt.revision}.json`), receiptBytes);
195
+ if (current.receipt?.revision !== receipt.revision)
196
+ atomicWrite(join(this.directory, 'rollback.json'), JSON.stringify({ candidate: receipt.revision, previous: current.activation ?? null }));
197
+ atomicWrite(this.pointer, JSON.stringify(activation));
198
+ });
199
+ return receipt;
200
+ }
201
+ async rollback(expectedRevision) {
202
+ const current = await this.current({ verifyResources: false });
203
+ if (current.activation?.installationRevision !== expectedRevision)
204
+ throw new BundleError('BUNDLE_CONFLICT', 'A newer preset installation cannot be rolled back');
205
+ const record = JSON.parse(readBounded(join(this.directory, 'rollback.json'), POINTER_BYTES + 256).toString('utf8'));
206
+ if (record.candidate !== expectedRevision)
207
+ throw new BundleError('BUNDLE_CONFLICT', 'The preset rollback record has changed');
208
+ const previous = record.previous === null ? undefined : await verifyCapabilityActivation(record.previous);
209
+ withRecordLock(this.pointer, () => {
210
+ this.assertCurrent(current.rawHash);
211
+ if (previous)
212
+ atomicWrite(this.pointer, JSON.stringify(previous));
213
+ else
214
+ rmSync(this.pointer, { force: true });
215
+ rmSync(join(this.directory, 'rollback.json'), { force: true });
216
+ this.collectLocked(previous);
217
+ });
218
+ }
219
+ async collectGarbage() {
220
+ const current = await this.current({ verifyResources: false });
221
+ const raw = optionalFile(join(this.directory, 'rollback.json'), POINTER_BYTES + 256);
222
+ const record = raw && JSON.parse(raw.toString('utf8'));
223
+ const previous = record?.candidate === current.activation?.installationRevision && record.previous !== null ? await verifyCapabilityActivation(record.previous) : undefined;
224
+ withRecordLock(this.pointer, () => {
225
+ this.assertCurrent(current.rawHash);
226
+ for (const child of ['blobs', 'objects', 'installations'])
227
+ mkdirSync(join(this.directory, child), { recursive: true, mode: 0o700 });
228
+ this.collectLocked(current.activation, previous);
229
+ });
230
+ }
231
+ collectLocked(active, previous) {
232
+ const receipts = new Set([active?.installationRevision, previous?.installationRevision].filter((value) => Boolean(value)));
233
+ const blobs = new Set();
234
+ const modules = new Set([active, previous].flatMap(selection => Object.values(selection?.modules ?? {}).map(entry => entry.sha256)));
235
+ for (const id of receipts) {
236
+ const record = JSON.parse(readBounded(join(this.directory, 'installations', `${id}.json`), MAX_RECEIPT_BYTES).toString('utf8'));
237
+ for (const bundle of record.bundles)
238
+ for (const entry of Object.values(bundle.manifest.resources))
239
+ blobs.add(entry.sha256);
240
+ }
241
+ for (const [directory, extension, retained] of [['blobs', '.bin', blobs], ['objects', '.cjs', modules], ['installations', '.json', receipts]]) {
242
+ for (const name of readdirSync(join(this.directory, directory))) {
243
+ const id = name.slice(0, -extension.length);
244
+ if (name.endsWith(extension) && hashPattern.test(id) && !retained.has(id))
245
+ rmSync(join(this.directory, directory, name), { force: true });
246
+ }
247
+ }
248
+ }
249
+ }
250
+ export function presetSelectionRevision(state) { return revision(state); }
251
+ /** Reads accepted local metadata without loading capability factories, browsers or network sources. */
252
+ export async function readInstallationManagement(options = {}) {
253
+ const current = await new PresetInstallationStore(options).current({ verifyResources: false });
254
+ return {
255
+ setup: parseSetupManagement(current.preset?.defaults.management),
256
+ source: current.receipt?.snapshot.source,
257
+ revision: current.receipt?.revision,
258
+ };
259
+ }
260
+ export { setupManagementCommand, setupRuntimeCompatible } from '@mearl/preset';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mearl/daemon-core",
3
- "version": "3.0.0-beta.8",
3
+ "version": "3.0.0-beta.9",
4
4
  "description": "Shared Node daemon lifecycle primitives for Mearl — process liveness, JSON record registry, log rotation, and a detached daemon manager",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -14,6 +14,10 @@
14
14
  "types": "./dist/node-capabilities.d.ts",
15
15
  "import": "./dist/node-capabilities.js"
16
16
  },
17
+ "./installation": {
18
+ "types": "./dist/preset-installation.d.ts",
19
+ "import": "./dist/preset-installation.js"
20
+ },
17
21
  "./page-runtimes": {
18
22
  "types": "./dist/page-runtimes.d.ts",
19
23
  "import": "./dist/page-runtimes.js"
@@ -39,7 +43,7 @@
39
43
  "typescript": "^5.8.3"
40
44
  },
41
45
  "dependencies": {
42
- "@mearl/preset": "3.0.0-beta.8"
46
+ "@mearl/preset": "3.0.0-beta.9"
43
47
  },
44
48
  "repository": {
45
49
  "type": "git",