@milaboratories/pl-middle-layer 1.32.7 → 1.32.8

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/dist/index.js CHANGED
@@ -1,7 +1,4 @@
1
- "use strict";var vs=Object.defineProperty;var Mt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Jt=s=>{throw TypeError(s)};var ys=(s,e,t)=>e in s?vs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ys(s,typeof e!="symbol"?e+"":e,t);var _t=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Jt("Object expected");var r;t&&(r=e[Mt("asyncDispose")]),r===void 0&&(r=e[Mt("dispose")]),typeof r!="function"&&Jt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Kt=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,u){return u=Error(c),u.name="SuppressedError",u.error=i,u.suppressed=a,u},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@platforma-sdk/model"),H=require("@milaboratories/pl-model-middle-layer"),Ht=require("@milaboratories/pl-deployments"),He=require("undici"),q=require("@platforma-sdk/block-tools"),Z=require("node:fs"),J=require("node:path"),ws=require("yaml"),k=require("@milaboratories/ts-helpers"),pt=require("node:fs/promises"),Ss=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),Me=require("@milaboratories/pl-tree"),B=require("@milaboratories/computable"),se=require("node:crypto"),j=require("@milaboratories/pl-model-backend"),Fr=require("lru-cache"),bs=require("node:worker_threads"),Lr=require("denque"),Ps=require("@platforma-sdk/workflow-tengo"),re=require("canonicalize"),Rs=require("@milaboratories/pl-errors"),Es=require("node:assert"),Oe=require("quickjs-emscripten"),Dr=require("node:timers/promises"),ee=require("@milaboratories/pl-drivers"),Cs=require("@milaboratories/pframes-rs-node"),ks=require("node:diagnostics_channel");function Os(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Nr=Os(pt);async function qt(s){try{return await Nr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const $s=[q.RegistryV1.PlPackageYamlConfigFile],Ts=[q.RegistryV1.PlPackageJsonConfigFile],Pt=["backend","dist","tengo","tpl","main.plj.gz"],Rt=["config","dist","config.json"],Br=["frontend","dist"],Wt="block-model/dist/config.json",Is="block-ui/package.json",As=[Pt,Rt,$s,Ts,Br];async function Fs(s){return await qt(J.join(s,...Rt))!==void 0||await qt(J.join(s,...Pt))!==void 0}function st(s,e){const t=Ss.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function zt(s,e){if(J.isAbsolute(s)||(s=J.resolve(s)),await Fs(s))return{workflow:J.join(s,...Pt),config:J.join(s,...Rt),ui:J.join(s,...Br)};{const t=st(s,Wt),r=st(s,Wt),o=st(s,Is);return{workflow:t,config:r,ui:J.resolve(o,"..","dist")}}}async function Ls(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Ds(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Et(s){let e=0n;for(const t of As){const r=J.join(s,...t),o=await Ds(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function qe(s){const e=await Z.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Ns{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await He.request(`${r.url}/${q.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:l,latestVersion:d}=a,g={organization:c,name:u,version:d},f={id:g,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:g,registryUrl:r.url}};t.push({registryId:e.id,id:g,latestByChannel:{[H.AnyChannel]:f,[H.StableChannel]:f},allVersions:a.allVersions.map(E=>({version:E,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=J.join(r.path,o.name),i=await Ls(J.join(n,q.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=q.RegistryV1.PlPackageConfigData.parse(ws.parse(i)),c=await Et(n),u={organization:a.organization,name:a.package,version:"DEV"},l={id:u,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:u,latestByChannel:{[H.AnyChannel]:l,[H.StableChannel]:l},allVersions:[]})}else{let a=n,c=await q.tryLoadPackDescription(a);if(c===void 0){for(const u of["block","meta"])if(a=J.join(n,u),c=await q.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const u=await qe(c),l={id:c.id,meta:await q.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:u}};t.push({registryId:e.id,id:c.id,latestByChannel:{[H.AnyChannel]:l,[H.StableChannel]:l},allVersions:[]})}}}return t;default:return k.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(a=>a.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class jr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new q.RegistryV2Reader(q.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Bs={type:"remote-v2",url:"https://blocks.pl-open.science/"},js={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},xs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Vs={groups:[{id:"default",label:"Default",blocks:[]}]},Us={stagingRefreshTimestamp:0,blocksInLimbo:[]},Gs={label:"New Project"},Ms={name:"UserProject",version:"2"},xr="SchemaVersion",Vr="1",Ct="ProjectCreated",$e="ProjectLastModified",Te="ProjectMeta",de="ProjectStructure",Je="BlockRenderingState",Js="BlockFrontendState/",_s=/^BlockFrontendState\/(?<blockid>.*)$/;function ht(s){return`${Js}${s}`}const Ks="BlockArgsAuthor/";function ft(s){return`${Ks}${s}`}const gt="ProjectStructureAuthor";function Hs(s){const e=s.match(_s);if(e!==null)return e.groups.blockid}const qs="__serviceTemplate_";function mt(s){return`${qs}${s}`}function M(s,e){return`${s}-${e}`}const Ws=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function zs(s){const e=s.match(Ws);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Xs="projects",Ur={name:"Projects",version:"1"},Ys=s=>h.resourceTypesEqual(s.type,Ur)?s.fields:[];async function Qs(s,e,t,r){const o=await Me.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Ys},r.logger);return{computable:B.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const d=a.traverse(l);if(d===void 0)continue;const g=k.notEmpty(d.getKeyValueAsJson(Te)),f=k.notEmpty(d.getKeyValueAsJson(Ct)),E=k.notEmpty(d.getKeyValueAsJson($e));u.push({id:l,rid:d.id,created:new Date(f),lastModified:new Date(E),opened:c.indexOf(d.id)>=0,meta:g})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:o}}const Zs={name:"EphRenderTemplate",version:"1"},eo={name:"RenderTemplate",version:"1"};function kt(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Zs):s.createStruct(eo),i=h.field(n,"template"),a=h.field(n,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(n),h.Pl.futureRecord(s,n,o,"Output","outputs/")}const to={name:"BContextEnd",version:"1"},ro={name:"BContext",version:"1"},so="id",oo="parent/",no=["context","result"];function Xt(s,e,t){return kt(s,e,!0,t,no)}function io(s){const e=s.createEphemeral(to);return s.lock(e),e}function Yt(s,e){if(e.length===0)return io(s);if(e.length===1)return e[0];const t=s.createEphemeral(ro);s.createField(h.field(t,so),"Input",h.Pl.createPlString(s,se.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${oo}${r}`),"Input",e[r]);return s.lock(t),t}function ao(s,e){const t=j.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Mr(s,t);default:k.assertNever(r)}}function co(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Mr(s,t);default:k.assertNever(r)}}const Qt={hash(s,e){e.update(j.PlTemplateLibV1.type.name).update(j.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(j.PlTemplateLibV1.type,JSON.stringify(j.PlTemplateLibV1.fromV2Data(s).data))}},Ae={hash(s,e){e.update(j.PlTemplateSoftwareV1.type.name).update(j.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=j.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(j.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,j.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},Gr={hash(s,e){e.update(j.PlTemplateV1.type.name).update(j.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Qt.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(j.PlTemplateV1.type,JSON.stringify(j.PlTemplateV1.fromV2Data(s).data));for(const[i,a]of Object.entries(s.libs??{})){const c=j.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Qt))}for(const[i,a]of Object.entries(s.software??{})){const c=j.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Ae))}for(const[i,a]of Object.entries(s.assets??{})){const c=j.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Ae))}for(const[i,a]of Object.entries(s.templates??{})){const c=j.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Gr))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(j.PlTemplateOverrideV1.type,JSON.stringify(j.PlTemplateOverrideV1.fromV2Data(s))),n=j.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function Mr(s,e){const t=new Map,r=(o,n)=>{const i=se.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,s,r);t.set(a,c)}return t.get(a)};return r(e,Gr)}const Jr={name:"TengoTemplateGet",version:"1"},_r="registry",Kr="templateURI",Hr="template",lo={name:"TengoTemplatePack",version:"1"},uo={name:"TengoTemplatePackConvert",version:"1"},po="templatePack",ho="template";async function qr(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return k.assertNever(s)}}function fo(s,e){const t=s.createStruct(Jr),r=h.field(t,_r),o=h.field(t,Kr),n=h.field(t,Hr);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function We(s,e){switch(e.type){case"from-registry":return fo(s,e);case"explicit":return ao(s,e);case"prepared":return co(s,e);default:return k.assertNever(e)}}const Ot={name:"Frontend/FromUrl",version:"1"},$t={name:"Frontend/FromFolder",version:"1"};function go(s,e){switch(e.type){case"url":return s.createValue(Ot,JSON.stringify({url:e.url}));case"local":return s.createValue($t,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}class mo{constructor(){S(this,"nextMessageId",0);S(this,"worker");S(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:J.resolve(void 0,"worker.js"),t=this.worker=new bs.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?a(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const vo={name:"BlockPackCustom",version:"1"},Wr="template",zr="frontend";function Zt(s){return s.endsWith("/")?s:`${s}/`}function yo(s){return Buffer.from(s).toString("utf8")}function Fe(s){return JSON.parse(yo(s))}class wo{constructor(e,t,r){S(this,"remoteContentCache",new Fr.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await He.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await zt(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await q.loadPackDescription(e.folder),r=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Zt(e.registryUrl)}${q.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Fe(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Fe(o)}default:return k.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=_t(o,new mo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,a=!0}finally{var c=Kt(o,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await zt(e.folder),r=await Z.promises.readFile(t.workflow),o=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await q.loadPackDescription(e.folder),r=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Z.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await qe(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${Zt(e.registryUrl)}${q.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=Fe(i);return{type:"explicit",template:{type:"explicit",content:n},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Fe(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,a]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return k.assertNever(e)}}}function So(s,e){const t={config:e.config,source:e.source},r=s.createStruct(vo,JSON.stringify(t));return s.createField(h.field(r,Wr),"Input",We(s,e.template)),s.createField(h.field(r,zr),"Input",go(s,e.frontend)),s.lock(r),r}function er(s,e){switch(e.type){case"prepared":return So(s,e);default:return k.assertNever(e.type)}}function Le(s,e){return{__isRef:!0,blockId:s,name:e}}function bo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function vt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(bo(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)vt(s,o,t);else for(const[,o]of Object.entries(e))vt(s,o,t);return;default:k.assertNever(r)}}function Po(s,e){const t={upstreams:new Set,missingReferences:!1};return vt(t,s,e),t}function ae(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Xr{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function yt(s){const e=new Map;let t;for(const{id:r}of ae(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Xr(e)}function Ge(s,e){const t=new Map,r=new Set;for(const{id:o}of ae(s)){const n=e(o);if(n===void 0)continue;const i=Po(n,r),a={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,a),i.upstreams.forEach(c=>t.get(c).downstream.add(o)),r.add(o)}return new Xr(t)}function Ro(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function wt(s,e){if(s.size>e.size)return wt(e,s);for(const t of s)if(e.has(t))return!0;return!1}function tr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Ro(n.upstream,i.upstream)||wt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?wt(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let ot;async function Yr(){if(ot===void 0){const s=await qr(Ps.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=se.createHash("sha256").update(s.content).digest("hex");ot={spec:s,hash:e}}return ot}function Eo(s,e,t){return kt(s,e,!0,{pf:t},["result"]).result}function nt(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class rr{constructor(e,t){S(this,"currentInputsC",nt(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));S(this,"actualProductionInputsC",nt(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return JSON.parse(Buffer.from(e).toString())}));S(this,"productionStaleC",nt(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),Wr,"Input")}}const Co=s=>{throw new Error(`No new block info for ${s}`)};class _e{constructor(e,t,r,o,n,i,a,c,u,l,d,g){S(this,"globalModCount",0);S(this,"fieldsChanged",!1);S(this,"lastModifiedChanged",!1);S(this,"structureChanged",!1);S(this,"metaChanged",!1);S(this,"renderingStateChanged",!1);S(this,"changedBlockFrontendStates",new Set);S(this,"blocksWithChangedInputs",new Set);S(this,"stagingGraph");S(this,"pendingProductionGraph");S(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=d,this.ctxExportTplHolder=g}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(H.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=yt(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ge(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ge(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ae(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=h.field(this.rid,M(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(h.field(this.rid,M(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(h.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Yt(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Yt(this.tx,t)}exportCtx(e){return Eo(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Xt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Xt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Co){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=yt(e),i=Ge(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=tr(r,n),c=tr(o,i);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new rr(u,{});this.blockInfos.set(u,l);const d=t(u),g=er(this.tx,d.blockPack);this.setBlockField(u,"blockPack",h.Pl.wrapInHolder(this.tx,g),"NotReady"),this.setBlockFieldObj(u,"blockSettings",this.createJsonFieldValue(H.InitialBlockSettings)),this.setBlockFieldObj(u,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(u,d.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);o.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,er(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const u of c.upstream)if(!r.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of ae(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const u of o.nodes.get(a.id).upstream)if(n.has(u)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new Lr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const c=r.shift(),u=this.getBlockInfo(c).fields;if(!(((i=u.prodOutput)==null?void 0:i.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))o.has(l)||(r.push(l),o.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,ft(t)):this.tx.setKValue(this.rid,ft(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,gt):this.tx.setKValue(this.rid,gt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Je,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Te,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,ht(e)):this.tx.setKValue(this.rid,ht(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,xr),i=e.getKValueJson(t,$e),a=e.getKValueJson(t,Te),c=e.getKValueJson(t,de),u=e.getKValueJson(t,Je),l=e.listKeyValuesString(t),[d,g,f,E,m,{stagingRefreshTimestamp:x,blocksInLimbo:D},U]=await Promise.all([o,n,i,a,c,u,l]);if(g!==Vr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${g}`);const I=new Map;for(const p of d.fields){const v=zs(p.name);if(v===void 0)continue;let w=I.get(v.blockId);w===void 0&&(w={id:v.blockId,fields:{}},I.set(v.blockId,w)),w.fields[v.fieldName]=h.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const _=await Yr(),pe=mt(_.hash),N=d.fields.find(p=>p.name===pe);let Y;N!==void 0?Y=h.ensureResourceIdNotNull(N.value):(Y=h.Pl.wrapInHolder(e,We(e,_.spec)),e.createField(h.field(t,mt(_.hash)),"Dynamic",Y));const le={stagingRefreshTimestamp:x},z=new Set(D),K=new Map;for(const p of U){const v=Hs(p.key);v!==void 0&&K.set(v,p.value)}const G=[];I.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!h.isResource(v.ref)||h.isResourceRef(v.ref))throw new Error("unexpected behaviour");G.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of G){const w=await v;p.value=w.data,h.isNotNullResourceId(w.error)?p.status="Error":w.resourceReady||h.isNotNullResourceId(w.originalResourceId)?p.status="Ready":p.status="NotReady"}const Q=new Map;I.forEach(({id:p,fields:v})=>Q.set(p,new rr(p,v)));const he=new Set;for(const p of ae(m)){if(!Q.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);he.add(p.id)}Q.forEach(p=>{if(!he.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new _e(t,e,r,g,f,E,m,le,z,Q,K,Y);return y.fixProblemsAndMigrate(),y}}async function ko(s,e=Gs){const t=s.createEphemeral(Ms);s.lock(t);const r=String(Date.now());s.setKValue(t,xr,JSON.stringify(Vr)),s.setKValue(t,Ct,r),s.setKValue(t,$e,r),s.setKValue(t,Te,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(Vs)),s.setKValue(t,Je,JSON.stringify(Us));const o=await Yr();return s.createField(h.field(t,mt(o.hash)),"Dynamic",h.Pl.wrapInHolder(s,We(s,o.spec))),t}async function De(s,e,t){return te(s,e,void 0,t)}async function te(s,e,t,r){if(s instanceof h.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await _e.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await _e.load(s,e,t),n=await r(o);return o.save(),n}}function*Oo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:k.assertNever(s)}}function sr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function $o(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:sr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:sr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(s)}}const To=h.resourceType("PColumnData/JsonPartitioned","1"),Io=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ao=h.resourceType("PColumnData/BinaryPartitioned","1"),Fo=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Lo=h.resourceType("PColumnData/Json","1");function Do(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,Lo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,To)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Io)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Ao)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Fo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function No(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Bo(s,e){const t=se.createHash("sha256");return t.update(re(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function or(s,e){return re({__isRef:!0,blockId:s,name:e})}function jo(s,e){return re({resolvePath:s,name:e})}function Qr(s,e=!0,t=!1,r=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const l of s.listInputFields()){const d=l.match(o);if(!d){if(e)throw new Error(`unexpected field name ${l}`);continue}let g=k.notEmpty((a=d.groups)==null?void 0:a.name);if(!g.startsWith(r)){if(e)throw new Error(`unexpected field name ${l}`);continue}g=g.slice(r.length);const f=k.notEmpty((c=d.groups)==null?void 0:c.type);let E=n.get(g);switch(E===void 0&&(E={},n.set(g,E)),f){case"spec":E.spec=(u=s.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":E.hasData=!0,E.data=()=>s.traverseOrError({field:l,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,l]of n)l.data===void 0&&(l.hasData=!1);return{locked:i,results:n}}function xo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Qr(s,e,!1,t);Es(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw Rs.parsePlError(c.error);n[i]={id:r.length===0?Bo(a.spec,c.value):jo(r,i),spec:a.spec,data:c.value}}return n}class Tt{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,a,c,u,l;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(l=(u=(c=r.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const r=this.blocks.get(e);if(r===void 0)return;const o=(a=(i=r.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return L.mapValueInVOE(n,u=>({id:or(e,t),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:Le(i,a),obj:{id:u.ok?or(i,a):void 0,spec:c.spec,data:u}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[u,l]of a.prod.results)c.add(u),n(i,u,l)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,l]of a.staging.results)c.has(u)||n(i,u,l)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,u]of i.staging.results)u.spec!==void 0&&(e.push({ref:Le(n,c),obj:u.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,u]of i.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:Le(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),L.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Le(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=k.notEmpty(o.getKeyValueAsJson(de)),a=yt(n).traverseIds("upstream",r),c=new Map;for(const u of ae(n)){if(!a.has(u.id))continue;const l=nr(o.traverse({field:M(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:M(u.id,"prodUiCtx"),stableIfNotFound:!0})),d=nr(o.traverse({field:M(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:M(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:d})}return new Tt(e,c)}}function nr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Qr(e.value,!1,!0)}function It(s,e){return{blockId:e,args:n=>k.notEmpty(n.accessor(s).node().traverse({field:M(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:M(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(ht(e)),blockMeta:n=>{const i=n.accessor(s).node(),a=k.notEmpty(i.getKeyValueAsJson(de)),c=new Map;for(const u of ae(a))c.set(u.id,u);return c}}}function Zr(s,e){return{...It(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:M(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:M(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Tt.create(t,s,e)}}function*X(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*X(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*X(t);return;case"MakeArray":for(const t of s.template)yield*X(t);return;case"GetJsonField":case"GetResourceField":yield*X(s.source),yield*X(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*X(s.source),yield*X(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*X(s.source);return;case"IsEmpty":yield*X(s.arg);return;case"Not":yield*X(s.operand);return;case"And":case"Or":yield*X(s.operand1),yield*X(s.operand2);return;default:k.assertNever(s)}}function Vo(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Re(s,e){return s===void 0?void 0:e(s)}function Uo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Go(s){for(const e of X(s))if(Uo(e))return!0;return!1}function ze(s){return{type:"ReturnResult",result:s}}function O(s){return()=>ze(s)}const Mo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return O(e)},Jo=s=>{const e=s.source;if(e===void 0)return O(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return O(t)},_o=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?O(void 0):({cCtx:r})=>{var o;return ze((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function es(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function Ko(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):()=>({type:"ScheduleSubroutine",subroutine:ts(r.length),args:es(r,o=>$({...s,[e.itVar]:o},e.mapping))})}}function ts(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return O(t)}}function Ho(s,e){return t=>{const r=t.source;if(r===void 0)return O(void 0);const o={};for(const[n,i]of Object.entries(r)){const a={...s,[e.itVar]:i};o[n]=$(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:qo,args:o})}}const qo=s=>O(s),Wo=s=>{const e=s.arg;return O(e===void 0?void 0:e.length===0)},zo=s=>{const e=s.operand;return O(e===void 0?void 0:!e)},Xo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e&&t)},Yo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e||t)},Qo=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t})=>{var r;return ze((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Zo=s=>{const e=s.source,t=s.field;return O(e===void 0||t===void 0?void 0:e[t])};function en(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=O(void 0);else{const u={...s,[e.itVar]:c.persist()};i[a]=$(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:tn,args:i}}}}const tn=s=>O(s),rn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:B.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},sn=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:B.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},on=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:B.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},nn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},an=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},cn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},ln=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},un=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},dn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},pn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},hn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function $(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>ze(t(r.cCtx)):O(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:os(t,s,e.cfg)});case"Immediate":return O(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:$(s,e.source),field:$(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Ko(s,e),args:{source:$(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Ho(s,e),args:{source:$(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:Vo(e.template,t=>$(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:ts(e.template.length),args:es(e.template,t=>$(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:{source:$(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{arg:$(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:{operand:$(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{operand1:$(s,e.operand1),operand2:$(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{operand1:$(s,e.operand1),operand2:$(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:en(s,e),args:{source:$(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{source:$(s,e.source),field:$(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:$(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:rn,args:{source:$(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{source:$(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:$(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:$(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{source:$(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:cn(e.format),args:{source:$(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:ln,args:{source:$(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:un(e.lines),args:{source:$(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:dn(e.patternToSearch),args:{source:$(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:pn(e.patternToSearch),args:{source:$(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:$(s,e.source)}});default:return k.assertNever(e)}}const fn=["$prod","$staging"];function gn(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const rs=Symbol(),ss="return",mn={op:rs,arg:ss};function vn(s){return s.op==rs&&s.arg==ss}function yn(){return{pendingSubroutines:new Map}}function ir(s,e,t,r){const o=new Lr(t),n=(a,c)=>{if(vn(a))return e.result=c,!1;const u=k.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const u=Symbol(),l=Object.entries(c.args),d=l.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[g,f]of l)o.push({destination:{op:u,arg:g},operation:f});e.pendingSubroutines.set(u,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:k.assertNever(c)}}return i}function wn(s,e,t,r={}){return os(s,gn(e),t,r)}function os(s,e,t,r={}){const o=`${e.blockId}#`+re({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>fn.indexOf(n)===-1)),cfg:t});return B.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},a=yn();return{ir:ir(i,a,[{destination:mn,operation:$(e,t)}],!0),postprocessValue(u){const l=[];for(const E of u)l.push({destination:E.destination,operation:O(E.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},g=new Map;for(const[E,m]of a.pendingSubroutines)g.set(E,{...m,args:{...m.args}});const f={result:a.result,pendingSubroutines:g};if(ir(d,f,l,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function Sn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function ar(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ke{constructor(e,t,r,o,n){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"errorRepo",new bn);S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ke.cleanErrorContext(t),t}}runCallback(e,...t){try{return Oe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw Ke.cleanErrorContext(r),this.errorRepo.getOriginal(r)}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return ar(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ar(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=xo(n,t,r,o),a={};for(const[c,u]of Object.entries(i))a[c]=L.mapPObjectData(u,l=>this.wrapAccessor(l));return a}registerComputable(e,t){const r=`${e}_${se.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",B.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",B.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=k.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:L.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:L.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return L.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>L.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(L.mapPTableDef(e,t=>L.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):L.isDataInfo(e)?L.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=se.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Sn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Oe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(L.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(a,c)=>{const u=(...l)=>{try{return c(...l)}catch(d){const g=this.errorRepo.setAndRecreateForQuickJS(d);throw this.vm.newError(g)}};this.vm.newFunction(a,u).consume(l=>this.vm.setProp(t,a,l)),this.vm.newFunction(a,c).consume(l=>this.vm.setProp(t,a+"__internal__",l))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...u)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...u.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,u,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(u),...l.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class bn{constructor(){S(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=se.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof Oe.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",h.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${h.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${h.stringifyWithResourceId(e)}`);return new Pn(e,o)}}class Pn extends Error{constructor(t,r){var o;super("",{cause:r});S(this,"stack");this.name="ModelError",this.stack=((o=t.stack)==null?void 0:o.replace(t.message,""))??"",this.stack=this.stack.replace(r.message,""),this.message=this.toString()}toString(){var r;return`ModelError: ${(r=this.cause)==null?void 0:r.message}
2
- QuickJS stacktrace:
3
- ${this.stack}
4
- `}}function Xe(s,e){return Re(s.traverse({field:M(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=L.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Ne=process.env.MI_LOG_OUTPUT_STATUS;function Rn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),B.Computable.makeRaw(a=>{const c=new Oe.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(s.quickJs.newRuntime());u.setMemoryLimit(1024*1024*8),u.setMaxStackSize(1024*320);const l=c.manage(u.newContext()),d=new Ke(c,l,e,s,a);d.evaluateBundle(r.content);const g=d.runCallback(t.handle);d.resetComputableCtx();let f=0;return Ne&&Ne!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:(E,{unstableMarker:m,stable:x})=>{for(const[U,I]of Object.entries(E))d.runCallback(U,I);const D=d.importObjectUniversal(g);return f++,Ne&&(Ne!=="unstable-only"||!x)&&console.log(x?`Stable output ${t.handle} calculated ${D!==void 0?"defined":"undefined"}; (#${f})`:`Unstable output ${t.handle}; marker = ${m}; ${D!==void 0?"defined":"undefined"} (#${f})`),D}}},n)}function En(s){return L.isConfigLambda(s)?s.isActive===!0:Go(s)}function Ee(s,e,t,r,o,n={}){if(L.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Rn(s,e,t,r,o,n)}else return wn(s.driverKit,e,t,n)}function Cn(s,e,t){return B.Computable.make(r=>{var E,m,x,D,U,I,_,pe;const o=r.accessor(s).node(),n=k.notEmpty(o.getKeyValueAsJson(Ct)),i=k.notEmpty(o.getKeyValueAsJson($e)),a=k.notEmpty(o.getKeyValueAsJson(Te)),c=k.notEmpty(o.getKeyValueAsJson(de)),u=k.notEmpty(o.getKeyValueAsJson(Je)),l=new Map;for(const{id:N}of ae(c)){const Y=o.traverse({field:M(N,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let le;const z=o.traverse({field:M(N,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(z!==void 0){const K=o.getField({field:M(N,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),G=o.getField({field:M(N,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});le={arguments:z.getDataAsJson(),stale:Y.id!==z.id,outputError:K.error!==void 0||G.error!==void 0||((E=K.value)==null?void 0:E.getError())!==void 0||((m=G.value)==null?void 0:m.getError())!==void 0,outputsError:((x=K.error)==null?void 0:x.getDataAsString())??((U=(D=K.value)==null?void 0:D.getError())==null?void 0:U.getDataAsString()),exportsError:((I=G.error)==null?void 0:I.getDataAsString())??((pe=(_=G.value)==null?void 0:_.getError())==null?void 0:pe.getDataAsString()),finished:(K.value!==void 0&&K.value.getIsReadyOrError()||K.error!==void 0&&K.error.getIsReadyOrError())&&(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())}}l.set(N,{currentArguments:Y.getDataAsJson(),prod:le})}const d=Ge(c,N=>l.get(N).currentArguments),g=new Set(u.blocksInLimbo),f=[...ae(c)].map(({id:N,label:Y,renderingMode:le})=>{var b,R,T,C,F;const z=k.notEmpty(l.get(N)),K=k.notEmpty(d.nodes.get(N));let G="NotCalculated";z.prod!==void 0&&(g.has(N)?G="Limbo":G=z.prod.finished?"Done":"Running");const Q=Xe(o,N),{sections:he,title:y,inputsValid:p,sdkVersion:v}=Re(Q,({bpId:V,cfg:A})=>{const ce=It(s,N);return{sections:Ee(t,ce,A.sections,A.code,V).wrap({recover:ye=>(t.logger.error("Error in block model sections"),t.logger.error(ye),[])}),title:Re(A.title,ye=>Ee(t,ce,ye,A.code,V).wrap({recover:ms=>(t.logger.error("Error in block model title"),t.logger.error(ms),"Invalid title")})),inputsValid:Ee(t,ce,A.inputsValid,A.code,V).wrap({recover:ye=>(t.logger.error("Error in block model argsValid"),t.logger.error(ye),!1)}),sdkVersion:A.sdkVersion}})||{},w=o.traverse({field:M(N,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Re(Q,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:w}));return{projectResourceId:h.resourceIdToString(s.rid),id:N,label:y??Y,title:y??Y,renderingMode:le,stale:((b=z.prod)==null?void 0:b.stale)!==!1||G==="Limbo",missingReference:K.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",N)],downstreams:[...d.traverseIdsExcludingRoots("downstream",N)],calculationStatus:G,outputErrors:((R=z.prod)==null?void 0:R.outputError)===!0,outputsError:(T=z.prod)==null?void 0:T.outputsError,exportsError:(C=z.prod)==null?void 0:C.exportsError,settings:w,sections:he,inputsValid:p,updateInfo:{},currentBlockPack:(F=Q==null?void 0:Q.info)==null?void 0:F.source,updates:P,sdkVersion:v,navigationState:e.getState(N)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(gt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var l,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(g=>n.has(g))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(g=>o.has(g))===-1,u={...i,canRun:c,stale:a,updateSuggestions:((l=i.updates)==null?void 0:l.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete u.updates,u})}}}).withStableType()}function kn(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,Ot)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,$t)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function On(s,e){if(s!==void 0)return B.Computable.make(t=>kn(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function $n(s,e,t){return B.Computable.make(r=>{var a;const o=r.accessor(s).node(),n=Xe(o,e),i=(a=o.traverse({field:M(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:zr,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:On(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ns(s,e,t){if(t===void 0)return B.Computable.make(i=>ns(s,e,i),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=It(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(ft(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function Tn(s,e,t){return B.Computable.make(r=>{const o=r.accessor(s).node(),n=Zr(s,e);return Re(Xe(o,e),({cfg:i,bpId:a})=>{const c={};for(const[u,l]of Object.entries(i.outputs)){const d=Ee(t,n,l,i.code,a);c[u]=B.Computable.wrapError(d)}return c})},{key:"outputs#"+h.resourceIdToString(s.rid)+"#"+e}).withStableType()}function In(s,e){return B.Computable.make(t=>{const r=t.accessor(s).node(),o=k.notEmpty(r.getKeyValueAsJson(de)),n=[];for(const{id:i}of ae(o)){const a=Xe(r,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,l])=>l).filter(l=>En(l)).map(l=>l);if(c.length===0)continue;const u=Zr(r.persist(),i);for(const l of c)n.push(B.Computable.wrapError(Ee(e,u,l,a.cfg.code,a.bpId)))}return n})}class An{constructor(){S(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new B.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...L.DefaultNavigationState},change:new B.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return B.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function cr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class Ye{constructor(e,t,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new An);S(this,"blockComputables",new Map);S(this,"blockFrontends",new Map);S(this,"activeConfigs");S(this,"refreshLoopResult");S(this,"abortController",new AbortController);S(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Cn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=In(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await De(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Dr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=se.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=L.extractConfig(a);return await te(this.env.pl,this.rid,o,u=>u.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await te(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await te(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await te(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await De(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await De(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await te(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await te(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await te(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await te(this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,M(e,"blockPack")))).value),n=h.ensureResourceIdNotNull((await r.getField(h.field(o,h.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(k.notEmpty(i.data)).toString("utf-8"));await te(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Tn(this.projectTree.entry(),e,this.env),n={fullState:B.Computable.make(i=>({argsAndUiState:ns(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,navigationState:i.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=$n(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await De(e.pl,t,o=>{});const r=await Me.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Fn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,a)=>{var c,u;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((u=i.data)==null?void 0:u.byteLength)??0)});const n=Me.treeDumpStats(o);await pt.writeFile(`${h.resourceIdToString(t)}.json`,cr(o)),await pt.writeFile(`${h.resourceIdToString(t)}.stats.json`,cr(n))}return new Ye(e,t,r)}}function Fn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}const At={logger:new k.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ft(s){return{blobDownloadPath:J.join(s,"download"),downloadBlobToURLPath:J.join(s,"downloadToURL")}}const is={...At,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function as(s){return{...Ft(s),frontendDownloadPath:J.join(s,"frontend")}}function Ln(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var St={exports:{}};const Dn="2.0.0",cs=256,Nn=Number.MAX_SAFE_INTEGER||9007199254740991,Bn=16,jn=cs-6,xn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Qe={MAX_LENGTH:cs,MAX_SAFE_COMPONENT_LENGTH:Bn,MAX_SAFE_BUILD_LENGTH:jn,MAX_SAFE_INTEGER:Nn,RELEASE_TYPES:xn,SEMVER_SPEC_VERSION:Dn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Vn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var Ze=Vn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=Qe,n=Ze;e=s.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const g="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[g,r]],E=x=>{for(const[D,U]of f)x=x.split(`${D}*`).join(`${D}{0,${U}}`).split(`${D}+`).join(`${D}{1,${U}}`);return x},m=(x,D,U)=>{const I=E(D),_=d++;n(x,_,D),l[x]=_,c[_]=D,u[_]=I,i[_]=new RegExp(D,U?"g":void 0),a[_]=new RegExp(I,U?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${g}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${g}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(St,St.exports);var Ie=St.exports;const Un=Object.freeze({loose:!0}),Gn=Object.freeze({}),Mn=s=>s?typeof s!="object"?Un:s:Gn;var Lt=Mn;const lr=/^[0-9]+$/,ls=(s,e)=>{const t=lr.test(s),r=lr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},Jn=(s,e)=>ls(e,s);var us={compareIdentifiers:ls,rcompareIdentifiers:Jn};const Be=Ze,{MAX_LENGTH:ur,MAX_SAFE_INTEGER:je}=Qe,{safeRe:dr,safeSrc:pr,t:xe}=Ie,_n=Lt,{compareIdentifiers:fe}=us;let Kn=class ie{constructor(e,t){if(t=_n(t),e instanceof ie){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>ur)throw new TypeError(`version is longer than ${ur} characters`);Be("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?dr[xe.LOOSE]:dr[xe.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>je||this.major<0)throw new TypeError("Invalid major version");if(this.minor>je||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>je||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<je)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Be("SemVer.compare",this.version,this.options,e),!(e instanceof ie)){if(typeof e=="string"&&e===this.version)return 0;e=new ie(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof ie||(e=new ie(e,this.options)),fe(this.major,e.major)||fe(this.minor,e.minor)||fe(this.patch,e.patch)}comparePre(e){if(e instanceof ie||(e=new ie(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(Be("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return fe(r,o)}while(++t)}compareBuild(e){e instanceof ie||(e=new ie(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Be("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return fe(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?pr[xe.PRERELEASELOOSE]:pr[xe.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),fe(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var W=Kn;const hr=W,Hn=(s,e,t=!1)=>{if(s instanceof hr)return s;try{return new hr(s,e)}catch(r){if(!t)return null;throw r}};var ve=Hn;const qn=ve,Wn=(s,e)=>{const t=qn(s,e);return t?t.version:null};var zn=Wn;const Xn=ve,Yn=(s,e)=>{const t=Xn(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Qn=Yn;const fr=W,Zn=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new fr(s instanceof fr?s.version:s,t).inc(e,r,o).version}catch{return null}};var ei=Zn;const gr=ve,ti=(s,e)=>{const t=gr(s,null,!0),r=gr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,a=n?r:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}const l=c?"pre":"";return t.major!==r.major?l+"major":t.minor!==r.minor?l+"minor":t.patch!==r.patch?l+"patch":"prerelease"};var ri=ti;const si=W,oi=(s,e)=>new si(s,e).major;var ni=oi;const ii=W,ai=(s,e)=>new ii(s,e).minor;var ci=ai;const li=W,ui=(s,e)=>new li(s,e).patch;var di=ui;const pi=ve,hi=(s,e)=>{const t=pi(s,e);return t&&t.prerelease.length?t.prerelease:null};var fi=hi;const mr=W,gi=(s,e,t)=>new mr(s,t).compare(new mr(e,t));var oe=gi;const mi=oe,vi=(s,e,t)=>mi(e,s,t);var yi=vi;const wi=oe,Si=(s,e)=>wi(s,e,!0);var bi=Si;const vr=W,Pi=(s,e,t)=>{const r=new vr(s,t),o=new vr(e,t);return r.compare(o)||r.compareBuild(o)};var Dt=Pi;const Ri=Dt,Ei=(s,e)=>s.sort((t,r)=>Ri(t,r,e));var Ci=Ei;const ki=Dt,Oi=(s,e)=>s.sort((t,r)=>ki(r,t,e));var $i=Oi;const Ti=oe,Ii=(s,e,t)=>Ti(s,e,t)>0;var et=Ii;const Ai=oe,Fi=(s,e,t)=>Ai(s,e,t)<0;var Nt=Fi;const Li=oe,Di=(s,e,t)=>Li(s,e,t)===0;var ds=Di;const Ni=oe,Bi=(s,e,t)=>Ni(s,e,t)!==0;var ps=Bi;const ji=oe,xi=(s,e,t)=>ji(s,e,t)>=0;var Bt=xi;const Vi=oe,Ui=(s,e,t)=>Vi(s,e,t)<=0;var jt=Ui;const Gi=ds,Mi=ps,Ji=et,_i=Bt,Ki=Nt,Hi=jt,qi=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return Gi(s,t,r);case"!=":return Mi(s,t,r);case">":return Ji(s,t,r);case">=":return _i(s,t,r);case"<":return Ki(s,t,r);case"<=":return Hi(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var hs=qi;const Wi=W,zi=ve,{safeRe:Ve,t:Ue}=Ie,Xi=(s,e)=>{if(s instanceof Wi)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?Ve[Ue.COERCEFULL]:Ve[Ue.COERCE]);else{const c=e.includePrerelease?Ve[Ue.COERCERTLFULL]:Ve[Ue.COERCERTL];let u;for(;(u=c.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return zi(`${r}.${o}.${n}${i}${a}`,e)};var Yi=Xi;class Qi{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var Zi=Qi,it,yr;function ne(){if(yr)return it;yr=1;const s=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(P=>!m(P[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&x(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const v=this.set[p];for(let w=0;w<v.length;w++)w>0&&(this.formatted+=" "),this.formatted+=v[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const w=((this.options.includePrerelease&&f)|(this.options.loose&&E))+":"+p,P=r.get(w);if(P)return P;const b=this.options.loose,R=b?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];p=p.replace(R,Q(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[u.COMPARATORTRIM],l),i("comparator trim",p),p=p.replace(c[u.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[u.CARETTRIM],g),i("caret trim",p);let T=p.split(" ").map(A=>U(A,this.options)).join(" ").split(/\s+/).map(A=>G(A,this.options));b&&(T=T.filter(A=>(i("loose invalid filter",A,this.options),!!A.match(c[u.COMPARATORLOOSE])))),i("range list",T);const C=new Map,F=T.map(A=>new n(A,this.options));for(const A of F){if(m(A))return[A];C.set(A.value,A)}C.size>1&&C.has("")&&C.delete("");const V=[...C.values()];return r.set(w,V),V}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>D(w,v)&&p.set.some(P=>D(P,v)&&w.every(b=>P.every(R=>b.intersects(R,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(he(this.set[v],p,this.options))return!0;return!1}}it=e;const t=Zi,r=new t,o=Lt,n=tt(),i=Ze,a=W,{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:g}=Ie,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:E}=Qe,m=y=>y.value==="<0.0.0-0",x=y=>y.value==="",D=(y,p)=>{let v=!0;const w=y.slice();let P=w.pop();for(;v&&w.length;)v=w.every(b=>P.intersects(b,p)),P=w.pop();return v},U=(y,p)=>(i("comp",y,p),y=N(y,p),i("caret",y),y=_(y,p),i("tildes",y),y=le(y,p),i("xrange",y),y=K(y,p),i("stars",y),y),I=y=>!y||y.toLowerCase()==="x"||y==="*",_=(y,p)=>y.trim().split(/\s+/).map(v=>pe(v,p)).join(" "),pe=(y,p)=>{const v=p.loose?c[u.TILDELOOSE]:c[u.TILDE];return y.replace(v,(w,P,b,R,T)=>{i("tilde",y,w,P,b,R,T);let C;return I(P)?C="":I(b)?C=`>=${P}.0.0 <${+P+1}.0.0-0`:I(R)?C=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:T?(i("replaceTilde pr",T),C=`>=${P}.${b}.${R}-${T} <${P}.${+b+1}.0-0`):C=`>=${P}.${b}.${R} <${P}.${+b+1}.0-0`,i("tilde return",C),C})},N=(y,p)=>y.trim().split(/\s+/).map(v=>Y(v,p)).join(" "),Y=(y,p)=>{i("caret",y,p);const v=p.loose?c[u.CARETLOOSE]:c[u.CARET],w=p.includePrerelease?"-0":"";return y.replace(v,(P,b,R,T,C)=>{i("caret",y,P,b,R,T,C);let F;return I(b)?F="":I(R)?F=`>=${b}.0.0${w} <${+b+1}.0.0-0`:I(T)?b==="0"?F=`>=${b}.${R}.0${w} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.0${w} <${+b+1}.0.0-0`:C?(i("replaceCaret pr",C),b==="0"?R==="0"?F=`>=${b}.${R}.${T}-${C} <${b}.${R}.${+T+1}-0`:F=`>=${b}.${R}.${T}-${C} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.${T}-${C} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?R==="0"?F=`>=${b}.${R}.${T}${w} <${b}.${R}.${+T+1}-0`:F=`>=${b}.${R}.${T}${w} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.${T} <${+b+1}.0.0-0`),i("caret return",F),F})},le=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>z(v,p)).join(" ")),z=(y,p)=>{y=y.trim();const v=p.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return y.replace(v,(w,P,b,R,T,C)=>{i("xRange",y,w,P,b,R,T,C);const F=I(b),V=F||I(R),A=V||I(T),ce=A;return P==="="&&ce&&(P=""),C=p.includePrerelease?"-0":"",F?P===">"||P==="<"?w="<0.0.0-0":w="*":P&&ce?(V&&(R=0),T=0,P===">"?(P=">=",V?(b=+b+1,R=0,T=0):(R=+R+1,T=0)):P==="<="&&(P="<",V?b=+b+1:R=+R+1),P==="<"&&(C="-0"),w=`${P+b}.${R}.${T}${C}`):V?w=`>=${b}.0.0${C} <${+b+1}.0.0-0`:A&&(w=`>=${b}.${R}.0${C} <${b}.${+R+1}.0-0`),i("xRange return",w),w})},K=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[u.STAR],"")),G=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?u.GTE0PRE:u.GTE0],"")),Q=y=>(p,v,w,P,b,R,T,C,F,V,A,ce)=>(I(w)?v="":I(P)?v=`>=${w}.0.0${y?"-0":""}`:I(b)?v=`>=${w}.${P}.0${y?"-0":""}`:R?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,I(F)?C="":I(V)?C=`<${+F+1}.0.0-0`:I(A)?C=`<${F}.${+V+1}.0-0`:ce?C=`<=${F}.${V}.${A}-${ce}`:y?C=`<${F}.${V}.${+A+1}-0`:C=`<=${C}`,`${v} ${C}`.trim()),he=(y,p,v)=>{for(let w=0;w<y.length;w++)if(!y[w].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let w=0;w<y.length;w++)if(i(y[w].semver),y[w].semver!==n.ANY&&y[w].semver.prerelease.length>0){const P=y[w].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return it}var at,wr;function tt(){if(wr)return at;wr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],g=l.match(d);if(!g)throw new TypeError(`Invalid comparator: ${l}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new a(g[2],this.options.loose):this.semver=s}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===s||l===s)return!0;if(typeof l=="string")try{l=new a(l,this.options)}catch{return!1}return n(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||n(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||n(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}at=e;const t=Lt,{safeRe:r,t:o}=Ie,n=hs,i=Ze,a=W,c=ne();return at}const ea=ne(),ta=(s,e,t)=>{try{e=new ea(e,t)}catch{return!1}return e.test(s)};var rt=ta;const ra=ne(),sa=(s,e)=>new ra(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var oa=sa;const na=W,ia=ne(),aa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new ia(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new na(r,t))}),r};var ca=aa;const la=W,ua=ne(),da=(s,e,t)=>{let r=null,o=null,n=null;try{n=new ua(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new la(r,t))}),r};var pa=da;const ct=W,ha=ne(),Sr=et,fa=(s,e)=>{s=new ha(s,e);let t=new ct("0.0.0");if(s.test(t)||(t=new ct("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const a=new ct(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Sr(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Sr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var ga=fa;const ma=ne(),va=(s,e)=>{try{return new ma(s,e).range||"*"}catch{return null}};var ya=va;const wa=W,fs=tt(),{ANY:Sa}=fs,ba=ne(),Pa=rt,br=et,Pr=Nt,Ra=jt,Ea=Bt,Ca=(s,e,t,r)=>{s=new wa(s,r),e=new ba(e,r);let o,n,i,a,c;switch(t){case">":o=br,n=Ra,i=Pr,a=">",c=">=";break;case"<":o=Pr,n=Ea,i=br,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Pa(s,e,r))return!1;for(let u=0;u<e.set.length;++u){const l=e.set[u];let d=null,g=null;if(l.forEach(f=>{f.semver===Sa&&(f=new fs(">=0.0.0")),d=d||f,g=g||f,o(f.semver,d.semver,r)?d=f:i(f.semver,g.semver,r)&&(g=f)}),d.operator===a||d.operator===c||(!g.operator||g.operator===a)&&n(s,g.semver))return!1;if(g.operator===c&&i(s,g.semver))return!1}return!0};var xt=Ca;const ka=xt,Oa=(s,e,t)=>ka(s,e,">",t);var $a=Oa;const Ta=xt,Ia=(s,e,t)=>Ta(s,e,"<",t);var Aa=Ia;const Rr=ne(),Fa=(s,e,t)=>(s=new Rr(s,t),e=new Rr(e,t),s.intersects(e,t));var La=Fa;const Da=rt,Na=oe;var Ba=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((l,d)=>Na(l,d,t));for(const l of i)Da(l,e,t)?(n=l,o||(o=l)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const a=[];for(const[l,d]of r)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);const c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e};const Er=ne(),Vt=tt(),{ANY:lt}=Vt,we=rt,Ut=oe,ja=(s,e,t={})=>{if(s===e)return!0;s=new Er(s,t),e=new Er(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Va(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},xa=[new Vt(">=0.0.0-0")],Cr=[new Vt(">=0.0.0")],Va=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===lt){if(e.length===1&&e[0].semver===lt)return!0;t.includePrerelease?s=xa:s=Cr}if(e.length===1&&e[0].semver===lt){if(t.includePrerelease)return!0;e=Cr}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=kr(o,f,t):f.operator==="<"||f.operator==="<="?n=Or(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Ut(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!we(f,String(o),t)||n&&!we(f,String(n),t))return null;for(const E of e)if(!we(f,String(E),t))return!1;return!0}let a,c,u,l,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,g=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(l=l||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",o){if(g&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===g.major&&f.semver.minor===g.minor&&f.semver.patch===g.patch&&(g=!1),f.operator===">"||f.operator===">="){if(a=kr(o,f,t),a===f&&a!==o)return!1}else if(o.operator===">="&&!we(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(c=Or(n,f,t),c===f&&c!==n)return!1}else if(n.operator==="<="&&!we(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&u&&!n&&i!==0||n&&l&&!o&&i!==0||g||d)},kr=(s,e,t)=>{if(!s)return e;const r=Ut(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Or=(s,e,t)=>{if(!s)return e;const r=Ut(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Ua=ja;const ut=Ie,$r=Qe,Ga=W,Tr=us,Ma=ve,Ja=zn,_a=Qn,Ka=ei,Ha=ri,qa=ni,Wa=ci,za=di,Xa=fi,Ya=oe,Qa=yi,Za=bi,ec=Dt,tc=Ci,rc=$i,sc=et,oc=Nt,nc=ds,ic=ps,ac=Bt,cc=jt,lc=hs,uc=Yi,dc=tt(),pc=ne(),hc=rt,fc=oa,gc=ca,mc=pa,vc=ga,yc=ya,wc=xt,Sc=$a,bc=Aa,Pc=La,Rc=Ba,Ec=Ua;var Cc={parse:Ma,valid:Ja,clean:_a,inc:Ka,diff:Ha,major:qa,minor:Wa,patch:za,prerelease:Xa,compare:Ya,rcompare:Qa,compareLoose:Za,compareBuild:ec,sort:tc,rsort:rc,gt:sc,lt:oc,eq:nc,neq:ic,gte:ac,lte:cc,cmp:lc,coerce:uc,Comparator:dc,Range:pc,satisfies:hc,toComparators:fc,maxSatisfying:gc,minSatisfying:mc,minVersion:vc,validRange:yc,outside:wc,gtr:Sc,ltr:bc,intersects:Pc,simplifyRange:Rc,subset:Ec,SemVer:Ga,re:ut.re,src:ut.src,tokens:ut.t,SEMVER_SPEC_VERSION:$r.SEMVER_SPEC_VERSION,RELEASE_TYPES:$r.RELEASE_TYPES,compareIdentifiers:Tr.compareIdentifiers,rcompareIdentifiers:Tr.rcompareIdentifiers};const kc=Ln(Cc),Oc={minDelay:1500},$c="__no_updates__";class Tc extends B.PollComputablePool{constructor(t,r,o={}){super({...o,...Oc},r);S(this,"http");S(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${re(t)}`;default:return $c}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Et(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await q.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await qe(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,H.StableChannel))u=H.StableChannel;else{if(await c.getLatestOverview(n.id,H.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${H.blockPackIdToString(n.id)}`),{suggestions:[]};u=H.AnyChannel}else u=n.channel;const l=await c.getUpdateSuggestions(n.id,u);if(l===void 0||l.length===0)return{suggestions:[]};l.reverse();let d;switch(i){case void 0:d=l[0].update;break;case"major":d=(r=l.find(E=>E.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=l.find(E=>E.type==="patch"))==null?void 0:o.update;break}const g=l.map(({type:E,update:m})=>({type:E,update:{...n,id:{...n.id,version:m}}}));if(d===void 0)return{suggestions:g};if(a!==void 0&&kc.lte(d,a))return{suggestions:g};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(E){this.logger.warn(E)}})(),{suggestions:g,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return re(t)===re(r)}}class Ir{constructor(){S(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Se;function ue(){return Se||(Se={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Se.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Se)}function Ce(s){return String(s.id)}const Ic=["Int","Long","Float","Double","String","Bytes"];function dt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const be=(s,e)=>typeof e=="bigint"?e.toString():e;class Ac{constructor(e,t,r,o){S(this,"rustPFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});S(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});S(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=r;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of Oo(a.data))this.blobIdToResource.set(Ce(c),c);const i=[...new Map(o.map(a=>({...a,data:$o(a.data,Ce)})).map(a=>[re(a),a])).values()];try{const a=new Cs.PFrame(ue().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.rustPFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Fc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Lc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");this.blobDriver=e,this.logger=t;const r=new Fr.LRUCache({maxSize:1e9,fetchMethod:async o=>await Nr.readFile(o),sizeCalculation:o=>o.length});this.blobContentCache=r,this.pFrames=new class extends Ir{constructor(o,n){super(),this.blobDriver=o,this.logger=n}createNewResource(o){return ue().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,be)}`),new Ac(this.blobDriver,this.logger,r,o)}calculateParamsKey(o){return Nc(o)}}(this.blobDriver,this.logger),this.pTables=new class extends Ir{constructor(o){super(),this.pFrames=o}createNewResource(o){const n=o.pFrameHandle;ue().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,be)}`);const i=this.pFrames.getByKey(n).rustPFrame.createTable({src:ke(o.def.src),filters:dt(o.def.filters)},o.signal).then(async a=>{if(o.def.sorting.length===0)return a;try{return await a.sort(o.def.sorting,o.signal)}finally{a.dispose()}});return new Fc(i)}calculateParamsKey(o){return Dc(o)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>Ic.find(i=>i===n.spec.valueType)).map(n=>L.mapPObjectData(n,i=>Me.isPlTreeNodeAccessor(i)?Do(i):L.isDataInfo(i)?L.mapDataInfo(i,a=>a.resourceInfo):No(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(L.extractAllColumns(e.src),t),n=L.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return ue().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(L.mapPTableDef(e,a=>a.spec),be)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[re(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).rustPFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,r){return ue().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,be)}`),await this.pFrames.getByKey(e).rustPFrame.createTable({src:ke(t.src),filters:dt(t.filters)},r).then(async o=>{if(t.sorting.length===0)return o;try{return await o.sort(t.sorting,r)}finally{o.dispose()}}).then(async o=>{try{const n=o.getSpec(),i=await o.getData([...n.keys()]);return n.map((a,c)=>({spec:a,data:i[c]}))}finally{o.dispose()}})}async getUniqueValues(e,t,r){return ue().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,be)}`),await this.pFrames.getByKey(e).rustPFrame.getUniqueValues({...t,filters:dt(t.filters)},r)}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r){return await(await this.pTables.getByKey(e).table).getData(t,r)}}function ke(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>ke(e))};case"outer":return{type:"outer",primary:ke(s.primary),secondary:s.secondary.map(e=>ke(e))};default:k.assertNever(s)}}function Dc(s){const e=se.createHash("sha256");return e.update(re(s)),e.digest().toString("hex")}function Nc(s){const e=[...s].map(r=>L.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:Ce(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[Ce(c.index),Ce(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=se.createHash("sha256");return t.update(re(e)),t.digest().toString("hex")}async function gs(s,e,t){const r={...At,...Ft(e),...t},o=new k.HmacSha256Signer(r.localSecret),n=ee.createDownloadClient(r.logger,s,r.localProjections),i=ee.createLogsClient(s,r.logger),a=ee.createUploadBlobClient(s,r.logger),c=ee.createUploadProgressClient(s,r.logger),u=new ee.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),l=new ee.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new ee.UploadDriver(r.logger,o,a,c,r.uploadDriverOps),g=new ee.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new ee.LogsDriver(r.logger,g,u),E=await ee.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),m=new Lc(u,r.logger);return{blobDriver:u,blobToURLDriver:l,logDriver:f,lsDriver:E,signer:o,uploadDriver:d,pFrameDriver:m}}class Gt{constructor(e,t,r,o,n,i,a,c){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=se.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await ko(o,e);return o.createField(h.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await h.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await te(this.pl,e,r,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await Ye.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),await this.projectListTree.terminate(),await this.env.retryHttpDispatcher.destroy(),await this.pl.close()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return k.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...is,...as(t),...r};o.defaultTreeOptions.logStat=ue().logTreeStats,o.debugOps.dumpInitialTreeState=ue().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async m=>{const x=h.field(m.clientRoot,Xs);m.createField(x,"Dynamic");const D=await m.getField(x);if(h.isNullResourceId(D.value)){const U=m.createEphemeral(Ur);return m.lock(U),m.setField(x,U),await m.commit(),await U.globalId}else return D.value}),i=o.logger,a=await gs(e,t,o),c=new He.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new jr(c),l=new wo(u,a.signer,c),d=new ee.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),g={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:l,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new Tc(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Oe.getQuickJS()},f=new B.WatchableValue([]),E=await Qs(e,n,f,g);return new Gt(g,a,a.signer,n,f,E.tree,u,E.computable)}}const Bc=["undici:request:create","undici:request:bodySent","undici:request:headers","undici:request:error","undici:request:trailers","undici:client:sendHeaders","undici:client:beforeConnect","undici:client:connected","undici:client:connectError","undici:socket:close","undici:socket:connect","undici:socket:error","undici:pool:request","undici:pool:connect","undici:pool:disconnect","undici:pool:destroy","undici:dispatcher:request","undici:dispatcher:connect","undici:dispatcher:disconnect","undici:dispatcher:retry"];async function jc(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,...e},r=[];Bc.forEach(c=>{ks.channel(c).subscribe(l=>{var g;const d=new Date().toISOString();(g=l==null?void 0:l.response)!=null&&g.headers&&(l.response.headers=l.response.headers.map(f=>f.toString())),r.push(JSON.stringify({timestamp:d,event:c,data:l}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=h.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ge(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new h.UnauthenticatedPlClient(n).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new h.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ge(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Pe(t.autoUpdateCdnUrl,t,a)),xc(o,s,t,r)}async function ge(s,e,t){const r=bt(),o=[];for(;Ar(r)<s;){const n=bt();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=Ar(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Dr.setTimeout(c)}return o}async function Pe(s,e,t){const{body:r,statusCode:o}=await He.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function xc(s,e,t,r){const o=s.plPings.filter(a=>a.response.ok),n=s.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
1
+ "use strict";var vs=Object.defineProperty;var Jt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Mt=s=>{throw TypeError(s)};var ys=(s,e,t)=>e in s?vs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var S=(s,e,t)=>ys(s,typeof e!="symbol"?e+"":e,t);var _t=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Mt("Object expected");var r;t&&(r=e[Jt("asyncDispose")]),r===void 0&&(r=e[Jt("dispose")]),typeof r!="function"&&Mt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Kt=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,u){return u=Error(c),u.name="SuppressedError",u.error=i,u.suppressed=a,u},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@platforma-sdk/model"),H=require("@milaboratories/pl-model-middle-layer"),Ht=require("@milaboratories/pl-deployments"),He=require("undici"),q=require("@platforma-sdk/block-tools"),Z=require("node:fs"),M=require("node:path"),ws=require("yaml"),k=require("@milaboratories/ts-helpers"),pt=require("node:fs/promises"),Ss=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),Je=require("@milaboratories/pl-tree"),B=require("@milaboratories/computable"),se=require("node:crypto"),j=require("@milaboratories/pl-model-backend"),Fr=require("lru-cache"),bs=require("node:worker_threads"),Lr=require("denque"),Ps=require("@platforma-sdk/workflow-tengo"),re=require("canonicalize"),Rs=require("node:assert"),Oe=require("quickjs-emscripten"),Es=require("@milaboratories/pl-errors"),Dr=require("node:timers/promises"),ee=require("@milaboratories/pl-drivers"),Cs=require("@milaboratories/pframes-rs-node"),ks=require("node:diagnostics_channel");function Os(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const Nr=Os(pt);async function qt(s){try{return await Nr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const $s=[q.RegistryV1.PlPackageYamlConfigFile],Ts=[q.RegistryV1.PlPackageJsonConfigFile],Pt=["backend","dist","tengo","tpl","main.plj.gz"],Rt=["config","dist","config.json"],Br=["frontend","dist"],Wt="block-model/dist/config.json",Is="block-ui/package.json",As=[Pt,Rt,$s,Ts,Br];async function Fs(s){return await qt(M.join(s,...Rt))!==void 0||await qt(M.join(s,...Pt))!==void 0}function st(s,e){const t=Ss.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function zt(s,e){if(M.isAbsolute(s)||(s=M.resolve(s)),await Fs(s))return{workflow:M.join(s,...Pt),config:M.join(s,...Rt),ui:M.join(s,...Br)};{const t=st(s,Wt),r=st(s,Wt),o=st(s,Is);return{workflow:t,config:r,ui:M.resolve(o,"..","dist")}}}async function Ls(s){try{return await Z.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Ds(s){try{return await Z.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Et(s){let e=0n;for(const t of As){const r=M.join(s,...t),o=await Ds(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function qe(s){const e=await Z.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Ns{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await He.request(`${r.url}/${q.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:l,latestVersion:d}=a,g={organization:c,name:u,version:d},f={id:g,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:g,registryUrl:r.url}};t.push({registryId:e.id,id:g,latestByChannel:{[H.AnyChannel]:f,[H.StableChannel]:f},allVersions:a.allVersions.map(E=>({version:E,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await Z.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=M.join(r.path,o.name),i=await Ls(M.join(n,q.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=q.RegistryV1.PlPackageConfigData.parse(ws.parse(i)),c=await Et(n),u={organization:a.organization,name:a.package,version:"DEV"},l={id:u,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:u,latestByChannel:{[H.AnyChannel]:l,[H.StableChannel]:l},allVersions:[]})}else{let a=n,c=await q.tryLoadPackDescription(a);if(c===void 0){for(const u of["block","meta"])if(a=M.join(n,u),c=await q.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const u=await qe(c),l={id:c.id,meta:await q.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:u}};t.push({registryId:e.id,id:c.id,latestByChannel:{[H.AnyChannel]:l,[H.StableChannel]:l},allVersions:[]})}}}return t;default:return k.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(a=>a.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class jr{constructor(e){S(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new q.RegistryV2Reader(q.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Bs={type:"remote-v2",url:"https://blocks.pl-open.science/"},js={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},xs={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Vs={groups:[{id:"default",label:"Default",blocks:[]}]},Us={stagingRefreshTimestamp:0,blocksInLimbo:[]},Gs={label:"New Project"},Js={name:"UserProject",version:"2"},xr="SchemaVersion",Vr="1",Ct="ProjectCreated",$e="ProjectLastModified",Te="ProjectMeta",de="ProjectStructure",Me="BlockRenderingState",Ms="BlockFrontendState/",_s=/^BlockFrontendState\/(?<blockid>.*)$/;function ht(s){return`${Ms}${s}`}const Ks="BlockArgsAuthor/";function ft(s){return`${Ks}${s}`}const gt="ProjectStructureAuthor";function Hs(s){const e=s.match(_s);if(e!==null)return e.groups.blockid}const qs="__serviceTemplate_";function mt(s){return`${qs}${s}`}function J(s,e){return`${s}-${e}`}const Ws=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function zs(s){const e=s.match(Ws);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Xs="projects",Ur={name:"Projects",version:"1"},Ys=s=>h.resourceTypesEqual(s.type,Ur)?s.fields:[];async function Qs(s,e,t,r){const o=await Je.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Ys},r.logger);return{computable:B.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const d=a.traverse(l);if(d===void 0)continue;const g=k.notEmpty(d.getKeyValueAsJson(Te)),f=k.notEmpty(d.getKeyValueAsJson(Ct)),E=k.notEmpty(d.getKeyValueAsJson($e));u.push({id:l,rid:d.id,created:new Date(f),lastModified:new Date(E),opened:c.indexOf(d.id)>=0,meta:g})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:o}}const Zs={name:"EphRenderTemplate",version:"1"},eo={name:"RenderTemplate",version:"1"};function kt(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Zs):s.createStruct(eo),i=h.field(n,"template"),a=h.field(n,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(n),h.Pl.futureRecord(s,n,o,"Output","outputs/")}const to={name:"BContextEnd",version:"1"},ro={name:"BContext",version:"1"},so="id",oo="parent/",no=["context","result"];function Xt(s,e,t){return kt(s,e,!0,t,no)}function io(s){const e=s.createEphemeral(to);return s.lock(e),e}function Yt(s,e){if(e.length===0)return io(s);if(e.length===1)return e[0];const t=s.createEphemeral(ro);s.createField(h.field(t,so),"Input",h.Pl.createPlString(s,se.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${oo}${r}`),"Input",e[r]);return s.lock(t),t}function ao(s,e){const t=j.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Jr(s,t);default:k.assertNever(r)}}function co(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Jr(s,t);default:k.assertNever(r)}}const Qt={hash(s,e){e.update(j.PlTemplateLibV1.type.name).update(j.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(j.PlTemplateLibV1.type,JSON.stringify(j.PlTemplateLibV1.fromV2Data(s).data))}},Ae={hash(s,e){e.update(j.PlTemplateSoftwareV1.type.name).update(j.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=j.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(j.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,j.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},Gr={hash(s,e){e.update(j.PlTemplateV1.type.name).update(j.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Qt.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(j.PlTemplateV1.type,JSON.stringify(j.PlTemplateV1.fromV2Data(s).data));for(const[i,a]of Object.entries(s.libs??{})){const c=j.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Qt))}for(const[i,a]of Object.entries(s.software??{})){const c=j.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Ae))}for(const[i,a]of Object.entries(s.assets??{})){const c=j.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Ae))}for(const[i,a]of Object.entries(s.templates??{})){const c=j.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Gr))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(j.PlTemplateOverrideV1.type,JSON.stringify(j.PlTemplateOverrideV1.fromV2Data(s))),n=j.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function Jr(s,e){const t=new Map,r=(o,n)=>{const i=se.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,s,r);t.set(a,c)}return t.get(a)};return r(e,Gr)}const Mr={name:"TengoTemplateGet",version:"1"},_r="registry",Kr="templateURI",Hr="template",lo={name:"TengoTemplatePack",version:"1"},uo={name:"TengoTemplatePackConvert",version:"1"},po="templatePack",ho="template";async function qr(s){switch(s.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return k.assertNever(s)}}function fo(s,e){const t=s.createStruct(Mr),r=h.field(t,_r),o=h.field(t,Kr),n=h.field(t,Hr);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function We(s,e){switch(e.type){case"from-registry":return fo(s,e);case"explicit":return ao(s,e);case"prepared":return co(s,e);default:return k.assertNever(e)}}const Ot={name:"Frontend/FromUrl",version:"1"},$t={name:"Frontend/FromFolder",version:"1"};function go(s,e){switch(e.type){case"url":return s.createValue(Ot,JSON.stringify({url:e.url}));case"local":return s.createValue($t,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}class mo{constructor(){S(this,"nextMessageId",0);S(this,"worker");S(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:M.resolve(void 0,"worker.js"),t=this.worker=new bs.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?a(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const vo={name:"BlockPackCustom",version:"1"},Wr="template",zr="frontend";function Zt(s){return s.endsWith("/")?s:`${s}/`}function yo(s){return Buffer.from(s).toString("utf8")}function Fe(s){return JSON.parse(yo(s))}class wo{constructor(e,t,r){S(this,"remoteContentCache",new Fr.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await He.request(e,t)).body.arrayBuffer()},sizeCalculation:e=>e.byteLength}));this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"prepared":return e.config;case"dev-v1":{const t=await zt(e.folder),r=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await q.loadPackDescription(e.folder),r=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Zt(e.registryUrl)}${q.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Fe(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Fe(o)}default:return k.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=_t(o,new mo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,a=!0}finally{var c=Kt(o,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await zt(e.folder),r=await Z.promises.readFile(t.workflow),o=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await q.loadPackDescription(e.folder),r=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Z.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await qe(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${Zt(e.registryUrl)}${q.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=Fe(i);return{type:"explicit",template:{type:"explicit",content:n},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Fe(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,a]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return k.assertNever(e)}}}function So(s,e){const t={config:e.config,source:e.source},r=s.createStruct(vo,JSON.stringify(t));return s.createField(h.field(r,Wr),"Input",We(s,e.template)),s.createField(h.field(r,zr),"Input",go(s,e.frontend)),s.lock(r),r}function er(s,e){switch(e.type){case"prepared":return So(s,e);default:return k.assertNever(e.type)}}function Le(s,e){return{__isRef:!0,blockId:s,name:e}}function bo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function vt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(bo(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)vt(s,o,t);else for(const[,o]of Object.entries(e))vt(s,o,t);return;default:k.assertNever(r)}}function Po(s,e){const t={upstreams:new Set,missingReferences:!1};return vt(t,s,e),t}function ae(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Xr{constructor(e){S(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function yt(s){const e=new Map;let t;for(const{id:r}of ae(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Xr(e)}function Ge(s,e){const t=new Map,r=new Set;for(const{id:o}of ae(s)){const n=e(o);if(n===void 0)continue;const i=Po(n,r),a={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,a),i.upstreams.forEach(c=>t.get(c).downstream.add(o)),r.add(o)}return new Xr(t)}function Ro(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function wt(s,e){if(s.size>e.size)return wt(e,s);for(const t of s)if(e.has(t))return!0;return!1}function tr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Ro(n.upstream,i.upstream)||wt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?wt(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let ot;async function Yr(){if(ot===void 0){const s=await qr(Ps.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=se.createHash("sha256").update(s.content).digest("hex");ot={spec:s,hash:e}}return ot}function Eo(s,e,t){return kt(s,e,!0,{pf:t},["result"]).result}function nt(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class rr{constructor(e,t){S(this,"currentInputsC",nt(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));S(this,"actualProductionInputsC",nt(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return JSON.parse(Buffer.from(e).toString())}));S(this,"productionStaleC",nt(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),Wr,"Input")}}const Co=s=>{throw new Error(`No new block info for ${s}`)};class _e{constructor(e,t,r,o,n,i,a,c,u,l,d,g){S(this,"globalModCount",0);S(this,"fieldsChanged",!1);S(this,"lastModifiedChanged",!1);S(this,"structureChanged",!1);S(this,"metaChanged",!1);S(this,"renderingStateChanged",!1);S(this,"changedBlockFrontendStates",new Set);S(this,"blocksWithChangedInputs",new Set);S(this,"stagingGraph");S(this,"pendingProductionGraph");S(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=d,this.ctxExportTplHolder=g}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(H.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=yt(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ge(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ge(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ae(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=h.field(this.rid,J(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(h.field(this.rid,J(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(h.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Yt(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Yt(this.tx,t)}exportCtx(e){return Eo(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Xt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Xt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Co){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=yt(e),i=Ge(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=tr(r,n),c=tr(o,i);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new rr(u,{});this.blockInfos.set(u,l);const d=t(u),g=er(this.tx,d.blockPack);this.setBlockField(u,"blockPack",h.Pl.wrapInHolder(this.tx,g),"NotReady"),this.setBlockFieldObj(u,"blockSettings",this.createJsonFieldValue(H.InitialBlockSettings)),this.setBlockFieldObj(u,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(u,d.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);o.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,er(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const u of c.upstream)if(!r.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of ae(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const u of o.nodes.get(a.id).upstream)if(n.has(u)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new Lr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const c=r.shift(),u=this.getBlockInfo(c).fields;if(!(((i=u.prodOutput)==null?void 0:i.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))o.has(l)||(r.push(l),o.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,ft(t)):this.tx.setKValue(this.rid,ft(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,gt):this.tx.setKValue(this.rid,gt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Me,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Te,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,ht(e)):this.tx.setKValue(this.rid,ht(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,xr),i=e.getKValueJson(t,$e),a=e.getKValueJson(t,Te),c=e.getKValueJson(t,de),u=e.getKValueJson(t,Me),l=e.listKeyValuesString(t),[d,g,f,E,m,{stagingRefreshTimestamp:x,blocksInLimbo:D},U]=await Promise.all([o,n,i,a,c,u,l]);if(g!==Vr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${g}`);const I=new Map;for(const p of d.fields){const v=zs(p.name);if(v===void 0)continue;let w=I.get(v.blockId);w===void 0&&(w={id:v.blockId,fields:{}},I.set(v.blockId,w)),w.fields[v.fieldName]=h.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const _=await Yr(),pe=mt(_.hash),N=d.fields.find(p=>p.name===pe);let Y;N!==void 0?Y=h.ensureResourceIdNotNull(N.value):(Y=h.Pl.wrapInHolder(e,We(e,_.spec)),e.createField(h.field(t,mt(_.hash)),"Dynamic",Y));const le={stagingRefreshTimestamp:x},z=new Set(D),K=new Map;for(const p of U){const v=Hs(p.key);v!==void 0&&K.set(v,p.value)}const G=[];I.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!h.isResource(v.ref)||h.isResourceRef(v.ref))throw new Error("unexpected behaviour");G.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of G){const w=await v;p.value=w.data,h.isNotNullResourceId(w.error)?p.status="Error":w.resourceReady||h.isNotNullResourceId(w.originalResourceId)?p.status="Ready":p.status="NotReady"}const Q=new Map;I.forEach(({id:p,fields:v})=>Q.set(p,new rr(p,v)));const he=new Set;for(const p of ae(m)){if(!Q.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);he.add(p.id)}Q.forEach(p=>{if(!he.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new _e(t,e,r,g,f,E,m,le,z,Q,K,Y);return y.fixProblemsAndMigrate(),y}}async function ko(s,e=Gs){const t=s.createEphemeral(Js);s.lock(t);const r=String(Date.now());s.setKValue(t,xr,JSON.stringify(Vr)),s.setKValue(t,Ct,r),s.setKValue(t,$e,r),s.setKValue(t,Te,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(Vs)),s.setKValue(t,Me,JSON.stringify(Us));const o=await Yr();return s.createField(h.field(t,mt(o.hash)),"Dynamic",h.Pl.wrapInHolder(s,We(s,o.spec))),t}async function De(s,e,t){return te(s,e,void 0,t)}async function te(s,e,t,r){if(s instanceof h.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await _e.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await _e.load(s,e,t),n=await r(o);return o.save(),n}}function*Oo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:k.assertNever(s)}}function sr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function $o(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:sr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:sr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(s)}}const To=h.resourceType("PColumnData/JsonPartitioned","1"),Io=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ao=h.resourceType("PColumnData/BinaryPartitioned","1"),Fo=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Lo=h.resourceType("PColumnData/Json","1");function Do(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,Lo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,To)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Io)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Ao)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Fo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=r[u];l===void 0&&(l={},r[u]=l),r[u].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function No(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Bo(s,e){const t=se.createHash("sha256");return t.update(re(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function or(s,e){return re({__isRef:!0,blockId:s,name:e})}function jo(s,e){return re({resolvePath:s,name:e})}function Qr(s,e=!0,t=!1,r=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const l of s.listInputFields()){const d=l.match(o);if(!d){if(e)throw new Error(`unexpected field name ${l}`);continue}let g=k.notEmpty((a=d.groups)==null?void 0:a.name);if(!g.startsWith(r)){if(e)throw new Error(`unexpected field name ${l}`);continue}g=g.slice(r.length);const f=k.notEmpty((c=d.groups)==null?void 0:c.type);let E=n.get(g);switch(E===void 0&&(E={},n.set(g,E)),f){case"spec":E.spec=(u=s.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":E.hasData=!0,E.data=()=>s.traverseOrError({field:l,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,l]of n)l.data===void 0&&(l.hasData=!1);return{locked:i,results:n}}function xo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Qr(s,e,!1,t);Rs(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw c.error;n[i]={id:r.length===0?Bo(a.spec,c.value):jo(r,i),spec:a.spec,data:c.value}}return n}class Tt{constructor(e,t){S(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,a,c,u,l;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(l=(u=(c=r.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const r=this.blocks.get(e);if(r===void 0)return;const o=(a=(i=r.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return L.mapValueInVOE(n,u=>({id:or(e,t),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:Le(i,a),obj:{id:u.ok?or(i,a):void 0,spec:c.spec,data:u}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[u,l]of a.prod.results)c.add(u),n(i,u,l)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,l]of a.staging.results)c.has(u)||n(i,u,l)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,u]of i.staging.results)u.spec!==void 0&&(e.push({ref:Le(n,c),obj:u.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,u]of i.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:Le(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),L.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Le(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=k.notEmpty(o.getKeyValueAsJson(de)),a=yt(n).traverseIds("upstream",r),c=new Map;for(const u of ae(n)){if(!a.has(u.id))continue;const l=nr(o.traverse({field:J(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(u.id,"prodUiCtx"),stableIfNotFound:!0})),d=nr(o.traverse({field:J(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:d})}return new Tt(e,c)}}function nr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Qr(e.value,!1,!0)}function It(s,e){return{blockId:e,args:n=>k.notEmpty(n.accessor(s).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:J(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(ht(e)),blockMeta:n=>{const i=n.accessor(s).node(),a=k.notEmpty(i.getKeyValueAsJson(de)),c=new Map;for(const u of ae(a))c.set(u.id,u);return c}}}function Zr(s,e){return{...It(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:J(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Tt.create(t,s,e)}}function*X(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*X(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*X(t);return;case"MakeArray":for(const t of s.template)yield*X(t);return;case"GetJsonField":case"GetResourceField":yield*X(s.source),yield*X(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*X(s.source),yield*X(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*X(s.source);return;case"IsEmpty":yield*X(s.arg);return;case"Not":yield*X(s.operand);return;case"And":case"Or":yield*X(s.operand1),yield*X(s.operand2);return;default:k.assertNever(s)}}function Vo(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Re(s,e){return s===void 0?void 0:e(s)}function Uo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Go(s){for(const e of X(s))if(Uo(e))return!0;return!1}function ze(s){return{type:"ReturnResult",result:s}}function O(s){return()=>ze(s)}const Jo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return O(e)},Mo=s=>{const e=s.source;if(e===void 0)return O(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return O(t)},_o=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?O(void 0):({cCtx:r})=>{var o;return ze((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function es(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function Ko(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):()=>({type:"ScheduleSubroutine",subroutine:ts(r.length),args:es(r,o=>$({...s,[e.itVar]:o},e.mapping))})}}function ts(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return O(t)}}function Ho(s,e){return t=>{const r=t.source;if(r===void 0)return O(void 0);const o={};for(const[n,i]of Object.entries(r)){const a={...s,[e.itVar]:i};o[n]=$(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:qo,args:o})}}const qo=s=>O(s),Wo=s=>{const e=s.arg;return O(e===void 0?void 0:e.length===0)},zo=s=>{const e=s.operand;return O(e===void 0?void 0:!e)},Xo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e&&t)},Yo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e||t)},Qo=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t})=>{var r;return ze((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Zo=s=>{const e=s.source,t=s.field;return O(e===void 0||t===void 0?void 0:e[t])};function en(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=O(void 0);else{const u={...s,[e.itVar]:c.persist()};i[a]=$(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:tn,args:i}}}}const tn=s=>O(s),rn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:B.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},sn=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:B.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},on=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:B.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},nn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},an=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},cn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},ln=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},un=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},dn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},pn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},hn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function $(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>ze(t(r.cCtx)):O(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:os(t,s,e.cfg)});case"Immediate":return O(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:$(s,e.source),field:$(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Ko(s,e),args:{source:$(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Ho(s,e),args:{source:$(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:Vo(e.template,t=>$(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:ts(e.template.length),args:es(e.template,t=>$(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{source:$(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{arg:$(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:{operand:$(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{operand1:$(s,e.operand1),operand2:$(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{operand1:$(s,e.operand1),operand2:$(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:en(s,e),args:{source:$(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{source:$(s,e.source),field:$(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:$(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:rn,args:{source:$(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{source:$(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:$(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:$(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{source:$(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:cn(e.format),args:{source:$(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:ln,args:{source:$(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:un(e.lines),args:{source:$(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:dn(e.patternToSearch),args:{source:$(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:pn(e.patternToSearch),args:{source:$(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:$(s,e.source)}});default:return k.assertNever(e)}}const fn=["$prod","$staging"];function gn(s){return{$blockId:s.blockId,$args:e=>JSON.parse(s.args(e)),$ui:e=>{const t=s.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:s.prod,$staging:s.staging}}const rs=Symbol(),ss="return",mn={op:rs,arg:ss};function vn(s){return s.op==rs&&s.arg==ss}function yn(){return{pendingSubroutines:new Map}}function ir(s,e,t,r){const o=new Lr(t),n=(a,c)=>{if(vn(a))return e.result=c,!1;const u=k.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const u=Symbol(),l=Object.entries(c.args),d=l.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[g,f]of l)o.push({destination:{op:u,arg:g},operation:f});e.pendingSubroutines.set(u,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:k.assertNever(c)}}return i}function wn(s,e,t,r={}){return os(s,gn(e),t,r)}function os(s,e,t,r={}){const o=`${e.blockId}#`+re({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>fn.indexOf(n)===-1)),cfg:t});return B.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},a=yn();return{ir:ir(i,a,[{destination:mn,operation:$(e,t)}],!0),postprocessValue(u){const l=[];for(const E of u)l.push({destination:E.destination,operation:O(E.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},g=new Map;for(const[E,m]of a.pendingSubroutines)g.set(E,{...m,args:{...m.args}});const f={result:a.result,pendingSubroutines:g};if(ir(d,f,l,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function Sn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function ar(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ke{constructor(e,t,r,o,n){S(this,"callbackRegistry");S(this,"fnJSONStringify");S(this,"fnJSONParse");S(this,"computablesToResolve",{});S(this,"computableCtx");S(this,"accessors",new Map);S(this,"meta");S(this,"errorRepo",new bn);S(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ke.cleanErrorContext(t),t}}runCallback(e,...t){try{return Oe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw Ke.cleanErrorContext(r),this.errorRepo.getOriginal(r)}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return ar(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ar(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=xo(n,t,r,o),a={};for(const[c,u]of Object.entries(i))a[c]=L.mapPObjectData(u,l=>this.wrapAccessor(l));return a}registerComputable(e,t){const r=`${e}_${se.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",B.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",B.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=k.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:L.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:L.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return L.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>L.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(L.mapPTableDef(e,t=>L.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):L.isDataInfo(e)?L.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=se.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Sn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Oe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(L.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(a,c)=>{const u=(...l)=>{try{return c(...l)}catch(d){const g=this.errorRepo.setAndRecreateForQuickJS(d);throw this.vm.newError(g)}};this.vm.newFunction(a,u).consume(l=>this.vm.setProp(t,a,l)),this.vm.newFunction(a,c).consume(l=>this.vm.setProp(t,a+"__internal__",l))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...u)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...u.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,u,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(u),...l.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class bn{constructor(){S(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=se.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof Oe.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",h.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${h.stringifyWithResourceId(e)}`);const o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${h.stringifyWithResourceId(e)}`);return new Es.PlQuickJSError(e,o)}}function Xe(s,e){return Re(s.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=L.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Ne=process.env.MI_LOG_OUTPUT_STATUS;function Pn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),B.Computable.makeRaw(a=>{const c=new Oe.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(s.quickJs.newRuntime());u.setMemoryLimit(1024*1024*8),u.setMaxStackSize(1024*320);const l=c.manage(u.newContext()),d=new Ke(c,l,e,s,a);d.evaluateBundle(r.content);const g=d.runCallback(t.handle);d.resetComputableCtx();let f=0;return Ne&&Ne!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:(E,{unstableMarker:m,stable:x})=>{for(const[U,I]of Object.entries(E))d.runCallback(U,I);const D=d.importObjectUniversal(g);return f++,Ne&&(Ne!=="unstable-only"||!x)&&console.log(x?`Stable output ${t.handle} calculated ${D!==void 0?"defined":"undefined"}; (#${f})`:`Unstable output ${t.handle}; marker = ${m}; ${D!==void 0?"defined":"undefined"} (#${f})`),D}}},n)}function Rn(s){return L.isConfigLambda(s)?s.isActive===!0:Go(s)}function Ee(s,e,t,r,o,n={}){if(L.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Pn(s,e,t,r,o,n)}else return wn(s.driverKit,e,t,n)}function En(s,e,t){return B.Computable.make(r=>{var E,m,x,D,U,I,_,pe;const o=r.accessor(s).node(),n=k.notEmpty(o.getKeyValueAsJson(Ct)),i=k.notEmpty(o.getKeyValueAsJson($e)),a=k.notEmpty(o.getKeyValueAsJson(Te)),c=k.notEmpty(o.getKeyValueAsJson(de)),u=k.notEmpty(o.getKeyValueAsJson(Me)),l=new Map;for(const{id:N}of ae(c)){const Y=o.traverse({field:J(N,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let le;const z=o.traverse({field:J(N,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(z!==void 0){const K=o.getField({field:J(N,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),G=o.getField({field:J(N,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});le={arguments:z.getDataAsJson(),stale:Y.id!==z.id,outputError:K.error!==void 0||G.error!==void 0||((E=K.value)==null?void 0:E.getError())!==void 0||((m=G.value)==null?void 0:m.getError())!==void 0,outputsError:((x=K.error)==null?void 0:x.getDataAsString())??((U=(D=K.value)==null?void 0:D.getError())==null?void 0:U.getDataAsString()),exportsError:((I=G.error)==null?void 0:I.getDataAsString())??((pe=(_=G.value)==null?void 0:_.getError())==null?void 0:pe.getDataAsString()),finished:(K.value!==void 0&&K.value.getIsReadyOrError()||K.error!==void 0&&K.error.getIsReadyOrError())&&(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())}}l.set(N,{currentArguments:Y.getDataAsJson(),prod:le})}const d=Ge(c,N=>l.get(N).currentArguments),g=new Set(u.blocksInLimbo),f=[...ae(c)].map(({id:N,label:Y,renderingMode:le})=>{var b,R,T,C,F;const z=k.notEmpty(l.get(N)),K=k.notEmpty(d.nodes.get(N));let G="NotCalculated";z.prod!==void 0&&(g.has(N)?G="Limbo":G=z.prod.finished?"Done":"Running");const Q=Xe(o,N),{sections:he,title:y,inputsValid:p,sdkVersion:v}=Re(Q,({bpId:V,cfg:A})=>{const ce=It(s,N);return{sections:Ee(t,ce,A.sections,A.code,V).wrap({recover:ye=>(t.logger.error("Error in block model sections"),t.logger.error(ye),[])}),title:Re(A.title,ye=>Ee(t,ce,ye,A.code,V).wrap({recover:ms=>(t.logger.error("Error in block model title"),t.logger.error(ms),"Invalid title")})),inputsValid:Ee(t,ce,A.inputsValid,A.code,V).wrap({recover:ye=>(t.logger.error("Error in block model argsValid"),t.logger.error(ye),!1)}),sdkVersion:A.sdkVersion}})||{},w=o.traverse({field:J(N,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Re(Q,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:w}));return{projectResourceId:h.resourceIdToString(s.rid),id:N,label:y??Y,title:y??Y,renderingMode:le,stale:((b=z.prod)==null?void 0:b.stale)!==!1||G==="Limbo",missingReference:K.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",N)],downstreams:[...d.traverseIdsExcludingRoots("downstream",N)],calculationStatus:G,outputErrors:((R=z.prod)==null?void 0:R.outputError)===!0,outputsError:(T=z.prod)==null?void 0:T.outputsError,exportsError:(C=z.prod)==null?void 0:C.exportsError,settings:w,sections:he,inputsValid:p,updateInfo:{},currentBlockPack:(F=Q==null?void 0:Q.info)==null?void 0:F.source,updates:P,sdkVersion:v,navigationState:e.getState(N)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(gt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var l,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(g=>n.has(g))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(g=>o.has(g))===-1,u={...i,canRun:c,stale:a,updateSuggestions:((l=i.updates)==null?void 0:l.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete u.updates,u})}}}).withStableType()}function Cn(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,Ot)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,$t)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function kn(s,e){if(s!==void 0)return B.Computable.make(t=>Cn(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function On(s,e,t){return B.Computable.make(r=>{var a;const o=r.accessor(s).node(),n=Xe(o,e),i=(a=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:zr,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:kn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ns(s,e,t){if(t===void 0)return B.Computable.make(i=>ns(s,e,i),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=It(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(ft(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function $n(s,e,t){return B.Computable.make(r=>{const o=r.accessor(s).node(),n=Zr(s,e);return Re(Xe(o,e),({cfg:i,bpId:a})=>{const c={};for(const[u,l]of Object.entries(i.outputs)){const d=Ee(t,n,l,i.code,a);c[u]=B.Computable.wrapError(d,1)}return c})},{key:"outputs#"+h.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Tn(s,e){return B.Computable.make(t=>{const r=t.accessor(s).node(),o=k.notEmpty(r.getKeyValueAsJson(de)),n=[];for(const{id:i}of ae(o)){const a=Xe(r,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,l])=>l).filter(l=>Rn(l)).map(l=>l);if(c.length===0)continue;const u=Zr(r.persist(),i);for(const l of c)n.push(B.Computable.wrapError(Ee(e,u,l,a.cfg.code,a.bpId)))}return n})}class In{constructor(){S(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new B.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...L.DefaultNavigationState},change:new B.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return B.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function cr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class Ye{constructor(e,t,r){S(this,"rid");S(this,"overview");S(this,"navigationStates",new In);S(this,"blockComputables",new Map);S(this,"blockFrontends",new Map);S(this,"activeConfigs");S(this,"refreshLoopResult");S(this,"abortController",new AbortController);S(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=En(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Tn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await De(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Dr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=se.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=L.extractConfig(a);return await te(this.env.pl,this.rid,o,u=>u.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await te(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await te(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await te(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await De(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await De(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await te(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await te(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await te(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await te(this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,J(e,"blockPack")))).value),n=h.ensureResourceIdNotNull((await r.getField(h.field(o,h.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(k.notEmpty(i.data)).toString("utf-8"));await te(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=$n(this.projectTree.entry(),e,this.env),n={fullState:B.Computable.make(i=>({argsAndUiState:ns(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var l,d,g;const a=(g=(d=(l=i.overview)==null?void 0:l.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:g.sdkVersion,u=a&&Fn(a)&&i.outputs!==void 0?Dn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:u,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=On(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await De(e.pl,t,o=>{});const r=await Je.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:An},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,a)=>{var c,u;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((u=i.data)==null?void 0:u.byteLength)??0)});const n=Je.treeDumpStats(o);await pt.writeFile(`${h.resourceIdToString(t)}.json`,cr(o)),await pt.writeFile(`${h.resourceIdToString(t)}.stats.json`,cr(n))}return new Ye(e,t,r)}}function An(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Fn(s){return!Ln(s,"1.26.0")}function Ln(s,e){const t=s.split(".").map(Number),r=e.split(".").map(Number);return t[0]>r[0]||t[0]===r[0]&&t[1]>r[1]||t[0]===r[0]&&t[1]===r[1]&&t[2]>r[2]}function Dn(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:r.moreErrors}}return e}const At={logger:new k.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ft(s){return{blobDownloadPath:M.join(s,"download"),downloadBlobToURLPath:M.join(s,"downloadToURL")}}const is={...At,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function as(s){return{...Ft(s),frontendDownloadPath:M.join(s,"frontend")}}function Nn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var St={exports:{}};const Bn="2.0.0",cs=256,jn=Number.MAX_SAFE_INTEGER||9007199254740991,xn=16,Vn=cs-6,Un=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Qe={MAX_LENGTH:cs,MAX_SAFE_COMPONENT_LENGTH:xn,MAX_SAFE_BUILD_LENGTH:Vn,MAX_SAFE_INTEGER:jn,RELEASE_TYPES:Un,SEMVER_SPEC_VERSION:Bn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Gn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var Ze=Gn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=Qe,n=Ze;e=s.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const g="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[g,r]],E=x=>{for(const[D,U]of f)x=x.split(`${D}*`).join(`${D}{0,${U}}`).split(`${D}+`).join(`${D}{1,${U}}`);return x},m=(x,D,U)=>{const I=E(D),_=d++;n(x,_,D),l[x]=_,c[_]=D,u[_]=I,i[_]=new RegExp(D,U?"g":void 0),a[_]=new RegExp(I,U?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${g}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${g}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(St,St.exports);var Ie=St.exports;const Jn=Object.freeze({loose:!0}),Mn=Object.freeze({}),_n=s=>s?typeof s!="object"?Jn:s:Mn;var Lt=_n;const lr=/^[0-9]+$/,ls=(s,e)=>{const t=lr.test(s),r=lr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},Kn=(s,e)=>ls(e,s);var us={compareIdentifiers:ls,rcompareIdentifiers:Kn};const Be=Ze,{MAX_LENGTH:ur,MAX_SAFE_INTEGER:je}=Qe,{safeRe:dr,safeSrc:pr,t:xe}=Ie,Hn=Lt,{compareIdentifiers:fe}=us;let qn=class ie{constructor(e,t){if(t=Hn(t),e instanceof ie){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>ur)throw new TypeError(`version is longer than ${ur} characters`);Be("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?dr[xe.LOOSE]:dr[xe.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>je||this.major<0)throw new TypeError("Invalid major version");if(this.minor>je||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>je||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<je)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Be("SemVer.compare",this.version,this.options,e),!(e instanceof ie)){if(typeof e=="string"&&e===this.version)return 0;e=new ie(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof ie||(e=new ie(e,this.options)),fe(this.major,e.major)||fe(this.minor,e.minor)||fe(this.patch,e.patch)}comparePre(e){if(e instanceof ie||(e=new ie(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(Be("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return fe(r,o)}while(++t)}compareBuild(e){e instanceof ie||(e=new ie(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Be("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return fe(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?pr[xe.PRERELEASELOOSE]:pr[xe.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),fe(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var W=qn;const hr=W,Wn=(s,e,t=!1)=>{if(s instanceof hr)return s;try{return new hr(s,e)}catch(r){if(!t)return null;throw r}};var ve=Wn;const zn=ve,Xn=(s,e)=>{const t=zn(s,e);return t?t.version:null};var Yn=Xn;const Qn=ve,Zn=(s,e)=>{const t=Qn(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var ei=Zn;const fr=W,ti=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new fr(s instanceof fr?s.version:s,t).inc(e,r,o).version}catch{return null}};var ri=ti;const gr=ve,si=(s,e)=>{const t=gr(s,null,!0),r=gr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,a=n?r:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}const l=c?"pre":"";return t.major!==r.major?l+"major":t.minor!==r.minor?l+"minor":t.patch!==r.patch?l+"patch":"prerelease"};var oi=si;const ni=W,ii=(s,e)=>new ni(s,e).major;var ai=ii;const ci=W,li=(s,e)=>new ci(s,e).minor;var ui=li;const di=W,pi=(s,e)=>new di(s,e).patch;var hi=pi;const fi=ve,gi=(s,e)=>{const t=fi(s,e);return t&&t.prerelease.length?t.prerelease:null};var mi=gi;const mr=W,vi=(s,e,t)=>new mr(s,t).compare(new mr(e,t));var oe=vi;const yi=oe,wi=(s,e,t)=>yi(e,s,t);var Si=wi;const bi=oe,Pi=(s,e)=>bi(s,e,!0);var Ri=Pi;const vr=W,Ei=(s,e,t)=>{const r=new vr(s,t),o=new vr(e,t);return r.compare(o)||r.compareBuild(o)};var Dt=Ei;const Ci=Dt,ki=(s,e)=>s.sort((t,r)=>Ci(t,r,e));var Oi=ki;const $i=Dt,Ti=(s,e)=>s.sort((t,r)=>$i(r,t,e));var Ii=Ti;const Ai=oe,Fi=(s,e,t)=>Ai(s,e,t)>0;var et=Fi;const Li=oe,Di=(s,e,t)=>Li(s,e,t)<0;var Nt=Di;const Ni=oe,Bi=(s,e,t)=>Ni(s,e,t)===0;var ds=Bi;const ji=oe,xi=(s,e,t)=>ji(s,e,t)!==0;var ps=xi;const Vi=oe,Ui=(s,e,t)=>Vi(s,e,t)>=0;var Bt=Ui;const Gi=oe,Ji=(s,e,t)=>Gi(s,e,t)<=0;var jt=Ji;const Mi=ds,_i=ps,Ki=et,Hi=Bt,qi=Nt,Wi=jt,zi=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return Mi(s,t,r);case"!=":return _i(s,t,r);case">":return Ki(s,t,r);case">=":return Hi(s,t,r);case"<":return qi(s,t,r);case"<=":return Wi(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var hs=zi;const Xi=W,Yi=ve,{safeRe:Ve,t:Ue}=Ie,Qi=(s,e)=>{if(s instanceof Xi)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?Ve[Ue.COERCEFULL]:Ve[Ue.COERCE]);else{const c=e.includePrerelease?Ve[Ue.COERCERTLFULL]:Ve[Ue.COERCERTL];let u;for(;(u=c.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Yi(`${r}.${o}.${n}${i}${a}`,e)};var Zi=Qi;class ea{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var ta=ea,it,yr;function ne(){if(yr)return it;yr=1;const s=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(P=>!m(P[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&x(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const v=this.set[p];for(let w=0;w<v.length;w++)w>0&&(this.formatted+=" "),this.formatted+=v[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const w=((this.options.includePrerelease&&f)|(this.options.loose&&E))+":"+p,P=r.get(w);if(P)return P;const b=this.options.loose,R=b?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];p=p.replace(R,Q(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[u.COMPARATORTRIM],l),i("comparator trim",p),p=p.replace(c[u.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[u.CARETTRIM],g),i("caret trim",p);let T=p.split(" ").map(A=>U(A,this.options)).join(" ").split(/\s+/).map(A=>G(A,this.options));b&&(T=T.filter(A=>(i("loose invalid filter",A,this.options),!!A.match(c[u.COMPARATORLOOSE])))),i("range list",T);const C=new Map,F=T.map(A=>new n(A,this.options));for(const A of F){if(m(A))return[A];C.set(A.value,A)}C.size>1&&C.has("")&&C.delete("");const V=[...C.values()];return r.set(w,V),V}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>D(w,v)&&p.set.some(P=>D(P,v)&&w.every(b=>P.every(R=>b.intersects(R,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(he(this.set[v],p,this.options))return!0;return!1}}it=e;const t=ta,r=new t,o=Lt,n=tt(),i=Ze,a=W,{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:g}=Ie,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:E}=Qe,m=y=>y.value==="<0.0.0-0",x=y=>y.value==="",D=(y,p)=>{let v=!0;const w=y.slice();let P=w.pop();for(;v&&w.length;)v=w.every(b=>P.intersects(b,p)),P=w.pop();return v},U=(y,p)=>(i("comp",y,p),y=N(y,p),i("caret",y),y=_(y,p),i("tildes",y),y=le(y,p),i("xrange",y),y=K(y,p),i("stars",y),y),I=y=>!y||y.toLowerCase()==="x"||y==="*",_=(y,p)=>y.trim().split(/\s+/).map(v=>pe(v,p)).join(" "),pe=(y,p)=>{const v=p.loose?c[u.TILDELOOSE]:c[u.TILDE];return y.replace(v,(w,P,b,R,T)=>{i("tilde",y,w,P,b,R,T);let C;return I(P)?C="":I(b)?C=`>=${P}.0.0 <${+P+1}.0.0-0`:I(R)?C=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:T?(i("replaceTilde pr",T),C=`>=${P}.${b}.${R}-${T} <${P}.${+b+1}.0-0`):C=`>=${P}.${b}.${R} <${P}.${+b+1}.0-0`,i("tilde return",C),C})},N=(y,p)=>y.trim().split(/\s+/).map(v=>Y(v,p)).join(" "),Y=(y,p)=>{i("caret",y,p);const v=p.loose?c[u.CARETLOOSE]:c[u.CARET],w=p.includePrerelease?"-0":"";return y.replace(v,(P,b,R,T,C)=>{i("caret",y,P,b,R,T,C);let F;return I(b)?F="":I(R)?F=`>=${b}.0.0${w} <${+b+1}.0.0-0`:I(T)?b==="0"?F=`>=${b}.${R}.0${w} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.0${w} <${+b+1}.0.0-0`:C?(i("replaceCaret pr",C),b==="0"?R==="0"?F=`>=${b}.${R}.${T}-${C} <${b}.${R}.${+T+1}-0`:F=`>=${b}.${R}.${T}-${C} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.${T}-${C} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?R==="0"?F=`>=${b}.${R}.${T}${w} <${b}.${R}.${+T+1}-0`:F=`>=${b}.${R}.${T}${w} <${b}.${+R+1}.0-0`:F=`>=${b}.${R}.${T} <${+b+1}.0.0-0`),i("caret return",F),F})},le=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>z(v,p)).join(" ")),z=(y,p)=>{y=y.trim();const v=p.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return y.replace(v,(w,P,b,R,T,C)=>{i("xRange",y,w,P,b,R,T,C);const F=I(b),V=F||I(R),A=V||I(T),ce=A;return P==="="&&ce&&(P=""),C=p.includePrerelease?"-0":"",F?P===">"||P==="<"?w="<0.0.0-0":w="*":P&&ce?(V&&(R=0),T=0,P===">"?(P=">=",V?(b=+b+1,R=0,T=0):(R=+R+1,T=0)):P==="<="&&(P="<",V?b=+b+1:R=+R+1),P==="<"&&(C="-0"),w=`${P+b}.${R}.${T}${C}`):V?w=`>=${b}.0.0${C} <${+b+1}.0.0-0`:A&&(w=`>=${b}.${R}.0${C} <${b}.${+R+1}.0-0`),i("xRange return",w),w})},K=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[u.STAR],"")),G=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?u.GTE0PRE:u.GTE0],"")),Q=y=>(p,v,w,P,b,R,T,C,F,V,A,ce)=>(I(w)?v="":I(P)?v=`>=${w}.0.0${y?"-0":""}`:I(b)?v=`>=${w}.${P}.0${y?"-0":""}`:R?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,I(F)?C="":I(V)?C=`<${+F+1}.0.0-0`:I(A)?C=`<${F}.${+V+1}.0-0`:ce?C=`<=${F}.${V}.${A}-${ce}`:y?C=`<${F}.${V}.${+A+1}-0`:C=`<=${C}`,`${v} ${C}`.trim()),he=(y,p,v)=>{for(let w=0;w<y.length;w++)if(!y[w].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let w=0;w<y.length;w++)if(i(y[w].semver),y[w].semver!==n.ANY&&y[w].semver.prerelease.length>0){const P=y[w].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return it}var at,wr;function tt(){if(wr)return at;wr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],g=l.match(d);if(!g)throw new TypeError(`Invalid comparator: ${l}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new a(g[2],this.options.loose):this.semver=s}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===s||l===s)return!0;if(typeof l=="string")try{l=new a(l,this.options)}catch{return!1}return n(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||n(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||n(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}at=e;const t=Lt,{safeRe:r,t:o}=Ie,n=hs,i=Ze,a=W,c=ne();return at}const ra=ne(),sa=(s,e,t)=>{try{e=new ra(e,t)}catch{return!1}return e.test(s)};var rt=sa;const oa=ne(),na=(s,e)=>new oa(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var ia=na;const aa=W,ca=ne(),la=(s,e,t)=>{let r=null,o=null,n=null;try{n=new ca(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new aa(r,t))}),r};var ua=la;const da=W,pa=ne(),ha=(s,e,t)=>{let r=null,o=null,n=null;try{n=new pa(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new da(r,t))}),r};var fa=ha;const ct=W,ga=ne(),Sr=et,ma=(s,e)=>{s=new ga(s,e);let t=new ct("0.0.0");if(s.test(t)||(t=new ct("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const a=new ct(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||Sr(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Sr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var va=ma;const ya=ne(),wa=(s,e)=>{try{return new ya(s,e).range||"*"}catch{return null}};var Sa=wa;const ba=W,fs=tt(),{ANY:Pa}=fs,Ra=ne(),Ea=rt,br=et,Pr=Nt,Ca=jt,ka=Bt,Oa=(s,e,t,r)=>{s=new ba(s,r),e=new Ra(e,r);let o,n,i,a,c;switch(t){case">":o=br,n=Ca,i=Pr,a=">",c=">=";break;case"<":o=Pr,n=ka,i=br,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ea(s,e,r))return!1;for(let u=0;u<e.set.length;++u){const l=e.set[u];let d=null,g=null;if(l.forEach(f=>{f.semver===Pa&&(f=new fs(">=0.0.0")),d=d||f,g=g||f,o(f.semver,d.semver,r)?d=f:i(f.semver,g.semver,r)&&(g=f)}),d.operator===a||d.operator===c||(!g.operator||g.operator===a)&&n(s,g.semver))return!1;if(g.operator===c&&i(s,g.semver))return!1}return!0};var xt=Oa;const $a=xt,Ta=(s,e,t)=>$a(s,e,">",t);var Ia=Ta;const Aa=xt,Fa=(s,e,t)=>Aa(s,e,"<",t);var La=Fa;const Rr=ne(),Da=(s,e,t)=>(s=new Rr(s,t),e=new Rr(e,t),s.intersects(e,t));var Na=Da;const Ba=rt,ja=oe;var xa=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((l,d)=>ja(l,d,t));for(const l of i)Ba(l,e,t)?(n=l,o||(o=l)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const a=[];for(const[l,d]of r)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);const c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e};const Er=ne(),Vt=tt(),{ANY:lt}=Vt,we=rt,Ut=oe,Va=(s,e,t={})=>{if(s===e)return!0;s=new Er(s,t),e=new Er(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Ga(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Ua=[new Vt(">=0.0.0-0")],Cr=[new Vt(">=0.0.0")],Ga=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===lt){if(e.length===1&&e[0].semver===lt)return!0;t.includePrerelease?s=Ua:s=Cr}if(e.length===1&&e[0].semver===lt){if(t.includePrerelease)return!0;e=Cr}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=kr(o,f,t):f.operator==="<"||f.operator==="<="?n=Or(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Ut(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!we(f,String(o),t)||n&&!we(f,String(n),t))return null;for(const E of e)if(!we(f,String(E),t))return!1;return!0}let a,c,u,l,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,g=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(l=l||f.operator===">"||f.operator===">=",u=u||f.operator==="<"||f.operator==="<=",o){if(g&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===g.major&&f.semver.minor===g.minor&&f.semver.patch===g.patch&&(g=!1),f.operator===">"||f.operator===">="){if(a=kr(o,f,t),a===f&&a!==o)return!1}else if(o.operator===">="&&!we(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(c=Or(n,f,t),c===f&&c!==n)return!1}else if(n.operator==="<="&&!we(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&u&&!n&&i!==0||n&&l&&!o&&i!==0||g||d)},kr=(s,e,t)=>{if(!s)return e;const r=Ut(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Or=(s,e,t)=>{if(!s)return e;const r=Ut(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Ja=Va;const ut=Ie,$r=Qe,Ma=W,Tr=us,_a=ve,Ka=Yn,Ha=ei,qa=ri,Wa=oi,za=ai,Xa=ui,Ya=hi,Qa=mi,Za=oe,ec=Si,tc=Ri,rc=Dt,sc=Oi,oc=Ii,nc=et,ic=Nt,ac=ds,cc=ps,lc=Bt,uc=jt,dc=hs,pc=Zi,hc=tt(),fc=ne(),gc=rt,mc=ia,vc=ua,yc=fa,wc=va,Sc=Sa,bc=xt,Pc=Ia,Rc=La,Ec=Na,Cc=xa,kc=Ja;var Oc={parse:_a,valid:Ka,clean:Ha,inc:qa,diff:Wa,major:za,minor:Xa,patch:Ya,prerelease:Qa,compare:Za,rcompare:ec,compareLoose:tc,compareBuild:rc,sort:sc,rsort:oc,gt:nc,lt:ic,eq:ac,neq:cc,gte:lc,lte:uc,cmp:dc,coerce:pc,Comparator:hc,Range:fc,satisfies:gc,toComparators:mc,maxSatisfying:vc,minSatisfying:yc,minVersion:wc,validRange:Sc,outside:bc,gtr:Pc,ltr:Rc,intersects:Ec,simplifyRange:Cc,subset:kc,SemVer:Ma,re:ut.re,src:ut.src,tokens:ut.t,SEMVER_SPEC_VERSION:$r.SEMVER_SPEC_VERSION,RELEASE_TYPES:$r.RELEASE_TYPES,compareIdentifiers:Tr.compareIdentifiers,rcompareIdentifiers:Tr.rcompareIdentifiers};const $c=Nn(Oc),Tc={minDelay:1500},Ic="__no_updates__";class Ac extends B.PollComputablePool{constructor(t,r,o={}){super({...o,...Tc},r);S(this,"http");S(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${re(t)}`;default:return Ic}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Et(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await q.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await qe(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,H.StableChannel))u=H.StableChannel;else{if(await c.getLatestOverview(n.id,H.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${H.blockPackIdToString(n.id)}`),{suggestions:[]};u=H.AnyChannel}else u=n.channel;const l=await c.getUpdateSuggestions(n.id,u);if(l===void 0||l.length===0)return{suggestions:[]};l.reverse();let d;switch(i){case void 0:d=l[0].update;break;case"major":d=(r=l.find(E=>E.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=l.find(E=>E.type==="patch"))==null?void 0:o.update;break}const g=l.map(({type:E,update:m})=>({type:E,update:{...n,id:{...n.id,version:m}}}));if(d===void 0)return{suggestions:g};if(a!==void 0&&$c.lte(d,a))return{suggestions:g};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(E){this.logger.warn(E)}})(),{suggestions:g,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return re(t)===re(r)}}class Ir{constructor(){S(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Se;function ue(){return Se||(Se={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Se.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Se)}function Ce(s){return String(s.id)}const Fc=["Int","Long","Float","Double","String","Bytes"];function dt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const be=(s,e)=>typeof e=="bigint"?e.toString():e;class Lc{constructor(e,t,r,o){S(this,"rustPFrame");S(this,"blobIdToResource",new Map);S(this,"blobHandleComputables",new Map);S(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});S(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});S(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=r;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of Oo(a.data))this.blobIdToResource.set(Ce(c),c);const i=[...new Map(o.map(a=>({...a,data:$o(a.data,Ce)})).map(a=>[re(a),a])).values()];try{const a=new Cs.PFrame(ue().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.rustPFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Dc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Nc{constructor(e,t){S(this,"pFrames");S(this,"pTables");S(this,"blobContentCache");this.blobDriver=e,this.logger=t;const r=new Fr.LRUCache({maxSize:1e9,fetchMethod:async o=>await Nr.readFile(o),sizeCalculation:o=>o.length});this.blobContentCache=r,this.pFrames=new class extends Ir{constructor(o,n){super(),this.blobDriver=o,this.logger=n}createNewResource(o){return ue().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,be)}`),new Lc(this.blobDriver,this.logger,r,o)}calculateParamsKey(o){return jc(o)}}(this.blobDriver,this.logger),this.pTables=new class extends Ir{constructor(o){super(),this.pFrames=o}createNewResource(o){const n=o.pFrameHandle;ue().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,be)}`);const i=this.pFrames.getByKey(n).rustPFrame.createTable({src:ke(o.def.src),filters:dt(o.def.filters)},o.signal).then(async a=>{if(o.def.sorting.length===0)return a;try{return await a.sort(o.def.sorting,o.signal)}finally{a.dispose()}});return new Dc(i)}calculateParamsKey(o){return Bc(o)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>Fc.find(i=>i===n.spec.valueType)).map(n=>L.mapPObjectData(n,i=>Je.isPlTreeNodeAccessor(i)?Do(i):L.isDataInfo(i)?L.mapDataInfo(i,a=>a.resourceInfo):No(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(L.extractAllColumns(e.src),t),n=L.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return ue().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(L.mapPTableDef(e,a=>a.spec),be)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[re(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).rustPFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,r){return ue().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,be)}`),await this.pFrames.getByKey(e).rustPFrame.createTable({src:ke(t.src),filters:dt(t.filters)},r).then(async o=>{if(t.sorting.length===0)return o;try{return await o.sort(t.sorting,r)}finally{o.dispose()}}).then(async o=>{try{const n=o.getSpec(),i=await o.getData([...n.keys()]);return n.map((a,c)=>({spec:a,data:i[c]}))}finally{o.dispose()}})}async getUniqueValues(e,t,r){return ue().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,be)}`),await this.pFrames.getByKey(e).rustPFrame.getUniqueValues({...t,filters:dt(t.filters)},r)}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r){return await(await this.pTables.getByKey(e).table).getData(t,r)}}function ke(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>ke(e))};case"outer":return{type:"outer",primary:ke(s.primary),secondary:s.secondary.map(e=>ke(e))};default:k.assertNever(s)}}function Bc(s){const e=se.createHash("sha256");return e.update(re(s)),e.digest().toString("hex")}function jc(s){const e=[...s].map(r=>L.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:Ce(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[Ce(c.index),Ce(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=se.createHash("sha256");return t.update(re(e)),t.digest().toString("hex")}async function gs(s,e,t){const r={...At,...Ft(e),...t},o=new k.HmacSha256Signer(r.localSecret),n=ee.createDownloadClient(r.logger,s,r.localProjections),i=ee.createLogsClient(s,r.logger),a=ee.createUploadBlobClient(s,r.logger),c=ee.createUploadProgressClient(s,r.logger),u=new ee.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),l=new ee.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new ee.UploadDriver(r.logger,o,a,c,r.uploadDriverOps),g=new ee.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new ee.LogsDriver(r.logger,g,u),E=await ee.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),m=new Nc(u,r.logger);return{blobDriver:u,blobToURLDriver:l,logDriver:f,lsDriver:E,signer:o,uploadDriver:d,pFrameDriver:m}}class Gt{constructor(e,t,r,o,n,i,a,c){S(this,"pl");S(this,"projectList");S(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=se.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await ko(o,e);return o.createField(h.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await h.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await te(this.pl,e,r,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await Ye.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),await this.projectListTree.terminate(),await this.env.retryHttpDispatcher.destroy(),await this.pl.close()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return k.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...is,...as(t),...r};o.defaultTreeOptions.logStat=ue().logTreeStats,o.debugOps.dumpInitialTreeState=ue().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async m=>{const x=h.field(m.clientRoot,Xs);m.createField(x,"Dynamic");const D=await m.getField(x);if(h.isNullResourceId(D.value)){const U=m.createEphemeral(Ur);return m.lock(U),m.setField(x,U),await m.commit(),await U.globalId}else return D.value}),i=o.logger,a=await gs(e,t,o),c=new He.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new jr(c),l=new wo(u,a.signer,c),d=new ee.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),g={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:l,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new Ac(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Oe.getQuickJS()},f=new B.WatchableValue([]),E=await Qs(e,n,f,g);return new Gt(g,a,a.signer,n,f,E.tree,u,E.computable)}}const xc=["undici:request:create","undici:request:bodySent","undici:request:headers","undici:request:error","undici:request:trailers","undici:client:sendHeaders","undici:client:beforeConnect","undici:client:connected","undici:client:connectError","undici:socket:close","undici:socket:connect","undici:socket:error","undici:pool:request","undici:pool:connect","undici:pool:disconnect","undici:pool:destroy","undici:dispatcher:request","undici:dispatcher:connect","undici:dispatcher:disconnect","undici:dispatcher:retry"];async function Vc(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,...e},r=[];xc.forEach(c=>{ks.channel(c).subscribe(l=>{var g;const d=new Date().toISOString();(g=l==null?void 0:l.response)!=null&&g.headers&&(l.response.headers=l.response.headers.map(f=>f.toString())),r.push(JSON.stringify({timestamp:d,event:c,data:l}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=h.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ge(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new h.UnauthenticatedPlClient(n).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new h.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ge(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ge(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Pe(t.autoUpdateCdnUrl,t,a)),Uc(o,s,t,r)}async function ge(s,e,t){const r=bt(),o=[];for(;Ar(r)<s;){const n=bt();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=Ar(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Dr.setTimeout(c)}return o}async function Pe(s,e,t){const{body:r,statusCode:o}=await He.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Uc(s,e,t,r){const o=s.plPings.filter(a=>a.response.ok),n=s.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
5
2
  Network report:
