@rig-c/parts 1.60.0 → 1.60.2
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/NOTICE.md +1 -1
- package/README.md +6 -3
- package/cli.ts +16 -23
- package/docs/AUTHORING.md +126 -11
- package/docs/PAINTING.md +2 -2
- package/docs/STABILITY.md +21 -4
- package/package.json +3 -1
- package/src/build.ts +31 -5
- package/src/check.ts +194 -43
- package/src/comfy/painting.ts +2 -1
- package/src/config.ts +74 -14
- package/src/configwrite.ts +56 -18
- package/src/diagnostics.ts +3 -2
- package/src/limblayout.ts +6 -4
- package/src/limbs.ts +18 -3
- package/src/limbslots.ts +17 -6
- package/src/propose.ts +4 -3
- package/src/remesh.ts +31 -7
- package/src/retune.ts +10 -8
- package/src/rig.ts +11 -5
- package/src/structure.ts +2 -1
- package/tools/alternate-cli.ts +25 -0
- package/tools/build-process.ts +206 -0
package/src/retune.ts
CHANGED
|
@@ -40,7 +40,7 @@ import { dirname, join, resolve, sep } from 'node:path';
|
|
|
40
40
|
import { checkStage, gateThroughRigc, type Log, rigStage } from './build.ts';
|
|
41
41
|
import { type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
|
|
42
42
|
import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
|
|
43
|
-
import { type CheckSide, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, INPUT_CHECK_FILE, type InputCheckBinding, inputCheckHashes, inputCheckMovedProblems, inputCheckOf, inputCheckReusedLine, inputCheckText, inputTreeProblems, perturbed, readTree, sha256 } from './remesh.ts';
|
|
43
|
+
import { type CheckSide, carryProvenance, type ParentProvenance, checkHeldProblems, checkSide, checkScope, type FileTree, firstDifference, type HashRow, hashRows, INPUT_CHECK_FILE, type InputCheckBinding, inputCheckHashes, inputCheckMovedProblems, inputCheckOf, inputCheckReusedLine, inputCheckText, inputTreeProblems, perturbed, readTree, sha256 } from './remesh.ts';
|
|
44
44
|
import { DEFAULT_IDLE_KEYS, type IdleKeys, rigJsonText } from './rig.ts';
|
|
45
45
|
|
|
46
46
|
/** The provenance file's spec. */
|
|
@@ -103,7 +103,7 @@ export interface RetuneProvenance {
|
|
|
103
103
|
spec: typeof RETUNE_SPEC;
|
|
104
104
|
request: { idle_keys: IdleKeys; page_edges: PageEdges; pack_shape: PackShape };
|
|
105
105
|
versions: { parts: string; rigc: string };
|
|
106
|
-
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string };
|
|
106
|
+
input: { rig: HashRow[]; config_sha256: string; parts_json_sha256: string; provenance?: ParentProvenance[] };
|
|
107
107
|
held: { compared: string[]; not_compared: string };
|
|
108
108
|
changed: { constraints: ConstraintChange[]; added: string[]; removed: string[]; idle: { tracks_changed: number; duration: [number, number] } };
|
|
109
109
|
preserved: { identical: string[]; spliced: string[] };
|
|
@@ -375,7 +375,7 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
375
375
|
if (changed.added.length > 0) log(` constraints added: ${changed.added.join(', ')}`);
|
|
376
376
|
if (changed.removed.length > 0) log(` constraints removed: ${changed.removed.join(', ')}`);
|
|
377
377
|
log(` idle: ${changed.idle.tracks_changed} track(s) changed, duration ${changed.idle.duration[0]} -> ${changed.idle.duration[1]}`);
|
|
378
|
-
log(` preserved: ${identical.length} file(s) byte-identical to the input; rig.json identical outside constraints and invariants.detached; motion.json identical outside animations.idle`);
|
|
378
|
+
log(` preserved: ${identical.filter((p) => p !== RETUNE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)).length} file(s) byte-identical to the input; rig.json identical outside constraints and invariants.detached; motion.json identical outside animations.idle`);
|
|
379
379
|
// 6. The gate and check.
|
|
380
380
|
const pngs = [...revision].filter(([k]) => k.startsWith('images/')).map(([k, b]) => [k.slice('images/'.length), b] as const);
|
|
381
381
|
const texts = [...revision].filter(([k]) => !k.startsWith('images/')).map(([k, b]) => [k, text(b)] as const);
|
|
@@ -405,15 +405,19 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
405
405
|
refuseIfAny(checkHeldProblems(sides.input, sides.revision, revCheck.problems, 'retune'));
|
|
406
406
|
const scope = checkScope(sides.revision.physics);
|
|
407
407
|
log(` check: input ${sides.input.pass ? 'PASS' : `FAIL (${sides.input.not_met.join(', ')})`}, revision ${sides.revision.pass ? 'PASS' : `FAIL (${sides.revision.not_met.join(', ')})`}, the same ${sides.revision.measured.length} bar(s) measured; ${scope}`);
|
|
408
|
-
// 7. The write.
|
|
408
|
+
// 7. The write. The hold above still compares the original rig and motion bytes.
|
|
409
|
+
const lineage = carryProvenance(tree, revision, RETUNE_FILE);
|
|
410
|
+
revision = lineage.revision;
|
|
411
|
+
if (input.recordInputCheck === true) revision.set(INPUT_CHECK_FILE, new TextEncoder().encode(inputCheckText(recorded.binding as InputCheckBinding, sides.input)));
|
|
412
|
+
revision = new Map([...revision].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
409
413
|
const provenance: RetuneProvenance = {
|
|
410
414
|
spec: RETUNE_SPEC,
|
|
411
415
|
request: { idle_keys: idleKeys, page_edges: pageEdges, pack_shape: packShape },
|
|
412
416
|
versions,
|
|
413
|
-
input: { rig: hashRows(tree), config_sha256: sha256(new Uint8Array(readFileSync(input.config))), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))) },
|
|
417
|
+
input: { rig: hashRows(tree), config_sha256: sha256(new Uint8Array(readFileSync(input.config))), parts_json_sha256: sha256(new Uint8Array(readFileSync(join(input.parts, 'parts.json')))), ...(lineage.parents.length === 0 ? {} : { provenance: lineage.parents }) },
|
|
414
418
|
held: { compared: [...RETUNE_HELD], not_compared: RETUNE_NOT_COMPARED },
|
|
415
419
|
changed,
|
|
416
|
-
preserved: { identical, spliced },
|
|
420
|
+
preserved: { identical: identical.filter((p) => p !== RETUNE_FILE && !(input.recordInputCheck === true && p === INPUT_CHECK_FILE)), spliced },
|
|
417
421
|
revision: hashRows(revision),
|
|
418
422
|
check: { ...sides, scope },
|
|
419
423
|
};
|
|
@@ -427,8 +431,6 @@ export function retuneStage(input: RetuneInput, rigc: RigcRunner, checkBin: stri
|
|
|
427
431
|
writeFileSync(join(outAt, RETUNE_FILE), rigJsonText(provenance));
|
|
428
432
|
written.push(RETUNE_FILE);
|
|
429
433
|
if (input.recordInputCheck === true) {
|
|
430
|
-
writeFileSync(join(outAt, INPUT_CHECK_FILE), inputCheckText(recorded.binding as InputCheckBinding, sides.input));
|
|
431
|
-
written.push(INPUT_CHECK_FILE);
|
|
432
434
|
log(` recorded: the input's check in ${INPUT_CHECK_FILE}, bound by ${inputCheckHashes(recorded.binding as InputCheckBinding)} sha256 row(s); pass it as --input-check to a later remesh or retune of ${input.rig}`);
|
|
433
435
|
}
|
|
434
436
|
log(' file sha256 (input) sha256 (revision)');
|
package/src/rig.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionBone } from './config.ts';
|
|
1
2
|
/**
|
|
2
3
|
* The rig stage: a character config and its assembled parts in, a rig spec
|
|
3
4
|
* and a motion spec in rig-c's format out.
|
|
@@ -1413,7 +1414,8 @@ export function buildRig(
|
|
|
1413
1414
|
: '';
|
|
1414
1415
|
const where = (part: string): string => `parts.json holds ${parts.parts.length} part(s): ${parts.parts.map((p) => p.name).join(', ')}`;
|
|
1415
1416
|
for (const part of Object.keys(cfg.meshes)) if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.meshes.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
|
|
1416
|
-
for (const [part,
|
|
1417
|
+
for (const [part, region] of Object.entries(cfg.regions)) {
|
|
1418
|
+
const bone = regionBone(region);
|
|
1417
1419
|
if (!byPart.has(part)) fail('RIG_PART_PRESENT', `config.regions.${part}`, `names the part "${part}", which is not in parts.json; ${where(part)}`);
|
|
1418
1420
|
if (!B.has(bone)) fail('RIG_NAME_RESOLVES', `config.regions.${part}`, `names the bone "${bone}", which config.bones does not declare`);
|
|
1419
1421
|
}
|
|
@@ -2259,7 +2261,7 @@ export function buildRig(
|
|
|
2259
2261
|
outImages.push([file, img]);
|
|
2260
2262
|
const mesh = cfg.meshes[p.name];
|
|
2261
2263
|
if (mesh === undefined) {
|
|
2262
|
-
const bone = B.get(cfg.regions[p.name]) as Bone;
|
|
2264
|
+
const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
|
|
2263
2265
|
const cx = p.x + p.w / 2;
|
|
2264
2266
|
const st = stills[p.name];
|
|
2265
2267
|
if (st !== undefined) {
|
|
@@ -2463,7 +2465,7 @@ export function buildRig(
|
|
|
2463
2465
|
coveredBones = new Set<string>();
|
|
2464
2466
|
for (const slotName of Object.keys(alt.slots)) {
|
|
2465
2467
|
const pName = declaredFront.has(slotName) && altFront.has(slotName.slice(0, -FRONT_SUFFIX.length)) ? slotName.slice(0, -FRONT_SUFFIX.length) : slotName;
|
|
2466
|
-
if (pName in cfg.regions) coveredBones.add(cfg.regions[pName]);
|
|
2468
|
+
if (pName in cfg.regions) coveredBones.add(regionBone(cfg.regions[pName]));
|
|
2467
2469
|
for (const s of meshSegments.get(pName) ?? []) coveredBones.add(s.bone);
|
|
2468
2470
|
const m = cfg.meshes[pName];
|
|
2469
2471
|
if (m !== undefined) {
|
|
@@ -2528,7 +2530,7 @@ export function buildRig(
|
|
|
2528
2530
|
outImages.push([file, img]);
|
|
2529
2531
|
const mesh = cfg.meshes[p.name];
|
|
2530
2532
|
if (mesh === undefined) {
|
|
2531
|
-
const bone = B.get(cfg.regions[p.name]) as Bone;
|
|
2533
|
+
const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
|
|
2532
2534
|
skin[skinSlot][attName] = altRegion(file, bone.name, p.x + p.w / 2, p.y + p.h / 2);
|
|
2533
2535
|
continue;
|
|
2534
2536
|
}
|
|
@@ -2676,7 +2678,11 @@ export function buildRig(
|
|
|
2676
2678
|
const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
|
|
2677
2679
|
// Read every base/alternate binding before rebinds; publish only the slot
|
|
2678
2680
|
// permutation below, after stops/turn have used the original enumeration.
|
|
2679
|
-
const
|
|
2681
|
+
const ungathered = [
|
|
2682
|
+
...Object.entries(cfg.meshes).filter(([, spec]) => spec.gather === false).map(([part]) => ({ part, object: `config.meshes.${part}.gather`, slots: slotFamilies.get(part) ?? [part] })),
|
|
2683
|
+
...Object.entries(cfg.regions).filter(([, spec]) => typeof spec !== 'string' && spec.gather === false).map(([part]) => ({ part, object: `config.regions.${part}.gather`, slots: slotFamilies.get(part) ?? [part] })),
|
|
2684
|
+
];
|
|
2685
|
+
const limbLayout = coalesceLimbSlots(cfg.limbs, bones, slots, skin, ungathered);
|
|
2680
2686
|
const explicitLayout = placeLimbLayouts(cfg.limbs, bones, limbLayout, skin, slotFamilies);
|
|
2681
2687
|
// ---- leg stops (issue #404) --------------------------------------------
|
|
2682
2688
|
// Only when the config has `stops`: each link after the first (and any bone hanging from a stopped link) hangs
|
package/src/structure.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { regionBone } from './config.ts';
|
|
1
2
|
/**
|
|
2
3
|
* A structural comparison of two skeletons (issue #85).
|
|
3
4
|
*
|
|
@@ -193,7 +194,7 @@ export function configRoles(s: SkeletonSections & { constraints?: readonly Confi
|
|
|
193
194
|
if (weightsABone(rg)) push(bound, rg.bone, `meshes.${part}.auto.regions[${i}]`);
|
|
194
195
|
});
|
|
195
196
|
}
|
|
196
|
-
for (const [part, bone] of Object.entries(s.regions)) push(bound, bone, `regions.${part}`);
|
|
197
|
+
for (const [part, bone] of Object.entries(s.regions)) push(bound, regionBone(bone), `regions.${part}`);
|
|
197
198
|
for (const [part, st] of Object.entries(s.motion.blink?.still ?? {})) push(bound, st.bone, `motion.blink.still.${part}`);
|
|
198
199
|
const keyed = new Map<string, string[]>();
|
|
199
200
|
s.motion.tracks.forEach((t, i) => {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AlternateCliInput } from '../src/build.ts';
|
|
2
|
+
|
|
3
|
+
/** Parse `--alt <name>=<source>:<full>[:<head>]` (issue #454), or return a usage message. */
|
|
4
|
+
export function parseAltArg(value: string): AlternateCliInput | string {
|
|
5
|
+
const eq = value.indexOf('=');
|
|
6
|
+
if (eq <= 0) return `--alt "${value}" is not <name>=<source>:<full>[:<head>]`;
|
|
7
|
+
const name = value.slice(0, eq);
|
|
8
|
+
if (name.startsWith('.') || name.includes('/') || name.includes('\\')) return `--alt set name "${name}" may not start with "." or hold a slash`;
|
|
9
|
+
const rest = value.slice(eq + 1);
|
|
10
|
+
const parts: string[] = [];
|
|
11
|
+
const drivePrefix = /^[A-Za-z]:[\\/]/;
|
|
12
|
+
let start = 0;
|
|
13
|
+
for (let at = 0; at < rest.length; at++) {
|
|
14
|
+
if (rest[at] !== ':') continue;
|
|
15
|
+
// Only the leading drive colon of this segment belongs to its path.
|
|
16
|
+
if (at === start + 1 && drivePrefix.test(rest.slice(start))) continue;
|
|
17
|
+
parts.push(rest.slice(start, at));
|
|
18
|
+
start = at + 1;
|
|
19
|
+
}
|
|
20
|
+
parts.push(rest.slice(start));
|
|
21
|
+
if (parts.length < 2 || parts.length > 3 || parts[0].length === 0 || parts[1].length === 0 || (parts.length === 3 && parts[2].length === 0)) {
|
|
22
|
+
return `--alt "${value}" is not <name>=<source>:<full>[:<head>]`;
|
|
23
|
+
}
|
|
24
|
+
return { name, source: parts[0], full: parts[1], ...(parts.length === 3 ? { head: parts[2] } : {}) };
|
|
25
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/** Ordinary build stage processes. No public option selects this internal protocol. */
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { assembleStage, checkStage, rigStage, type AssembleOutputs, type AssembleStageInput, type CheckStageInput, type RigStageInput } from '../src/build.ts';
|
|
6
|
+
import { rigcRunnerAt, type CheckReport, type RigcRunner } from '../src/check.ts';
|
|
7
|
+
import { PartsError, type Problem } from '../src/errors.ts';
|
|
8
|
+
|
|
9
|
+
/** Preserve native/custom executables; adapt only a proven package-manager script shim. */
|
|
10
|
+
export function selectedRigcCommand(bin: string, platform: NodeJS.Platform = process.platform): { command: string; prefix: string[] } {
|
|
11
|
+
if (platform !== 'win32' || extname(bin).toLowerCase() === '.exe') return { command: bin, prefix: [] };
|
|
12
|
+
const fail = (detail: string): never => { throw new Error('RIGC_LAUNCHER_IDENTITY: ' + bin + ' — ' + detail + '; the selected executable must keep its own launcher'); };
|
|
13
|
+
try {
|
|
14
|
+
const selected = resolve(bin);
|
|
15
|
+
// findRigc selected this exact local .bin path; do not resolve an ambient package.
|
|
16
|
+
if (basename(selected) !== 'rigc' || basename(dirname(selected)) !== '.bin') return fail('unknown or custom script shim');
|
|
17
|
+
const packageRoot = join(dirname(dirname(selected)), 'rig-c');
|
|
18
|
+
const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { name?: unknown; bin?: unknown };
|
|
19
|
+
const binMap = manifest.bin;
|
|
20
|
+
const declared = typeof binMap === 'string' ? binMap : binMap !== null && typeof binMap === 'object' ? (binMap as Record<string, unknown>).rigc : undefined;
|
|
21
|
+
if (manifest.name !== 'rig-c' || typeof declared !== 'string') return fail('the selected package does not declare rigc');
|
|
22
|
+
const entry = resolve(packageRoot, declared);
|
|
23
|
+
const within = relative(realpathSync.native(packageRoot), realpathSync.native(entry));
|
|
24
|
+
if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within) || !statSync(entry).isFile()) return fail('bin target is outside the selected package');
|
|
25
|
+
const launcher = readFileSync(entry, 'utf8');
|
|
26
|
+
if (launcher.split(/\r?\n/, 1)[0] !== '#!/usr/bin/env node') return fail('declared bin is not a Node launcher');
|
|
27
|
+
if (realpathSync.native(selected) !== realpathSync.native(entry)) {
|
|
28
|
+
// npm cmd-shim's shell companion is checked in full, including both forwarding branches.
|
|
29
|
+
// Extra custom commands, another target or an unknown shim format are refused, never bypassed.
|
|
30
|
+
const reference = relative(dirname(selected), entry).split(sep).join('/');
|
|
31
|
+
if (/["$\x60\r\n]/.test(reference)) return fail('target cannot be identified literally in the package shim');
|
|
32
|
+
const expected = [
|
|
33
|
+
'#!/bin/sh', 'basedir=$(dirname "$(echo "$0" | sed -e \'s,\\\\,/,g\')")',
|
|
34
|
+
'case \x60uname\x60 in', '*CYGWIN*|*MINGW*|*MSYS*)', 'if command -v cygpath > /dev/null 2>&1; then',
|
|
35
|
+
'basedir=\x60cygpath -w "$basedir"\x60', 'fi', ';;', 'esac',
|
|
36
|
+
'if [ -x "$basedir/node" ]; then', 'exec "$basedir/node" "$basedir/' + reference + '" "$@"',
|
|
37
|
+
'else', 'exec node "$basedir/' + reference + '" "$@"', 'fi',
|
|
38
|
+
];
|
|
39
|
+
const actual = readFileSync(selected, 'utf8').split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
|
40
|
+
const equal = actual.length === expected.length && actual.every((line, i) => line === expected[i] ||
|
|
41
|
+
(i === 10 && line === expected[i].replace('node" ', 'node" ')) || (i === 12 && line === expected[i].replace('exec node ', 'exec node ')));
|
|
42
|
+
if (!equal) return fail('selected shim is not the declared launcher forwarding wrapper');
|
|
43
|
+
}
|
|
44
|
+
return { command: 'node', prefix: [entry] };
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof Error && error.message.startsWith('RIGC_LAUNCHER_IDENTITY:')) throw error;
|
|
47
|
+
return fail(error instanceof Error ? error.message : String(error));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function childStarted(child: { status: number | null; signal: string | null }): boolean {
|
|
52
|
+
return typeof child.status === 'number' || (typeof child.signal === 'string' && child.signal !== '');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function processRigcRunner(bin: string): RigcRunner {
|
|
56
|
+
return rigcRunnerAt(bin, (b, args) => {
|
|
57
|
+
let launch: { command: string; prefix: string[] };
|
|
58
|
+
try { launch = selectedRigcCommand(b); }
|
|
59
|
+
catch (error) { return { status: 127, out: error instanceof Error ? error.message : String(error) }; }
|
|
60
|
+
const r = spawnSync(launch.command, [...launch.prefix, ...args], { shell: false, windowsHide: true, encoding: 'utf8', maxBuffer: 1 << 28 });
|
|
61
|
+
if (!childStarted(r)) return { status: 127, out: 'could not start ' + b + ': ' + (r.error?.message ?? 'no exit status or signal was reported') };
|
|
62
|
+
return { status: r.status ?? 1, out: (r.stdout ?? '') + (r.stderr ?? '') };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Stage = 'assemble' | 'rig' | 'check';
|
|
67
|
+
export type BuildProcessJob =
|
|
68
|
+
| { stage: 'assemble'; bin: string; input: AssembleStageInput; outputs: AssembleOutputs }
|
|
69
|
+
| { stage: 'rig'; bin: string; input: Omit<RigStageInput, 'reduce'>; scratch: string }
|
|
70
|
+
| { stage: 'check'; bin: string; input: CheckStageInput };
|
|
71
|
+
|
|
72
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
73
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
74
|
+
}
|
|
75
|
+
function problems(value: unknown): value is Problem[] {
|
|
76
|
+
return Array.isArray(value) && value.length > 0 && value.every((p) => record(p) && typeof p.code === 'string' && typeof p.object === 'string' && typeof p.detail === 'string');
|
|
77
|
+
}
|
|
78
|
+
function resultError(stage: Stage, detail: string): never {
|
|
79
|
+
throw new Error('BUILD_STAGE_RESULT: ' + stage + ' child — ' + detail + '; a matching complete receipt is required');
|
|
80
|
+
}
|
|
81
|
+
function checkReport(value: unknown): value is CheckReport {
|
|
82
|
+
if (!record(value) || !record(value.figures) || typeof value.figures.PASS !== 'boolean') return false;
|
|
83
|
+
const arrays = ['gateHtml', 'pack', 'packOpaque', 'problems', 'written', 'besideIdle'];
|
|
84
|
+
if (!arrays.every((key) => Array.isArray(value[key]))) return false;
|
|
85
|
+
if (!record(value.bars) || !Array.isArray(value.bars.measured) || !Array.isArray(value.bars.skipped)) return false;
|
|
86
|
+
if (!record(value.motionSeam) || !record(value.cloth)) return false;
|
|
87
|
+
if (!['idle', 'loopPhysics', 'seamViewport', 'requirements'].every((key) => Object.hasOwn(value, key))) return false;
|
|
88
|
+
return (value.pack as unknown[]).every((p) => record(p) && typeof p.line === 'string' && typeof p.page === 'string' &&
|
|
89
|
+
['width', 'height', 'regions', 'coveredPct', 'padding'].every((key) => typeof p[key] === 'number') &&
|
|
90
|
+
(p.pageEdges === 'free' || p.pageEdges === 'pot') && (p.packShape === 'rect' || p.packShape === 'polygon')) &&
|
|
91
|
+
(value.problems as unknown[]).every((p) => record(p) && typeof p.code === 'string' && typeof p.object === 'string' && typeof p.detail === 'string');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Decode only a matching successful stage or its original named input refusal. */
|
|
95
|
+
export function readBuildReceipt(stage: 'check', status: number | null, signal: string | null, text: string): CheckReport;
|
|
96
|
+
export function readBuildReceipt(stage: 'assemble' | 'rig', status: number | null, signal: string | null, text: string): void;
|
|
97
|
+
export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void;
|
|
98
|
+
export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void {
|
|
99
|
+
if (signal !== null || status === null || (status !== 0 && status !== 1) || (status !== 0 && text === '')) {
|
|
100
|
+
throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ', signal ' + signal + '; no later stage ran');
|
|
101
|
+
}
|
|
102
|
+
let row: unknown;
|
|
103
|
+
try { row = JSON.parse(text); } catch { return resultError(stage, 'missing or malformed JSON'); }
|
|
104
|
+
if (!record(row) || row.version !== 1 || row.stage !== stage) return resultError(stage, 'wrong version or stage');
|
|
105
|
+
if (row.kind === 'refused') {
|
|
106
|
+
if (status !== 1 || !problems(row.problems)) return resultError(stage, 'refusal must exit 1 and name at least one complete problem');
|
|
107
|
+
throw new PartsError(row.problems);
|
|
108
|
+
}
|
|
109
|
+
if (row.kind !== 'done') return resultError(stage, 'unknown receipt kind');
|
|
110
|
+
if (status !== 0) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ' with a completion receipt; no later stage ran');
|
|
111
|
+
if (stage !== 'check') {
|
|
112
|
+
if (Object.hasOwn(row, 'report') || Object.hasOwn(row, 'sweepSteps')) return resultError(stage, 'a void stage returned an invented check report');
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!checkReport(row.report)) return resultError(stage, 'check report is incomplete');
|
|
116
|
+
if (row.sweepSteps !== null && (!Array.isArray(row.sweepSteps) || !row.sweepSteps.every((p) =>
|
|
117
|
+
Array.isArray(p) && p.length === 2 && typeof p[0] === 'string' && record(p[1]) && typeof p[1].left === 'number' && typeof p[1].right === 'number'))) {
|
|
118
|
+
return resultError(stage, 'sweepSteps must be null or the original map entries');
|
|
119
|
+
}
|
|
120
|
+
const report = row.report;
|
|
121
|
+
if (row.sweepSteps !== null) report.sweepSteps = new Map(row.sweepSteps as Array<[string, { left: number; right: number }]>);
|
|
122
|
+
return report;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The check's one optional Map is carried as entries; every other field is the original report. */
|
|
126
|
+
export function encodeCheckReceipt(report: CheckReport): string {
|
|
127
|
+
return JSON.stringify({ version: 1, stage: 'check', kind: 'done', report: { ...report, sweepSteps: undefined },
|
|
128
|
+
sweepSteps: report.sweepSteps === undefined ? null : [...report.sweepSteps] });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Minimum Bun may attach error to an ordinary nonzero exit; only an unstarted child is a launch failure. */
|
|
132
|
+
export function readBuildChild(stage: Stage, child: { status: number | null; signal: string | null; error?: Error }, text: string): CheckReport | void {
|
|
133
|
+
if (!childStarted(child) && child.error !== undefined) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' could not start — ' + child.error.message);
|
|
134
|
+
return readBuildReceipt(stage, child.status ?? null, child.signal ?? null, text);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Inherited descriptors keep stdout/stderr write order; no shell parses paths or flags. */
|
|
138
|
+
export function launchBuildChild(argv: readonly string[]): { status: number | null; signal: string | null; error?: Error } {
|
|
139
|
+
const [command, ...args] = argv;
|
|
140
|
+
if (command === undefined) throw new Error('BUILD_STAGE_CHILD: executable is required');
|
|
141
|
+
return spawnSync(command, args, { shell: false, windowsHide: true, stdio: ['ignore', 'inherit', 'inherit'] });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function runBuildProcess(job: Extract<BuildProcessJob, { stage: 'check' }>, home: string): CheckReport;
|
|
145
|
+
export function runBuildProcess(job: Exclude<BuildProcessJob, { stage: 'check' }>, home: string): void;
|
|
146
|
+
export function runBuildProcess(job: BuildProcessJob, home: string): CheckReport | void {
|
|
147
|
+
mkdirSync(home, { recursive: true });
|
|
148
|
+
const request = join(home, job.stage + '.request.json');
|
|
149
|
+
const result = join(home, job.stage + '.result.json');
|
|
150
|
+
rmSync(result, { force: true });
|
|
151
|
+
writeFileSync(request, JSON.stringify(job));
|
|
152
|
+
try {
|
|
153
|
+
const child = launchBuildChild([process.execPath, import.meta.path, request, result]);
|
|
154
|
+
return readBuildChild(job.stage, child, existsSync(result) ? readFileSync(result, 'utf8') : '');
|
|
155
|
+
} finally {
|
|
156
|
+
rmSync(request, { force: true });
|
|
157
|
+
rmSync(result, { force: true });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function requestError(detail: string): never {
|
|
162
|
+
throw new PartsError([{ code: 'BUILD_STAGE_REQUEST', object: 'internal build worker', detail: detail + '; a complete assemble, rig or check request is required' }]);
|
|
163
|
+
}
|
|
164
|
+
function readJob(path: string): BuildProcessJob {
|
|
165
|
+
let job: unknown;
|
|
166
|
+
try { job = JSON.parse(readFileSync(path, 'utf8')); } catch { return requestError('request file is missing or malformed'); }
|
|
167
|
+
if (!record(job) || typeof job.bin !== 'string' || !record(job.input)) return requestError('request must name its runner and typed input');
|
|
168
|
+
const input = job.input;
|
|
169
|
+
const strings = (keys: string[]): boolean => keys.every((key) => typeof input[key] === 'string');
|
|
170
|
+
if (job.stage === 'assemble') {
|
|
171
|
+
if (!strings(['config', 'source', 'full', 'seam', 'project']) || !(input.head === null || typeof input.head === 'string') ||
|
|
172
|
+
!record(job.outputs) || !['partsJson', 'partsDir', 'recomposite', 'errorMap'].every((key) => typeof (job.outputs as Record<string, unknown>)[key] === 'string')) return requestError('assemble input or output paths are incomplete');
|
|
173
|
+
} else if (job.stage === 'rig') {
|
|
174
|
+
if (!strings(['config', 'parts', 'out']) || typeof job.scratch !== 'string' || Object.hasOwn(input, 'reduce')) return requestError('rig input or scratch is incomplete, or contains a nonserializable reducer');
|
|
175
|
+
} else if (job.stage === 'check') {
|
|
176
|
+
if (!strings(['rig', 'out'])) return requestError('check input paths are incomplete');
|
|
177
|
+
} else return requestError('unknown stage ' + JSON.stringify(job.stage));
|
|
178
|
+
return job as unknown as BuildProcessJob;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function worker(args: string[]): number {
|
|
182
|
+
if (args.length !== 2 || args.some((a) => a === '' || a.startsWith('--'))) return requestError('expected exactly one request path and one result path');
|
|
183
|
+
const job = readJob(args[0]);
|
|
184
|
+
const runner = processRigcRunner(job.bin);
|
|
185
|
+
const log = (line: string): void => { console.log('[' + job.stage + '] ' + line); };
|
|
186
|
+
try {
|
|
187
|
+
let report: CheckReport | undefined;
|
|
188
|
+
if (job.stage === 'assemble') assembleStage(job.input, job.outputs, log);
|
|
189
|
+
else if (job.stage === 'rig') rigStage(job.input, runner, job.scratch, log);
|
|
190
|
+
else report = checkStage(job.input, runner, job.bin, log);
|
|
191
|
+
writeFileSync(args[1], report === undefined ? JSON.stringify({ version: 1, stage: job.stage, kind: 'done' }) : encodeCheckReceipt(report));
|
|
192
|
+
return 0;
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (!(err instanceof PartsError)) throw err;
|
|
195
|
+
writeFileSync(args[1], JSON.stringify({ version: 1, stage: job.stage, kind: 'refused', problems: err.problems }));
|
|
196
|
+
return 1;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (import.meta.main) {
|
|
200
|
+
try { process.exit(worker(process.argv.slice(2))); }
|
|
201
|
+
catch (err) {
|
|
202
|
+
if (!(err instanceof PartsError)) throw err;
|
|
203
|
+
console.error(err.message);
|
|
204
|
+
process.exit(1);
|
|
205
|
+
}
|
|
206
|
+
}
|