velloo 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -40
- package/canvas/assets/index-ClaBqcaS.js +28 -0
- package/canvas/assets/lucide-all-iIF-pmzN.js +1 -0
- package/canvas/index.html +1 -1
- package/{chunk-k6ferbam.js → chunk-08sv3k41.js} +1 -1
- package/{chunk-74skmg76.js → chunk-0fe83yzt.js} +1 -1
- package/{chunk-n5007jcz.js → chunk-1h55s5he.js} +1 -1
- package/{chunk-5js0qw32.js → chunk-2c7jbx46.js} +1 -1
- package/chunk-308ynsxd.js +2 -0
- package/{chunk-w5rzk6ms.js → chunk-3e8vez4d.js} +2 -2
- package/{chunk-bk8b7f9a.js → chunk-40xgcth8.js} +4 -3
- package/chunk-4dn75m6t.js +3 -0
- package/chunk-4fj5tahv.js +3 -0
- package/chunk-6nqghjda.js +3 -0
- package/chunk-6w6ch4ce.js +2 -0
- package/chunk-735ezz23.js +86 -0
- package/chunk-7eq7nx37.js +7 -0
- package/chunk-7eyb8yrf.js +6 -0
- package/{chunk-8ssr8a8w.js → chunk-80fjfyha.js} +3 -6
- package/{chunk-b7j86xq7.js → chunk-80r93t2e.js} +1 -1
- package/chunk-94vx1yb0.js +3 -0
- package/{chunk-g02nd9hn.js → chunk-a84n72m2.js} +1 -1
- package/chunk-ampmdzz4.js +10 -0
- package/chunk-avns4dbf.js +2 -0
- package/{chunk-kxk5x7g6.js → chunk-ayrb3qnm.js} +1 -1
- package/{chunk-fgw3hp2v.js → chunk-bwnvcncx.js} +1 -1
- package/chunk-ccszg02q.js +5 -0
- package/{chunk-jnsfgtn9.js → chunk-cvn689d5.js} +1 -1
- package/{chunk-65wb0g7d.js → chunk-dg6z4vdd.js} +1 -1
- package/chunk-dgwjpbp9.js +3 -0
- package/{chunk-hs2j6s1v.js → chunk-dy41n60j.js} +8 -31
- package/{chunk-e2ag33vd.js → chunk-ek71z2fv.js} +2 -2
- package/{chunk-h0c36khx.js → chunk-er1fxb7d.js} +1 -1
- package/{chunk-xr6f94rj.js → chunk-eyr8hrzf.js} +1 -1
- package/{chunk-56vqqr8s.js → chunk-fsbsksga.js} +1 -1
- package/{chunk-t2ttkxe9.js → chunk-hcb68zt7.js} +1 -1
- package/chunk-j11fyeqh.js +2 -0
- package/{chunk-d385435m.js → chunk-jb21jkp1.js} +1 -1
- package/{chunk-7e39xe21.js → chunk-jfx9xjmr.js} +1 -1
- package/{chunk-b2ebm1t3.js → chunk-jr0ss0mm.js} +1 -1
- package/chunk-jv0xggh0.js +2 -0
- package/chunk-k17gfwq3.js +2 -0
- package/chunk-mh2pr7cq.js +5 -0
- package/chunk-mnapdp1y.js +2 -0
- package/chunk-n9gs6yx9.js +2 -0
- package/chunk-ngnymg2q.js +3 -0
- package/{chunk-79ykzywe.js → chunk-pjtg3wnm.js} +1 -1
- package/{chunk-2z0k59hz.js → chunk-pp86v6m6.js} +1 -1
- package/chunk-r22epxz2.js +3 -0
- package/chunk-rgasy862.js +5 -0
- package/{chunk-7p7ha0qk.js → chunk-rpwpeph5.js} +1 -1
- package/{chunk-k784090q.js → chunk-sjgqnykd.js} +1 -1
- package/chunk-sn3x2m0m.js +6 -0
- package/{chunk-mq4znqv2.js → chunk-t448rrfr.js} +1 -1
- package/{chunk-329e3phg.js → chunk-tdsk5wxa.js} +25 -25
- package/{chunk-2vx420g2.js → chunk-v40fn08f.js} +1 -1
- package/chunk-vdkrbzh1.js +2 -0
- package/{chunk-1gx45384.js → chunk-vgmr98cv.js} +7 -8
- package/chunk-vsv8z729.js +6 -0
- package/chunk-x4f4k9pp.js +26 -0
- package/{chunk-cep3ktr3.js → chunk-xt5ayg7g.js} +1 -1
- package/{chunk-rksq3w72.js → chunk-ydhwv29b.js} +1 -1
- package/chunk-zb6hc1y0.js +2 -0
- package/cli.js +1 -1
- package/launcher.cjs +1 -1
- package/package.json +3 -3
- package/pkgs/schema/src/config.ts +8 -1
- package/pkgs/schema/src/index.ts +8 -0
- package/pkgs/schema/src/migrate.ts +57 -4
- package/pkgs/schema/src/repo.ts +98 -16
- package/pkgs/schema/src/svg-sanitize.ts +472 -59
- package/skills/velloo-setup/SKILL.md +1 -1
- package/canvas/assets/index-BcBJ11d2.js +0 -28
- package/canvas/assets/lucide-all-BdEyryfF.js +0 -1
- package/chunk-1bywxgc5.js +0 -4
- package/chunk-1y50g9vp.js +0 -2
- package/chunk-1yhc252b.js +0 -3
- package/chunk-2mv65qxs.js +0 -5
- package/chunk-40657ggd.js +0 -10
- package/chunk-582y60bv.js +0 -2
- package/chunk-5x173xay.js +0 -2
- package/chunk-75wbh438.js +0 -2
- package/chunk-7dggmqwq.js +0 -53
- package/chunk-946pcnt5.js +0 -5
- package/chunk-aapybh30.js +0 -6
- package/chunk-bjnhhsak.js +0 -2
- package/chunk-dt03awr1.js +0 -2
- package/chunk-erwfk47h.js +0 -3
- package/chunk-nfr3q7mg.js +0 -5
- package/chunk-nsqs1bqf.js +0 -2
- package/chunk-pphgrsxa.js +0 -2
- package/chunk-qpvj6kzq.js +0 -6
- package/chunk-qwv7xkms.js +0 -2
- package/chunk-tmtzxcs5.js +0 -2
- package/chunk-y0zxzefg.js +0 -5
- package/chunk-zf3xc1wz.js +0 -2
package/canvas/index.html
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
<link rel="manifest" href="/site.webmanifest" />
|
|
10
10
|
<meta name="theme-color" content="#0d0c0a" />
|
|
11
11
|
<title>velloo</title>
|
|
12
|
-
<script type="module" crossorigin src="/assets/index-
|
|
12
|
+
<script type="module" crossorigin src="/assets/index-ClaBqcaS.js"></script>
|
|
13
13
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
14
14
|
<link rel="modulepreload" crossorigin href="/assets/react-D0Ec-185.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="/assets/vendor-CKmQ-Zst.js">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCancel,confirm}from"./chunk-
|
|
2
|
+
import{isCancel,confirm}from"./chunk-80fjfyha.js";import{CHROMIUM_INSTALL_ARGV,CHROMIUM_INSTALL_CMD,CHROMIUM_DEPS_INSTALL_ARGV,CHROMIUM_DEPS_INSTALL_CMD,BrowserMissingError}from"./chunk-3e8vez4d.js";import{fail}from"./chunk-s23gtejf.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM}from"./chunk-2smsg2ct.js";var import_picocolors=__toESM(require_picocolors(),1);var BROWSER_PROMPT_DETAIL=import_picocolors.default.dim("Headless Chromium \u2014 powers the agent's screenshot tool, velloo render --to=png, and PNG/PDF export. The canvas itself never needs it."),BROWSER_PROMPT_SIZE="(~110MB, one-time)";async function runChromiumInstall(){let proc=Bun.spawn([...CHROMIUM_INSTALL_ARGV],{stdout:"pipe",stderr:"pipe",stdin:"inherit"}),captured="",pump=async(stream,out)=>{let decoder=new TextDecoder;for await(let chunk of stream)out.write(chunk),captured+=decoder.decode(chunk,{stream:!0})},[,,code]=await Promise.all([pump(proc.stdout,process.stdout),pump(proc.stderr,process.stderr),proc.exited]),missingSystemLibs=/missing dependencies to run browsers|Missing libraries:/i.test(captured);return{ok:code===0&&!missingSystemLibs,missingSystemLibs}}async function installChromiumInteractive(){let result=await runChromiumInstall();if(result.ok)return!0;if(!result.missingSystemLibs)return!1;console.log(""),console.log(` ${import_picocolors.default.yellow("\u26A0")} Browser downloaded, but your system is missing libraries it needs to run.`);let proceed=await confirm({message:`Install the missing system libraries now? ${import_picocolors.default.dim(`(${CHROMIUM_DEPS_INSTALL_CMD} \u2014 uses your distro's package manager, needs root/sudo)`)}`,initialValue:!0});if(isCancel(proceed)||!proceed)return console.log(import_picocolors.default.dim(` Install them later with: ${import_picocolors.default.cyan(CHROMIUM_DEPS_INSTALL_CMD)}`)),!1;if(await Bun.spawn([...CHROMIUM_DEPS_INSTALL_ARGV],{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited!==0)return console.log(import_picocolors.default.dim(` That didn't finish \u2014 run it manually: ${import_picocolors.default.cyan(`sudo ${CHROMIUM_DEPS_INSTALL_CMD}`)}`)),!1;return!0}async function captureWithBrowserSetup(cmd,capture){try{await capture();return}catch(e){if(!(e instanceof BrowserMissingError))throw e;if(!process.stdin.isTTY)fail(cmd,e.message);let proceed=await confirm({message:`Chromium isn't installed \u2014 \`${CHROMIUM_INSTALL_CMD}\` now? ${BROWSER_PROMPT_SIZE}
|
|
3
3
|
${BROWSER_PROMPT_DETAIL}`,initialValue:!0});if(isCancel(proceed)||!proceed)fail(cmd,e.message);if(!await installChromiumInteractive())fail(cmd,"the browser isn't usable yet \u2014 see the output above.")}await capture()}
|
|
4
4
|
export{BROWSER_PROMPT_DETAIL,BROWSER_PROMPT_SIZE,installChromiumInteractive,captureWithBrowserSetup};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-
|
|
2
|
+
import"./chunk-t448rrfr.js";import"./chunk-40xgcth8.js";import{normalizeCloudUrl,loadCredential,deleteCredential,clearCredentials}from"./chunk-80r93t2e.js";import{defaultCloudUrl}from"./chunk-pp86v6m6.js";import{defineCommand}from"./chunk-2smsg2ct.js";var logout_default=defineCommand({meta:{name:"logout",description:"Log out of velloo-cloud (removes the saved CLI token)"},args:{url:{type:"string",description:"velloo-cloud base URL (default: $VELLOO_CLOUD_URL or the built-in default)"},all:{type:"boolean",default:!1,description:"Remove saved credentials for every cloud"}},async run({args}){if(args.all){let count=await clearCredentials();console.log(count>0?`velloo logout: removed credentials for ${count} cloud${count===1?"":"s"}`:"velloo logout: no saved credentials");return}let cloudUrl=args.url?normalizeCloudUrl(args.url):defaultCloudUrl(),existing=await loadCredential(cloudUrl);if(await deleteCredential(cloudUrl))console.log(`velloo logout: logged out of ${cloudUrl}${existing?.email?` (${existing.email})`:""}`);else console.log(`velloo logout: not logged in to ${cloudUrl}`)}});export{logout_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-bk8b7f9a.js";import{signInRequired,boardLimitReached,topUpTokens,createServer}from"./chunk-329e3phg.js";import{boardLimitFrom,describeCloudError}from"./chunk-mq4znqv2.js";import"./chunk-w5rzk6ms.js";import{loadCredential,saveCredential,deleteCredential}from"./chunk-b7j86xq7.js";import{listPublishedDesigns,unpublishDesign,listPublishDestinations,describePublishError,PUBLISH_VIEWPORT,gitContext,listTeams,publishDesign}from"./chunk-946pcnt5.js";import{TOOL_VERSION}from"./chunk-65wb0g7d.js";import{updateStatus,upgradeInstalledVelloo}from"./chunk-cep3ktr3.js";import{assertLoopbackHost,daemonRoot,writeLock,removeLock,readRememberedPort,rememberPort,portCandidates,registryUpsert,registryRemove}from"./chunk-k784090q.js";import{fetchAccount,performDeviceLogin}from"./chunk-fgw3hp2v.js";import{defaultCloudUrl,fetchCloudAppUrl}from"./chunk-2z0k59hz.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{existsSync as existsSync2}from"fs";import{existsSync}from"fs";import{dirname,join}from"path";import{fileURLToPath}from"url";var here=dirname(fileURLToPath(import.meta.url));function resolveCanvasDist(){let devLayout=join(here,"..","dist");return[process.env.VELLOO_CANVAS_DIST,join(here,"canvas"),devLayout].filter((p)=>Boolean(p)).find((p)=>existsSync(join(p,"index.html")))??devLayout}var canvasDistPath=resolveCanvasDist();var ACCOUNT_TTL_MS=60000,ACCOUNT_TIMEOUT_MS=5000;function createCanvasAuth(cloudUrl,dependencies={}){let runDeviceLogin=dependencies.performDeviceLogin??performDeviceLogin,login={state:"idle"},pending=null,cached=null,cachedApp=null,describe=async(token,email)=>{if(cached&&cached.token===token&&Date.now()-cached.at<ACCOUNT_TTL_MS)return{account:cached.account,verified:cached.verified};let found=await fetchAccount(cloudUrl,token,ACCOUNT_TIMEOUT_MS),resolved=found.status==="ok"?{account:found.account,verified:!0}:{account:{email},verified:found.status==="rejected"?!1:null};return cached={token,at:Date.now(),...resolved},resolved},resolveAppUrl=async()=>{if(cachedApp&&Date.now()-cachedApp.at<ACCOUNT_TTL_MS)return cachedApp.url;let url=await fetchCloudAppUrl(cloudUrl,ACCOUNT_TIMEOUT_MS);return cachedApp={at:Date.now(),url},url},status=async()=>{let cred=await loadCredential(cloudUrl),appUrlP=resolveAppUrl();if(!cred?.token)return{loggedIn:!1,cloudUrl,appUrl:await appUrlP,verified:null,login};let[{account,verified},appUrl]=await Promise.all([describe(cred.token,cred.email),appUrlP]);return{loggedIn:!0,cloudUrl,appUrl,verified,login,...account?{account}:{}}};return{status,async beginLogin(){if(login.state==="pending")return status();let attempt=new AbortController;pending=attempt,login={state:"idle"};let settle=()=>{},ready=new Promise((resolve)=>{settle=resolve});return runDeviceLogin(cloudUrl,({verificationUrl,userCode,expiresIn})=>{login={state:"pending",userCode,verificationUrl,expiresAt:new Date(Date.now()+expiresIn*1000).toISOString()},settle()},attempt.signal).then(async(result)=>{await saveCredential(cloudUrl,result),cached=null,login={state:"idle"},await topUpTokens({url:cloudUrl,token:result.token},10).catch(()=>{return})}).catch((err)=>{login=attempt.signal.aborted?{state:"idle"}:{state:"error",message:err instanceof Error?err.message:String(err)}}).finally(()=>{if(pending===attempt)pending=null;settle()}),await ready,status()},async cancelLogin(){pending?.abort(),pending=null,login={state:"idle"}},async logout(){pending?.abort(),pending=null,login={state:"idle"},cached=null,await deleteCredential(cloudUrl)}}}function createCanvasPublish(cloudUrl,auth){let tokenFor=async()=>(await loadCredential(cloudUrl))?.token,access=async()=>{if(!await tokenFor())return{state:"signed-out"};return(await auth.status().catch(()=>null))?.verified===!1?{state:"expired"}:{state:"ready"}},rejection=(error)=>error.kind==="LoggedOut"?signInRequired("expired",describeCloudError(error)):Error(describeCloudError(error)),publishedAt=(value)=>{let parsed=value?Date.parse(value):Number.NaN;return Number.isFinite(parsed)?parsed:Number.NEGATIVE_INFINITY};return{access,async teams(){let token=await tokenFor();if(!token)return[];let listed=await listTeams(cloudUrl,token);return listed.ok?listed.value:[]},async published(){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let listed=await listPublishedDesigns({baseUrl:cloudUrl,token});if(!listed.ok)throw rejection(listed.error);return listed.value.map((design)=>({slug:design.slug,title:design.title??"",url:design.url,visibility:design.visibility,passwordProtected:design.passwordProtected,canManage:design.canManage,lastPublishedAt:design.lastPublishedAt})).sort((left,right)=>publishedAt(right.lastPublishedAt)-publishedAt(left.lastPublishedAt))},async unpublish(slug){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let removed=await unpublishDesign({baseUrl:cloudUrl,token,slug});if(!removed.ok)throw rejection(removed.error)},async destinations(host){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let provenance=gitContext(host.folder.root),folderId=host.folder.config.folderId;if(!folderId){let teams=await listTeams(cloudUrl,token);if(!teams.ok)throw rejection(teams.error);return{effectiveTeamId:teams.value.find((team)=>team.isDefault)?.id??null,provenance,slots:[]}}let listed=await listPublishDestinations({baseUrl:cloudUrl,token,folderId});if(!listed.ok)throw rejection(listed.error);return{...listed.value,provenance}},async run(host,request,onProgress,onWarning){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud \u2014 sign in from the account menu first.");let step="start",message="starting",published=await publishDesign({baseUrl:cloudUrl,token},{folder:host.folder,providers:host.providers,defaultProvider:host.defaultProvider,snapshotCss:host.snapshotCss},{boardIds:request.boardIds,...request.title?{title:request.title}:{},visibility:request.visibility,...request.password?{password:request.password}:{},destination:request.destination,...request.teamId?{teamId:request.teamId}:{},provenance:gitContext(host.folder.root),viewport:PUBLISH_VIEWPORT},(event)=>{if(event.kind==="warn"){onWarning(event.message);return}if(event.kind==="note"){onWarning(event.message);return}if(event.kind==="info")return;if(event.kind==="capture"){onProgress({step,message,capture:{done:event.done,total:event.total}});return}step=event.step,message=event.message,onProgress({step,message})});if(!published.ok){let reason=describePublishError(published.error);if(published.error.kind==="LoggedOut")throw signInRequired("expired",reason);let limit=published.error.kind==="HttpFailure"?boardLimitFrom(published.error):null;if(limit)throw boardLimitReached(limit,reason);throw Error(reason)}let outcome=published.value;return{shareUrl:outcome.shareUrl,visibility:outcome.visibility,passwordProtected:outcome.passwordProtected,files:outcome.files,bytes:outcome.bytes,screenshots:outcome.screenshots,boards:outcome.boards,screens:outcome.screens,created:outcome.created,...outcome.tier!==void 0?{tier:outcome.tier}:{},...outcome.history!==void 0?{history:outcome.history}:{}}}}}function createCanvasUpdates(){return{async status(opts={}){let status=await updateStatus(opts);return{current:status.current,latest:status.latest,available:status.available,method:status.method,channel:status.channel,upgradable:status.upgradable,...status.reason===void 0?{}:{reason:status.reason}}},async upgrade(){let outcome=await upgradeInstalledVelloo();return{upgraded:outcome.upgraded,from:outcome.from,to:outcome.to,restartRequired:outcome.upgraded}}}}var IDLE_MS=300000;function portFree(port,host){try{return Bun.serve({port,hostname:host,fetch:()=>new Response("")}).stop(!0),!0}catch{return!1}}var daemon_default=defineCommand({meta:{name:"__daemon",hidden:!0,description:"(internal) Run the persistent canvas daemon. Spawned by `velloo run` / `velloo mcp`."},args:{folder:{type:"positional",required:!0,description:"Design folder (absolute)"},port:{type:"string",description:"Preferred canvas port"},host:{type:"string",description:"Bind hostname (default 127.0.0.1)"}},async run({args}){let root=daemonRoot(args.folder),host=args.host??"127.0.0.1";assertLoopbackHost(host);let cloudUrl=defaultCloudUrl(),cred=await loadCredential(cloudUrl),cloud={url:cloudUrl,token:cred?.token,resolveToken:async()=>(await loadCredential(cloudUrl))?.token},auth=createCanvasAuth(cloudUrl),publish=createCanvasPublish(cloudUrl,auth),updates=createCanvasUpdates(),canvasPort=portCandidates({explicit:args.port?Number(args.port):void 0,remembered:await readRememberedPort(root),root}).find((port)=>portFree(port,host))??0,handle;try{handle=await createServer({folder:root,port:canvasPort,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}catch(err){if(canvasPort===0)throw err;handle=await createServer({folder:root,port:0,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}let rec={root,pid:process.pid,canvasUrl:handle.url,canvasPort:handle.port,mcpUrl:handle.mcpUrl??"",mcpPort:handle.mcpPort??0,cloudUrl,version:TOOL_VERSION,startedAt:new Date().toISOString()};await writeLock(rec),await registryUpsert(rec),await rememberPort(root,handle.port).catch(()=>{return}),console.error(`velloo: canvas daemon up at ${handle.url} (mcp ${handle.mcpUrl}), pid ${process.pid}`);let stopped=!1,shutdown=async()=>{if(stopped)return;stopped=!0,removeLock(root),await registryRemove(root).catch(()=>{return}),await handle.close(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown);let rootMissing=0;setInterval(()=>{if(existsSync2(root)){rootMissing=0;return}if(rootMissing+=1,rootMissing>=2)console.error(`velloo: design folder ${root} is gone \u2014 shutting down.`),shutdown()},1e4);let idleSince=Date.now();setInterval(()=>{let{canvas,mcp}=handle.connections();if(canvas+mcp>0){idleSince=null;return}if(idleSince===null){idleSince=Date.now();return}if(Date.now()-idleSince>=IDLE_MS)console.error("velloo: canvas idle for 5 min \u2014 shutting down."),shutdown()},30000),await new Promise(()=>{})}});export{daemon_default as default};
|
|
2
|
+
import"./chunk-40xgcth8.js";import{signInRequired,boardLimitReached,topUpTokens,createServer}from"./chunk-tdsk5wxa.js";import{boardLimitFrom,describeCloudError}from"./chunk-t448rrfr.js";import"./chunk-3e8vez4d.js";import{loadCredential,saveCredential,deleteCredential}from"./chunk-80r93t2e.js";import{listPublishedDesigns,unpublishDesign,listPublishDestinations,describePublishError,PUBLISH_VIEWPORT,gitContext,listTeams,publishDesign}from"./chunk-rgasy862.js";import{TOOL_VERSION}from"./chunk-dg6z4vdd.js";import{updateStatus,upgradeInstalledVelloo}from"./chunk-xt5ayg7g.js";import{assertLoopbackHost,daemonRoot,writeLock,removeLock,readRememberedPort,rememberPort,portCandidates,registryUpsert,registryRemove}from"./chunk-sjgqnykd.js";import{fetchAccount,performDeviceLogin}from"./chunk-bwnvcncx.js";import{defaultCloudUrl,fetchCloudAppUrl}from"./chunk-pp86v6m6.js";import{defineCommand}from"./chunk-2smsg2ct.js";import{existsSync as existsSync2}from"fs";import{existsSync}from"fs";import{dirname,join}from"path";import{fileURLToPath}from"url";var here=dirname(fileURLToPath(import.meta.url));function resolveCanvasDist(){let devLayout=join(here,"..","dist");return[process.env.VELLOO_CANVAS_DIST,join(here,"canvas"),devLayout].filter((p)=>Boolean(p)).find((p)=>existsSync(join(p,"index.html")))??devLayout}var canvasDistPath=resolveCanvasDist();var ACCOUNT_TTL_MS=60000,ACCOUNT_TIMEOUT_MS=5000;function createCanvasAuth(cloudUrl,dependencies={}){let runDeviceLogin=dependencies.performDeviceLogin??performDeviceLogin,login={state:"idle"},pending=null,cached=null,cachedApp=null,describe=async(token,email)=>{if(cached&&cached.token===token&&Date.now()-cached.at<ACCOUNT_TTL_MS)return{account:cached.account,verified:cached.verified};let found=await fetchAccount(cloudUrl,token,ACCOUNT_TIMEOUT_MS),resolved=found.status==="ok"?{account:found.account,verified:!0}:{account:{email},verified:found.status==="rejected"?!1:null};return cached={token,at:Date.now(),...resolved},resolved},resolveAppUrl=async()=>{if(cachedApp&&Date.now()-cachedApp.at<ACCOUNT_TTL_MS)return cachedApp.url;let url=await fetchCloudAppUrl(cloudUrl,ACCOUNT_TIMEOUT_MS);return cachedApp={at:Date.now(),url},url},status=async()=>{let cred=await loadCredential(cloudUrl),appUrlP=resolveAppUrl();if(!cred?.token)return{loggedIn:!1,cloudUrl,appUrl:await appUrlP,verified:null,login};let[{account,verified},appUrl]=await Promise.all([describe(cred.token,cred.email),appUrlP]);return{loggedIn:!0,cloudUrl,appUrl,verified,login,...account?{account}:{}}};return{status,async beginLogin(){if(login.state==="pending")return status();let attempt=new AbortController;pending=attempt,login={state:"idle"};let settle=()=>{},ready=new Promise((resolve)=>{settle=resolve});return runDeviceLogin(cloudUrl,({verificationUrl,userCode,expiresIn})=>{login={state:"pending",userCode,verificationUrl,expiresAt:new Date(Date.now()+expiresIn*1000).toISOString()},settle()},attempt.signal).then(async(result)=>{await saveCredential(cloudUrl,result),cached=null,login={state:"idle"},await topUpTokens({url:cloudUrl,token:result.token},10).catch(()=>{return})}).catch((err)=>{login=attempt.signal.aborted?{state:"idle"}:{state:"error",message:err instanceof Error?err.message:String(err)}}).finally(()=>{if(pending===attempt)pending=null;settle()}),await ready,status()},async cancelLogin(){pending?.abort(),pending=null,login={state:"idle"}},async logout(){pending?.abort(),pending=null,login={state:"idle"},cached=null,await deleteCredential(cloudUrl)}}}function createCanvasPublish(cloudUrl,auth){let tokenFor=async()=>(await loadCredential(cloudUrl))?.token,access=async()=>{if(!await tokenFor())return{state:"signed-out"};return(await auth.status().catch(()=>null))?.verified===!1?{state:"expired"}:{state:"ready"}},rejection=(error)=>error.kind==="LoggedOut"?signInRequired("expired",describeCloudError(error)):Error(describeCloudError(error)),publishedAt=(value)=>{let parsed=value?Date.parse(value):Number.NaN;return Number.isFinite(parsed)?parsed:Number.NEGATIVE_INFINITY};return{access,async teams(){let token=await tokenFor();if(!token)return[];let listed=await listTeams(cloudUrl,token);return listed.ok?listed.value:[]},async published(){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let listed=await listPublishedDesigns({baseUrl:cloudUrl,token});if(!listed.ok)throw rejection(listed.error);return listed.value.map((design)=>({slug:design.slug,title:design.title??"",url:design.url,visibility:design.visibility,passwordProtected:design.passwordProtected,canManage:design.canManage,lastPublishedAt:design.lastPublishedAt})).sort((left,right)=>publishedAt(right.lastPublishedAt)-publishedAt(left.lastPublishedAt))},async unpublish(slug){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let removed=await unpublishDesign({baseUrl:cloudUrl,token,slug});if(!removed.ok)throw rejection(removed.error)},async destinations(host){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud");let provenance=gitContext(host.folder.root),folderId=host.folder.config.folderId;if(!folderId){let teams=await listTeams(cloudUrl,token);if(!teams.ok)throw rejection(teams.error);return{effectiveTeamId:teams.value.find((team)=>team.isDefault)?.id??null,provenance,slots:[]}}let listed=await listPublishDestinations({baseUrl:cloudUrl,token,folderId});if(!listed.ok)throw rejection(listed.error);return{...listed.value,provenance}},async run(host,request,onProgress,onWarning){let token=await tokenFor();if(!token)throw signInRequired("signed-out","not signed in to velloo-cloud \u2014 sign in from the account menu first.");let step="start",message="starting",published=await publishDesign({baseUrl:cloudUrl,token},{folder:host.folder,providers:host.providers,defaultProvider:host.defaultProvider,snapshotCss:host.snapshotCss},{boardIds:request.boardIds,...request.title?{title:request.title}:{},visibility:request.visibility,...request.password?{password:request.password}:{},destination:request.destination,...request.teamId?{teamId:request.teamId}:{},provenance:gitContext(host.folder.root),viewport:PUBLISH_VIEWPORT},(event)=>{if(event.kind==="warn"){onWarning(event.message);return}if(event.kind==="note"){onWarning(event.message);return}if(event.kind==="info")return;if(event.kind==="capture"){onProgress({step,message,capture:{done:event.done,total:event.total}});return}step=event.step,message=event.message,onProgress({step,message})});if(!published.ok){let reason=describePublishError(published.error);if(published.error.kind==="LoggedOut")throw signInRequired("expired",reason);let limit=published.error.kind==="HttpFailure"?boardLimitFrom(published.error):null;if(limit)throw boardLimitReached(limit,reason);throw Error(reason)}let outcome=published.value;return{shareUrl:outcome.shareUrl,visibility:outcome.visibility,passwordProtected:outcome.passwordProtected,files:outcome.files,bytes:outcome.bytes,screenshots:outcome.screenshots,boards:outcome.boards,screens:outcome.screens,created:outcome.created,...outcome.tier!==void 0?{tier:outcome.tier}:{},...outcome.history!==void 0?{history:outcome.history}:{}}}}}function createCanvasUpdates(){return{async status(opts={}){let status=await updateStatus(opts);return{current:status.current,latest:status.latest,available:status.available,method:status.method,channel:status.channel,upgradable:status.upgradable,...status.reason===void 0?{}:{reason:status.reason}}},async upgrade(){let outcome=await upgradeInstalledVelloo();return{upgraded:outcome.upgraded,from:outcome.from,to:outcome.to,restartRequired:outcome.upgraded}}}}var IDLE_MS=300000;function portFree(port,host){try{return Bun.serve({port,hostname:host,fetch:()=>new Response("")}).stop(!0),!0}catch{return!1}}var daemon_default=defineCommand({meta:{name:"__daemon",hidden:!0,description:"(internal) Run the persistent canvas daemon. Spawned by `velloo run` / `velloo mcp`."},args:{folder:{type:"positional",required:!0,description:"Design folder (absolute)"},port:{type:"string",description:"Preferred canvas port"},host:{type:"string",description:"Bind hostname (default 127.0.0.1)"}},async run({args}){let root=daemonRoot(args.folder),host=args.host??"127.0.0.1";assertLoopbackHost(host);let cloudUrl=defaultCloudUrl(),cred=await loadCredential(cloudUrl),cloud={url:cloudUrl,token:cred?.token,resolveToken:async()=>(await loadCredential(cloudUrl))?.token},auth=createCanvasAuth(cloudUrl),publish=createCanvasPublish(cloudUrl,auth),updates=createCanvasUpdates(),canvasPort=portCandidates({explicit:args.port?Number(args.port):void 0,remembered:await readRememberedPort(root),root}).find((port)=>portFree(port,host))??0,handle;try{handle=await createServer({folder:root,port:canvasPort,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}catch(err){if(canvasPort===0)throw err;handle=await createServer({folder:root,port:0,host,mcp:{transport:"http",port:0},canvasDist:canvasDistPath,cloud,auth,publish,updates})}let rec={root,pid:process.pid,canvasUrl:handle.url,canvasPort:handle.port,mcpUrl:handle.mcpUrl??"",mcpPort:handle.mcpPort??0,cloudUrl,version:TOOL_VERSION,startedAt:new Date().toISOString()};await writeLock(rec),await registryUpsert(rec),await rememberPort(root,handle.port).catch(()=>{return}),console.error(`velloo: canvas daemon up at ${handle.url} (mcp ${handle.mcpUrl}), pid ${process.pid}`);let stopped=!1,shutdown=async()=>{if(stopped)return;stopped=!0,removeLock(root),await registryRemove(root).catch(()=>{return}),await handle.close(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown);let rootMissing=0;setInterval(()=>{if(existsSync2(root)){rootMissing=0;return}if(rootMissing+=1,rootMissing>=2)console.error(`velloo: design folder ${root} is gone \u2014 shutting down.`),shutdown()},1e4);let idleSince=Date.now();setInterval(()=>{let{canvas,mcp}=handle.connections();if(canvas+mcp>0){idleSince=null;return}if(idleSince===null){idleSince=Date.now();return}if(Date.now()-idleSince>=IDLE_MS)console.error("velloo: canvas idle for 5 min \u2014 shutting down."),shutdown()},30000),await new Promise(()=>{})}});export{daemon_default as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TAILWIND_CLASSNAME,helperSourcePath}from"./chunk-329e3phg.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-jnsfgtn9.js";import{registry2}from"./chunk-t2ttkxe9.js";import"./chunk-d385435m.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4}from"fs";import{join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(hostAppRoot){let dir=findUiDir(hostAppRoot);if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=body.indexOf(",",index),value=body.slice(index,end<0?body.length:end).trim();out.push([key,value]),index=end<0?body.length:end+1}return out}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir2,version=opts.version??snapshotVersion2,hostAppRoot=opts.hostAppRoot,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-pphgrsxa.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath2,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app, uses named canvas-safe adaptations for portal/state-heavy families, and falls back per component when a host file is missing or cannot compile. Velloo helpers (`Box`, `Heading`, `Text`, `Icon`, `Image`, `Gradient`, `Layer`, `SVG`, `Divider`, `Placeholder`, `Prose`) remain canvas primitives. Style through `update_props { style: "flex gap-4 p-6" }` \u2014 a Tailwind className string. Call `list_components` for the catalog and `component_status` before making a fidelity claim.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=hostAppRoot?installedAddNames(hostAppRoot):new Set;return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"fallback",note:"Velloo helper used alongside repo-backed shadcn components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir2,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName))return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:"The app component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline."}]}];let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]);export{createProvider};
|
|
2
|
+
import{TAILWIND_CLASSNAME,helperSourcePath}from"./chunk-tdsk5wxa.js";import{snapshotVersion2,entryCssPath2,componentsDir2}from"./chunk-cvn689d5.js";import{registry2}from"./chunk-hcb68zt7.js";import"./chunk-jb21jkp1.js";import{readFile}from"fs/promises";import{join}from"path";async function readManifest(cacheDir){let raw=await readFile(join(cacheDir,"manifest.json"),"utf8");return JSON.parse(raw)}import{existsSync as existsSync4}from"fs";import{join as join5}from"path";import{existsSync as existsSync3,readFileSync as readFileSync3}from"fs";import{join as join4}from"path";import{existsSync,readFileSync}from"fs";import{join as join2}from"path";function exportsName(source,id){let name=id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const|let|var|class)\\s+${name}\\b`).test(source))return!0;for(let match of source.matchAll(/\bexport\s*\{([^}]*)\}/g)){let clause=match[1]??"";for(let part of clause.split(",")){let local=part.trim().split(/\s+as\s+/);if((local.length>1?local[1]:local[0])?.trim()===id)return!0}}return/\bexport\s+\*\s+from\b/.test(source)}function hostComponentFile(uiDir,addName,id){for(let extension of["tsx","ts","jsx","js"]){let path=join2(uiDir,`${addName}.${extension}`);if(!existsSync(path))continue;try{return exportsName(readFileSync(path,"utf8"),id)?path:null}catch{return null}}return null}import{existsSync as existsSync2,readdirSync,readFileSync as readFileSync2}from"fs";import{join as join3,resolve}from"path";function kebab(id){return id.replace(/(?<!^)(?=[A-Z])/g,"-").toLowerCase()}function addNameIndex(manifest){let byId=new Map(manifest.flatMap((c)=>c.registryName?[[c.id,c.registryName]]:[]));return(id)=>byId.get(id)??kebab(id)}function findUiDir(hostAppRoot){let candidates=[];try{let cj=JSON.parse(readFileSync2(join3(hostAppRoot,"components.json"),"utf8")),fromAlias=(alias,suffix="")=>{if(!alias)return;let srcBase=existsSync2(join3(hostAppRoot,"src"))?"src":"",rel=alias.replace(/^@\//,srcBase?`${srcBase}/`:"")+suffix;candidates.push(resolve(hostAppRoot,rel))};fromAlias(cj.aliases?.ui),fromAlias(cj.aliases?.components,"/ui")}catch{}candidates.push(resolve(hostAppRoot,"src/components/ui"),resolve(hostAppRoot,"components/ui"),resolve(hostAppRoot,"app/components/ui"));for(let dir of candidates)if(existsSync2(dir))return dir;return null}function installedAddNames(hostAppRoot){let dir=findUiDir(hostAppRoot);if(!dir)return new Set;try{return new Set(readdirSync(dir).filter((f)=>f.endsWith(".tsx")||f.endsWith(".ts")).map((f)=>f.replace(/\.(tsx|ts)$/,"")))}catch{return new Set}}function enrichManifestFromHost(manifest,uiDir){if(!uiDir)return manifest;let addNameOf=addNameIndex(manifest),byFile=new Map,read=(addName)=>{if(byFile.has(addName))return byFile.get(addName)??null;for(let ext of["tsx","ts","jsx","js"]){let path=join4(uiDir,`${addName}.${ext}`);if(!existsSync3(path))continue;let source=readFileSync3(path,"utf8");return byFile.set(addName,source),source}return byFile.set(addName,""),null};return manifest.map((descriptor)=>{if(descriptor.source==="velloo")return descriptor;let source=read(addNameOf(descriptor.id));if(!source||!exportsName(source,descriptor.id))return descriptor;let additions=[...variantPropsFor(source,descriptor.id===descriptor.family),...declaredPropsFor(source,descriptor.id)];if(additions.length===0)return descriptor;let props=[...descriptor.props];for(let addition of additions){let index=props.findIndex((prop)=>prop.name===addition.name);if(index>=0)props[index]={...props[index],...addition};else props.push(addition)}return{...descriptor,props,designModeNotes:appendNote(descriptor.designModeNotes,"Props include variants detected from the app's component source.")}})}function appendNote(current,next){return current?`${current} ${next}`:next}function variantPropsFor(source,primary){let out=[];if(!primary)return out;let variantsAt=source.indexOf("variants:");if(variantsAt<0)return out;let open=source.indexOf("{",variantsAt),block=balancedBlock(source,open);if(!block)return out;for(let[name,value]of objectEntries(block.slice(1,-1))){let values=objectEntries(value.slice(1,-1)).map(([key])=>key);if(values.length===0)continue;out.push({name,type:`${values.map((value)=>JSON.stringify(value)).join(" | ")} | undefined`,optional:!0,control:"enum",enumValues:values,...defaultVariant(source,name)?{defaultValue:defaultVariant(source,name)}:{}})}return out}function defaultVariant(source,name){let at=source.indexOf("defaultVariants:");if(at<0)return;let open=source.indexOf("{",at),block=balancedBlock(source,open);if(!block)return;return objectEntries(block.slice(1,-1)).find(([key])=>key===name)?.[1].replace(/["'`\s]/g,"")}function declaredPropsFor(source,componentId){let match=[new RegExp(`interface\\s+${componentId}Props(?:\\s+extends[^\\{]+)?\\s*\\{`,"m"),new RegExp(`type\\s+${componentId}Props\\s*=.*?&\\s*\\{`,"m")].map((pattern)=>pattern.exec(source)).find(Boolean);if(!match||match.index===void 0)return[];let open=source.indexOf("{",match.index),block=balancedBlock(source,open);if(!block)return[];let out=[],property=/(?:^|[;{\n])\s*([A-Za-z_$][\w$]*)(\?)?\s*:\s*([^;\n}]+)/gm;for(let found of block.slice(1,-1).matchAll(property)){let name=found[1],raw=found[3]?.trim();if(!name||!raw||name==="children")continue;let enumValues=[...raw.matchAll(/["']([^"']+)["']/g)].map((value)=>value[1]),optional=found[2]==="?"||raw.includes("undefined");out.push({name,type:optional&&!raw.includes("undefined")?`${raw} | undefined`:raw,optional,control:enumValues.length>0?"enum":/boolean/.test(raw)?"boolean":/number/.test(raw)?"number":"string",...enumValues.length>0?{enumValues}:{}})}return out}function balancedBlock(source,open){if(open<0||source[open]!=="{")return null;let depth=0,quote="";for(let index=open;index<source.length;index++){let char=source[index],prev=source[index-1];if(quote){if(char===quote&&prev!=="\\")quote="";continue}if(char==='"'||char==="'"||char==="`"){quote=char;continue}if(char==="{")depth++;if(char==="}"&&--depth===0)return source.slice(open,index+1)}return null}function objectEntries(body){let out=[],index=0;while(index<body.length){while(index<body.length&&/[\s,]/.test(body[index]))index++;let keyMatch=/^(?:["']([^"']+)["']|([A-Za-z_$][\w$-]*))\s*:/.exec(body.slice(index));if(!keyMatch)break;let key=keyMatch[1]??keyMatch[2];if(!key)break;index+=keyMatch[0].length;while(/\s/.test(body[index]??""))index++;if(body[index]==="{"){let block=balancedBlock(body,index);if(!block)break;out.push([key,block]),index+=block.length;continue}let end=body.indexOf(",",index),value=body.slice(index,end<0?body.length:end).trim();out.push([key,value]),index=end<0?body.length:end+1}return out}function createProvider(opts={}){let cacheDir=opts.cacheDir,plannedUiDir=cacheDir?join5(cacheDir,"ui"):void 0,hostUiDir=()=>plannedUiDir&&existsSync4(plannedUiDir)?plannedUiDir:opts.hostAppRoot?findUiDir(opts.hostAppRoot):null,componentsDir=componentsDir2,version=opts.version??snapshotVersion2,hostAppRoot=opts.hostAppRoot,loadManifest=async()=>{if(cacheDir&&existsSync4(join5(cacheDir,"manifest.json")))return enrichManifestFromHost(await readManifest(cacheDir),hostUiDir());let{loadManifest:snapshotManifest}=await import("./chunk-zb6hc1y0.js");return enrichManifestFromHost(await snapshotManifest(),hostUiDir())};return{id:"shadcn-upstream",version,componentsDir,styleEntryPath:entryCssPath2,registry:registry2,loadManifest,label:`shadcn (upstream @ ${version})`,styleChannel:TAILWIND_CLASSNAME,styleChannels:["tailwind-classname"],mcpIntro:()=>['**This folder targets shadcn/ui with Tailwind.** The canvas imports client-safe components directly from the app, uses named canvas-safe adaptations for portal/state-heavy families, and falls back per component when a host file is missing or cannot compile. Velloo helpers (`Box`, `Heading`, `Text`, `Icon`, `Image`, `Gradient`, `Layer`, `SVG`, `Divider`, `Placeholder`, `Prose`) remain canvas primitives. Style through `update_props { style: "flex gap-4 p-6" }` \u2014 a Tailwind className string. Call `list_components` for the catalog and `component_status` before making a fidelity claim.',""],catalog:async()=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),shadcn=manifest.filter((c)=>c.source!=="velloo"),present=hostAppRoot?installedAddNames(hostAppRoot):new Set;return shadcn.map((c)=>{let addName=addNameOf(c.id);return{id:c.id,installed:present.has(addName),importPath:`@/components/ui/${addName}`}})},canvasBundleSpec:{styleRuntime:{kind:"none"},components:async(ids)=>{let manifest=await loadManifest(),addNameOf=addNameIndex(manifest),sourceById=new Map(manifest.map((entry)=>[entry.id,entry.source])),uiDir=hostUiDir();return ids.flatMap((id)=>{if(sourceById.get(id)==="velloo"){let path=helperSourcePath(id);return path?[{id,sources:[{importPath:path,exportName:id,fidelity:"fallback",note:"Velloo helper used alongside repo-backed shadcn components."}]}]:[]}if(!sourceById.has(id))return[];let addName=addNameOf(id),snapshotPath=join5(componentsDir2,"ui",`${addName}.tsx`);if(CANVAS_ADAPTED_FAMILIES.has(addName))return[{id,sources:[{importPath:snapshotPath,exportName:id,fidelity:"adapted",note:"The app component uses portals or runtime state; Velloo renders its canvas-safe counterpart inline."}]}];let hostPath=uiDir?hostComponentFile(uiDir,addName,id):null;return[{id,sources:[...hostPath?[{importPath:hostPath,exportName:id,fidelity:"exact",preflight:!0,note:"Rendered directly from the app's shadcn source file."}]:[],{importPath:snapshotPath,exportName:id,fidelity:"fallback",note:hostPath?"The app source did not compile for the browser canvas; using the bundled canvas fallback.":"The app does not install this component under this name (it may be renamed in its own file); using the bundled canvas fallback."}]}]})},sourceDirs:()=>{let uiDir=hostUiDir()??plannedUiDir;return uiDir?[uiDir]:[]}}}}var CANVAS_ADAPTED_FAMILIES=new Set(["alert-dialog","calendar","carousel","chart","dialog","dropdown-menu","popover","select","sheet","sonner","tooltip"]);export{createProvider};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{upgrade_default,migrateFolder2}from"./chunk-4dn75m6t.js";import"./chunk-pjtg3wnm.js";import"./chunk-vgmr98cv.js";import"./chunk-7eq7nx37.js";import"./chunk-vsv8z729.js";import"./chunk-sjgqnykd.js";import"./chunk-80fjfyha.js";import"./chunk-tdsk5wxa.js";import"./chunk-3e8vez4d.js";import"./chunk-pp86v6m6.js";import"./chunk-t448rrfr.js";import"./chunk-xt5ayg7g.js";import"./chunk-dg6z4vdd.js";import"./chunk-s23gtejf.js";import"./chunk-40xgcth8.js";export{upgrade_default as default,migrateFolder2 as migrateFolder};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isCssIdent,sanitizeCssTokenValue,neutralizeCssText,sanitizeGoogleFontSpec,typesetCss,isComponentNode,isSnippetInstance,isParamRef,ScreenSchema,resolveSnippetArgs,substituteSnippetParams,applySnippetOverrides,applySnippetExtraClassName,ThemeSchema}from"./chunk-bk8b7f9a.js";import{__toESM,__commonJS,__exportCjs,__require}from"./chunk-2smsg2ct.js";var require_chunkstream=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),ChunkStream=module.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};util.inherits(ChunkStream,Stream);ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};ChunkStream.prototype.write=function(data,encoding){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let dataBuffer;if(Buffer.isBuffer(data))dataBuffer=data;else dataBuffer=Buffer.from(data,encoding||this._encoding);if(this._buffers.push(dataBuffer),this._buffered+=dataBuffer.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};ChunkStream.prototype.end=function(data,encoding){if(data)this.write(data,encoding);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};ChunkStream.prototype.destroySoon=ChunkStream.prototype.end;ChunkStream.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};ChunkStream.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();let smallerBuf=this._buffers[0];if(smallerBuf.length>read.length)this._buffered-=read.length,this._buffers[0]=smallerBuf.slice(read.length),read.func.call(this,smallerBuf.slice(0,read.length));else this._buffered-=smallerBuf.length,this._buffers.shift(),read.func.call(this,smallerBuf)};ChunkStream.prototype._processRead=function(read){this._reads.shift();let pos=0,count=0,data=Buffer.alloc(read.length);while(pos<read.length){let buf=this._buffers[count++],len=Math.min(buf.length,read.length-pos);if(buf.copy(data,pos,0,len),pos+=len,len!==buf.length)this._buffers[--count]=buf.slice(len)}if(count>0)this._buffers.splice(0,count);this._buffered-=read.length,read.func.call(this,data)};ChunkStream.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let read=this._reads[0];if(read.allowLess)this._processReadAllowingLess(read);else if(this._buffered>=read.length)this._processRead(read);else break}if(this._buffers&&!this.writable)this._end()}catch(ex){this.emit("error",ex)}}});var require_interlace=__commonJS(function(exports){var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(width,height){let images=[],xLeftOver=width%8,yLeftOver=height%8,xRepeats=(width-xLeftOver)/8,yRepeats=(height-yLeftOver)/8;for(let i=0;i<imagePasses.length;i++){let pass=imagePasses[i],passWidth=xRepeats*pass.x.length,passHeight=yRepeats*pass.y.length;for(let j=0;j<pass.x.length;j++)if(pass.x[j]<xLeftOver)passWidth++;else break;for(let j=0;j<pass.y.length;j++)if(pass.y[j]<yLeftOver)passHeight++;else break;if(passWidth>0&&passHeight>0)images.push({width:passWidth,height:passHeight,index:i})}return images};exports.getInterlaceIterator=function(width){return function(x,y,pass){let outerXLeftOver=x%imagePasses[pass].x.length,outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver],outerYLeftOver=y%imagePasses[pass].y.length,outerY=(y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver];return outerX*4+outerY*width*4}}});var require_paeth_predictor=__commonJS(function(exports,module){module.exports=function(left,above,upLeft){let paeth=left+above-upLeft,pLeft=Math.abs(paeth-left),pAbove=Math.abs(paeth-above),pUpLeft=Math.abs(paeth-upLeft);if(pLeft<=pAbove&&pLeft<=pUpLeft)return left;if(pAbove<=pUpLeft)return above;return upLeft}});var require_filter_parse=__commonJS(function(exports,module){var interlaceUtils=require_interlace(),paethPredictor=require_paeth_predictor();function getByteWidth(width,bpp,depth){let byteWidth=width*bpp;if(depth!==8)byteWidth=Math.ceil(byteWidth/(8/depth));return byteWidth}var Filter=module.exports=function(bitmapInfo,dependencies){let{width,height,interlace,bpp,depth}=bitmapInfo;if(this.read=dependencies.read,this.write=dependencies.write,this.complete=dependencies.complete,this._imageIndex=0,this._images=[],interlace){let passes=interlaceUtils.getImagePasses(width,height);for(let i=0;i<passes.length;i++)this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}else this._images.push({byteWidth:getByteWidth(width,bpp,depth),height,lineIndex:0});if(depth===8)this._xComparison=bpp;else if(depth===16)this._xComparison=bpp*2;else this._xComparison=1};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}};Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){let lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}};Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f3Up=lastLine?lastLine[x]:0,f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}};Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f4Up=lastLine?lastLine[x]:0,f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0,f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}};Filter.prototype._reverseFilterLine=function(rawData){let filter=rawData[0],unfilteredLine,currentImage=this._images[this._imageIndex],byteWidth=currentImage.byteWidth;if(filter===0)unfilteredLine=rawData.slice(1,byteWidth+1);else switch(unfilteredLine=Buffer.alloc(byteWidth),filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw Error("Unrecognised filter type - "+filter)}if(this.write(unfilteredLine),currentImage.lineIndex++,currentImage.lineIndex>=currentImage.height)this._lastLine=null,this._imageIndex++,currentImage=this._images[this._imageIndex];else this._lastLine=unfilteredLine;if(currentImage)this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var require_filter_parse_async=__commonJS(function(exports,module){var util=__require("util"),ChunkStream=require_chunkstream(),Filter=require_filter_parse(),FilterAsync=module.exports=function(bitmapInfo){ChunkStream.call(this);let buffers=[],that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}}),this._filter.start()};util.inherits(FilterAsync,ChunkStream)});var require_constants=__commonJS(function(exports,module){module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var require_crc=__commonJS(function(exports,module){var crcTable=[];(function(){for(let i=0;i<256;i++){let currentCrc=i;for(let j=0;j<8;j++)if(currentCrc&1)currentCrc=3988292384^currentCrc>>>1;else currentCrc=currentCrc>>>1;crcTable[i]=currentCrc}})();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(data){for(let i=0;i<data.length;i++)this._crc=crcTable[(this._crc^data[i])&255]^this._crc>>>8;return!0};CrcCalculator.prototype.crc32=function(){return this._crc^-1};CrcCalculator.crc32=function(buf){let crc=-1;for(let i=0;i<buf.length;i++)crc=crcTable[(crc^buf[i])&255]^crc>>>8;return crc^-1}});var require_parser=__commonJS(function(exports,module){var constants=require_constants(),CrcCalculator=require_crc(),Parser=module.exports=function(options,dependencies){this._options=options,options.checkCRC=options.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=dependencies.read,this.error=dependencies.error,this.metadata=dependencies.metadata,this.gamma=dependencies.gamma,this.transColor=dependencies.transColor,this.palette=dependencies.palette,this.parsed=dependencies.parsed,this.inflateData=dependencies.inflateData,this.finished=dependencies.finished,this.simpleTransparency=dependencies.simpleTransparency,this.headersFinished=dependencies.headersFinished||function(){}};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Parser.prototype._parseSignature=function(data){let signature=constants.PNG_SIGNATURE;for(let i=0;i<signature.length;i++)if(data[i]!==signature[i]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._parseChunkBegin=function(data){let length=data.readUInt32BE(0),type=data.readUInt32BE(4),name="";for(let i=4;i<8;i++)name+=String.fromCharCode(data[i]);let ancillary=Boolean(data[4]&32);if(!this._hasIHDR&&type!==constants.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new CrcCalculator,this._crc.write(Buffer.from(name)),this._chunks[type])return this._chunks[type](length);if(!ancillary){this.error(Error("Unsupported critical chunk type "+name));return}this.read(length+4,this._skipChunk.bind(this))};Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Parser.prototype._parseChunkEnd=function(data){let fileCrc=data.readInt32BE(0),calcCrc=this._crc.crc32();if(this._options.checkCRC&&calcCrc!==fileCrc){this.error(Error("Crc error - "+fileCrc+" - "+calcCrc));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))};Parser.prototype._parseIHDR=function(data){this._crc.write(data);let width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],colorType=data[9],compr=data[10],filter=data[11],interlace=data[12];if(depth!==8&&depth!==4&&depth!==2&&depth!==1&&depth!==16){this.error(Error("Unsupported bit depth "+depth));return}if(!(colorType in constants.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(compr!==0){this.error(Error("Unsupported compression method"));return}if(filter!==0){this.error(Error("Unsupported filter method"));return}if(interlace!==0&&interlace!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=colorType;let bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width,height,depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp,colorType}),this._handleChunkEnd()};Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))};Parser.prototype._parsePLTE=function(data){this._crc.write(data);let entries=Math.floor(data.length/3);for(let i=0;i<entries;i++)this._palette.push([data[i*3],data[i*3+1],data[i*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Parser.prototype._handleTRNS=function(length){this.simpleTransparency(),this.read(length,this._parseTRNS.bind(this))};Parser.prototype._parseTRNS=function(data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(data.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let i=0;i<data.length;i++)this._palette[i][3]=data[i];this.palette(this._palette)}if(this._colorType===constants.COLORTYPE_GRAYSCALE)this.transColor([data.readUInt16BE(0)]);if(this._colorType===constants.COLORTYPE_COLOR)this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)]);this._handleChunkEnd()};Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))};Parser.prototype._parseGAMA=function(data){this._crc.write(data),this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()};Parser.prototype._handleIDAT=function(length){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-length,this._parseIDAT.bind(this,length))};Parser.prototype._parseIDAT=function(length,data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(data);let leftOverLength=length-data.length;if(leftOverLength>0)this._handleIDAT(leftOverLength);else this._handleChunkEnd()};Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))};Parser.prototype._parseIEND=function(data){if(this._crc.write(data),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var require_bitmapper=__commonJS(function(exports){var interlaceUtils=require_interlace(),pixelBppMapper=[function(){},function(pxData,data,pxPos,rawPos){if(rawPos===data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+1>=data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=data[rawPos+1]},function(pxData,data,pxPos,rawPos){if(rawPos+2>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+3>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=data[rawPos+3]}],pixelBppCustomMapper=[function(){},function(pxData,pixelData,pxPos,maxBit){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=pixelData[1]},function(pxData,pixelData,pxPos,maxBit){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=pixelData[3]}];function bitRetriever(data,depth){let leftOver=[],i=0;function split(){if(i===data.length)throw Error("Ran out of data");let byte=data[i];i++;let byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1;switch(depth){default:throw Error("unrecognised depth");case 16:byte2=data[i],i++,leftOver.push((byte<<8)+byte2);break;case 4:byte2=byte&15,byte1=byte>>4,leftOver.push(byte1,byte2);break;case 2:byte4=byte&3,byte3=byte>>2&3,byte2=byte>>4&3,byte1=byte>>6&3,leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=byte&1,byte7=byte>>1&1,byte6=byte>>2&1,byte5=byte>>3&1,byte4=byte>>4&1,byte3=byte>>5&1,byte2=byte>>6&1,byte1=byte>>7&1,leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8);break}}return{get:function(count){while(leftOver.length<count)split();let returner=leftOver.slice(0,count);return leftOver=leftOver.slice(count),returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length)throw Error("extra data found")}}}function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++)for(let x=0;x<imageWidth;x++){let pxPos=getPxPos(x,y,imagePass);pixelBppMapper[bpp](pxData,data,pxPos,rawPos),rawPos+=bpp}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++){for(let x=0;x<imageWidth;x++){let pixelData=bits.get(bpp),pxPos=getPxPos(x,y,imagePass);pixelBppCustomMapper[bpp](pxData,pixelData,pxPos,maxBit)}bits.resetAfterLine()}}exports.dataToBitMap=function(data,bitmapInfo){let{width,height,depth,bpp,interlace}=bitmapInfo,bits;if(depth!==8)bits=bitRetriever(data,depth);let pxData;if(depth<=8)pxData=Buffer.alloc(width*height*4);else pxData=new Uint16Array(width*height*4);let maxBit=Math.pow(2,depth)-1,rawPos=0,images,getPxPos;if(interlace)images=interlaceUtils.getImagePasses(width,height),getPxPos=interlaceUtils.getInterlaceIterator(width,height);else{let nonInterlacedPxPos=0;getPxPos=function(){let returner=nonInterlacedPxPos;return nonInterlacedPxPos+=4,returner},images=[{width,height}]}for(let imageIndex=0;imageIndex<images.length;imageIndex++)if(depth===8)rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos);else mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit);if(depth===8){if(rawPos!==data.length)throw Error("extra data found")}else bits.end();return pxData}});var require_format_normaliser=__commonJS(function(exports,module){function dePalette(indata,outdata,width,height,palette){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let color=palette[indata[pxPos]];if(!color)throw Error("index "+indata[pxPos]+" not in palette");for(let i=0;i<4;i++)outdata[pxPos+i]=color[i];pxPos+=4}}function replaceTransparentColor(indata,outdata,width,height,transColor){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let makeTrans=!1;if(transColor.length===1){if(transColor[0]===indata[pxPos])makeTrans=!0}else if(transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2])makeTrans=!0;if(makeTrans)for(let i=0;i<4;i++)outdata[pxPos+i]=0;pxPos+=4}}function scaleDepth(indata,outdata,width,height,depth){let maxOutSample=255,maxInSample=Math.pow(2,depth)-1,pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){for(let i=0;i<4;i++)outdata[pxPos+i]=Math.floor(indata[pxPos+i]*maxOutSample/maxInSample+0.5);pxPos+=4}}module.exports=function(indata,imageData,skipRescale=!1){let{depth,width,height,colorType,transColor,palette}=imageData,outdata=indata;if(colorType===3)dePalette(indata,outdata,width,height,palette);else{if(transColor)replaceTransparentColor(indata,outdata,width,height,transColor);if(depth!==8&&!skipRescale){if(depth===16)outdata=Buffer.alloc(width*height*4);scaleDepth(indata,outdata,width,height,depth)}}return outdata}});var require_parser_async=__commonJS(function(exports,module){var util=__require("util"),zlib=__require("zlib"),ChunkStream=require_chunkstream(),FilterAsync=require_filter_parse_async(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser(),ParserAsync=module.exports=function(options){ChunkStream.call(this),this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=options,this.writable=!0,this._parser.start()};util.inherits(ParserAsync,ChunkStream);ParserAsync.prototype._handleError=function(err){if(this.emit("error",err),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ParserAsync.prototype._inflateData=function(data){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let imageSize=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,chunkSize=Math.max(imageSize,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize});let leftToInflate=imageSize,emitError=this.emit.bind(this,"error");this._inflate.on("error",function(err){if(!leftToInflate)return;emitError(err)}),this._filter.on("complete",this._complete.bind(this));let filterWrite=this._filter.write.bind(this._filter);this._inflate.on("data",function(chunk){if(!leftToInflate)return;if(chunk.length>leftToInflate)chunk=chunk.slice(0,leftToInflate);leftToInflate-=chunk.length,filterWrite(chunk)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(data)};ParserAsync.prototype._handleMetaData=function(metaData){this._metaData=metaData,this._bitmapInfo=Object.create(metaData),this._filter=new FilterAsync(this._bitmapInfo)};ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor};ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette};ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ParserAsync.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ParserAsync.prototype._complete=function(filteredData){if(this.errord)return;let normalisedBitmapData;try{let bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo,this._options.skipRescale),bitmapData=null}catch(ex){this._handleError(ex);return}this.emit("parsed",normalisedBitmapData)}});var require_bitpacker=__commonJS(function(exports,module){var constants=require_constants();module.exports=function(dataIn,width,height,options){let outHasAlpha=[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)!==-1;if(options.colorType===options.inputColorType){let bigEndian=function(){let buffer=new ArrayBuffer(2);return new DataView(buffer).setInt16(0,256,!0),new Int16Array(buffer)[0]!==256}();if(options.bitDepth===8||options.bitDepth===16&&bigEndian)return dataIn}let data=options.bitDepth!==16?dataIn:new Uint16Array(dataIn.buffer),maxValue=255,inBpp=constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];if(inBpp===4&&!options.inputHasAlpha)inBpp=3;let outBpp=constants.COLORTYPE_TO_BPP_MAP[options.colorType];if(options.bitDepth===16)maxValue=65535,outBpp*=2;let outData=Buffer.alloc(width*height*outBpp),inIndex=0,outIndex=0,bgColor=options.bgColor||{};if(bgColor.red===void 0)bgColor.red=maxValue;if(bgColor.green===void 0)bgColor.green=maxValue;if(bgColor.blue===void 0)bgColor.blue=maxValue;function getRGBA(){let red,green,blue,alpha=maxValue;switch(options.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:alpha=data[inIndex+3],red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_COLOR:red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_ALPHA:alpha=data[inIndex+1],red=data[inIndex],green=red,blue=red;break;case constants.COLORTYPE_GRAYSCALE:red=data[inIndex],green=red,blue=red;break;default:throw Error("input color type:"+options.inputColorType+" is not supported at present")}if(options.inputHasAlpha){if(!outHasAlpha)alpha/=maxValue,red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),maxValue),green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),maxValue),blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),maxValue)}return{red,green,blue,alpha}}for(let y=0;y<height;y++)for(let x=0;x<width;x++){let rgba=getRGBA(data,inIndex);switch(options.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:if(options.bitDepth===8){if(outData[outIndex]=rgba.red,outData[outIndex+1]=rgba.green,outData[outIndex+2]=rgba.blue,outHasAlpha)outData[outIndex+3]=rgba.alpha}else if(outData.writeUInt16BE(rgba.red,outIndex),outData.writeUInt16BE(rgba.green,outIndex+2),outData.writeUInt16BE(rgba.blue,outIndex+4),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+6);break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:{let grayscale=(rgba.red+rgba.green+rgba.blue)/3;if(options.bitDepth===8){if(outData[outIndex]=grayscale,outHasAlpha)outData[outIndex+1]=rgba.alpha}else if(outData.writeUInt16BE(grayscale,outIndex),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+2);break}default:throw Error("unrecognised color Type "+options.colorType)}inIndex+=inBpp,outIndex+=outBpp}return outData}});var require_filter_pack=__commonJS(function(exports,module){var paethPredictor=require_paeth_predictor();function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++)rawData[rawPos+x]=pxData[pxPos+x]}function filterSumNone(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let i=pxPos;i<length;i++)sum+=Math.abs(pxData[i]);return sum}function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}}function filterSumSub(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum}function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++){let up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}}function filterSumUp(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let x=pxPos;x<length;x++){let up=pxPos>0?pxData[x-byteWidth]:0,val=pxData[x]-up;sum+=Math.abs(val)}return sum}function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}}function filterSumAvg(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum}function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}function filterSumPaeth(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth},filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(pxData,width,height,options,bpp){let filterTypes;if(!("filterType"in options)||options.filterType===-1)filterTypes=[0,1,2,3,4];else if(typeof options.filterType==="number")filterTypes=[options.filterType];else throw Error("unrecognised filter types");if(options.bitDepth===16)bpp*=2;let byteWidth=width*bpp,rawPos=0,pxPos=0,rawData=Buffer.alloc((byteWidth+1)*height),sel=filterTypes[0];for(let y=0;y<height;y++){if(filterTypes.length>1){let min=1/0;for(let i=0;i<filterTypes.length;i++){let sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);if(sum<min)sel=filterTypes[i],min=sum}}rawData[rawPos]=sel,rawPos++,filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp),rawPos+=byteWidth,pxPos+=byteWidth}return rawData}});var require_packer=__commonJS(function(exports,module){var constants=require_constants(),CrcStream=require_crc(),bitPacker=require_bitpacker(),filter=require_filter_pack(),zlib=__require("zlib"),Packer=module.exports=function(options){if(this._options=options,options.deflateChunkSize=options.deflateChunkSize||32768,options.deflateLevel=options.deflateLevel!=null?options.deflateLevel:9,options.deflateStrategy=options.deflateStrategy!=null?options.deflateStrategy:3,options.inputHasAlpha=options.inputHasAlpha!=null?options.inputHasAlpha:!0,options.deflateFactory=options.deflateFactory||zlib.createDeflate,options.bitDepth=options.bitDepth||8,options.colorType=typeof options.colorType==="number"?options.colorType:constants.COLORTYPE_COLOR_ALPHA,options.inputColorType=typeof options.inputColorType==="number"?options.inputColorType:constants.COLORTYPE_COLOR_ALPHA,[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)===-1)throw Error("option color type:"+options.colorType+" is not supported at present");if([constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.inputColorType)===-1)throw Error("option input color type:"+options.inputColorType+" is not supported at present");if(options.bitDepth!==8&&options.bitDepth!==16)throw Error("option bit depth:"+options.bitDepth+" is not supported at present")};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Packer.prototype.filterData=function(data,width,height){let packedData=bitPacker(data,width,height,this._options),bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(packedData,width,height,this._options,bpp)};Packer.prototype._packChunk=function(type,data){let len=data?data.length:0,buf=Buffer.alloc(len+12);if(buf.writeUInt32BE(len,0),buf.writeUInt32BE(type,4),data)data.copy(buf,8);return buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4),buf};Packer.prototype.packGAMA=function(gamma){let buf=Buffer.alloc(4);return buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,buf)};Packer.prototype.packIHDR=function(width,height){let buf=Buffer.alloc(13);return buf.writeUInt32BE(width,0),buf.writeUInt32BE(height,4),buf[8]=this._options.bitDepth,buf[9]=this._options.colorType,buf[10]=0,buf[11]=0,buf[12]=0,this._packChunk(constants.TYPE_IHDR,buf)};Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)};Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)}});var require_packer_async=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),constants=require_constants(),Packer=require_packer(),PackerAsync=module.exports=function(opt){Stream.call(this);let options=opt||{};this._packer=new Packer(options),this._deflate=this._packer.createDeflate(),this.readable=!0};util.inherits(PackerAsync,Stream);PackerAsync.prototype.pack=function(data,width,height,gamma){if(this.emit("data",Buffer.from(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(width,height)),gamma)this.emit("data",this._packer.packGAMA(gamma));let filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(filteredData)}});var require_sync_inflate=__commonJS(function(exports,module){var assert=__require("assert").ok,zlib=__require("zlib"),util=__require("util"),kMaxLength=__require("buffer").kMaxLength;function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);if(opts&&opts.chunkSize<zlib.Z_MIN_CHUNK)opts.chunkSize=zlib.Z_MIN_CHUNK;if(zlib.Inflate.call(this,opts),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,opts&&opts.maxLength!=null)this._maxLength=opts.maxLength}function createInflate(opts){return new Inflate(opts)}function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}Inflate.prototype._processChunk=function(chunk,flushFlag,asyncCb){if(typeof asyncCb==="function")return zlib.Inflate._processChunk.call(this,chunk,flushFlag,asyncCb);let self=this,availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,leftToInflate=this._maxLength,inOff=0,buffers=[],nread=0,error;this.on("error",function(err){error=err});function handleChunk(availInAfter,availOutAfter){if(self._hadError)return;let have=availOutBefore-availOutAfter;if(assert(have>=0,"have should not go down"),have>0){let out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,out.length>leftToInflate)out=out.slice(0,leftToInflate);if(buffers.push(out),nread+=out.length,leftToInflate-=out.length,leftToInflate===0)return!1}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer.allocUnsafe(self._chunkSize);if(availOutAfter===0)return inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!0;return!1}assert(this._handle,"zlib binding closed");let res;do res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore),res=res||this._writeState;while(!this._hadError&&handleChunk(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)throw _close(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");let buf=Buffer.concat(buffers,nread);return _close(this),buf};util.inherits(Inflate,zlib.Inflate);function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=Buffer.from(buffer);if(!(buffer instanceof Buffer))throw TypeError("Not a string or buffer");let flushFlag=engine._finishFlushFlag;if(flushFlag==null)flushFlag=zlib.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function inflateSync(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)}module.exports=exports=inflateSync;exports.Inflate=Inflate;exports.createInflate=createInflate;exports.inflateSync=inflateSync});var require_sync_reader=__commonJS(function(exports,module){var SyncReader=module.exports=function(buffer){this._buffer=buffer,this._reads=[]};SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})};SyncReader.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let read=this._reads[0];if(this._buffer.length&&(this._buffer.length>=read.length||read.allowLess)){this._reads.shift();let buf=this._buffer;this._buffer=buf.slice(read.length),read.func.call(this,buf.slice(0,read.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var require_filter_parse_sync=__commonJS(function(exports){var SyncReader=require_sync_reader(),Filter=require_filter_parse();exports.process=function(inBuffer,bitmapInfo){let outBuffers=[],reader=new SyncReader(inBuffer);return new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}}).start(),reader.process(),Buffer.concat(outBuffers)}});var require_parser_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib"),inflateSync=require_sync_inflate();if(!zlib.deflateSync)hasSyncZlib=!1;var SyncReader=require_sync_reader(),FilterSync=require_filter_parse_sync(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser();module.exports=function(buffer,options){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let err;function handleError(_err_){err=_err_}let metaData;function handleMetaData(_metaData_){metaData=_metaData_}function handleTransColor(transColor){metaData.transColor=transColor}function handlePalette(palette){metaData.palette=palette}function handleSimpleTransparency(){metaData.alpha=!0}let gamma;function handleGamma(_gamma_){gamma=_gamma_}let inflateDataList=[];function handleInflateData(inflatedData){inflateDataList.push(inflatedData)}let reader=new SyncReader(buffer);if(new Parser(options,{read:reader.read.bind(reader),error:handleError,metadata:handleMetaData,gamma:handleGamma,palette:handlePalette,transColor:handleTransColor,inflateData:handleInflateData,simpleTransparency:handleSimpleTransparency}).start(),reader.process(),err)throw err;let inflateData=Buffer.concat(inflateDataList);inflateDataList.length=0;let inflatedData;if(metaData.interlace)inflatedData=zlib.inflateSync(inflateData);else{let imageSize=((metaData.width*metaData.bpp*metaData.depth+7>>3)+1)*metaData.height;inflatedData=inflateSync(inflateData,{chunkSize:imageSize,maxLength:imageSize})}if(inflateData=null,!inflatedData||!inflatedData.length)throw Error("bad png - invalid inflate data response");let unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;let bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;let normalisedBitmapData=formatNormaliser(bitmapData,metaData,options.skipRescale);return metaData.data=normalisedBitmapData,metaData.gamma=gamma||0,metaData}});var require_packer_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib");if(!zlib.deflateSync)hasSyncZlib=!1;var constants=require_constants(),Packer=require_packer();module.exports=function(metaData,opt){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let packer=new Packer(opt||{}),chunks=[];if(chunks.push(Buffer.from(constants.PNG_SIGNATURE)),chunks.push(packer.packIHDR(metaData.width,metaData.height)),metaData.gamma)chunks.push(packer.packGAMA(metaData.gamma));let filteredData=packer.filterData(metaData.data,metaData.width,metaData.height),compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());if(filteredData=null,!compressedData||!compressedData.length)throw Error("bad png - invalid compressed data response");return chunks.push(packer.packIDAT(compressedData)),chunks.push(packer.packIEND()),Buffer.concat(chunks)}});var require_png_sync=__commonJS(function(exports){var parse=require_parser_sync(),pack=require_packer_sync();exports.read=function(buffer,options){return parse(buffer,options||{})};exports.write=function(png,options){return pack(png,options)}});var require_png=__commonJS(function(exports){var util=__require("util"),Stream=__require("stream"),Parser=require_parser_async(),Packer=require_packer_async(),PNGSync=require_png_sync(),PNG=exports.PNG=function(options){if(Stream.call(this),options=options||{},this.width=options.width|0,this.height=options.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,options.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(options),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(data){this.data=data,this.emit("parsed",data)}.bind(this)),this._packer=new Packer(options),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream);PNG.sync=PNGSync;PNG.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};PNG.prototype.parse=function(data,callback){if(callback){let onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError),this.data=parsedData,callback(null,this)}.bind(this),onError=function(err){this.removeListener("parsed",onParsed),callback(err,null)}.bind(this),this.once("parsed",onParsed),this.once("error",onError)}return this.end(data),this};PNG.prototype.write=function(data){return this._parser.write(data),!0};PNG.prototype.end=function(data){this._parser.end(data)};PNG.prototype._metadata=function(metadata){this.width=metadata.width,this.height=metadata.height,this.emit("metadata",metadata)};PNG.prototype._gamma=function(gamma){this.gamma=gamma};PNG.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){if(srcX|=0,srcY|=0,width|=0,height|=0,deltaX|=0,deltaY|=0,srcX>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height)throw Error("bitblt reading outside image");if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height)throw Error("bitblt writing outside image");for(let y=0;y<height;y++)src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)};PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){return PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY),this};PNG.adjustGamma=function(src){if(src.gamma){for(let y=0;y<src.height;y++)for(let x=0;x<src.width;x++){let idx=src.width*y+x<<2;for(let i=0;i<3;i++){let sample=src.data[idx+i]/255;sample=Math.pow(sample,0.45454545454545453/src.gamma),src.data[idx+i]=Math.round(sample*255)}}src.gamma=0}};PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)}});var require_react_development=__commonJS(function(exports,module){(function(){function defineDeprecationWarning(methodName,info){Object.defineProperty(Component.prototype,methodName,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",info[0],info[1])}})}function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}function warnNoop(publicInstance,callerName){publicInstance=(publicInstance=publicInstance.constructor)&&(publicInstance.displayName||publicInstance.name)||"ReactClass";var warningKey=publicInstance+"."+callerName;didWarnStateUpdateForUnmountedComponent[warningKey]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",callerName,publicInstance),didWarnStateUpdateForUnmountedComponent[warningKey]=!0)}function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function noop(){}function testStringCoercion(value){return""+value}function checkKeyStringCoercion(value){try{testStringCoercion(value);var JSCompiler_inline_result=!1}catch(e){JSCompiler_inline_result=!0}if(JSCompiler_inline_result){JSCompiler_inline_result=console;var JSCompiler_temp_const=JSCompiler_inline_result.error,JSCompiler_inline_result$jscomp$0=typeof Symbol==="function"&&Symbol.toStringTag&&value[Symbol.toStringTag]||value.constructor.name||"Object";return JSCompiler_temp_const.call(JSCompiler_inline_result,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",JSCompiler_inline_result$jscomp$0),testStringCoercion(value)}}function getComponentNameFromType(type){if(type==null)return null;if(typeof type==="function")return type.$$typeof===REACT_CLIENT_REFERENCE?null:type.displayName||type.name||null;if(typeof type==="string")return type;switch(type){case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_ACTIVITY_TYPE:return"Activity"}if(typeof type==="object")switch(typeof type.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),type.$$typeof){case REACT_PORTAL_TYPE:return"Portal";case REACT_CONTEXT_TYPE:return type.displayName||"Context";case REACT_CONSUMER_TYPE:return(type._context.displayName||"Context")+".Consumer";case REACT_FORWARD_REF_TYPE:var innerType=type.render;return type=type.displayName,type||(type=innerType.displayName||innerType.name||"",type=type!==""?"ForwardRef("+type+")":"ForwardRef"),type;case REACT_MEMO_TYPE:return innerType=type.displayName||null,innerType!==null?innerType:getComponentNameFromType(type.type)||"Memo";case REACT_LAZY_TYPE:innerType=type._payload,type=type._init;try{return getComponentNameFromType(type(innerType))}catch(x){}}return null}function getTaskName(type){if(type===REACT_FRAGMENT_TYPE)return"<>";if(typeof type==="object"&&type!==null&&type.$$typeof===REACT_LAZY_TYPE)return"<...>";try{var name=getComponentNameFromType(type);return name?"<"+name+">":"<...>"}catch(x){return"<...>"}}function getOwner(){var dispatcher=ReactSharedInternals.A;return dispatcher===null?null:dispatcher.getOwner()}function UnknownOwner(){return Error("react-stack-top-frame")}function hasValidKey(config){if(hasOwnProperty.call(config,"key")){var getter=Object.getOwnPropertyDescriptor(config,"key").get;if(getter&&getter.isReactWarning)return!1}return config.key!==void 0}function defineKeyPropWarningGetter(props,displayName){function warnAboutAccessingKey(){specialPropKeyWarningShown||(specialPropKeyWarningShown=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",displayName))}warnAboutAccessingKey.isReactWarning=!0,Object.defineProperty(props,"key",{get:warnAboutAccessingKey,configurable:!0})}function elementRefGetterWithDeprecationWarning(){var componentName=getComponentNameFromType(this.type);return didWarnAboutElementRef[componentName]||(didWarnAboutElementRef[componentName]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),componentName=this.props.ref,componentName!==void 0?componentName:null}function ReactElement(type,key,props,owner,debugStack,debugTask){var refProp=props.ref;return type={$$typeof:REACT_ELEMENT_TYPE,type,key,props,_owner:owner},(refProp!==void 0?refProp:null)!==null?Object.defineProperty(type,"ref",{enumerable:!1,get:elementRefGetterWithDeprecationWarning}):Object.defineProperty(type,"ref",{enumerable:!1,value:null}),type._store={},Object.defineProperty(type._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(type,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(type,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:debugStack}),Object.defineProperty(type,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:debugTask}),Object.freeze&&(Object.freeze(type.props),Object.freeze(type)),type}function cloneAndReplaceKey(oldElement,newKey){return newKey=ReactElement(oldElement.type,newKey,oldElement.props,oldElement._owner,oldElement._debugStack,oldElement._debugTask),oldElement._store&&(newKey._store.validated=oldElement._store.validated),newKey}function validateChildKeys(node){isValidElement(node)?node._store&&(node._store.validated=1):typeof node==="object"&&node!==null&&node.$$typeof===REACT_LAZY_TYPE&&(node._payload.status==="fulfilled"?isValidElement(node._payload.value)&&node._payload.value._store&&(node._payload.value._store.validated=1):node._store&&(node._store.validated=1))}function isValidElement(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}function getElementKey(element,index){return typeof element==="object"&&element!==null&&element.key!=null?(checkKeyStringCoercion(element.key),escape(""+element.key)):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch(typeof thenable.status==="string"?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){thenable.status==="pending"&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){thenable.status==="pending"&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;if(type==="undefined"||type==="boolean")children=null;var invokeCallback=!1;if(children===null)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return invokeCallback=children._init,mapIntoArray(invokeCallback(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback){invokeCallback=children,callback=callback(invokeCallback);var childKey=nameSoFar===""?"."+getElementKey(invokeCallback,0):nameSoFar;return isArrayImpl(callback)?(escapedPrefix="",childKey!=null&&(escapedPrefix=childKey.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):callback!=null&&(isValidElement(callback)&&(callback.key!=null&&(invokeCallback&&invokeCallback.key===callback.key||checkKeyStringCoercion(callback.key)),escapedPrefix=cloneAndReplaceKey(callback,escapedPrefix+(callback.key==null||invokeCallback&&invokeCallback.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+childKey),nameSoFar!==""&&invokeCallback!=null&&isValidElement(invokeCallback)&&invokeCallback.key==null&&invokeCallback._store&&!invokeCallback._store.validated&&(escapedPrefix._store.validated=2),callback=escapedPrefix),array.push(callback)),1}if(invokeCallback=0,childKey=nameSoFar===""?".":nameSoFar+":",isArrayImpl(children))for(var i=0;i<children.length;i++)nameSoFar=children[i],type=childKey+getElementKey(nameSoFar,i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(i=getIteratorFn(children),typeof i==="function")for(i===children.entries&&(didWarnAboutMaps||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),didWarnAboutMaps=!0),children=i.call(children),i=0;!(nameSoFar=children.next()).done;)nameSoFar=nameSoFar.value,type=childKey+getElementKey(nameSoFar,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(type==="object"){if(typeof children.then==="function")return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw array=String(children),Error("Objects are not valid as a React child (found: "+(array==="[object Object]"?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(children==null)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(payload._status===-1){var ioInfo=payload._ioInfo;ioInfo!=null&&(ioInfo.start=ioInfo.end=performance.now()),ioInfo=payload._result;var thenable=ioInfo();if(thenable.then(function(moduleObject){if(payload._status===0||payload._status===-1){payload._status=1,payload._result=moduleObject;var _ioInfo=payload._ioInfo;_ioInfo!=null&&(_ioInfo.end=performance.now()),thenable.status===void 0&&(thenable.status="fulfilled",thenable.value=moduleObject)}},function(error){if(payload._status===0||payload._status===-1){payload._status=2,payload._result=error;var _ioInfo2=payload._ioInfo;_ioInfo2!=null&&(_ioInfo2.end=performance.now()),thenable.status===void 0&&(thenable.status="rejected",thenable.reason=error)}}),ioInfo=payload._ioInfo,ioInfo!=null){ioInfo.value=thenable;var displayName=thenable.displayName;typeof displayName==="string"&&(ioInfo.name=displayName)}payload._status===-1&&(payload._status=0,payload._result=thenable)}if(payload._status===1)return ioInfo=payload._result,ioInfo===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
2
|
+
import{isCssIdent,sanitizeCssTokenValue,neutralizeCssText,sanitizeGoogleFontSpec,isComponentNode,isSnippetInstance,isParamRef,ScreenSchema,resolveSnippetArgs,substituteSnippetParams,applySnippetOverrides,applySnippetExtraClassName,ThemeSchema,typesetCss}from"./chunk-40xgcth8.js";import{__toESM,__commonJS,__exportCjs,__require}from"./chunk-2smsg2ct.js";var require_chunkstream=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),ChunkStream=module.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};util.inherits(ChunkStream,Stream);ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};ChunkStream.prototype.write=function(data,encoding){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let dataBuffer;if(Buffer.isBuffer(data))dataBuffer=data;else dataBuffer=Buffer.from(data,encoding||this._encoding);if(this._buffers.push(dataBuffer),this._buffered+=dataBuffer.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};ChunkStream.prototype.end=function(data,encoding){if(data)this.write(data,encoding);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};ChunkStream.prototype.destroySoon=ChunkStream.prototype.end;ChunkStream.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};ChunkStream.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();let smallerBuf=this._buffers[0];if(smallerBuf.length>read.length)this._buffered-=read.length,this._buffers[0]=smallerBuf.slice(read.length),read.func.call(this,smallerBuf.slice(0,read.length));else this._buffered-=smallerBuf.length,this._buffers.shift(),read.func.call(this,smallerBuf)};ChunkStream.prototype._processRead=function(read){this._reads.shift();let pos=0,count=0,data=Buffer.alloc(read.length);while(pos<read.length){let buf=this._buffers[count++],len=Math.min(buf.length,read.length-pos);if(buf.copy(data,pos,0,len),pos+=len,len!==buf.length)this._buffers[--count]=buf.slice(len)}if(count>0)this._buffers.splice(0,count);this._buffered-=read.length,read.func.call(this,data)};ChunkStream.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let read=this._reads[0];if(read.allowLess)this._processReadAllowingLess(read);else if(this._buffered>=read.length)this._processRead(read);else break}if(this._buffers&&!this.writable)this._end()}catch(ex){this.emit("error",ex)}}});var require_interlace=__commonJS(function(exports){var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(width,height){let images=[],xLeftOver=width%8,yLeftOver=height%8,xRepeats=(width-xLeftOver)/8,yRepeats=(height-yLeftOver)/8;for(let i=0;i<imagePasses.length;i++){let pass=imagePasses[i],passWidth=xRepeats*pass.x.length,passHeight=yRepeats*pass.y.length;for(let j=0;j<pass.x.length;j++)if(pass.x[j]<xLeftOver)passWidth++;else break;for(let j=0;j<pass.y.length;j++)if(pass.y[j]<yLeftOver)passHeight++;else break;if(passWidth>0&&passHeight>0)images.push({width:passWidth,height:passHeight,index:i})}return images};exports.getInterlaceIterator=function(width){return function(x,y,pass){let outerXLeftOver=x%imagePasses[pass].x.length,outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver],outerYLeftOver=y%imagePasses[pass].y.length,outerY=(y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver];return outerX*4+outerY*width*4}}});var require_paeth_predictor=__commonJS(function(exports,module){module.exports=function(left,above,upLeft){let paeth=left+above-upLeft,pLeft=Math.abs(paeth-left),pAbove=Math.abs(paeth-above),pUpLeft=Math.abs(paeth-upLeft);if(pLeft<=pAbove&&pLeft<=pUpLeft)return left;if(pAbove<=pUpLeft)return above;return upLeft}});var require_filter_parse=__commonJS(function(exports,module){var interlaceUtils=require_interlace(),paethPredictor=require_paeth_predictor();function getByteWidth(width,bpp,depth){let byteWidth=width*bpp;if(depth!==8)byteWidth=Math.ceil(byteWidth/(8/depth));return byteWidth}var Filter=module.exports=function(bitmapInfo,dependencies){let{width,height,interlace,bpp,depth}=bitmapInfo;if(this.read=dependencies.read,this.write=dependencies.write,this.complete=dependencies.complete,this._imageIndex=0,this._images=[],interlace){let passes=interlaceUtils.getImagePasses(width,height);for(let i=0;i<passes.length;i++)this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}else this._images.push({byteWidth:getByteWidth(width,bpp,depth),height,lineIndex:0});if(depth===8)this._xComparison=bpp;else if(depth===16)this._xComparison=bpp*2;else this._xComparison=1};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}};Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){let lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}};Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f3Up=lastLine?lastLine[x]:0,f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}};Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f4Up=lastLine?lastLine[x]:0,f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0,f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}};Filter.prototype._reverseFilterLine=function(rawData){let filter=rawData[0],unfilteredLine,currentImage=this._images[this._imageIndex],byteWidth=currentImage.byteWidth;if(filter===0)unfilteredLine=rawData.slice(1,byteWidth+1);else switch(unfilteredLine=Buffer.alloc(byteWidth),filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw Error("Unrecognised filter type - "+filter)}if(this.write(unfilteredLine),currentImage.lineIndex++,currentImage.lineIndex>=currentImage.height)this._lastLine=null,this._imageIndex++,currentImage=this._images[this._imageIndex];else this._lastLine=unfilteredLine;if(currentImage)this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var require_filter_parse_async=__commonJS(function(exports,module){var util=__require("util"),ChunkStream=require_chunkstream(),Filter=require_filter_parse(),FilterAsync=module.exports=function(bitmapInfo){ChunkStream.call(this);let buffers=[],that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}}),this._filter.start()};util.inherits(FilterAsync,ChunkStream)});var require_constants=__commonJS(function(exports,module){module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var require_crc=__commonJS(function(exports,module){var crcTable=[];(function(){for(let i=0;i<256;i++){let currentCrc=i;for(let j=0;j<8;j++)if(currentCrc&1)currentCrc=3988292384^currentCrc>>>1;else currentCrc=currentCrc>>>1;crcTable[i]=currentCrc}})();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(data){for(let i=0;i<data.length;i++)this._crc=crcTable[(this._crc^data[i])&255]^this._crc>>>8;return!0};CrcCalculator.prototype.crc32=function(){return this._crc^-1};CrcCalculator.crc32=function(buf){let crc=-1;for(let i=0;i<buf.length;i++)crc=crcTable[(crc^buf[i])&255]^crc>>>8;return crc^-1}});var require_parser=__commonJS(function(exports,module){var constants=require_constants(),CrcCalculator=require_crc(),Parser=module.exports=function(options,dependencies){this._options=options,options.checkCRC=options.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=dependencies.read,this.error=dependencies.error,this.metadata=dependencies.metadata,this.gamma=dependencies.gamma,this.transColor=dependencies.transColor,this.palette=dependencies.palette,this.parsed=dependencies.parsed,this.inflateData=dependencies.inflateData,this.finished=dependencies.finished,this.simpleTransparency=dependencies.simpleTransparency,this.headersFinished=dependencies.headersFinished||function(){}};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Parser.prototype._parseSignature=function(data){let signature=constants.PNG_SIGNATURE;for(let i=0;i<signature.length;i++)if(data[i]!==signature[i]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._parseChunkBegin=function(data){let length=data.readUInt32BE(0),type=data.readUInt32BE(4),name="";for(let i=4;i<8;i++)name+=String.fromCharCode(data[i]);let ancillary=Boolean(data[4]&32);if(!this._hasIHDR&&type!==constants.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new CrcCalculator,this._crc.write(Buffer.from(name)),this._chunks[type])return this._chunks[type](length);if(!ancillary){this.error(Error("Unsupported critical chunk type "+name));return}this.read(length+4,this._skipChunk.bind(this))};Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Parser.prototype._parseChunkEnd=function(data){let fileCrc=data.readInt32BE(0),calcCrc=this._crc.crc32();if(this._options.checkCRC&&calcCrc!==fileCrc){this.error(Error("Crc error - "+fileCrc+" - "+calcCrc));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))};Parser.prototype._parseIHDR=function(data){this._crc.write(data);let width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],colorType=data[9],compr=data[10],filter=data[11],interlace=data[12];if(depth!==8&&depth!==4&&depth!==2&&depth!==1&&depth!==16){this.error(Error("Unsupported bit depth "+depth));return}if(!(colorType in constants.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(compr!==0){this.error(Error("Unsupported compression method"));return}if(filter!==0){this.error(Error("Unsupported filter method"));return}if(interlace!==0&&interlace!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=colorType;let bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width,height,depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp,colorType}),this._handleChunkEnd()};Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))};Parser.prototype._parsePLTE=function(data){this._crc.write(data);let entries=Math.floor(data.length/3);for(let i=0;i<entries;i++)this._palette.push([data[i*3],data[i*3+1],data[i*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Parser.prototype._handleTRNS=function(length){this.simpleTransparency(),this.read(length,this._parseTRNS.bind(this))};Parser.prototype._parseTRNS=function(data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(data.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let i=0;i<data.length;i++)this._palette[i][3]=data[i];this.palette(this._palette)}if(this._colorType===constants.COLORTYPE_GRAYSCALE)this.transColor([data.readUInt16BE(0)]);if(this._colorType===constants.COLORTYPE_COLOR)this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)]);this._handleChunkEnd()};Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))};Parser.prototype._parseGAMA=function(data){this._crc.write(data),this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()};Parser.prototype._handleIDAT=function(length){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-length,this._parseIDAT.bind(this,length))};Parser.prototype._parseIDAT=function(length,data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(data);let leftOverLength=length-data.length;if(leftOverLength>0)this._handleIDAT(leftOverLength);else this._handleChunkEnd()};Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))};Parser.prototype._parseIEND=function(data){if(this._crc.write(data),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var require_bitmapper=__commonJS(function(exports){var interlaceUtils=require_interlace(),pixelBppMapper=[function(){},function(pxData,data,pxPos,rawPos){if(rawPos===data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+1>=data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=data[rawPos+1]},function(pxData,data,pxPos,rawPos){if(rawPos+2>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+3>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=data[rawPos+3]}],pixelBppCustomMapper=[function(){},function(pxData,pixelData,pxPos,maxBit){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=pixelData[1]},function(pxData,pixelData,pxPos,maxBit){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=pixelData[3]}];function bitRetriever(data,depth){let leftOver=[],i=0;function split(){if(i===data.length)throw Error("Ran out of data");let byte=data[i];i++;let byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1;switch(depth){default:throw Error("unrecognised depth");case 16:byte2=data[i],i++,leftOver.push((byte<<8)+byte2);break;case 4:byte2=byte&15,byte1=byte>>4,leftOver.push(byte1,byte2);break;case 2:byte4=byte&3,byte3=byte>>2&3,byte2=byte>>4&3,byte1=byte>>6&3,leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=byte&1,byte7=byte>>1&1,byte6=byte>>2&1,byte5=byte>>3&1,byte4=byte>>4&1,byte3=byte>>5&1,byte2=byte>>6&1,byte1=byte>>7&1,leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8);break}}return{get:function(count){while(leftOver.length<count)split();let returner=leftOver.slice(0,count);return leftOver=leftOver.slice(count),returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length)throw Error("extra data found")}}}function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++)for(let x=0;x<imageWidth;x++){let pxPos=getPxPos(x,y,imagePass);pixelBppMapper[bpp](pxData,data,pxPos,rawPos),rawPos+=bpp}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++){for(let x=0;x<imageWidth;x++){let pixelData=bits.get(bpp),pxPos=getPxPos(x,y,imagePass);pixelBppCustomMapper[bpp](pxData,pixelData,pxPos,maxBit)}bits.resetAfterLine()}}exports.dataToBitMap=function(data,bitmapInfo){let{width,height,depth,bpp,interlace}=bitmapInfo,bits;if(depth!==8)bits=bitRetriever(data,depth);let pxData;if(depth<=8)pxData=Buffer.alloc(width*height*4);else pxData=new Uint16Array(width*height*4);let maxBit=Math.pow(2,depth)-1,rawPos=0,images,getPxPos;if(interlace)images=interlaceUtils.getImagePasses(width,height),getPxPos=interlaceUtils.getInterlaceIterator(width,height);else{let nonInterlacedPxPos=0;getPxPos=function(){let returner=nonInterlacedPxPos;return nonInterlacedPxPos+=4,returner},images=[{width,height}]}for(let imageIndex=0;imageIndex<images.length;imageIndex++)if(depth===8)rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos);else mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit);if(depth===8){if(rawPos!==data.length)throw Error("extra data found")}else bits.end();return pxData}});var require_format_normaliser=__commonJS(function(exports,module){function dePalette(indata,outdata,width,height,palette){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let color=palette[indata[pxPos]];if(!color)throw Error("index "+indata[pxPos]+" not in palette");for(let i=0;i<4;i++)outdata[pxPos+i]=color[i];pxPos+=4}}function replaceTransparentColor(indata,outdata,width,height,transColor){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let makeTrans=!1;if(transColor.length===1){if(transColor[0]===indata[pxPos])makeTrans=!0}else if(transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2])makeTrans=!0;if(makeTrans)for(let i=0;i<4;i++)outdata[pxPos+i]=0;pxPos+=4}}function scaleDepth(indata,outdata,width,height,depth){let maxOutSample=255,maxInSample=Math.pow(2,depth)-1,pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){for(let i=0;i<4;i++)outdata[pxPos+i]=Math.floor(indata[pxPos+i]*maxOutSample/maxInSample+0.5);pxPos+=4}}module.exports=function(indata,imageData,skipRescale=!1){let{depth,width,height,colorType,transColor,palette}=imageData,outdata=indata;if(colorType===3)dePalette(indata,outdata,width,height,palette);else{if(transColor)replaceTransparentColor(indata,outdata,width,height,transColor);if(depth!==8&&!skipRescale){if(depth===16)outdata=Buffer.alloc(width*height*4);scaleDepth(indata,outdata,width,height,depth)}}return outdata}});var require_parser_async=__commonJS(function(exports,module){var util=__require("util"),zlib=__require("zlib"),ChunkStream=require_chunkstream(),FilterAsync=require_filter_parse_async(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser(),ParserAsync=module.exports=function(options){ChunkStream.call(this),this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=options,this.writable=!0,this._parser.start()};util.inherits(ParserAsync,ChunkStream);ParserAsync.prototype._handleError=function(err){if(this.emit("error",err),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ParserAsync.prototype._inflateData=function(data){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let imageSize=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,chunkSize=Math.max(imageSize,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize});let leftToInflate=imageSize,emitError=this.emit.bind(this,"error");this._inflate.on("error",function(err){if(!leftToInflate)return;emitError(err)}),this._filter.on("complete",this._complete.bind(this));let filterWrite=this._filter.write.bind(this._filter);this._inflate.on("data",function(chunk){if(!leftToInflate)return;if(chunk.length>leftToInflate)chunk=chunk.slice(0,leftToInflate);leftToInflate-=chunk.length,filterWrite(chunk)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(data)};ParserAsync.prototype._handleMetaData=function(metaData){this._metaData=metaData,this._bitmapInfo=Object.create(metaData),this._filter=new FilterAsync(this._bitmapInfo)};ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor};ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette};ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ParserAsync.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ParserAsync.prototype._complete=function(filteredData){if(this.errord)return;let normalisedBitmapData;try{let bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo,this._options.skipRescale),bitmapData=null}catch(ex){this._handleError(ex);return}this.emit("parsed",normalisedBitmapData)}});var require_bitpacker=__commonJS(function(exports,module){var constants=require_constants();module.exports=function(dataIn,width,height,options){let outHasAlpha=[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)!==-1;if(options.colorType===options.inputColorType){let bigEndian=function(){let buffer=new ArrayBuffer(2);return new DataView(buffer).setInt16(0,256,!0),new Int16Array(buffer)[0]!==256}();if(options.bitDepth===8||options.bitDepth===16&&bigEndian)return dataIn}let data=options.bitDepth!==16?dataIn:new Uint16Array(dataIn.buffer),maxValue=255,inBpp=constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];if(inBpp===4&&!options.inputHasAlpha)inBpp=3;let outBpp=constants.COLORTYPE_TO_BPP_MAP[options.colorType];if(options.bitDepth===16)maxValue=65535,outBpp*=2;let outData=Buffer.alloc(width*height*outBpp),inIndex=0,outIndex=0,bgColor=options.bgColor||{};if(bgColor.red===void 0)bgColor.red=maxValue;if(bgColor.green===void 0)bgColor.green=maxValue;if(bgColor.blue===void 0)bgColor.blue=maxValue;function getRGBA(){let red,green,blue,alpha=maxValue;switch(options.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:alpha=data[inIndex+3],red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_COLOR:red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_ALPHA:alpha=data[inIndex+1],red=data[inIndex],green=red,blue=red;break;case constants.COLORTYPE_GRAYSCALE:red=data[inIndex],green=red,blue=red;break;default:throw Error("input color type:"+options.inputColorType+" is not supported at present")}if(options.inputHasAlpha){if(!outHasAlpha)alpha/=maxValue,red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),maxValue),green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),maxValue),blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),maxValue)}return{red,green,blue,alpha}}for(let y=0;y<height;y++)for(let x=0;x<width;x++){let rgba=getRGBA(data,inIndex);switch(options.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:if(options.bitDepth===8){if(outData[outIndex]=rgba.red,outData[outIndex+1]=rgba.green,outData[outIndex+2]=rgba.blue,outHasAlpha)outData[outIndex+3]=rgba.alpha}else if(outData.writeUInt16BE(rgba.red,outIndex),outData.writeUInt16BE(rgba.green,outIndex+2),outData.writeUInt16BE(rgba.blue,outIndex+4),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+6);break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:{let grayscale=(rgba.red+rgba.green+rgba.blue)/3;if(options.bitDepth===8){if(outData[outIndex]=grayscale,outHasAlpha)outData[outIndex+1]=rgba.alpha}else if(outData.writeUInt16BE(grayscale,outIndex),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+2);break}default:throw Error("unrecognised color Type "+options.colorType)}inIndex+=inBpp,outIndex+=outBpp}return outData}});var require_filter_pack=__commonJS(function(exports,module){var paethPredictor=require_paeth_predictor();function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++)rawData[rawPos+x]=pxData[pxPos+x]}function filterSumNone(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let i=pxPos;i<length;i++)sum+=Math.abs(pxData[i]);return sum}function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}}function filterSumSub(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum}function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++){let up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}}function filterSumUp(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let x=pxPos;x<length;x++){let up=pxPos>0?pxData[x-byteWidth]:0,val=pxData[x]-up;sum+=Math.abs(val)}return sum}function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}}function filterSumAvg(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum}function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}function filterSumPaeth(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth},filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(pxData,width,height,options,bpp){let filterTypes;if(!("filterType"in options)||options.filterType===-1)filterTypes=[0,1,2,3,4];else if(typeof options.filterType==="number")filterTypes=[options.filterType];else throw Error("unrecognised filter types");if(options.bitDepth===16)bpp*=2;let byteWidth=width*bpp,rawPos=0,pxPos=0,rawData=Buffer.alloc((byteWidth+1)*height),sel=filterTypes[0];for(let y=0;y<height;y++){if(filterTypes.length>1){let min=1/0;for(let i=0;i<filterTypes.length;i++){let sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);if(sum<min)sel=filterTypes[i],min=sum}}rawData[rawPos]=sel,rawPos++,filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp),rawPos+=byteWidth,pxPos+=byteWidth}return rawData}});var require_packer=__commonJS(function(exports,module){var constants=require_constants(),CrcStream=require_crc(),bitPacker=require_bitpacker(),filter=require_filter_pack(),zlib=__require("zlib"),Packer=module.exports=function(options){if(this._options=options,options.deflateChunkSize=options.deflateChunkSize||32768,options.deflateLevel=options.deflateLevel!=null?options.deflateLevel:9,options.deflateStrategy=options.deflateStrategy!=null?options.deflateStrategy:3,options.inputHasAlpha=options.inputHasAlpha!=null?options.inputHasAlpha:!0,options.deflateFactory=options.deflateFactory||zlib.createDeflate,options.bitDepth=options.bitDepth||8,options.colorType=typeof options.colorType==="number"?options.colorType:constants.COLORTYPE_COLOR_ALPHA,options.inputColorType=typeof options.inputColorType==="number"?options.inputColorType:constants.COLORTYPE_COLOR_ALPHA,[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)===-1)throw Error("option color type:"+options.colorType+" is not supported at present");if([constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.inputColorType)===-1)throw Error("option input color type:"+options.inputColorType+" is not supported at present");if(options.bitDepth!==8&&options.bitDepth!==16)throw Error("option bit depth:"+options.bitDepth+" is not supported at present")};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Packer.prototype.filterData=function(data,width,height){let packedData=bitPacker(data,width,height,this._options),bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(packedData,width,height,this._options,bpp)};Packer.prototype._packChunk=function(type,data){let len=data?data.length:0,buf=Buffer.alloc(len+12);if(buf.writeUInt32BE(len,0),buf.writeUInt32BE(type,4),data)data.copy(buf,8);return buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4),buf};Packer.prototype.packGAMA=function(gamma){let buf=Buffer.alloc(4);return buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,buf)};Packer.prototype.packIHDR=function(width,height){let buf=Buffer.alloc(13);return buf.writeUInt32BE(width,0),buf.writeUInt32BE(height,4),buf[8]=this._options.bitDepth,buf[9]=this._options.colorType,buf[10]=0,buf[11]=0,buf[12]=0,this._packChunk(constants.TYPE_IHDR,buf)};Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)};Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)}});var require_packer_async=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),constants=require_constants(),Packer=require_packer(),PackerAsync=module.exports=function(opt){Stream.call(this);let options=opt||{};this._packer=new Packer(options),this._deflate=this._packer.createDeflate(),this.readable=!0};util.inherits(PackerAsync,Stream);PackerAsync.prototype.pack=function(data,width,height,gamma){if(this.emit("data",Buffer.from(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(width,height)),gamma)this.emit("data",this._packer.packGAMA(gamma));let filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(filteredData)}});var require_sync_inflate=__commonJS(function(exports,module){var assert=__require("assert").ok,zlib=__require("zlib"),util=__require("util"),kMaxLength=__require("buffer").kMaxLength;function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);if(opts&&opts.chunkSize<zlib.Z_MIN_CHUNK)opts.chunkSize=zlib.Z_MIN_CHUNK;if(zlib.Inflate.call(this,opts),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,opts&&opts.maxLength!=null)this._maxLength=opts.maxLength}function createInflate(opts){return new Inflate(opts)}function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}Inflate.prototype._processChunk=function(chunk,flushFlag,asyncCb){if(typeof asyncCb==="function")return zlib.Inflate._processChunk.call(this,chunk,flushFlag,asyncCb);let self=this,availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,leftToInflate=this._maxLength,inOff=0,buffers=[],nread=0,error;this.on("error",function(err){error=err});function handleChunk(availInAfter,availOutAfter){if(self._hadError)return;let have=availOutBefore-availOutAfter;if(assert(have>=0,"have should not go down"),have>0){let out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,out.length>leftToInflate)out=out.slice(0,leftToInflate);if(buffers.push(out),nread+=out.length,leftToInflate-=out.length,leftToInflate===0)return!1}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer.allocUnsafe(self._chunkSize);if(availOutAfter===0)return inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!0;return!1}assert(this._handle,"zlib binding closed");let res;do res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore),res=res||this._writeState;while(!this._hadError&&handleChunk(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)throw _close(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");let buf=Buffer.concat(buffers,nread);return _close(this),buf};util.inherits(Inflate,zlib.Inflate);function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=Buffer.from(buffer);if(!(buffer instanceof Buffer))throw TypeError("Not a string or buffer");let flushFlag=engine._finishFlushFlag;if(flushFlag==null)flushFlag=zlib.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function inflateSync(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)}module.exports=exports=inflateSync;exports.Inflate=Inflate;exports.createInflate=createInflate;exports.inflateSync=inflateSync});var require_sync_reader=__commonJS(function(exports,module){var SyncReader=module.exports=function(buffer){this._buffer=buffer,this._reads=[]};SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})};SyncReader.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let read=this._reads[0];if(this._buffer.length&&(this._buffer.length>=read.length||read.allowLess)){this._reads.shift();let buf=this._buffer;this._buffer=buf.slice(read.length),read.func.call(this,buf.slice(0,read.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var require_filter_parse_sync=__commonJS(function(exports){var SyncReader=require_sync_reader(),Filter=require_filter_parse();exports.process=function(inBuffer,bitmapInfo){let outBuffers=[],reader=new SyncReader(inBuffer);return new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}}).start(),reader.process(),Buffer.concat(outBuffers)}});var require_parser_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib"),inflateSync=require_sync_inflate();if(!zlib.deflateSync)hasSyncZlib=!1;var SyncReader=require_sync_reader(),FilterSync=require_filter_parse_sync(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser();module.exports=function(buffer,options){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let err;function handleError(_err_){err=_err_}let metaData;function handleMetaData(_metaData_){metaData=_metaData_}function handleTransColor(transColor){metaData.transColor=transColor}function handlePalette(palette){metaData.palette=palette}function handleSimpleTransparency(){metaData.alpha=!0}let gamma;function handleGamma(_gamma_){gamma=_gamma_}let inflateDataList=[];function handleInflateData(inflatedData){inflateDataList.push(inflatedData)}let reader=new SyncReader(buffer);if(new Parser(options,{read:reader.read.bind(reader),error:handleError,metadata:handleMetaData,gamma:handleGamma,palette:handlePalette,transColor:handleTransColor,inflateData:handleInflateData,simpleTransparency:handleSimpleTransparency}).start(),reader.process(),err)throw err;let inflateData=Buffer.concat(inflateDataList);inflateDataList.length=0;let inflatedData;if(metaData.interlace)inflatedData=zlib.inflateSync(inflateData);else{let imageSize=((metaData.width*metaData.bpp*metaData.depth+7>>3)+1)*metaData.height;inflatedData=inflateSync(inflateData,{chunkSize:imageSize,maxLength:imageSize})}if(inflateData=null,!inflatedData||!inflatedData.length)throw Error("bad png - invalid inflate data response");let unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;let bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;let normalisedBitmapData=formatNormaliser(bitmapData,metaData,options.skipRescale);return metaData.data=normalisedBitmapData,metaData.gamma=gamma||0,metaData}});var require_packer_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib");if(!zlib.deflateSync)hasSyncZlib=!1;var constants=require_constants(),Packer=require_packer();module.exports=function(metaData,opt){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let packer=new Packer(opt||{}),chunks=[];if(chunks.push(Buffer.from(constants.PNG_SIGNATURE)),chunks.push(packer.packIHDR(metaData.width,metaData.height)),metaData.gamma)chunks.push(packer.packGAMA(metaData.gamma));let filteredData=packer.filterData(metaData.data,metaData.width,metaData.height),compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());if(filteredData=null,!compressedData||!compressedData.length)throw Error("bad png - invalid compressed data response");return chunks.push(packer.packIDAT(compressedData)),chunks.push(packer.packIEND()),Buffer.concat(chunks)}});var require_png_sync=__commonJS(function(exports){var parse=require_parser_sync(),pack=require_packer_sync();exports.read=function(buffer,options){return parse(buffer,options||{})};exports.write=function(png,options){return pack(png,options)}});var require_png=__commonJS(function(exports){var util=__require("util"),Stream=__require("stream"),Parser=require_parser_async(),Packer=require_packer_async(),PNGSync=require_png_sync(),PNG=exports.PNG=function(options){if(Stream.call(this),options=options||{},this.width=options.width|0,this.height=options.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,options.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(options),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(data){this.data=data,this.emit("parsed",data)}.bind(this)),this._packer=new Packer(options),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream);PNG.sync=PNGSync;PNG.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};PNG.prototype.parse=function(data,callback){if(callback){let onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError),this.data=parsedData,callback(null,this)}.bind(this),onError=function(err){this.removeListener("parsed",onParsed),callback(err,null)}.bind(this),this.once("parsed",onParsed),this.once("error",onError)}return this.end(data),this};PNG.prototype.write=function(data){return this._parser.write(data),!0};PNG.prototype.end=function(data){this._parser.end(data)};PNG.prototype._metadata=function(metadata){this.width=metadata.width,this.height=metadata.height,this.emit("metadata",metadata)};PNG.prototype._gamma=function(gamma){this.gamma=gamma};PNG.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){if(srcX|=0,srcY|=0,width|=0,height|=0,deltaX|=0,deltaY|=0,srcX>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height)throw Error("bitblt reading outside image");if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height)throw Error("bitblt writing outside image");for(let y=0;y<height;y++)src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)};PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){return PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY),this};PNG.adjustGamma=function(src){if(src.gamma){for(let y=0;y<src.height;y++)for(let x=0;x<src.width;x++){let idx=src.width*y+x<<2;for(let i=0;i<3;i++){let sample=src.data[idx+i]/255;sample=Math.pow(sample,0.45454545454545453/src.gamma),src.data[idx+i]=Math.round(sample*255)}}src.gamma=0}};PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)}});var require_react_development=__commonJS(function(exports,module){(function(){function defineDeprecationWarning(methodName,info){Object.defineProperty(Component.prototype,methodName,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",info[0],info[1])}})}function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}function warnNoop(publicInstance,callerName){publicInstance=(publicInstance=publicInstance.constructor)&&(publicInstance.displayName||publicInstance.name)||"ReactClass";var warningKey=publicInstance+"."+callerName;didWarnStateUpdateForUnmountedComponent[warningKey]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",callerName,publicInstance),didWarnStateUpdateForUnmountedComponent[warningKey]=!0)}function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function noop(){}function testStringCoercion(value){return""+value}function checkKeyStringCoercion(value){try{testStringCoercion(value);var JSCompiler_inline_result=!1}catch(e){JSCompiler_inline_result=!0}if(JSCompiler_inline_result){JSCompiler_inline_result=console;var JSCompiler_temp_const=JSCompiler_inline_result.error,JSCompiler_inline_result$jscomp$0=typeof Symbol==="function"&&Symbol.toStringTag&&value[Symbol.toStringTag]||value.constructor.name||"Object";return JSCompiler_temp_const.call(JSCompiler_inline_result,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",JSCompiler_inline_result$jscomp$0),testStringCoercion(value)}}function getComponentNameFromType(type){if(type==null)return null;if(typeof type==="function")return type.$$typeof===REACT_CLIENT_REFERENCE?null:type.displayName||type.name||null;if(typeof type==="string")return type;switch(type){case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_ACTIVITY_TYPE:return"Activity"}if(typeof type==="object")switch(typeof type.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),type.$$typeof){case REACT_PORTAL_TYPE:return"Portal";case REACT_CONTEXT_TYPE:return type.displayName||"Context";case REACT_CONSUMER_TYPE:return(type._context.displayName||"Context")+".Consumer";case REACT_FORWARD_REF_TYPE:var innerType=type.render;return type=type.displayName,type||(type=innerType.displayName||innerType.name||"",type=type!==""?"ForwardRef("+type+")":"ForwardRef"),type;case REACT_MEMO_TYPE:return innerType=type.displayName||null,innerType!==null?innerType:getComponentNameFromType(type.type)||"Memo";case REACT_LAZY_TYPE:innerType=type._payload,type=type._init;try{return getComponentNameFromType(type(innerType))}catch(x){}}return null}function getTaskName(type){if(type===REACT_FRAGMENT_TYPE)return"<>";if(typeof type==="object"&&type!==null&&type.$$typeof===REACT_LAZY_TYPE)return"<...>";try{var name=getComponentNameFromType(type);return name?"<"+name+">":"<...>"}catch(x){return"<...>"}}function getOwner(){var dispatcher=ReactSharedInternals.A;return dispatcher===null?null:dispatcher.getOwner()}function UnknownOwner(){return Error("react-stack-top-frame")}function hasValidKey(config){if(hasOwnProperty.call(config,"key")){var getter=Object.getOwnPropertyDescriptor(config,"key").get;if(getter&&getter.isReactWarning)return!1}return config.key!==void 0}function defineKeyPropWarningGetter(props,displayName){function warnAboutAccessingKey(){specialPropKeyWarningShown||(specialPropKeyWarningShown=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",displayName))}warnAboutAccessingKey.isReactWarning=!0,Object.defineProperty(props,"key",{get:warnAboutAccessingKey,configurable:!0})}function elementRefGetterWithDeprecationWarning(){var componentName=getComponentNameFromType(this.type);return didWarnAboutElementRef[componentName]||(didWarnAboutElementRef[componentName]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),componentName=this.props.ref,componentName!==void 0?componentName:null}function ReactElement(type,key,props,owner,debugStack,debugTask){var refProp=props.ref;return type={$$typeof:REACT_ELEMENT_TYPE,type,key,props,_owner:owner},(refProp!==void 0?refProp:null)!==null?Object.defineProperty(type,"ref",{enumerable:!1,get:elementRefGetterWithDeprecationWarning}):Object.defineProperty(type,"ref",{enumerable:!1,value:null}),type._store={},Object.defineProperty(type._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(type,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(type,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:debugStack}),Object.defineProperty(type,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:debugTask}),Object.freeze&&(Object.freeze(type.props),Object.freeze(type)),type}function cloneAndReplaceKey(oldElement,newKey){return newKey=ReactElement(oldElement.type,newKey,oldElement.props,oldElement._owner,oldElement._debugStack,oldElement._debugTask),oldElement._store&&(newKey._store.validated=oldElement._store.validated),newKey}function validateChildKeys(node){isValidElement(node)?node._store&&(node._store.validated=1):typeof node==="object"&&node!==null&&node.$$typeof===REACT_LAZY_TYPE&&(node._payload.status==="fulfilled"?isValidElement(node._payload.value)&&node._payload.value._store&&(node._payload.value._store.validated=1):node._store&&(node._store.validated=1))}function isValidElement(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}function getElementKey(element,index){return typeof element==="object"&&element!==null&&element.key!=null?(checkKeyStringCoercion(element.key),escape(""+element.key)):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch(typeof thenable.status==="string"?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){thenable.status==="pending"&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){thenable.status==="pending"&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;if(type==="undefined"||type==="boolean")children=null;var invokeCallback=!1;if(children===null)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return invokeCallback=children._init,mapIntoArray(invokeCallback(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback){invokeCallback=children,callback=callback(invokeCallback);var childKey=nameSoFar===""?"."+getElementKey(invokeCallback,0):nameSoFar;return isArrayImpl(callback)?(escapedPrefix="",childKey!=null&&(escapedPrefix=childKey.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):callback!=null&&(isValidElement(callback)&&(callback.key!=null&&(invokeCallback&&invokeCallback.key===callback.key||checkKeyStringCoercion(callback.key)),escapedPrefix=cloneAndReplaceKey(callback,escapedPrefix+(callback.key==null||invokeCallback&&invokeCallback.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+childKey),nameSoFar!==""&&invokeCallback!=null&&isValidElement(invokeCallback)&&invokeCallback.key==null&&invokeCallback._store&&!invokeCallback._store.validated&&(escapedPrefix._store.validated=2),callback=escapedPrefix),array.push(callback)),1}if(invokeCallback=0,childKey=nameSoFar===""?".":nameSoFar+":",isArrayImpl(children))for(var i=0;i<children.length;i++)nameSoFar=children[i],type=childKey+getElementKey(nameSoFar,i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(i=getIteratorFn(children),typeof i==="function")for(i===children.entries&&(didWarnAboutMaps||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),didWarnAboutMaps=!0),children=i.call(children),i=0;!(nameSoFar=children.next()).done;)nameSoFar=nameSoFar.value,type=childKey+getElementKey(nameSoFar,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(type==="object"){if(typeof children.then==="function")return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw array=String(children),Error("Objects are not valid as a React child (found: "+(array==="[object Object]"?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(children==null)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(payload._status===-1){var ioInfo=payload._ioInfo;ioInfo!=null&&(ioInfo.start=ioInfo.end=performance.now()),ioInfo=payload._result;var thenable=ioInfo();if(thenable.then(function(moduleObject){if(payload._status===0||payload._status===-1){payload._status=1,payload._result=moduleObject;var _ioInfo=payload._ioInfo;_ioInfo!=null&&(_ioInfo.end=performance.now()),thenable.status===void 0&&(thenable.status="fulfilled",thenable.value=moduleObject)}},function(error){if(payload._status===0||payload._status===-1){payload._status=2,payload._result=error;var _ioInfo2=payload._ioInfo;_ioInfo2!=null&&(_ioInfo2.end=performance.now()),thenable.status===void 0&&(thenable.status="rejected",thenable.reason=error)}}),ioInfo=payload._ioInfo,ioInfo!=null){ioInfo.value=thenable;var displayName=thenable.displayName;typeof displayName==="string"&&(ioInfo.name=displayName)}payload._status===-1&&(payload._status=0,payload._result=thenable)}if(payload._status===1)return ioInfo=payload._result,ioInfo===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
3
3
|
|
|
4
4
|
Your code should look like:
|
|
5
5
|
const MyComponent = lazy(() => import('./MyComponent'))
|
|
@@ -76,7 +76,7 @@ Check the top-level render call using <`+componentName+">."),componentName="",di
|
|
|
76
76
|
`,VALID_TAG_REGEX=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,validatedTagCache=new Map,endTagCache=new Map,shellTimeRuntimeScript="requestAnimationFrame(function(){$RT=performance.now()});",placeholder1='<template id="',placeholder2='"></template>',startCompletedSuspenseBoundary="<!--$-->",startPendingSuspenseBoundary1='<!--$?--><template id="',startPendingSuspenseBoundary2='"></template>',startClientRenderedSuspenseBoundary="<!--$!-->",endSuspenseBoundary="<!--/$-->",clientRenderedSuspenseBoundaryError1="<template",clientRenderedSuspenseBoundaryErrorAttrInterstitial='"',clientRenderedSuspenseBoundaryError1A=' data-dgst="',clientRenderedSuspenseBoundaryError1B=' data-msg="',clientRenderedSuspenseBoundaryError1C=' data-stck="',clientRenderedSuspenseBoundaryError1D=' data-cstck="',clientRenderedSuspenseBoundaryError2="></template>",startSegmentHTML='<div hidden id="',startSegmentHTML2='">',endSegmentHTML="</div>",startSegmentSVG='<svg aria-hidden="true" style="display:none" id="',startSegmentSVG2='">',endSegmentSVG="</svg>",startSegmentMathML='<math aria-hidden="true" style="display:none" id="',startSegmentMathML2='">',endSegmentMathML="</math>",startSegmentTable='<table hidden id="',startSegmentTable2='">',endSegmentTable="</table>",startSegmentTableBody='<table hidden><tbody id="',startSegmentTableBody2='">',endSegmentTableBody="</tbody></table>",startSegmentTableRow='<table hidden><tr id="',startSegmentTableRow2='">',endSegmentTableRow="</tr></table>",startSegmentColGroup='<table hidden><colgroup id="',startSegmentColGroup2='">',endSegmentColGroup="</colgroup></table>",completeSegmentScript1Full='$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("',completeSegmentScript1Partial='$RS("',completeSegmentScript2='","',completeSegmentScriptEnd='")</script>',completeBoundaryScriptFunctionOnly=`$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};
|
|
77
77
|
$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};`,completeBoundaryScript1Partial='$RC("',completeBoundaryWithStylesScript1FullPartial=`$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=
|
|
78
78
|
"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=
|
|
79
|
-
"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("`,completeBoundaryWithStylesScript1Partial='$RR("',completeBoundaryScript2='","',completeBoundaryScript3a='",',completeBoundaryScript3b='"',completeBoundaryScriptEnd=")</script>",clientRenderScriptFunctionOnly='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};',clientRenderScript1Full='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("',clientRenderScript1Partial='$RX("',clientRenderScript1A='"',clientRenderErrorScriptArgInterstitial=",",clientRenderScriptEnd=")</script>",regexForJSStringsInInstructionScripts=/[<\u2028\u2029]/g,regexForJSStringsInScripts=/[&><\u2028\u2029]/g,lateStyleTagResourceOpen1=' media="not all" data-precedence="',lateStyleTagResourceOpen2='" data-href="',lateStyleTagResourceOpen3='">',lateStyleTagTemplateClose="</style>",currentlyRenderingBoundaryHasStylesToHoist=!1,destinationHasCapacity=!0,stylesheetFlushingQueue=[],styleTagResourceOpen1=' data-precedence="',styleTagResourceOpen2='" data-href="',spaceSeparator=" ",styleTagResourceOpen3='">',styleTagResourceClose="</style>",completedShellIdAttributeStart=' id="',arrayFirstOpenBracket="[",arraySubsequentOpenBracket=",[",arrayInterstitial=",",arrayCloseBracket="]",PENDING$1=0,PRELOADED=1,PREAMBLE=2,LATE=3,regexForHrefInLinkHeaderURLContext=/[<>\r\n]/g,regexForLinkHeaderQuotedParamValueContext=/["';,\r\n]/g,doctypeChunk="",bind=Function.prototype.bind,REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference"),emptyContextObject={};Object.freeze(emptyContextObject);var rendererSigil={},currentActiveSnapshot=null,didWarnAboutNoopUpdateForComponent={},didWarnAboutDeprecatedWillMount={},didWarnAboutUninitializedState=new Set,didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set,didWarnAboutLegacyLifecyclesAndDerivedState=new Set,didWarnAboutDirectlyAssigningPropsToState=new Set,didWarnAboutUndefinedDerivedState=new Set,didWarnAboutContextTypes$1=new Set,didWarnAboutChildContextTypes=new Set,didWarnAboutInvalidateContextType=new Set,didWarnOnInvalidCallback=new Set,classComponentUpdater={enqueueSetState:function(inst,payload,callback){var internals=inst._reactInternals;internals.queue===null?warnNoop(inst,"setState"):(internals.queue.push(payload),callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback))},enqueueReplaceState:function(inst,payload,callback){inst=inst._reactInternals,inst.replace=!0,inst.queue=[payload],callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)},enqueueForceUpdate:function(inst,callback){inst._reactInternals.queue===null?warnNoop(inst,"forceUpdate"):callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)}},emptyTreeContext={id:1,overflow:""},clz32=Math.clz32?Math.clz32:clz32Fallback,{log,LN2}=Math,SuspenseException=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."),suspendedThenable=null,objectIs=typeof Object.is==="function"?Object.is:is,currentlyRenderingComponent=null,currentlyRenderingTask=null,currentlyRenderingRequest=null,currentlyRenderingKeyPath=null,firstWorkInProgressHook=null,workInProgressHook=null,isReRender=!1,didScheduleRenderPhaseUpdate=!1,localIdCounter=0,actionStateCounter=0,actionStateMatchingIndex=-1,thenableIndexCounter=0,thenableState=null,renderPhaseUpdates=null,numberOfReRenders=0,isInHookUserCodeInDev=!1,currentHookNameInDev,HooksDispatcher={readContext,use:function(usable){if(usable!==null&&typeof usable==="object"){if(typeof usable.then==="function")return unwrapThenable(usable);if(usable.$$typeof===REACT_CONTEXT_TYPE)return readContext(usable)}throw Error("An unsupported type was passed to use(): "+String(usable))},useContext:function(context){return currentHookNameInDev="useContext",resolveCurrentlyRenderingComponent(),context._currentValue2},useMemo,useReducer,useRef:function(initialValue){currentlyRenderingComponent=resolveCurrentlyRenderingComponent(),workInProgressHook=createWorkInProgressHook();var previousRef=workInProgressHook.memoizedState;return previousRef===null?(initialValue={current:initialValue},Object.seal(initialValue),workInProgressHook.memoizedState=initialValue):previousRef},useState:function(initialState){return currentHookNameInDev="useState",useReducer(basicStateReducer,initialState)},useInsertionEffect:noop,useLayoutEffect:noop,useCallback:function(callback,deps){return useMemo(function(){return callback},deps)},useImperativeHandle:noop,useEffect:noop,useDebugValue:noop,useDeferredValue:function(value,initialValue){return resolveCurrentlyRenderingComponent(),initialValue!==void 0?initialValue:value},useTransition:function(){return resolveCurrentlyRenderingComponent(),[!1,unsupportedStartTransition]},useId:function(){var treeId=currentlyRenderingTask.treeContext,overflow=treeId.overflow;treeId=treeId.id,treeId=(treeId&~(1<<32-clz32(treeId)-1)).toString(32)+overflow;var resumableState=currentResumableState;if(resumableState===null)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");return overflow=localIdCounter++,treeId="_"+resumableState.idPrefix+"R_"+treeId,0<overflow&&(treeId+="H"+overflow.toString(32)),treeId+"_"},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){if(getServerSnapshot===void 0)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");return getServerSnapshot()},useOptimistic:function(passthrough){return resolveCurrentlyRenderingComponent(),[passthrough,unsupportedSetOptimisticState]},useActionState,useFormState:useActionState,useHostTransitionStatus:function(){return resolveCurrentlyRenderingComponent(),NotPending},useMemoCache:function(size){for(var data=Array(size),i=0;i<size;i++)data[i]=REACT_MEMO_CACHE_SENTINEL;return data},useCacheRefresh:function(){return unsupportedRefresh},useEffectEvent:function(){return throwOnUseEffectEventCall}},currentResumableState=null,currentTaskInDEV=null,DefaultAsyncDispatcher={getCacheForType:function(){throw Error("Not implemented.")},cacheSignal:function(){throw Error("Not implemented.")},getOwner:function(){return currentTaskInDEV===null?null:currentTaskInDEV.componentStack}},disabledDepth=0,prevLog,prevInfo,prevWarn,prevError,prevGroup,prevGroupCollapsed,prevGroupEnd;disabledLog.__reactDisabledLog=!0;var prefix,suffix,reentry=!1,componentFrameCache=new(typeof WeakMap==="function"?WeakMap:Map),callComponent={react_stack_bottom_frame:function(Component,props,secondArg){return Component(props,secondArg)}},callComponentInDEV=callComponent.react_stack_bottom_frame.bind(callComponent),callRender={react_stack_bottom_frame:function(instance){return instance.render()}},callRenderInDEV=callRender.react_stack_bottom_frame.bind(callRender),callLazyInit={react_stack_bottom_frame:function(lazy){var init=lazy._init;return init(lazy._payload)}},callLazyInitInDEV=callLazyInit.react_stack_bottom_frame.bind(callLazyInit),lastResetTime=0;if(typeof performance==="object"&&typeof performance.now==="function")var localPerformance=performance,getCurrentTime=function(){return localPerformance.now()};else{var localDate=Date;getCurrentTime=function(){return localDate.now()}}var CLIENT_RENDERED=4,PENDING=0,COMPLETED=1,FLUSHED=2,ABORTED=3,ERRORED=4,POSTPONED=5,CLOSED=14,currentRequest=null,didWarnAboutBadClass={},didWarnAboutContextTypes={},didWarnAboutContextTypeOnFunctionComponent={},didWarnAboutGetDerivedStateOnFunctionComponent={},didWarnAboutReassigningProps=!1,didWarnAboutGenerators=!1,didWarnAboutMaps=!1,flushedByteSize=0,flushingPartialBoundaries=!1;exports.renderToStaticMarkup=function(children,options){return renderToStringImpl(children,options,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.renderToString=function(children,options){return renderToStringImpl(children,options,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.version="19.2.8"})()});import{existsSync,readdirSync}from"fs";import{join}from"path";var package_default={name:"@velloo/renderer",version:"0.1.0",license:"Apache-2.0",private:!0,type:"module",description:"Headless renderer: design JSON \u2192 HTML + screenshot",exports:{".":"./src/index.ts","./iframe-protocol":"./src/iframe-protocol.ts"},dependencies:{"@velloo/provider":"workspace:*","@velloo/schema":"workspace:*",pixelmatch:"7.2.0",pngjs:"7.0.0",react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@types/pngjs":"6.0.5","@types/react":"19.2.18","@types/react-dom":"19.2.7","@velloo/shadcn-snapshot":"workspace:*",playwright:"1.62.1","playwright-core":"1.62.1"}};var PLAYWRIGHT_VERSION=package_default.devDependencies["playwright-core"],PLAYWRIGHT_PIN=`playwright@${PLAYWRIGHT_VERSION}`,CHROMIUM_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium","--only-shell"],CHROMIUM_INSTALL_CMD="velloo browser install",CHROMIUM_FULL_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium"],CHROMIUM_FULL_INSTALL_CMD="velloo browser install --full",CHROMIUM_DEPS_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install-deps","chromium"],CHROMIUM_DEPS_INSTALL_CMD="velloo browser install --with-deps",INSTALL_HINT=`Velloo screenshots need a headless browser. Install it once with:
|
|
79
|
+
"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("`,completeBoundaryWithStylesScript1Partial='$RR("',completeBoundaryScript2='","',completeBoundaryScript3a='",',completeBoundaryScript3b='"',completeBoundaryScriptEnd=")</script>",clientRenderScriptFunctionOnly='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};',clientRenderScript1Full='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("',clientRenderScript1Partial='$RX("',clientRenderScript1A='"',clientRenderErrorScriptArgInterstitial=",",clientRenderScriptEnd=")</script>",regexForJSStringsInInstructionScripts=/[<\u2028\u2029]/g,regexForJSStringsInScripts=/[&><\u2028\u2029]/g,lateStyleTagResourceOpen1=' media="not all" data-precedence="',lateStyleTagResourceOpen2='" data-href="',lateStyleTagResourceOpen3='">',lateStyleTagTemplateClose="</style>",currentlyRenderingBoundaryHasStylesToHoist=!1,destinationHasCapacity=!0,stylesheetFlushingQueue=[],styleTagResourceOpen1=' data-precedence="',styleTagResourceOpen2='" data-href="',spaceSeparator=" ",styleTagResourceOpen3='">',styleTagResourceClose="</style>",completedShellIdAttributeStart=' id="',arrayFirstOpenBracket="[",arraySubsequentOpenBracket=",[",arrayInterstitial=",",arrayCloseBracket="]",PENDING$1=0,PRELOADED=1,PREAMBLE=2,LATE=3,regexForHrefInLinkHeaderURLContext=/[<>\r\n]/g,regexForLinkHeaderQuotedParamValueContext=/["';,\r\n]/g,doctypeChunk="",bind=Function.prototype.bind,REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference"),emptyContextObject={};Object.freeze(emptyContextObject);var rendererSigil={},currentActiveSnapshot=null,didWarnAboutNoopUpdateForComponent={},didWarnAboutDeprecatedWillMount={},didWarnAboutUninitializedState=new Set,didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set,didWarnAboutLegacyLifecyclesAndDerivedState=new Set,didWarnAboutDirectlyAssigningPropsToState=new Set,didWarnAboutUndefinedDerivedState=new Set,didWarnAboutContextTypes$1=new Set,didWarnAboutChildContextTypes=new Set,didWarnAboutInvalidateContextType=new Set,didWarnOnInvalidCallback=new Set,classComponentUpdater={enqueueSetState:function(inst,payload,callback){var internals=inst._reactInternals;internals.queue===null?warnNoop(inst,"setState"):(internals.queue.push(payload),callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback))},enqueueReplaceState:function(inst,payload,callback){inst=inst._reactInternals,inst.replace=!0,inst.queue=[payload],callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)},enqueueForceUpdate:function(inst,callback){inst._reactInternals.queue===null?warnNoop(inst,"forceUpdate"):callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)}},emptyTreeContext={id:1,overflow:""},clz32=Math.clz32?Math.clz32:clz32Fallback,{log,LN2}=Math,SuspenseException=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."),suspendedThenable=null,objectIs=typeof Object.is==="function"?Object.is:is,currentlyRenderingComponent=null,currentlyRenderingTask=null,currentlyRenderingRequest=null,currentlyRenderingKeyPath=null,firstWorkInProgressHook=null,workInProgressHook=null,isReRender=!1,didScheduleRenderPhaseUpdate=!1,localIdCounter=0,actionStateCounter=0,actionStateMatchingIndex=-1,thenableIndexCounter=0,thenableState=null,renderPhaseUpdates=null,numberOfReRenders=0,isInHookUserCodeInDev=!1,currentHookNameInDev,HooksDispatcher={readContext,use:function(usable){if(usable!==null&&typeof usable==="object"){if(typeof usable.then==="function")return unwrapThenable(usable);if(usable.$$typeof===REACT_CONTEXT_TYPE)return readContext(usable)}throw Error("An unsupported type was passed to use(): "+String(usable))},useContext:function(context){return currentHookNameInDev="useContext",resolveCurrentlyRenderingComponent(),context._currentValue2},useMemo,useReducer,useRef:function(initialValue){currentlyRenderingComponent=resolveCurrentlyRenderingComponent(),workInProgressHook=createWorkInProgressHook();var previousRef=workInProgressHook.memoizedState;return previousRef===null?(initialValue={current:initialValue},Object.seal(initialValue),workInProgressHook.memoizedState=initialValue):previousRef},useState:function(initialState){return currentHookNameInDev="useState",useReducer(basicStateReducer,initialState)},useInsertionEffect:noop,useLayoutEffect:noop,useCallback:function(callback,deps){return useMemo(function(){return callback},deps)},useImperativeHandle:noop,useEffect:noop,useDebugValue:noop,useDeferredValue:function(value,initialValue){return resolveCurrentlyRenderingComponent(),initialValue!==void 0?initialValue:value},useTransition:function(){return resolveCurrentlyRenderingComponent(),[!1,unsupportedStartTransition]},useId:function(){var treeId=currentlyRenderingTask.treeContext,overflow=treeId.overflow;treeId=treeId.id,treeId=(treeId&~(1<<32-clz32(treeId)-1)).toString(32)+overflow;var resumableState=currentResumableState;if(resumableState===null)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");return overflow=localIdCounter++,treeId="_"+resumableState.idPrefix+"R_"+treeId,0<overflow&&(treeId+="H"+overflow.toString(32)),treeId+"_"},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){if(getServerSnapshot===void 0)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");return getServerSnapshot()},useOptimistic:function(passthrough){return resolveCurrentlyRenderingComponent(),[passthrough,unsupportedSetOptimisticState]},useActionState,useFormState:useActionState,useHostTransitionStatus:function(){return resolveCurrentlyRenderingComponent(),NotPending},useMemoCache:function(size){for(var data=Array(size),i=0;i<size;i++)data[i]=REACT_MEMO_CACHE_SENTINEL;return data},useCacheRefresh:function(){return unsupportedRefresh},useEffectEvent:function(){return throwOnUseEffectEventCall}},currentResumableState=null,currentTaskInDEV=null,DefaultAsyncDispatcher={getCacheForType:function(){throw Error("Not implemented.")},cacheSignal:function(){throw Error("Not implemented.")},getOwner:function(){return currentTaskInDEV===null?null:currentTaskInDEV.componentStack}},disabledDepth=0,prevLog,prevInfo,prevWarn,prevError,prevGroup,prevGroupCollapsed,prevGroupEnd;disabledLog.__reactDisabledLog=!0;var prefix,suffix,reentry=!1,componentFrameCache=new(typeof WeakMap==="function"?WeakMap:Map),callComponent={react_stack_bottom_frame:function(Component,props,secondArg){return Component(props,secondArg)}},callComponentInDEV=callComponent.react_stack_bottom_frame.bind(callComponent),callRender={react_stack_bottom_frame:function(instance){return instance.render()}},callRenderInDEV=callRender.react_stack_bottom_frame.bind(callRender),callLazyInit={react_stack_bottom_frame:function(lazy){var init=lazy._init;return init(lazy._payload)}},callLazyInitInDEV=callLazyInit.react_stack_bottom_frame.bind(callLazyInit),lastResetTime=0;if(typeof performance==="object"&&typeof performance.now==="function")var localPerformance=performance,getCurrentTime=function(){return localPerformance.now()};else{var localDate=Date;getCurrentTime=function(){return localDate.now()}}var CLIENT_RENDERED=4,PENDING=0,COMPLETED=1,FLUSHED=2,ABORTED=3,ERRORED=4,POSTPONED=5,CLOSED=14,currentRequest=null,didWarnAboutBadClass={},didWarnAboutContextTypes={},didWarnAboutContextTypeOnFunctionComponent={},didWarnAboutGetDerivedStateOnFunctionComponent={},didWarnAboutReassigningProps=!1,didWarnAboutGenerators=!1,didWarnAboutMaps=!1,flushedByteSize=0,flushingPartialBoundaries=!1;exports.renderToStaticMarkup=function(children,options){return renderToStringImpl(children,options,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.renderToString=function(children,options){return renderToStringImpl(children,options,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.version="19.2.8"})()});import{existsSync,readdirSync}from"fs";import{join}from"path";var package_default={name:"@velloo/renderer",version:"0.0.0",license:"Apache-2.0",private:!0,type:"module",description:"Headless renderer: design JSON \u2192 HTML + screenshot",exports:{".":"./src/index.ts","./iframe-protocol":"./src/iframe-protocol.ts"},dependencies:{"@velloo/provider":"workspace:*","@velloo/schema":"workspace:*",pixelmatch:"7.2.0",pngjs:"7.0.0",react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@types/pngjs":"6.0.5","@types/react":"19.2.18","@types/react-dom":"19.2.7","@velloo/shadcn-snapshot":"workspace:*",playwright:"1.62.1","playwright-core":"1.62.1"}};var PLAYWRIGHT_VERSION=package_default.devDependencies["playwright-core"],PLAYWRIGHT_PIN=`playwright@${PLAYWRIGHT_VERSION}`,CHROMIUM_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium","--only-shell"],CHROMIUM_INSTALL_CMD="velloo browser install",CHROMIUM_FULL_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium"],CHROMIUM_FULL_INSTALL_CMD="velloo browser install --full",CHROMIUM_DEPS_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install-deps","chromium"],CHROMIUM_DEPS_INSTALL_CMD="velloo browser install --with-deps",INSTALL_HINT=`Velloo screenshots need a headless browser. Install it once with:
|
|
80
80
|
${CHROMIUM_INSTALL_CMD}
|
|
81
81
|
`+"Then just retry the tool \u2014 the browser is picked up on the next call, no server restart needed. "+"(It's an on-demand extra; the canvas itself never needs it.)";class BrowserMissingError extends Error{constructor(message=INSTALL_HINT){super(message);this.name="BrowserMissingError"}}async function chromiumExecutable(){try{let{chromium}=await import("playwright-core"),path=chromium.executablePath();if(!path)return null;if(existsSync(path))return path;let m=path.match(/^(.*)[/\\]chromium-(\d+)[/\\]/);if(!m?.[1]||!m[2])return null;let shellRoot=join(m[1],`chromium_headless_shell-${m[2]}`);if(!existsSync(shellRoot))return null;let bin=process.platform==="win32"?"chrome-headless-shell.exe":"chrome-headless-shell";for(let sub of readdirSync(shellRoot)){let candidate=join(shellRoot,sub,bin);if(existsSync(candidate))return candidate}return null}catch{return null}}async function launchBrowser(){let chromium;try{({chromium}=await import("playwright-core"))}catch{throw new BrowserMissingError}try{return await chromium.launch()}catch(e){let msg=e instanceof Error?e.message:String(e);if(/Executable doesn't exist|playwright install|browserType\.launch/i.test(msg))throw new BrowserMissingError;let firstLine=msg.split(`
|
|
82
82
|
`).find((l)=>l.trim()!=="")?.trim()??msg;throw new BrowserMissingError(`Chromium failed to launch: ${firstLine}
|