rig-review 1.16.4 → 1.16.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "1.16.4",
3
+ "version": "1.16.6",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/parts-view.ts CHANGED
@@ -99,7 +99,7 @@ const refuse = (code: string, message: string): never => { throw new Error(`${co
99
99
  export async function insideRoot(root: string, path: string, code: string, what: string): Promise<string> {
100
100
  const realRoot = await realpath(root), real = await realpath(path);
101
101
  const rel = relative(realRoot, real);
102
- if (!rel || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) refuse(code, `${what} resolves outside ${basename(realRoot)}/ (symlinks may not escape the package)`);
102
+ if (!rel || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) refuse(code, `${what} resolves outside ${basename(realRoot)}/`);
103
103
  return real;
104
104
  }
105
105
 
@@ -128,6 +128,21 @@ function relativeTo(dir: string, abs: string): string {
128
128
  return sep === '/' ? rel : rel.split(sep).join('/');
129
129
  }
130
130
 
131
+ /** Match canonical input paths, resolving only the destination's parent. Missing
132
+ * 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
+ }
144
+ }
145
+
131
146
  /** Faint islands (rig-parts #326) from `mesh_report.json` rows, on the parts the view holds. */
132
147
  export function meshReportFlags(rows: unknown, names: ReadonlySet<string>): ProducerFlag[] {
133
148
  if (!Array.isArray(rows)) refuse('PARTS_FLAGS_MALFORMED', 'mesh_report.json is not an array of rows');
@@ -234,7 +249,7 @@ async function producerFlags(rigDir: string | null, buildRoot: string | null, na
234
249
  const flags: ProducerFlag[] = [], readings: ProducerFlag[] = [], files: LocalFile[] = [], notes: string[] = [];
235
250
  // A discovered file must resolve inside the directory it was discovered in; a path given on the command line is the user's own choice.
236
251
  const pick = async (explicit: string | undefined, candidates: ([string, string] | null)[], what: string): Promise<string | null> => {
237
- if (explicit !== undefined) return resolve(explicit);
252
+ if (explicit !== undefined) return realpath(resolve(explicit));
238
253
  const found = candidates.find((c): c is [string, string] => !!c && existsSync(c[1]));
239
254
  return found ? insideRoot(found[0], found[1], 'PARTS_FLAGS_OUTSIDE', what) : null;
240
255
  };
@@ -352,8 +367,9 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
352
367
  paintingInRig={abs,declaredPath,bytes:bytes.length,sha256,width:png!.width,height:png!.height};files.push(paintingInRig);
353
368
  }
354
369
  let painting:PartsViewPackage['painting'];if(options.painting){
355
- 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');
356
- 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');}
370
+ // Both paths are physical: a user-designated alias to an inside file is valid,
371
+ // while a link reaching outside is refused before any painting bytes are read.
372
+ let abs:string,bytes:Buffer;try{abs=await insideRoot(root,resolve(options.painting),'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');}
357
373
  let png:PNG;try{png=PNG.sync.read(bytes!);}catch{refuse('PARTS_PAINTING_PNG','painting must be a valid PNG');}
358
374
  assertOriginalPaintingSize(png!.width,png!.height,rigSize,doc.scale_rig_per_source);
359
375
  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);
@@ -362,9 +378,9 @@ async function loadPartsMode(root: string, options: PartsViewOptions): Promise<P
362
378
  const protectedPaths = [join(root, 'rig.json'), join(root, 'config.json'), join(root, 'review.json'), join(root, 'report.json')];
363
379
  if (basename(root) === 'rig') protectedPaths.push(...['parts.json', 'config.json', 'review.json', 'report.json'].map(name => join(dirname(root), name)));
364
380
  if (options.rig !== undefined) protectedPaths.push(resolve(options.rig));
365
- const verdictPath = options.verdict ? resolve(options.verdict) : join(root, PARTS_VERDICT_FILE);
381
+ const verdictPath = options.verdict ? await verdictDestination(options.verdict) : join(root, PARTS_VERDICT_FILE);
366
382
  await assertVerdictDestination({ files, flagFiles, protectedPaths, verdictPath });
367
- 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;
383
+ 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;
368
384
  if (rigPath) {
369
385
  const report = notes.includes('mesh_report.json') ? undefined : flagFiles[0];
370
386
  const rigBytes = await readFile(rigPath);
@@ -419,7 +435,7 @@ export async function loadPartsAtlas(p: ReviewPackage, options: PartsViewOptions
419
435
  protectedPaths.push(...['rig.json', 'config.json', 'report.json', 'review.json'].map(name => join(p.root, name)));
420
436
  if (p.handoff) protectedPaths.push(...p.handoff.record.files.map(file => resolve(p.root, file.path)));
421
437
  if (buildRoot) protectedPaths.push(...['parts.json', 'config.json', 'rig/rig.json', 'rig/parts.json'].map(name => join(buildRoot, name)));
422
- return { mode: 'atlas', root: p.root, title: p.manifest.title, rigSize: null, items, pages, flags, readings, files, flagFiles, flagNotes: notes, protectedPaths, verdictPath: options.verdict ? resolve(options.verdict) : join(dirname(modelAbs), PARTS_VERDICT_FILE), imagePaths: [], pagePaths };
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 };
423
439
  }
424
440
 
425
441
  /**
@@ -1,11 +1,27 @@
1
1
  /** Native image policy for the canonical pair. Camera gestures and writes belong to viewport-controller. */
2
- import {createViewportController,createViewportState,type ViewportProvider} from './viewport-controller.ts';
2
+ import {createViewportController,createViewportState,type CameraTarget,type ViewportProvider} from './viewport-controller.ts';
3
3
  import {t} from './i18n.ts';
4
- export function createPartsViewport(host:{el:ViewportProvider['el'];canvas:HTMLCanvasElement;message:ViewportProvider['message'];reference:()=>HTMLCanvasElement|null}){
4
+
5
+ export function createPartsViewport(host:{el:ViewportProvider['el'];canvas:HTMLCanvasElement;message:ViewportProvider['message'];reference:()=>HTMLCanvasElement|null;frameSize:(target:CameraTarget)=>{w:number;h:number}|null}){
5
6
  const state=createViewportState();state.cameraSync=false;
7
+ let dimensionProbe:HTMLCanvasElement|undefined;
8
+ const ordinaryExtent=(value:number)=>Number.isInteger(value)&&value>=0&&value<=0x7fffffff;
9
+ const canvasSize=(size:{w:number;h:number})=>{
10
+ if(ordinaryExtent(size.w)&&ordinaryExtent(size.h))return {width:size.w,height:size.h};
11
+ // Match the browser's canvas IDL conversion even for legacy fractional or clipped dimensions.
12
+ const probe=dimensionProbe??=document.createElement('canvas');
13
+ probe.width=size.w;probe.height=size.h;
14
+ return {width:probe.width,height:probe.height};
15
+ };
6
16
  const provider:ViewportProvider={el:host.el,message:host.message,nativeScale:true,
7
17
  panes:(['rig','reference'] as const).map(target=>({target,viewport:host.el(target+'-viewport'),pane:host.el(target+'-pane')})),
8
- geometry:target=>{const canvas=target==='rig'?host.canvas:host.reference();return canvas?{space:'image',box:{x:0,y:0,width:canvas.width,height:canvas.height},marginX:24,marginY:24}:null;},
18
+ geometry:target=>{
19
+ const declared=host.frameSize(target);
20
+ const size=declared?canvasSize(declared):target==='rig'?host.canvas:host.reference();
21
+ if(!size)return null;
22
+ const {width,height}=size;
23
+ return {space:'image',box:{x:0,y:0,width,height},marginX:24,marginY:24};
24
+ },
9
25
  layoutKey:()=>[host.canvas.width,host.canvas.height,host.reference()?.width??0,host.reference()?.height??0,host.el('rig-viewport').clientWidth,host.el('rig-viewport').clientHeight].join(':'),selection:()=>({selected:false,bounds:null}),
10
26
  render:controller=>{for(const target of ['rig','reference'] as const){const frame=controller.paneFrame(target);if(!frame)continue;const c=controller.paneCamera(target),center=c.center??frame.center,root=host.el(target==='rig'?'rig-root':'reference-content');root.style.left=`${frame.width/2-center.x*c.zoom}px`;root.style.top=`${frame.height/2-center.y*c.zoom}px`;root.style.transform=`scale(${c.zoom})`;if(target==='rig'){state.rigScale=c.zoom;state.displayedCenter={...center};}}controller.renderCameraControls();},
11
27
  renderControls:controller=>{const zoom=controller.paneCamera(controller.availableCamera()??'rig').zoom;host.el('zoom-value').textContent=zoom===1?t('1:1'):`${(zoom*100).toFixed(1)}%`;host.el('native-one').setAttribute('aria-pressed',String(zoom===1));(host.el('camera-sync') as HTMLInputElement).checked=state.cameraSync;host.el('fit').textContent=t('Fit');}
package/web/parts.ts CHANGED
@@ -107,13 +107,34 @@ function sourceAlpha(item:Item,img:HTMLImageElement):Uint8ClampedArray {
107
107
  const rgba=ctx.getImageData(0,0,item.w,item.h).data,alpha=new Uint8ClampedArray(item.w*item.h);for(let i=0;i<alpha.length;i++)alpha[i]=rgba[i*4+3]!;assemblyAlpha.set(item.name,alpha);return alpha;
108
108
  }
109
109
 
110
+ function partFrame(data:ViewData,item:Item) {
111
+ if(state.view==='assembled'&&data.rigSize) {
112
+ return {x:0,y:0,w:data.rigSize[0],h:data.rigSize[1]};
113
+ }
114
+ return item;
115
+ }
116
+
117
+ function rasterFrame(data:ViewData,item:Item) {
118
+ if(data.mode==='parts')return partFrame(data,item);
119
+ if(state.view==='page') {
120
+ const page=data.pages[state.page]!;
121
+ return {x:0,y:0,w:page.width,h:page.height};
122
+ }
123
+ const page=data.pages.find(p=>p.name===item.page)!;
124
+ const x=Math.max(0,item.x-REGION_MARGIN),y=Math.max(0,item.y-REGION_MARGIN);
125
+ const right=Math.min(page.width,item.x+item.w+REGION_MARGIN);
126
+ const bottom=Math.min(page.height,item.y+item.h+REGION_MARGIN);
127
+ return {x,y,w:right-x,h:bottom-y};
128
+ }
129
+
110
130
  async function paintRaster(token:number): Promise<void> {
111
131
  const data = state.data;
112
132
  if (!data || !data.items.length) return;
113
133
  const canvas = $<HTMLCanvasElement>('pv-canvas'), overlay = $('pv-overlay'), caption = $('pv-caption');
114
134
  const item = data.items[state.selected]!;
135
+ const {x,y,w,h}=rasterFrame(data,item);
115
136
  if(state.view==='assembled'&&data.mode==='parts'&&data.rigSize){
116
- const [w,h]=data.rigSize,shown=data.items.filter(i=>!state.hidden.has(i.name));
137
+ const shown=data.items.filter(i=>!state.hidden.has(i.name));
117
138
  const layers=await Promise.all(shown.map(async box=>({box,image:await itemImage(box)})));
118
139
  const original=state.comparison.mode==='overlay'&&data.painting?await load('/api/parts/painting'):null;
119
140
  if(token!==paintToken)return;
@@ -131,7 +152,7 @@ async function paintRaster(token:number): Promise<void> {
131
152
  if (data.mode === 'atlas' && state.view === 'page') {
132
153
  const page = data.pages[state.page]!, img = await pageImage(page.name);
133
154
  if (token !== paintToken) return;
134
- const ctx = setCanvas(canvas, page.width, page.height);
155
+ const ctx = setCanvas(canvas, w, h);
135
156
  if (state.alpha) paintAlphaOnly(ctx, img, 0, 0, page.width, page.height);
136
157
  else { paintBackground(ctx, page.width, page.height, state.bg); ctx.drawImage(img, 0, 0); }
137
158
  overlay.replaceChildren(...data.items.filter(r => r.page === page.name).map(r => {
@@ -153,12 +174,10 @@ async function paintRaster(token:number): Promise<void> {
153
174
  if (data.mode === 'atlas') {
154
175
  const page = data.pages.find(p => p.name === item.page)!, img = await pageImage(item.page!);
155
176
  if (token !== paintToken) return;
156
- const x0 = Math.max(0, item.x - REGION_MARGIN), y0 = Math.max(0, item.y - REGION_MARGIN);
157
- const x1 = Math.min(page.width, item.x + item.w + REGION_MARGIN), y1 = Math.min(page.height, item.y + item.h + REGION_MARGIN);
158
- const ctx = setCanvas(canvas, x1 - x0, y1 - y0);
159
- if (state.alpha) paintAlphaOnly(ctx, img, x0, y0, x1 - x0, y1 - y0);
160
- else { paintBackground(ctx, x1 - x0, y1 - y0, state.bg); ctx.drawImage(img, x0, y0, x1 - x0, y1 - y0, 0, 0, x1 - x0, y1 - y0); }
161
- const edge = overlayBox(item.x - x0, item.y - y0, item.w, item.h);
177
+ const ctx = setCanvas(canvas, w, h);
178
+ if (state.alpha) paintAlphaOnly(ctx, img, x, y, w, h);
179
+ else { paintBackground(ctx, w, h, state.bg); ctx.drawImage(img, x, y, w, h, 0, 0, w, h); }
180
+ const edge = overlayBox(item.x - x, item.y - y, item.w, item.h);
162
181
  edge.className = 'pv-region-edge';
163
182
  overlay.replaceChildren(edge);
164
183
  caption.textContent = t('Region {name} on {page} at {x},{y}, {width}×{height} px, with {margin} px of the page around it (dashed: the region box).', { name: item.name, page: item.page!, x: item.x, y: item.y, width: item.w, height: item.h, margin: REGION_MARGIN }) + (item.degrees ? ' ' + t('Packed at {degrees}°.', { degrees: item.degrees }) : '');
@@ -168,7 +187,7 @@ async function paintRaster(token:number): Promise<void> {
168
187
  const response=await fetch(access.route(`${partsApi}/difference/${item.index}?threshold=${state.comparison.threshold}&footprints=${state.footprints}`),{headers:stageHeaders()});
169
188
  if(!response.ok){const out=await response.json() as {error:string};throw new Error(out.error);}
170
189
  const image=await createImageBitmap(await response.blob());
171
- try{if(token!==paintToken)return;const ctx=setCanvas(canvas,item.w,item.h);paintBackground(ctx,item.w,item.h,state.bg);ctx.drawImage(image,0,0);overlay.replaceChildren();
190
+ try{if(token!==paintToken)return;const ctx=setCanvas(canvas,w,h);paintBackground(ctx,w,h,state.bg);ctx.drawImage(image,0,0);overlay.replaceChildren();
172
191
  caption.textContent=t('Difference: {count} pixels above threshold · {covered} covered pixels excluded · visual comparison, no automatic verdict.',{count:response.headers.get('X-Difference-Count')??'',covered:response.headers.get('X-Difference-Covered')??''});
173
192
  }finally{image.close();}return;
174
193
  }
@@ -176,7 +195,7 @@ async function paintRaster(token:number): Promise<void> {
176
195
  const fronts = await Promise.all(front.map(async o => ({ o, img: await itemImage(o) })));
177
196
  const original=state.comparison.mode==='overlay'&&data.painting?await load('/api/parts/painting'):null;
178
197
  if (token !== paintToken) return;
179
- const ctx = setCanvas(canvas, item.w, item.h);
198
+ const ctx = setCanvas(canvas, w, h);
180
199
  const makeCanvas=(w:number,h:number)=>Object.assign(document.createElement('canvas'),{width:w,height:h});
181
200
  if(original){paintOverlay(ctx,item,img,original,paintingRectangle(item,data.rigSize!,data.painting!),state.comparison.opacity,state.bg);paintFootprints(ctx,item,fronts.map(f=>({box:f.o,image:f.img})),makeCanvas);}
182
201
  else paintPart(ctx, item, img, { bg: state.bg, alpha: state.alpha, fronts: fronts.map(f => ({ box: f.o, image: f.img })), makeCanvas: (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }) });
@@ -190,7 +209,7 @@ async function paintRaster(token:number): Promise<void> {
190
209
  + (state.footprints ? ' ' + (front.length === 1 ? t('Tinted: the footprint of the part drawn in front ({names}).', { names: front[0]!.name }) : front.length ? t('Tinted: the footprints of {count} parts drawn in front ({names}).', { count: front.length, names: front.map(o => o.name).join(', ') }) : t('No part is drawn in front of it.')) : '');
191
210
  }
192
211
 
193
- async function paintReference(token:number):Promise<void>{const data=state.data,item=data?.items[state.selected];if(!data?.painting||!item)return;const img=await load('/api/parts/painting');if(token!==paintToken||data!==state.data||item!==state.data?.items[state.selected])return;const box=state.view==='assembled'?{x:0,y:0,w:data.rigSize![0],h:data.rigSize![1]}:item;const canvas=$<HTMLCanvasElement>('pv-reference');canvas.width=box.w;canvas.height=box.h;const ctx=canvas.getContext('2d')!;paintPaintingCrop(ctx,img,paintingRectangle(box,data.rigSize!,data.painting),box.w,box.h,state.bg);}
212
+ async function paintReference(token:number):Promise<void>{const data=state.data,item=data?.items[state.selected];if(!data?.painting||!item)return;const img=await load('/api/parts/painting');if(token!==paintToken||data!==state.data||item!==state.data?.items[state.selected])return;const box=partFrame(data,item);const canvas=$<HTMLCanvasElement>('pv-reference');canvas.width=box.w;canvas.height=box.h;const ctx=canvas.getContext('2d')!;paintPaintingCrop(ctx,img,paintingRectangle(box,data.rigSize!,data.painting),box.w,box.h,state.bg);}
194
213
 
195
214
  function renderComparison():void {
196
215
  const active=state.data?.mode==='parts'&&(!!state.data.painting||!!state.data.differenceAvailable),overlay=active&&state.comparison.mode==='overlay',difference=state.comparison.mode==='difference';
@@ -405,7 +424,13 @@ async function save(): Promise<void> {
405
424
 
406
425
  async function boot(): Promise<void> {
407
426
  const box=$('pv-canvas-box'),layout=$('stage-layout');mountViewportPair(layout);$('rig-root').append(box);const reference=document.createElement('canvas');reference.id='pv-reference';$('reference-content').append(reference);$('rig-empty').hidden=true;$('rig-overlay').hidden=true;$('rig-label').textContent=t('Selected part');$('rig-viewport').tabIndex=0;
408
- viewport=createPartsViewport({el:$,canvas:$<HTMLCanvasElement>('pv-canvas'),message:(msg)=>{$('pv-save-status').textContent=t(msg);},reference:()=>state.data?.painting?$<HTMLCanvasElement>('pv-reference'):null});viewport.bindControls();
427
+ viewport=createPartsViewport({el:$,canvas:$<HTMLCanvasElement>('pv-canvas'),message:(msg)=>{$('pv-save-status').textContent=t(msg);},reference:()=>state.data?.painting?$<HTMLCanvasElement>('pv-reference'):null,
428
+ frameSize:target=>{
429
+ const data=state.data,item=data?.items[state.selected];
430
+ if(!data||!item)return null;
431
+ return target==='rig'?rasterFrame(data,item):data.painting?partFrame(data,item):null;
432
+ },
433
+ });viewport.bindControls();
409
434
  $('native-one').onclick=()=>viewport!.cameraAction(()=>viewport!.updateCamera(viewport!.availableCamera()??'rig',{zoom:1,pan:{x:0,y:0}}));
410
435
  bindDomI18n(document);
411
436
  bindStageNav({partsOnly:true,model:false});