6
3
  pl endpoint: ${e};
7
4
  options: ${JSON.stringify(t,null,2)}.
@@ -42,11 +39,11 @@ ${JSON.stringify(i,null,2)}
42
39
  Undici logs:
43
40
  ${r.join(`
44
41
  `)}
45
- `}function me(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=Vc(s);return`
42
+ `}function me(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=Gc(s);return`
46
43
  total: ${s.length};
47
44
  successes: ${e.length};
48
45
  errors: ${s.length-e.length};
49
46
  mean in ms: ${t};
50
47
  median in ms: ${r};
51
- `}function Vc(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function bt(){return Date.now()}function Ar(s){return bt()-s}exports.BlockPackRegistry=Ns;exports.CentralBlockRegistry=Bs;exports.DefaultDriverKitOpsPaths=Ft;exports.DefaultDriverKitOpsSettings=At;exports.DefaultMiddleLayerOpsPaths=as;exports.DefaultMiddleLayerOpsSettings=is;exports.FrontendFromFolderResourceType=$t;exports.FrontendFromUrlResourceType=Ot;exports.MiddleLayer=Gt;exports.Project=Ye;exports.TengoTemplateGet=Jr;exports.TengoTemplateGetRegistry=_r;exports.TengoTemplateGetTemplate=Hr;exports.TengoTemplateGetTemplateURI=Kr;exports.TengoTemplatePack=lo;exports.TengoTemplatePackConvert=uo;exports.TengoTemplatePackConvertTemplate=ho;exports.TengoTemplatePackConvertTemplatePack=po;exports.V1CentralDevSnapshotRegistry=xs;exports.V1CentralRegistry=js;exports.V2RegistryProvider=jr;exports.checkNetwork=jc;exports.createRenderTemplate=kt;exports.getDevV1PacketMtime=Et;exports.getDevV2PacketMtime=qe;exports.initDriverKit=gs;exports.loadTemplate=We;exports.prepareTemplateSpec=qr;Object.keys(L).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>L[s]})});Object.keys(H).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>H[s]})});Object.keys(Ht).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Ht[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
48
+ `}function Gc(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function bt(){return Date.now()}function Ar(s){return bt()-s}exports.BlockPackRegistry=Ns;exports.CentralBlockRegistry=Bs;exports.DefaultDriverKitOpsPaths=Ft;exports.DefaultDriverKitOpsSettings=At;exports.DefaultMiddleLayerOpsPaths=as;exports.DefaultMiddleLayerOpsSettings=is;exports.FrontendFromFolderResourceType=$t;exports.FrontendFromUrlResourceType=Ot;exports.MiddleLayer=Gt;exports.Project=Ye;exports.TengoTemplateGet=Mr;exports.TengoTemplateGetRegistry=_r;exports.TengoTemplateGetTemplate=Hr;exports.TengoTemplateGetTemplateURI=Kr;exports.TengoTemplatePack=lo;exports.TengoTemplatePackConvert=uo;exports.TengoTemplatePackConvertTemplate=ho;exports.TengoTemplatePackConvertTemplatePack=po;exports.V1CentralDevSnapshotRegistry=xs;exports.V1CentralRegistry=js;exports.V2RegistryProvider=jr;exports.checkNetwork=Vc;exports.createRenderTemplate=kt;exports.getDevV1PacketMtime=Et;exports.getDevV2PacketMtime=qe;exports.initDriverKit=gs;exports.loadTemplate=We;exports.prepareTemplateSpec=qr;Object.keys(L).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>L[s]})});Object.keys(H).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>H[s]})});Object.keys(Ht).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Ht[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
52
49
  //# sourceMappingURL=index.js.map