@rig-c/review 1.5.4 → 1.7.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.
- package/docs/DESIGN.md +58 -4
- package/docs/PANELS.md +31 -0
- package/docs/PARTS_VIEW.md +199 -4
- package/docs/REVIEW_PACKAGE.md +9 -0
- package/docs/WORKFLOWS.md +4 -0
- package/package.json +4 -2
- package/src/cli.ts +6 -5
- package/src/comment-crops.ts +19 -6
- package/src/compare-html.ts +3 -1
- package/src/compare-server.ts +5 -1
- package/src/front.ts +25 -3
- package/src/parts-comment-crops.ts +31 -0
- package/src/parts-comment.ts +33 -0
- package/src/parts-comparison.ts +20 -0
- package/src/parts-server.ts +29 -7
- package/src/parts-view.ts +185 -22
- package/src/server.ts +5 -1
- package/src/stage-parts.ts +37 -0
- package/web/camera-view.ts +9 -8
- package/web/catalog-en.ts +53 -0
- package/web/catalog-ko.ts +53 -0
- package/web/compare.css +16 -0
- package/web/compare.html +2 -2
- package/web/compare.ts +3 -0
- package/web/index.html +2 -2
- package/web/main.ts +35 -104
- package/web/parts-flags.ts +11 -2
- package/web/parts-render.ts +57 -3
- package/web/parts-viewport-provider.ts +14 -0
- package/web/parts.css +47 -6
- package/web/parts.html +11 -3
- package/web/parts.ts +165 -26
- package/web/rig-viewport-provider.ts +44 -0
- package/web/stage-comments.ts +38 -25
- package/web/stage-nav.ts +45 -0
- package/web/styles.css +16 -0
- package/web/view-controls.ts +6 -4
- package/web/viewport-capture.ts +2 -1
- package/web/viewport-controller.ts +93 -0
- package/web/viewport-pair.ts +5 -0
package/src/front.ts
CHANGED
|
@@ -50,6 +50,8 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
|
|
|
50
50
|
const read=method==='GET'||method==='HEAD',get:Route={mutation:false,limit:0,timeoutMs:30000,control:false};
|
|
51
51
|
if(path===LIVE_PATH)return method==='GET'?{...get,live:true}:null;
|
|
52
52
|
if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
|
|
53
|
+
if(['/stage-parts.html','/parts.js','/parts.css'].includes(path))return read?get:null;
|
|
54
|
+
if((mode==='single'?/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/:/^\/api\/compare\/(?:a|b)\/stage-parts(?:\/(?:image|page)\/\d+)?$/).test(path))return read?get:null;
|
|
53
55
|
if(path==='/api/control/config')return method==='GET'?{...get,control:true}:null;
|
|
54
56
|
if(['/api/control/register','/api/control/poll','/api/control/ack','/api/control/close'].includes(path))return method==='POST'?{mutation:true,limit:16384,timeoutMs:10000,control:true}:null;
|
|
55
57
|
const session=mode==='single'?'/api/session':'/api/compare/session',strip=mode==='single'?'/api/strip':'/api/compare/strip';
|
|
@@ -89,6 +91,26 @@ async function instanceRecord(control:string,key:string):Promise<RecordFile|null
|
|
|
89
91
|
/** Worker statuses map to named front codes; worker text never reaches the client. */
|
|
90
92
|
const upstreamFailure:Record<number,string>={400:'FRONT_UPSTREAM_REJECTED',403:'FRONT_UPSTREAM_FORBIDDEN',404:'FRONT_UPSTREAM_NOT_FOUND',405:'FRONT_UPSTREAM_METHOD',409:'FRONT_UPSTREAM_CONFLICT'};
|
|
91
93
|
const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
|
|
94
|
+
/** The trusted atlas frame alone may carry this closed navigation query. */
|
|
95
|
+
export function stageFrameQuery(mode:'single'|'compare',search:string):boolean {
|
|
96
|
+
const params=new URLSearchParams(search),keys=[...params.keys()];
|
|
97
|
+
const allowed=mode==='single'?['stageEmbed','lang']:['stageEmbed','lang','side'];
|
|
98
|
+
return keys.length===allowed.length&&new Set(keys).size===keys.length&&keys.every(k=>allowed.includes(k))&¶ms.get('stageEmbed')==='1'&&['en','ko'].includes(params.get('lang')??'')&&(mode==='single'||['a','b'].includes(params.get('side')??''));
|
|
99
|
+
}
|
|
100
|
+
/** Preserve only this closed, bounded stage-data refusal; never relay arbitrary worker text. */
|
|
101
|
+
async function stagePartsRefusal(mode:'single'|'compare',method:string,path:string,response:Response):Promise<string|null>{
|
|
102
|
+
const stageData=mode==='single'?path==='/api/stage-parts':/^\/api\/compare\/(?:a|b)\/stage-parts$/.test(path);
|
|
103
|
+
if(!stageData||method!=='GET'||response.status!==409||!/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type')??''))return null;
|
|
104
|
+
const limit=512,declared=response.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>limit))return null;
|
|
105
|
+
const reader=response.body?.getReader();if(!reader)return null;
|
|
106
|
+
try{
|
|
107
|
+
const chunks:Uint8Array[]=[];let bytes=0;
|
|
108
|
+
for(;;){const {value,done}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>limit){void reader.cancel().catch(()=>{});return null;}chunks.push(value);}
|
|
109
|
+
const body=new Uint8Array(bytes);let offset=0;for(const chunk of chunks){body.set(chunk,offset);offset+=chunk.byteLength;}
|
|
110
|
+
const data:unknown=JSON.parse(new TextDecoder().decode(body)),named='PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.';
|
|
111
|
+
return data!==null&&typeof data==='object'&&!Array.isArray(data)&&Object.keys(data).length===1&&(data as {error?:unknown}).error===named?named:null;
|
|
112
|
+
}catch{return null;}finally{reader.releaseLock();}
|
|
113
|
+
}
|
|
92
114
|
export const maximumUpstreamStreams=32;
|
|
93
115
|
interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
|
|
94
116
|
export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
|
|
@@ -108,7 +130,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
|
|
|
108
130
|
if(req.headers.get('sec-fetch-site')==='cross-site'||sentOrigin!==null&&sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
109
131
|
const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
|
|
110
132
|
const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
|
|
111
|
-
const landing=path==='/'||path==='/index.html';if(
|
|
133
|
+
const landing=path==='/'||path==='/index.html',stageFrame=path==='/stage-parts.html';if(stageFrame?!stageFrameQuery(record.mode,url.search):!landing&&!!url.search)return refuse('FRONT_QUERY_REFUSED',400);
|
|
112
134
|
if(route.live){
|
|
113
135
|
if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
114
136
|
if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
|
|
@@ -150,10 +172,10 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
|
|
|
150
172
|
active++;let released=false;const abort=new AbortController(),timer=setTimeout(()=>abort.abort(),route.timeoutMs);const release=()=>{if(released)return;released=true;active--;clearTimeout(timer);};
|
|
151
173
|
req.signal.addEventListener('abort',()=>abort.abort(),{once:true});
|
|
152
174
|
let upstream:Response;
|
|
153
|
-
try{upstream=await fetch(record.origin+path+(landing?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
|
|
175
|
+
try{upstream=await fetch(record.origin+path+(landing||stageFrame?url.search:''),{method:req.method,headers,...(body?{body}:{}),redirect:'manual',signal:abort.signal});}
|
|
154
176
|
catch{release();return abort.signal.aborted&&!req.signal.aborted?refuse('FRONT_UPSTREAM_TIMEOUT',504):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);}
|
|
155
177
|
if(upstream.headers.get(openKeyHeader)!==key){void upstream.body?.cancel().catch(()=>{});release();return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);}
|
|
156
|
-
if(upstream.status>=400&&upstream.status!==416){void upstream.body?.cancel().catch(()=>{});release();const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
|
|
178
|
+
if(upstream.status>=400&&upstream.status!==416){const named=await stagePartsRefusal(record.mode,req.method,path,upstream);void upstream.body?.cancel().catch(()=>{});release();if(named)return refuse(named,409);const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
|
|
157
179
|
const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
|
|
158
180
|
if(!upstream.body||req.method==='HEAD'){void upstream.body?.cancel().catch(()=>{});release();return new Response(null,{status:upstream.status,headers:out});}
|
|
159
181
|
if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Native evidence is cut from the bound original PNG, never from a displayed alpha mask. */
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {readFile} from 'node:fs/promises';
|
|
4
|
+
import {PNG} from 'pngjs';
|
|
5
|
+
import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
|
|
6
|
+
import {validatePngCrop,storePngCrop,readPngCrop} from './comment-crops.ts';
|
|
7
|
+
import {verdictSource,type PartsViewPackage} from './parts-view.ts';
|
|
8
|
+
export async function preparePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative=false):Promise<PartsComment>{return resolvePartsComment(pkg,raw,requireNative,true);}
|
|
9
|
+
export async function validateStoredPartsComment(pkg:PartsViewPackage,raw:unknown):Promise<PartsComment>{return resolvePartsComment(pkg,raw,true,false);}
|
|
10
|
+
async function resolvePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative:boolean,persist:boolean):Promise<PartsComment>{
|
|
11
|
+
const c=parsePartsComment(raw,requireNative),item=pkg.items.find(i=>i.name===c.part);
|
|
12
|
+
if(pkg.mode!=='parts'||!item)throw new Error('PARTS_COMMENT_UNAVAILABLE: original part image required');
|
|
13
|
+
const path=pkg.imagePaths[item.index],file=pkg.files.find(f=>f.abs===path);if(!path||!file)throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
|
|
14
|
+
assertPartsCommentBinding(c,item,file.sha256,verdictSource(pkg).sha256);
|
|
15
|
+
if(c.view.comparison?.mode==='overlay'&&!pkg.painting)throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
|
|
16
|
+
const bytes=await readFile(path);if(createHash('sha256').update(bytes).digest('hex')!==file.sha256)throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
|
|
17
|
+
validatePngCrop(c.crop);
|
|
18
|
+
const original=PNG.sync.read(bytes),r=c.imageRegion;
|
|
19
|
+
if(original.width!==item.w||original.height!==item.h)throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
|
|
20
|
+
if(r.width*r.height>16777216)throw new Error('PARTS_COMMENT_CROP_LIMIT: native crop exceeds 16 million pixels');
|
|
21
|
+
const native=new PNG({width:r.width,height:r.height});for(let y=0;y<r.height;y++)original.data.copy(native.data,y*r.width*4,((r.y+y)*original.width+r.x)*4,((r.y+y)*original.width+r.x+r.width)*4);
|
|
22
|
+
if(requireNative){
|
|
23
|
+
const stored=await readPngCrop(c.nativeCrop!),decoded=PNG.sync.read(stored);
|
|
24
|
+
if(decoded.width!==r.width||decoded.height!==r.height||!decoded.data.equals(native.data))throw new Error('PARTS_COMMENT_NATIVE_CROP_TAMPERED: native crop differs from bound original');
|
|
25
|
+
if(persist)await storePngCrop(c.crop);else await readPngCrop(c.crop);
|
|
26
|
+
return c;
|
|
27
|
+
}
|
|
28
|
+
const png=PNG.sync.write(native),sha256=createHash('sha256').update(png).digest('hex'),nativeCrop={path:`comment-crops/${sha256}.png`,sha256,width:r.width,height:r.height};
|
|
29
|
+
await storePngCrop(c.crop);await storePngCrop({...nativeCrop,png:'data:image/png;base64,'+png.toString('base64')});
|
|
30
|
+
return {...c,nativeCrop};
|
|
31
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Closed parts evidence. No synthetic model, frame, slot or package identity. */
|
|
2
|
+
import {parsePartsComparison,type PartsComparison} from './parts-comparison.ts';
|
|
3
|
+
import type {MarkRegion} from './stage-comment.ts';
|
|
4
|
+
export interface PartsCrop {path:string;sha256:string;width:number;height:number}
|
|
5
|
+
export interface PartsComment {
|
|
6
|
+
schema:'rig-review-parts-comment/1';id:string;summary:string;part:string;imageHash:string;sourceHash:string;
|
|
7
|
+
imageRegion:MarkRegion;rigRegion:MarkRegion;
|
|
8
|
+
view:{camera:{zoom:number;center:{x:number;y:number};viewport:{width:number;height:number}};cameraSync:boolean;referenceCamera:{zoom:number;center:{x:number;y:number};viewport:{width:number;height:number}}|null;background:string;alpha:boolean;footprints:boolean;mesh:boolean;comparison?:PartsComparison};
|
|
9
|
+
crop:PartsCrop&{png:string};nativeCrop:PartsCrop|null;
|
|
10
|
+
}
|
|
11
|
+
const fail=(code:string,why:string):never=>{throw new Error(code+': '+why);};
|
|
12
|
+
const obj=(v:unknown):Record<string,any>=>v!==null&&typeof v==='object'&&!Array.isArray(v)?v as Record<string,any>:fail('PARTS_COMMENT_INVALID','object required');
|
|
13
|
+
const exact=(v:Record<string,any>,keys:string[])=>{if(Object.keys(v).length!==keys.length||keys.some(k=>!Object.hasOwn(v,k)))fail('PARTS_COMMENT_INVALID','unknown or missing fields');};
|
|
14
|
+
const finite=(v:unknown):v is number=>typeof v==='number'&&Number.isFinite(v)&&Math.abs(v)<=Number.MAX_SAFE_INTEGER;
|
|
15
|
+
const hash=(v:unknown)=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
16
|
+
export function parsePartsComment(raw:unknown,prepared=true):PartsComment {
|
|
17
|
+
const v=obj(raw);exact(v,['schema','id','summary','part','imageHash','sourceHash','imageRegion','rigRegion','view','crop','nativeCrop']);
|
|
18
|
+
if(v.schema!=='rig-review-parts-comment/1'||typeof v.id!=='string'||!v.id||v.id.length>128||typeof v.summary!=='string'||!v.summary.trim()||v.summary.length>1000||typeof v.part!=='string'||!v.part||v.part.length>512||!hash(v.imageHash)||!hash(v.sourceHash))fail('PARTS_COMMENT_INVALID','schema, text or source binding');
|
|
19
|
+
for(const key of ['imageRegion','rigRegion']){const r=obj(v[key]);exact(r,['x','y','width','height']);if(!Object.values(r).every(finite))fail('PARTS_COMMENT_INVALID','finite region required');if(key==='imageRegion'&&!Object.values(r).every(Number.isSafeInteger))fail('PARTS_COMMENT_FRACTIONAL','image coordinates must be integer pixels');if(r.width<=0||r.height<=0)fail('PARTS_COMMENT_EMPTY','positive region required');}
|
|
20
|
+
const view=obj(v.view);exact(view,['camera','cameraSync','referenceCamera','background','alpha','footprints','mesh',...(Object.hasOwn(view,'comparison')?['comparison']:[])]);if(Object.hasOwn(view,'comparison'))parsePartsComparison(view.comparison);if(!['green','magenta','black','white','checker'].includes(view.background)||![view.alpha,view.footprints,view.mesh,view.cameraSync].every(n=>typeof n==='boolean'))fail('PARTS_COMMENT_INVALID','view state');
|
|
21
|
+
for(const rawCamera of [view.camera,...(view.referenceCamera===null?[]:[view.referenceCamera])]){const c=obj(rawCamera);exact(c,['zoom','center','viewport']);exact(obj(c.center),['x','y']);exact(obj(c.viewport),['width','height']);if(!finite(c.zoom)||c.zoom<=0||c.zoom>16||!Object.values(c.center).every(finite)||!Object.values(c.viewport).every(n=>finite(n)&&n>0&&n<=65536))fail('PARTS_CAMERA_RANGE','native scale or camera extent');}
|
|
22
|
+
for(const [crop,inline]of [[v.crop,true],[v.nativeCrop,false]] as const){if(crop===null&&!inline&&!prepared)continue;const p=obj(crop);exact(p,['path','sha256','width','height',...(inline?['png']:[])]);if(!hash(p.sha256)||p.path!==`comment-crops/${p.sha256}.png`||![p.width,p.height].every(n=>Number.isSafeInteger(n)&&n>0&&n<=16384)||inline&&(typeof p.png!=='string'||p.png.length>200000||p.width>1024||p.height>1024))fail('PARTS_COMMENT_CROP_INVALID','bounded content-addressed crop');}
|
|
23
|
+
return v as PartsComment;
|
|
24
|
+
}
|
|
25
|
+
/** Drag edges snap outward to whole native pixels. OOB is refused by the binding check, never clipped. */
|
|
26
|
+
export function snapImageRegion(r:MarkRegion):MarkRegion {if(r.width<=0||r.height<=0)return {x:Math.floor(r.x),y:Math.floor(r.y),width:0,height:0};const x=Math.floor(r.x),y=Math.floor(r.y);return {x,y,width:Math.ceil(r.x+r.width)-x,height:Math.ceil(r.y+r.height)-y};}
|
|
27
|
+
export function assertPartsCommentBinding(c:PartsComment,item:{name:string;x:number;y:number;w:number;h:number},imageHash:string,sourceHash:string):void {
|
|
28
|
+
if(c.part!==item.name)fail('PARTS_COMMENT_PART_MISMATCH','comment belongs to another part');
|
|
29
|
+
if(c.imageHash!==imageHash||c.sourceHash!==sourceHash)fail('PARTS_COMMENT_STALE_SOURCE','original image or package source hash differs');
|
|
30
|
+
const camera=c.view.camera,fit=Math.max(.001,Math.min((camera.viewport.width-24)/item.w,(camera.viewport.height-24)/item.h));if(camera.zoom<Math.min(fit,1))fail('PARTS_CAMERA_RANGE','native zoom below fit/1 minimum');
|
|
31
|
+
const r=c.imageRegion;if(r.x<0||r.y<0||r.x+r.width>item.w||r.y+r.height>item.h)fail('PARTS_COMMENT_OUT_OF_BOUNDS','region exceeds original image');
|
|
32
|
+
if(c.rigRegion.x!==item.x+r.x||c.rigRegion.y!==item.y+r.y||c.rigRegion.width!==r.width||c.rigRegion.height!==r.height)fail('PARTS_COMMENT_RIG_REGION','rig region must be exact placement plus image region');
|
|
33
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Visual comparison settings are evidence, never a producer verdict. Older comments omit them. */
|
|
2
|
+
export interface PartsComparison {mode:'part'|'overlay';opacity:number}
|
|
3
|
+
export const defaultPartsComparison = ():PartsComparison => ({mode:'part',opacity:.5});
|
|
4
|
+
export function parsePartsComparison(raw:unknown):PartsComparison {
|
|
5
|
+
const v=raw as PartsComparison;
|
|
6
|
+
if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).length!==2||!['mode','opacity'].every(k=>Object.hasOwn(v,k))||!['part','overlay'].includes(v.mode)||typeof v.opacity!=='number'||!Number.isFinite(v.opacity)||v.opacity<0||v.opacity>1)throw new Error('PARTS_COMPARISON_INVALID: part/overlay mode and opacity 0..1 required');
|
|
7
|
+
return v;
|
|
8
|
+
}
|
|
9
|
+
export interface PaintingRectangle {x:number;y:number;width:number;height:number}
|
|
10
|
+
/** Whole-canvas geometry of parts@2.17.0 sourceInRig: trunc(source size * declared scale).
|
|
11
|
+
* This validates original input dimensions, not equality with the producer's resampled pixels. */
|
|
12
|
+
export function assertOriginalPaintingSize(width:number,height:number,rigSize:readonly number[]|null,scale:unknown):void {
|
|
13
|
+
if(typeof scale!=='number'||!Number.isFinite(scale)||scale<=0||!rigSize||!rigSize.every(n=>Number.isSafeInteger(n)&&n>0))throw new Error('PARTS_PAINTING_MAPPING: declared rig_size and positive scale_rig_per_source required');
|
|
14
|
+
if(Math.trunc(width*scale)!==rigSize[0]||Math.trunc(height*scale)!==rigSize[1])throw new Error('PARTS_PAINTING_SIZE: original painting dimensions times declared scale must match the rig canvas');
|
|
15
|
+
}
|
|
16
|
+
/** Exact continuous source rectangle for a visual comparison. No pixel pairing, rounding or producer resampler. */
|
|
17
|
+
export function paintingRectangle(item:{x:number;y:number;w:number;h:number},rigSize:readonly number[],painting:{width:number;height:number}):PaintingRectangle {
|
|
18
|
+
const x=painting.width/rigSize[0]!,y=painting.height/rigSize[1]!;
|
|
19
|
+
return {x:item.x*x,y:item.y*y,width:item.w*x,height:item.h*y};
|
|
20
|
+
}
|
package/src/parts-server.ts
CHANGED
|
@@ -3,7 +3,9 @@ import { readFile } from 'node:fs/promises';
|
|
|
3
3
|
import { appRoot, buildWeb } from './build.ts';
|
|
4
4
|
import { accessGate } from './open-protocol.ts';
|
|
5
5
|
import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
|
|
6
|
-
import {
|
|
6
|
+
import {preparePartsComment} from './parts-comment-crops.ts';
|
|
7
|
+
import {serveReference} from './reference.ts';
|
|
8
|
+
import { partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdict, servedImage, type PartsViewPackage } from './parts-view.ts';
|
|
7
9
|
|
|
8
10
|
const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
|
|
9
11
|
const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
|
|
@@ -11,9 +13,26 @@ const BODY_LIMIT = 4 * 1024 * 1024;
|
|
|
11
13
|
|
|
12
14
|
async function bodyJson(req: Request): Promise<unknown> {
|
|
13
15
|
if (!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type') ?? '')) throw new Error('Expected application/json');
|
|
14
|
-
const
|
|
15
|
-
if (
|
|
16
|
-
|
|
16
|
+
const reader = req.body?.getReader();
|
|
17
|
+
if (!reader) return JSON.parse('');
|
|
18
|
+
const chunks: Uint8Array[] = [];
|
|
19
|
+
let bytes = 0;
|
|
20
|
+
try {
|
|
21
|
+
for (;;) {
|
|
22
|
+
const { value, done } = await reader.read();
|
|
23
|
+
if (done) break;
|
|
24
|
+
bytes += value.byteLength;
|
|
25
|
+
if (bytes > BODY_LIMIT) {
|
|
26
|
+
await reader.cancel().catch(() => {});
|
|
27
|
+
throw new Error('Verdict payload exceeds 4 MiB');
|
|
28
|
+
}
|
|
29
|
+
chunks.push(value);
|
|
30
|
+
}
|
|
31
|
+
} finally { reader.releaseLock(); }
|
|
32
|
+
const body = new Uint8Array(bytes);
|
|
33
|
+
let offset = 0;
|
|
34
|
+
for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; }
|
|
35
|
+
return JSON.parse(new TextDecoder().decode(body));
|
|
17
36
|
}
|
|
18
37
|
|
|
19
38
|
export interface PartsServerOptions { port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number; onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void }
|
|
@@ -35,18 +54,21 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
|
|
|
35
54
|
}
|
|
36
55
|
live.onRequestStart(url.pathname);
|
|
37
56
|
try {
|
|
38
|
-
if (url.pathname === '/api/parts' && req.method === 'GET') return json(partsViewJson(pkg,
|
|
57
|
+
if (url.pathname === '/api/parts' && req.method === 'GET'){await assertPartsUnchanged(pkg);return json(partsViewJson(pkg,await readVerdict(pkg)));}
|
|
58
|
+
if(url.pathname==='/api/parts/comment'&&req.method==='POST'){if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);await assertPartsUnchanged(pkg);return json({comment:await preparePartsComment(pkg,await bodyJson(req))});}
|
|
59
|
+
if(url.pathname==='/api/parts/export'&&req.method==='GET'){const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
|
|
39
60
|
if (url.pathname === '/api/parts/verdict' && req.method === 'POST') {
|
|
40
61
|
if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
|
|
41
62
|
saving = true;
|
|
42
63
|
try { return json({ verdict: await saveVerdict(pkg, await bodyJson(req)) }); } finally { saving = false; }
|
|
43
64
|
}
|
|
65
|
+
if(url.pathname==='/api/parts/painting'&&req.method==='GET'){if(!pkg.painting)return json({error:'PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting'},404);return serveReference(req,pkg.painting.abs,pkg.painting.sha256,headers);}
|
|
44
66
|
const image = /^\/api\/parts\/(image|page)\/(\d+)$/.exec(url.pathname);
|
|
45
67
|
if (image && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
46
68
|
const path = servedImage(pkg, image[1] as 'image' | 'page', Number(image[2]));
|
|
47
69
|
if (!path) return json({ error: 'Not found' }, 404);
|
|
48
|
-
const
|
|
49
|
-
|
|
70
|
+
const pinned=pkg.files.find(f=>f.abs===path);if(!pinned)return json({error:'PARTS_IMAGE_UNBOUND'},409);return serveReference(req,path,pinned.sha256,headers);
|
|
71
|
+
|
|
50
72
|
}
|
|
51
73
|
if (url.pathname === '/parts.js') return new Response(req.method === 'HEAD' ? null : bundle, { headers: { ...headers, 'Content-Type': 'text/javascript' } });
|
|
52
74
|
if (url.pathname === '/' || url.pathname === '/parts.html') return new Response(req.method === 'HEAD' ? null : await readFile(appRoot + 'web/parts.html'), { headers: { ...headers, 'Content-Type': 'text/html; charset=utf-8' } });
|
package/src/parts-view.ts
CHANGED
|
@@ -10,17 +10,22 @@
|
|
|
10
10
|
* - `mesh_report.json` rows: `contour.bridges.faint[]` (rig-parts #326), each a faint island the mesh left out;
|
|
11
11
|
* - `check.json`: a gate whose `status` is FAIL or WARN, `seam_pairs` and `figure_openings`, on every part they name.
|
|
12
12
|
*
|
|
13
|
-
* The sign-off is `rig-review-parts-verdict/
|
|
13
|
+
* The sign-off is `rig-review-parts-verdict/2` (docs/PARTS_VIEW.md), written beside `parts.json` by default. Its
|
|
14
14
|
* `source.sha256` is the sha256 over the UTF-8 lines `<path>\t<sha256>\n`, sorted by path bytewise, where every path
|
|
15
15
|
* is relative to the verdict file's directory. rig-c/create recomputes it, so the definition is fixed here.
|
|
16
16
|
*/
|
|
17
|
+
import {assertOriginalPaintingSize} from './parts-comparison.ts';
|
|
18
|
+
import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
|
|
19
|
+
import {preparePartsComment,validateStoredPartsComment} from './parts-comment-crops.ts';
|
|
20
|
+
import {resolvedCropPath} from './comment-crops.ts';
|
|
17
21
|
import { createHash } from 'node:crypto';
|
|
18
22
|
import { existsSync } from 'node:fs';
|
|
19
|
-
import { mkdir, readFile, realpath, rename, stat, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
20
24
|
import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
|
|
21
|
-
import {
|
|
25
|
+
import { PNG } from 'pngjs';
|
|
26
|
+
import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
|
|
22
27
|
|
|
23
|
-
export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/
|
|
28
|
+
export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/2';
|
|
24
29
|
export const PARTS_VERDICT_FILE = 'parts-review.json';
|
|
25
30
|
export const PARTS_NOTE_LIMIT = 10000;
|
|
26
31
|
export type PartsViewMode = 'parts' | 'atlas';
|
|
@@ -32,7 +37,9 @@ export interface HashedFile { path: string; bytes: number; sha256: string }
|
|
|
32
37
|
interface LocalFile { abs: string; bytes: number; sha256: string }
|
|
33
38
|
|
|
34
39
|
/** A part (parts mode) or a named region (atlas mode). Boxes are rig px (parts) or page px (atlas). */
|
|
40
|
+
export interface PartMesh { vertices: number[]; triangles: number[]; figures: Record<string, unknown>; width: number; height: number; image: string }
|
|
35
41
|
export interface ViewItem {
|
|
42
|
+
mesh?: PartMesh;
|
|
36
43
|
name: string;
|
|
37
44
|
/** Draw order, back first (parts mode); the region's place in the atlas file (atlas mode). */
|
|
38
45
|
index: number;
|
|
@@ -52,6 +59,7 @@ export type ProducerFlag =
|
|
|
52
59
|
root: string; status: string | null; entry: Record<string, unknown> };
|
|
53
60
|
|
|
54
61
|
export interface PartsViewPackage {
|
|
62
|
+
painting?:{sha256:string;width:number;height:number;abs:string};
|
|
55
63
|
mode: PartsViewMode;
|
|
56
64
|
root: string;
|
|
57
65
|
title: string;
|
|
@@ -65,13 +73,15 @@ export interface PartsViewPackage {
|
|
|
65
73
|
flagFiles: LocalFile[];
|
|
66
74
|
/** Where flags were looked for and not found, said in words. */
|
|
67
75
|
flagNotes: string[];
|
|
76
|
+
/** Additional package/producer inputs protected from verdict writes, without changing verdict identity. */
|
|
77
|
+
protectedPaths?: string[];
|
|
68
78
|
verdictPath: string;
|
|
69
79
|
/** Absolute paths, served by index. */
|
|
70
80
|
imagePaths: string[];
|
|
71
81
|
pagePaths: string[];
|
|
72
82
|
}
|
|
73
83
|
|
|
74
|
-
export interface PartsViewOptions { meshReport?: string; check?: string; verdict?: string }
|
|
84
|
+
export interface PartsViewOptions { rig?: string; meshReport?: string; check?: string; verdict?: string;painting?:string }
|
|
75
85
|
|
|
76
86
|
const record = (v: unknown): Record<string, unknown> | null => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null;
|
|
77
87
|
const finite = (v: unknown, min: number): v is number => typeof v === 'number' && Number.isFinite(v) && v >= min;
|
|
@@ -196,6 +206,70 @@ async function producerFlags(rigDir: string | null, buildRoot: string | null, na
|
|
|
196
206
|
return { flags, files, notes };
|
|
197
207
|
}
|
|
198
208
|
|
|
209
|
+
/** Exact attachment identity and UV-derived geometry; never reconstruct through weights. */
|
|
210
|
+
export function readPartMeshes(raw: unknown, items: ViewItem[], reports: unknown): void {
|
|
211
|
+
const skins = record(record(raw)?.skins);
|
|
212
|
+
if (!skins) refuse('PARTS_MESH_MALFORMED', 'rig.json requires skins object');
|
|
213
|
+
const byName = new Map(items.map(i => [i.name, i]));
|
|
214
|
+
for (const slots of Object.values(skins!)) for (const attachments of Object.values(record(slots) ?? {})) {
|
|
215
|
+
for (const [name, value] of Object.entries(record(attachments) ?? {})) {
|
|
216
|
+
const a = record(value);
|
|
217
|
+
if (a?.type !== 'mesh') continue;
|
|
218
|
+
const item = byName.get(name);
|
|
219
|
+
if (!item) refuse('PARTS_MESH_UNKNOWN_PART', `${name}: found mesh; required a part in parts.json`);
|
|
220
|
+
if (item!.mesh) refuse('PARTS_MESH_AMBIGUOUS', `${name}: found multiple meshes; required one attachment`);
|
|
221
|
+
if (!finite(a.width, 1) || !Number.isInteger(a.width) || !finite(a.height, 1) || !Number.isInteger(a.height) || typeof a.image !== 'string') refuse('PARTS_MESH_SIZE', `${name}: found invalid raster declaration; required image and positive integer dimensions`);
|
|
222
|
+
const uv = a.uvs, triangles = a.triangles;
|
|
223
|
+
if (!Array.isArray(uv) || !uv.length || uv.length % 2) refuse('PARTS_MESH_UV', `${name}: found invalid uvs; required nonempty coordinate pairs in [0,1]`);
|
|
224
|
+
for (const v of uv as unknown[]) if (!finite(v, 0) || v > 1) refuse('PARTS_MESH_UV', `${name}: found ${String(v)}; required UV in [0,1]`);
|
|
225
|
+
const count = (uv as number[]).length / 2;
|
|
226
|
+
if (!Array.isArray(triangles) || !triangles.length || triangles.length % 3) refuse('PARTS_MESH_TRIANGLE', `${name}: found invalid triangles; required nonempty index triples`);
|
|
227
|
+
for (const v of triangles as unknown[]) if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v >= count) refuse('PARTS_MESH_TRIANGLE', `${name}: found ${String(v)}; required integer index in [0,${count - 1}]`);
|
|
228
|
+
const rows = Array.isArray(reports) ? reports.filter(r => record(r)?.part === name) : [];
|
|
229
|
+
if (rows.length > 1) refuse('PARTS_MESH_REPORT_AMBIGUOUS', `${name}: found ${rows.length} report rows; required at most one`);
|
|
230
|
+
const row = record(rows[0]) ?? {}, figures: Record<string, unknown> = {};
|
|
231
|
+
for (const field of ['mode', 'vertices', 'triangles', 'art_coverage', 'stray_cleared']) if (Object.hasOwn(row, field)) figures[field] = row[field];
|
|
232
|
+
item!.mesh = { vertices: (uv as number[]).map((v, i) => v * (i % 2 ? a.height as number : a.width as number)), triangles: triangles as number[], figures, width: a.width as number, height: a.height as number, image: a.image as string };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Prove the crop window in the mesh raster byte-for-byte; accept no inferred producer padding. */
|
|
238
|
+
async function locateMeshRasters(rig: unknown, root: string, items: ViewItem[], images: string[], files: LocalFile[]): Promise<void> {
|
|
239
|
+
const directory = record(rig)?.images;
|
|
240
|
+
for (const item of items) {
|
|
241
|
+
const mesh = item.mesh; if (!mesh) continue;
|
|
242
|
+
let path: string;
|
|
243
|
+
try {
|
|
244
|
+
// Validate both literal components before joining: normalization must not hide traversal.
|
|
245
|
+
path = await safeFile(root, `${packagePath(directory, 'rig.images')}/${packagePath(mesh.image, 'mesh.image')}`);
|
|
246
|
+
} catch { return refuse('PARTS_MESH_IMAGE_PATH', `${item.name}: found unavailable or unsafe rig image; required a literal local raster inside the rig directory`); }
|
|
247
|
+
const bytes = await readFile(path);
|
|
248
|
+
let image: ReturnType<typeof PNG.sync.read>, part: ReturnType<typeof PNG.sync.read>;
|
|
249
|
+
try {
|
|
250
|
+
const partBytes = await readFile(images[item.index]!);
|
|
251
|
+
image = PNG.sync.read(bytes); part = PNG.sync.read(partBytes);
|
|
252
|
+
// Retain all sixteen bits where present; 8-bit downsampling would hide a differing sample.
|
|
253
|
+
if (image.depth === 16) image = PNG.sync.read(bytes, { skipRescale: true });
|
|
254
|
+
if (part.depth === 16) part = PNG.sync.read(partBytes, { skipRescale: true });
|
|
255
|
+
}
|
|
256
|
+
catch { return refuse('PARTS_MESH_IMAGE_FORMAT', `${item.name}: found undecodable PNG; required PNG raster`); }
|
|
257
|
+
if (image.width !== mesh.width || image.height !== mesh.height) refuse('PARTS_MESH_IMAGE_SIZE', `${item.name}: found ${image.width}×${image.height}; required ${mesh.width}×${mesh.height}`);
|
|
258
|
+
const ox = (mesh.width - part.width) / 2, oy = (mesh.height - part.height) / 2;
|
|
259
|
+
if (part.width !== item.w || part.height !== item.h || ox < 0 || oy < 0 || !Number.isInteger(ox) || !Number.isInteger(oy)) refuse('PARTS_MESH_IMAGE_MISMATCH', `${item.name}: found incompatible raster window ${ox},${oy}; required a centred integer window of ${item.w}×${item.h}`);
|
|
260
|
+
const raster = image.data, original = part.data;
|
|
261
|
+
const rasterScale = image.depth === 16 ? 1 : 257, partScale = part.depth === 16 ? 1 : 257;
|
|
262
|
+
for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
|
|
263
|
+
const i = (y * image.width + x) * 4;
|
|
264
|
+
const inside = x >= ox && x < ox + part.width && y >= oy && y < oy + part.height;
|
|
265
|
+
const j = ((y - oy) * part.width + x - ox) * 4;
|
|
266
|
+
if (inside ? [0, 1, 2, 3].some(c => raster[i + c]! * rasterScale !== original[j + c]! * partScale) : raster[i + 3] !== 0) refuse('PARTS_MESH_IMAGE_MISMATCH', `${item.name}: first differing rig pixel (${x},${y}) found RGBA [${[...raster.slice(i, i + 4)]}]; required ${inside ? `RGBA [${[...original.slice(j, j + 4)]}]` : 'border alpha 0'}`);
|
|
267
|
+
}
|
|
268
|
+
mesh.vertices = mesh.vertices.map((v, i) => v - (i % 2 ? oy : ox));
|
|
269
|
+
files.push({ abs: path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
199
273
|
async function loadPartsMode(root: string, options: PartsViewOptions): Promise<PartsViewPackage> {
|
|
200
274
|
const partsJson = await insideRoot(root, join(root, 'parts.json'), 'PARTS_FILE_OUTSIDE', 'parts.json');
|
|
201
275
|
const doc = record(await readJson(partsJson, 'parts.json'));
|
|
@@ -219,14 +293,46 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
|
|
|
219
293
|
imagePaths.push(real);
|
|
220
294
|
items.push({ name: part.name, index, x: part.x, y: part.y, w: part.w, h: part.h, image: true });
|
|
221
295
|
}
|
|
296
|
+
let painting:PartsViewPackage['painting'];if(options.painting){
|
|
297
|
+
const candidate=resolve(options.painting),rel=relative(resolve(root),candidate);if(!rel||rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))refuse('PARTS_PAINTING_OUTSIDE','painting must be inside the parts package');
|
|
298
|
+
let abs:string,bytes:Buffer;try{abs=await insideRoot(root,candidate,'PARTS_PAINTING_OUTSIDE','painting');packagePath(relative(root,abs).split(sep).join('/'),'painting');bytes=await readFile(abs);}catch(error){if(error instanceof Error&&error.message.startsWith('PARTS_PAINTING_OUTSIDE:'))throw error;refuse('PARTS_PAINTING_UNAVAILABLE','painting must be a readable portable package PNG');}
|
|
299
|
+
let png:PNG;try{png=PNG.sync.read(bytes!);}catch{refuse('PARTS_PAINTING_PNG','painting must be a valid PNG');}
|
|
300
|
+
assertOriginalPaintingSize(png!.width,png!.height,rigSize,doc.scale_rig_per_source);
|
|
301
|
+
const file={abs:abs!,bytes:bytes!.length,sha256:createHash('sha256').update(bytes!).digest('hex')};painting={...file,width:png!.width,height:png!.height};files.push(file);
|
|
302
|
+
}
|
|
222
303
|
const { flags, files: flagFiles, notes } = await producerFlags(root, null, seen, options);
|
|
223
|
-
|
|
304
|
+
const protectedPaths = [join(root, 'rig.json'), join(root, 'config.json'), join(root, 'review.json'), join(root, 'report.json')];
|
|
305
|
+
if (basename(root) === 'rig') protectedPaths.push(...['parts.json', 'config.json', 'review.json', 'report.json'].map(name => join(dirname(root), name)));
|
|
306
|
+
if (options.rig !== undefined) protectedPaths.push(resolve(options.rig));
|
|
307
|
+
const verdictPath = options.verdict ? resolve(options.verdict) : join(root, PARTS_VERDICT_FILE);
|
|
308
|
+
await assertVerdictDestination({ files, flagFiles, protectedPaths, verdictPath });
|
|
309
|
+
const rigPath = options.rig !== undefined ? resolve(options.rig) : existsSync(join(root, 'rig.json')) ? await insideRoot(root, join(root, 'rig.json'), 'PARTS_MESH_OUTSIDE', 'rig.json') : null;
|
|
310
|
+
if (rigPath) {
|
|
311
|
+
const report = notes.includes('mesh_report.json') ? undefined : flagFiles[0];
|
|
312
|
+
const rigBytes = await readFile(rigPath);
|
|
313
|
+
let rig: unknown;
|
|
314
|
+
try { rig = JSON.parse(rigBytes.toString('utf8')); }
|
|
315
|
+
catch (e) { return refuse('PARTS_MESH_MALFORMED', `rig.json: ${e instanceof Error ? e.message : String(e)}`); }
|
|
316
|
+
readPartMeshes(rig, items, report ? await readJson(report.abs, 'mesh_report.json') : null);
|
|
317
|
+
await locateMeshRasters(rig, dirname(rigPath), items, imagePaths, files);
|
|
318
|
+
// Bind exactly the bytes parsed above, even if the path is replaced during raster checks.
|
|
319
|
+
files.push({ abs: rigPath, bytes: rigBytes.length, sha256: createHash('sha256').update(rigBytes).digest('hex') });
|
|
320
|
+
if (report) files.push(report);
|
|
321
|
+
}
|
|
322
|
+
return { ...(painting?{painting}:{}),mode: 'parts', root, title: basename(root) === 'rig' ? basename(dirname(root)) : basename(root), rigSize, items, pages: [], flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath, imagePaths, pagePaths: [] };
|
|
224
323
|
}
|
|
225
324
|
|
|
226
325
|
async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<PartsViewPackage> {
|
|
326
|
+
if(options.painting)refuse('PARTS_PAINTING_UNAVAILABLE','atlas regions have no rig placement; use a pre-rig parts package');
|
|
227
327
|
const p = await loadReview(input);
|
|
328
|
+
if (!p.manifest.model) return refuse('PARTS_VIEW_NO_ATLAS', `${input} holds neither parts.json nor a compiled model with pages`);
|
|
329
|
+
return loadPartsAtlas(p, options);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Atlas inspector bound to an already loaded package; never rediscover a different source. */
|
|
333
|
+
export async function loadPartsAtlas(p: ReviewPackage, options: PartsViewOptions = {}): Promise<PartsViewPackage> {
|
|
228
334
|
const modelPath = p.manifest.model;
|
|
229
|
-
if (!modelPath) return refuse('PARTS_VIEW_NO_ATLAS',
|
|
335
|
+
if (!modelPath) return refuse('PARTS_VIEW_NO_ATLAS', `The inspected package holds no compiled model with pages`);
|
|
230
336
|
const modelAbs = await safeFile(p.root, modelPath);
|
|
231
337
|
const model = record(JSON.parse(await readFile(modelAbs, 'utf8')));
|
|
232
338
|
const pagesRaw = model?.pages;
|
|
@@ -251,7 +357,11 @@ async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<
|
|
|
251
357
|
// A build root opens as its check package (#149); its own rig/ and check/ hold the flags.
|
|
252
358
|
const buildRoot = p.buildRoot ?? null;
|
|
253
359
|
const { flags, files: flagFiles, notes } = await producerFlags(null, buildRoot, names, options);
|
|
254
|
-
|
|
360
|
+
const protectedPaths = [...p.files].map(path => resolve(p.root, path));
|
|
361
|
+
protectedPaths.push(...['rig.json', 'config.json', 'report.json', 'review.json'].map(name => join(p.root, name)));
|
|
362
|
+
if (p.handoff) protectedPaths.push(...p.handoff.record.files.map(file => resolve(p.root, file.path)));
|
|
363
|
+
if (buildRoot) protectedPaths.push(...['parts.json', 'config.json', 'rig/rig.json', 'rig/parts.json'].map(name => join(buildRoot, name)));
|
|
364
|
+
return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
|
|
255
365
|
}
|
|
256
366
|
|
|
257
367
|
/**
|
|
@@ -261,10 +371,30 @@ async function loadAtlasMode(input: string, options: PartsViewOptions): Promise<
|
|
|
261
371
|
export async function loadPartsView(input: string, options: PartsViewOptions = {}): Promise<PartsViewPackage> {
|
|
262
372
|
const abs = await realpath(resolve(input)).catch(() => refuse('PARTS_VIEW_INPUT_MISSING', `${input} does not exist`));
|
|
263
373
|
if ((await stat(abs)).isDirectory()) {
|
|
264
|
-
if (existsSync(join(abs, 'parts.json'))) return loadPartsMode(abs, options);
|
|
265
|
-
if (existsSync(join(abs, 'rig', 'parts.json')) && !existsSync(join(abs, 'review.json'))) return loadPartsMode(join(abs, 'rig'), options);
|
|
374
|
+
if (existsSync(join(abs, 'parts.json'))) return checkedVerdict(await loadPartsMode(abs, options));
|
|
375
|
+
if (existsSync(join(abs, 'rig', 'parts.json')) && !existsSync(join(abs, 'review.json'))) return checkedVerdict(await loadPartsMode(join(abs, 'rig'), options));
|
|
376
|
+
}
|
|
377
|
+
return checkedVerdict(await loadAtlasMode(input, options));
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Compare names, real paths (including parent links), and filesystem identities before creating output. */
|
|
381
|
+
async function assertVerdictDestination(pkg: Pick<PartsViewPackage, 'files' | 'flagFiles' | 'protectedPaths' | 'verdictPath'>): Promise<void> {
|
|
382
|
+
const target = resolve(pkg.verdictPath);
|
|
383
|
+
const targetReal = await realpath(target).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
384
|
+
const targetStat = await stat(target, { bigint: true }).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
385
|
+
const parent = await realpath(dirname(target)).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
386
|
+
for (const path of [...pkg.files, ...pkg.flagFiles].map(file => file.abs).concat(pkg.protectedPaths ?? [])) {
|
|
387
|
+
const input = resolve(path);
|
|
388
|
+
const real = await realpath(input).catch((e: NodeJS.ErrnoException) => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
389
|
+
const sameName = target === input || (real !== null && (targetReal === real || (parent !== null && join(parent, basename(target)) === real)));
|
|
390
|
+
const identity = targetStat && real ? await stat(real, { bigint: true }) : null;
|
|
391
|
+
if (sameName || (targetStat && identity && targetStat.dev === identity.dev && targetStat.ino === identity.ino)) refuse('PARTS_VERDICT_INPUT_COLLISION', `${basename(target)} is a protected input; choose a separate verdict file`);
|
|
266
392
|
}
|
|
267
|
-
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function checkedVerdict(pkg: PartsViewPackage): Promise<PartsViewPackage> {
|
|
396
|
+
await assertVerdictDestination(pkg);
|
|
397
|
+
return pkg;
|
|
268
398
|
}
|
|
269
399
|
|
|
270
400
|
/** The hashed files as the verdict records them: relative to the verdict file's directory. */
|
|
@@ -280,7 +410,8 @@ export interface PartsVerdict {
|
|
|
280
410
|
tool: { name: '@rig-c/review'; version: string };
|
|
281
411
|
source: ReturnType<typeof verdictSource>;
|
|
282
412
|
status: VerdictStatus;
|
|
283
|
-
parts: Record<string, { outcome: PartOutcome; note: string; flags: string[] }>;
|
|
413
|
+
parts: Record<string, { outcome: PartOutcome; note: string; flags: string[]; mesh?: { outcome: PartOutcome; note: string } }>;
|
|
414
|
+
comments: PartsComment[];
|
|
284
415
|
updatedAt: string;
|
|
285
416
|
}
|
|
286
417
|
|
|
@@ -291,7 +422,7 @@ export interface VerdictSubmission { status: VerdictStatus; parts: Record<string
|
|
|
291
422
|
export const itemNames = (pkg: Pick<PartsViewPackage, 'items'>): string[] => [...new Set(pkg.items.map(i => i.name))];
|
|
292
423
|
|
|
293
424
|
/** Builds the verdict document, or refuses by name. Pure but for the clock. */
|
|
294
|
-
export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath'>, input: unknown, version: string, now = new Date()): PartsVerdict {
|
|
425
|
+
export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'flags' | 'files' | 'flagFiles' | 'verdictPath' | 'imagePaths' | 'painting'>, input: unknown, version: string, now = new Date()): PartsVerdict {
|
|
295
426
|
const body = record(input);
|
|
296
427
|
if (!body) return refuse('PARTS_VERDICT_INVALID', 'expected { status, parts }');
|
|
297
428
|
const status = body.status;
|
|
@@ -309,12 +440,25 @@ export function buildVerdict(pkg: Pick<PartsViewPackage, 'mode' | 'items' | 'fla
|
|
|
309
440
|
const note = entry.note === undefined ? '' : entry.note;
|
|
310
441
|
if (typeof note !== 'string' || note.length > PARTS_NOTE_LIMIT) return refuse('PARTS_VERDICT_INVALID', `${name}.note is a string of at most ${PARTS_NOTE_LIMIT} characters`);
|
|
311
442
|
if (outcome === 'flagged' && !note.trim()) return refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name} is flagged and has no note saying what is wrong`);
|
|
312
|
-
|
|
443
|
+
const meshInput = record(entry.mesh);
|
|
444
|
+
const hasMesh = pkg.items.some(i => i.name === name && i.mesh);
|
|
445
|
+
if (!hasMesh && entry.mesh !== undefined) refuse('PARTS_MESH_OUTCOME_UNAVAILABLE', `${name}: no mesh; required no mesh outcome`);
|
|
446
|
+
let mesh: { outcome: PartOutcome; note: string } | undefined;
|
|
447
|
+
if (hasMesh) {
|
|
448
|
+
if (!meshInput || !['pending', 'clean', 'flagged'].includes(String(meshInput.outcome))) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh outcome pending, clean or flagged`);
|
|
449
|
+
const meshNote = meshInput!.note ?? '';
|
|
450
|
+
if (typeof meshNote !== 'string' || meshNote.length > PARTS_NOTE_LIMIT) refuse('PARTS_MESH_OUTCOME', `${name}: required mesh note up to ${PARTS_NOTE_LIMIT} characters`);
|
|
451
|
+
if (meshInput!.outcome === 'flagged' && !(meshNote as string).trim()) refuse('PARTS_VERDICT_NOTE_REQUIRED', `${name}.mesh is flagged and has no note`);
|
|
452
|
+
mesh = { outcome: meshInput!.outcome as PartOutcome, note: meshNote as string };
|
|
453
|
+
}
|
|
454
|
+
parts[name] = { ...(mesh ? { mesh } : {}), outcome, note, flags: [...new Set(pkg.flags.filter(f => f.item === name).map(f => f.id))] };
|
|
313
455
|
}
|
|
314
|
-
const outcomes = Object.values(parts).
|
|
456
|
+
const outcomes = Object.values(parts).flatMap(p => p.mesh ? [p.outcome, p.mesh.outcome] : [p.outcome]);
|
|
315
457
|
if (status === 'approved' && outcomes.some(o => o !== 'clean')) refuse('PARTS_VERDICT_NOT_CLEAN', `approved needs every part clean; ${outcomes.filter(o => o !== 'clean').length} are not`);
|
|
316
458
|
if (status === 'changes-requested' && !outcomes.includes('flagged')) refuse('PARTS_VERDICT_NOTHING_FLAGGED', 'changes-requested needs at least one flagged part');
|
|
317
|
-
|
|
459
|
+
const comments=body.comments??[];if(!Array.isArray(comments)||comments.length>1000)refuse('PARTS_COMMENT_LIMIT','comments must be an array of at most 1000 entries');
|
|
460
|
+
const ids=new Set<string>();for(const raw of comments as unknown[]){const c=parsePartsComment(raw);if(c.view.comparison?.mode==='overlay'&&!pkg.painting)refuse('PARTS_COMPARISON_UNAVAILABLE','original painting required');const item=pkg.items.find(i=>i.name===c.part);if(!item||pkg.mode!=='parts')refuse('PARTS_COMMENT_UNAVAILABLE','original part required');if(ids.has(c.id))refuse('PARTS_COMMENT_DUPLICATE','duplicate comment id');ids.add(c.id);const file=pkg.files.find(f=>f.abs===pkg.imagePaths[item!.index]);assertPartsCommentBinding(c,item!,file?.sha256??'',verdictSource(pkg).sha256);}
|
|
461
|
+
return { schema: PARTS_VERDICT_SCHEMA, mode: pkg.mode, tool: { name: '@rig-c/review', version }, source: verdictSource(pkg), status, parts, comments:comments as PartsComment[], updatedAt: now.toISOString() };
|
|
318
462
|
}
|
|
319
463
|
|
|
320
464
|
/** Every file the package was loaded from still has the bytes it was loaded with. */
|
|
@@ -331,12 +475,19 @@ async function packageVersion(): Promise<string> {
|
|
|
331
475
|
|
|
332
476
|
/** Writes the verdict atomically beside its sources. */
|
|
333
477
|
export async function saveVerdict(pkg: PartsViewPackage, input: unknown): Promise<PartsVerdict> {
|
|
478
|
+
await assertVerdictDestination(pkg);
|
|
334
479
|
await assertPartsUnchanged(pkg);
|
|
480
|
+
await readVerdict(pkg); // Existing read-side evidence errors must never become an implicit reset.
|
|
335
481
|
const verdict = buildVerdict(pkg, input, await packageVersion());
|
|
482
|
+
for(const comment of verdict.comments)await preparePartsComment(pkg,comment,true);
|
|
483
|
+
await assertPartsUnchanged(pkg);
|
|
336
484
|
await mkdir(dirname(pkg.verdictPath), { recursive: true });
|
|
337
485
|
const tmp = `${pkg.verdictPath}.${crypto.randomUUID()}.tmp`;
|
|
338
|
-
|
|
339
|
-
|
|
486
|
+
try {
|
|
487
|
+
await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n', { flag: 'wx' });
|
|
488
|
+
await assertVerdictDestination(pkg);
|
|
489
|
+
await rename(tmp, pkg.verdictPath);
|
|
490
|
+
} finally { await rm(tmp, { force: true }); }
|
|
340
491
|
return verdict;
|
|
341
492
|
}
|
|
342
493
|
|
|
@@ -350,18 +501,23 @@ export type VerdictStale = 'files' | 'flags' | null;
|
|
|
350
501
|
*/
|
|
351
502
|
export async function readVerdict(pkg: PartsViewPackage): Promise<{ verdict: PartsVerdict | null; stale: VerdictStale }> {
|
|
352
503
|
let raw: unknown;
|
|
353
|
-
try
|
|
504
|
+
let text:string;try{text=await readFile(pkg.verdictPath,'utf8');}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return {verdict:null,stale:null};throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read');}
|
|
505
|
+
try{raw=JSON.parse(text);}catch{throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');}
|
|
354
506
|
const v = record(raw), source = record(v?.source), now = verdictSource(pkg);
|
|
355
|
-
if
|
|
507
|
+
if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1'].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
|
|
508
|
+
if(v.mode!==pkg.mode||source.sha256!==now.sha256)return {verdict:null,stale:'files'};
|
|
356
509
|
if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) return { verdict: null, stale: 'flags' };
|
|
357
|
-
|
|
510
|
+
const date=new Date(String(v.updatedAt));if(!Number.isFinite(date.getTime()))throw new Error('PARTS_VERDICT_INVALID: saved verdict date is invalid');
|
|
511
|
+
const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);for(const c of normalized.comments)await validateStoredPartsComment(pkg,c);return {verdict:normalized,stale:null};
|
|
358
512
|
}
|
|
359
513
|
|
|
360
514
|
/** What the page reads: no absolute path leaves the server but the verdict file's name. */
|
|
361
515
|
export function partsViewJson(pkg: PartsViewPackage, saved: { verdict: PartsVerdict | null; stale: VerdictStale }) {
|
|
362
516
|
return {
|
|
363
517
|
schema: 'rig-review-parts-view/1', mode: pkg.mode, title: pkg.title, rigSize: pkg.rigSize,
|
|
364
|
-
|
|
518
|
+
painting:pkg.painting?{sha256:pkg.painting.sha256,width:pkg.painting.width,height:pkg.painting.height}:null,
|
|
519
|
+
sourceHash:verdictSource(pkg).sha256,
|
|
520
|
+
items:pkg.items.map(item=>({...item,...(pkg.mode==='parts'?{imageHash:pkg.files.find(f=>f.abs===pkg.imagePaths[item.index])?.sha256}:{})})), pages: pkg.pages, flags: pkg.flags,
|
|
365
521
|
flagSources: pkg.flagFiles.map(f => basename(f.abs)), flagMissing: pkg.flagNotes,
|
|
366
522
|
verdictFile: basename(pkg.verdictPath), verdict: saved.verdict, verdictStale: saved.stale,
|
|
367
523
|
};
|
|
@@ -373,3 +529,10 @@ export function servedImage(pkg: PartsViewPackage, kind: 'image' | 'page', index
|
|
|
373
529
|
return Number.isInteger(index) && index >= 0 && index < list.length ? list[index]! : null;
|
|
374
530
|
}
|
|
375
531
|
|
|
532
|
+
|
|
533
|
+
/** Both export forms preserve original text, native and rig coordinates and resolved evidence. */
|
|
534
|
+
export function exportPartsVerdict(verdict:PartsVerdict,format:'json'|'issue'):string {
|
|
535
|
+
const comments=verdict.comments.map(c=>{const {png,...crop}=c.crop;return {...c,crop:{...crop,path:resolvedCropPath(crop.path)},nativeCrop:c.nativeCrop?{...c.nativeCrop,path:resolvedCropPath(c.nativeCrop.path)}:null};});
|
|
536
|
+
if(format==='json')return JSON.stringify({...verdict,comments},null,2)+'\n';
|
|
537
|
+
return [`# Parts review`, `Source: ${verdict.source.sha256}`,`Status: ${verdict.status}`,...Object.entries(verdict.parts).flatMap(([name,p])=>[`\n## ${name}`,`${p.outcome}: ${p.note}`,...comments.filter(c=>c.part===name).flatMap(c=>[`\n### ${c.summary}`,`Part: ${c.part} · image SHA-256: ${c.imageHash}`,`Image region: ${JSON.stringify(c.imageRegion)}`,`Rig region: ${JSON.stringify(c.rigRegion)}`,`Viewport crop: ${c.crop.path} · SHA-256 ${c.crop.sha256}`,`Native crop: ${c.nativeCrop!.path} · SHA-256 ${c.nativeCrop!.sha256}`,`View: ${JSON.stringify(c.view)}`])])].join('\n')+'\n';
|
|
538
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {stagePartsRoutes} from './stage-parts.ts';
|
|
1
2
|
import {createControlServer,type ControlIdentity} from './control-server.ts';
|
|
2
3
|
import { readFile } from 'node:fs/promises';
|
|
3
4
|
import { appRoot, buildWeb } from './build.ts';
|
|
@@ -17,7 +18,7 @@ import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError
|
|
|
17
18
|
import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
|
|
18
19
|
import { homedir } from 'node:os';
|
|
19
20
|
import { join } from 'node:path';
|
|
20
|
-
const headers={ 'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
|
|
21
|
+
const headers={ 'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; frame-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
|
|
21
22
|
/** Request shapes the page or an edit card got wrong: 400. Everything else a refusal names is an outcome (200). */
|
|
22
23
|
const MALFORMED=new Set(['REBUILD_REQUEST_INVALID','DENSITY_STRIP_REQUEST_INVALID','DENSITY_STRIP_FIELD','MESH_PATCH_SCOPE','EDIT_PATCH_INVALID','EDIT_PATCH_OP_UNKNOWN','EDIT_PATCH_POINTER_INVALID','EDIT_PATCH_CMD_UNKNOWN','EDIT_PATCH_ARG_UNKNOWN','BONES_OP_OUT_OF_SCOPE','RETARGET_REQUEST_INVALID']);
|
|
23
24
|
function json(data:unknown,status=200){return Response.json(data,{status,headers});}
|
|
@@ -31,6 +32,7 @@ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceed
|
|
|
31
32
|
/** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it.
|
|
32
33
|
* `cwd` is where the producer is looked for after the package's own directories (review's working directory by default). */
|
|
33
34
|
export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void;viewOnly?:boolean}={}){
|
|
35
|
+
const stageParts=stagePartsRoutes({single:p});
|
|
34
36
|
const bundle=await buildWeb();
|
|
35
37
|
const unchanged=()=>assertReviewUnchanged(p);
|
|
36
38
|
const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
|
|
@@ -66,6 +68,8 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
|
|
|
66
68
|
}
|
|
67
69
|
live.onRequestStart(url.pathname);
|
|
68
70
|
try {
|
|
71
|
+
const stageResponse=await stageParts(req);if(stageResponse)return stageResponse;
|
|
72
|
+
|
|
69
73
|
const controlled=await control?.(req,origin);if(controlled)return controlled;
|
|
70
74
|
options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
|
|
71
75
|
if(req.method==='PUT'&&url.pathname==='/api/session'){
|