@rig-c/review 1.16.6 → 1.17.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.
@@ -0,0 +1,163 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { chmodSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import type { JobErrorCode } from './job-contract.ts';
6
+
7
+ export class JobError extends Error {
8
+ constructor(readonly code: JobErrorCode, message: string = code) {
9
+ super(message);
10
+ this.name = 'JobError';
11
+ }
12
+ }
13
+
14
+ export interface StoredJob<Data> {
15
+ readonly jobId: string;
16
+ readonly rootKey: string;
17
+ readonly revision: number;
18
+ readonly active: boolean;
19
+ readonly data: Data;
20
+ }
21
+
22
+ interface JobRow {
23
+ job_id: string;
24
+ root_key: string;
25
+ revision: number;
26
+ active: number;
27
+ document: string;
28
+ }
29
+
30
+ const maximumDocumentBytes = 16 * 1024 * 1024;
31
+
32
+ function encode(value: unknown): string {
33
+ try {
34
+ const text = JSON.stringify(value, (_key, item) => {
35
+ if (item === undefined || typeof item === 'function' || typeof item === 'symbol' ||
36
+ typeof item === 'bigint' || typeof item === 'number' && !Number.isFinite(item)) {
37
+ throw new JobError('JOB_STORAGE_FAILED');
38
+ }
39
+ return item;
40
+ });
41
+ if (text === undefined || Buffer.byteLength(text) > maximumDocumentBytes) {
42
+ throw new JobError('JOB_STORAGE_FAILED');
43
+ }
44
+ return text;
45
+ } catch {
46
+ throw new JobError('JOB_STORAGE_FAILED', 'Job state could not be serialized within its bound');
47
+ }
48
+ }
49
+
50
+ function decode<Data>(row: JobRow): StoredJob<Data> {
51
+ try {
52
+ if (Buffer.byteLength(row.document) > maximumDocumentBytes || !Number.isSafeInteger(row.revision) ||
53
+ row.revision < 0 || ![0, 1].includes(row.active)) throw new Error('Invalid row');
54
+ return {
55
+ jobId: row.job_id,
56
+ rootKey: row.root_key,
57
+ revision: row.revision,
58
+ active: row.active === 1,
59
+ data: JSON.parse(row.document) as Data,
60
+ };
61
+ } catch {
62
+ throw new JobError('JOB_STORAGE_FAILED', 'Stored job state is invalid');
63
+ }
64
+ }
65
+
66
+ function privateEntry(path: string, directory: boolean): void {
67
+ const info = lstatSync(path);
68
+ if (!(directory ? info.isDirectory() : info.isFile()) || (info.mode & 0o077) !== 0 ||
69
+ (!directory && info.nlink !== 1) || typeof process.getuid === 'function' && info.uid !== process.getuid()) {
70
+ throw new JobError('JOB_STORAGE_FAILED', 'Job state requires private owned regular storage');
71
+ }
72
+ }
73
+
74
+ /** One SQLite transaction seals the entire job, including its events, acts and
75
+ * idempotency receipts. IMMEDIATE transactions serialize independent daemons.
76
+ * FULL synchronous durability and the rollback journal survive process death.
77
+ * Callbacks are synchronous and must not perform external writes.
78
+ */
79
+ export class JobStore<Data> {
80
+ readonly root: string;
81
+ private readonly db: Database;
82
+
83
+ constructor(directory: string) {
84
+ try {
85
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
86
+ privateEntry(directory, true);
87
+ this.root = realpathSync(directory);
88
+ const file = join(this.root, 'jobs.sqlite');
89
+ try { privateEntry(file, false); }
90
+ catch (error) {
91
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
92
+ }
93
+ this.db = new Database(file, { create: true });
94
+ chmodSync(file, 0o600);
95
+ this.db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA busy_timeout=1000;');
96
+ this.db.exec(`CREATE TABLE IF NOT EXISTS jobs (
97
+ job_id TEXT PRIMARY KEY,
98
+ root_key TEXT NOT NULL,
99
+ revision INTEGER NOT NULL CHECK(revision >= 0),
100
+ active INTEGER NOT NULL CHECK(active IN (0,1)),
101
+ document TEXT NOT NULL
102
+ );
103
+ CREATE UNIQUE INDEX IF NOT EXISTS jobs_active_root ON jobs(root_key) WHERE active=1;`);
104
+ } catch {
105
+ throw new JobError('JOB_STORAGE_FAILED', 'Private job storage could not be opened');
106
+ }
107
+ }
108
+
109
+ private transaction<Value>(operation: () => Value): Value {
110
+ try { return this.db.transaction(operation).immediate(); }
111
+ catch (error) {
112
+ if (typeof (error as { code?: unknown }).code === 'string' &&
113
+ String((error as { code: string }).code).startsWith('SQLITE_')) {
114
+ throw new JobError('JOB_STORAGE_FAILED', 'Job transaction could not be committed');
115
+ }
116
+ throw error;
117
+ }
118
+ }
119
+
120
+ get(jobId: string): StoredJob<Data> {
121
+ const row = this.db.query<JobRow, [string]>('SELECT * FROM jobs WHERE job_id=?').get(jobId);
122
+ if (!row) throw new JobError('JOB_UNKNOWN');
123
+ return decode<Data>(row);
124
+ }
125
+
126
+ open(rootKey: string, initialize: (jobId: string) => Data): StoredJob<Data> {
127
+ return this.transaction(() => {
128
+ const current = this.db.query<JobRow, [string]>(
129
+ 'SELECT * FROM jobs WHERE root_key=? AND active=1',
130
+ ).get(rootKey);
131
+ if (current) return decode<Data>(current);
132
+ const jobId = randomUUID();
133
+ const document = encode(initialize(jobId));
134
+ this.db.query('INSERT INTO jobs(job_id,root_key,revision,active,document) VALUES(?,?,0,1,?)')
135
+ .run(jobId, rootKey, document);
136
+ return this.get(jobId);
137
+ });
138
+ }
139
+
140
+ /** Re-read under the write transaction. A callback failure rolls everything
141
+ * back. A successful callback publishes its complete data and replay receipt
142
+ * together. Closing releases the active-root slot in the same commit.
143
+ */
144
+ update(jobId: string, expectedRevision: number, operation: (current: StoredJob<Data>) => {
145
+ readonly data: Data;
146
+ readonly active?: boolean;
147
+ }): StoredJob<Data> {
148
+ return this.transaction(() => {
149
+ const current = this.get(jobId);
150
+ if (current.revision !== expectedRevision) throw new JobError('JOB_GENERATION_STALE');
151
+ const next = operation(current);
152
+ const active = next.active ?? current.active;
153
+ const document = encode(next.data);
154
+ this.db.query('UPDATE jobs SET revision=?,active=?,document=? WHERE job_id=?')
155
+ .run(current.revision + 1, active ? 1 : 0, document, jobId);
156
+ return this.get(jobId);
157
+ });
158
+ }
159
+
160
+ close(): void {
161
+ this.db.close();
162
+ }
163
+ }
@@ -0,0 +1,56 @@
1
+ import { createJobHostPorts } from './job-api.ts';
2
+ import { JobSession, type JobSessionOptions } from './job-session.ts';
3
+ import type { JobHostPorts } from './job-contract.ts';
4
+ import { JobError } from './job-store.ts';
5
+
6
+ export interface JobWorkerOptions extends JobSessionOptions {
7
+ readonly port?: number;
8
+ /** Trusted Create #184 adapter installs its private writer-owned sibling.
9
+ * No project record key or binding-file format is defined by this callback.
10
+ */
11
+ readonly installWriterBinding?: (binding: {
12
+ readonly jobId: string;
13
+ readonly origin: string;
14
+ readonly fetchCapability: string;
15
+ }) => void | Promise<void>;
16
+ }
17
+
18
+ /** Backend host only. Lane B mounts these same ports in its managed front and
19
+ * supplies the owner UI. This listener serves semantic API requests only and
20
+ * never serves a private snapshot directory or starts a browser/producer.
21
+ */
22
+ export async function startJobWorker(options: JobWorkerOptions): Promise<{
23
+ readonly session: JobSession;
24
+ readonly ports: JobHostPorts;
25
+ readonly origin: string;
26
+ stop(): void;
27
+ }> {
28
+ const session = new JobSession(options);
29
+ let ports: JobHostPorts;
30
+ let stopped = false;
31
+ const server = Bun.serve({
32
+ hostname: '127.0.0.1', port: options.port ?? 0, idleTimeout: 0,
33
+ fetch(request) {
34
+ const url = new URL(request.url);
35
+ if (url.pathname === `/jobs/${session.jobId}/api`) return ports.handleJobApi(request);
36
+ return Response.json({ error: 'JOB_REQUEST_INVALID' }, {
37
+ status: 404, headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
38
+ });
39
+ },
40
+ });
41
+ const origin = `http://127.0.0.1:${server.port}`;
42
+ ports = createJobHostPorts(session, origin);
43
+ const stop = () => {
44
+ if (stopped) return;
45
+ stopped = true;
46
+ server.stop(true);
47
+ session.dispose();
48
+ };
49
+ try {
50
+ await options.installWriterBinding?.({ ...session.writerGrant(), origin });
51
+ return { session, ports, origin, stop };
52
+ } catch {
53
+ stop();
54
+ throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');
55
+ }
56
+ }
package/src/open.ts CHANGED
@@ -19,6 +19,7 @@ import {ensureFront,frontPort} from './front.ts';
19
19
  import {playPackagePath} from './versions.ts';
20
20
  import {HandoffError,HANDOFF_FLAGS,isBuildRoot,type HandoffFlags,type HandoffRecord} from './handoff.ts';
21
21
  import {stateDirInside,stateRoots} from './state-dir.ts';
22
+ import {destinationDirectory} from './destination-directory.ts';
22
23
  import {DEFAULT_UNOPENED_TIMEOUT_MS} from './live-lifecycle.ts';
23
24
  import {verifyCompiledModel} from './strip-render.ts';
24
25
  import {verifyHandoffReadiness} from './rebuild.ts';
@@ -82,7 +83,6 @@ async function claimOwner(claim:string):Promise<{file:string;pid:number;nonce:st
82
83
  }
83
84
  async function removeClaimFile(claim:string,owner:{file:string;nonce:string}){try{const current=await smallJson(owner.file) as {nonce?:string};if(current.nonce!==owner.nonce)return;await unlink(owner.file);await rmdir(claim);}catch(e){if(!['ENOENT','ENOTEMPTY','EEXIST'].includes((e as NodeJS.ErrnoException).code??''))throw e;}}
84
85
  export async function releaseClaim(claim:string,nonce:string){await removeClaimFile(claim,{file:join(claim,`owner.${nonce}.json`),nonce});}
85
- async function canonicalDestination(path:string):Promise<string>{try{return await realpath(path);}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;const parent=dirname(path);if(parent===path)throw e;return join(await canonicalDestination(parent),basename(path));}}
86
86
  /** Single-owner startup: publish a populated claim directory atomically (no live owner ever exposes an empty
87
87
  * claim; unique owner filenames make stale cleanup safe after replacement). A ready reuse wins while waiting. */
