@milaboratories/pl-middle-layer 1.38.0 → 1.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var Fn=Object.defineProperty;var Tr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Ir=s=>{throw TypeError(s)};var $n=(s,e,t)=>e in s?Fn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var P=(s,e,t)=>$n(s,typeof e!="symbol"?e+"":e,t);var Fr=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Ir("Object expected");var r,n;t&&(r=e[Tr("asyncDispose")]),r===void 0&&(r=e[Tr("dispose")],t&&(n=r)),typeof r!="function"&&Ir("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(o){return Promise.reject(o)}}),s.push([t,r,e])}else t&&s.push([t]);return e},$r=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,l){return l=Error(c),l.name="SuppressedError",l.error=i,l.suppressed=a,l},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(o,c=>(n(c),o()))}catch(c){n(c)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Dr=require("@milaboratories/pl-deployments"),Ye=require("undici"),Z=require("@platforma-sdk/block-tools"),ie=require("node:fs"),_=require("node:path"),Dn=require("yaml"),b=require("@milaboratories/ts-helpers"),$e=require("node:fs/promises"),Ln=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),He=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),$=require("@milaboratories/pl-model-backend"),Gs=require("lru-cache"),An=require("node:worker_threads"),_s=require("denque"),me=require("@platforma-sdk/workflow-tengo"),ne=require("canonicalize"),Nn=require("node:assert"),he=require("quickjs-emscripten"),jn=require("@milaboratories/pl-errors"),Bn=require("remeda"),Ks=require("node:timers/promises"),H=require("@milaboratories/pl-drivers"),Hs=require("@milaboratories/pframes-rs-node"),xn=require("node:diagnostics_channel"),Vn=require("node:stream/consumers"),Ws=require("node:os");function cr(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 Un=cr(_),zs=cr($e),Lr=cr(Bn);async function Ar(s){try{return await zs.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Mn=[Z.RegistryV1.PlPackageYamlConfigFile],qn=[Z.RegistryV1.PlPackageJsonConfigFile],lr=["backend","dist","tengo","tpl","main.plj.gz"],ur=["config","dist","config.json"],Xs=["frontend","dist"],Nr="block-model/dist/config.json",Jn="block-ui/package.json",Gn=[lr,ur,Mn,qn,Xs];async function _n(s){return await Ar(_.join(s,...ur))!==void 0||await Ar(_.join(s,...lr))!==void 0}function ct(s,e){const t=Ln.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function jr(s,e){if(_.isAbsolute(s)||(s=_.resolve(s)),await _n(s))return{workflow:_.join(s,...lr),config:_.join(s,...ur),ui:_.join(s,...Xs)};{const t=ct(s,Nr),r=ct(s,Nr),n=ct(s,Jn);return{workflow:t,config:r,ui:_.resolve(n,"..","dist")}}}async function Kn(s){try{return await ie.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Hn(s){try{return await ie.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function dr(s){let e=0n;for(const t of Gn){const r=_.join(s,...t),n=await Hn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function Qe(s){const e=await ie.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await ie.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Wn{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 n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await Ye.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const a of i){const{organization:c,package:l,latestMeta:u,latestVersion:d}=a,p={organization:c,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[Q.AnyChannel]:f,[Q.StableChannel]:f},allVersions:a.allVersions.map(y=>({version:y,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(n=>({...n,registryId:e.id}));case"local-dev":for(const n of await ie.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=_.join(r.path,n.name),i=await Kn(_.join(o,Z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=Z.RegistryV1.PlPackageConfigData.parse(Dn.parse(i)),c=await dr(o),l={organization:a.organization,name:a.package,version:"DEV"},u={id:l,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:o,mtime:c}};t.push({registryId:e.id,id:l,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let a=o,c=await Z.tryLoadPackDescription(a);if(c===void 0){for(const l of["block","meta"])if(a=_.join(o,l),c=await Z.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const l=await Qe(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),featureFlags:c.featureFlags,spec:{type:"dev-v2",folder:a,mtime:l}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return b.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 n=(i=this.registries.find(a=>a.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Ys{constructor(e){P(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new Z.RegistryV2Reader(Z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const zn={type:"remote-v2",url:"https://blocks.pl-open.science/"},Xn={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Yn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Qn={groups:[{id:"default",label:"Default",blocks:[]}]},Zn={stagingRefreshTimestamp:0,blocksInLimbo:[]},eo={label:"New Project"},to={name:"UserProject",version:"2"},We="SchemaVersion",De="2",pr="ProjectCreated",Le="ProjectLastModified",Ae="ProjectMeta",fe="ProjectStructure",ze="BlockRenderingState",ro="BlockArgsAuthor/";function rr(s){return`${ro}${s}`}const sr="ProjectStructureAuthor",so="__serviceTemplate_";function nr(s){return`${so}${s}`}function W(s,e){return`${s}-${e}`}const no=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function oo(s){const e=s.match(no);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const io="projects",Qs={name:"Projects",version:"1"},ao=s=>g.resourceTypesEqual(s.type,Qs)?s.fields:[];async function co(s,e,t,r){const n=await He.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:ao},r.logger);return{computable:J.Computable.make(i=>{const a=i.accessor(n.entry()).node(),c=t.getValue(i);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const d=a.traverse(u);if(d===void 0)continue;const p=b.notEmpty(d.getKeyValueAsJson(Ae)),f=b.notEmpty(d.getKeyValueAsJson(pr)),y=b.notEmpty(d.getKeyValueAsJson(Le));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:n}}const lo={name:"EphRenderTemplate",version:"1"},uo={name:"RenderTemplate",version:"1"};function Ze(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(lo):s.createStruct(uo),i=g.field(o,"template"),a=g.field(o,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(o),g.Pl.futureRecord(s,o,n,"Output","outputs/")}const po={name:"BContextEnd",version:"1"},fo={name:"BContext",version:"1"},go="id",ho="parent/",mo=["context","result"];function Br(s,e,t){return Ze(s,e,!0,t,mo)}function vo(s){const e=s.createEphemeral(po);return s.lock(e),e}function xr(s,e){if(e.length===0)return vo(s);if(e.length===1)return e[0];const t=s.createEphemeral(fo);s.createField(g.field(t,go),"Input",g.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${ho}${r}`),"Input",e[r]);return s.lock(t),t}function Zs(s,e){const t=new Map,r=(n,o,i)=>{const a=te.createHash("sha256");o.updateCacheKey(n,a,i);const c=a.digest("hex");if(!t.has(c)){const l=o.render(n,s,r,i);t.set(c,l)}return t.get(c)};return r(e.template,en,e.hashToSource)}const Vr={updateCacheKey(s,e,t){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(be(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV3Data(s,be(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(be(s.name,t,s.sourceHash))},render(s,e,t,r){const n=$.PlTemplateSoftwareV1.fromV3Data(s,be(s.name,r,s.sourceHash)),o=e.createStruct($.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},en={updateCacheKey(s,e,t){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(be(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),Vr.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),Ue.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),Ue.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV3Data(s,be(s.name,r,s.sourceHash)).data));for(const[a,c]of Object.entries(s.libs??{})){const l=$.PlTemplateV1.libField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Vr,r))}for(const[a,c]of Object.entries(s.software??{})){const l=$.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.assets??{})){const l=$.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.templates??{})){const l=$.PlTemplateV1.tplField(n,a);e.createField(l,"Input"),e.setField(l,t(c,en,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV3Data(s))),i=$.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function be(s,e,t){return b.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function yo(s,e){const t=$.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return rn(s,t);case"pl.tengo-template.v3":return Zs(s,t);default:b.assertNever(r)}}function wo(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return rn(s,t);case"pl.tengo-template.v3":return Zs(s,t);default:b.assertNever(r)}}const Ur={hash(s,e){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV2Data(s).data))}},Me={hash(s,e){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=$.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct($.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},tn={hash(s,e){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Ur.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV2Data(s).data));for(const[i,a]of Object.entries(s.libs??{})){const c=$.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Ur))}for(const[i,a]of Object.entries(s.software??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[i,a]of Object.entries(s.assets??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[i,a]of Object.entries(s.templates??{})){const c=$.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(a,tn))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV2Data(s))),o=$.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function rn(s,e){const t=new Map,r=(n,o)=>{const i=te.createHash("sha256");o.hash(n,i);const a=i.digest("hex");if(!t.has(a)){const c=o.render(n,s,r);t.set(a,c)}return t.get(a)};return r(e,tn)}const sn={name:"TengoTemplateGet",version:"1"},nn="registry",on="templateURI",an="template",bo={name:"TengoTemplatePack",version:"1"},So={name:"TengoTemplatePackConvert",version:"1"},Ro="templatePack",Co="template";async function fr(s){switch(s.type){case"from-file":return{type:"explicit",content:await ie.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return b.assertNever(s)}}function ko(s,e){const t=s.createStruct(sn),r=g.field(t,nn),n=g.field(t,on),o=g.field(t,an);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Be(s,e){switch(e.type){case"from-registry":return ko(s,e);case"explicit":return yo(s,e);case"prepared":return wo(s,e);default:return b.assertNever(e)}}const gr={name:"Frontend/FromUrl",version:"1"},hr={name:"Frontend/FromFolder",version:"1"};function Po(s,e){switch(e.type){case"url":return s.createValue(gr,JSON.stringify({url:e.url}));case"local":return s.createValue(hr,JSON.stringify({path:e.path,signature:e.signature}));default:return b.assertNever(e)}}class Eo{constructor(){P(this,"nextMessageId",0);P(this,"worker");P(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:_.resolve(void 0,"worker.js"),t=this.worker=new An.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?a(new Error(o)):i(n)}),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,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Oo={name:"BlockPackCustom",version:"1"},cn="template",ln="frontend";function Mr(s){return s.endsWith("/")?s:`${s}/`}function To(s){return Buffer.from(s).toString("utf8")}function qe(s){return JSON.parse(To(s))}class Io{constructor(e,t,r){P(this,"remoteContentCache",new Gs.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await Ye.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 jr(e.folder),r=await ie.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await ie.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Mr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return qe(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=await this.remoteContentCache.forceFetch(r.model.url);return qe(n)}default:return b.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Fr(n,new Eo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,a=!0}finally{var c=$r(n,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await jr(e.folder),r=await ie.promises.readFile(t.workflow),n=JSON.parse(await ie.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await ie.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await ie.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Qe(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${Mr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=qe(i);return{type:"explicit",template:{type:"explicit",content:o},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),n=async()=>qe(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,a]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return b.assertNever(e)}}}function Fo(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Oo,JSON.stringify(t));return s.createField(g.field(r,cn),"Input",Be(s,e.template)),s.createField(g.field(r,ln),"Input",Po(s,e.frontend)),s.lock(r),r}function qr(s,e){switch(e.type){case"prepared":return Fo(s,e);default:return b.assertNever(e.type)}}function Je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function $o(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function or(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($o(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const n of e)or(s,n,t);else for(const[,n]of Object.entries(e))or(s,n,t);return;default:b.assertNever(r)}}function Do(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return or(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class un{constructor(e){P(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const a of n){const c=this.nodes.get(a);r(c),c[e].forEach(l=>{o.has(l)||(o.add(l),i.push(l))})}n=i}}}function ir(s){const e=new Map;let t;for(const{id:r}of oe(s)){const n={id:r,missingReferences:!1};e.set(r,n),t===void 0?(n.directUpstream=n.upstream=new Set,n.enrichments=n.enrichmentTargets=new Set):(n.directUpstream=n.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([n.id]),t.enrichments=t.enrichmentTargets=new Set),t=n}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new un(e)}function Ke(s,e){const t=new Map,r=new un(t),n=new Set;for(const{id:o}of oe(s)){const i=e(o);if(i===void 0)continue;const a=Do(i.args,n),c=new Set([...a.upstreams,...r.traverseIds("enrichments",...a.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of oe(s)){if(p===o)break;if(c.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(a.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:a.missingReferences,upstream:l,directUpstream:a.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),a.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),l.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function Lo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function ar(s,e){if(s.size>e.size)return ar(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Jr(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!Lo(o.upstream,i.upstream)||ar(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?ar(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let lt;async function dn(){if(lt===void 0){const s=await fr(me.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=te.createHash("sha256").update(s.content).digest("hex");lt={spec:s,hash:e}}return lt}function Ao(s,e,t){return Ze(s,e,!0,{pf:t},["result"]).result}let ye;function se(){return ye||(ye={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0,logProjectMutationStat:process.env.MI_LOG_PROJECT_MUTATION_STAT!==void 0,logOutputRecalculations:process.env.MI_LOG_OUTPUT_RECALCULATIONS!==void 0},process.env.MI_LOG_OUTPUT_STATUS&&(ye.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(ye.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),ye)}function ut(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class Gr{constructor(e,t,r,n){P(this,"currentArgsC",ut(()=>this.fields.currentArgs.modCount,()=>b.cachedDeserialize(this.fields.currentArgs.value)));P(this,"prodArgsC",ut(()=>{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 b.cachedDeserialize(e)}));P(this,"productionStaleC",ut(()=>{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,this.config=r,this.source=n}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 currentArgs(){return this.currentArgsC()}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 prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),cn,"Input")}}const No=s=>{throw new Error(`No new block info for ${s}`)};class Xe{constructor(e,t,r,n,o,i,a,c,l,u,d,p){P(this,"globalModCount",0);P(this,"fieldsChanged",!1);P(this,"lastModifiedChanged",!1);P(this,"structureChanged",!1);P(this,"metaChanged",!1);P(this,"renderingStateChanged",!1);P(this,"blocksWithChangedInputs",new Set);P(this,"stagingGraph");P(this,"pendingProductionGraph");P(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.ctxExportTplHolder=d,this.projectHelper=p}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(Q.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=ir(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=b.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=b.notEmpty(r.fields.blockPack);return g.isResourceId(n.ref)&&g.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),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(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=g.field(this.rid,W(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(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(g.field(this.rid,W(e,o))),delete i[o],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,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.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,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.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,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.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")}setStates(e){const t=[];let r=!1;for(const n of e){const o=this.getBlockInfo(n.blockId);let i=!1;for(const a of["args","uiState"]){if(!(a in n))continue;const c=n[a];if(c==null)throw new Error(`Can't set ${a} to null or undefined, please omit the key if you don't want to change it`);const l=a==="args"?"currentArgs":"uiState";let u,d=!1;if(a==="args")u=b.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=b.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(o.fields[l].value,u)===0)continue;console.log("setting",l,d,u.length);const p=this.tx.createValue(d?g.Pl.JsonGzObject:g.Pl.JsonObject,u);this.setBlockField(n.blockId,l,p,"Ready",u),i=!0,a==="args"&&t.push(n.blockId)}i&&(this.blocksWithChangedInputs.add(n.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:n})=>this.resetStaging(n)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),xr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),xr(this.tx,t)}exportCtx(e){return Ao(this.tx,g.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 n=t.getTemplate(this.tx),o=Br(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.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 n=t.getTemplate(this.tx),o=Br(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=No){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=ir(e),i=Jr(r,o);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0)}for(const l of i.onlyInB){const u=t(l),d=new Gr(l,{},L.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=qr(this.tx,u.blockPack);this.setBlockField(l,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),this.setBlockFieldObj(l,"uiState",this.createJsonFieldValueByContent(u.uiState??"{}")),d.check()}for(const l of i.different)this.resetStaging(l);const a=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),c=Jr(n,a);n.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.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 n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,qr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=n.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const l of c.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const a of oe(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const l of n.nodes.get(a.id).upstream)if(o.has(l)){c=!0;break}}c&&(this.renderProductionFor(a.id),o.add(a.id))}const i=[...o];return n.traverse("downstream",i,a=>{o.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new _s(e),n=new Set(e),o=[];for(;!r.isEmpty();){const c=r.shift(),l=this.getBlockInfo(c).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))n.has(u)||(r.push(u),n.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(n.id,i),t.set(n.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 n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.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,rr(t)):this.tx.setKValue(this.rid,rr(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,sr):this.tx.setKValue(this.rid,sr,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,Le,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ze,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Ae,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,We),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,Ae),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,ze),d=await o,p=new Map;for(const m of d.fields){const v=oo(m.name);if(v===void 0)continue;let S=p.get(v.blockId);S===void 0&&(S={id:v.blockId,fields:{}},p.set(v.blockId,S)),S.fields[v.fieldName]=g.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[S,w]of Object.entries(v)){if(w.ref===void 0)continue;if(!g.isResource(w.ref)||g.isResourceRef(w.ref))throw new Error("unexpected behaviour");const k=S;f.push([m,k,w,t.getResourceData(w.ref,k=="blockPack")])}});const[y,h,R,O,{stagingRefreshTimestamp:V,blocksInLimbo:D}]=await Promise.all([i,a,c,l,u]);if(y!==De)throw Number(y)<Number(De)?new L.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new L.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const x=[];for(const[m,v,S,w]of f){const k=await w;if(S.value=k.data,g.isNotNullResourceId(k.error)?S.status="Error":k.resourceReady||g.isNotNullResourceId(k.originalResourceId)?S.status="Ready":S.status="NotReady",v==="blockPack"){const C=k.fields.find(I=>I.name===g.Pl.HolderRefField);if(C===void 0)throw new Error("Block pack ref field is missing");x.push([m,t.getResourceData(g.ensureResourceIdNotNull(C.value),!1)])}}for(const[m,v]of x){const S=await v,w=b.cachedDeserialize(b.notEmpty(S.data));m.blockConfig=L.extractConfig(w.config),m.blockPack=w.source}const M=await dn(),T=nr(M.hash),B=d.fields.find(m=>m.name===T);let E;B!==void 0?E=g.ensureResourceIdNotNull(B.value):(E=g.Pl.wrapInHolder(t,Be(t,M.spec)),t.createField(g.field(r,nr(M.hash)),"Dynamic",E));const K={stagingRefreshTimestamp:V},de=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:S,blockPack:w})=>Y.set(m,new Gr(m,v,b.notEmpty(S),b.notEmpty(w))));const G=new Set;for(const m of oe(O)){if(!Y.has(m.id))throw new Error(`Inconsistent project structure: no inputs for ${m.id}`);G.add(m.id)}Y.forEach(m=>{if(!G.has(m.id))throw new Error(`Inconsistent project structure: no structure entry for ${m.id}`);m.check()});const X=new Xe(r,t,n,y,h,R,O,K,de,Y,E,e);return X.fixProblemsAndMigrate(),X}}async function jo(s,e=eo){const t=s.createEphemeral(to);s.lock(t);const r=String(Date.now());s.setKValue(t,We,JSON.stringify(De)),s.setKValue(t,pr,r),s.setKValue(t,Le,r),s.setKValue(t,Ae,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(Qn)),s.setKValue(t,ze,JSON.stringify(Zn));const n=await dn();return s.createField(g.field(t,nr(n.hash)),"Dynamic",g.Pl.wrapInHolder(s,Be(s,n.spec))),t}async function Ge(s,e,t,r){return ce(s,e,t,void 0,r)}async function ce(s,e,t,r,n){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await Xe.load(s,o,t,r),a=await n(i);return i.wasModified&&(i.save(),await o.commit(),se().logProjectMutationStat&&console.log(JSON.stringify(o.stat))),a});{const o=await Xe.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Bo(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:b.assertNever(s)}}function _r(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function xo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:_r(s.parts,e)};case"BinaryPartitioned":return{...s,parts:_r(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:b.assertNever(s)}}const Vo=g.resourceType("PColumnData/JsonPartitioned","1"),Uo=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Mo=g.resourceType("PColumnData/BinaryPartitioned","1"),qo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Jo=g.resourceType("PColumnData/Json","1");function Go(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(g.resourceTypesEqual(s.resourceType,Jo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,Vo)){const t=e,r=Object.fromEntries(s.listInputFields().map(n=>[n,s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Uo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of i){const c=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);r[c]=o.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Mo)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=o.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=o.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: ${g.resourceTypeToString(s.resourceType)}`)}function _o(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function Ko(s,e){const t=te.createHash("sha256");return t.update(ne(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Kr(s,e){return ne({__isRef:!0,blockId:s,name:e})}function Ho(s,e){return ne({resolvePath:s,name:e})}function pn(s,e=!0,t=!1,r=""){var a,c,l;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=b.notEmpty((a=d.groups)==null?void 0:a.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=b.notEmpty((c=d.groups)==null?void 0:c.type);let y=o.get(p);switch(y===void 0&&(y={},o.set(p,y)),f){case"spec":y.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function Wo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=pn(s,e,!1,t);Nn(n.locked);const o={};for(const[i,a]of n.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;o[i]={id:r.length===0?Ko(a.spec,c.value):Ho(r,i),spec:a.spec,data:c.value}}return o}class mr{constructor(e,t){P(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,a,c,l,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(a=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(n!==void 0||(n=(u=(l=(c=r.staging)==null?void 0:c.results)==null?void 0:l.get(t))==null?void 0:u.spec,n!==void 0))return n;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 n=(a=(i=r.prod)==null?void 0:i.results)==null?void 0:a.get(t),o=(c=n==null?void 0:n.data)==null?void 0:c.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return L.mapValueInVOE(o,l=>({id:Kr(e,t),spec:n.spec,data:l}));n!==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 n=i=>{r===void 0&&(r=i),t=!1},o=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:Je(i,a),obj:{id:l.ok?Kr(i,a):void 0,spec:c.spec,data:l}}):n(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||n(`prod_not_locked:${i}`);for(const[l,u]of a.prod.results)c.add(l),o(i,l,u)}if(a.staging!==void 0){a.staging.locked||n(`staging_not_locked:${i}`);for(const[l,u]of a.staging.results)c.has(l)||o(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[c,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Je(o,c),obj:l.spec}),a.add(c))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[c,l]of i.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:Je(o,c),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[a,c]of i.results)n.has(a)||c.spec===void 0||(n.add(a),L.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Je(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=b.notEmpty(n.getKeyValueAsJson(fe)),a=ir(o).traverseIds("upstream",r),c=new Map;for(const l of oe(o)){if(!a.has(l.id))continue;const u=Hr(n.traverse({field:W(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:W(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=Hr(n.traverse({field:W(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:W(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:d})}return new mr(e,c)}}function Hr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return pn(e.value,!1,!0)}function vr(s,e){return{blockId:e,args:o=>b.cachedDecode(b.notEmpty(o.accessor(s).node().traverse({field:W(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:o=>{var a;const i=(a=o.accessor(s).node().traverse({field:W(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:a.getData();return i?b.cachedDecode(i):void 0},uiState:o=>{var a;const i=(a=o.accessor(s).node().traverse({field:W(e,"uiState"),stableIfNotFound:!0}))==null?void 0:a.getData();return i?b.cachedDecode(i):void 0},blockMeta:o=>{const i=o.accessor(s).node(),a=b.notEmpty(i.getKeyValueAsJson(fe)),c=new Map;for(const l of oe(a))c.set(l.id,l);return c}}}function fn(s,e){return{...vr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var n;const r=(n=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>mr.create(t,s,e)}}function*re(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*re(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*re(t);return;case"MakeArray":for(const t of s.template)yield*re(t);return;case"GetJsonField":case"GetResourceField":yield*re(s.source),yield*re(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*re(s.source),yield*re(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*re(s.source);return;case"IsEmpty":yield*re(s.arg);return;case"Not":yield*re(s.operand);return;case"And":case"Or":yield*re(s.operand1),yield*re(s.operand2);return;default:b.assertNever(s)}}function zo(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Oe(s,e){return s===void 0?void 0:e(s)}function Xo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Yo(s){for(const e of re(s))if(Xo(e))return!0;return!1}function et(s){return{type:"ReturnResult",result:s}}function A(s){return()=>et(s)}const Qo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return A(e)},Zo=s=>{const e=s.source;if(e===void 0)return A(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return A(t)},ei=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?A(void 0):({cCtx:r})=>{var n;return et((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function gn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function ti(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):()=>({type:"ScheduleSubroutine",subroutine:hn(r.length),args:gn(r,n=>j({...s,[e.itVar]:n},e.mapping))})}}function hn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return A(t)}}function ri(s,e){return t=>{const r=t.source;if(r===void 0)return A(void 0);const n={};for(const[o,i]of Object.entries(r)){const a={...s,[e.itVar]:i};n[o]=j(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:si,args:n})}}const si=s=>A(s),ni=s=>{const e=s.arg;return A(e===void 0?void 0:e.length===0)},oi=s=>{const e=s.operand;return A(e===void 0?void 0:!e)},ii=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e&&t)},ai=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e||t)},ci=s=>{const e=s.source;return e===void 0?A(void 0):({cCtx:t})=>{var r;return et((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},li=s=>{const e=s.source,t=s.field;return A(e===void 0||t===void 0?void 0:e[t])};function ui(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const a of o.listInputFields()){const c=o.traverse(a);if(c===void 0)i[a]=A(void 0);else{const l={...s,[e.itVar]:c.persist()};i[a]=j(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:di,args:i}}}}const di=s=>A(s),pi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo),{postprocessValue:async n=>{if(n!==void 0)return await r.blobDriver.getContent(n.handle,s)}})})},fi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({cCtx:r,drivers:n})=>{const o=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(i=>n.blobDriver.getDownloadedBlob(o,i),{postprocessValue:async i=>i===void 0?void 0:(await n.blobDriver.getContent(i.handle,s)).toString()})}}},gi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const o=await r.blobDriver.getContent(n.handle,s);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},hi=s=>{const e=s.source;return e===void 0?A(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},mi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},vi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},yi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},wi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},bi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Si=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Ri=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function j(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>et(t(r.cCtx)):A(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:yn(t,s,e.cfg)});case"Immediate":return A(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:li,args:{source:j(s,e.source),field:j(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:ti(s,e),args:{source:j(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ri(s,e),args:{source:j(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:zo(e.template,t=>j(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:hn(e.template.length),args:gn(e.template,t=>j(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:j(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ni,args:{arg:j(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:oi,args:{operand:j(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{operand1:j(s,e.operand1),operand2:j(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:ai,args:{operand1:j(s,e.operand1),operand2:j(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:ui(s,e),args:{source:j(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ei,args:{source:j(s,e.source),field:j(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ci,args:{source:j(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:pi(e.range),args:{source:j(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:fi(e.range),args:{source:j(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:gi(e.range),args:{source:j(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:hi,args:{source:j(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:mi,args:{source:j(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:vi(e.format),args:{source:j(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:yi,args:{source:j(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:wi(e.lines),args:{source:j(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:bi(e.patternToSearch),args:{source:j(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:Si(e.patternToSearch),args:{source:j(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Ri,args:{source:j(s,e.source)}});default:return b.assertNever(e)}}const Ci=["$prod","$staging"];function ki(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 mn=Symbol(),vn="return",Pi={op:mn,arg:vn};function Ei(s){return s.op==mn&&s.arg==vn}function Oi(){return{pendingSubroutines:new Map}}function Wr(s,e,t,r){const n=new _s(t),o=(a,c)=>{if(Ei(a))return e.result=c,!1;const l=b.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),n.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;n.length>0;){const a=n.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!o(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)n.push({destination:a.destination,operation:c.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{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:b.assertNever(c)}}return i}function Ti(s,e,t,r={}){return yn(s,ki(e),t,r)}function yn(s,e,t,r={}){const n=`${e.blockId}#`+ne({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Ci.indexOf(o)===-1)),cfg:t});return J.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},a=Oi();return{ir:Wr(i,a,[{destination:Pi,operation:j(e,t)}],!0),postprocessValue(l){const u=[];for(const y of l)u.push({destination:y.destination,operation:A(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,h]of a.pendingSubroutines)p.set(y,{...h,args:{...h.args}});const f={result:a.result,pendingSubroutines:p};if(Wr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function zr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ii{constructor(e,t,r,n,o){P(this,"computablesToResolve",{});P(this,"computableCtx");P(this,"accessors",new Map);P(this,"meta");P(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.featureFlags=n,this.computableCtx=o,this.meta=t.blockMeta(o)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(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 zr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return zr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=Wo(o,t,r,n),a={};for(const[c,l]of Object.entries(i))a[c]=L.mapPObjectData(l,u=>this.wrapAccessor(u));return a}registerComputable(e,t){const r=`${e}_${te.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).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=b.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}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}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=te.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;he.Scope.withScope(n=>{const o=(i,a)=>{const c=(...l)=>{try{return a(...l)}catch(u){const d=t.errorRepo.setAndRecreateForQuickJS(u);throw r.newError(d)}};r.newFunction(i,c).consume(l=>r.setProp(e,i,l)),r.newFunction(i,a).consume(l=>r.setProp(e,i+"__internal__",l))};if(L.checkBlockFlag(this.featureFlags,"supportsLazyState"))o("args",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.args outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.args(this.computableCtx))}),o("uiState",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.uiState outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.uiState(this.computableCtx)??"{}")}),o("activeArgs",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.activeArgs outside the future lambda. Can't be directly used in this context.");const i=this.blockCtx.activeArgs(this.computableCtx);return i===void 0?r.undefined:r.newString(i)});else{const i=this.blockCtx.args(this.computableCtx),a=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(i))),r.setProp(e,"uiState",n.manage(r.newString(c??"{}"))),a!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(a)))}o("getAccessorHandleByName",i=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(i)),void 0)),o("resolveWithCommon",(i,a,...c)=>t.exportSingleValue(this.resolveWithCommon(r.getString(i),t.importObjectViaJson(a),...c.map(l=>t.importObjectViaJson(l))),void 0)),o("getResourceType",i=>t.exportObjectViaJson(this.getResourceType(r.getString(i)),void 0)),o("getInputsLocked",i=>t.exportSingleValue(this.getInputsLocked(r.getString(i)),void 0)),o("getOutputsLocked",i=>t.exportSingleValue(this.getOutputsLocked(r.getString(i)),void 0)),o("getIsReadyOrError",i=>t.exportSingleValue(this.getIsReadyOrError(r.getString(i)),void 0)),o("getIsFinal",i=>t.exportSingleValue(this.getIsFinal(r.getString(i)),void 0)),o("getError",i=>t.exportSingleValue(this.getError(r.getString(i)),void 0)),o("listInputFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("listOutputFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("listDynamicFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("getKeyValueBase64",(i,a)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(i),r.getString(a)),void 0)),o("getKeyValueAsString",(i,a)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(i),r.getString(a)),void 0)),o("getDataBase64",i=>t.exportSingleValue(this.getDataBase64(r.getString(i)),void 0)),o("getDataAsString",i=>t.exportSingleValue(this.getDataAsString(r.getString(i)),void 0)),o("parsePObjectCollection",(i,a,c,...l)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(i),r.dump(a),r.getString(c),...l.map(u=>r.getString(u))),void 0)),o("getBlobContentAsBase64",(i,a)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(i),t.importObjectUniversal(a)),void 0)),o("getBlobContentAsString",(i,a)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(i),t.importObjectUniversal(a)),void 0)),o("getDownloadedBlobContentHandle",i=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(i)),void 0)),o("getOnDemandBlobContentHandle",i=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(i)),void 0)),o("extractArchiveAndGetURL",(i,a)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(i),r.getString(a)),void 0)),o("getImportProgress",i=>t.exportSingleValue(this.getImportProgress(r.getString(i)),void 0)),o("getLastLogs",(i,a)=>t.exportSingleValue(this.getLastLogs(r.getString(i),r.getNumber(a)),void 0)),o("getProgressLog",(i,a)=>t.exportSingleValue(this.getProgressLog(r.getString(i),r.getString(a)),void 0)),o("getProgressLogWithInfo",(i,a)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(i),r.getString(a)),void 0)),o("getLogHandle",i=>t.exportSingleValue(this.getLogHandle(r.getString(i)),void 0)),o("getBlockLabel",i=>t.exportSingleValue(this.getBlockLabel(r.getString(i)),void 0)),o("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),o("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),o("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),o("calculateOptions",i=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(i)),void 0)),o("getSpecFromResultPoolByRef",(i,a)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(i),r.getString(a)),void 0)),o("getDataFromResultPoolByRef",(i,a)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(i),r.getString(a)),void 0)),o("createPFrame",i=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(i)),void 0)),o("createPTable",i=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(i)),void 0)),o("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),o("logInfo",i=>{this.logInfo(r.getString(i))}),o("logWarn",i=>{this.logWarn(r.getString(i))}),o("logError",i=>{this.logError(r.getString(i))})})}}function Fi(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,n,o){P(this,"callbackRegistry");P(this,"fnJSONStringify");P(this,"fnJSONParse");P(this,"errorRepo",new $i);P(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,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.");o!==void 0&&(this.computableHelper=new Ii(this,o.blockCtx,o.mlEnv,n,o.computableCtx)),this.injectCtx()}resetComputableCtx(){b.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ne.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),he.Scope.withScope(r=>{const n=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(n)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(n,this.vm.undefined,...t.map(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw Ne.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}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,n=!1;switch(typeof e){case"string":r=this.vm.newString(e),n=!0;break;case"number":r=this.vm.newNumber(e),n=!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(Fi(e)){r=this.vm.newArrayBuffer(e),n=!0;break}return}return n&&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(n=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,n)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){if(e!==void 0)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(){he.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(L.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class $i{constructor(){P(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=te.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 he.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.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}, ${g.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new jn.PlQuickJSError(e,n)}}function Di(s,e,t,r,n,o={}){const{code:i,featureFlags:a}=r,c=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:c},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{se().logOutputRecalculations&&console.log(`Block lambda recalculation : ${c} (${l.changeSourceMarker}; ${l.bodyInvocations} invocations)`);const u=new he.Scope;l.addOnDestroy(()=>u.dispose());const d=u.manage(s.quickJs.newRuntime());d.setMemoryLimit(1024*1024*8),d.setMaxStackSize(1024*320);let p;d.setInterruptHandler(()=>p===void 0?!1:Date.now()>p.deadline);const f=u.manage(d.newContext()),y=new Ne(u,f,O=>{p=O},a,{computableCtx:l,blockCtx:e,mlEnv:s});y.evaluateBundle(i.content);const h=y.runCallback(t.handle);y.resetComputableCtx();let R=0;return se().logOutputStatus==="any"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:y.computableHelper.computablesToResolve,postprocessValue:(O,{unstableMarker:V,stable:D})=>{for(const[M,T]of Object.entries(O))y.runCallback(M,T);const x=y.importObjectUniversal(h);return R++,se().logOutputStatus&&(se().logOutputStatus==="any"||!D)&&console.log(D?`Stable output ${t.handle} calculated ${x!==void 0?"defined":"undefined"}; (#${R})`:`Unstable output ${t.handle}; marker = ${V}; ${x!==void 0?"defined":"undefined"} (#${R})`),x}}},o)}function Li(s,e,t,...r){const{code:n,featureFlags:o}=t,i=new he.Scope;try{const a=i.manage(s.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let c;a.setInterruptHandler(()=>c===void 0?!1:Date.now()>c.deadline);const l=i.manage(a.newContext()),u=new Ne(i,l,d=>{c=d},o);return u.evaluateBundle(n.content),u.importObjectUniversal(u.runCallback(e.handle,...r))}finally{i.dispose()}}function Ai(s){return L.isConfigLambda(s)?s.isActive===!0:Yo(s)}function Te(s,e,t,r,n,o={}){if(L.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Di(s,e,t,r,n,o)}else return Ti(s.driverKit,e,t,o)}function je(s,e){return Oe(s.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=L.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}function Ni(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Lr.omitBy((r,n)=>n.startsWith("__"));return Lr.isDeepEqual(t(s),t(e))}function ji(s,e,t){return J.Computable.make(r=>{var y,h,R,O,V,D,x,M;const n=r.accessor(s).node(),o=b.notEmpty(n.getKeyValueAsJson(pr)),i=b.notEmpty(n.getKeyValueAsJson(Le)),a=b.notEmpty(n.getKeyValueAsJson(Ae)),c=b.notEmpty(n.getKeyValueAsJson(fe)),l=b.notEmpty(n.getKeyValueAsJson(ze)),u=new Map;for(const{id:T}of oe(c)){const B=n.traverse({field:W(T,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),E=B.getDataAsJson();let K;const de=n.traverse({field:W(T,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(de!==void 0){const Y=de.getDataAsJson(),G=n.getField({field:W(T,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=n.getField({field:W(T,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:Y,stale:!Ni(E,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((h=X.value)==null?void 0:h.getError())!==void 0,outputsError:((R=G.error)==null?void 0:R.getDataAsString())??((V=(O=G.value)==null?void 0:O.getError())==null?void 0:V.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((M=(x=X.value)==null?void 0:x.getError())==null?void 0:M.getDataAsString()),finished:(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())&&(X.value!==void 0&&X.value.getIsReadyOrError()||X.error!==void 0&&X.error.getIsReadyOrError())}}u.set(T,{currentArguments:E,prod:K,argsRid:B.resourceInfo.id})}const d=Ke(c,T=>{const B=je(n,T),E=u.get(T),K=E.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>B.cfg,()=>K,{argsRid:E.argsRid,blockPackRid:B.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...oe(c)].map(({id:T,label:B,renderingMode:E})=>{var N,F,U,z,q;const K=b.notEmpty(u.get(T)),de=b.notEmpty(d.nodes.get(T));let Y="NotCalculated";K.prod!==void 0&&(p.has(T)?Y="Limbo":Y=K.prod.finished?"Done":"Running");const G=je(n,T),{sections:X,title:m,inputsValid:v,sdkVersion:S,featureFlags:w,isIncompatibleWithRuntime:k}=Oe(G,({bpId:ae,cfg:ve})=>{if(!t.runtimeCapabilities.checkCompatibility(ve.featureFlags))return{isIncompatibleWithRuntime:!0,featureFlags:ve.featureFlags};const at=vr(s,T),pe=L.extractCodeWithInfo(ve);return{sections:Te(t,at,ve.sections,pe,ae).wrap({recover:Pe=>(t.logger.error("Error in block model sections"),t.logger.error(Pe),[])}),title:Oe(ve.title,Pe=>Te(t,at,Pe,pe,ae).wrap({recover:In=>(t.logger.error("Error in block model title"),t.logger.error(In),"Invalid title")})),inputsValid:Te(t,at,ve.inputsValid,pe,ae).wrap({recover:Pe=>(t.logger.error("Error in block model argsValid"),t.logger.error(Pe),!1)}),sdkVersion:pe==null?void 0:pe.sdkVersion,featureFlags:(pe==null?void 0:pe.featureFlags)??{},isIncompatibleWithRuntime:!1}})||{},C=n.traverse({field:W(T,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),I=Oe(G,({info:ae})=>t.blockUpdateWatcher.get({currentSpec:ae.source,settings:C}));return{projectResourceId:g.resourceIdToString(s.rid),id:T,label:m??B,title:m??B,renderingMode:E,stale:((N=K.prod)==null?void 0:N.stale)!==!1||Y==="Limbo",missingReference:de.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",T)],downstreams:[...d.traverseIdsExcludingRoots("downstream",T)],calculationStatus:Y,outputErrors:((F=K.prod)==null?void 0:F.outputError)===!0,outputsError:(U=K.prod)==null?void 0:U.outputsError,exportsError:(z=K.prod)==null?void 0:z.exportsError,settings:C,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(q=G==null?void 0:G.info)==null?void 0:q.source,updates:I,sdkVersion:S,featureFlags:w,isIncompatibleWithRuntime:k,navigationState:e.getState(T)}});return{meta:a,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(sr),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const a=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,l={...i,canRun:c,stale:a,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Bi(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,gr)){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(g.resourceTypesEqual(t.resourceType,hr)){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 xi(s,e){if(s!==void 0)return J.Computable.make(t=>Bi(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 Vi(s,e,t){return J.Computable.make(r=>{var a;const n=r.accessor(s).node(),o=je(n,e),i=(a=n.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:ln,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:xi(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function wn(s,e,t){if(t===void 0)return J.Computable.make(i=>wn(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=vr(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(rr(e)),args:b.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?b.deepFreeze(JSON.parse(o)):void 0}}function Ui(s,e,t){const r="outputs#"+g.resourceIdToString(s.rid)+"#"+e;return J.Computable.make(n=>{se().logOutputRecalculations&&console.log(`blockOutput recalculation : ${r} (${n.changeSourceMarker}; ${n.bodyInvocations} invocations)`);const o=n.accessor(s).node(),i=fn(s,e);return Oe(je(o,e),({cfg:a,bpId:c})=>{const l={};for(const[u,d]of Object.entries(a.outputs)){const p=Te(t,i,d,L.extractCodeWithInfo(a),c);l[u]=J.Computable.wrapError(p,1)}return l})},{key:r}).withStableType()}function Mi(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),n=b.notEmpty(r.getKeyValueAsJson(fe)),o=[];for(const{id:i}of oe(n)){const a=je(r,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,u])=>u).filter(u=>Ai(u)).map(u=>u);if(c.length===0)continue;const l=fn(r.persist(),i);for(const u of c)o.push(J.Computable.wrapError(Te(e,l,u,L.extractCodeWithInfo(a.cfg),a.bpId)))}return o})}class qi{constructor(){P(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 J.ChangeSource});return}r.state={...t},r.change.markChanged("navigation state changed")}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...L.DefaultNavigationState},change:new J.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return J.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("block deleted"))}}function Ji(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=b.notEmpty(t.getKeyValueAsJson(fe));return{listOfBlocks:[...oe(r)].map(n=>n.id)}})}const Gi="1",_i="BlockFrontendState/";async function Ki(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,We);if(r!==De){if(r===Gi)await Hi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,We,JSON.stringify(De)),await t.commit()}})}async function Hi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,fe),s.listKeyValues(e)]),n=new Map(r.map(o=>[o.key,o.value]));for(const o of oe(t)){const i=_i+o.id,a=n.get(i),c=a?b.cachedDeserialize(a):{},l=s.createJsonGzValue(c),u=g.field(e,W(o.id,"uiState"));s.createField(u,"Dynamic",l),s.deleteKValue(e,i)}}function Xr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.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 tt{constructor(e,t,r){P(this,"rid");P(this,"overview");P(this,"overviewLight");P(this,"navigationStates",new qi);P(this,"blockComputables",new Map);P(this,"blockFrontends",new Map);P(this,"activeConfigs");P(this,"refreshLoopResult");P(this,"abortController",new AbortController);P(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=ji(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=Ji(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Mi(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ge(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ks.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=te.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=L.extractConfig(a);return await ce(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.addBlock({id:o,label:e,renderingMode:c.renderingMode},{args:ne(c.initialArgs),uiState:ne(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=L.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ce(this.env.projectHelper,this.env.pl,this.rid,n,a=>a.migrateBlockPack(e,o,r?{args:i.initialArgs,uiState:i.initialUiState}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ce(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ce(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const n=r.structure;if(n.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(a=>{const c=o.blocks.find(l=>l.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 Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ce(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,args:t}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ce(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,uiState:t}])),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,n){await ce(this.env.projectHelper,this.env.pl,this.rid,n,o=>{o.setStates([{blockId:e,args:t,uiState:r}])}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ce(this.env.projectHelper,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 n=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,W(e,"blockPack")))).value),o=g.ensureResourceIdNotNull((await r.getField(g.field(n,g.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),a=L.extractConfig(b.cachedDeserialize(b.notEmpty(i.data)).config);await ce(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:a.initialArgs,uiState:a.initialUiState}])}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=Ui(this.projectTree.entry(),e,this.env),o={fullState:J.Computable.make(i=>({argsAndUiState:wn(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const a=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=a&&zi(a)&&i.outputs!==void 0?Yi(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Vi(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!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Ki(e.pl,t),await Ge(e.projectHelper,e.pl,t,n=>{});const r=await He.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Wi},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,a)=>{var c,l;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const o=He.treeDumpStats(n);await $e.writeFile(`${g.resourceIdToString(t)}.json`,Xr(n)),await $e.writeFile(`${g.resourceIdToString(t)}.stats.json`,Xr(o))}return new tt(e,t,r)}}function Wi(s){if(s.type.name.startsWith("StreamWorkdir/"))return[];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 zi(s){return!Xi(s,"1.26.0")}function Xi(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 Yi(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(n=>typeof n=="string"?n:n.type=="PlError"&&n.fullMessage!==void 0?n.fullMessage:n.message),moreErrors:r.moreErrors}}return e}const yr={logger:new b.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function wr(s){return{blobDownloadPath:_.join(s,"download"),blobDownloadRangesCachePath:_.join(s,"downloadRangesCache"),downloadBlobToURLPath:_.join(s,"downloadToURL"),pframesSpillPath:_.join(s,"pframes")}}const bn={...yr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Sn(s){return{...wr(s),frontendDownloadPath:_.join(s,"frontend")}}function Qi(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var _e={exports:{}},dt,Yr;function rt(){if(Yr)return dt;Yr=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return dt={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:s,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},dt}var pt,Qr;function st(){return Qr||(Qr=1,pt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),pt}var Zr;function xe(){return Zr||(Zr=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=rt(),o=st();e=s.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],y=R=>{for(const[O,V]of f)R=R.split(`${O}*`).join(`${O}{0,${V}}`).split(`${O}+`).join(`${O}{1,${V}}`);return R},h=(R,O,V)=>{const D=y(O),x=d++;o(R,x,O),u[R]=x,c[x]=O,l[x]=D,i[x]=new RegExp(O,V?"g":void 0),a[x]=new RegExp(D,V?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(_e,_e.exports)),_e.exports}var ft,es;function br(){if(es)return ft;es=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return ft=r=>r?typeof r!="object"?s:r:e,ft}var gt,ts;function Rn(){if(ts)return gt;ts=1;const s=/^[0-9]+$/,e=(r,n)=>{const o=s.test(r),i=s.test(n);return o&&i&&(r=+r,n=+n),r===n?0:o&&!i?-1:i&&!o?1:r<n?-1:1};return gt={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},gt}var ht,rs;function ee(){if(rs)return ht;rs=1;const s=st(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=rt(),{safeRe:r,t:n}=xe(),o=br(),{compareIdentifiers:i}=Rn();class a{constructor(l,u){if(u=o(u),l instanceof a){if(l.loose===!!u.loose&&l.includePrerelease===!!u.includePrerelease)return l;l=l.version}else if(typeof l!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof l}".`);if(l.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",l,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=l.trim().match(u.loose?r[n.LOOSE]:r[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${l}`);if(this.raw=l,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(p=>{if(/^[0-9]+$/.test(p)){const f=+p;if(f>=0&&f<t)return f}return p}):this.prerelease=[],this.build=d[5]?d[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(l){if(s("SemVer.compare",this.version,this.options,l),!(l instanceof a)){if(typeof l=="string"&&l===this.version)return 0;l=new a(l,this.options)}return l.version===this.version?0:this.compareMain(l)||this.comparePre(l)}compareMain(l){return l instanceof a||(l=new a(l,this.options)),i(this.major,l.major)||i(this.minor,l.minor)||i(this.patch,l.patch)}comparePre(l){if(l instanceof a||(l=new a(l,this.options)),this.prerelease.length&&!l.prerelease.length)return-1;if(!this.prerelease.length&&l.prerelease.length)return 1;if(!this.prerelease.length&&!l.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=l.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}compareBuild(l){l instanceof a||(l=new a(l,this.options));let u=0;do{const d=this.build[u],p=l.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}inc(l,u,d){if(l.startsWith("pre")){if(!u&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(u){const p=`-${u}`.match(this.options.loose?r[n.PRERELEASELOOSE]:r[n.PRERELEASE]);if(!p||p[1]!==u)throw new Error(`invalid identifier: ${u}`)}}switch(l){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);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 p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),i(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${l}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return ht=a,ht}var mt,ss;function Se(){if(ss)return mt;ss=1;const s=ee();return mt=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(o){if(!n)return null;throw o}},mt}var vt,ns;function Zi(){if(ns)return vt;ns=1;const s=Se();return vt=(t,r)=>{const n=s(t,r);return n?n.version:null},vt}var yt,os;function ea(){if(os)return yt;os=1;const s=Se();return yt=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},yt}var wt,is;function ta(){if(is)return wt;is=1;const s=ee();return wt=(t,r,n,o,i)=>{typeof n=="string"&&(i=o,o=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,o,i).version}catch{return null}},wt}var bt,as;function ra(){if(as)return bt;as=1;const s=Se();return bt=(t,r)=>{const n=s(t,null,!0),o=s(r,null,!0),i=n.compare(o);if(i===0)return null;const a=i>0,c=a?n:o,l=a?o:n,u=!!c.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(c)===0)return l.minor&&!l.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==o.major?p+"major":n.minor!==o.minor?p+"minor":n.patch!==o.patch?p+"patch":"prerelease"},bt}var St,cs;function sa(){if(cs)return St;cs=1;const s=ee();return St=(t,r)=>new s(t,r).major,St}var Rt,ls;function na(){if(ls)return Rt;ls=1;const s=ee();return Rt=(t,r)=>new s(t,r).minor,Rt}var Ct,us;function oa(){if(us)return Ct;us=1;const s=ee();return Ct=(t,r)=>new s(t,r).patch,Ct}var kt,ds;function ia(){if(ds)return kt;ds=1;const s=Se();return kt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},kt}var Pt,ps;function le(){if(ps)return Pt;ps=1;const s=ee();return Pt=(t,r,n)=>new s(t,n).compare(new s(r,n)),Pt}var Et,fs;function aa(){if(fs)return Et;fs=1;const s=le();return Et=(t,r,n)=>s(r,t,n),Et}var Ot,gs;function ca(){if(gs)return Ot;gs=1;const s=le();return Ot=(t,r)=>s(t,r,!0),Ot}var Tt,hs;function Sr(){if(hs)return Tt;hs=1;const s=ee();return Tt=(t,r,n)=>{const o=new s(t,n),i=new s(r,n);return o.compare(i)||o.compareBuild(i)},Tt}var It,ms;function la(){if(ms)return It;ms=1;const s=Sr();return It=(t,r)=>t.sort((n,o)=>s(n,o,r)),It}var Ft,vs;function ua(){if(vs)return Ft;vs=1;const s=Sr();return Ft=(t,r)=>t.sort((n,o)=>s(o,n,r)),Ft}var $t,ys;function nt(){if(ys)return $t;ys=1;const s=le();return $t=(t,r,n)=>s(t,r,n)>0,$t}var Dt,ws;function Rr(){if(ws)return Dt;ws=1;const s=le();return Dt=(t,r,n)=>s(t,r,n)<0,Dt}var Lt,bs;function Cn(){if(bs)return Lt;bs=1;const s=le();return Lt=(t,r,n)=>s(t,r,n)===0,Lt}var At,Ss;function kn(){if(Ss)return At;Ss=1;const s=le();return At=(t,r,n)=>s(t,r,n)!==0,At}var Nt,Rs;function Cr(){if(Rs)return Nt;Rs=1;const s=le();return Nt=(t,r,n)=>s(t,r,n)>=0,Nt}var jt,Cs;function kr(){if(Cs)return jt;Cs=1;const s=le();return jt=(t,r,n)=>s(t,r,n)<=0,jt}var Bt,ks;function Pn(){if(ks)return Bt;ks=1;const s=Cn(),e=kn(),t=nt(),r=Cr(),n=Rr(),o=kr();return Bt=(a,c,l,u)=>{switch(c){case"===":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a===l;case"!==":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a!==l;case"":case"=":case"==":return s(a,l,u);case"!=":return e(a,l,u);case">":return t(a,l,u);case">=":return r(a,l,u);case"<":return n(a,l,u);case"<=":return o(a,l,u);default:throw new TypeError(`Invalid operator: ${c}`)}},Bt}var xt,Ps;function da(){if(Ps)return xt;Ps=1;const s=ee(),e=Se(),{safeRe:t,t:r}=xe();return xt=(o,i)=>{if(o instanceof s)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let a=null;if(!i.rtl)a=o.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(o))&&(!a||a.index+a[0].length!==o.length);)(!a||y.index+y[0].length!==a.index+a[0].length)&&(a=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(a===null)return null;const c=a[2],l=a[3]||"0",u=a[4]||"0",d=i.includePrerelease&&a[5]?`-${a[5]}`:"",p=i.includePrerelease&&a[6]?`+${a[6]}`:"";return e(`${c}.${l}.${u}${d}${p}`,i)},xt}var Vt,Es;function pa(){if(Es)return Vt;Es=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}}return Vt=s,Vt}var Ut,Os;function ue(){if(Os)return Ut;Os=1;const s=/\s+/g;class e{constructor(v,S){if(S=n(S),v instanceof e)return v.loose===!!S.loose&&v.includePrerelease===!!S.includePrerelease?v:new e(v.raw,S);if(v instanceof o)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=v.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(k=>!h(k[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const k of this.set)if(k.length===1&&R(k[0])){this.set=[k];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let v=0;v<this.set.length;v++){v>0&&(this.formatted+="||");const S=this.set[v];for(let w=0;w<S.length;w++)w>0&&(this.formatted+=" "),this.formatted+=S[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const w=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,k=r.get(w);if(k)return k;const C=this.options.loose,I=C?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];v=v.replace(I,G(this.options.includePrerelease)),i("hyphen replace",v),v=v.replace(c[l.COMPARATORTRIM],u),i("comparator trim",v),v=v.replace(c[l.TILDETRIM],d),i("tilde trim",v),v=v.replace(c[l.CARETTRIM],p),i("caret trim",v);let N=v.split(" ").map(q=>V(q,this.options)).join(" ").split(/\s+/).map(q=>Y(q,this.options));C&&(N=N.filter(q=>(i("loose invalid filter",q,this.options),!!q.match(c[l.COMPARATORLOOSE])))),i("range list",N);const F=new Map,U=N.map(q=>new o(q,this.options));for(const q of U){if(h(q))return[q];F.set(q.value,q)}F.size>1&&F.has("")&&F.delete("");const z=[...F.values()];return r.set(w,z),z}intersects(v,S){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>O(w,S)&&v.set.some(k=>O(k,S)&&w.every(C=>k.every(I=>C.intersects(I,S)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new a(v,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(X(this.set[S],v,this.options))return!0;return!1}}Ut=e;const t=pa(),r=new t,n=br(),o=ot(),i=st(),a=ee(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=xe(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=rt(),h=m=>m.value==="<0.0.0-0",R=m=>m.value==="",O=(m,v)=>{let S=!0;const w=m.slice();let k=w.pop();for(;S&&w.length;)S=w.every(C=>k.intersects(C,v)),k=w.pop();return S},V=(m,v)=>(i("comp",m,v),m=T(m,v),i("caret",m),m=x(m,v),i("tildes",m),m=E(m,v),i("xrange",m),m=de(m,v),i("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",x=(m,v)=>m.trim().split(/\s+/).map(S=>M(S,v)).join(" "),M=(m,v)=>{const S=v.loose?c[l.TILDELOOSE]:c[l.TILDE];return m.replace(S,(w,k,C,I,N)=>{i("tilde",m,w,k,C,I,N);let F;return D(k)?F="":D(C)?F=`>=${k}.0.0 <${+k+1}.0.0-0`:D(I)?F=`>=${k}.${C}.0 <${k}.${+C+1}.0-0`:N?(i("replaceTilde pr",N),F=`>=${k}.${C}.${I}-${N} <${k}.${+C+1}.0-0`):F=`>=${k}.${C}.${I} <${k}.${+C+1}.0-0`,i("tilde return",F),F})},T=(m,v)=>m.trim().split(/\s+/).map(S=>B(S,v)).join(" "),B=(m,v)=>{i("caret",m,v);const S=v.loose?c[l.CARETLOOSE]:c[l.CARET],w=v.includePrerelease?"-0":"";return m.replace(S,(k,C,I,N,F)=>{i("caret",m,k,C,I,N,F);let U;return D(C)?U="":D(I)?U=`>=${C}.0.0${w} <${+C+1}.0.0-0`:D(N)?C==="0"?U=`>=${C}.${I}.0${w} <${C}.${+I+1}.0-0`:U=`>=${C}.${I}.0${w} <${+C+1}.0.0-0`:F?(i("replaceCaret pr",F),C==="0"?I==="0"?U=`>=${C}.${I}.${N}-${F} <${C}.${I}.${+N+1}-0`:U=`>=${C}.${I}.${N}-${F} <${C}.${+I+1}.0-0`:U=`>=${C}.${I}.${N}-${F} <${+C+1}.0.0-0`):(i("no pr"),C==="0"?I==="0"?U=`>=${C}.${I}.${N}${w} <${C}.${I}.${+N+1}-0`:U=`>=${C}.${I}.${N}${w} <${C}.${+I+1}.0-0`:U=`>=${C}.${I}.${N} <${+C+1}.0.0-0`),i("caret return",U),U})},E=(m,v)=>(i("replaceXRanges",m,v),m.split(/\s+/).map(S=>K(S,v)).join(" ")),K=(m,v)=>{m=m.trim();const S=v.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return m.replace(S,(w,k,C,I,N,F)=>{i("xRange",m,w,k,C,I,N,F);const U=D(C),z=U||D(I),q=z||D(N),ae=q;return k==="="&&ae&&(k=""),F=v.includePrerelease?"-0":"",U?k===">"||k==="<"?w="<0.0.0-0":w="*":k&&ae?(z&&(I=0),N=0,k===">"?(k=">=",z?(C=+C+1,I=0,N=0):(I=+I+1,N=0)):k==="<="&&(k="<",z?C=+C+1:I=+I+1),k==="<"&&(F="-0"),w=`${k+C}.${I}.${N}${F}`):z?w=`>=${C}.0.0${F} <${+C+1}.0.0-0`:q&&(w=`>=${C}.${I}.0${F} <${C}.${+I+1}.0-0`),i("xRange return",w),w})},de=(m,v)=>(i("replaceStars",m,v),m.trim().replace(c[l.STAR],"")),Y=(m,v)=>(i("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?l.GTE0PRE:l.GTE0],"")),G=m=>(v,S,w,k,C,I,N,F,U,z,q,ae)=>(D(w)?S="":D(k)?S=`>=${w}.0.0${m?"-0":""}`:D(C)?S=`>=${w}.${k}.0${m?"-0":""}`:I?S=`>=${S}`:S=`>=${S}${m?"-0":""}`,D(U)?F="":D(z)?F=`<${+U+1}.0.0-0`:D(q)?F=`<${U}.${+z+1}.0-0`:ae?F=`<=${U}.${z}.${q}-${ae}`:m?F=`<${U}.${z}.${+q+1}-0`:F=`<=${F}`,`${S} ${F}`.trim()),X=(m,v,S)=>{for(let w=0;w<m.length;w++)if(!m[w].test(v))return!1;if(v.prerelease.length&&!S.includePrerelease){for(let w=0;w<m.length;w++)if(i(m[w].semver),m[w].semver!==o.ANY&&m[w].semver.prerelease.length>0){const k=m[w].semver;if(k.major===v.major&&k.minor===v.minor&&k.patch===v.patch)return!0}return!1}return!0};return Ut}var Mt,Ts;function ot(){if(Ts)return Mt;Ts=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new a(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new a(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}Mt=e;const t=br(),{safeRe:r,t:n}=xe(),o=Pn(),i=st(),a=ee(),c=ue();return Mt}var qt,Is;function it(){if(Is)return qt;Is=1;const s=ue();return qt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},qt}var Jt,Fs;function fa(){if(Fs)return Jt;Fs=1;const s=ue();return Jt=(t,r)=>new s(t,r).set.map(n=>n.map(o=>o.value).join(" ").trim().split(" ")),Jt}var Gt,$s;function ga(){if($s)return Gt;$s=1;const s=ee(),e=ue();return Gt=(r,n,o)=>{let i=null,a=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(l=>{c.test(l)&&(!i||a.compare(l)===-1)&&(i=l,a=new s(i,o))}),i},Gt}var _t,Ds;function ha(){if(Ds)return _t;Ds=1;const s=ee(),e=ue();return _t=(r,n,o)=>{let i=null,a=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(l=>{c.test(l)&&(!i||a.compare(l)===1)&&(i=l,a=new s(i,o))}),i},_t}var Kt,Ls;function ma(){if(Ls)return Kt;Ls=1;const s=ee(),e=ue(),t=nt();return Kt=(n,o)=>{n=new e(n,o);let i=new s("0.0.0");if(n.test(i)||(i=new s("0.0.0-0"),n.test(i)))return i;i=null;for(let a=0;a<n.set.length;++a){const c=n.set[a];let l=null;c.forEach(u=>{const d=new s(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!i||t(i,l))&&(i=l)}return i&&n.test(i)?i:null},Kt}var Ht,As;function va(){if(As)return Ht;As=1;const s=ue();return Ht=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Ht}var Wt,Ns;function Pr(){if(Ns)return Wt;Ns=1;const s=ee(),e=ot(),{ANY:t}=e,r=ue(),n=it(),o=nt(),i=Rr(),a=kr(),c=Cr();return Wt=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,h,R,O,V;switch(p){case">":y=o,h=a,R=i,O=">",V=">=";break;case"<":y=i,h=c,R=o,O="<",V="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const x=d.set[D];let M=null,T=null;if(x.forEach(B=>{B.semver===t&&(B=new e(">=0.0.0")),M=M||B,T=T||B,y(B.semver,M.semver,f)?M=B:R(B.semver,T.semver,f)&&(T=B)}),M.operator===O||M.operator===V||(!T.operator||T.operator===O)&&h(u,T.semver))return!1;if(T.operator===V&&R(u,T.semver))return!1}return!0},Wt}var zt,js;function ya(){if(js)return zt;js=1;const s=Pr();return zt=(t,r,n)=>s(t,r,">",n),zt}var Xt,Bs;function wa(){if(Bs)return Xt;Bs=1;const s=Pr();return Xt=(t,r,n)=>s(t,r,"<",n),Xt}var Yt,xs;function ba(){if(xs)return Yt;xs=1;const s=ue();return Yt=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),Yt}var Qt,Vs;function Sa(){if(Vs)return Qt;Vs=1;const s=it(),e=le();return Qt=(t,r,n)=>{const o=[];let i=null,a=null;const c=t.sort((p,f)=>e(p,f,n));for(const p of c)s(p,r,n)?(a=p,i||(i=p)):(a&&o.push([i,a]),a=null,i=null);i&&o.push([i,null]);const l=[];for(const[p,f]of o)p===f?l.push(p):!f&&p===c[0]?l.push("*"):f?p===c[0]?l.push(`<=${f}`):l.push(`${p} - ${f}`):l.push(`>=${p}`);const u=l.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},Qt}var Zt,Us;function Ra(){if(Us)return Zt;Us=1;const s=ue(),e=ot(),{ANY:t}=e,r=it(),n=le(),o=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const h of d.set){for(const R of p.set){const O=c(h,R,f);if(y=y||O!==null,O)continue e}if(y)return!1}return!0},i=[new e(">=0.0.0-0")],a=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=i:d=a}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=a}const y=new Set;let h,R;for(const E of d)E.operator===">"||E.operator===">="?h=l(h,E,f):E.operator==="<"||E.operator==="<="?R=u(R,E,f):y.add(E.semver);if(y.size>1)return null;let O;if(h&&R){if(O=n(h.semver,R.semver,f),O>0)return null;if(O===0&&(h.operator!==">="||R.operator!=="<="))return null}for(const E of y){if(h&&!r(E,String(h),f)||R&&!r(E,String(R),f))return null;for(const K of p)if(!r(E,String(K),f))return!1;return!0}let V,D,x,M,T=R&&!f.includePrerelease&&R.semver.prerelease.length?R.semver:!1,B=h&&!f.includePrerelease&&h.semver.prerelease.length?h.semver:!1;T&&T.prerelease.length===1&&R.operator==="<"&&T.prerelease[0]===0&&(T=!1);for(const E of p){if(M=M||E.operator===">"||E.operator===">=",x=x||E.operator==="<"||E.operator==="<=",h){if(B&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===B.major&&E.semver.minor===B.minor&&E.semver.patch===B.patch&&(B=!1),E.operator===">"||E.operator===">="){if(V=l(h,E,f),V===E&&V!==h)return!1}else if(h.operator===">="&&!r(h.semver,String(E),f))return!1}if(R){if(T&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===T.major&&E.semver.minor===T.minor&&E.semver.patch===T.patch&&(T=!1),E.operator==="<"||E.operator==="<="){if(D=u(R,E,f),D===E&&D!==R)return!1}else if(R.operator==="<="&&!r(R.semver,String(E),f))return!1}if(!E.operator&&(R||h)&&O!==0)return!1}return!(h&&x&&!R&&O!==0||R&&M&&!h&&O!==0||B||T)},l=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y>0?d:y<0||p.operator===">"&&d.operator===">="?p:d},u=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y<0?d:y>0||p.operator==="<"&&d.operator==="<="?p:d};return Zt=o,Zt}var er,Ms;function Ca(){if(Ms)return er;Ms=1;const s=xe(),e=rt(),t=ee(),r=Rn(),n=Se(),o=Zi(),i=ea(),a=ta(),c=ra(),l=sa(),u=na(),d=oa(),p=ia(),f=le(),y=aa(),h=ca(),R=Sr(),O=la(),V=ua(),D=nt(),x=Rr(),M=Cn(),T=kn(),B=Cr(),E=kr(),K=Pn(),de=da(),Y=ot(),G=ue(),X=it(),m=fa(),v=ga(),S=ha(),w=ma(),k=va(),C=Pr(),I=ya(),N=wa(),F=ba(),U=Sa(),z=Ra();return er={parse:n,valid:o,clean:i,inc:a,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:h,compareBuild:R,sort:O,rsort:V,gt:D,lt:x,eq:M,neq:T,gte:B,lte:E,cmp:K,coerce:de,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:S,minVersion:w,validRange:k,outside:C,gtr:I,ltr:N,intersects:F,simplifyRange:U,subset:z,SemVer:t,re:s.re,src:s.src,tokens:s.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},er}var ka=Ca();const Pa=Qi(ka),Ea={minDelay:1500},Oa="__no_updates__";class Ta extends J.PollComputablePool{constructor(t,r,n={}){super({...n,...Ea},r);P(this,"http");P(this,"preferredUpdateChannel");this.registryProvider=t,this.http=n.http,this.preferredUpdateChannel=n.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_${ne(t)}`;default:return Oa}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await dr(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await Z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await Qe(i);return a===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,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(o.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(o.channel===void 0)if(await c.getLatestOverview(o.id,Q.StableChannel))l=Q.StableChannel;else{if(await c.getLatestOverview(o.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(o.id)}`),{suggestions:[]};l=Q.AnyChannel}else l=o.channel;const u=await c.getUpdateSuggestions(o.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(y=>y.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:y,update:h})=>({type:y,update:{...o,id:{...o.id,version:h}}}));if(d===void 0)return{suggestions:p};if(a!==void 0&&Pa.lte(d,a))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return ne(t)===ne(r)}}class qs{constructor(){P(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),(n=>n!=null&&typeof n[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 n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!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}}function Ie(s){return String(s.id)}const Ia=["Int","Long","Float","Double","String","Bytes"];function tr(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}function Fa(s){return"partitionFilters"in s?s:{...s,partitionFilters:s.filters,filters:[]}}const Ee=(s,e)=>typeof e=="bigint"?e.toString():e;class $a{constructor(e,t,r,n){P(this,"pFrame");P(this,"abortController",new AbortController);P(this,"blobIdToResource",new Map);P(this,"blobHandleComputables",new Map);P(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue(this.disposeSignal)});P(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await zs.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const o=(a,c)=>this.logger[a](c);for(const a of n)for(const c of Bo(a.data))this.blobIdToResource.set(Ie(c),c);const i=[...new Map(n.map(a=>({...a,data:xo(a.data,Ie)})).map(a=>[ne(a),a])).values()];try{const a=new Hs.PFrame(this.spillPath,o);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.pFrame=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}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Da{constructor(e,t){this.pTable=e,this.abortController=t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort(),this.pTable.dispose()}}class Er{constructor(e,t,r){P(this,"pFrames");P(this,"pTables");P(this,"frameConcurrencyLimiter");P(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new b.ConcurrencyLimitingExecutor(1);this.frameConcurrencyLimiter=n,this.tableConcurrencyLimiter=new b.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends qs{constructor(o,i,a){super(),this.blobDriver=o,this.logger=i,this.spillPath=a}createNewResource(o){return se().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ee)}`),new $a(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){return Aa(o)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends qs{constructor(o){super(),this.pFrames=o}createNewResource(o){const i=o.pFrameHandle;se().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ee)}`);const a=this.pFrames.getByKey(i),c=new AbortController,l=a.pFrame.createTable({src:Fe(o.def.src),filters:tr([...o.def.partitionFilters,...o.def.filters])});let u=l;if(o.def.sorting.length>0)try{u=l.sort(o.def.sorting)}finally{l.dispose()}return new Da(u,c)}calculateParamsKey(o){return La(o)}}(this.pFrames)}async pprofDump(){return await Hs.PFrame.pprofDump()}static async init(e,t,r){const n=Un.resolve(r);return await b.emptyDir(n),new Er(e,t,n)}createPFrame(e,t){const r=e.filter(o=>Ia.find(i=>i===o.spec.valueType)).map(o=>L.mapPObjectData(o,i=>He.isPlTreeNodeAccessor(i)?Go(i):L.isDataInfo(i)?L.mapDataInfo(i,a=>a.resourceInfo):_o(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t){const r=Fa(e),n=this.createPFrame(L.extractAllColumns(r.src),t),o=L.mapPTableDef(r,a=>a.id),i=this.pTables.acquire({def:o,pFrameHandle:n});return se().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(L.mapPTableDef(r,a=>a.spec),Ee)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(o=>[ne(o),o])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(o=>o.mappingVariants.length===0||o.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(o=>o.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r,n){return se().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ee)}`),await this.frameConcurrencyLimiter.run(async()=>{const o=this.pFrames.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(l=>!!l)),a=o.pFrame.createTable({src:Fe(t.src),filters:tr(t.filters)});let c=a;if(t.sorting.length>0)try{c=a.sort(t.sorting)}finally{a.dispose()}try{const l=c.getSpec(),u=await c.getData([...l.keys()],{range:r,signal:i});return l.map((d,p)=>({spec:d,data:u[p]}))}finally{c.dispose()}})}async getUniqueValues(e,t,r){return se().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ee)}`),await this.frameConcurrencyLimiter.run(async()=>{const n=this.pFrames.getByKey(e),o=AbortSignal.any([r,n.disposeSignal].filter(i=>!!i));return await n.pFrame.getUniqueValues({...t,filters:tr(t.filters)},{signal:o})})}getSpec(e){const t=this.pTables.getByKey(e).pTable;return Promise.resolve(t.getSpec())}async getShape(e,t){return await this.tableConcurrencyLimiter.run(async()=>{const r=this.pTables.getByKey(e),n=AbortSignal.any([t,r.disposeSignal].filter(o=>!!o));return await r.pTable.getShape({signal:n})})}async getData(e,t,r,n){return await this.tableConcurrencyLimiter.run(async()=>{const o=this.pTables.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(a=>!!a));return await o.pTable.getData(t,{range:r,signal:i})})}}function Fe(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"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Fe(e))};case"outer":return{type:"outer",primary:Fe(s.primary),secondary:s.secondary.map(e=>Fe(e))};default:b.assertNever(s)}}function La(s){const e=te.createHash("sha256");return e.update(ne(s)),e.digest().toString("hex")}function Aa(s){const e=[...s].map(r=>L.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:Ie(c)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:[Ie(c.index),Ie(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((a,c)=>a.key.localeCompare(c.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(ne(e)),t.digest().toString("hex")}async function En(s,e,t){const r={...yr,...wr(e),...t},n=new b.HmacSha256Signer(r.localSecret),o=H.createDownloadClient(r.logger,s,r.localProjections),i=H.createLogsClient(s,r.logger),a=H.createUploadBlobClient(s,r.logger),c=H.createUploadProgressClient(s,r.logger),l=await H.DownloadDriver.init(r.logger,o,i,r.blobDownloadPath,r.blobDownloadRangesCachePath,n,r.blobDriverOps),u=new H.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new H.UploadDriver(r.logger,n,a,c,r.uploadDriverOps),p=new H.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new H.LogsDriver(r.logger,p,l),y=await H.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),h=await Er.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:y,signer:n,uploadDriver:d,pFrameDriver:h}}class Na{constructor(e){P(this,"enrichmentTargetsCache",new Gs.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return Li(this.quickJs,t.enrichmentTargets,L.extractCodeWithInfo(t),r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Or{constructor(e,t,r,n,o,i,a,c){P(this,"pl");P(this,"projectList");P(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}addRuntimeCapability(e,t=!0){this.env.runtimeCapabilities.addSupportedRequirement(e,t)}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await jo(n,e);return n.createField(g.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await g.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ce(this.env.projectHelper,this.pl,e,r,n=>{n.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(g.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(g.field(this.projectListResourceId,e))).value;if(g.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 tt.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 b.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...bn,...Sn(t),...r};n.defaultTreeOptions.logStat=se().logTreeStats,n.debugOps.dumpInitialTreeState=se().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async O=>{const V=g.field(O.clientRoot,io);O.createField(V,"Dynamic");const D=await O.getField(V);if(g.isNullResourceId(D.value)){const x=O.createEphemeral(Qs);return O.lock(x),O.setField(V,x),await O.commit(),await x.globalId}else return D.value}),i=n.logger,a=await En(e,t,n),c=new Ye.RetryAgent(e.httpDispatcher),l=new Ys(c),u=new Io(l,a.signer,c),d=new H.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await he.getQuickJS(),f=new L.RuntimeCapabilities;f.addSupportedRequirement("requiresModelAPIVersion",1);const y={pl:e,blockEventDispatcher:new b.BlockEventDispatcher,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new Ta(l,i,{minDelay:n.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:n.preferredUpdateChannel}),runtimeCapabilities:f,quickJs:p,projectHelper:new Na(p)},h=new J.WatchableValue([]),R=await co(e,o,h,y);return new Or(y,a,a.signer,o,h,R.tree,l,R.computable)}}async function ja(s,e){return await Re(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Ba(s,e){return await Re(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function xa(s,e){return await Re(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function Va(s,e){return await Re(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function Ua(s,e){return await Re(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Ma(s,e){return await Re(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Ve(s.autoUpdateCdnUrl,s,e))}async function Re(s,e,t){const r=Date.now(),n=[];for(;Js(r)<s;){const o=Date.now();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const a=Js(o);n.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Ks.setTimeout(c)}return n}async function Ve(s,e,t){const{body:r,statusCode:n}=await Ye.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Js(s){return Date.now()-s}function we(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:n}=qa(s),o=`
1
+ "use strict";var Dn=Object.defineProperty;var Fr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),$r=s=>{throw TypeError(s)};var Ln=(s,e,t)=>e in s?Dn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var R=(s,e,t)=>Ln(s,typeof e!="symbol"?e+"":e,t);var Dr=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&$r("Object expected");var r,n;t&&(r=e[Fr("asyncDispose")]),r===void 0&&(r=e[Fr("dispose")],t&&(n=r)),typeof r!="function"&&$r("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(o){return Promise.reject(o)}}),s.push([t,r,e])}else t&&s.push([t]);return e},Lr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,l){return l=Error(c),l.name="SuppressedError",l.error=i,l.suppressed=a,l},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(o,c=>(n(c),o()))}catch(c){n(c)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Ar=require("@milaboratories/pl-deployments"),Qe=require("undici"),Z=require("@platforma-sdk/block-tools"),ie=require("node:fs"),_=require("node:path"),An=require("yaml"),b=require("@milaboratories/ts-helpers"),$e=require("node:fs/promises"),Nn=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),We=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),$=require("@milaboratories/pl-model-backend"),lr=require("lru-cache"),jn=require("node:worker_threads"),Hs=require("denque"),me=require("@platforma-sdk/workflow-tengo"),ne=require("canonicalize"),Bn=require("node:assert"),he=require("quickjs-emscripten"),xn=require("@milaboratories/pl-errors"),Vn=require("remeda"),Ws=require("node:timers/promises"),H=require("@milaboratories/pl-drivers"),zs=require("@milaboratories/pframes-rs-node"),Un=require("node:diagnostics_channel"),Mn=require("node:stream/consumers"),Xs=require("node:os");function ur(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 qn=ur(_),Ys=ur($e),Nr=ur(Vn);async function jr(s){try{return await Ys.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Jn=[Z.RegistryV1.PlPackageYamlConfigFile],Gn=[Z.RegistryV1.PlPackageJsonConfigFile],dr=["backend","dist","tengo","tpl","main.plj.gz"],pr=["config","dist","config.json"],Qs=["frontend","dist"],Br="block-model/dist/config.json",_n="block-ui/package.json",Kn=[dr,pr,Jn,Gn,Qs];async function Hn(s){return await jr(_.join(s,...pr))!==void 0||await jr(_.join(s,...dr))!==void 0}function lt(s,e){const t=Nn.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function xr(s,e){if(_.isAbsolute(s)||(s=_.resolve(s)),await Hn(s))return{workflow:_.join(s,...dr),config:_.join(s,...pr),ui:_.join(s,...Qs)};{const t=lt(s,Br),r=lt(s,Br),n=lt(s,_n);return{workflow:t,config:r,ui:_.resolve(n,"..","dist")}}}async function Wn(s){try{return await ie.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function zn(s){try{return await ie.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function fr(s){let e=0n;for(const t of Kn){const r=_.join(s,...t),n=await zn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function Ze(s){const e=await ie.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await ie.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Xn{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 n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await Qe.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const a of i){const{organization:c,package:l,latestMeta:u,latestVersion:d}=a,p={organization:c,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[Q.AnyChannel]:f,[Q.StableChannel]:f},allVersions:a.allVersions.map(y=>({version:y,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(n=>({...n,registryId:e.id}));case"local-dev":for(const n of await ie.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=_.join(r.path,n.name),i=await Wn(_.join(o,Z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=Z.RegistryV1.PlPackageConfigData.parse(An.parse(i)),c=await fr(o),l={organization:a.organization,name:a.package,version:"DEV"},u={id:l,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:o,mtime:c}};t.push({registryId:e.id,id:l,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let a=o,c=await Z.tryLoadPackDescription(a);if(c===void 0){for(const l of["block","meta"])if(a=_.join(o,l),c=await Z.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const l=await Ze(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),featureFlags:c.featureFlags,spec:{type:"dev-v2",folder:a,mtime:l}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return b.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 n=(i=this.registries.find(a=>a.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Zs{constructor(e){R(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new Z.RegistryV2Reader(Z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Yn={type:"remote-v2",url:"https://blocks.pl-open.science/"},Qn={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Zn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},eo={groups:[{id:"default",label:"Default",blocks:[]}]},to={stagingRefreshTimestamp:0,blocksInLimbo:[]},ro={label:"New Project"},so={name:"UserProject",version:"2"},ze="SchemaVersion",De="2",gr="ProjectCreated",Le="ProjectLastModified",Ae="ProjectMeta",fe="ProjectStructure",Xe="BlockRenderingState",no="BlockArgsAuthor/";function sr(s){return`${no}${s}`}const nr="ProjectStructureAuthor",oo="__serviceTemplate_";function or(s){return`${oo}${s}`}function W(s,e){return`${s}-${e}`}const io=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ao(s){const e=s.match(io);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const co="projects",en={name:"Projects",version:"1"},lo=s=>g.resourceTypesEqual(s.type,en)?s.fields:[];async function uo(s,e,t,r){const n=await We.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:lo},r.logger);return{computable:J.Computable.make(i=>{const a=i.accessor(n.entry()).node(),c=t.getValue(i);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const d=a.traverse(u);if(d===void 0)continue;const p=b.notEmpty(d.getKeyValueAsJson(Ae)),f=b.notEmpty(d.getKeyValueAsJson(gr)),y=b.notEmpty(d.getKeyValueAsJson(Le));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:n}}const po={name:"EphRenderTemplate",version:"1"},fo={name:"RenderTemplate",version:"1"};function et(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(po):s.createStruct(fo),i=g.field(o,"template"),a=g.field(o,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(o),g.Pl.futureRecord(s,o,n,"Output","outputs/")}const go={name:"BContextEnd",version:"1"},ho={name:"BContext",version:"1"},mo="id",vo="parent/",yo=["context","result"];function Vr(s,e,t){return et(s,e,!0,t,yo)}function wo(s){const e=s.createEphemeral(go);return s.lock(e),e}function Ur(s,e){if(e.length===0)return wo(s);if(e.length===1)return e[0];const t=s.createEphemeral(ho);s.createField(g.field(t,mo),"Input",g.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${vo}${r}`),"Input",e[r]);return s.lock(t),t}function tn(s,e){const t=new Map,r=(n,o,i)=>{const a=te.createHash("sha256");o.updateCacheKey(n,a,i);const c=a.digest("hex");if(!t.has(c)){const l=o.render(n,s,r,i);t.set(c,l)}return t.get(c)};return r(e.template,rn,e.hashToSource)}const Mr={updateCacheKey(s,e,t){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(be(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV3Data(s,be(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(be(s.name,t,s.sourceHash))},render(s,e,t,r){const n=$.PlTemplateSoftwareV1.fromV3Data(s,be(s.name,r,s.sourceHash)),o=e.createStruct($.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},rn={updateCacheKey(s,e,t){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(be(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),Mr.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),Ue.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),Ue.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV3Data(s,be(s.name,r,s.sourceHash)).data));for(const[a,c]of Object.entries(s.libs??{})){const l=$.PlTemplateV1.libField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Mr,r))}for(const[a,c]of Object.entries(s.software??{})){const l=$.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.assets??{})){const l=$.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.templates??{})){const l=$.PlTemplateV1.tplField(n,a);e.createField(l,"Input"),e.setField(l,t(c,rn,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV3Data(s))),i=$.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function be(s,e,t){return b.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function bo(s,e){const t=$.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return nn(s,t);case"pl.tengo-template.v3":return tn(s,t);default:b.assertNever(r)}}function So(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return nn(s,t);case"pl.tengo-template.v3":return tn(s,t);default:b.assertNever(r)}}const qr={hash(s,e){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV2Data(s).data))}},Me={hash(s,e){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=$.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct($.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},sn={hash(s,e){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),qr.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV2Data(s).data));for(const[i,a]of Object.entries(s.libs??{})){const c=$.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(a,qr))}for(const[i,a]of Object.entries(s.software??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[i,a]of Object.entries(s.assets??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[i,a]of Object.entries(s.templates??{})){const c=$.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(a,sn))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV2Data(s))),o=$.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function nn(s,e){const t=new Map,r=(n,o)=>{const i=te.createHash("sha256");o.hash(n,i);const a=i.digest("hex");if(!t.has(a)){const c=o.render(n,s,r);t.set(a,c)}return t.get(a)};return r(e,sn)}const on={name:"TengoTemplateGet",version:"1"},an="registry",cn="templateURI",ln="template",Co={name:"TengoTemplatePack",version:"1"},Ro={name:"TengoTemplatePackConvert",version:"1"},ko="templatePack",Po="template";async function hr(s){switch(s.type){case"from-file":return{type:"explicit",content:await ie.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return b.assertNever(s)}}function Eo(s,e){const t=s.createStruct(on),r=g.field(t,an),n=g.field(t,cn),o=g.field(t,ln);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Be(s,e){switch(e.type){case"from-registry":return Eo(s,e);case"explicit":return bo(s,e);case"prepared":return So(s,e);default:return b.assertNever(e)}}const mr={name:"Frontend/FromUrl",version:"1"},vr={name:"Frontend/FromFolder",version:"1"};function Oo(s,e){switch(e.type){case"url":return s.createValue(mr,JSON.stringify({url:e.url}));case"local":return s.createValue(vr,JSON.stringify({path:e.path,signature:e.signature}));default:return b.assertNever(e)}}class To{constructor(){R(this,"nextMessageId",0);R(this,"worker");R(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:_.resolve(void 0,"worker.js"),t=this.worker=new jn.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?a(new Error(o)):i(n)}),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,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Io={name:"BlockPackCustom",version:"1"},un="template",dn="frontend";function Jr(s){return s.endsWith("/")?s:`${s}/`}function Fo(s){return Buffer.from(s).toString("utf8")}function qe(s){return JSON.parse(Fo(s))}class $o{constructor(e,t,r){R(this,"remoteContentCache",new lr.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await Qe.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 xr(e.folder),r=await ie.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await ie.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Jr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return qe(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=await this.remoteContentCache.forceFetch(r.model.url);return qe(n)}default:return b.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Dr(n,new To,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,a=!0}finally{var c=Lr(n,i,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await xr(e.folder),r=await ie.promises.readFile(t.workflow),n=JSON.parse(await ie.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await ie.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await ie.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Ze(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${Jr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=qe(i);return{type:"explicit",template:{type:"explicit",content:o},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),n=async()=>qe(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,a]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return b.assertNever(e)}}}function Do(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Io,JSON.stringify(t));return s.createField(g.field(r,un),"Input",Be(s,e.template)),s.createField(g.field(r,dn),"Input",Oo(s,e.frontend)),s.lock(r),r}function Gr(s,e){switch(e.type){case"prepared":return Do(s,e);default:return b.assertNever(e.type)}}function Je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Lo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function ir(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(Lo(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const n of e)ir(s,n,t);else for(const[,n]of Object.entries(e))ir(s,n,t);return;default:b.assertNever(r)}}function Ao(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return ir(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class pn{constructor(e){R(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const a of n){const c=this.nodes.get(a);r(c),c[e].forEach(l=>{o.has(l)||(o.add(l),i.push(l))})}n=i}}}function ar(s){const e=new Map;let t;for(const{id:r}of oe(s)){const n={id:r,missingReferences:!1};e.set(r,n),t===void 0?(n.directUpstream=n.upstream=new Set,n.enrichments=n.enrichmentTargets=new Set):(n.directUpstream=n.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([n.id]),t.enrichments=t.enrichmentTargets=new Set),t=n}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new pn(e)}function Ke(s,e){const t=new Map,r=new pn(t),n=new Set;for(const{id:o}of oe(s)){const i=e(o);if(i===void 0)continue;const a=Ao(i.args,n),c=new Set([...a.upstreams,...r.traverseIds("enrichments",...a.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of oe(s)){if(p===o)break;if(c.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(a.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:a.missingReferences,upstream:l,directUpstream:a.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),a.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),l.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function No(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function cr(s,e){if(s.size>e.size)return cr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function _r(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!No(o.upstream,i.upstream)||cr(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?cr(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let ut;async function fn(){if(ut===void 0){const s=await hr(me.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=te.createHash("sha256").update(s.content).digest("hex");ut={spec:s,hash:e}}return ut}function jo(s,e,t){return et(s,e,!0,{pf:t},["result"]).result}let ye;function se(){return ye||(ye={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0,logProjectMutationStat:process.env.MI_LOG_PROJECT_MUTATION_STAT!==void 0,logOutputRecalculations:process.env.MI_LOG_OUTPUT_RECALCULATIONS!==void 0},process.env.MI_LOG_OUTPUT_STATUS&&(ye.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(ye.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),ye)}function dt(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class Kr{constructor(e,t,r,n){R(this,"currentArgsC",dt(()=>this.fields.currentArgs.modCount,()=>b.cachedDeserialize(this.fields.currentArgs.value)));R(this,"prodArgsC",dt(()=>{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 b.cachedDeserialize(e)}));R(this,"productionStaleC",dt(()=>{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,this.config=r,this.source=n}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 currentArgs(){return this.currentArgsC()}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 prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),un,"Input")}}const Bo=s=>{throw new Error(`No new block info for ${s}`)};class Ye{constructor(e,t,r,n,o,i,a,c,l,u,d,p){R(this,"globalModCount",0);R(this,"fieldsChanged",!1);R(this,"lastModifiedChanged",!1);R(this,"structureChanged",!1);R(this,"metaChanged",!1);R(this,"renderingStateChanged",!1);R(this,"blocksWithChangedInputs",new Set);R(this,"stagingGraph");R(this,"pendingProductionGraph");R(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.ctxExportTplHolder=d,this.projectHelper=p}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(Q.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=ar(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=b.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=b.notEmpty(r.fields.blockPack);return g.isResourceId(n.ref)&&g.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),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(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=g.field(this.rid,W(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(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(g.field(this.rid,W(e,o))),delete i[o],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,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.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,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.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,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.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")}setStates(e){const t=[];let r=!1;for(const n of e){const o=this.getBlockInfo(n.blockId);let i=!1;for(const a of["args","uiState"]){if(!(a in n))continue;const c=n[a];if(c==null)throw new Error(`Can't set ${a} to null or undefined, please omit the key if you don't want to change it`);const l=a==="args"?"currentArgs":"uiState";let u,d=!1;if(a==="args")u=b.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=b.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(o.fields[l].value,u)===0)continue;console.log("setting",l,d,u.length);const p=this.tx.createValue(d?g.Pl.JsonGzObject:g.Pl.JsonObject,u);this.setBlockField(n.blockId,l,p,"Ready",u),i=!0,a==="args"&&t.push(n.blockId)}i&&(this.blocksWithChangedInputs.add(n.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:n})=>this.resetStaging(n)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Ur(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Ur(this.tx,t)}exportCtx(e){return jo(this.tx,g.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 n=t.getTemplate(this.tx),o=Vr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.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 n=t.getTemplate(this.tx),o=Vr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Bo){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=ar(e),i=_r(r,o);for(const l of i.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0)}for(const l of i.onlyInB){const u=t(l),d=new Kr(l,{},L.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(l,d);const p=Gr(this.tx,u.blockPack);this.setBlockField(l,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(u.args)),this.setBlockFieldObj(l,"uiState",this.createJsonFieldValueByContent(u.uiState??"{}")),d.check()}for(const l of i.different)this.resetStaging(l);const a=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),c=_r(n,a);n.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.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 n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,Gr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=n.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const l of c.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const a of oe(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const l of n.nodes.get(a.id).upstream)if(o.has(l)){c=!0;break}}c&&(this.renderProductionFor(a.id),o.add(a.id))}const i=[...o];return n.traverse("downstream",i,a=>{o.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new Hs(e),n=new Set(e),o=[];for(;!r.isEmpty();){const c=r.shift(),l=this.getBlockInfo(c).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))n.has(u)||(r.push(u),n.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(n.id,i),t.set(n.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 n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.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,sr(t)):this.tx.setKValue(this.rid,sr(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,nr):this.tx.setKValue(this.rid,nr,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,Le,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Xe,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Ae,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,ze),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,Ae),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,Xe),d=await o,p=new Map;for(const m of d.fields){const v=ao(m.name);if(v===void 0)continue;let S=p.get(v.blockId);S===void 0&&(S={id:v.blockId,fields:{}},p.set(v.blockId,S)),S.fields[v.fieldName]=g.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[S,w]of Object.entries(v)){if(w.ref===void 0)continue;if(!g.isResource(w.ref)||g.isResourceRef(w.ref))throw new Error("unexpected behaviour");const P=S;f.push([m,P,w,t.getResourceData(w.ref,P=="blockPack")])}});const[y,h,C,O,{stagingRefreshTimestamp:V,blocksInLimbo:D}]=await Promise.all([i,a,c,l,u]);if(y!==De)throw Number(y)<Number(De)?new L.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new L.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const x=[];for(const[m,v,S,w]of f){const P=await w;if(S.value=P.data,g.isNotNullResourceId(P.error)?S.status="Error":P.resourceReady||g.isNotNullResourceId(P.originalResourceId)?S.status="Ready":S.status="NotReady",v==="blockPack"){const k=P.fields.find(I=>I.name===g.Pl.HolderRefField);if(k===void 0)throw new Error("Block pack ref field is missing");x.push([m,t.getResourceData(g.ensureResourceIdNotNull(k.value),!1)])}}for(const[m,v]of x){const S=await v,w=b.cachedDeserialize(b.notEmpty(S.data));m.blockConfig=L.extractConfig(w.config),m.blockPack=w.source}const M=await fn(),T=or(M.hash),B=d.fields.find(m=>m.name===T);let E;B!==void 0?E=g.ensureResourceIdNotNull(B.value):(E=g.Pl.wrapInHolder(t,Be(t,M.spec)),t.createField(g.field(r,or(M.hash)),"Dynamic",E));const K={stagingRefreshTimestamp:V},de=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:S,blockPack:w})=>Y.set(m,new Kr(m,v,b.notEmpty(S),b.notEmpty(w))));const G=new Set;for(const m of oe(O)){if(!Y.has(m.id))throw new Error(`Inconsistent project structure: no inputs for ${m.id}`);G.add(m.id)}Y.forEach(m=>{if(!G.has(m.id))throw new Error(`Inconsistent project structure: no structure entry for ${m.id}`);m.check()});const X=new Ye(r,t,n,y,h,C,O,K,de,Y,E,e);return X.fixProblemsAndMigrate(),X}}async function xo(s,e=ro){const t=s.createEphemeral(so);s.lock(t);const r=String(Date.now());s.setKValue(t,ze,JSON.stringify(De)),s.setKValue(t,gr,r),s.setKValue(t,Le,r),s.setKValue(t,Ae,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(eo)),s.setKValue(t,Xe,JSON.stringify(to));const n=await fn();return s.createField(g.field(t,or(n.hash)),"Dynamic",g.Pl.wrapInHolder(s,Be(s,n.spec))),t}async function Ge(s,e,t,r){return ce(s,e,t,void 0,r)}async function ce(s,e,t,r,n){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await Ye.load(s,o,t,r),a=await n(i);return i.wasModified&&(i.save(),await o.commit(),se().logProjectMutationStat&&console.log(JSON.stringify(o.stat))),a});{const o=await Ye.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Vo(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:b.assertNever(s)}}function Hr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Uo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Hr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Hr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:b.assertNever(s)}}const Mo=g.resourceType("PColumnData/JsonPartitioned","1"),qo=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Jo=g.resourceType("PColumnData/BinaryPartitioned","1"),Go=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),_o=g.resourceType("PColumnData/Json","1");function Ko(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(g.resourceTypesEqual(s.resourceType,_o)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,Mo)){const t=e,r=Object.fromEntries(s.listInputFields().map(n=>[n,s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of i){const c=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);r[c]=o.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Jo)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Go)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=o.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=o.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: ${g.resourceTypeToString(s.resourceType)}`)}function Ho(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function Wo(s,e){const t=te.createHash("sha256");return t.update(ne(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Wr(s,e){return ne({__isRef:!0,blockId:s,name:e})}function zo(s,e){return ne({resolvePath:s,name:e})}function gn(s,e=!0,t=!1,r=""){var a,c,l;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=b.notEmpty((a=d.groups)==null?void 0:a.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=b.notEmpty((c=d.groups)==null?void 0:c.type);let y=o.get(p);switch(y===void 0&&(y={},o.set(p,y)),f){case"spec":y.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function Xo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=gn(s,e,!1,t);Bn(n.locked);const o={};for(const[i,a]of n.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;o[i]={id:r.length===0?Wo(a.spec,c.value):zo(r,i),spec:a.spec,data:c.value}}return o}class yr{constructor(e,t){R(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,a,c,l,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(a=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(n!==void 0||(n=(u=(l=(c=r.staging)==null?void 0:c.results)==null?void 0:l.get(t))==null?void 0:u.spec,n!==void 0))return n;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 n=(a=(i=r.prod)==null?void 0:i.results)==null?void 0:a.get(t),o=(c=n==null?void 0:n.data)==null?void 0:c.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return L.mapValueInVOE(o,l=>({id:Wr(e,t),spec:n.spec,data:l}));n!==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 n=i=>{r===void 0&&(r=i),t=!1},o=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:Je(i,a),obj:{id:l.ok?Wr(i,a):void 0,spec:c.spec,data:l}}):n(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||n(`prod_not_locked:${i}`);for(const[l,u]of a.prod.results)c.add(l),o(i,l,u)}if(a.staging!==void 0){a.staging.locked||n(`staging_not_locked:${i}`);for(const[l,u]of a.staging.results)c.has(l)||o(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[c,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Je(o,c),obj:l.spec}),a.add(c))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[c,l]of i.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:Je(o,c),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[a,c]of i.results)n.has(a)||c.spec===void 0||(n.add(a),L.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Je(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=b.notEmpty(n.getKeyValueAsJson(fe)),a=ar(o).traverseIds("upstream",r),c=new Map;for(const l of oe(o)){if(!a.has(l.id))continue;const u=zr(n.traverse({field:W(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:W(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=zr(n.traverse({field:W(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:W(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:d})}return new yr(e,c)}}function zr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return gn(e.value,!1,!0)}function wr(s,e){return{blockId:e,args:o=>b.cachedDecode(b.notEmpty(o.accessor(s).node().traverse({field:W(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:o=>{var a;const i=(a=o.accessor(s).node().traverse({field:W(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:a.getData();return i?b.cachedDecode(i):void 0},uiState:o=>{var a;const i=(a=o.accessor(s).node().traverse({field:W(e,"uiState"),stableIfNotFound:!0}))==null?void 0:a.getData();return i?b.cachedDecode(i):void 0},blockMeta:o=>{const i=o.accessor(s).node(),a=b.notEmpty(i.getKeyValueAsJson(fe)),c=new Map;for(const l of oe(a))c.set(l.id,l);return c}}}function hn(s,e){return{...wr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var n;const r=(n=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>yr.create(t,s,e)}}function*re(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*re(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*re(t);return;case"MakeArray":for(const t of s.template)yield*re(t);return;case"GetJsonField":case"GetResourceField":yield*re(s.source),yield*re(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*re(s.source),yield*re(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*re(s.source);return;case"IsEmpty":yield*re(s.arg);return;case"Not":yield*re(s.operand);return;case"And":case"Or":yield*re(s.operand1),yield*re(s.operand2);return;default:b.assertNever(s)}}function Yo(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Te(s,e){return s===void 0?void 0:e(s)}function Qo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Zo(s){for(const e of re(s))if(Qo(e))return!0;return!1}function tt(s){return{type:"ReturnResult",result:s}}function A(s){return()=>tt(s)}const ei=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return A(e)},ti=s=>{const e=s.source;if(e===void 0)return A(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return A(t)},ri=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?A(void 0):({cCtx:r})=>{var n;return tt((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function mn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function si(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):()=>({type:"ScheduleSubroutine",subroutine:vn(r.length),args:mn(r,n=>j({...s,[e.itVar]:n},e.mapping))})}}function vn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return A(t)}}function ni(s,e){return t=>{const r=t.source;if(r===void 0)return A(void 0);const n={};for(const[o,i]of Object.entries(r)){const a={...s,[e.itVar]:i};n[o]=j(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:oi,args:n})}}const oi=s=>A(s),ii=s=>{const e=s.arg;return A(e===void 0?void 0:e.length===0)},ai=s=>{const e=s.operand;return A(e===void 0?void 0:!e)},ci=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e&&t)},li=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e||t)},ui=s=>{const e=s.source;return e===void 0?A(void 0):({cCtx:t})=>{var r;return tt((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},di=s=>{const e=s.source,t=s.field;return A(e===void 0||t===void 0?void 0:e[t])};function pi(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const a of o.listInputFields()){const c=o.traverse(a);if(c===void 0)i[a]=A(void 0);else{const l={...s,[e.itVar]:c.persist()};i[a]=j(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:fi,args:i}}}}const fi=s=>A(s),gi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo),{postprocessValue:async n=>{if(n!==void 0)return await r.blobDriver.getContent(n.handle,s)}})})},hi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({cCtx:r,drivers:n})=>{const o=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(i=>n.blobDriver.getDownloadedBlob(o,i),{postprocessValue:async i=>i===void 0?void 0:(await n.blobDriver.getContent(i.handle,s)).toString()})}}},mi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const o=await r.blobDriver.getContent(n.handle,s);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},vi=s=>{const e=s.source;return e===void 0?A(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},yi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},wi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},bi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Si=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Ci=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Ri=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},ki=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function j(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>tt(t(r.cCtx)):A(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:bn(t,s,e.cfg)});case"Immediate":return A(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:di,args:{source:j(s,e.source),field:j(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:si(s,e),args:{source:j(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ni(s,e),args:{source:j(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:ei,args:Yo(e.template,t=>j(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:vn(e.template.length),args:mn(e.template,t=>j(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:ti,args:{source:j(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{arg:j(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:ai,args:{operand:j(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ci,args:{operand1:j(s,e.operand1),operand2:j(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:li,args:{operand1:j(s,e.operand1),operand2:j(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:pi(s,e),args:{source:j(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ri,args:{source:j(s,e.source),field:j(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:ui,args:{source:j(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:gi(e.range),args:{source:j(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:hi(e.range),args:{source:j(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:mi(e.range),args:{source:j(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vi,args:{source:j(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:yi,args:{source:j(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:wi(e.format),args:{source:j(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:bi,args:{source:j(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Si(e.lines),args:{source:j(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Ci(e.patternToSearch),args:{source:j(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:Ri(e.patternToSearch),args:{source:j(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:ki,args:{source:j(s,e.source)}});default:return b.assertNever(e)}}const Pi=["$prod","$staging"];function Ei(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 yn=Symbol(),wn="return",Oi={op:yn,arg:wn};function Ti(s){return s.op==yn&&s.arg==wn}function Ii(){return{pendingSubroutines:new Map}}function Xr(s,e,t,r){const n=new Hs(t),o=(a,c)=>{if(Ti(a))return e.result=c,!1;const l=b.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),n.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;n.length>0;){const a=n.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!o(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)n.push({destination:a.destination,operation:c.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{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:b.assertNever(c)}}return i}function Fi(s,e,t,r={}){return bn(s,Ei(e),t,r)}function bn(s,e,t,r={}){const n=`${e.blockId}#`+ne({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Pi.indexOf(o)===-1)),cfg:t});return J.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},a=Ii();return{ir:Xr(i,a,[{destination:Oi,operation:j(e,t)}],!0),postprocessValue(l){const u=[];for(const y of l)u.push({destination:y.destination,operation:A(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,h]of a.pendingSubroutines)p.set(y,{...h,args:{...h.args}});const f={result:a.result,pendingSubroutines:p};if(Xr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function Yr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class $i{constructor(e,t,r,n,o){R(this,"computablesToResolve",{});R(this,"computableCtx");R(this,"accessors",new Map);R(this,"meta");R(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.featureFlags=n,this.computableCtx=o,this.meta=t.blockMeta(o)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(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 Yr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Yr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=Xo(o,t,r,n),a={};for(const[c,l]of Object.entries(i))a[c]=L.mapPObjectData(l,u=>this.wrapAccessor(u));return a}registerComputable(e,t){const r=`${e}_${te.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).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=b.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}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}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=te.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;he.Scope.withScope(n=>{const o=(i,a)=>{const c=(...l)=>{try{return a(...l)}catch(u){const d=t.errorRepo.setAndRecreateForQuickJS(u);throw r.newError(d)}};r.newFunction(i,c).consume(l=>r.setProp(e,i,l)),r.newFunction(i,a).consume(l=>r.setProp(e,i+"__internal__",l))};if(L.checkBlockFlag(this.featureFlags,"supportsLazyState"))o("args",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.args outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.args(this.computableCtx))}),o("uiState",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.uiState outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.uiState(this.computableCtx)??"{}")}),o("activeArgs",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.activeArgs outside the future lambda. Can't be directly used in this context.");const i=this.blockCtx.activeArgs(this.computableCtx);return i===void 0?r.undefined:r.newString(i)});else{const i=this.blockCtx.args(this.computableCtx),a=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(i))),r.setProp(e,"uiState",n.manage(r.newString(c??"{}"))),a!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(a)))}o("getAccessorHandleByName",i=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(i)),void 0)),o("resolveWithCommon",(i,a,...c)=>t.exportSingleValue(this.resolveWithCommon(r.getString(i),t.importObjectViaJson(a),...c.map(l=>t.importObjectViaJson(l))),void 0)),o("getResourceType",i=>t.exportObjectViaJson(this.getResourceType(r.getString(i)),void 0)),o("getInputsLocked",i=>t.exportSingleValue(this.getInputsLocked(r.getString(i)),void 0)),o("getOutputsLocked",i=>t.exportSingleValue(this.getOutputsLocked(r.getString(i)),void 0)),o("getIsReadyOrError",i=>t.exportSingleValue(this.getIsReadyOrError(r.getString(i)),void 0)),o("getIsFinal",i=>t.exportSingleValue(this.getIsFinal(r.getString(i)),void 0)),o("getError",i=>t.exportSingleValue(this.getError(r.getString(i)),void 0)),o("listInputFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("listOutputFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("listDynamicFields",i=>t.exportObjectViaJson(this.listInputFields(r.getString(i)),void 0)),o("getKeyValueBase64",(i,a)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(i),r.getString(a)),void 0)),o("getKeyValueAsString",(i,a)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(i),r.getString(a)),void 0)),o("getDataBase64",i=>t.exportSingleValue(this.getDataBase64(r.getString(i)),void 0)),o("getDataAsString",i=>t.exportSingleValue(this.getDataAsString(r.getString(i)),void 0)),o("parsePObjectCollection",(i,a,c,...l)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(i),r.dump(a),r.getString(c),...l.map(u=>r.getString(u))),void 0)),o("getBlobContentAsBase64",(i,a)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(i),t.importObjectUniversal(a)),void 0)),o("getBlobContentAsString",(i,a)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(i),t.importObjectUniversal(a)),void 0)),o("getDownloadedBlobContentHandle",i=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(i)),void 0)),o("getOnDemandBlobContentHandle",i=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(i)),void 0)),o("extractArchiveAndGetURL",(i,a)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(i),r.getString(a)),void 0)),o("getImportProgress",i=>t.exportSingleValue(this.getImportProgress(r.getString(i)),void 0)),o("getLastLogs",(i,a)=>t.exportSingleValue(this.getLastLogs(r.getString(i),r.getNumber(a)),void 0)),o("getProgressLog",(i,a)=>t.exportSingleValue(this.getProgressLog(r.getString(i),r.getString(a)),void 0)),o("getProgressLogWithInfo",(i,a)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(i),r.getString(a)),void 0)),o("getLogHandle",i=>t.exportSingleValue(this.getLogHandle(r.getString(i)),void 0)),o("getBlockLabel",i=>t.exportSingleValue(this.getBlockLabel(r.getString(i)),void 0)),o("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),o("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),o("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),o("calculateOptions",i=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(i)),void 0)),o("getSpecFromResultPoolByRef",(i,a)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(i),r.getString(a)),void 0)),o("getDataFromResultPoolByRef",(i,a)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(i),r.getString(a)),void 0)),o("createPFrame",i=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(i)),void 0)),o("createPTable",i=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(i)),void 0)),o("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),o("logInfo",i=>{this.logInfo(r.getString(i))}),o("logWarn",i=>{this.logWarn(r.getString(i))}),o("logError",i=>{this.logError(r.getString(i))})})}}function Di(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,n,o){R(this,"callbackRegistry");R(this,"fnJSONStringify");R(this,"fnJSONParse");R(this,"errorRepo",new Li);R(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,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.");o!==void 0&&(this.computableHelper=new $i(this,o.blockCtx,o.mlEnv,n,o.computableCtx)),this.injectCtx()}resetComputableCtx(){b.notEmpty(this.computableHelper,"Computable context helper is not initialized").resetComputableCtx()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.deadlineSetter({currentExecutionTarget:"evaluateBundle",deadline:Date.now()+1e4}),this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Ne.cleanErrorContext(t),t}finally{this.deadlineSetter(void 0)}}runCallback(e,...t){try{return this.deadlineSetter({currentExecutionTarget:e,deadline:Date.now()+1e4}),he.Scope.withScope(r=>{const n=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(n)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(n,this.vm.undefined,...t.map(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw Ne.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}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,n=!1;switch(typeof e){case"string":r=this.vm.newString(e),n=!0;break;case"number":r=this.vm.newNumber(e),n=!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(Di(e)){r=this.vm.newArrayBuffer(e),n=!0;break}return}return n&&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(n=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,n)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){if(e!==void 0)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(){he.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(L.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Li{constructor(){R(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=te.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 he.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.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}, ${g.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new xn.PlQuickJSError(e,n)}}function Ai(s,e,t,r,n,o={}){const{code:i,featureFlags:a}=r,c=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:c},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{se().logOutputRecalculations&&console.log(`Block lambda recalculation : ${c} (${l.changeSourceMarker}; ${l.bodyInvocations} invocations)`);const u=new he.Scope;l.addOnDestroy(()=>u.dispose());const d=u.manage(s.quickJs.newRuntime());d.setMemoryLimit(1024*1024*8),d.setMaxStackSize(1024*320);let p;d.setInterruptHandler(()=>p===void 0?!1:Date.now()>p.deadline);const f=u.manage(d.newContext()),y=new Ne(u,f,O=>{p=O},a,{computableCtx:l,blockCtx:e,mlEnv:s});y.evaluateBundle(i.content);const h=y.runCallback(t.handle);y.resetComputableCtx();let C=0;return se().logOutputStatus==="any"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:y.computableHelper.computablesToResolve,postprocessValue:(O,{unstableMarker:V,stable:D})=>{for(const[M,T]of Object.entries(O))y.runCallback(M,T);const x=y.importObjectUniversal(h);return C++,se().logOutputStatus&&(se().logOutputStatus==="any"||!D)&&console.log(D?`Stable output ${t.handle} calculated ${x!==void 0?"defined":"undefined"}; (#${C})`:`Unstable output ${t.handle}; marker = ${V}; ${x!==void 0?"defined":"undefined"} (#${C})`),x}}},o)}function Ni(s,e,t,...r){const{code:n,featureFlags:o}=t,i=new he.Scope;try{const a=i.manage(s.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let c;a.setInterruptHandler(()=>c===void 0?!1:Date.now()>c.deadline);const l=i.manage(a.newContext()),u=new Ne(i,l,d=>{c=d},o);return u.evaluateBundle(n.content),u.importObjectUniversal(u.runCallback(e.handle,...r))}finally{i.dispose()}}function ji(s){return L.isConfigLambda(s)?s.isActive===!0:Zo(s)}function Ie(s,e,t,r,n,o={}){if(L.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Ai(s,e,t,r,n,o)}else return Fi(s.driverKit,e,t,o)}function je(s,e){return Te(s.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=L.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}function Bi(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Nr.omitBy((r,n)=>n.startsWith("__"));return Nr.isDeepEqual(t(s),t(e))}function xi(s,e,t){return J.Computable.make(r=>{var y,h,C,O,V,D,x,M;const n=r.accessor(s).node(),o=b.notEmpty(n.getKeyValueAsJson(gr)),i=b.notEmpty(n.getKeyValueAsJson(Le)),a=b.notEmpty(n.getKeyValueAsJson(Ae)),c=b.notEmpty(n.getKeyValueAsJson(fe)),l=b.notEmpty(n.getKeyValueAsJson(Xe)),u=new Map;for(const{id:T}of oe(c)){const B=n.traverse({field:W(T,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),E=B.getDataAsJson();let K;const de=n.traverse({field:W(T,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(de!==void 0){const Y=de.getDataAsJson(),G=n.getField({field:W(T,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=n.getField({field:W(T,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:Y,stale:!Bi(E,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((h=X.value)==null?void 0:h.getError())!==void 0,outputsError:((C=G.error)==null?void 0:C.getDataAsString())??((V=(O=G.value)==null?void 0:O.getError())==null?void 0:V.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((M=(x=X.value)==null?void 0:x.getError())==null?void 0:M.getDataAsString()),finished:(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())&&(X.value!==void 0&&X.value.getIsReadyOrError()||X.error!==void 0&&X.error.getIsReadyOrError())}}u.set(T,{currentArguments:E,prod:K,argsRid:B.resourceInfo.id})}const d=Ke(c,T=>{const B=je(n,T),E=u.get(T),K=E.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>B.cfg,()=>K,{argsRid:E.argsRid,blockPackRid:B.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...oe(c)].map(({id:T,label:B,renderingMode:E})=>{var N,F,U,z,q;const K=b.notEmpty(u.get(T)),de=b.notEmpty(d.nodes.get(T));let Y="NotCalculated";K.prod!==void 0&&(p.has(T)?Y="Limbo":Y=K.prod.finished?"Done":"Running");const G=je(n,T),{sections:X,title:m,inputsValid:v,sdkVersion:S,featureFlags:w,isIncompatibleWithRuntime:P}=Te(G,({bpId:ae,cfg:ve})=>{if(!t.runtimeCapabilities.checkCompatibility(ve.featureFlags))return{isIncompatibleWithRuntime:!0,featureFlags:ve.featureFlags};const ct=wr(s,T),pe=L.extractCodeWithInfo(ve);return{sections:Ie(t,ct,ve.sections,pe,ae).wrap({recover:Pe=>(t.logger.error("Error in block model sections"),t.logger.error(Pe),[])}),title:Te(ve.title,Pe=>Ie(t,ct,Pe,pe,ae).wrap({recover:$n=>(t.logger.error("Error in block model title"),t.logger.error($n),"Invalid title")})),inputsValid:Ie(t,ct,ve.inputsValid,pe,ae).wrap({recover:Pe=>(t.logger.error("Error in block model argsValid"),t.logger.error(Pe),!1)}),sdkVersion:pe==null?void 0:pe.sdkVersion,featureFlags:(pe==null?void 0:pe.featureFlags)??{},isIncompatibleWithRuntime:!1}})||{},k=n.traverse({field:W(T,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),I=Te(G,({info:ae})=>t.blockUpdateWatcher.get({currentSpec:ae.source,settings:k}));return{projectResourceId:g.resourceIdToString(s.rid),id:T,label:m??B,title:m??B,renderingMode:E,stale:((N=K.prod)==null?void 0:N.stale)!==!1||Y==="Limbo",missingReference:de.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",T)],downstreams:[...d.traverseIdsExcludingRoots("downstream",T)],calculationStatus:Y,outputErrors:((F=K.prod)==null?void 0:F.outputError)===!0,outputsError:(U=K.prod)==null?void 0:U.outputsError,exportsError:(z=K.prod)==null?void 0:z.exportsError,settings:k,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(q=G==null?void 0:G.info)==null?void 0:q.source,updates:I,sdkVersion:S,featureFlags:w,isIncompatibleWithRuntime:P,navigationState:e.getState(T)}});return{meta:a,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(nr),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const a=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,l={...i,canRun:c,stale:a,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Vi(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,mr)){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(g.resourceTypesEqual(t.resourceType,vr)){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 Ui(s,e){if(s!==void 0)return J.Computable.make(t=>Vi(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 Mi(s,e,t){return J.Computable.make(r=>{var a;const n=r.accessor(s).node(),o=je(n,e),i=(a=n.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:dn,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Ui(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Sn(s,e,t){if(t===void 0)return J.Computable.make(i=>Sn(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=wr(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(sr(e)),args:b.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?b.deepFreeze(JSON.parse(o)):void 0}}function qi(s,e,t){const r="outputs#"+g.resourceIdToString(s.rid)+"#"+e;return J.Computable.make(n=>{se().logOutputRecalculations&&console.log(`blockOutput recalculation : ${r} (${n.changeSourceMarker}; ${n.bodyInvocations} invocations)`);const o=n.accessor(s).node(),i=hn(s,e);return Te(je(o,e),({cfg:a,bpId:c})=>{const l={};for(const[u,d]of Object.entries(a.outputs)){const p=Ie(t,i,d,L.extractCodeWithInfo(a),c);l[u]=J.Computable.wrapError(p,1)}return l})},{key:r}).withStableType()}function Ji(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),n=b.notEmpty(r.getKeyValueAsJson(fe)),o=[];for(const{id:i}of oe(n)){const a=je(r,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,u])=>u).filter(u=>ji(u)).map(u=>u);if(c.length===0)continue;const l=hn(r.persist(),i);for(const u of c)o.push(J.Computable.wrapError(Ie(e,l,u,L.extractCodeWithInfo(a.cfg),a.bpId)))}return o})}class Gi{constructor(){R(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 J.ChangeSource});return}r.state={...t},r.change.markChanged("navigation state changed")}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...L.DefaultNavigationState},change:new J.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return J.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("block deleted"))}}function _i(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=b.notEmpty(t.getKeyValueAsJson(fe));return{listOfBlocks:[...oe(r)].map(n=>n.id)}})}const Ki="1",Hi="BlockFrontendState/";async function Wi(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,ze);if(r!==De){if(r===Ki)await zi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,ze,JSON.stringify(De)),await t.commit()}})}async function zi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,fe),s.listKeyValues(e)]),n=new Map(r.map(o=>[o.key,o.value]));for(const o of oe(t)){const i=Hi+o.id,a=n.get(i),c=a?b.cachedDeserialize(a):{},l=s.createJsonGzValue(c),u=g.field(e,W(o.id,"uiState"));s.createField(u,"Dynamic",l),s.deleteKValue(e,i)}}function Qr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.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 rt{constructor(e,t,r){R(this,"rid");R(this,"overview");R(this,"overviewLight");R(this,"navigationStates",new Gi);R(this,"blockComputables",new Map);R(this,"blockFrontends",new Map);R(this,"activeConfigs");R(this,"refreshLoopResult");R(this,"abortController",new AbortController);R(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=xi(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=_i(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Ji(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ge(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Ws.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=te.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=L.extractConfig(a);return await ce(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.addBlock({id:o,label:e,renderingMode:c.renderingMode},{args:ne(c.initialArgs),uiState:ne(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=L.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ce(this.env.projectHelper,this.env.pl,this.rid,n,a=>a.migrateBlockPack(e,o,r?{args:i.initialArgs,uiState:i.initialUiState}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ce(this.env.projectHelper,this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ce(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const n=r.structure;if(n.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(a=>{const c=o.blocks.find(l=>l.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 Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ce(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,args:t}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ce(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,uiState:t}])),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,n){await ce(this.env.projectHelper,this.env.pl,this.rid,n,o=>{o.setStates([{blockId:e,args:t,uiState:r}])}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ce(this.env.projectHelper,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 n=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,W(e,"blockPack")))).value),o=g.ensureResourceIdNotNull((await r.getField(g.field(n,g.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),a=L.extractConfig(b.cachedDeserialize(b.notEmpty(i.data)).config);await ce(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:a.initialArgs,uiState:a.initialUiState}])}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=qi(this.projectTree.entry(),e,this.env),o={fullState:J.Computable.make(i=>({argsAndUiState:Sn(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const a=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=a&&Yi(a)&&i.outputs!==void 0?Zi(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:l,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Mi(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!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Wi(e.pl,t),await Ge(e.projectHelper,e.pl,t,n=>{});const r=await We.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Xi},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,a)=>{var c,l;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((l=i.data)==null?void 0:l.byteLength)??0)});const o=We.treeDumpStats(n);await $e.writeFile(`${g.resourceIdToString(t)}.json`,Qr(n)),await $e.writeFile(`${g.resourceIdToString(t)}.stats.json`,Qr(o))}return new rt(e,t,r)}}function Xi(s){if(s.type.name.startsWith("StreamWorkdir/"))return[];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 Yi(s){return!Qi(s,"1.26.0")}function Qi(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 Zi(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(n=>typeof n=="string"?n:n.type=="PlError"&&n.fullMessage!==void 0?n.fullMessage:n.message),moreErrors:r.moreErrors}}return e}const br={logger:new b.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Sr(s){return{blobDownloadPath:_.join(s,"download"),blobDownloadRangesCachePath:_.join(s,"downloadRangesCache"),downloadBlobToURLPath:_.join(s,"downloadToURL"),pframesSpillPath:_.join(s,"pframes")}}const Cn={...br,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Rn(s){return{...Sr(s),frontendDownloadPath:_.join(s,"frontend")}}function ea(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var _e={exports:{}},pt,Zr;function st(){if(Zr)return pt;Zr=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return pt={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:s,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},pt}var ft,es;function nt(){return es||(es=1,ft=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),ft}var ts;function xe(){return ts||(ts=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=st(),o=nt();e=s.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],y=C=>{for(const[O,V]of f)C=C.split(`${O}*`).join(`${O}{0,${V}}`).split(`${O}+`).join(`${O}{1,${V}}`);return C},h=(C,O,V)=>{const D=y(O),x=d++;o(C,x,O),u[C]=x,c[x]=O,l[x]=D,i[x]=new RegExp(O,V?"g":void 0),a[x]=new RegExp(D,V?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(_e,_e.exports)),_e.exports}var gt,rs;function Cr(){if(rs)return gt;rs=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return gt=r=>r?typeof r!="object"?s:r:e,gt}var ht,ss;function kn(){if(ss)return ht;ss=1;const s=/^[0-9]+$/,e=(r,n)=>{const o=s.test(r),i=s.test(n);return o&&i&&(r=+r,n=+n),r===n?0:o&&!i?-1:i&&!o?1:r<n?-1:1};return ht={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},ht}var mt,ns;function ee(){if(ns)return mt;ns=1;const s=nt(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=st(),{safeRe:r,t:n}=xe(),o=Cr(),{compareIdentifiers:i}=kn();class a{constructor(l,u){if(u=o(u),l instanceof a){if(l.loose===!!u.loose&&l.includePrerelease===!!u.includePrerelease)return l;l=l.version}else if(typeof l!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof l}".`);if(l.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",l,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=l.trim().match(u.loose?r[n.LOOSE]:r[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${l}`);if(this.raw=l,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(p=>{if(/^[0-9]+$/.test(p)){const f=+p;if(f>=0&&f<t)return f}return p}):this.prerelease=[],this.build=d[5]?d[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(l){if(s("SemVer.compare",this.version,this.options,l),!(l instanceof a)){if(typeof l=="string"&&l===this.version)return 0;l=new a(l,this.options)}return l.version===this.version?0:this.compareMain(l)||this.comparePre(l)}compareMain(l){return l instanceof a||(l=new a(l,this.options)),i(this.major,l.major)||i(this.minor,l.minor)||i(this.patch,l.patch)}comparePre(l){if(l instanceof a||(l=new a(l,this.options)),this.prerelease.length&&!l.prerelease.length)return-1;if(!this.prerelease.length&&l.prerelease.length)return 1;if(!this.prerelease.length&&!l.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=l.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}compareBuild(l){l instanceof a||(l=new a(l,this.options));let u=0;do{const d=this.build[u],p=l.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}inc(l,u,d){if(l.startsWith("pre")){if(!u&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(u){const p=`-${u}`.match(this.options.loose?r[n.PRERELEASELOOSE]:r[n.PRERELEASE]);if(!p||p[1]!==u)throw new Error(`invalid identifier: ${u}`)}}switch(l){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);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 p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),i(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${l}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return mt=a,mt}var vt,os;function Se(){if(os)return vt;os=1;const s=ee();return vt=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(o){if(!n)return null;throw o}},vt}var yt,is;function ta(){if(is)return yt;is=1;const s=Se();return yt=(t,r)=>{const n=s(t,r);return n?n.version:null},yt}var wt,as;function ra(){if(as)return wt;as=1;const s=Se();return wt=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},wt}var bt,cs;function sa(){if(cs)return bt;cs=1;const s=ee();return bt=(t,r,n,o,i)=>{typeof n=="string"&&(i=o,o=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,o,i).version}catch{return null}},bt}var St,ls;function na(){if(ls)return St;ls=1;const s=Se();return St=(t,r)=>{const n=s(t,null,!0),o=s(r,null,!0),i=n.compare(o);if(i===0)return null;const a=i>0,c=a?n:o,l=a?o:n,u=!!c.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(c)===0)return l.minor&&!l.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==o.major?p+"major":n.minor!==o.minor?p+"minor":n.patch!==o.patch?p+"patch":"prerelease"},St}var Ct,us;function oa(){if(us)return Ct;us=1;const s=ee();return Ct=(t,r)=>new s(t,r).major,Ct}var Rt,ds;function ia(){if(ds)return Rt;ds=1;const s=ee();return Rt=(t,r)=>new s(t,r).minor,Rt}var kt,ps;function aa(){if(ps)return kt;ps=1;const s=ee();return kt=(t,r)=>new s(t,r).patch,kt}var Pt,fs;function ca(){if(fs)return Pt;fs=1;const s=Se();return Pt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},Pt}var Et,gs;function le(){if(gs)return Et;gs=1;const s=ee();return Et=(t,r,n)=>new s(t,n).compare(new s(r,n)),Et}var Ot,hs;function la(){if(hs)return Ot;hs=1;const s=le();return Ot=(t,r,n)=>s(r,t,n),Ot}var Tt,ms;function ua(){if(ms)return Tt;ms=1;const s=le();return Tt=(t,r)=>s(t,r,!0),Tt}var It,vs;function Rr(){if(vs)return It;vs=1;const s=ee();return It=(t,r,n)=>{const o=new s(t,n),i=new s(r,n);return o.compare(i)||o.compareBuild(i)},It}var Ft,ys;function da(){if(ys)return Ft;ys=1;const s=Rr();return Ft=(t,r)=>t.sort((n,o)=>s(n,o,r)),Ft}var $t,ws;function pa(){if(ws)return $t;ws=1;const s=Rr();return $t=(t,r)=>t.sort((n,o)=>s(o,n,r)),$t}var Dt,bs;function ot(){if(bs)return Dt;bs=1;const s=le();return Dt=(t,r,n)=>s(t,r,n)>0,Dt}var Lt,Ss;function kr(){if(Ss)return Lt;Ss=1;const s=le();return Lt=(t,r,n)=>s(t,r,n)<0,Lt}var At,Cs;function Pn(){if(Cs)return At;Cs=1;const s=le();return At=(t,r,n)=>s(t,r,n)===0,At}var Nt,Rs;function En(){if(Rs)return Nt;Rs=1;const s=le();return Nt=(t,r,n)=>s(t,r,n)!==0,Nt}var jt,ks;function Pr(){if(ks)return jt;ks=1;const s=le();return jt=(t,r,n)=>s(t,r,n)>=0,jt}var Bt,Ps;function Er(){if(Ps)return Bt;Ps=1;const s=le();return Bt=(t,r,n)=>s(t,r,n)<=0,Bt}var xt,Es;function On(){if(Es)return xt;Es=1;const s=Pn(),e=En(),t=ot(),r=Pr(),n=kr(),o=Er();return xt=(a,c,l,u)=>{switch(c){case"===":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a===l;case"!==":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a!==l;case"":case"=":case"==":return s(a,l,u);case"!=":return e(a,l,u);case">":return t(a,l,u);case">=":return r(a,l,u);case"<":return n(a,l,u);case"<=":return o(a,l,u);default:throw new TypeError(`Invalid operator: ${c}`)}},xt}var Vt,Os;function fa(){if(Os)return Vt;Os=1;const s=ee(),e=Se(),{safeRe:t,t:r}=xe();return Vt=(o,i)=>{if(o instanceof s)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let a=null;if(!i.rtl)a=o.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(o))&&(!a||a.index+a[0].length!==o.length);)(!a||y.index+y[0].length!==a.index+a[0].length)&&(a=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(a===null)return null;const c=a[2],l=a[3]||"0",u=a[4]||"0",d=i.includePrerelease&&a[5]?`-${a[5]}`:"",p=i.includePrerelease&&a[6]?`+${a[6]}`:"";return e(`${c}.${l}.${u}${d}${p}`,i)},Vt}var Ut,Ts;function ga(){if(Ts)return Ut;Ts=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}}return Ut=s,Ut}var Mt,Is;function ue(){if(Is)return Mt;Is=1;const s=/\s+/g;class e{constructor(v,S){if(S=n(S),v instanceof e)return v.loose===!!S.loose&&v.includePrerelease===!!S.includePrerelease?v:new e(v.raw,S);if(v instanceof o)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=v.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=>!h(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&&C(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let v=0;v<this.set.length;v++){v>0&&(this.formatted+="||");const S=this.set[v];for(let w=0;w<S.length;w++)w>0&&(this.formatted+=" "),this.formatted+=S[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const w=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,P=r.get(w);if(P)return P;const k=this.options.loose,I=k?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];v=v.replace(I,G(this.options.includePrerelease)),i("hyphen replace",v),v=v.replace(c[l.COMPARATORTRIM],u),i("comparator trim",v),v=v.replace(c[l.TILDETRIM],d),i("tilde trim",v),v=v.replace(c[l.CARETTRIM],p),i("caret trim",v);let N=v.split(" ").map(q=>V(q,this.options)).join(" ").split(/\s+/).map(q=>Y(q,this.options));k&&(N=N.filter(q=>(i("loose invalid filter",q,this.options),!!q.match(c[l.COMPARATORLOOSE])))),i("range list",N);const F=new Map,U=N.map(q=>new o(q,this.options));for(const q of U){if(h(q))return[q];F.set(q.value,q)}F.size>1&&F.has("")&&F.delete("");const z=[...F.values()];return r.set(w,z),z}intersects(v,S){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>O(w,S)&&v.set.some(P=>O(P,S)&&w.every(k=>P.every(I=>k.intersects(I,S)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new a(v,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(X(this.set[S],v,this.options))return!0;return!1}}Mt=e;const t=ga(),r=new t,n=Cr(),o=it(),i=nt(),a=ee(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=xe(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=st(),h=m=>m.value==="<0.0.0-0",C=m=>m.value==="",O=(m,v)=>{let S=!0;const w=m.slice();let P=w.pop();for(;S&&w.length;)S=w.every(k=>P.intersects(k,v)),P=w.pop();return S},V=(m,v)=>(i("comp",m,v),m=T(m,v),i("caret",m),m=x(m,v),i("tildes",m),m=E(m,v),i("xrange",m),m=de(m,v),i("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",x=(m,v)=>m.trim().split(/\s+/).map(S=>M(S,v)).join(" "),M=(m,v)=>{const S=v.loose?c[l.TILDELOOSE]:c[l.TILDE];return m.replace(S,(w,P,k,I,N)=>{i("tilde",m,w,P,k,I,N);let F;return D(P)?F="":D(k)?F=`>=${P}.0.0 <${+P+1}.0.0-0`:D(I)?F=`>=${P}.${k}.0 <${P}.${+k+1}.0-0`:N?(i("replaceTilde pr",N),F=`>=${P}.${k}.${I}-${N} <${P}.${+k+1}.0-0`):F=`>=${P}.${k}.${I} <${P}.${+k+1}.0-0`,i("tilde return",F),F})},T=(m,v)=>m.trim().split(/\s+/).map(S=>B(S,v)).join(" "),B=(m,v)=>{i("caret",m,v);const S=v.loose?c[l.CARETLOOSE]:c[l.CARET],w=v.includePrerelease?"-0":"";return m.replace(S,(P,k,I,N,F)=>{i("caret",m,P,k,I,N,F);let U;return D(k)?U="":D(I)?U=`>=${k}.0.0${w} <${+k+1}.0.0-0`:D(N)?k==="0"?U=`>=${k}.${I}.0${w} <${k}.${+I+1}.0-0`:U=`>=${k}.${I}.0${w} <${+k+1}.0.0-0`:F?(i("replaceCaret pr",F),k==="0"?I==="0"?U=`>=${k}.${I}.${N}-${F} <${k}.${I}.${+N+1}-0`:U=`>=${k}.${I}.${N}-${F} <${k}.${+I+1}.0-0`:U=`>=${k}.${I}.${N}-${F} <${+k+1}.0.0-0`):(i("no pr"),k==="0"?I==="0"?U=`>=${k}.${I}.${N}${w} <${k}.${I}.${+N+1}-0`:U=`>=${k}.${I}.${N}${w} <${k}.${+I+1}.0-0`:U=`>=${k}.${I}.${N} <${+k+1}.0.0-0`),i("caret return",U),U})},E=(m,v)=>(i("replaceXRanges",m,v),m.split(/\s+/).map(S=>K(S,v)).join(" ")),K=(m,v)=>{m=m.trim();const S=v.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return m.replace(S,(w,P,k,I,N,F)=>{i("xRange",m,w,P,k,I,N,F);const U=D(k),z=U||D(I),q=z||D(N),ae=q;return P==="="&&ae&&(P=""),F=v.includePrerelease?"-0":"",U?P===">"||P==="<"?w="<0.0.0-0":w="*":P&&ae?(z&&(I=0),N=0,P===">"?(P=">=",z?(k=+k+1,I=0,N=0):(I=+I+1,N=0)):P==="<="&&(P="<",z?k=+k+1:I=+I+1),P==="<"&&(F="-0"),w=`${P+k}.${I}.${N}${F}`):z?w=`>=${k}.0.0${F} <${+k+1}.0.0-0`:q&&(w=`>=${k}.${I}.0${F} <${k}.${+I+1}.0-0`),i("xRange return",w),w})},de=(m,v)=>(i("replaceStars",m,v),m.trim().replace(c[l.STAR],"")),Y=(m,v)=>(i("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?l.GTE0PRE:l.GTE0],"")),G=m=>(v,S,w,P,k,I,N,F,U,z,q,ae)=>(D(w)?S="":D(P)?S=`>=${w}.0.0${m?"-0":""}`:D(k)?S=`>=${w}.${P}.0${m?"-0":""}`:I?S=`>=${S}`:S=`>=${S}${m?"-0":""}`,D(U)?F="":D(z)?F=`<${+U+1}.0.0-0`:D(q)?F=`<${U}.${+z+1}.0-0`:ae?F=`<=${U}.${z}.${q}-${ae}`:m?F=`<${U}.${z}.${+q+1}-0`:F=`<=${F}`,`${S} ${F}`.trim()),X=(m,v,S)=>{for(let w=0;w<m.length;w++)if(!m[w].test(v))return!1;if(v.prerelease.length&&!S.includePrerelease){for(let w=0;w<m.length;w++)if(i(m[w].semver),m[w].semver!==o.ANY&&m[w].semver.prerelease.length>0){const P=m[w].semver;if(P.major===v.major&&P.minor===v.minor&&P.patch===v.patch)return!0}return!1}return!0};return Mt}var qt,Fs;function it(){if(Fs)return qt;Fs=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new a(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new a(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}qt=e;const t=Cr(),{safeRe:r,t:n}=xe(),o=On(),i=nt(),a=ee(),c=ue();return qt}var Jt,$s;function at(){if($s)return Jt;$s=1;const s=ue();return Jt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},Jt}var Gt,Ds;function ha(){if(Ds)return Gt;Ds=1;const s=ue();return Gt=(t,r)=>new s(t,r).set.map(n=>n.map(o=>o.value).join(" ").trim().split(" ")),Gt}var _t,Ls;function ma(){if(Ls)return _t;Ls=1;const s=ee(),e=ue();return _t=(r,n,o)=>{let i=null,a=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(l=>{c.test(l)&&(!i||a.compare(l)===-1)&&(i=l,a=new s(i,o))}),i},_t}var Kt,As;function va(){if(As)return Kt;As=1;const s=ee(),e=ue();return Kt=(r,n,o)=>{let i=null,a=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(l=>{c.test(l)&&(!i||a.compare(l)===1)&&(i=l,a=new s(i,o))}),i},Kt}var Ht,Ns;function ya(){if(Ns)return Ht;Ns=1;const s=ee(),e=ue(),t=ot();return Ht=(n,o)=>{n=new e(n,o);let i=new s("0.0.0");if(n.test(i)||(i=new s("0.0.0-0"),n.test(i)))return i;i=null;for(let a=0;a<n.set.length;++a){const c=n.set[a];let l=null;c.forEach(u=>{const d=new s(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!i||t(i,l))&&(i=l)}return i&&n.test(i)?i:null},Ht}var Wt,js;function wa(){if(js)return Wt;js=1;const s=ue();return Wt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Wt}var zt,Bs;function Or(){if(Bs)return zt;Bs=1;const s=ee(),e=it(),{ANY:t}=e,r=ue(),n=at(),o=ot(),i=kr(),a=Er(),c=Pr();return zt=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,h,C,O,V;switch(p){case">":y=o,h=a,C=i,O=">",V=">=";break;case"<":y=i,h=c,C=o,O="<",V="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const x=d.set[D];let M=null,T=null;if(x.forEach(B=>{B.semver===t&&(B=new e(">=0.0.0")),M=M||B,T=T||B,y(B.semver,M.semver,f)?M=B:C(B.semver,T.semver,f)&&(T=B)}),M.operator===O||M.operator===V||(!T.operator||T.operator===O)&&h(u,T.semver))return!1;if(T.operator===V&&C(u,T.semver))return!1}return!0},zt}var Xt,xs;function ba(){if(xs)return Xt;xs=1;const s=Or();return Xt=(t,r,n)=>s(t,r,">",n),Xt}var Yt,Vs;function Sa(){if(Vs)return Yt;Vs=1;const s=Or();return Yt=(t,r,n)=>s(t,r,"<",n),Yt}var Qt,Us;function Ca(){if(Us)return Qt;Us=1;const s=ue();return Qt=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),Qt}var Zt,Ms;function Ra(){if(Ms)return Zt;Ms=1;const s=at(),e=le();return Zt=(t,r,n)=>{const o=[];let i=null,a=null;const c=t.sort((p,f)=>e(p,f,n));for(const p of c)s(p,r,n)?(a=p,i||(i=p)):(a&&o.push([i,a]),a=null,i=null);i&&o.push([i,null]);const l=[];for(const[p,f]of o)p===f?l.push(p):!f&&p===c[0]?l.push("*"):f?p===c[0]?l.push(`<=${f}`):l.push(`${p} - ${f}`):l.push(`>=${p}`);const u=l.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},Zt}var er,qs;function ka(){if(qs)return er;qs=1;const s=ue(),e=it(),{ANY:t}=e,r=at(),n=le(),o=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const h of d.set){for(const C of p.set){const O=c(h,C,f);if(y=y||O!==null,O)continue e}if(y)return!1}return!0},i=[new e(">=0.0.0-0")],a=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=i:d=a}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=a}const y=new Set;let h,C;for(const E of d)E.operator===">"||E.operator===">="?h=l(h,E,f):E.operator==="<"||E.operator==="<="?C=u(C,E,f):y.add(E.semver);if(y.size>1)return null;let O;if(h&&C){if(O=n(h.semver,C.semver,f),O>0)return null;if(O===0&&(h.operator!==">="||C.operator!=="<="))return null}for(const E of y){if(h&&!r(E,String(h),f)||C&&!r(E,String(C),f))return null;for(const K of p)if(!r(E,String(K),f))return!1;return!0}let V,D,x,M,T=C&&!f.includePrerelease&&C.semver.prerelease.length?C.semver:!1,B=h&&!f.includePrerelease&&h.semver.prerelease.length?h.semver:!1;T&&T.prerelease.length===1&&C.operator==="<"&&T.prerelease[0]===0&&(T=!1);for(const E of p){if(M=M||E.operator===">"||E.operator===">=",x=x||E.operator==="<"||E.operator==="<=",h){if(B&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===B.major&&E.semver.minor===B.minor&&E.semver.patch===B.patch&&(B=!1),E.operator===">"||E.operator===">="){if(V=l(h,E,f),V===E&&V!==h)return!1}else if(h.operator===">="&&!r(h.semver,String(E),f))return!1}if(C){if(T&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===T.major&&E.semver.minor===T.minor&&E.semver.patch===T.patch&&(T=!1),E.operator==="<"||E.operator==="<="){if(D=u(C,E,f),D===E&&D!==C)return!1}else if(C.operator==="<="&&!r(C.semver,String(E),f))return!1}if(!E.operator&&(C||h)&&O!==0)return!1}return!(h&&x&&!C&&O!==0||C&&M&&!h&&O!==0||B||T)},l=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y>0?d:y<0||p.operator===">"&&d.operator===">="?p:d},u=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y<0?d:y>0||p.operator==="<"&&d.operator==="<="?p:d};return er=o,er}var tr,Js;function Pa(){if(Js)return tr;Js=1;const s=xe(),e=st(),t=ee(),r=kn(),n=Se(),o=ta(),i=ra(),a=sa(),c=na(),l=oa(),u=ia(),d=aa(),p=ca(),f=le(),y=la(),h=ua(),C=Rr(),O=da(),V=pa(),D=ot(),x=kr(),M=Pn(),T=En(),B=Pr(),E=Er(),K=On(),de=fa(),Y=it(),G=ue(),X=at(),m=ha(),v=ma(),S=va(),w=ya(),P=wa(),k=Or(),I=ba(),N=Sa(),F=Ca(),U=Ra(),z=ka();return tr={parse:n,valid:o,clean:i,inc:a,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:h,compareBuild:C,sort:O,rsort:V,gt:D,lt:x,eq:M,neq:T,gte:B,lte:E,cmp:K,coerce:de,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:S,minVersion:w,validRange:P,outside:k,gtr:I,ltr:N,intersects:F,simplifyRange:U,subset:z,SemVer:t,re:s.re,src:s.src,tokens:s.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},tr}var Ea=Pa();const Oa=ea(Ea),Ta={minDelay:1500},Ia="__no_updates__";class Fa extends J.PollComputablePool{constructor(t,r,n={}){super({...n,...Ta},r);R(this,"http");R(this,"preferredUpdateChannel");this.registryProvider=t,this.http=n.http,this.preferredUpdateChannel=n.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_${ne(t)}`;default:return Ia}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await fr(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await Z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await Ze(i);return a===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,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(o.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(o.channel===void 0)if(await c.getLatestOverview(o.id,Q.StableChannel))l=Q.StableChannel;else{if(await c.getLatestOverview(o.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(o.id)}`),{suggestions:[]};l=Q.AnyChannel}else l=o.channel;const u=await c.getUpdateSuggestions(o.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(y=>y.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:y,update:h})=>({type:y,update:{...o,id:{...o.id,version:h}}}));if(d===void 0)return{suggestions:p};if(a!==void 0&&Oa.lte(d,a))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return ne(t)===ne(r)}}class Gs{constructor(){R(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),(n=>n!=null&&typeof n[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 n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!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}}function Fe(s){return String(s.id)}const $a=["Int","Long","Float","Double","String","Bytes"];function Oe(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}function _s(s){return"partitionFilters"in s?{...s,partitionFilters:Oe(s.partitionFilters),filters:Oe(s.filters)}:{...s,partitionFilters:Oe(s.filters.filter(e=>e.column.type==="axis")),filters:Oe(s.filters.filter(e=>e.column.type==="column"))}}const Ee=(s,e)=>typeof e=="bigint"?e.toString():e;class Da{constructor(e,t,r,n){R(this,"pFrame");R(this,"abortController",new AbortController);R(this,"pTableCache");R(this,"blobIdToResource",new Map);R(this,"blobHandleComputables",new Map);R(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue(this.disposeSignal)});R(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await Ys.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const o=(a,c)=>this.logger[a](c);for(const a of n)for(const c of Vo(a.data))this.blobIdToResource.set(Fe(c),c);const i=[...new Map(n.map(a=>({...a,data:Uo(a.data,Fe)})).map(a=>[ne(a),a])).values()];try{const a=new zs.PFrame(this.spillPath,o);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);this.pFrame=a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}this.pTableCache=new lr.LRUCache({max:5,dispose:a=>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}get disposeSignal(){return this.abortController.signal}cache(e,t){this.pTableCache.set(e,t)}[Symbol.dispose](){this.abortController.abort(),this.pTableCache.clear();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class rr{constructor(e,t,r){R(this,"abortController",new AbortController);R(this,"combinedDisposeSignal");this.pTable=t,this.unrefPredecessor=r,this.combinedDisposeSignal=AbortSignal.any([e,this.abortController.signal])}get disposeSignal(){return this.combinedDisposeSignal}[Symbol.dispose](){var e;this.abortController.abort(),this.pTable.dispose(),(e=this.unrefPredecessor)==null||e.call(this)}}class Tr{constructor(e,t,r){R(this,"pFrames");R(this,"pTables");R(this,"frameConcurrencyLimiter");R(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new b.ConcurrencyLimitingExecutor(1);this.frameConcurrencyLimiter=n,this.tableConcurrencyLimiter=new b.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends Gs{constructor(o,i,a){super(),this.blobDriver=o,this.logger=i,this.spillPath=a}createNewResource(o){return se().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ee)}`),new Da(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){return Aa(o)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Gs{constructor(o){super(),this.pFrames=o}createNewResource(o){se().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ee)}`);const i=o.pFrameHandle,{pFrame:a,disposeSignal:c}=this.pFrames.getByKey(i);if(o.def.sorting.length>0){const{resource:{pTable:u},unref:d}=this.acquire({...o,def:{...o.def,sorting:[]}}),p=u.sort(o.def.sorting);return new rr(c,p,d)}if(o.def.filters.length>0){const{resource:{pTable:u},unref:d}=this.acquire({...o,def:{...o.def,filters:[]}}),p=u.filter(o.def.filters);return new rr(c,p,d)}const l=a.createTable({src:He(o.def.src),filters:o.def.partitionFilters});return new rr(c,l)}calculateParamsKey(o){return La(o)}}(this.pFrames)}async pprofDump(){return await zs.PFrame.pprofDump()}static async init(e,t,r){const n=qn.resolve(r);return await b.emptyDir(n),new Tr(e,t,n)}createPFrame(e,t){const r=e.filter(o=>$a.find(i=>i===o.spec.valueType)).map(o=>L.mapPObjectData(o,i=>We.isPlTreeNodeAccessor(i)?Ko(i):L.isDataInfo(i)?L.mapDataInfo(i,a=>a.resourceInfo):Ho(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t){const r=_s(e),n=this.createPFrame(L.extractAllColumns(r.src),t),o=L.mapPTableDef(r,a=>a.id),i=this.pTables.acquire({def:o,pFrameHandle:n});return se().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(L.mapPTableDef(r,a=>a.spec),Ee)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(i=>[ne(i),i])).values()],qualifications:[]}]:[]},{pFrame:n}=this.pFrames.getByKey(e);return{hits:(await n.findColumns(r)).hits.filter(i=>i.mappingVariants.length===0||i.mappingVariants.some(a=>a.qualifications.forHit.length===0&&a.qualifications.forQueries.every(c=>c.length===0))).map(i=>i.hit)}}async getColumnSpec(e,t){const{pFrame:r}=this.pFrames.getByKey(e);return await r.getColumnSpec(t)}async listColumns(e){const{pFrame:t}=this.pFrames.getByKey(e);return await t.listColumns()}async calculateTableData(e,t,r,n){se().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ee)}`);const{key:o,resource:{pTable:i,disposeSignal:a},unref:c}=this.pTables.acquire({pFrameHandle:e,def:_s(t)}),l=AbortSignal.any([n,a].filter(u=>!!u));return await this.frameConcurrencyLimiter.run(async()=>{this.pFrames.getByKey(e).cache(o,c);const u=i.getSpec(),d=await i.getData([...u.keys()],{range:r,signal:l});return u.map((p,f)=>({spec:p,data:d[f]}))})}async getUniqueValues(e,t,r){se().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ee)}`);const{pFrame:n,disposeSignal:o}=this.pFrames.getByKey(e),i=AbortSignal.any([r,o].filter(a=>!!a));return await this.frameConcurrencyLimiter.run(async()=>await n.getUniqueValues({...t,filters:Oe(t.filters)},{signal:i}))}getSpec(e){const{pTable:t}=this.pTables.getByKey(e);try{return Promise.resolve(t.getSpec())}catch(r){return Promise.reject(L.ensureError(r))}}async getShape(e,t){const{pTable:r,disposeSignal:n}=this.pTables.getByKey(e),o=AbortSignal.any([t,n].filter(i=>!!i));return await this.tableConcurrencyLimiter.run(async()=>await r.getShape({signal:o}))}async getData(e,t,r,n){const{pTable:o,disposeSignal:i}=this.pTables.getByKey(e),a=AbortSignal.any([n,i].filter(c=>!!c));return await this.tableConcurrencyLimiter.run(async()=>await o.getData(t,{range:r,signal:a}))}}function He(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"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>He(e))};case"outer":return{type:"outer",primary:He(s.primary),secondary:s.secondary.map(e=>He(e))};default:b.assertNever(s)}}function La(s){const e=te.createHash("sha256");return e.update(ne(s)),e.digest().toString("hex")}function Aa(s){const e=[...s].map(r=>L.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:Fe(c)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:[Fe(c.index),Fe(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((a,c)=>a.key.localeCompare(c.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(ne(e)),t.digest().toString("hex")}async function Tn(s,e,t){const r={...br,...Sr(e),...t},n=new b.HmacSha256Signer(r.localSecret),o=H.createDownloadClient(r.logger,s,r.localProjections),i=H.createLogsClient(s,r.logger),a=H.createUploadBlobClient(s,r.logger),c=H.createUploadProgressClient(s,r.logger),l=await H.DownloadDriver.init(r.logger,o,i,r.blobDownloadPath,r.blobDownloadRangesCachePath,n,r.blobDriverOps),u=new H.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new H.UploadDriver(r.logger,n,a,c,r.uploadDriverOps),p=new H.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new H.LogsDriver(r.logger,p,l),y=await H.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),h=await Tr.init(l,r.logger,r.pframesSpillPath);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:y,signer:n,uploadDriver:d,pFrameDriver:h}}class Na{constructor(e){R(this,"enrichmentTargetsCache",new lr.LRUCache({max:256,memoMethod:(e,t,{context:r})=>({value:this.calculateEnrichmentTargets(r)})}));this.quickJs=e}calculateEnrichmentTargets(e){const t=e.blockConfig();if(t.enrichmentTargets===void 0)return;const r=e.args();return Ni(this.quickJs,t.enrichmentTargets,L.extractCodeWithInfo(t),r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Ir{constructor(e,t,r,n,o,i,a,c){R(this,"pl");R(this,"projectList");R(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}addRuntimeCapability(e,t=!0){this.env.runtimeCapabilities.addSupportedRequirement(e,t)}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await xo(n,e);return n.createField(g.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await g.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ce(this.env.projectHelper,this.pl,e,r,n=>{n.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(g.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(g.field(this.projectListResourceId,e))).value;if(g.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 rt.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 b.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...Cn,...Rn(t),...r};n.defaultTreeOptions.logStat=se().logTreeStats,n.debugOps.dumpInitialTreeState=se().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async O=>{const V=g.field(O.clientRoot,co);O.createField(V,"Dynamic");const D=await O.getField(V);if(g.isNullResourceId(D.value)){const x=O.createEphemeral(en);return O.lock(x),O.setField(V,x),await O.commit(),await x.globalId}else return D.value}),i=n.logger,a=await Tn(e,t,n),c=new Qe.RetryAgent(e.httpDispatcher),l=new Zs(c),u=new $o(l,a.signer,c),d=new H.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await he.getQuickJS(),f=new L.RuntimeCapabilities;f.addSupportedRequirement("requiresModelAPIVersion",1);const y={pl:e,blockEventDispatcher:new b.BlockEventDispatcher,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new Fa(l,i,{minDelay:n.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:n.preferredUpdateChannel}),runtimeCapabilities:f,quickJs:p,projectHelper:new Na(p)},h=new J.WatchableValue([]),C=await uo(e,o,h,y);return new Ir(y,a,a.signer,o,h,C.tree,l,C.computable)}}async function ja(s,e){return await Ce(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Ba(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function xa(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function Va(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function Ua(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Ma(s,e){return await Ce(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Ve(s.autoUpdateCdnUrl,s,e))}async function Ce(s,e,t){const r=Date.now(),n=[];for(;Ks(r)<s;){const o=Date.now();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const a=Ks(o);n.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Ws.setTimeout(c)}return n}async function Ve(s,e,t){const{body:r,statusCode:n}=await Qe.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Ks(s){return Date.now()-s}function we(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:n}=qa(s),o=`
2
2
  total: ${s.length};
3
3
  successes: ${e.length};
4
4
  errors: ${t};
5
5
  mean in ms: ${r};
6
6
  median in ms: ${n};
7
- `;return{ok:t===0,details:o}}function qa(s){const e=s.map(n=>n.elapsedMs).sort(),t=e.reduce((n,o)=>n+o)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}async function Ja(s,e,t){try{const r=await Ga(s,e,t);return r!==`Hello, ${t}`?{status:"failed",message:`Template uploading failed: expected: ${t}, got: ${r}`}:{status:"ok",message:`Template uploading succeeded: ${r}`}}catch(r){return{status:"failed",message:`Template uploading failed: error occurred: ${r}`}}}async function Ga(s,e,t){var n;const r=await Ce(e,me.Templates["check_network.upload_template"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(b.notEmpty((n=(await ge(e,r.greeting)).data)==null?void 0:n.toString()))}finally{r!=null&&await ke(e,Object.values(r))}}async function _a(s,e,t,r,n,o){try{const i=await Ka(s,e,t,r,n,o);return i.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${i.type.name}`}:{status:"ok",message:`File uploading succeeded: ${i.type.name}`}}catch(i){return{status:"failed",message:`File uploading failed: error occurred: ${i}`}}}async function Ka(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),a=await Ce(n,me.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await ge(n,a.progress);if(H.isUpload(l)){const u=H.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((c=l.data)==null?void 0:c.toString())));H.isSignMatch(e,u.localPath,u.pathSignature)&&await H.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await ge(n,a.file)}finally{await ke(n,Object.values(a))}}async function Ha(s,e,t,r,n,o,i){try{const a=await Wa(s,e,t,r,n,o);return a!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${a}`}:{status:"ok",message:`File downloading succeeded: ${a}`}}catch(a){return{status:"failed",message:`File downloading failed: error occurred: ${a}`}}}async function Wa(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),a=await Ce(e,me.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await ge(e,a.progress);await H.uploadBlob(s,r,l,H.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((c=l.data)==null?void 0:c.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await ge(e,a.file),{content:d}=await n.downloadBlob(u);return await Vn.text(d)}finally{await ke(e,Object.values(a))}}async function za(s){try{const e=await Xa(s);return e!==`Hello from go binary
8
- `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function Xa(s){var t;const e=await Ce(s,me.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return b.notEmpty((t=(await ge(s,e.greeting)).data)==null?void 0:t.toString())}finally{await ke(s,Object.values(e))}}async function Ya(s,e){try{const t=await Qa(s,e);return t!==`Hello, ${e}!
9
- `?{status:"failed",message:`Python software check failed: got: ${t}`}:{status:"ok",message:`Python software check succeeded: ${t}`}}catch(t){return{status:"failed",message:`Python software check failed: error occurred: ${t}`}}}async function Qa(s,e){var r;const t=await Ce(s,me.Templates["check_network.run_hello_world_py"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return b.notEmpty((r=(await ge(s,t.greeting)).data)==null?void 0:r.toString())}finally{await ke(s,Object.values(t))}}async function Za(s,e,t,r){var n,o;try{const i=await t.getStorageList(),a={};for(const c of i){const l=await ec(t,c,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){a[c.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${c.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${c.name}`);const u=await Ce(e,me.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdirTypeName"]);try{const d=JSON.parse(Buffer.from((await ge(e,u.workdirTypeName)).data).toString());d!=null&&d.startsWith("WorkingDirectory")?a[c.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(n=l.file)==null?void 0:n.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:a[c.name]={status:"failed",message:`Workdir creation failed: ${d}, size of file: ${(o=l.file)==null?void 0:o.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await ke(e,Object.values(u))}}return a}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function ec(s,e,t,r,n,o){const i=On(s,e,"",0);let a,c=0,l=0;for await(const{file:u,nLsRequests:d}of i){if(l=Math.max(l,d),c>=t&&l>o)return{file:a,nLsRequests:l,nCheckedFiles:c};if(c++,r<=u.size&&u.size<=n)return{file:u,nLsRequests:l,nCheckedFiles:c};u.size<r&&(a=u)}return{file:a,nLsRequests:l,nCheckedFiles:c}}async function*On(s,e,t,r){r++;const n=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const o of n.entries)if(o.type==="file"&&o.fullPath.startsWith(t))yield{file:o,nLsRequests:r};else if(o.type==="dir")for await(const i of On(s,e,o.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function tc(){const s=_.join(Ws.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await $e.appendFile(s,t),{filePath:s}}async function rc(){const s=_.join(Ws.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await $e.writeFile(s,e),{filePath:s,fileContent:e}}async function Ce(s,e,t,r,n){return await s.withWriteTx("TemplateRender",async o=>{const i=await fr(e),a=Be(o,i),c=Ze(o,a,t,r(o),n),l={};for(const u of n){const d=g.field(s.clientRoot,u);o.createField(d,"Dynamic",c[u]),l[u]=await g.toGlobalFieldId(d)}return await o.commit(),l})}async function ge(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const n=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${n.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function ke(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function sc(s,e,t,r={}){const n=[];oc.forEach(o=>{xn.channel(o).subscribe(a=>{var u,d;const c=new Date().toISOString(),l={...a};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),n.push(JSON.stringify({timestamp:c,event:o,data:l}))})});try{const{logger:o,plConfig:i,client:a,signer:c,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Tn(s,e,t,r),{filePath:y,fileContent:h}=await rc(),{filePath:R}=await tc(),O={plPings:await ja(f,i),blockRegistryOverviewChecks:await Ba(f,p),blockGARegistryOverviewChecks:await xa(f,p),blockRegistryUiChecks:await Va(f,p),blockGARegistryUiChecks:await Ua(f,p),autoUpdateCdnChecks:await Ma(f,p),uploadTemplateCheck:await Ja(o,a,"Jack"),uploadFileCheck:await _a(o,c,d,u,a,R),downloadFileCheck:await Ha(o,a,d,u,l,y,h),softwareCheck:await za(a),pythonSoftwareCheck:await Ya(a,"Jack"),storageToDownloadReport:await Za(o,a,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return nc(O,s,f,n)}catch(o){return`Unhandled error while checking the network: ${o}`}}async function Tn(s,e,t,r={}){const n={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,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},o=g.plAddressToConfig(s,{defaultRequestTimeout:n.pingTimeoutMs});o.alternativeRoot=`check_network_${te.randomUUID()}`;const i=new g.UnauthenticatedPlClient(o);let a={};e&&t&&(a=await i.login(e,t));const c=await g.PlClient.init(s,{authInformation:a}),l=i.ll.httpDispatcher,u=new b.ConsoleLoggerAdapter,d=new b.HmacSha256Signer("localSecret"),p=H.createDownloadClient(u,c,[]),f=H.createUploadBlobClient(c,u),y=await H.LsDriver.init(u,c,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:o,client:c,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:y,httpClient:l,ops:n,terminate:async()=>{p.close(),f.close(),await l.close(),await c.close()}}}function nc(s,e,t,r){const n=s.plPings.filter(R=>R.response.ok),o=s.plPings.filter(R=>!R.response.ok),i=[...new Set(n.map(R=>JSON.stringify(R.response.value)))],a=R=>R?"OK":"FAILED",c=R=>R.status==="ok"?"OK":R.status==="warn"?"WARN":"FAILED",l=we(s.plPings),u=we(s.blockRegistryOverviewChecks),d=we(s.blockGARegistryOverviewChecks),p=we(s.blockRegistryUiChecks),f=we(s.blockGARegistryUiChecks),y=we(s.autoUpdateCdnChecks),h=Object.entries(s.storageToDownloadReport).map(([R,O])=>`${c(O)} ${R} storage check`).join(`
7
+ `;return{ok:t===0,details:o}}function qa(s){const e=s.map(n=>n.elapsedMs).sort(),t=e.reduce((n,o)=>n+o)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}async function Ja(s,e,t){try{const r=await Ga(s,e,t);return r!==`Hello, ${t}`?{status:"failed",message:`Template uploading failed: expected: ${t}, got: ${r}`}:{status:"ok",message:`Template uploading succeeded: ${r}`}}catch(r){return{status:"failed",message:`Template uploading failed: error occurred: ${r}`}}}async function Ga(s,e,t){var n;const r=await Re(e,me.Templates["check_network.upload_template"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(b.notEmpty((n=(await ge(e,r.greeting)).data)==null?void 0:n.toString()))}finally{r!=null&&await ke(e,Object.values(r))}}async function _a(s,e,t,r,n,o){try{const i=await Ka(s,e,t,r,n,o);return i.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${i.type.name}`}:{status:"ok",message:`File uploading succeeded: ${i.type.name}`}}catch(i){return{status:"failed",message:`File uploading failed: error occurred: ${i}`}}}async function Ka(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),a=await Re(n,me.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await ge(n,a.progress);if(H.isUpload(l)){const u=H.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((c=l.data)==null?void 0:c.toString())));H.isSignMatch(e,u.localPath,u.pathSignature)&&await H.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await ge(n,a.file)}finally{await ke(n,Object.values(a))}}async function Ha(s,e,t,r,n,o,i){try{const a=await Wa(s,e,t,r,n,o);return a!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${a}`}:{status:"ok",message:`File downloading succeeded: ${a}`}}catch(a){return{status:"failed",message:`File downloading failed: error occurred: ${a}`}}}async function Wa(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),a=await Re(e,me.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const l=await ge(e,a.progress);await H.uploadBlob(s,r,l,H.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((c=l.data)==null?void 0:c.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await ge(e,a.file),{content:d}=await n.downloadBlob(u);return await Mn.text(d)}finally{await ke(e,Object.values(a))}}async function za(s){try{const e=await Xa(s);return e!==`Hello from go binary
8
+ `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function Xa(s){var t;const e=await Re(s,me.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return b.notEmpty((t=(await ge(s,e.greeting)).data)==null?void 0:t.toString())}finally{await ke(s,Object.values(e))}}async function Ya(s,e){try{const t=await Qa(s,e);return t!==`Hello, ${e}!
9
+ `?{status:"failed",message:`Python software check failed: got: ${t}`}:{status:"ok",message:`Python software check succeeded: ${t}`}}catch(t){return{status:"failed",message:`Python software check failed: error occurred: ${t}`}}}async function Qa(s,e){var r;const t=await Re(s,me.Templates["check_network.run_hello_world_py"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return b.notEmpty((r=(await ge(s,t.greeting)).data)==null?void 0:r.toString())}finally{await ke(s,Object.values(t))}}async function Za(s,e,t,r){var n,o;try{const i=await t.getStorageList(),a={};for(const c of i){const l=await ec(t,c,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){a[c.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${c.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${c.name}`);const u=await Re(e,me.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdirTypeName"]);try{const d=JSON.parse(Buffer.from((await ge(e,u.workdirTypeName)).data).toString());d!=null&&d.startsWith("WorkingDirectory")?a[c.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(n=l.file)==null?void 0:n.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:a[c.name]={status:"failed",message:`Workdir creation failed: ${d}, size of file: ${(o=l.file)==null?void 0:o.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await ke(e,Object.values(u))}}return a}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function ec(s,e,t,r,n,o){const i=In(s,e,"",0);let a,c=0,l=0;for await(const{file:u,nLsRequests:d}of i){if(l=Math.max(l,d),c>=t&&l>o)return{file:a,nLsRequests:l,nCheckedFiles:c};if(c++,r<=u.size&&u.size<=n)return{file:u,nLsRequests:l,nCheckedFiles:c};u.size<r&&(a=u)}return{file:a,nLsRequests:l,nCheckedFiles:c}}async function*In(s,e,t,r){r++;const n=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const o of n.entries)if(o.type==="file"&&o.fullPath.startsWith(t))yield{file:o,nLsRequests:r};else if(o.type==="dir")for await(const i of In(s,e,o.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function tc(){const s=_.join(Xs.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await $e.appendFile(s,t),{filePath:s}}async function rc(){const s=_.join(Xs.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await $e.writeFile(s,e),{filePath:s,fileContent:e}}async function Re(s,e,t,r,n){return await s.withWriteTx("TemplateRender",async o=>{const i=await hr(e),a=Be(o,i),c=et(o,a,t,r(o),n),l={};for(const u of n){const d=g.field(s.clientRoot,u);o.createField(d,"Dynamic",c[u]),l[u]=await g.toGlobalFieldId(d)}return await o.commit(),l})}async function ge(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const n=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${n.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function ke(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function sc(s,e,t,r={}){const n=[];oc.forEach(o=>{Un.channel(o).subscribe(a=>{var u,d;const c=new Date().toISOString(),l={...a};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),n.push(JSON.stringify({timestamp:c,event:o,data:l}))})});try{const{logger:o,plConfig:i,client:a,signer:c,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Fn(s,e,t,r),{filePath:y,fileContent:h}=await rc(),{filePath:C}=await tc(),O={plPings:await ja(f,i),blockRegistryOverviewChecks:await Ba(f,p),blockGARegistryOverviewChecks:await xa(f,p),blockRegistryUiChecks:await Va(f,p),blockGARegistryUiChecks:await Ua(f,p),autoUpdateCdnChecks:await Ma(f,p),uploadTemplateCheck:await Ja(o,a,"Jack"),uploadFileCheck:await _a(o,c,d,u,a,C),downloadFileCheck:await Ha(o,a,d,u,l,y,h),softwareCheck:await za(a),pythonSoftwareCheck:await Ya(a,"Jack"),storageToDownloadReport:await Za(o,a,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return nc(O,s,f,n)}catch(o){return`Unhandled error while checking the network: ${o}`}}async function Fn(s,e,t,r={}){const n={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,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},o=g.plAddressToConfig(s,{defaultRequestTimeout:n.pingTimeoutMs});o.alternativeRoot=`check_network_${te.randomUUID()}`;const i=new g.UnauthenticatedPlClient(o);let a={};e&&t&&(a=await i.login(e,t));const c=await g.PlClient.init(s,{authInformation:a}),l=i.ll.httpDispatcher,u=new b.ConsoleLoggerAdapter,d=new b.HmacSha256Signer("localSecret"),p=H.createDownloadClient(u,c,[]),f=H.createUploadBlobClient(c,u),y=await H.LsDriver.init(u,c,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:o,client:c,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:y,httpClient:l,ops:n,terminate:async()=>{p.close(),f.close(),await l.close(),await c.close()}}}function nc(s,e,t,r){const n=s.plPings.filter(C=>C.response.ok),o=s.plPings.filter(C=>!C.response.ok),i=[...new Set(n.map(C=>JSON.stringify(C.response.value)))],a=C=>C?"OK":"FAILED",c=C=>C.status==="ok"?"OK":C.status==="warn"?"WARN":"FAILED",l=we(s.plPings),u=we(s.blockRegistryOverviewChecks),d=we(s.blockGARegistryOverviewChecks),p=we(s.blockRegistryUiChecks),f=we(s.blockGARegistryUiChecks),y=we(s.autoUpdateCdnChecks),h=Object.entries(s.storageToDownloadReport).map(([C,O])=>`${c(O)} ${C} storage check`).join(`
10
10
  `);return`
11
11
  ${a(l.ok)} pings to Platforma Backend
12
12
  ${a(u.ok)} block registry overview
@@ -72,5 +72,5 @@ ${JSON.stringify(i,null,2)}
72
72
  Undici logs:
73
73
  ${r.join(`
74
74
  `)}
75
- `}const oc=["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"];exports.BlockPackRegistry=Wn;exports.CentralBlockRegistry=zn;exports.DefaultDriverKitOpsPaths=wr;exports.DefaultDriverKitOpsSettings=yr;exports.DefaultMiddleLayerOpsPaths=Sn;exports.DefaultMiddleLayerOpsSettings=bn;exports.FrontendFromFolderResourceType=hr;exports.FrontendFromUrlResourceType=gr;exports.MiddleLayer=Or;exports.Project=tt;exports.TengoTemplateGet=sn;exports.TengoTemplateGetRegistry=nn;exports.TengoTemplateGetTemplate=an;exports.TengoTemplateGetTemplateURI=on;exports.TengoTemplatePack=bo;exports.TengoTemplatePackConvert=So;exports.TengoTemplatePackConvertTemplate=Co;exports.TengoTemplatePackConvertTemplatePack=Ro;exports.V1CentralDevSnapshotRegistry=Yn;exports.V1CentralRegistry=Xn;exports.V2RegistryProvider=Ys;exports.checkNetwork=sc;exports.createRenderTemplate=Ze;exports.getDevV1PacketMtime=dr;exports.getDevV2PacketMtime=Qe;exports.initDriverKit=En;exports.initNetworkCheck=Tn;exports.loadTemplate=Be;exports.prepareTemplateSpec=fr;Object.keys(L).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>L[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(Dr).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Dr[s]})});Object.keys(g).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>g[s]})});
75
+ `}const oc=["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"];exports.BlockPackRegistry=Xn;exports.CentralBlockRegistry=Yn;exports.DefaultDriverKitOpsPaths=Sr;exports.DefaultDriverKitOpsSettings=br;exports.DefaultMiddleLayerOpsPaths=Rn;exports.DefaultMiddleLayerOpsSettings=Cn;exports.FrontendFromFolderResourceType=vr;exports.FrontendFromUrlResourceType=mr;exports.MiddleLayer=Ir;exports.Project=rt;exports.TengoTemplateGet=on;exports.TengoTemplateGetRegistry=an;exports.TengoTemplateGetTemplate=ln;exports.TengoTemplateGetTemplateURI=cn;exports.TengoTemplatePack=Co;exports.TengoTemplatePackConvert=Ro;exports.TengoTemplatePackConvertTemplate=Po;exports.TengoTemplatePackConvertTemplatePack=ko;exports.V1CentralDevSnapshotRegistry=Zn;exports.V1CentralRegistry=Qn;exports.V2RegistryProvider=Zs;exports.checkNetwork=sc;exports.createRenderTemplate=et;exports.getDevV1PacketMtime=fr;exports.getDevV2PacketMtime=Ze;exports.initDriverKit=Tn;exports.initNetworkCheck=Fn;exports.loadTemplate=Be;exports.prepareTemplateSpec=hr;Object.keys(L).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>L[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(Ar).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Ar[s]})});Object.keys(g).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>g[s]})});
76
76
  //# sourceMappingURL=index.js.map