@rig-c/parts 2.41.0 → 2.43.0

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.
@@ -5,7 +5,7 @@
5
5
  import { closeSync, fchmodSync, linkSync, mkdirSync, lstatSync, openSync, readFileSync, realpathSync, statSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
6
  import { randomBytes } from 'node:crypto';
7
7
  import { basename, dirname, join, resolve } from 'node:path';
8
- import { loadConfigAndAnimations, loadEarlyConfig, repeatedKeys } from '../src/config.ts';
8
+ import { loadConfigAndAnimations, loadEarlyConfig, parseConfig, parseEarlyConfig, repeatedKeys } from '../src/config.ts';
9
9
  import { mergeConfigProposal, type ConfigWriteChange, type ConfigWritePatch } from '../src/configwrite.ts';
10
10
  import { PartsError, type Problem } from '../src/errors.ts';
11
11
  import { splicedEdits } from '../src/meshdraft.ts';
@@ -18,6 +18,8 @@ export interface ConfigWriteFiles {
18
18
  replace?: (from: string, to: string) => void;
19
19
  remove?: (path: string) => void;
20
20
  publish?: (from: string, to: string) => void;
21
+ /** Batch rollback is independent of the replacement failure being controlled. */
22
+ restore?: (from: string, to: string) => void;
21
23
  }
22
24
  export interface StagedConfigWrite {
23
25
  changes: readonly ConfigWriteChange[];
@@ -201,3 +203,83 @@ export function stageConfigWrite(target: ConfigWriteTarget | FreshConfigWrite, p
201
203
  export function configWriteLines(target: ConfigWriteTarget, changes: readonly ConfigWriteChange[]): string[] {
202
204
  return changes.length === 0 ? [`config ${target.path}: unchanged`] : changes.map((c) => `config ${target.path}: ${c.kind} ${c.path}${c.value === undefined ? '' : ` ${c.value}`}`);
203
205
  }
206
+
207
+ export interface ConfigWriteRequest { target: ConfigWriteTarget; patch: ConfigWritePatch }
208
+ export interface StagedConfigWriteBatch {
209
+ writes: ReadonlyArray<{ target: ConfigWriteTarget; changes: readonly ConfigWriteChange[] }>;
210
+ commit(): void;
211
+ cancel(): void;
212
+ }
213
+ /** Existing configs only: every candidate stages through stageConfigWrite before
214
+ * any destination commits. A later commit failure restores earlier originals.
215
+ * Backups whose restoration fails are retained and named, never deleted.
216
+ */
217
+ export function stageConfigWriteBatch(requests: readonly ConfigWriteRequest[], files: ConfigWriteFiles = {}): StagedConfigWriteBatch {
218
+ const entries: Array<{ target: ConfigWriteTarget; staged: StagedConfigWrite; backup: string | null; committed: boolean; restoreFailed: boolean }> = [];
219
+ const problemsOf = (error: unknown, path: string, action: string): Problem[] => error instanceof PartsError ? [...error.problems] : [ioProblem(path, action, error)];
220
+ const cancelAll = (): Problem[] => entries.flatMap(({ target, staged }) => {
221
+ try { staged.cancel(); return []; }
222
+ catch (error) { return problemsOf(error, target.path, 'removing the staged config failed'); }
223
+ });
224
+ try {
225
+ // Two names for one inode cannot be independent members of a write batch.
226
+ const identities = new Set<string>();
227
+ for (const { target } of requests) {
228
+ const stat = statSync(target.path), identity = `${stat.dev}:${stat.ino}`;
229
+ if (identities.has(identity)) refusal('CONFIG_WRITE_TARGET', target.path, 'names another config in the batch; distinct existing config files are required');
230
+ identities.add(identity);
231
+ }
232
+ // Candidate shape refusals precede even temporary writes. The existing
233
+ // stage loader then validates each real same-directory staged file, including
234
+ // relative sidecars. Edited receipts are full-config updates, not early drafts.
235
+ for (const { target, patch } of requests) {
236
+ const candidate = mergeConfigProposal(target.raw, patch).config;
237
+ if (patch.kind === 'head-box') parseEarlyConfig(candidate, 'layers');
238
+ else if (patch.kind === 'assemble-plan') parseEarlyConfig(candidate, 'assemble');
239
+ else parseConfig(candidate);
240
+ }
241
+ for (const { target, patch } of requests) entries.push({ target, staged: stageConfigWrite(target, patch, files), backup: null, committed: false, restoreFailed: false });
242
+ } catch (error) {
243
+ throw new PartsError([...problemsOf(error, 'config batch', 'staging configs failed'), ...cancelAll()]);
244
+ }
245
+ return {
246
+ writes: entries.map(({ target, staged }) => ({ target, changes: staged.changes })),
247
+ cancel(): void {
248
+ const problems = cancelAll();
249
+ if (problems.length > 0) throw new PartsError(problems);
250
+ },
251
+ commit(): void {
252
+ let problems: Problem[] = [];
253
+ try {
254
+ for (const entry of entries) {
255
+ unchanged(entry.target);
256
+ if (entry.staged.changes.length === 0) continue;
257
+ const path = entry.target.path;
258
+ const backup = join(dirname(path), `.${basename(path)}.rig-parts-${randomBytes(8).toString('hex')}.bak`);
259
+ linkSync(path, backup);
260
+ entry.backup = backup;
261
+ }
262
+ for (const entry of entries) {
263
+ entry.staged.commit();
264
+ entry.committed = entry.staged.changes.length > 0;
265
+ }
266
+ } catch (error) {
267
+ problems = problemsOf(error, 'config batch', 'committing configs failed');
268
+ for (const entry of entries.toReversed()) if (entry.committed && entry.backup !== null) {
269
+ try { (files.restore ?? renameSync)(entry.backup, entry.target.path); entry.backup = null; entry.committed = false; }
270
+ catch (restore) {
271
+ entry.restoreFailed = true;
272
+ problems.push(ioProblem(entry.target.path, `restoring original config failed; original retained at ${entry.backup}`, restore));
273
+ }
274
+ }
275
+ problems.push(...cancelAll());
276
+ }
277
+ for (const entry of entries) if (entry.backup !== null && !entry.restoreFailed) {
278
+ const backup = entry.backup;
279
+ try { (files.remove ?? ((path: string) => rmSync(path, { force: true })))(backup); entry.backup = null; }
280
+ catch (error) { problems.push(ioProblem(backup, 'removing the original-config backup failed', error)); }
281
+ }
282
+ if (problems.length > 0) throw new PartsError(problems);
283
+ },
284
+ };
285
+ }
@@ -0,0 +1,61 @@
1
+ /** Issue #1328: record file bytes, splice one receipt, then publish checked configs. */
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { dirname, relative, resolve } from 'node:path';
5
+ import { parseConfig } from '../src/config.ts';
6
+ import type { EditedPartReceipt } from '../src/editedparts.ts';
7
+ import { PartsError } from '../src/errors.ts';
8
+ import { decodePngBytes } from '../src/raster/png.ts';
9
+ import { readConfigWriteTarget, stageConfigWriteBatch, type StagedConfigWriteBatch } from './configwrite.ts';
10
+
11
+ export interface EditedPartInput {
12
+ config: string;
13
+ rigConfig?: string;
14
+ part: string;
15
+ file: string;
16
+ from: string;
17
+ editor: string;
18
+ }
19
+ function refuse(code: string, object: string, detail: string): never {
20
+ throw new PartsError([{ code, object, detail }]);
21
+ }
22
+ function png(path: string, flag: string): { bytes: Buffer; width: number; height: number } {
23
+ let bytes: Buffer;
24
+ try { bytes = readFileSync(path); }
25
+ catch { return refuse('EDITED_PART_FILE', flag, `file ${JSON.stringify(path)} is not readable; a readable PNG is required`); }
26
+ try {
27
+ const { width, height } = decodePngBytes(bytes, path);
28
+ return { bytes, width, height };
29
+ } catch {
30
+ return refuse('EDITED_PART_PNG', flag, `file ${JSON.stringify(path)} is not a decodable PNG; a PNG is required`);
31
+ }
32
+ }
33
+ const hash = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
34
+ export interface EditedPartWriteResult { receipt: EditedPartReceipt; writes: StagedConfigWriteBatch['writes'] }
35
+
36
+ /** Prepare every replacement before even temporary files are written. No assembly or filename discovery. */
37
+ export function writeEditedPart(input: EditedPartInput): EditedPartWriteResult {
38
+ for (const [flag, value] of [
39
+ ['--config', input.config], ['--part', input.part], ['--file', input.file],
40
+ ['--from', input.from], ['--editor', input.editor],
41
+ ...(input.rigConfig === undefined ? [] : [['--rig-config', input.rigConfig]]),
42
+ ]) if (typeof value !== 'string' || value.trim() === '') refuse('EDITED_PART_ARGUMENT', flag, 'is missing or blank; a non-empty value is required');
43
+ const edited = png(input.file, '--file'), from = png(input.from, '--from');
44
+ if (edited.width !== from.width || edited.height !== from.height) refuse('EDITED_PART_SIZE', input.part,
45
+ `edited PNG is ${edited.width}x${edited.height}; --from PNG dimensions ${from.width}x${from.height} are required`);
46
+ const receipt = { part: input.part, file: input.file, sha256: hash(edited.bytes), from_sha256: hash(from.bytes), editor: input.editor };
47
+ const targets = [input.config, ...(input.rigConfig === undefined ? [] : [input.rigConfig])].map(readConfigWriteTarget);
48
+ const receipts: EditedPartReceipt[] = [];
49
+ const requests = targets.map(target => {
50
+ const config = parseConfig(target.raw as Parameters<typeof parseConfig>[0]);
51
+ const spec = config.assemble.edited_parts;
52
+ if (spec === undefined) return refuse('EDITED_PART_BLOCK', target.path, 'has no assemble.edited_parts; declare {dir, receipts: []} before recording an edited part');
53
+ const file = relative(resolve(dirname(target.path), spec.dir), resolve(input.file)).replaceAll('\\', '/');
54
+ const value: EditedPartReceipt = { ...receipt, file };
55
+ receipts.push(value);
56
+ return { target, patch: { kind: 'edited-part-receipt' as const, receipt: value } };
57
+ });
58
+ const staged = stageConfigWriteBatch(requests);
59
+ staged.commit();
60
+ return { receipt: receipts[0], writes: staged.writes };
61
+ }