← Files DXIRARCHIVED FILE
scripts/document.mjs
8.34 KB · Nov 29, 2026 · 18:15 UTC
import a from"node:fs";import L from"node:os";import n from"node:path";import{createHash as F}from"node:crypto";import{spawn as j}from"node:child_process";import{pathToFileURL as R}from"node:url";import{DOCUMENT_LIMIT as S,DOCUMENT_VERSION as M,renderDocument as N}from"./document-template.mjs";import{readProjectBrand as T}from"./brand.mjs";const b=o=>F("sha256").update(o).digest("hex"),s=(o,e)=>{if(!o)throw new Error(e)};function f(o,e,r=!0){const i=a.realpathSync(e);s(typeof o=="string"&&o.length>0&&!n.isAbsolute(o),"Use a project-relative path.");const t=n.resolve(i,o),l=r?a.realpathSync(t):n.join(a.realpathSync(n.dirname(t)),n.basename(t)),c=n.relative(i,l);return s(c&&c!==".."&&!c.startsWith(`..${n.sep}`)&&!n.isAbsolute(c),"Keep document files inside the selected project."),r||s(!a.existsSync(l),"Output already exists. Preserve reserved files; choose a new versioned filename."),l}function I({input:o,output:e,cwd:r=process.cwd(),sources:i}){const t=f(o,r);s(a.statSync(t).size<=S,"Document input exceeds 8 MiB."),s(/\.html$/i.test(e),"Save the document as .html.");const l=f(e,r,!1),c=N(JSON.parse(a.readFileSync(t,"utf8").replace(/^\uFEFF/,"")),T(r,i));return a.writeFileSync(l,c,{encoding:"utf8",flag:"wx"}),{relative_path:e,content_type:"text/html",size_bytes:Buffer.byteLength(c),sha256:b(c),print_checked:!1}}function $(o=process.env.DXIR_PRINT_BROWSER){const r=(o?[o]:[process.env.PROGRAMFILES&&n.join(process.env.PROGRAMFILES,"Google/Chrome/Application/chrome.exe"),process.env["PROGRAMFILES(X86)"]&&n.join(process.env["PROGRAMFILES(X86)"],"Microsoft/Edge/Application/msedge.exe"),process.env.PROGRAMFILES&&n.join(process.env.PROGRAMFILES,"Microsoft/Edge/Application/msedge.exe"),process.env.LOCALAPPDATA&&n.join(process.env.LOCALAPPDATA,"Google/Chrome/Application/chrome.exe"),"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/usr/bin/chromium","/usr/bin/chromium-browser","/usr/bin/google-chrome","/usr/bin/microsoft-edge"]).find(i=>i&&a.existsSync(i)&&a.statSync(i).isFile());return s(r,"Install Edge/Chrome or set DXIR_PRINT_BROWSER to its executable. HTML exists, but printing is not verified."),r}const k=`async function inspectDocument(){
if (document.readyState !== 'complete') await new Promise(resolve => window.addEventListener('load', resolve, {once:true}));
await document.fonts.ready;
const issues = [];
for (const [index, image] of Array.from(document.images).entries()) if (!image.complete || !image.naturalWidth || !image.naturalHeight) issues.push('image_' + (index + 1) + '_unavailable');
const slides = Array.from(document.querySelectorAll('.slide'));
for (const [index, slide] of slides.entries()) {
const box = slide.getBoundingClientRect();
const body = slide.querySelector('.slide-body');
if (!body || body.getBoundingClientRect().bottom > box.bottom - parseFloat(getComputedStyle(slide).paddingBottom) + 1 || slide.scrollWidth > slide.clientWidth + 1) issues.push('slide_' + (index + 1) + '_overflow');
}
const paper = document.querySelector('.document');
if (paper) {
if (paper.scrollWidth > paper.clientWidth + 1) issues.push('document_horizontal_overflow');
for (const [index, row] of Array.from(paper.querySelectorAll('tr')).entries()) if (row.getBoundingClientRect().height > 261 * 96 / 25.4) issues.push('table_row_' + (index + 1) + '_exceeds_page');
}
document.body.setAttribute('data-action-room-check', btoa(JSON.stringify({issues, slides: slides.length})));
}
inspectDocument().catch(() => document.body.setAttribute('data-action-room-check', btoa(JSON.stringify({issues:['layout_check_failed'],slides:0}))));`;function W(o,e,r){const i=o.toString("latin1");s(i.startsWith("%PDF-"),"Browser did not produce a PDF.");const t=[...i.matchAll(/\/Type\s*\/Page\b/g)].length,l=[...i.matchAll(/\/MediaBox\s*\[\s*([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)\s*\]/g)];s(t>0&&l.length===t,"PDF page geometry could not be verified.");const c=e==="presentation";for(const d of l){const m=Number(d[3])-Number(d[1]),u=Number(d[4])-Number(d[2]);s(Math.abs(m-(c?841.89:595.28))<2&&Math.abs(u-(c?595.28:841.89))<2,"PDF paper size or orientation is incorrect.")}return s(!c||t===r,"Each slide must occupy exactly one PDF page. Split overflowing slides and check again."),t}function G(o,e){return new Promise((r,i)=>{const t=j(o,e,{windowsHide:!0,stdio:["ignore","pipe","ignore"]}),l=[];let c=0,d=!1;const m=p=>{d||(d=!0,t.kill(),i(new Error(p)))},u=setTimeout(()=>m("Browser print check timed out. Printing remains unverified."),6e4);t.stdout.on("data",p=>{c+=p.length,c>S*3?m("Browser output exceeded the print-check limit."):l.push(p)}),t.once("error",()=>{clearTimeout(u),m("Could not start the print browser.")}),t.once("close",p=>{clearTimeout(u),d||(p===0?r(Buffer.concat(l).toString("utf8")):i(new Error("Browser print check failed.")))})})}async function U({file:o,pdf:e,evidence:r,browser:i,supportDir:t,cwd:l=process.cwd()}){const c=f(o,l);s(a.statSync(c).size<=S,"HTML exceeds 8 MiB.");const d=a.readFileSync(c),m=d.toString("utf8");s(m.includes(`data-action-room-document="${M}"`),"Use the Action Room HTML template before checking the document.");const u=/data-action-room-layout="(document|presentation)"/.exec(m)?.[1];s(u,"Document layout is missing.");const p=e?f(e,l,!1):null,v=r?f(r,l,!1):null;s(!e||/\.pdf$/i.test(e),"Use a .pdf output path."),s(!r||/\.json$/i.test(r),"Use a .json evidence path.");const B=$(i),w=t?f(t,l):L.tmpdir();s(a.statSync(w).isDirectory(),"Print support path must be a directory.");const h=a.mkdtempSync(n.join(w,"dxir-document-print-"));try{const E=`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-${F("sha256").update(k).digest("base64")}'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'">`,O=m.replace(/<meta\b[^>]*http-equiv=["']Content-Security-Policy["'][^>]*>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,"").replace(/<head>/i,`<head>${E}`).replace(/<\/body>/i,`<script>${k}<\/script></body>`),x=n.join(h,"document.html"),A=n.join(h,"document.pdf");a.writeFileSync(x,O);const C=await G(B,["--headless","--disable-gpu","--no-first-run","--no-default-browser-check","--disable-extensions","--disable-background-networking",`--user-data-dir=${n.join(h,"profile")}`,"--window-size=1440,1100","--virtual-time-budget=2000","--no-pdf-header-footer",`--print-to-pdf=${A}`,"--dump-dom",R(x).href]),P=/data-action-room-check="([A-Za-z0-9+/=]+)"/.exec(C)?.[1];s(P,"Browser did not return a layout check. Printing remains unverified.");const g=JSON.parse(Buffer.from(P,"base64").toString("utf8"));s(Array.isArray(g.issues)&&g.issues.length===0,`Print layout needs correction: ${(g.issues||[]).join(", ")}. Preserve content and split long slides/rows.`),s(u!=="presentation"||g.slides>0,"Presentation has no slides.");const y=a.readFileSync(A),D=W(y,u,g.slides);s(!p||y.length<=S,"PDF exceeds 8 MiB. Reduce images or split the deliverable."),s(b(a.readFileSync(c))===b(d),"HTML changed during verification. Check the current file again.");const _={version:M,relative_path:o,sha256:b(d),size_bytes:d.length,layout:u,paper:"A4",orientation:u==="presentation"?"landscape":"portrait",pages:D,browser_layout_checked:!0,pdf_geometry_checked:!0,visual_review_required:!0,...p?{pdf:{relative_path:e,sha256:b(y),size_bytes:y.length,content_type:"application/pdf"}}:{}};return p&&a.writeFileSync(p,y,{flag:"wx"}),v&&a.writeFileSync(v,JSON.stringify(_,null,2)+`
`,{flag:"wx"}),_}finally{s(n.dirname(n.resolve(h))===n.resolve(w)&&n.basename(h).startsWith("dxir-document-print-"),"Unsafe temporary path."),a.rmSync(h,{recursive:!0,force:!0,maxRetries:5,retryDelay:150})}}async function z(){const[o,...e]=process.argv.slice(2),r={};for(let t=0;t<e.length;t+=2)s(e[t].startsWith("--")&&e[t+1]!==void 0,"Use named options with values."),e[t]==="--source"?(r.sources??=[]).push(e[t+1]):r[e[t].slice(2)]=e[t+1];s(["build","check"].includes(o),"Use document.mjs build or check.");const i=o==="build"?I(r):await U(r);process.stdout.write(JSON.stringify(i)+`
`)}process.argv[1]&&import.meta.url===R(n.resolve(process.argv[1])).href&&z().catch(o=>{const e=o instanceof SyntaxError||o.code?"Check the input JSON and project-relative paths; existing outputs were preserved.":o.message;process.stderr.write(`${e}
`),process.exitCode=1});export{I as buildDocument,U as checkDocument,$ as findPrintBrowser,W as inspectChromiumPdf,f as projectPath,G as runBrowser};
SHA-256: f8cd9cd690a793cf33af96bb4f93b186a1729d77b5a8616ccaac2c0128ca649b