88
88
  export async function acquireClaim<T>(control:string,name:string,nonce:string,reuse:()=>Promise<T|null>,deadline:number,busy:string):Promise<{row:T}|{claim:string}>{
@@ -132,7 +132,7 @@ export async function openReview(inputs:OpenInputs,options:{stateDir?:string;idl
132
132
  let p:OpenPackage;try{p=await loadOpenPackage(inputs);}catch(error){throw await openRefusal(error,inputs);}
133
133
  const fingerprint=await openFingerprint(),key=openKey(p,fingerprint);
134
134
  // #187: canonical (symlinks and ancestors resolved) and outside every supplied folder: the package, the build root a check package belongs to, the handoff root.
135
- const stateDir=await canonicalDestination(resolve(options.stateDir??defaultStateDir())),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
135
+ const stateDir=destinationDirectory(options.stateDir??defaultStateDir(),'OPEN_STATE_INVALID: the state directory path has a non-directory component or a symlink loop'),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
136
136
  if(p.mode==='single'&&p.joined&&stateDirInside(stateDir,[{kind:'package',path:p.joined.opened.root}]))throw new Error('OPEN_STATE_INSIDE_PACKAGE: review state must be outside the joined project');
137
137
  const inside=stateDirInside(stateDir,roots);if(inside)throw new Error(`OPEN_STATE_INSIDE_PACKAGE ${inside.kind}: the review state directory must be outside input packages; it is inside the ${inside.kind}; set RIG_REVIEW_STATE_DIR outside it`);
138
138
  await verifyOpenLoad(p,viewOnly,options.cwd);
@@ -177,7 +177,8 @@ export async function runOpenWorker(requestPath:string):Promise<void>{
177
177
  /** Read/control an already running, explicitly opted-in exact binding. Never starts a worker. */
178
178
  export async function controlReview(inputs:OpenInputs,commandOptions:{pageId?:string;expectedRevision?:number;requestId?:string;command?:ControlCommand;waitMs?:number;stateDir?:string}={}):Promise<unknown>{
179
179
  const wait=commandOptions.waitMs??10000;if(!Number.isSafeInteger(wait)||wait<0||wait>30000)throw new Error('CONTROL_WAIT: expected integer 0..30000');
180
- const p=await loadOpenPackage({...inputs,control:true}),fingerprint=await openFingerprint(),key=openKey(p,fingerprint),stateDir=await canonicalDestination(resolve(commandOptions.stateDir??defaultStateDir()));
180
+ const p=await loadOpenPackage({...inputs,control:true}),fingerprint=await openFingerprint(),key=openKey(p,fingerprint);
181
+ const stateDir=destinationDirectory(commandOptions.stateDir??defaultStateDir(),'CONTROL_STATE: the state directory path has a non-directory component or a symlink loop');
181
182
  const controlDir=join(stateDir,'open');
182
183
  try{if((await lstat(controlDir)).isSymbolicLink())throw new Error('CONTROL_STATE: control directory cannot be a symlink');}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')throw new Error('CONTROL_INSTANCE_UNAVAILABLE: open the exact inputs once with --control');throw error;}
183
184
  const file=join(controlDir,key+'.json');try{const info=await lstat(file);if(!info.isFile()||(info.mode&0o077)!==0)throw new Error('CONTROL_STATE: owner-only regular capability record required');}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')throw new Error('CONTROL_INSTANCE_UNAVAILABLE: open the exact inputs once with --control');throw error;}
package/src/parts-view.ts CHANGED
@@ -25,6 +25,7 @@ import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/
25
25
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
26
26
  import { PNG } from 'pngjs';
27
27
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
28
+ import { destinationDirectory } from './destination-directory.ts';
28
29
 
29
30
  export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/2';
30
31
  export const PARTS_VERDICT_FILE = 'parts-review.json';
@@ -130,17 +131,10 @@ function relativeTo(dir: string, abs: string): string {
130
131
 
131
132
  /** Match canonical input paths, resolving only the destination's parent. Missing
132
133
  * directories retain their suffix; the output leaf is never followed through a symlink. */
133
- async function verdictDestination(path: string): Promise<string> {
134
- const abs = resolve(path), suffix = [basename(abs)];
135
- let parent = dirname(abs);
136
- for (;;) {
137
- try { return join(await realpath(parent), ...suffix); }
138
- catch (error) {
139
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(parent) === parent) throw error;
140
- suffix.unshift(basename(parent));
141
- parent = dirname(parent);
142
- }
143
- }
134
+ function verdictDestination(path: string): string {
135
+ const absolute = resolve(path);
136
+ const parent = destinationDirectory(dirname(absolute), 'PARTS_VERDICT_DESTINATION_INVALID: the verdict parent path has a non-directory component or a symlink loop');
137
+ return join(parent, basename(absolute));
144
138
  }
145
139
 
146
140
  /** Faint islands (rig-parts #326) from `mesh_report.json` rows, on the parts the view holds. */
@@ -378,7 +372,7 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
378
372
  const protectedPaths = [join(root, 'rig.json'), join(root, 'config.json'), join(root, 'review.json'), join(root, 'report.json')];
379
373
  if (basename(root) === 'rig') protectedPaths.push(...['parts.json', 'config.json', 'review.json', 'report.json'].map(name => join(dirname(root), name)));
380
374
  if (options.rig !== undefined) protectedPaths.push(resolve(options.rig));
381
- const verdictPath = options.verdict ? await verdictDestination(options.verdict) : join(root, PARTS_VERDICT_FILE);
375
+ const verdictPath = options.verdict ? verdictDestination(options.verdict) : join(root, PARTS_VERDICT_FILE);
382
376
  await assertVerdictDestination({ files, flagFiles, protectedPaths, verdictPath });
383
377
  const rigPath = options.rig !== undefined ? await realpath(resolve(options.rig)) : existsSync(join(root, 'rig.json')) ? await insideRoot(root, join(root, 'rig.json'), 'PARTS_MESH_OUTSIDE', 'rig.json') : null;
384
378
  if (rigPath) {
@@ -435,7 +429,7 @@ export async function loadPartsAtlas(p: ReviewPackage, options: PartsViewOptions
435
429
  protectedPaths.push(...['rig.json', 'config.json', 'report.json', 'review.json'].map(name => join(p.root, name)));
436
430
  if (p.handoff) protectedPaths.push(...p.handoff.record.files.map(file => resolve(p.root, file.path)));
437
431
  if (buildRoot) protectedPaths.push(...['parts.json', 'config.json', 'rig/rig.json', 'rig/parts.json'].map(name => join(buildRoot, name)));
438
- return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, readings, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? await verdictDestination(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
432
+ return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, readings, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? verdictDestination(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
439
433
  }
440
434
 
441
435
  /**
@@ -68,7 +68,7 @@ export function createReadings(p: ReviewPackage, options: ReadingsOptions) {
68
68
  let running: string | null = null;
69
69
  const snapshot = (job: ReadingsJob): ReadingsJob => JSON.parse(JSON.stringify(job)) as ReadingsJob;
70
70
  function assertStateOutside(): void {
71
- assertStateDirOutside(options.stateDir, p, message => new ReadingsError('READINGS_STATE_INSIDE_PACKAGE', message));
71
+ assertStateDirOutside(options.stateDir, p, (message, code) => new ReadingsError(code ?? 'READINGS_STATE_INSIDE_PACKAGE', message));
72
72
  }
73
73
  /** Whether this rigc's `render --help` lists `--environment`, asked once per compiler. */
74
74
  async function environmentFlag(compiler: InstalledTool): Promise<boolean> {
package/src/rebuild.ts CHANGED
@@ -772,7 +772,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
772
772
 
773
773
  /** The state directory may not sit inside the package or the handoff's root (the parent of an opened out/). */
774
774
  function assertStateOutside(): void {
775
- assertStateDirOutside(options.stateDir, p, message => new RebuildError('REBUILD_STATE_INSIDE_PACKAGE', message));
775
+ assertStateDirOutside(options.stateDir, p, (message, code) => new RebuildError(code ?? 'REBUILD_STATE_INSIDE_PACKAGE', message));
776
776
  }
777
777
  /** Once per session: the first time the handoff and the producer both resolve, the baseline starts (or is reused). */
778
778
  let baseline: BaselineResult | null = null, baselineRun: Promise<BaselineResult> | null = null;
@@ -90,7 +90,7 @@ export function createRequirementsCheck(p: ReviewPackage, options: RequirementsO
90
90
  let running: string | null = null;
91
91
  const snapshot = (job: RequirementsJob): RequirementsJob => JSON.parse(JSON.stringify(job)) as RequirementsJob;
92
92
  function assertStateOutside(): void {
93
- assertStateDirOutside(options.stateDir, p, message => new RequirementsError('REQUIREMENTS_STATE_INSIDE_PACKAGE', message));
93
+ assertStateDirOutside(options.stateDir, p, (message, code) => new RequirementsError(code ?? 'REQUIREMENTS_STATE_INSIDE_PACKAGE', message));
94
94
  }
95
95
  const asRequirements = (e: unknown): never => { if (e instanceof RebuildError) throw new RequirementsError(e.code, e.message.slice(e.code.length + 2)); throw e; };
96
96
 
package/src/state-dir.ts CHANGED
@@ -5,23 +5,20 @@
5
5
  * inside the rig-parts build root the check package belongs to (opening `out` redirects the package to `out/check`;
6
6
  * the build is still the supplied folder), the package root, or the producer handoff's root.
7
7
  */
8
- import { realpathSync } from 'node:fs';
9
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
8
+ import { isAbsolute, relative, sep } from 'node:path';
9
+ import { destinationDirectory, DestinationDirectoryError } from './destination-directory.ts';
10
10
 
11
11
  export type StateRootKind = 'build root' | 'package' | 'handoff root';
12
12
  export interface StateRoot { kind: StateRootKind; path: string }
13
13
  /** The fields of a loaded package that name supplied folders. */
14
14
  export interface StateRootsSource { root: string; buildRoot?: string; handoff?: { root: string } | null }
15
15
 
16
- const missing = (e: unknown) => ['ENOENT', 'ENOTDIR'].includes((e as NodeJS.ErrnoException).code ?? '');
16
+ const invalidCode = 'STATE_DIRECTORY_INVALID';
17
+ const invalidMessage = 'the state directory path has a non-directory component or a symlink loop';
17
18
 
18
- /** The canonical location of `path`: realpath of the longest existing prefix joined with the remainder. */
19
+ /** Resolve the existing directory prefix and keep any missing suffix. */
19
20
  export function canonicalStatePath(path: string): string {
20
- const absolute = resolve(path), rest: string[] = [];
21
- for (let current = absolute; ; current = dirname(current)) {
22
- try { const real = realpathSync(current); return rest.length ? join(real, ...rest.reverse()) : real; }
23
- catch (e) { if (!missing(e) || dirname(current) === current) throw e; rest.push(basename(current)); }
24
- }
21
+ return destinationDirectory(path, `${invalidCode}: ${invalidMessage}`);
25
22
  }
26
23
 
27
24
  /** The supplied folders of one package, innermost first (a refusal names the first that holds the state). */
@@ -41,8 +38,14 @@ export function stateDirInside(stateDir: string, roots: readonly StateRoot[]): S
41
38
  /** The refusal text after the code: which supplied folder holds the state directory. */
42
39
  export const stateInsideMessage = (root: StateRoot) => `the review state directory is inside the inspected ${root.kind}; set RIG_REVIEW_STATE_DIR outside it`;
43
40
 
44
- /** Throws `make(code-less message)` when the state directory sits inside one of the package's supplied folders. */
45
- export function assertStateOutside(stateDir: string, p: StateRootsSource, make: (message: string, root: StateRoot) => Error): void {
46
- const root = stateDirInside(stateDir, stateRoots(p));
47
- if (root) throw make(stateInsideMessage(root), root);
41
+ /** Use the caller's refusal type for invalid state paths and paths inside supplied folders. */
42
+ export function assertStateOutside(stateDir: string, p: StateRootsSource, make: (message: string, code?: typeof invalidCode) => Error): void {
43
+ let root: StateRoot | null;
44
+ try {
45
+ root = stateDirInside(stateDir, stateRoots(p));
46
+ } catch (error) {
47
+ if (error instanceof DestinationDirectoryError) throw make(invalidMessage, invalidCode);
48
+ throw error;
49
+ }
50
+ if (root) throw make(stateInsideMessage(root));
48
51
  }
@@ -1,7 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { realpath, stat, lstat, writeFile } from 'node:fs/promises';
3
3
  import { createReadStream } from 'node:fs';
4
- import { basename, dirname, isAbsolute, relative, resolve, parse, sep, type posix } from 'node:path';
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, parse, sep, type posix } from 'node:path';
5
+ import { destinationDirectory } from './destination-directory.ts';
5
6
  import { isDeepStrictEqual } from 'node:util';
6
7
  import { safeFile, type ReviewPackage } from './manifest.ts';
7
8
  import {assertReviewUnchanged,selectedReference,safeSelectedReference,packageSourceHash} from './reference.ts';
@@ -55,10 +56,11 @@ export function stripParentPaths(target:string,paths:Pick<typeof posix,'relative
55
56
  const base=paths.parse(target).root,parts=paths.relative(base,paths.dirname(target)).split(paths.sep).filter(Boolean),parents:string[]=[];let cursor=base;
56
57
  for(const part of parts){cursor=paths.resolve(cursor,part);parents.push(cursor);}return parents;
57
58
  }
58
- /** No symlink parent or package-contained path can become a derived output target. */
59
+ /** Resolve the parent, preserving the output filename for the existence check and exclusive write. */
59
60
  export async function validateStripOutput(output:string,roots:string[]):Promise<string>{
60
- const target=resolve(output);
61
- for(const parent of stripParentPaths(target)){const info=await lstat(parent);if(info.isSymbolicLink()||!info.isDirectory())throw new Error('strip.output: parent must be an existing directory without symlinks');}
61
+ const absolute=resolve(output);
62
+ const parent=destinationDirectory(dirname(absolute),'strip.output: parent must be an existing directory',false);
63
+ const target=join(parent,basename(absolute));
62
64
  for(const root of roots)if(stripPathIsInside(await realpath(root),target))throw new Error('strip.output: derived files must be outside every source package');
63
65
  try{await lstat(target);throw new Error('strip.output: destination already exists');}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;}
64
66
  return target;
package/web/catalog-en.ts CHANGED
@@ -940,6 +940,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
940
940
  "Instance route must be app-absolute": "Instance route must be app-absolute",
941
941
  "Invalid {0} asset path: {1}": "Invalid {0} asset path: {1}",
942
942
  "Issue Markdown": "Issue Markdown",
943
+ "JOB_HOST_OPTION_ID_INVALID: {0} (listener={1}, requested={2})": "JOB_HOST_OPTION_ID_INVALID: {0} (listener={1}, requested={2})",
944
+ "JOB_HOST_REUSE_MISMATCH: {0} (listener={1}, requested={2})": "JOB_HOST_REUSE_MISMATCH: {0} (listener={1}, requested={2})",
943
945
  "JSON body required": "JSON body required",
944
946
  "JSON frames and provenance": "JSON frames and provenance",
945
947
  "Jolt": "Jolt",
@@ -1544,6 +1546,10 @@ export const enCatalog: Readonly<Record<string, string>> = {
1544
1546
  "Runtime event: {0} · {1} s": "Runtime event: {0} · {1} s",
1545
1547
  "Runtime events: none": "Runtime events: none",
1546
1548
  "Runtime start values · wind [{0}] · gravity [{1}] · controls not applied": "Runtime start values · wind [{0}] · gravity [{1}] · controls not applied",
1549
+ "SCENE_PLATE_DIMENSIONS: {0}": "SCENE_PLATE_DIMENSIONS: {0}",
1550
+ "SCENE_PLATE_NOT_READY: {0}": "SCENE_PLATE_NOT_READY: {0}",
1551
+ "SCENE_PLATE_REQUIRED: {0}": "SCENE_PLATE_REQUIRED: {0}",
1552
+ "SCENE_RECT_INVALID: {0}": "SCENE_RECT_INVALID: {0}",
1547
1553
  "SEAM PAIR": "SEAM PAIR",
1548
1554
  "SEGMENTS": "SEGMENTS",
1549
1555
  "SELECTED CHECKPOINT": "SELECTED CHECKPOINT",
@@ -3275,4 +3281,64 @@ export const enCatalog: Readonly<Record<string, string>> = {
3275
3281
  "CORRECTION_APPLY_PENDING: Apply and check the correction first.": "CORRECTION_APPLY_PENDING: Apply and check the correction first.",
3276
3282
  "Saved part notes and pointed comments can be handed off as described corrections.": "Saved part notes and pointed comments can be handed off as described corrections.",
3277
3283
  "Unsupported correction operation": "Unsupported correction operation",
3284
+ "job.binding": "Displayed source binding",
3285
+ "job.cameraSync": "Synchronize cameras",
3286
+ "job.choose": "Choose an option",
3287
+ "job.closed": "This job was explicitly closed.",
3288
+ "job.fail": "Fail",
3289
+ "job.failed": "The next result could not be displayed. The previous result is still shown.",
3290
+ "job.incompatible": "The previous selection is unavailable in this result.",
3291
+ "job.metadata": "Direction metadata only.",
3292
+ "job.pending": "Pending human actions",
3293
+ "job.preparing": "Preparing the next result.",
3294
+ "job.retained": "This draft belongs to {0}. It keeps its original source.",
3295
+ "job.saveCheckpoint": "Save checkpoint outcome",
3296
+ "job.savePartsVerdict": "Save parts verdict",
3297
+ "job.saved": "Human action saved.",
3298
+ "job.signoff": "Save stage approval",
3299
+ "job.time": "Inspection time (s)",
3300
+ "job.title": "Live review job",
3301
+ "job.updated": "Updated from {0} to {1}.",
3302
+ "job.waiting": "Waiting for a published result.",
3303
+ "job.wholeRig": "Whole rig",
3304
+ "job.zoomIn": "Zoom in",
3305
+ "job.zoomOut": "Zoom out",
3306
+ "JOB_ACT_INVALID": "JOB_ACT_INVALID",
3307
+ "JOB_ACT_KIND_DISABLED": "JOB_ACT_KIND_DISABLED",
3308
+ "JOB_ACT_SOURCE_STALE": "JOB_ACT_SOURCE_STALE",
3309
+ "JOB_ACT_UNKNOWN": "JOB_ACT_UNKNOWN",
3310
+ "JOB_AGENT_ISOLATION_HOLE": "JOB_AGENT_ISOLATION_HOLE",
3311
+ "JOB_ASK_INVALID": "JOB_ASK_INVALID",
3312
+ "JOB_ASK_SUPERSEDED": "JOB_ASK_SUPERSEDED",
3313
+ "JOB_AUTHORITY_REFUSED": "JOB_AUTHORITY_REFUSED",
3314
+ "JOB_BODY_LIMIT": "JOB_BODY_LIMIT",
3315
+ "JOB_CAPABILITY_REQUIRED": "JOB_CAPABILITY_REQUIRED",
3316
+ "JOB_CLOSED": "JOB_CLOSED",
3317
+ "JOB_CURSOR_INVALID": "JOB_CURSOR_INVALID",
3318
+ "JOB_DISPLAY_MISMATCH": "JOB_DISPLAY_MISMATCH",
3319
+ "JOB_FREEZE_REQUIRED": "JOB_FREEZE_REQUIRED",
3320
+ "JOB_GENERATION_STALE": "JOB_GENERATION_STALE",
3321
+ "JOB_IDEMPOTENCY_CONFLICT": "JOB_IDEMPOTENCY_CONFLICT",
3322
+ "JOB_LOOPBACK_REQUIRED": "JOB_LOOPBACK_REQUIRED",
3323
+ "JOB_PRELOAD_CANCELLED": "JOB_PRELOAD_CANCELLED",
3324
+ "JOB_PRELOAD_FAILED": "JOB_PRELOAD_FAILED",
3325
+ "JOB_PUBLICATION_UNKNOWN": "JOB_PUBLICATION_UNKNOWN",
3326
+ "JOB_RECORD_INCOMPLETE": "JOB_RECORD_INCOMPLETE",
3327
+ "JOB_RECORD_MOVED": "JOB_RECORD_MOVED",
3328
+ "JOB_REQUEST_INVALID": "JOB_REQUEST_INVALID",
3329
+ "JOB_ROOT_REPLACED": "JOB_ROOT_REPLACED",
3330
+ "JOB_SAME_ORIGIN_REQUIRED": "JOB_SAME_ORIGIN_REQUIRED",
3331
+ "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3332
+ "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3333
+ "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3334
+ "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3335
+ "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3336
+ "JOB_UNKNOWN": "JOB_UNKNOWN",
3337
+ "JOB_VISUAL_UNAVAILABLE": "JOB_VISUAL_UNAVAILABLE",
3338
+ "JOB_WINDOW_CLEANUP_FAILED": "JOB_WINDOW_CLEANUP_FAILED",
3339
+ "JOB_WINDOW_ELEMENT_MISSING": "JOB_WINDOW_ELEMENT_MISSING",
3340
+ "JOB_WINDOW_FAILED": "JOB_WINDOW_FAILED",
3341
+ "KEY_TIME_OUT_OF_DOMAIN": "KEY_TIME_OUT_OF_DOMAIN",
3342
+ "MODEL_UNAVAILABLE": "MODEL_UNAVAILABLE",
3343
+ "REFERENCE_OUT_OF_DOMAIN": "REFERENCE_OUT_OF_DOMAIN",
3278
3344
  };
package/web/catalog-ko.ts CHANGED
@@ -940,6 +940,8 @@ export const koCatalog: Readonly<Record<string, string>> = {
940
940
  "Instance route must be app-absolute": "인스턴스 경로는 앱 절대 경로여야 함",
941
941
  "Invalid {0} asset path: {1}": "유효하지 않은 {0} 에셋 경로: {1}",
942
942
  "Issue Markdown": "이슈 마크다운",
943
+ "JOB_HOST_OPTION_ID_INVALID: {0} (listener={1}, requested={2})": "JOB_HOST_OPTION_ID_INVALID: {0} (listener={1}, requested={2})",
944
+ "JOB_HOST_REUSE_MISMATCH: {0} (listener={1}, requested={2})": "JOB_HOST_REUSE_MISMATCH: {0} (listener={1}, requested={2})",
943
945
  "JSON body required": "JSON 본문이 필요합니다",
944
946
  "JSON frames and provenance": "JSON 프레임 및 출처 정보",
945
947
  "Jolt": "충격(졸트)",
@@ -1544,6 +1546,10 @@ export const koCatalog: Readonly<Record<string, string>> = {
1544
1546
  "Runtime event: {0} · {1} s": "런타임 이벤트: {0} · {1}초",
1545
1547
  "Runtime events: none": "런타임 이벤트: 없음",
1546
1548
  "Runtime start values · wind [{0}] · gravity [{1}] · controls not applied": "런타임 초기값 · 바람 [{0}] · 중력 [{1}] · 컨트롤 미적용",
1549
+ "SCENE_PLATE_DIMENSIONS: {0}": "SCENE_PLATE_DIMENSIONS: {0}",
1550
+ "SCENE_PLATE_NOT_READY: {0}": "SCENE_PLATE_NOT_READY: {0}",
1551
+ "SCENE_PLATE_REQUIRED: {0}": "SCENE_PLATE_REQUIRED: {0}",
1552
+ "SCENE_RECT_INVALID: {0}": "SCENE_RECT_INVALID: {0}",
1547
1553
  "SEAM PAIR": "심(Seam) 쌍",
1548
1554
  "SEGMENTS": "세그먼트",
1549
1555
  "SELECTED CHECKPOINT": "선택된 체크포인트",
@@ -3275,4 +3281,64 @@ export const koCatalog: Readonly<Record<string, string>> = {
3275
3281
  "CORRECTION_APPLY_PENDING: Apply and check the correction first.": "CORRECTION_APPLY_PENDING: 먼저 수정을 적용하고 검사해 주세요.",
3276
3282
  "Saved part notes and pointed comments can be handed off as described corrections.": "저장한 파츠 메모와 위치 댓글을 수정 요청으로 인계할 수 있어요.",
3277
3283
  "Unsupported correction operation": "지원하지 않는 수정 작업",
3284
+ "job.binding": "표시된 소스 연결 정보",
3285
+ "job.cameraSync": "카메라 동기화",
3286
+ "job.choose": "옵션 선택",
3287
+ "job.closed": "이 작업은 명시적으로 종료되었습니다.",
3288
+ "job.fail": "실패",
3289
+ "job.failed": "다음 결과를 표시하지 못했습니다. 이전 결과를 계속 표시합니다.",
3290
+ "job.incompatible": "이 결과에서 이전 선택 항목을 사용할 수 없습니다.",
3291
+ "job.metadata": "연출 메타데이터만 표시합니다.",
3292
+ "job.pending": "대기 중인 사용자 작업",
3293
+ "job.preparing": "다음 결과를 준비하고 있습니다.",
3294
+ "job.retained": "이 초안은 {0}에 속합니다. 원래 소스에 연결된 채로 보관됩니다.",
3295
+ "job.saveCheckpoint": "체크포인트 결과 저장",
3296
+ "job.savePartsVerdict": "파츠 판정 저장",
3297
+ "job.saved": "사용자 작업을 저장했습니다.",
3298
+ "job.signoff": "단계 승인 저장",
3299
+ "job.time": "검사 시간 (초)",
3300
+ "job.title": "실시간 리뷰 작업",
3301
+ "job.updated": "{0}에서 {1}(으)로 업데이트되었습니다.",
3302
+ "job.waiting": "게시된 결과를 기다리고 있습니다.",
3303
+ "job.wholeRig": "전체 리그",
3304
+ "job.zoomIn": "확대",
3305
+ "job.zoomOut": "축소",
3306
+ "JOB_ACT_INVALID": "JOB_ACT_INVALID",
3307
+ "JOB_ACT_KIND_DISABLED": "JOB_ACT_KIND_DISABLED",
3308
+ "JOB_ACT_SOURCE_STALE": "JOB_ACT_SOURCE_STALE",
3309
+ "JOB_ACT_UNKNOWN": "JOB_ACT_UNKNOWN",
3310
+ "JOB_AGENT_ISOLATION_HOLE": "JOB_AGENT_ISOLATION_HOLE",
3311
+ "JOB_ASK_INVALID": "JOB_ASK_INVALID",
3312
+ "JOB_ASK_SUPERSEDED": "JOB_ASK_SUPERSEDED",
3313
+ "JOB_AUTHORITY_REFUSED": "JOB_AUTHORITY_REFUSED",
3314
+ "JOB_BODY_LIMIT": "JOB_BODY_LIMIT",
3315
+ "JOB_CAPABILITY_REQUIRED": "JOB_CAPABILITY_REQUIRED",
3316
+ "JOB_CLOSED": "JOB_CLOSED",
3317
+ "JOB_CURSOR_INVALID": "JOB_CURSOR_INVALID",
3318
+ "JOB_DISPLAY_MISMATCH": "JOB_DISPLAY_MISMATCH",
3319
+ "JOB_FREEZE_REQUIRED": "JOB_FREEZE_REQUIRED",
3320
+ "JOB_GENERATION_STALE": "JOB_GENERATION_STALE",
3321
+ "JOB_IDEMPOTENCY_CONFLICT": "JOB_IDEMPOTENCY_CONFLICT",
3322
+ "JOB_LOOPBACK_REQUIRED": "JOB_LOOPBACK_REQUIRED",
3323
+ "JOB_PRELOAD_CANCELLED": "JOB_PRELOAD_CANCELLED",
3324
+ "JOB_PRELOAD_FAILED": "JOB_PRELOAD_FAILED",
3325
+ "JOB_PUBLICATION_UNKNOWN": "JOB_PUBLICATION_UNKNOWN",
3326
+ "JOB_RECORD_INCOMPLETE": "JOB_RECORD_INCOMPLETE",
3327
+ "JOB_RECORD_MOVED": "JOB_RECORD_MOVED",
3328
+ "JOB_REQUEST_INVALID": "JOB_REQUEST_INVALID",
3329
+ "JOB_ROOT_REPLACED": "JOB_ROOT_REPLACED",
3330
+ "JOB_SAME_ORIGIN_REQUIRED": "JOB_SAME_ORIGIN_REQUIRED",
3331
+ "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3332
+ "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3333
+ "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3334
+ "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3335
+ "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3336
+ "JOB_UNKNOWN": "JOB_UNKNOWN",
3337
+ "JOB_VISUAL_UNAVAILABLE": "JOB_VISUAL_UNAVAILABLE",
3338
+ "JOB_WINDOW_CLEANUP_FAILED": "JOB_WINDOW_CLEANUP_FAILED",
3339
+ "JOB_WINDOW_ELEMENT_MISSING": "JOB_WINDOW_ELEMENT_MISSING",
3340
+ "JOB_WINDOW_FAILED": "JOB_WINDOW_FAILED",
3341
+ "KEY_TIME_OUT_OF_DOMAIN": "KEY_TIME_OUT_OF_DOMAIN",
3342
+ "MODEL_UNAVAILABLE": "MODEL_UNAVAILABLE",
3343
+ "REFERENCE_OUT_OF_DOMAIN": "REFERENCE_OUT_OF_DOMAIN",
3278
3344
  };