@format.dev/studio 0.1.0 → 0.1.1

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.
@@ -1,240 +0,0 @@
1
- import{LogLevel as e}from"@format.dev/compile/shared/types/index";import*as t from"node:path";import n,{basename as r,dirname as i,isAbsolute as a,join as o,relative as s,resolve as c,sep as l}from"node:path";import u,{existsSync as d,readFileSync as f,readdirSync as p,renameSync as m,rmSync as h,writeFileSync as g}from"node:fs";import{atlas as ee}from"gradient-string";import{createServer as te,mergeConfig as ne}from"vite";import re from"open";import{RemoteAssetFetchError as ie,fetchRemote as ae,fetchRemoteIfChanged as oe,readRemoteAssets as se,scanAssetRefs as ce,scanRemoteRefs as le}from"@format.dev/zip";import{SUPPORTED_FRAMEWORKS as ue}from"@format.dev/compile/shared/types/public/index";import{checkDir as de,formatForLog as fe,getLogLevel as pe,getUnknownConfigKeyWarnings as me,loadConfig as he,logger as _,parseLogLevelFromEnv as ge,readFile as v,setLogLevel as _e}from"@format.dev/compile/server/utils/index";import{getSchemaPath as ve,validate as ye}from"@format.dev/compile/server/utils/schema";import y,{chmod as be,mkdir as b,readFile as x,readdir as xe,rm as Se,stat as Ce,writeFile as S}from"node:fs/promises";import{CliError as we,buildDocumentPlan as Te,maybeInstallDependencies as Ee,maybeSetupProject as De,readProjectDependencies as Oe,resolveStyling as ke,writeDocument as Ae}from"@format.dev/cli/scaffold";import{PROJECT_EXTENSIONS_ALL as je,SERVER_WATCH_IGNORE as Me}from"@format.dev/compile/server/constants";import Ne from"node:os";import{URL as Pe,fileURLToPath as Fe}from"node:url";import{DOT_FORMAT_DIR_NAME as Ie,DOT_TMP_DIR_NAME as Le}from"@format.dev/compile/server/project/paths";import{DEFAULT_VARIANT as Re,DEV_API_PORT as ze,DEV_DASHBOARD_API_PORT as Be,DEV_DASHBOARD_PORT as Ve,DEV_WEB_PORT as He,NO_DOCUMENTS_MESSAGE as Ue,VARIANT_PARAM as We}from"@format.dev/compile/shared/constants";import{readFile as Ge}from"@format.dev/compile/server/utils/read-file";import{CompileError as Ke}from"@format.dev/compile/server/errors";import{DEFAULT_STYLING as qe,SCHEMA_DEPENDENCIES as Je,STYLING_DEPENDENCIES as Ye,isSchemaKind as Xe,isValidDimension as Ze}from"@format.dev/cli/scaffold/shared";import{findFormatConfigPath as Qe,loadConfig as $e}from"@format.dev/compile/server/utils/load-config";import{getUserProjectDir as C}from"@format.dev/compile/server/project/user-project-dir";import{SHARED_ASSETS_OUT_DIR_NAME as et}from"@format.dev/compile/server/compile/constants";import{compileState as w}from"@format.dev/compile/server/runtime-state";import{getDocumentDataDir as tt,getDocumentDataFile as nt,getDocumentDataVariantPath as rt,getDocumentDataVariantPath as it,getDocuments as at,getDocuments as ot,getUserDocumentIndex as st}from"@format.dev/compile/server/project/documents";import{SANDBOX_ERROR_CODE as ct}from"@format.dev/compile/server/render-worker/sandbox";import{STUDIO_FORBID_TAGS as lt,UNSUPPORTED_TAGS as ut,getPermittedContentType as dt}from"@format.dev/utils";import{unified as ft}from"unified";import pt,{defaultSchema as mt}from"rehype-sanitize";import{buildObservedSchema as ht,parseHtmlFragment as gt,removeTags as _t,stringifyHtmlFragment as vt,stripDangerousUrls as yt}from"@format.dev/compile/server/compile/sanitize/shared";import{compileForStudio as bt,getBundleOutDir as xt,getDocumentAssetsPath as St,getDocumentEntryPath as Ct,renderCompiledDocument as wt}from"@format.dev/compile/server/compile/compile";import{DOCUMENT_ASSETS_DIR_NAME as Tt,resolveDocumentAssetSources as Et}from"@format.dev/compile/server/compile/document-assets";import*as Dt from"@format.dev/compile/server/compile/producer-release";import{createHash as Ot,randomUUID as kt}from"node:crypto";import{documentFontCss as At,fontsDir as jt}from"@format.dev/fonts";import{isDev as T}from"@format.dev/compile/shared/env";import{restampDocumentEngine as Mt}from"@format.dev/compile/server/compile/finalize-document-html";import Nt from"node:http";import Pt,{parseEnv as Ft}from"node:util";import It from"get-port";import{http as Lt}from"@format.dev/compile/shared/http";import{FormatClient as Rt}from"@format.dev/client";import{logger as zt}from"@format.dev/compile/server/utils/log";import E from"os";import Bt from"fast-glob";import Vt from"adm-zip";import Ht from"prettier";import{stylesPreProcessor as Ut}from"@format.dev/compile/server/vite/plugins/styles-pre-processor";import{createConfig as Wt}from"@format.dev/compile/server/vite/create-config";import{shouldDecodeStyleEntities as Gt}from"@format.dev/compile/server/utils/dependencies";import{getLockstepStatus as Kt}from"@format.dev/cli/lockstep";import{assertProducersAgree as qt}from"@format.dev/compile/server/compile/producer-agreement";import{RenderWorker as Jt}from"@format.dev/compile/server/render-worker/index";var Yt=Object.defineProperty,Xt=Object.getOwnPropertyDescriptor,Zt=Object.getOwnPropertyNames,Qt=Object.prototype.hasOwnProperty,$t=(e,t)=>{let n={};for(var r in e)Yt(n,r,{get:e[r],enumerable:!0});return t&&Yt(n,Symbol.toStringTag,{value:`Module`}),n},en=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Zt(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Qt.call(e,s)&&s!==n&&Yt(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Xt(t,s))||r.enumerable});return e},tn=(e,t,n)=>(en(e,t,`default`),n&&en(n,t,`default`)),D=class e extends Error{constructor(t){super(t),this.name=`StudioError`,Error.captureStackTrace?.(this,e)}},O=class extends D{constructor(e){super(e),this.name=`ServerUnreachableError`}},nn=class extends D{constructor(e){super(e),this.name=`SessionExpiredError`}};function k({res:e,status:t,data:n}){let r=JSON.stringify(n);e.statusCode=t,e.setHeader(`Content-Type`,`application/json; charset=utf-8`),e.setHeader(`Content-Length`,Buffer.byteLength(r)),e.end(r)}async function A(e){let t=``;for await(let n of e)t+=n.toString();if(!t)throw Error(`Request body is empty`);try{return JSON.parse(t)}catch{throw Error(`Invalid JSON body`)}}var j=class extends Error{constructor(e,t){super(t),this.status=e,this.name=`HttpError`}};function M(e,t){return t instanceof j?k({res:e,status:t.status,data:{error:t.message}}):k({res:e,status:500,data:{error:t instanceof Error?t.message:`Internal server error`}})}function N(e,t){e?.ws.send({type:`custom`,event:`studio-server-error`,data:t})}const P=`Session expired, please log in again.`,rn=`http://localhost`,an=`Can't connect to Format servers. Check your connection and try again.`,on=e=>`Port ${e} is already in use. Another Studio may still be running. Stop it, or pass --port <number>.`;function sn(e){return e.backgroundPdfBuild??!0}function cn(){try{return JSON.parse(f(z,`utf-8`))}catch{return{}}}async function ln(){await Ge(z)||(await b(bn,{recursive:!0}),await S(z,JSON.stringify({},null,2)))}async function un(){return await ln(),await Ge(z)}async function dn(e){await ln(),await S(z,JSON.stringify(e,null,2))}const fn={production:{name:`production`,dashboardUrl:`https://dash.format.dev`,dashboardApiUrl:`https://backend.dash.format.dev`,apiUrl:`https://api.format.dev`,webUrl:`https://format.dev`},local:{name:`local`,dashboardUrl:`http://localhost:${Ve}`,dashboardApiUrl:`http://localhost:${Be}`,apiUrl:`http://localhost:${ze}`,webUrl:`http://localhost:${He}`,stampEngineVersion:`999.0.0`}};let F=null;function pn(e){let t=process.env.FMT_ENV?.trim();if(t)return{name:t,source:`FMT_ENV`};let n=typeof e.env==`string`?e.env:void 0;return n?{name:n,source:`settings`}:{name:`production`,source:`default`}}function mn(e){let{name:t,source:n}=pn(e),r=process.env.FMT_DASHBOARD_URL?.trim(),i=process.env.FMT_DASHBOARD_API_URL?.trim(),a=process.env.FMT_API_URL?.trim(),o=process.env.FMT_WEB_URL?.trim(),s=fn[t];if(s)return{environment:{...s,dashboardUrl:r||s.dashboardUrl,dashboardApiUrl:i||s.dashboardApiUrl,apiUrl:a||s.apiUrl,webUrl:o||s.webUrl},source:n};if(r&&i&&a&&o)return{environment:{name:t,dashboardUrl:r,dashboardApiUrl:i,apiUrl:a,webUrl:o},source:n};throw new D(`Unknown environment "${t}". Known environments are production and local; define another by setting FMT_DASHBOARD_URL, FMT_DASHBOARD_API_URL, FMT_API_URL and FMT_WEB_URL.`)}function hn(e){return F=mn(e.settings),F.environment}function gn(){return F||(F=mn(cn())),F}function I(){return gn().environment}var L=$t({DOT_FORMAT_DIR:()=>bn,ENGINE_DIR:()=>H,ENVS_DIR:()=>xn,FORMAT_ENGINE_PATH:()=>Tn,PUBLIC_DIR:()=>vn,SETTINGS_FILE:()=>z,STUDIO_APP_ALIAS:()=>yn,_dirname:()=>R,getCredentialsFile:()=>Sn,getDotTempDir:()=>wn,getEnvDir:()=>B,getPdfBuildDir:()=>V,getStateFile:()=>Cn});import*as _n from"@format.dev/compile/server/project/paths";tn(L,_n);const R=o(i(Fe(import.meta.url)),`..`),vn=o(R,`public`),yn=`/@format/studio`,bn=o(Ne.homedir(),Ie),z=o(bn,`settings.json`),xn=o(bn,`envs`),B=()=>o(xn,I().name),Sn=()=>o(B(),`credentials.json`),Cn=()=>o(B(),`state.json`),wn=()=>process.env.FMT_DOT_TMP_DIR?.trim()||c(R,`..`,Le),V=e=>o(e,`node_modules`,`.cache`,`format-studio`,`pdf-build`),H=o(R,`engine`),Tn=e=>o(H,e,`format_engine.js`),U={diagnostics:{sanitization:null,remoteAssets:null,imageFormats:null,unsupportedElements:null},auth:{token:null,failed:!1},engine:{requested:null,resolved:null},activeDocumentAssetSources:null,skipNextConfigRestart:!1},W={armConfigRestartSkip(){U.skipNextConfigRestart=!0},consumeConfigRestartSkip(){return U.skipNextConfigRestart?(U.skipNextConfigRestart=!1,!0):!1},getToken(){if(!U.auth.token)throw new D(`Auth token not initialized`);return U.auth.token},setToken(e){U.auth.token=e},clearToken(){U.auth.token=null},isAuthFailed(){return U.auth.failed},setAuthFailed(){U.auth.failed=!0},clearAuthFailed(){U.auth.failed=!1},setEngineVersions(e){U.engine.requested=e.requested,U.engine.resolved=e.resolved},getEngineRequested(){if(!U.engine.requested)throw new D(`Requested engine not set`);return U.engine.requested},getEngineResolved(){if(!U.engine.resolved)throw new D(`Resolved engine not set`);return U.engine.resolved},setSanitizationDiagnostics(e){U.diagnostics.sanitization=e},setRemoteAssetDiagnostics(e){U.diagnostics.remoteAssets=e},setImageFormatDiagnostics(e){U.diagnostics.imageFormats=e},setUnsupportedElementDiagnostics(e){U.diagnostics.unsupportedElements=e},getDiagnostics(){return U.diagnostics},setActiveDocumentAssetSources(e){U.activeDocumentAssetSources=e},getActiveDocumentAssetSources(){return U.activeDocumentAssetSources}};function En(e){return async(t,n,r)=>{let i=t.url?.match(/^\/api\/documents\/([^\/]+)\/data\/([^\/]+)$/);if(!i)return r();if(W.isAuthFailed())return M(n,new j(401,P));let[,a,o]=i,s=await nt(a,o,w.getConfig());if(!s){let n=o===Re?`Please create a default.json file in the ${a}/data directory. Refer to our documentation for more information.`:`Failed to load ${a} with variant ${o}. Please check the URL or create a ${o}.json file in the ${a}/data directory. Refer to our documentation for more information.`;return N(e,{scope:`document`,path:t.url,message:n,dismissible:!1}),r()}k({res:n,status:200,data:s})}}function Dn(){return async(e,t)=>{try{if(W.isAuthFailed())throw new j(401,P);k({res:t,status:200,data:await at(w.getConfig())})}catch(e){M(t,e)}}}const On={react:`.tsx`,vue:`.vue`,html:`.ts`};async function kn(e){let{wanted:t,styling:n,config:r}=e;if(!t||n===void 0||!ke({framework:r.framework,method:n}).setupProject)return null;let i=C(),a=Qe(i);if(!a)return _.warn(`Skipping project setup: no Format config file found to amend.`),null;let o=s(i,(0,L.getDocumentsDir)(r));W.armConfigRestartSkip();let c=await De({wanted:t,styling:n,config:r,projectRoot:i,formatConfigPath:a,documentsGlobBase:o});try{let e=await $e(a);w.setConfig(e.config)}catch(e){_.warn(`Failed to reload the Format config after project setup.`,e)}return c}function An(e){if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();if(t!==``)try{return JSON.parse(t)}catch{throw new j(400,`The data you provided isn't valid JSON.`)}}function jn(e){return async(t,n,r)=>{if(t.method!==`POST`)return r();try{if(W.isAuthFailed())throw new j(401,P);let r=await A(t);if(typeof r.name!=`string`)throw new j(400,`A document name is required.`);let i=r.styling===void 0?void 0:String(r.styling),a=w.getConfig(),o=r.schema===!0,s=typeof r.schemaKind==`string`&&Xe(r.schemaKind)?r.schemaKind:void 0,c=typeof r.width==`number`&&Ze(r.width)?r.width:void 0,l=typeof r.height==`number`&&Ze(r.height)?r.height:void 0,u=c!==void 0&&l!==void 0,d=An(r.data),f=await Te({config:a,projectRoot:C(),name:r.name,styling:i,emitSchema:o,schemaKind:s,width:u?c:void 0,height:u?l:void 0,data:d}),p=await Ee({wanted:r.installDependencies===!0,projectRoot:C(),emitSchema:o,schemaKind:s,missingStylingDependencies:f.prerequisites.missingDependencies.map(e=>e.name)}),m=await kn({wanted:r.installDependencies===!0,styling:i,config:a});await Ae(f);let h={name:f.documentName,variants:[Re],extension:On[a.framework],lastModified:Date.now()},g=await ke({framework:a.framework,method:i??qe}).checkPrerequisites({config:w.getConfig(),projectRoot:C()});if(p.attempted&&p.ok||m!==null)try{m!==null&&e.updateInitConfig(JSON.stringify(w.getConfig())),await e.restart()}catch(e){_.warn(`Failed to restart the render worker after project setup.`,e)}k({res:n,status:201,data:{document:h,prerequisites:g,install:p,projectSetup:m}})}catch(e){if(e instanceof Ke||e instanceof we)return M(n,new j(400,e.message));M(n,e)}}}const Mn=async(e,t)=>{try{return await e.ssrLoadModule(t)}catch(e){return _.error(`Failed to load module at path: ${t}`,e),null}};async function Nn(e){let t=`Loaded "${e.documentName}" document in`;_.time(t);let n={},{dataFilePath:r,config:i,documentName:a,server:o,renderWorker:s}=e;_.debug(`Render input args`,JSON.stringify({dataFilePath:r,config:i}));try{if(!i.framework)throw new D(`Framework not provided or invalid: ${i.framework}. Must be one of: ${ue.join(`, `)}`);if(r){let e=await v(r);e&&(n=e)}let c=await ve(tt(a,i));if(c){let{default:e}=await Mn(o,c);if(e||_.warn(`Schema File found, but no valid schema found at ${c}. Ensure your schema library follows the Standard Schema V1 spec and you are using a default export. Read more in our docs.`),e){let t=await ye(e,n);if(!t.ok){let{errors:e}=t;return N(o,{scope:`document`,dismissible:!1,message:`Data validation failed for ${a}. Check your schema and data.`,details:e}),_.error(`Data validation failed for ${a}. Check your schema and data.`,e),null}n=t.data}}let{framework:l}=i,u=W.getEngineResolved();_.debug(`Delegating render to worker (framework=${l}, engine=${u})`);let d=await s.devRender({entryFilePath:e.entryFilePath,data:n,framework:l,engineVersion:u});return _.timeEnd(t),d.html}catch(e){let t=e?.code===ct;throw N(o,{scope:`document`,dismissible:!1,title:t?`Document restriction`:`Document rendering error`,message:t?e.message:void 0,...!t&&{stack:e.stack}}),e}}const Pn=new Set(lt.map(e=>e.toLowerCase()));function Fn(e){return ht(mt,e,!0)}function In(e){let t={},n=gt(e);_t(n,Pn,e=>{t[e]=(t[e]??0)+1}),yt(n);let r=Fn(n),i=ft().use(pt,r).runSync(n),a=vt(i),o=Object.values(t).reduce((e,t)=>e+t,0),s=o===0?null:{removedElements:o,removedTags:t};return{html:String(a),diagnostics:s,tree:i}}const Ln=[`.webp`,`.avif`];function Rn(e){let t=e.toLowerCase();return Ln.some(e=>t.endsWith(e))}function zn(e){return e.filter(Rn).sort()}const Bn=new Set(ut.map(e=>e.toLowerCase()));function Vn(e,t){if(e.type===`element`&&e.tagName){let n=e.tagName.toLowerCase();Bn.has(n)&&t.add(n)}for(let n of e.children||[])Vn(n,t);for(let n of e.content?.children||[])Vn(n,t)}function Hn(e){let t=new Set;return Vn(e,t),[...t].sort()}function Un(){let e=w.getConfig(),t=C(),n=e.dotEnvPath??`.env`;return a(n)?n:o(t,n)}async function Wn(e,t){return Yn(await Promise.all([...e].sort().map(async e=>(await t(e)).map(e=>`${e.path}:${e.mtimeMs}:${e.size}`).sort().join(`
2
- `))))}async function Gn(e){let{inputs:t,directories:n,key:r,stat:i,listDir:a}=e;return{files:(await Promise.all(t.map(async e=>({path:e,stats:await i(e)})))).filter(e=>e.stats!==null).map(({path:e,stats:t})=>({path:e,mtimeMs:t.mtimeMs,size:t.size})).sort((e,t)=>e.path.localeCompare(t.path)),directories:[...n].sort(),directoriesHash:await Wn(n,a),key:r}}async function Kn(e){let{manifest:t,key:n,stat:r,listDir:i}=e;return t.key!==n||t.files.length===0||await Wn(t.directories,i)!==t.directoriesHash?!1:(await Promise.all(t.files.map(async e=>{let t=await r(e.path);return t!==null&&t.mtimeMs===e.mtimeMs&&t.size===e.size}))).every(Boolean)}function qn(e,t){let n=s(c(t),c(e));return n===``||!n.startsWith(`..${l}`)&&n!==`..`&&!n.startsWith(`/`)}function Jn(e,t){let n=c(t);return e.files.some(e=>e.path===n)||e.directories.some(e=>qn(n,e))?!0:e.files.some(e=>i(e.path)===n)}function Yn(e){return Ot(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function Xn(e){let t=Ot(`sha256`);for(let n of e)t.update(typeof n==`string`?n:Buffer.from(n)),t.update(`\0`);return t.digest(`hex`)}function Zn(){let e=new Map,t=Promise.resolve(),n=e=>{let n=t.then(e,e);return t=n.catch(()=>{}),n},r=(t,r)=>{let i={running:Promise.resolve(),dirty:!1},a=(async()=>{let e=await n(r);return i.dirty?(i.dirty=!1,n(r)):e})().finally(()=>{e.get(t)===i&&e.delete(t)});return i.running=a,e.set(t,i),a};return{run(t,n){let i=e.get(t);return i?(i.dirty=!0,i.running):r(t,n)},isRunning(t){return e.has(t)},isBusy(){return e.size>0}}}function Qn(e={fetchRemote:ae,fetchRemoteIfChanged:oe}){let t=new Map,n=new Map;async function r(n){let r=t.get(n.url);if(!r){let r=await e.fetchRemote(n);return t.set(n.url,r),r}try{let i=await e.fetchRemoteIfChanged({...n,validators:r.validators});return i?(t.set(n.url,i),i):r}catch(e){if(!(e instanceof ie))throw e;return _.debug(`Could not reach ${n.url} to check for changes, using the copy from earlier`),r}}function i(e){let t=n.get(e.url);if(t)return t;let i=r(e).finally(()=>n.delete(e.url));return n.set(e.url,i),i}return{beginCheck(){let e=new Set;return async n=>{let r=t.get(n.url);if(r&&e.has(n.url))return r;let a=await i(n);return e.add(n.url),a}},clear(){t.clear(),n.clear()}}}const $n=(e,t)=>o(e,t,`build`),er=(e,t)=>o(e,t,`inputs.json`),tr=(e,t)=>o(e,t,`pdfs`);async function nr(e,t){try{let n=await x(er(e,t),`utf-8`),r=JSON.parse(n);return!Array.isArray(r.files)||!Array.isArray(r.directories)||typeof r.key!=`string`?null:r}catch{return null}}async function rr(e,t,n){let r=er(e,t);await b(c(r,`..`),{recursive:!0}),await S(r,JSON.stringify(n),`utf-8`)}async function ir(e,t){await Se(er(e,t),{force:!0}).catch(()=>{})}async function ar(e,t,n){try{return await x(o(tr(e,t),`${n}.pdf`))}catch{return null}}async function or(e,t,n,r){let i=tr(e,t);try{await b(i,{recursive:!0}),await S(o(i,`${n}.pdf`),r),await sr(i)}catch(e){_.debug(`Could not cache the generated PDF`,e)}}async function sr(e){let t=(await xe(e).catch(()=>[])).filter(e=>e.endsWith(`.pdf`));if(t.length<=5)return;let n=(await Promise.all(t.map(async t=>({name:t,mtimeMs:(await Ce(o(e,t)).catch(()=>null))?.mtimeMs??0})))).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(5);await Promise.all(n.map(t=>Se(o(e,t.name),{force:!0}).catch(()=>{})))}const G=async e=>{let t=await Ce(e).catch(()=>null);return!t||!t.isFile()?null:{mtimeMs:t.mtimeMs,size:t.size}},cr=async e=>{let t=await xe(e,{recursive:!0,withFileTypes:!0}).catch(()=>[]);return(await Promise.all(t.filter(e=>e.isFile()).map(async e=>{let t=o(e.parentPath,e.name),n=await G(t);return n?{path:t,mtimeMs:n.mtimeMs,size:n.size}:null}))).filter(e=>e!==null)},K=new Map,lr=new Map,ur=Zn();let dr=1,fr=null;const pr=Qn(),mr=new Set;function hr(e){fr=e}function q(e,t){fr?.({documentName:e,state:t})}const gr=(e,t)=>`${e}/${t}`;function _r(e,t){return{documents:[e],remoteAssets:!0,inlineRemoteCss:!0,validateSchema:!1,clean:!1,outDir:t}}function vr(e){return Yn({options:e.options,config:e.config,sdkVersion:Dt.sdkVersion,engineTarget:Dt.engineTarget})}function yr(e,t){return[(0,L.getSharedAssetsDir)(t),o((0,L.getDocumentsDir)(t),e,Tt)]}async function br(e){let{documentName:t,outDir:n,key:r}=e,i=await nr(V(C()),t);return!i||await G(Ct(n,t))===null||!await Kn({manifest:i,key:r,stat:G,listDir:cr})?null:(_.debug(`Reusing the PDF bundle on disk for "${t}"`),{buildId:dr++,outDir:n,manifest:i})}async function xr(e){let{documentName:t,config:n,outDir:r,key:i,background:a,remoteFetch:o}=e,s=V(C()),c=_r(t,r);q(t,`building`);let l=performance.now(),{inputs:u}=await bt(c,{useDiskCache:!1,remoteFetch:o,quiet:a}),d=Un(),f=await Gn({inputs:await G(d)===null?u:[...u,d],directories:yr(t,n),key:i,stat:G,listDir:cr});return await rr(s,t,f),_.debug(`Built the PDF bundle for "${t}" in ${(performance.now()-l).toFixed(0)}ms`),{buildId:dr++,outDir:r,manifest:f}}async function Sr(e){let{documentName:t,config:n,background:r=!1,remoteFetch:i=pr.beginCheck()}=e,a=V(C()),o=$n(a,t),s=vr({documentName:t,config:n,options:_r(t,o)}),c=K.get(t);return!mr.has(t)&&c&&c.manifest.key===s&&await Kn({manifest:c.manifest,key:s,stat:G,listDir:cr})?c:ur.run(t,async()=>{let e=mr.has(t),c=K.get(t);if(!e&&c&&c.manifest.key===s&&await Kn({manifest:c.manifest,key:s,stat:G,listDir:cr}))return c;try{let a=(e?null:await br({documentName:t,config:n,outDir:o,key:s}))??await xr({documentName:t,config:n,outDir:o,key:s,background:r,remoteFetch:i});return mr.delete(t),K.set(t,a),q(t,`ready`),a}catch(e){throw K.delete(t),await ir(a,t),q(t,`error`),e}})}async function Cr(e){let{documentName:t,variant:n,config:r,remoteFetch:i}=e,a=await Sr({documentName:t,config:r,remoteFetch:i}),o=(await G(rt(t,n,r)))?.mtimeMs??null,s=gr(t,n),c=lr.get(s);if(c&&c.buildId===a.buildId&&c.dataMtimeMs===o)return{html:c.html,outDir:a.outDir};let l=await wt({outDir:a.outDir,documentName:t,variant:n,config:r,remoteAssets:!0,remoteFetch:i});return lr.set(s,{buildId:a.buildId,dataMtimeMs:o,html:l}),{html:l,outDir:a.outDir}}async function wr(e){let{documentName:t,variant:n,config:r,stampHtml:i,generatePdf:a}=e,o=pr.beginCheck();await Tr({documentName:t,config:r,remoteFetch:o});let{html:s,outDir:c}=await Cr({documentName:t,variant:n,config:r,remoteFetch:o}),l=i(s),u=await x(St(c,t)).catch(()=>void 0),d=V(C()),f=Xn([l,u??new Uint8Array]),p=await ar(d,t,f);if(p)return _.debug(`Serving "${t}" (${n}) from the PDF cache`),{bytes:p,cached:!0};let m=await a({html:l,assets:u});return await or(d,t,f,m),{bytes:m,cached:!1}}async function Tr(e){let{documentName:t,config:n,remoteFetch:r}=e,i=await x(St((await Sr({documentName:t,config:n,remoteFetch:r})).outDir,t)).catch(()=>void 0);i&&(await Promise.all(se(i).map(async e=>{let t=await r({url:e.url});return Buffer.compare(t.bytes,e.bytes)!==0}))).some(Boolean)&&(_.debug(`A remote asset used by "${t}" changed, rebuilding its PDF bundle`),mr.add(t),K.delete(t),Dr(t),q(t,`stale`))}function Er(e,t){for(let[t,n]of K)Jn(n.manifest,e)&&(K.delete(t),Dr(t),q(t,`stale`))}function Dr(e){for(let t of lr.keys())t.startsWith(`${e}/`)&&lr.delete(t)}let J=null;function Or(e){let{documentName:t,config:n}=e;J&&clearTimeout(J),J=setTimeout(()=>{J=null,kr({documentName:t,config:n})},1e3),J.unref?.()}async function kr(e){let{documentName:t,config:n}=e;if(sn(await un().catch(()=>({}))))try{await Sr({documentName:t,config:n,background:!0})}catch(e){_.debug(`Background PDF build for "${t}" failed`,e)}}function Ar(){J&&(clearTimeout(J),J=null)}async function jr(e){let{entryFilePath:t,config:n}=e;try{let e=await Et({entryFilePath:t,config:n,outDir:xt(n),sharedAssetsOutDirName:et});W.setActiveDocumentAssetSources(e)}catch(e){_.debug(`Asset source resolution skipped`,e)}}function Mr(){W.setSanitizationDiagnostics(null),W.setRemoteAssetDiagnostics(null),W.setImageFormatDiagnostics(null),W.setUnsupportedElementDiagnostics(null)}function Nr(t,n){return async(r,i,a)=>{let o=r.url?.match(/^\/api\/render\/([^\/]+)\/([^\/]+)$/);if(!o)return a();let[,s,c]=o;try{if(W.isAuthFailed())throw new j(401,P);let r=w.getConfig(),a=await st({documentName:s,config:r}),o=await Nn({entryFilePath:a,dataFilePath:it(s,c,r),config:r,server:t,documentName:s,renderWorker:n});if(typeof o!=`string`)throw new j(500,`Render output must be HTML.`);let l=In(o);pe()>=e.DEBUG&&_.debug(`Final HTML (post-sanitize)
3
- `,await fe(l.html,`html`)),W.setSanitizationDiagnostics(l?.diagnostics?{documentName:s,variant:c,...l.diagnostics,timestamp:Date.now()}:null),await jr({entryFilePath:a,config:r});let u=le(l.html);W.setRemoteAssetDiagnostics(u.length>0?{documentName:s,variant:c,urls:u,timestamp:Date.now()}:null);let d=zn(ce(l.html));W.setImageFormatDiagnostics(d.length>0?{documentName:s,variant:c,assets:d,timestamp:Date.now()}:null);let f=Hn(l.tree);W.setUnsupportedElementDiagnostics(f.length>0?{documentName:s,variant:c,tags:f,timestamp:Date.now()}:null),Or({documentName:s,config:r}),i.setHeader(`Content-Type`,`text/html`),i.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),i.setHeader(`Pragma`,`no-cache`),i.setHeader(`Expires`,`0`),i.end(l.html);return}catch(e){Mr(),e?.code===ct?_.error(e.message):_.error(`Render error`,e),M(i,e);return}}}function Pr(){return async(e,t,r)=>{let i=e.url?.replace(`/@studio`,``);if(!i){r();return}let a=n.join(vn,i);try{await y.access(a);let e=await y.readFile(a),r=dt(n.extname(i).toLowerCase());if(r){t.setHeader(`Content-Type`,r),T()&&t.setHeader(`Cache-Control`,`no-store`),t.end(e);return}}catch{}r()}}function Fr(){return(e,t)=>{let n=At(new URL(e.url??``,rn).searchParams.get(`mode`),{delivery:`url`,baseUrl:`/@studio/fonts`});t.setHeader(`Content-Type`,`text/css`),t.setHeader(`Cache-Control`,`no-store`),t.end(n)}}function Ir(){return async(e,t,r)=>{let i=e.url?.split(`?`)[0];if(!i){r();return}let a;try{a=decodeURIComponent(i.replace(/^\/+/,``))}catch{r();return}let o=n.resolve(jt,n.normalize(a)),s=n.resolve(jt);if(!o.startsWith(s+n.sep)){t.statusCode=403,t.end(`Forbidden`);return}let c=dt(n.extname(a).toLowerCase());if(!c){r();return}try{let e=await y.readFile(o);t.setHeader(`Content-Type`,c),t.end(e);return}catch{r()}}}async function Lr(e,t){for(let r of e){let e=n.resolve(r,t),i=n.resolve(r);if(e.startsWith(i+n.sep))try{if((await y.stat(e)).isFile())return e}catch{}}return null}const Rr=new Set([`.svg`,`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.avif`,`.ico`]),zr=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function Br(e){return Rr.has(e)?`image`:zr.has(e)?`font`:`other`}async function Vr(e,t){let r=[],i=async(e,a)=>{let o;try{o=await y.readdir(e,{withFileTypes:!0})}catch{return}for(let s of o){let o=a?`${a}/${s.name}`:s.name;if(s.isDirectory()){await i(n.join(e,s.name),o);continue}if(!(!s.isFile()||s.name.startsWith(`.`)))try{let i=await y.stat(n.join(e,s.name));r.push({path:o,size:i.size,type:Br(n.extname(s.name).toLowerCase()),source:t})}catch{}}};return await i(e,``),r}function Hr(){return async(e,t,r)=>{if(e.method!==`GET`)return r();let i=e.url?.match(/^\/api\/documents\/([^/]+)\/assets$/);if(!i)return r();try{if(W.isAuthFailed())throw new j(401,P);let e=decodeURIComponent(i[1]),r=w.getConfig(),a=n.resolve((0,L.getDocumentsDir)(r),e,`assets`),[o,s]=await Promise.all([Vr(a,`document`),Vr((0,L.getSharedAssetsDir)(r),`shared`)]),c=new Set(o.map(e=>e.path));k({res:t,status:200,data:{assets:[...o,...s.filter(e=>!c.has(e.path))]}})}catch(e){M(t,e)}}}function Ur(e){return async(e,t,r)=>{if(e.method!==`GET`&&e.method!==`HEAD`)return r();if(W.isAuthFailed()){t.statusCode=401,t.end(P);return}let i=new URL(e.url??``,rn).pathname;if(i.startsWith(`/.well-known/`)||i.startsWith(`/@fs/`)||i.startsWith(`/@id/`)||i.startsWith(`/@vite/`))return r();let a=dt(n.extname(i).toLowerCase());if(!a)return r();let o=(0,L.getSharedAssetsDir)(w.getConfig()),s=[W.getActiveDocumentAssetSources()?.documentAssetsDir,o].filter(e=>!!e),c;try{c=decodeURIComponent(i.slice(1))}catch{return r()}let l=await Lr(s,n.normalize(c));if(!l)return r();try{let e=await y.readFile(l);t.setHeader(`Content-Type`,a),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`Pragma`,`no-cache`),t.setHeader(`Expires`,`0`),t.end(e);return}catch{return r()}}}async function Wr(e){await b(B(),{recursive:!0});let t=await Gr(),n=t.findIndex(t=>t.org.id===e.org.id);n>=0?t[n]=e:t.push(e);let r=Sn();await S(r,JSON.stringify(t,null,2)),await be(r,384)}async function Gr(){return await v(Sn())||(_.debug(`Credentials file not found or empty`),[])}async function Kr(e){return e&&(await Gr()).find(t=>t.org.id===e)||null}const qr=[`format_engine.js`,`format_engine_bg.wasm`],Jr=`.engine-digest`,Yr=/^[0-9a-f]{64}$/;function Xr(e){return qr.every(t=>d(o(H,e,t)))}function Zr(e){let t=o(H,e,Jr);if(!d(t))return null;try{let e=f(t,`utf8`).trim();return Yr.test(e)?e:null}catch{return null}}function Qr(e,t){g(o(e,Jr),`${t}\n`)}function $r(e,t){return Xr(e)?Zr(e)===t:!1}const ei=/^[0-9a-f]{64}$/;function ti(e){let t;try{t=new URL(e).hostname}catch{return!1}return t===`localhost`||t===`::1`||t===`[::1]`||/^127(?:\.\d{1,3}){3}$/.test(t)}function ni(e,t){return e?t==null?ti(e)?{ok:!0,digest:null}:{ok:!1,reason:`no expected SHA-256 was supplied for a remote engine`}:ei.test(t)?{ok:!0,digest:t}:{ok:!1,reason:`'${t}' is not a SHA-256`}:{ok:!1,reason:`the credentials name no engine URL`}}function ri(e,t){let n=ni(e,t);if(!n.ok)throw new D(`Engine download refused: ${n.reason}. Sign in again to obtain a usable one.`);return n.digest}async function ii(){let e=await v(Cn());return _.debug(`State loaded`,{hasState:!!e,currentOrgId:e?.currentOrgId}),e||{}}async function ai(e){await b(B(),{recursive:!0}),await S(Cn(),JSON.stringify(e,null,2))}async function oi(e){let t=await ii();t.currentOrgId=e,await ai(t)}function si(){let{dashboardUrl:e,dashboardApiUrl:t}=I();return{dashboardUrl:e,exchangeUrl:`${t}/studio/exchange`,refreshUrl:`${t}/studio/refresh`}}const ci=`http://localhost`,li=`health`,ui=`link`,di={"Access-Control-Allow-Origin":`*`,"Access-Control-Allow-Methods":`POST, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type`};let fi=!1;function pi(){fi=!1}function mi(){return fi?!1:(fi=!0,!0)}function Y(e){return Pt.inspect(e,{depth:null,colors:!0})}function hi(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.id!=`string`||typeof t.name!=`string`||`logo`in t&&t.logo!==void 0&&typeof t.logo!=`string`||typeof t.isPersonal!=`boolean`)}function gi(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.sub!=`string`||typeof t.name!=`string`||typeof t.sid!=`string`||typeof t.engine!=`string`||typeof t.plan!=`string`||typeof t.pageLimit!=`number`||`email`in t&&typeof t.email!=`string`||!hi(t.org))}function X(e){try{let t=e.split(`.`);if(t.length!==3)throw new D(`Invalid JWT format`);let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=Buffer.from(n,`base64`).toString(`utf-8`),i=JSON.parse(r);if(!gi(i))throw new D(`Invalid JWT payload`);return i}catch(e){return _.warn(`Failed to decode JWT payload:`,Y(e)),null}}async function _i(e){let t=``;for await(let n of e)t+=n;return t?JSON.parse(t):{}}function Z(e,t,n){e.writeHead(t,{"Content-Type":`text/plain`,...di}),e.end(n)}function vi(e){e.writeHead(204,di),e.end()}function yi(e){_.debug(`Health check received`),Z(e,200,`ok`)}var bi=class extends D{constructor(){super(`The sign-in was closed without linking an organization.`),this.name=`LinkCancelledError`}};async function xi(e,t,n,r){let{code:i,token:a,cancelled:o}=n;if(o)throw _.debug(`Link cancelled by the dashboard`),Z(t,200,`ok`),new bi;T()&&_.debug(`Link request received`,{code:i,token:a});let{data:s,error:c}=await Lt(si().exchangeUrl,{method:`POST`,headers:{Authorization:`Bearer ${a}`},body:{code:i,requestedEngine:r}});if(c)throw Error(`Exchange failed: ${typeof c==`object`?JSON.stringify(c):c}`);if(!s)throw Error(`Exchange failed: No data returned`);return _.debug(`Token exchange successful`),Z(t,200,`ok`),s}function Si(e,t,n,r,i){let a;return a=Nt.createServer(async(o,s)=>{if(!o.url)return Z(s,400,`Missing URL`);let c=new Pe(o.url,`${ci}:${e}`);if(_.debug(`Incoming request:`,o.method,c.pathname),o.method===`OPTIONS`)return vi(s);if(o.method===`GET`&&c.pathname===`/${li}`)return yi(s);let l={};if(o.method===`POST`)try{l=await _i(o)}catch(e){return _.error(`Invalid JSON body:`,e),Z(s,400,`Invalid JSON body`)}if(o.method===`POST`&&c.pathname===`/${ui}`){if(i?.aborted)return Z(s,409,`This link was cancelled in Studio. Start again from Studio to link an organization.`);try{let e=await xi(o,s,l,t);return a.close(),n(e)}catch(e){return e instanceof bi?_.debug(`Link flow closed without linking`):(_.error(`Link error:`,Y(e)),Z(s,500,`Error processing link`)),a.close(),r(e)}}Z(s,404,`Not found`)}),a}const Ci=`Login timed out before completing in the browser. Please try again.`;function wi(e,t,n,r){return new Promise((i,a)=>{let o=null,s=()=>{o&&(clearTimeout(o),o=null),r?.removeEventListener(`abort`,d)},c=e=>{s(),i(e)},l=e=>{s(),a(e)},u=Si(e,t,c,l,r);function d(){u.close(),u.closeIdleConnections(),l(new bi)}if(r?.aborted)return a(new bi);r?.addEventListener(`abort`,d,{once:!0}),n&&(o=setTimeout(()=>{u.close(),l(new D(Ci))},n)),u.listen(e)})}function Ti(e,t){let n={deviceName:Ne.platform()===`darwin`?Ne.hostname().replace(/\.local$/,``):Ne.hostname(),studioHealthUrl:`${ci}:${e}/${li}`,studioLinkUrl:`${ci}:${e}/${ui}`,...t?.length?{linkedOrganizationIds:t}:{}},r=Buffer.from(JSON.stringify(n)).toString(`base64url`);return`${si().dashboardUrl}/studio/link?state=${r}`}function Ei(e,t){if(t.open){_.info(`Opening Format login in your browser...`),re(e);return}_.info(`Open this URL to log in: ${e}`)}async function Di(e,t){let n=await It();return{loginUrl:Ti(n,t?.linkedOrganizationIds),waitForLogin:(async()=>{let r=await ki({authResult:await wi(n,e,t?.timeoutMs,t?.signal),requestedEngine:e});return T()&&_.debug(`Login success`,r),r})()}}function Oi(e){let{accessToken:t,requestedEngine:n,expectedOrgId:r}=e,i=X(t);if(!i)throw new D(`Failed to decode access token`);let{engine:a,org:o}=i,s=i.exp;if(typeof s==`number`){let e=Math.floor(Date.now()/1e3);if(s<e)throw new D(`Access token is already expired (expired ${e-s}s ago, exp=${s}, now=${e})`)}if(a!==n&&!a.startsWith(`${n}-edge.`))throw new D(`Engine version mismatch (requested: ${n}, resolved: ${a})`);if(r&&o.id!==r)throw new D(`Organization ID mismatch`);return{engine:a,org:o}}async function ki(e){let{authResult:t,requestedEngine:n,expectedOrgId:r}=e,{accessToken:i,engineUrl:a,engineDigest:o}=t,{engine:s,org:c}=Oi({accessToken:i,requestedEngine:n,expectedOrgId:r});return await Wr({org:c,...t}),{org:c,accessToken:i,engineUrl:a,engineDigest:o,engine:s}}async function Ai(e,t){let n=await Kr(e);if(!n||!n.refreshToken)throw Error(`No refresh token found for org`);let r=await Pi({refreshToken:n.refreshToken,requestedEngine:t,orgId:e});return W.setToken(r.accessToken),{accessToken:r.accessToken,engineUrl:r.engineUrl,engineDigest:r.engineDigest}}async function ji(){let e=X(W.getToken());if(!e)throw new D(`Failed to decode current token`);let{accessToken:t}=await Ai(e.org.id,W.getEngineRequested());return t}function Mi({server:e}){let t=setInterval(async()=>{try{T()&&_.debug(`Refreshing engine licence`);let t=X(W.getToken());if(!t)throw Error(`Failed to decode current token`);let n=t.org.id,{accessToken:r}=await Ai(n,W.getEngineRequested()),i=W.isAuthFailed();W.clearAuthFailed(),T()&&_.debug(`Engine licence refreshed`),e.ws.send({type:`custom`,event:`token-refreshed`,data:r}),i&&e.ws.send({type:`custom`,event:`auth-restored`}),pi()}catch(t){_.error(`Failed to refresh licence:`,Y(t)),mi()&&(W.setAuthFailed(),e.ws.send({type:`custom`,event:`token-refresh-failed`,data:{message:P,details:[{message:`Token refresh failed`,error:Y(t)}]}}))}},3e3*1e3);return t.unref(),()=>clearInterval(t)}function Ni(e){let{status:t,message:n}=e;return t===null||t>=500?new O(n??`Format servers are unreachable`):new nn(n??`Refresh token rejected`)}async function Pi(e){let{refreshToken:t,requestedEngine:n,orgId:r}=e;_.debug(`Refreshing credentials from stored refresh token`);let{data:i,error:a,status:o}=await Lt(si().refreshUrl,{method:`POST`,body:{refreshToken:t,requestedEngine:n}});if(a||!i)throw _.error(`Token refresh failed`),Ni({status:o,message:a});return _.debug(`Refresh result: success`),await ki({authResult:i,requestedEngine:n,expectedOrgId:r})}async function Fi(e,t){let{loginUrl:n,waitForLogin:r}=await Di(e);Ei(n,t);let i=await r;return await oi(i.org.id),i}function Ii(e){let t=X(e);if(!t)return!1;let n=t.exp;return typeof n==`number`?n>Math.floor(Date.now()/1e3)+60:!1}function Li(e,t){if(!Ii(e.accessToken))return null;let n=X(e.accessToken);if(!n||!(n.engine===t||n.engine.startsWith(`${t}-edge.`)))return null;let r=ni(e.engineUrl,e.engineDigest);return!r.ok||!$r(n.engine,r.digest)?null:{org:e.org,accessToken:e.accessToken,engineUrl:e.engineUrl,engineDigest:e.engineDigest,engine:n.engine}}async function Ri(e,t){let{currentOrgId:n}=await ii(),r=await Kr(n);if(!n||!r?.refreshToken)return await Fi(e,t);let i=Li(r,e);if(i)return _.debug(`Access token still valid and engine present — skipping refresh`),i;try{return await Pi({requestedEngine:e,refreshToken:r.refreshToken,orgId:n})}catch(r){if(_.error(`Authentication error`),_.debug(`Authentication error details for org ${n}:`,Y(r)),r instanceof O)throw r;return await Fi(e,t)}}function zi(e){let{dashboardUrl:t}=I(),n=Bi();return n?`${t}/studio/open?${new URLSearchParams({organizationId:n,to:e}).toString()}`:t}function Bi(){try{return X(W.getToken())?.org.id??null}catch{return null}}function Vi(e){let{stampEngineVersion:t}=I();return t?(zt.debug(`Stamping data-engine="${t}" for local engine`),Mt(e,t)):e}const Hi={MISSING_API_KEY:"No Format API key found. Add `FORMAT_API_KEY` to your `.env` file or environment variables.",INVALID_API_KEY:"Your Format API key is invalid or revoked. Check `FORMAT_API_KEY` in your `.env` file or environment variables.",VERIFY_SERVICE_ERROR:`Could not verify your API key right now — the verification service is temporarily unavailable. Try again shortly.`},Ui=new Set([`MISSING_API_KEY`,`INVALID_API_KEY`]);function Wi(){return zi(`api-keys`)}function Gi(e){let t=e?.detail;if(!t||typeof t!=`object`)return null;let n=t;return!n.error||typeof n.error!=`object`?null:{code:n.error.code,message:n.error.message}}function Ki(e){let t=Gi(e),n=t?.code?Ui.has(t.code):!1,r=t?.code?Hi[t.code]:void 0;if(n)return`${r??t?.message??Hi.INVALID_API_KEY}\n\nYou can generate a new API key [here](${Wi()}).`;if(r)return r;if(t?.message)return t.message;let i=e?.message;return typeof i==`string`&&i?i:`Something went wrong generating the PDF. Check the server logs.`}function qi(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Ji(e){let t=qi(e,`missing`),n=qi(e,`brokenRemote`),r=[...t,...n];if(r.length===0)return Ki(e);let i=r.map(e=>`- \`${e}\``).join(`
4
- `),a=[];return t.length>0&&a.push("Add the missing files to your `sharedAssetsDir` or the document's assets folder."),n.length>0&&a.push(`Make sure any remote assets are reachable when generating the PDF.`),`Couldn't generate PDF due to the following assets being missing:\n\n${i}\n\n${a.join(` `)}`}function Yi(e){return async(t,n,r)=>{let i=t.url?.match(/^\/api\/download\/([^\/]+)\/([^\/]+)$/);if(!i)return r();if(W.isAuthFailed())return M(n,new j(401,P));let[,a,o]=i,s=t.url??`/api/download/${a}/${o}`,c=t=>{N(e,{path:s,...t})};if(!process.env.FORMAT_API_KEY?.trim())return c({title:`PDF downloads require an API key`,message:`Create an API key [here](${Wi()}) then add as \`FORMAT_API_KEY\` to your \`.env\` file. No restart needed.`}),M(n,new j(400,`Missing API key`));let l=async e=>{let t=e.getReader(),n=[],r=0;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;i&&(n.push(i),r+=i.length)}}finally{t.releaseLock()}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i};try{let{config:e}=await he();if(!e)throw new D(`Could not find Format config file`);let t=I().apiUrl,r=new Rt({baseUrl:t}),{bytes:i,cached:s}=await wr({documentName:a,variant:o,config:e,stampHtml:Vi,generatePdf:async e=>{zt.debug(`Sending PDF request to API with HTML`,e.html);let t=await r.pdf(e.html,e.assets?{assets:e.assets}:void 0);if(!t.isPdf)throw new j(500,`Failed to generate PDF`);if(!t.body)throw new j(500,`No PDF content received`);return l(t.body)}}),c=`${a}-${o}.pdf`;n.statusCode=200,n.setHeader(`Content-Type`,`application/pdf`),n.setHeader(`Content-Disposition`,`attachment; filename="${c}"`),n.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),n.setHeader(`Pragma`,`no-cache`),n.setHeader(`Expires`,`0`),n.setHeader(`Content-Length`,i.length.toString()),n.setHeader(`x-format-studio-cache`,s?`hit`:`miss`),n.end(Buffer.from(i));return}catch(e){console.error(`Download error:`,e),c({title:`PDF generation error`,message:Ji(e)}),n.headersSent?n.end():M(n,e)}}}function Xi(){return async(e,t)=>{try{k({res:t,status:200,data:W.getDiagnostics()})}catch(e){M(t,e)}}}function Zi(e,t,r){let i=n.join(e,`app`,`manifest.json`);if(!d(i))throw new D(`Manifest file not found`);try{let a=JSON.parse(f(i,`utf-8`))[r];if(!a)throw new D(`Entry '${r}' not found in manifest`);return n.join(e,t,a)}catch(e){zt.warn(`Failed to read manifest file:`,e)}}var Qi=`if (import.meta.hot) {
5
- let hasReportedDisconnect = false
6
-
7
- const removeEnginePages = () => {
8
- const existing = document.querySelector('#format-pages')
9
- existing && existing.remove()
10
- }
11
-
12
- const reportAuthFailure = async () => {
13
- try {
14
- await fetch('/api/auth/failed', {
15
- method: 'POST',
16
- headers: {
17
- 'Content-Type': 'application/json'
18
- },
19
- body: JSON.stringify({ reason: 'set_licence_failed' })
20
- })
21
- } catch {
22
- // Best-effort only.
23
- }
24
- }
25
-
26
- const markAuthFailed = (notifyServer = false) => {
27
- removeEnginePages()
28
-
29
- if (window.engine) {
30
- window.engine = null
31
- }
32
-
33
- if (notifyServer) {
34
- reportAuthFailure()
35
- }
36
- }
37
-
38
- const emitAuthError = () => {
39
- window.dispatchEvent(
40
- new CustomEvent('studio:error', {
41
- detail: {
42
- data: {
43
- kind: 'auth',
44
- message: 'Session expired, please log in again.',
45
- title: 'Authentication error',
46
- link: {
47
- href: '/api/auth/login',
48
- label: 'Log in'
49
- }
50
- }
51
- }
52
- })
53
- )
54
- }
55
-
56
- import.meta.hot.on('studio-server-error', data => {
57
- const title = data.title || 'Server error'
58
-
59
- window.dispatchEvent(
60
- new CustomEvent('studio:error', {
61
- detail: { data: { ...data, title } }
62
- })
63
- )
64
- })
65
-
66
- import.meta.hot.on('vite:ws:connect', async () => {
67
- if (!window.engine) {
68
- return
69
- }
70
-
71
- try {
72
- const res = await fetch('/api/engine-token')
73
- const { token } = await res.json()
74
-
75
- if (token) {
76
- window.engine.set_licence(token)
77
- console.log('[format] Token refreshed on WebSocket reconnect')
78
- }
79
- } catch {
80
- // Best-effort — the next scheduled refresh will retry.
81
- }
82
- })
83
-
84
- import.meta.hot.on('vite:ws:disconnect', () => {
85
- if (hasReportedDisconnect) {
86
- return
87
- }
88
-
89
- hasReportedDisconnect = true
90
-
91
- window.dispatchEvent(
92
- new CustomEvent('studio:error', {
93
- detail: {
94
- data: {
95
- kind: 'server-disconnected',
96
- message: 'Format Studio server not connected. Close this tab and restart the server.',
97
- title: 'Server not connected'
98
- }
99
- }
100
- })
101
- )
102
- })
103
-
104
- import.meta.hot.on('hmr', data => {
105
- window.dispatchEvent(new CustomEvent('studio:hmr', { detail: data }))
106
- })
107
-
108
- import.meta.hot.on('pdf-build-status', data => {
109
- window.dispatchEvent(new CustomEvent('studio:pdf-build-status', { detail: data }))
110
- })
111
-
112
- import.meta.hot.on('documents-changed', () => {
113
- window.dispatchEvent(new CustomEvent('studio:documents-changed'))
114
- })
115
-
116
- import.meta.hot.on('token-refresh-failed', data => {
117
- markAuthFailed()
118
- emitAuthError()
119
- })
120
-
121
- import.meta.hot.on('auth-restored', () => {
122
- window.dispatchEvent(new CustomEvent('studio:auth-restored', { detail: { restartEngine: true } }))
123
- })
124
-
125
- import.meta.hot.on('org-linked', data => {
126
- window.dispatchEvent(new CustomEvent('studio:org-linked', { detail: data }))
127
- })
128
-
129
- import.meta.hot.on('org-link-failed', data => {
130
- window.dispatchEvent(new CustomEvent('studio:org-link-failed', { detail: data }))
131
- })
132
-
133
- // The dashboard closed the sign-in because every organisation is already
134
- // linked. Nothing failed, so the app stops waiting without reporting anything.
135
- import.meta.hot.on('org-link-cancelled', data => {
136
- window.dispatchEvent(new CustomEvent('studio:org-link-cancelled', { detail: data }))
137
- })
138
-
139
- import.meta.hot.on('token-refreshed', jwt => {
140
- // Reload organisation metadata even if the engine has not loaded.
141
- window.dispatchEvent(new CustomEvent('studio:token-refreshed'))
142
-
143
- if (!window.engine) {
144
- return
145
- }
146
-
147
- try {
148
- window.engine.set_licence(jwt)
149
- } catch (error) {
150
- console.error('Failed to set licence', error)
151
- markAuthFailed(true)
152
- emitAuthError()
153
- }
154
- })
155
- }
156
- `;function $i(){try{let e=Zi(R,`app`,`index.css`);if(e&&d(o(R,`public`,r(e))))return`/@studio/${r(e)}`}catch{}return`/@studio/index.css`}function ea(e){return`
157
- <!DOCTYPE html>
158
- <html class="html is-loading">
159
- <head>
160
- <meta charset="utf-8" />
161
- <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
162
- <title>Format Studio</title>
163
- <base href="${rn}:${e}/" />
164
- <link rel="stylesheet" href="${$i()}" />
165
- <link rel="icon" type="image/png" href="/@studio/favicon-96x96.png" sizes="96x96" />
166
- <link rel="icon" type="image/svg+xml" href="/@studio/favicon.svg" />
167
- <link rel="shortcut icon" href="/@studio/favicon.ico" />
168
- <link rel="apple-touch-icon" sizes="180x180" href="/@studio/apple-touch-icon.png" />
169
- <meta name="apple-mobile-web-app-title" content="Format Studio" />
170
- <link rel="manifest" href="/@studio/site.webmanifest" />
171
- </head>
172
- <body class="body">
173
- <div id="loader">
174
- <div class="spinner"></div>
175
- </div>
176
- <div id="studio-ui" class="studio-ui"></div>
177
- <div id="user-root" inert></div>
178
-
179
- <script type="module" src="${yn}"><\/script>
180
- <script type="module">${Qi}<\/script>
181
- </body>
182
- </html>
183
- `}function ta(e){return async(t,n,r,i)=>{if(!(t.url===`/`||t.url?.match(/^\/[^/.]+$/)))return r();let a=ea(e),o=await i.transformIndexHtml(`/@studio`,a);n.setHeader(`Content-Type`,`text/html`),n.end(o)}}const na=[...new Set([...Object.values(Ye).flat(),...Object.values(Je)])];async function ra(){try{let e=await Oe(C());return na.filter(t=>e.has(t))}catch{return[]}}function ia(){return async(e,t)=>{try{let e=W.getEngineResolved();k({res:t,status:200,data:{...await ii(),engineVersion:e,enginePath:Tn(e),framework:w.getConfig().framework,projectName:r(C()),webUrl:I().webUrl,installedDependencies:await ra()}})}catch(e){M(t,e)}}}function aa(){return async(e,t,n)=>{if(e.method===`GET`){try{k({res:t,status:200,data:await un()})}catch(e){M(t,e)}return}if(e.method===`PUT`||e.method===`PATCH`){try{let n=await A(e),r={...await un(),...n};await dn(r),k({res:t,status:200,data:r})}catch(e){M(t,e)}return}n?n():k({res:t,status:405,data:{error:`Method not allowed`}})}}function oa(){return{platform:E.platform(),arch:E.arch(),release:E.release(),type:E.type(),hostname:E.hostname(),userInfo:{username:E.userInfo().username,homedir:E.userInfo().homedir}}}function sa(){return async(e,t)=>{try{k({res:t,status:200,data:{os:oa()}})}catch(e){M(t,e)}}}function ca(){return async(e,t)=>{k({res:t,status:200,data:{token:W.getToken()}})}}function la(){return(e,t,n)=>{if(e.url!==`/health`)return n();t.statusCode=200,t.end(`ok`)}}function ua(){return async(e,t)=>{try{k({res:t,status:200,data:(await Gr()).map(e=>({...e.org,email:X(e.accessToken)?.email}))})}catch(e){M(t,e)}}}async function da(e,t,n){let r=c(H,t),i=ri(e,n);if(_.debug(`Engine directory: ${H}`),_.debug(`Engine version directory: ${r}`),$r(t,i))return _.debug(`Engine already downloaded`),r;d(r)&&h(r,{recursive:!0,force:!0}),_.debug(`Downloading engine`);let{data:a,error:s}=await Lt(e,{responseType:`arrayBuffer`});if(s)throw _.error(`Failed to download engine. Are you connected to the internet?`),new D(`Engine download error: ${s}`);if(!a)throw new D(`Engine download error: No data returned`);let l=Buffer.from(a);if(i!==null){let e=Ot(`sha256`).update(l).digest(`hex`);if(e!==i)throw new D(`Engine ${t} failed verification: expected SHA-256 ${i}, downloaded bytes hash to ${e}. Nothing was installed.`)}let u=c(H,`.tmp-${t}-${process.pid}-${Date.now()}`);h(u,{recursive:!0,force:!0});try{new Vt(l).extractAllTo(u,!0);let e=await Bt([`**/__MACOSX`],{cwd:u,onlyDirectories:!0,absolute:!1});for(let t of e)h(o(u,t),{recursive:!0,force:!0});let t=p(u,{withFileTypes:!0}).filter(e=>e.isDirectory());if(t.length!==1)throw new D(`Unexpected engine archive layout: ${t.length} top-level directories`);i!==null&&Qr(o(u,t[0].name),i),h(r,{recursive:!0,force:!0}),m(o(u,t[0].name),r)}finally{h(u,{recursive:!0,force:!0})}for(let e of p(H,{withFileTypes:!0}))e.isDirectory()&&e.name!==t&&!e.name.startsWith(`.`)&&h(o(H,e.name),{recursive:!0,force:!0});return r}var fa=class extends D{constructor(e,t){super(t),this.problem=e,this.name=`ConnectionPreparationError`}};async function pa(e,t,n){let r,i;try{let a=Oi({accessToken:e.accessToken,requestedEngine:t,expectedOrgId:n});r=a.engine,i=a.org}catch(e){throw new fa(`mismatch`,`Format returned credentials that do not match: ${String(e)}`)}if(e.engineUrl)try{await da(e.engineUrl,r,e.engineDigest)}catch(e){throw new fa(`engine`,`The engine could not be downloaded: ${String(e)}`)}return{org:i,accessToken:e.accessToken,requestedEngine:t,engine:r}}async function ma(e){await oi(e.org.id),W.setToken(e.accessToken),W.setEngineVersions({requested:e.requestedEngine,resolved:e.engine})}const ha=`Sign in again to reconnect to this organization. If your access has changed, contact an organization admin.`;function ga(){return async(e,t)=>{try{let{orgId:n}=await A(e);if(!n)throw new j(400,`Select an organization to continue.`);let r=await Kr(n);if(!r?.refreshToken)throw new j(404,ha);let i=W.getEngineRequested(),a;try{a=await Pi({refreshToken:r.refreshToken,requestedEngine:i,orgId:n})}catch(e){throw e instanceof O?new j(503,`Studio couldn't connect to Format. Check your connection and try again.`):new j(401,ha)}let o;try{o=await pa(a,i,n)}catch(e){throw new j(502,e instanceof fa&&e.problem===`engine`?`Studio couldn't download the rendering engine. Try again.`:`Studio couldn't verify this connection. Try again.`)}await ma(o),k({res:t,status:200,data:{success:!0,org:o.org}})}catch(e){M(t,e)}}}let Q=null;function _a(e){return Q===e?(Q=null,!0):!1}function va(){let e=Q;Q=null,e?.controller.abort()}function ya(e){return async(t,n)=>{va();let r={id:kt(),controller:new AbortController};Q=r;try{let t=W.getEngineRequested(),{loginUrl:i,waitForLogin:a}=await Di(t,{timeoutMs:3e5,linkedOrganizationIds:(await Gr()).map(e=>e.org.id),signal:r.controller.signal}),o=!1;a.then(async n=>{if(Q!==r)return;let i=await pa(n,t);_a(r)&&(o=!0,await ma(i),pi(),W.clearAuthFailed(),e.ws.send({type:`custom`,event:`org-linked`,data:i.org}))}).catch(t=>{if(!(!o&&!_a(r))){if(t instanceof bi){_.debug(`Nothing left to link`),e.ws.send({type:`custom`,event:`org-link-cancelled`,data:{attemptId:r.id}});return}_.error(`Link organization failed`,t),e.ws.send({type:`custom`,event:`org-link-failed`,data:{message:xa(t),attemptId:r.id}})}}),k({res:n,status:200,data:{loginUrl:i,attemptId:r.id}})}catch(e){_a(r),M(n,e)}}}function ba(){return async(e,t)=>{try{let{attemptId:n}=await A(e),r=Q!==null&&Q.id===n;r&&va(),k({res:t,status:200,data:{cancelled:r}})}catch(e){M(t,e)}}}function xa(e){return e instanceof Error&&e.message===Ci?Ci:e instanceof fa?`Organization linked, but Studio couldn't finish switching. Your current organization is still active. Try switching again.`:`Failed to link organization. Please try again.`}function Sa(e){return async(t,n,r)=>t.method===`GET`&&t.url===`/api/organizations`?ua()(t,n):t.method===`POST`&&t.url===`/api/organizations/switch`?ga()(t,n):t.method===`POST`&&t.url===`/api/organizations/add`?ya(e)(t,n):t.method===`POST`&&t.url===`/api/organizations/add/cancel`?ba()(t,n):r()}let $=null;async function Ca(e){if($)return $;let t=W.getEngineRequested(),n=(await ii()).currentOrgId;return $=await Di(t),$.waitForLogin.then(async r=>{let i=W.isAuthFailed(),a=await pa(r,t);if(await ma(a),pi(),W.clearAuthFailed(),a.org.id!==n){e.ws.send({type:`custom`,event:`org-linked`,data:a.org});return}e.ws.send({type:`custom`,event:`token-refreshed`,data:a.accessToken}),i&&e.ws.send({type:`custom`,event:`auth-restored`})}).catch(e=>{_.error(`Login flow failed`,e)}).finally(()=>{$=null}),$}function wa(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`GET`||i!==`/api/auth/login`)return r();try{let t=await Ca(e);n.statusCode=302,n.setHeader(`Location`,t.loginUrl),n.end()}catch(e){M(n,e)}}}function Ta(){return async(e,t,n)=>{let r=e.url?.split(`?`)[0];if(e.method!==`POST`||r!==`/api/auth/failed`)return n();try{Number(e.headers[`content-length`]??0)>0&&await A(e),W.setAuthFailed(),k({res:t,status:200,data:{ok:!0}})}catch(e){M(t,e)}}}function Ea(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`POST`||i!==`/api/auth/refresh`)return r();try{let t=W.isAuthFailed(),r=await ji();pi(),W.clearAuthFailed(),e.ws.send({type:`custom`,event:`token-refreshed`,data:r}),t&&e.ws.send({type:`custom`,event:`auth-restored`}),k({res:n,status:200,data:{token:r}})}catch(e){_.error(`On-demand token refresh failed`,e);let t=e instanceof O;k({res:n,status:t?503:401,data:{error:t?an:P}})}}}function Da(e,t){return{name:`format-studio-middleware`,apply:`serve`,configureServer(n){n.middlewares.use(la()),n.middlewares.use(wa(n)),n.middlewares.use(Ta()),n.middlewares.use(Ea(n)),n.middlewares.use(`/@studio/fonts.css`,Fr()),n.middlewares.use(`/@studio/fonts`,Ir()),n.middlewares.use(`/@studio`,Pr()),n.middlewares.use(Ur(n)),n.middlewares.use(`/api/engine-token`,ca()),n.middlewares.use(En(n)),n.middlewares.use(Hr()),n.middlewares.use(`/api/documents`,jn(t)),n.middlewares.use(`/api/documents`,Dn()),n.middlewares.use(Nr(n,t)),n.middlewares.use(`/api/diagnostics`,Xi()),n.middlewares.use(`/api/state`,ia()),n.middlewares.use(`/api/settings`,aa()),n.middlewares.use(`/api/system`,sa()),n.middlewares.use(Sa(n)),n.middlewares.use(Yi(n)),n.middlewares.use((t,r,i)=>ta(e)(t,r,i,n))}}}const Oa={parser:`typescript`},ka=e=>`${`/`.replace(/\/$/,``)}/${e.replace(/^\.?\//,``)}`,Aa=`
184
- export const loadDocumentData = async (documentName, variant = 'default') => {
185
- try {
186
- const baseUrl = window.location.origin
187
- const response = await fetch(\`\${baseUrl}/api/documents/\${documentName}/data/\${variant}\`)
188
-
189
- if (!response.ok) {
190
- throw new Error(\`Failed to load data for \${documentName}/\${variant}\`)
191
- }
192
-
193
- return await response.json()
194
- } catch (error) {
195
- console.error('Failed to load document data:', error)
196
- return {}
197
- }
198
- }
199
- `;function ja(){return`const globs = import.meta.glob("${ka(`*/index.${`{${je.join(`,`).replace(/\./g,``)}}`}`)}");`}function Ma(e){return e.map(e=>{let t=ka(`./${e.name}/index${e.extension}`);return`"${e.name}": () => {
200
- const loader = globs["${t}"];
201
-
202
- if (!loader) {
203
- throw new Error("Component not found for ${t}");
204
- }
205
-
206
- return loader();
207
- }`}).join(`,
208
- `)}async function Na(e){if(e.length===0)throw new D(Ue);let t=`
209
- import React from "react"
210
- import ReactDOM from "react-dom/client"
211
-
212
- ${Aa}
213
-
214
- ${ja()}
215
-
216
- export const components = {
217
- ${Ma(e)}
218
- }
219
- `;return await Ht.format(t,Oa)}async function Pa(e){if(e.length===0)throw new D(Ue);let t=`
220
- import { createApp } from "vue"
221
-
222
- ${Aa}
223
-
224
- ${ja()}
225
-
226
- export const components = {
227
- ${Ma(e)}
228
- }
229
- `;return await Ht.format(t,Oa)}async function Fa(e){if(e.length===0)throw new D(Ue);let t=`
230
- import { Eta } from 'eta'
231
- const eta = new Eta({ varName: 'data' })
232
-
233
- ${Aa}
234
-
235
- ${ja()}
236
-
237
- export const components = {
238
- ${Ma(e)}
239
- }
240
- `;return await Ht.format(t,Oa)}const Ia={react:Na,vue:Pa,html:Fa};async function La(e,t){return await Ia[t.framework](e)}const Ra=`virtual:generate-modules`;function za(){return{name:`user-virtual-module`,apply:`serve`,resolveId(e){if(e===Ra)return e},async load(e){if(e===Ra){let e=w.getConfig();return await La(await ot(e),e)}}}}const Ba=/\.(css|scss|sass|less)(\?inline)?$/i;function Va(){return{name:`auto-inline-css`,enforce:`pre`,resolveId(e,t,n){return n?.ssr||!Ba.test(e)||!t||/\?inline($|&)/.test(e)?null:this.resolve(e+`?inline`,t)}}}function Ha(e,n){let r=t.relative(t.resolve(n),t.resolve(e));return r===``||!r.startsWith(`..`)&&!t.isAbsolute(r)}function Ua(e,t){for(let n of t)if(Ha(e,n))return!0;return!1}async function Wa(e){try{let t=await x(e);return Ot(`sha256`).update(t).digest(`hex`).slice(0,8)}catch{return null}}function Ga(e={}){let n=(e.watchDirs??[]).map(e=>t.resolve(e)),r=e.documentsDir?t.resolve(e.documentsDir):null,i=e.onFileChanged??(()=>{});return{name:`hot-update-notifier`,apply:`serve`,configureServer(e){if(n.length===0&&!r)return;let a=null,o=null,s=async()=>{if(!o)return;let{event:t,file:n}=o;o=null,_.debug(`HMR asset event detected (${t})`,n),e.ws.send({type:`custom`,event:`hmr`,data:{file:n,ts:Date.now(),hash:t===`unlink`||t===`unlinkDir`?null:await Wa(n),event:t}})},c=(e,r)=>{let i=t.resolve(r);Ua(i,n)&&(o={event:e,file:i},a&&clearTimeout(a),a=setTimeout(()=>void s(),75))},l=null,u=()=>{_.debug(`documents change settled, client refreshing documents`),e.ws.send({type:`custom`,event:`documents-changed`,data:{ts:Date.now()}})},d=(e,n)=>{!r||!Ha(t.resolve(n),r)||(_.debug(`documents ${e}: ${n}`),l&&clearTimeout(l),l=setTimeout(u,100))},f=[...n,...r?[r]:[]];for(let t of f)e.watcher.add(t);r&&_.debug(`Watching for document changes in: ${r}`);let p=e=>{i(e),c(`add`,e),d(`add`,e)},m=e=>{i(e),c(`change`,e)},h=e=>{i(e),c(`unlink`,e),d(`unlink`,e)},g=e=>{i(e),c(`addDir`,e),d(`addDir`,e)},ee=e=>{i(e),c(`unlinkDir`,e),d(`unlinkDir`,e)};e.watcher.on(`add`,p),e.watcher.on(`change`,m),e.watcher.on(`unlink`,h),e.watcher.on(`addDir`,g),e.watcher.on(`unlinkDir`,ee),e.httpServer?.once(`close`,()=>{for(let t of f)e.watcher.unwatch(t);a&&clearTimeout(a),l&&clearTimeout(l),e.watcher.off(`add`,p),e.watcher.off(`change`,m),e.watcher.off(`unlink`,h),e.watcher.off(`addDir`,g),e.watcher.off(`unlinkDir`,ee)})},async handleHotUpdate(e){if(i(e.file),n.length>0&&Ua(e.file,n))return[];_.debug(`HMR file update detected`,e.file);let t=await Wa(e.file);return e.server.ws.send({type:`custom`,event:`hmr`,data:{file:e.file,ts:Date.now(),hash:t,modules:e.modules.map(e=>e.url)}}),[]}}}function Ka(){let e=new Set,t=new Map;return function(n={}){let r=[Un()],i={};for(let e of r){if(!u.existsSync(e))continue;let t=Ft(u.readFileSync(e,`utf8`));Object.assign(i,t)}let a=n.keyFilter??(()=>!0),o=new Set(Object.keys(i).filter(a));for(let n of e)if(!o.has(n))if(t.has(n)){let e=t.get(n);e===void 0?delete process.env[n]:process.env[n]=e,t.delete(n)}else delete process.env[n];for(let e of o)t.has(e)||t.set(e,process.env[e]),process.env[e]=i[e];e=o}}const qa=Ka();function Ja(e={}){return qa(e)}function Ya(e){return t=>{let n=c(Un()),r=null,i=t=>{c(t)===n&&(r&&clearTimeout(r),r=setTimeout(()=>{e()},75))};t.watcher.add(n),t.watcher.on(`add`,i),t.watcher.on(`change`,i),t.watcher.on(`unlink`,i),t.httpServer?.once(`close`,()=>{r&&clearTimeout(r),t.watcher.unwatch(n),t.watcher.off(`add`,i),t.watcher.off(`change`,i),t.watcher.off(`unlink`,i)})}}function Xa(e,t){let n=!1,r=null,i=i=>{r&&clearTimeout(r),r=setTimeout(async()=>{if(!n){n=!0;try{_.info(`Config file changed — restarting Format Studio server...`);let{config:n}=await he(e);w.setConfig(n),await t?.(),await i.restart()}catch(e){_.error(`Restart failed.`,e);let t={message:`Failed to restart Format Studio server after config file change.`};e instanceof Error&&e.message&&(t.details=[{message:e.message}]),N(i,t)}finally{n=!1}}},120)};return t=>{let n=n=>{n===e&&(W.consumeConfigRestartSkip()||i(t))};t.watcher.add(e),t.watcher.on(`change`,n),t.watcher.on(`add`,n),t.watcher.on(`unlink`,n),t.httpServer?.once(`close`,()=>{t.watcher.unwatch(e),t.watcher.off(`change`,n),t.watcher.off(`add`,n),t.watcher.off(`unlink`,n)})}}function Za(e,t,n=`pre`){return{name:e,enforce:n,async configResolved(e){for(let n of t.configResolved??[])await n(e)},async configureServer(e){for(let n of t.configureServer??[])await n(e)},async handleHotUpdate(e){for(let n of t.handleHotUpdate??[])await n(e)},async buildStart(){for(let e of t.buildStart??[])await e()},async closeBundle(){for(let e of t.closeBundle??[])await e()}}}function Qa(e,t={}){let{onRestart:n}=t,r=()=>{Ja(),_e(ge())};return Za(`format:hooks`,{configResolved:[r],configureServer:[r,Ya(r),Xa(e,n)]})}function $a(e=process.env.FMT_ENGINE_VERSION){return e?.trim()||`0.1.0`}const eo={FMT_ENV:`the FMT_ENV variable`,settings:`saved settings`,default:`the default`},to=e=>eo[e],no=e=>e.port?Number(e.port):process.env.PORT?Number(process.env.PORT):1234;async function ro(t){let{config:n,filepath:r}=await he();w.setConfig(n);let i=Un();Ja(),d(i)||_.debug(`No .env file found at startup: ${i}`),_e(ge()),hn({settings:await un()});let{environment:a,source:o}=gn();_.info(`Environment: ${a.name} (from ${to(o)})`);let s=no(t),l=C();_.info(`Loading Format Studio...`),_.debug(`Format dev options`,t),_.debug(`CWD: ${l}`),_.debug(`User config: ${JSON.stringify(n)}`),_.debug(`Log level: ${pe()}`),_.debug(`Checking dependency versions`);try{qt(l)}catch(e){_.error(e.message),process.exit(1)}let u=await Kt(l);if(u.pinnedVersion||(_.error('No "version" field found in your Format config. Run `format update latest` to pin a release.'),process.exit()),u.mismatches.length>0){_.error(`Some installed Format packages do not match the pinned version (${u.pinnedVersion}):`);for(let e of u.mismatches)_.error(` ${e.name} ${e.actual} (expected ${e.expected})`);_.error("Run `format update` to bring everything in line."),process.exit()}let f=$a();_.debug(`Engine requested: ${f}`);try{_.debug(`Authenticating`);let e=await Ri(f,t);if(!e)throw new D(`Failed to authenticate`);let{accessToken:n,engineUrl:r,engineDigest:i,engine:a}=e;if(!n)throw new D(`Access token missing from credentials`);if(!r)throw new D(`Engine URL missing from access token`);W.setToken(n),W.setEngineVersions({requested:f,resolved:a}),await da(r,a,i)}catch(e){_.error(`Failed to start Format Studio`),e instanceof O&&(_.error(an),process.exit()),_.error(`Error: ${e.message}`),process.exit()}let p=(0,L.getSharedAssetsDir)(n),{isDirectory:m}=await de(p),h=m;!m&&n.sharedAssetsDir&&_.error(`Shared assets directory (sharedAssetsDir) not found or is not a directory: ${n.sharedAssetsDir} (${p})`);let{baseViteConfig:g,frameworkPlugins:ie,stylePlugins:ae}=Wt(),oe=new Jt({log:e=>_.debug(e),warn:e=>_.warn(e),allowedReadPaths:[l],sandbox:`standard`}),se=[()=>void oe.dispose(),Ar];process.once(`exit`,()=>{for(let e of se)e()});let ce=()=>process.exit();process.once(`SIGINT`,ce),process.once(`SIGTERM`,ce);let le=await te(ne(g,{clearScreen:!1,configFile:!1,server:{port:s,strictPort:!0,watch:{ignored:Me,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}},plugins:[Ga({watchDirs:[i,...h?[p]:[]],documentsDir:(0,L.getDocumentsDir)(n),onFileChanged:e=>Er(e,n)}),Qa(r),Ut(!1),Va(),za(),Da(s,oe),...ie,...ae],optimizeDeps:{entries:!1,exclude:[`dist/app`]},define:{DEFAULT_VARIANT:JSON.stringify(Re),VARIANT_PARAM:JSON.stringify(We)},build:{rollupOptions:{input:{}}},cacheDir:c(wn(),`vite-cache`),resolve:{dedupe:[`react`,`react-dom`],alias:{[yn]:Zi(R,`app`,`index.js`)},mainFields:[]}}));hr(e=>{le.ws.send({type:`custom`,event:`pdf-build-status`,data:e})}),await oe.initDev({root:l,framework:n.framework,configJson:JSON.stringify(n),decodeStyleEntities:Gt({framework:n.framework})});try{await le.listen()}catch(e){if(!/already in use/i.test(e.message))throw e;_.error(on(s)),process.exit(1)}se.push(Mi({server:le})),pe()!==e.DEBUG&&_.clear();let ue=`${rn}:${s}`;t.open&&await re(ue);let fe=[`FORMAT STUDIO`,`————————————————————————`,ue,`————————————————————————`,`Build something amazing.`],v=Math.max(...fe.map(e=>e.length))+8,ve=`═`.repeat(v+2);if(console.log(ee(`╔${ve}╗`)),fe.forEach(e=>{let t=e.padStart((v+e.length)/2).padEnd(v);console.log(ee(`║ ${t} ║`))}),console.log(ee(`╚${ve}╝`)),pe()!==e.DEBUG)for(let e of me(n))_.warn(e)}export{wn as n,ro as t};