astra/pd-power-supply

USB-PD Power Supply with RP2040 controller

Version
1.1.6
License
unset
Stars
0

scripts/package-fast-review.mjs

import {readFileSync,writeFileSync} from 'node:fs'
import {resolve} from 'node:path'
const data=JSON.parse(readFileSync('dist/index/circuit.json','utf8'))
if(data.some(x=>x.type.includes('error')))throw new Error('Cannot package a circuit with errors')
const assets=[],assetIds=new Map()
function inline(url,mime){
 if(url.includes('/C221660.obj'))return `data:${mime};base64,${readFileSync('imports/JS102011SAQN.obj').toString('base64')}`
 if(url.startsWith('data:'))return url
 if(url.includes('://'))return url
 return `data:${mime};base64,${readFileSync(resolve(url)).toString('base64')}`
}
for(const c of data.filter(x=>x.type==='cad_component')){
 // STEP is only a loader fallback. Keep source STEP files; omit from this preview
 // when a mesh is available, instead of copying unused multi-megabyte solids.
 if(c.model_obj_url||c.model_glb_url||c.model_gltf_url||c.model_stl_url||c.model_wrl_url)delete c.model_step_url
 for(const [key,mime] of [['model_obj_url','text/plain'],['model_glb_url','model/gltf-binary'],['model_step_url','application/step']]){
  if(!c[key])continue
  const asset=inline(c[key],mime)
  if(!asset.startsWith('data:'))continue
  if(!assetIds.has(asset)){assetIds.set(asset,assets.length);assets.push(asset)}
  c[key]=`preview-asset:${assetIds.get(asset)}`
 }
}
let js=readFileSync('dist/standalone.min.js','utf8')
function replaceExactly(from,to,count=1){
 const matches=js.split(from).length-1
 if(matches!==count)throw new Error(`Viewer changed: expected ${count} occurrences of ${from}, got ${matches}`)
 js=js.split(from).join(to)
}
// Preview-only overrides for the bundled @tscircuit/3d-viewer 0.0.607.
// Assert exact fragments so upgrades cannot silently patch unrelated code.
if(!js.includes('nan={version:"0.0.607"}'))throw new Error('Unsupported viewer version')
replaceExactly('var X5i=4e6,Z5i=4096,e4i=1;','var X5i=1e6,Z5i=2048,e4i=1;')
replaceExactly('.setPixelRatio(window.devicePixelRatio)','.setPixelRatio(Math.min(window.devicePixelRatio,1))',2)
replaceExactly('.shadow.mapSize.set(2048,2048)','.shadow.mapSize.set(1024,1024)')
replaceExactly('"cadViewerLightingEnabled"','"pdSupplyFastReviewLightingEnabled"')
replaceExactly('window.localStorage.getItem(oan)!=="false"','window.localStorage.getItem(oan)==="true"')
const safeScript=s=>s.replace(/<\/script/gi,'<\\/script')
const bootstrap=`
window.TSCIRCUIT_USE_RUNFRAME_FOR_CLI=false;
const previewData=${JSON.stringify(data)};
const previewAssets=${JSON.stringify(assets)}.map(dataUrl=>{
 const comma=dataUrl.indexOf(',');
 const header=dataUrl.slice(5,comma),binary=atob(dataUrl.slice(comma+1));
 const bytes=new Uint8Array(binary.length);
 for(let i=0;i<binary.length;i++)bytes[i]=binary.charCodeAt(i);
 return URL.createObjectURL(new Blob([bytes],{type:header.split(';')[0]}));
});
for(const c of previewData){
 if(c.type!=='cad_component')continue;
 for(const k of ['model_obj_url','model_glb_url','model_step_url']){
  if(c[k]?.startsWith('preview-asset:'))c[k]=previewAssets[Number(c[k].split(':')[1])];
 }
}
window.TSCIRCUIT_RUNFRAME_STATIC_FILE_LIST=[{filePath:'index.circuit.tsx',fileStaticAssetUrl:URL.createObjectURL(new Blob([JSON.stringify(previewData)],{type:'application/json'}))}];
window.TSCIRCUIT_PACKAGE_NAME='@tsci/astra.pd-power-supply';
`
let html=readFileSync('dist/index.html','utf8')
html=html.replace(/<script>\s*window\.TSCIRCUIT_USE_RUNFRAME_FOR_CLI[\s\S]*?<\/script>/,()=>`<script>${safeScript(bootstrap)}</script>`)
html=html.replace('<script type="module" src="./standalone.min.js"></script>',()=>`<script type="module">${safeScript(js)}</script>`)
if(html.includes('src="./standalone.min.js"')||!html.includes('pdSupplyFastReviewLightingEnabled'))throw new Error('Viewer embedding failed')
html=html.replace('<title>@tsci/astra.pd-power-supply</title>','<title>PD Supply — lighter review</title>')
writeFileSync('review-fast.html',html)
const metrics={originalHtmlBytes:readFileSync('review.html').length,fastHtmlBytes:Buffer.byteLength(html),embeddedCadAssets:assets.length,boardTexturePixelBudget:1000000,renderPixelRatioCap:1,shadowDefault:false,geometry:'unchanged',viewer:'0.0.607'}
writeFileSync('preview-performance.json',JSON.stringify(metrics,null,2)+'\n')
console.log(metrics)