@milaboratories/pl-middle-layer 1.37.26 → 1.37.28

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,4 +1,4 @@
1
- "use strict";var Fs=Object.defineProperty;var Yt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Qt=s=>{throw TypeError(s)};var As=(s,e,t)=>e in s?Fs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var k=(s,e,t)=>As(s,typeof e!="symbol"?e+"":e,t);var Zt=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Qt("Object expected");var r;t&&(r=e[Yt("asyncDispose")]),r===void 0&&(r=e[Yt("dispose")]),typeof r!="function"&&Qt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},er=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,l,a,c){return c=Error(a),c.name="SuppressedError",c.error=i,c.suppressed=l,c},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var l=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(l).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("@platforma-sdk/model"),z=require("@milaboratories/pl-model-middle-layer"),tr=require("@milaboratories/pl-deployments"),tt=require("undici"),X=require("@platforma-sdk/block-tools"),te=require("node:fs"),J=require("node:path"),Ds=require("yaml"),b=require("@milaboratories/ts-helpers"),Ae=require("node:fs/promises"),Ls=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),Qe=require("@milaboratories/pl-tree"),V=require("@milaboratories/computable"),ee=require("node:crypto"),O=require("@milaboratories/pl-model-backend"),$t=require("lru-cache"),Ns=require("node:worker_threads"),Gr=require("denque"),he=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),Bs=require("node:assert"),fe=require("quickjs-emscripten"),js=require("@milaboratories/pl-errors"),Vs=require("remeda"),_r=require("node:timers/promises"),M=require("@milaboratories/pl-drivers"),xs=require("@milaboratories/pframes-rs-node"),Us=require("node:diagnostics_channel"),Ms=require("node:stream/consumers"),Kr=require("node:os");function Tt(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 Js=Tt(J),Hr=Tt(Ae),rr=Tt(Vs);async function sr(s){try{return await Hr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Gs=[X.RegistryV1.PlPackageYamlConfigFile],_s=[X.RegistryV1.PlPackageJsonConfigFile],It=["backend","dist","tengo","tpl","main.plj.gz"],Ft=["config","dist","config.json"],qr=["frontend","dist"],or="block-model/dist/config.json",Ks="block-ui/package.json",Hs=[It,Ft,Gs,_s,qr];async function qs(s){return await sr(J.join(s,...Ft))!==void 0||await sr(J.join(s,...It))!==void 0}function dt(s,e){const t=Ls.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function nr(s,e){if(J.isAbsolute(s)||(s=J.resolve(s)),await qs(s))return{workflow:J.join(s,...It),config:J.join(s,...Ft),ui:J.join(s,...qr)};{const t=dt(s,or),r=dt(s,or),o=dt(s,Ks);return{workflow:t,config:r,ui:J.resolve(o,"..","dist")}}}async function Ws(s){try{return await te.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function zs(s){try{return await te.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function At(s){let e=0n;for(const t of Hs){const r=J.join(s,...t),o=await zs(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function rt(s){const e=await te.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await te.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Xs{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await tt.request(`${r.url}/${X.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const l of i){const{organization:a,package:c,latestMeta:u,latestVersion:d}=l,p={organization:a,name:c,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[z.AnyChannel]:f,[z.StableChannel]:f},allVersions:l.allVersions.map(R=>({version:R,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await te.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=J.join(r.path,o.name),i=await Ws(J.join(n,X.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const l=X.RegistryV1.PlPackageConfigData.parse(Ds.parse(i)),a=await At(n),c={organization:l.organization,name:l.package,version:"DEV"},u={id:c,meta:{title:l.meta.title??"No title",description:l.meta.description??"No Description",organization:{name:l.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:a}};t.push({registryId:e.id,id:c,latestByChannel:{[z.AnyChannel]:u,[z.StableChannel]:u},allVersions:[]})}else{let l=n,a=await X.tryLoadPackDescription(l);if(a===void 0){for(const c of["block","meta"])if(l=J.join(n,c),a=await X.tryLoadPackDescription(l),a!==void 0)break}if(a!==void 0){const c=await rt(a),u={id:a.id,meta:await X.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:l,mtime:c}};t.push({registryId:e.id,id:a.id,latestByChannel:{[z.AnyChannel]:u,[z.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 o=(i=this.registries.find(l=>l.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class Wr{constructor(e){k(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new X.RegistryV2Reader(X.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ys={type:"remote-v2",url:"https://blocks.pl-open.science/"},Qs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Zs={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"},zr="SchemaVersion",Xr="1",Dt="ProjectCreated",De="ProjectLastModified",Le="ProjectMeta",ge="ProjectStructure",Ze="BlockRenderingState",oo="BlockFrontendState/",no=/^BlockFrontendState\/(?<blockid>.*)$/;function St(s){return`${oo}${s}`}const io="BlockArgsAuthor/";function bt(s){return`${io}${s}`}const kt="ProjectStructureAuthor";function ao(s){const e=s.match(no);if(e!==null)return e.groups.blockid}const co="__serviceTemplate_";function Pt(s){return`${co}${s}`}function K(s,e){return`${s}-${e}`}const lo=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function uo(s){const e=s.match(lo);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const po="projects",Yr={name:"Projects",version:"1"},fo=s=>g.resourceTypesEqual(s.type,Yr)?s.fields:[];async function go(s,e,t,r){const o=await Qe.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:fo},r.logger);return{computable:V.Computable.make(i=>{const l=i.accessor(o.entry()).node(),a=t.getValue(i);if(l===void 0)return;const c=[];for(const u of l.listDynamicFields()){const d=l.traverse(u);if(d===void 0)continue;const p=b.notEmpty(d.getKeyValueAsJson(Le)),f=b.notEmpty(d.getKeyValueAsJson(Dt)),R=b.notEmpty(d.getKeyValueAsJson(De));c.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(R),opened:a.indexOf(d.id)>=0,meta:p})}return c.sort(u=>-u.lastModified.valueOf()),c}).withStableType(),tree:o}}const ho={name:"EphRenderTemplate",version:"1"},mo={name:"RenderTemplate",version:"1"};function st(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(ho):s.createStruct(mo),i=g.field(n,"template"),l=g.field(n,"inputs");return s.createField(i,"Input",e),s.createField(l,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(n),g.Pl.futureRecord(s,n,o,"Output","outputs/")}const yo={name:"BContextEnd",version:"1"},vo={name:"BContext",version:"1"},wo="id",So="parent/",bo=["context","result"];function ir(s,e,t){return st(s,e,!0,t,bo)}function ko(s){const e=s.createEphemeral(yo);return s.lock(e),e}function ar(s,e){if(e.length===0)return ko(s);if(e.length===1)return e[0];const t=s.createEphemeral(vo);s.createField(g.field(t,wo),"Input",g.Pl.createPlString(s,ee.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${So}${r}`),"Input",e[r]);return s.lock(t),t}function Qr(s,e){const t=new Map,r=(o,n,i)=>{const l=ee.createHash("sha256");n.updateCacheKey(o,l,i);const a=l.digest("hex");if(!t.has(a)){const c=n.render(o,s,r,i);t.set(a,c)}return t.get(a)};return r(e.template,Zr,e.hashToSource)}const cr={updateCacheKey(s,e,t){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){const o=O.PlTemplateSoftwareV1.fromV3Data(s,we(s.name,r,s.sourceHash)),n=e.createStruct(O.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},Zr={updateCacheKey(s,e,t){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(we(s.name,t,s.sourceHash));const r=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of r(Object.entries(s.libs??{})))e.update("lib:"+o),cr.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.software??{})))e.update("soft:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.assets??{})))e.update("asset:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(s,e,t,r){const o=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data));for(const[l,a]of Object.entries(s.libs??{})){const c=O.PlTemplateV1.libField(o,l);e.createField(c,"Input"),e.setField(c,t(a,cr,r))}for(const[l,a]of Object.entries(s.software??{})){const c=O.PlTemplateV1.swField(o,l);e.createField(c,"Input"),e.setField(c,t(a,Ue,r))}for(const[l,a]of Object.entries(s.assets??{})){const c=O.PlTemplateV1.swField(o,l);e.createField(c,"Input"),e.setField(c,t(a,Ue,r))}for(const[l,a]of Object.entries(s.templates??{})){const c=O.PlTemplateV1.tplField(o,l);e.createField(c,"Input"),e.setField(c,t(a,Zr,r))}if(e.lock(o),!s.hashOverride)return o;const n=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV3Data(s))),i=O.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function we(s,e,t){return b.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function Po(s,e){const t=O.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return ts(s,t);case"pl.tengo-template.v3":return Qr(s,t);default:b.assertNever(r)}}function Ro(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return ts(s,t);case"pl.tengo-template.v3":return Qr(s,t);default:b.assertNever(r)}}const lr={hash(s,e){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV2Data(s).data))}},Me={hash(s,e){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=O.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(O.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},es={hash(s,e){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),lr.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Me.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Me.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV2Data(s).data));for(const[i,l]of Object.entries(s.libs??{})){const a=O.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(l,lr))}for(const[i,l]of Object.entries(s.software??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(l,Me))}for(const[i,l]of Object.entries(s.assets??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(l,Me))}for(const[i,l]of Object.entries(s.templates??{})){const a=O.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(l,es))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV2Data(s))),n=O.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function ts(s,e){const t=new Map,r=(o,n)=>{const i=ee.createHash("sha256");n.hash(o,i);const l=i.digest("hex");if(!t.has(l)){const a=n.render(o,s,r);t.set(l,a)}return t.get(l)};return r(e,es)}const rs={name:"TengoTemplateGet",version:"1"},ss="registry",os="templateURI",ns="template",Co={name:"TengoTemplatePack",version:"1"},Eo={name:"TengoTemplatePackConvert",version:"1"},Oo="templatePack",$o="template";async function Lt(s){switch(s.type){case"from-file":return{type:"explicit",content:await te.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return b.assertNever(s)}}function To(s,e){const t=s.createStruct(rs),r=g.field(t,ss),o=g.field(t,os),n=g.field(t,ns);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function je(s,e){switch(e.type){case"from-registry":return To(s,e);case"explicit":return Po(s,e);case"prepared":return Ro(s,e);default:return b.assertNever(e)}}const Nt={name:"Frontend/FromUrl",version:"1"},Bt={name:"Frontend/FromFolder",version:"1"};function Io(s,e){switch(e.type){case"url":return s.createValue(Nt,JSON.stringify({url:e.url}));case"local":return s.createValue(Bt,JSON.stringify({path:e.path,signature:e.signature}));default:return b.assertNever(e)}}class Fo{constructor(){k(this,"nextMessageId",0);k(this,"worker");k(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:J.resolve(void 0,"worker.js"),t=this.worker=new Ns.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:l}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?l(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Ao={name:"BlockPackCustom",version:"1"},is="template",as="frontend";function ur(s){return s.endsWith("/")?s:`${s}/`}function Do(s){return Buffer.from(s).toString("utf8")}function Je(s){return JSON.parse(Do(s))}class Lo{constructor(e,t,r){k(this,"remoteContentCache",new $t.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await tt.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 nr(e.folder),r=await te.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=await te.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${ur(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Je(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Je(o)}default:return b.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Zt(o,new Fo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,l=!0}finally{var a=er(o,i,l);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await nr(e.folder),r=await te.promises.readFile(t.workflow),o=JSON.parse(await te.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=JSON.parse(await te.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await te.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await rt(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${ur(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),l=Je(i);return{type:"explicit",template:{type:"explicit",content:n},config:l,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Je(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,l]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(l)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return b.assertNever(e)}}}function No(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Ao,JSON.stringify(t));return s.createField(g.field(r,is),"Input",je(s,e.template)),s.createField(g.field(r,as),"Input",Io(s,e.frontend)),s.lock(r),r}function dr(s,e){switch(e.type){case"prepared":return No(s,e);default:return b.assertNever(e.type)}}function Ge(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Bo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Rt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Bo(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)Rt(s,o,t);else for(const[,o]of Object.entries(e))Rt(s,o,t);return;default:b.assertNever(r)}}function jo(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return Rt(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class cs{constructor(e){k(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const l of o){const a=this.nodes.get(l);r(a),a[e].forEach(c=>{n.has(c)||(n.add(c),i.push(c))})}o=i}}}function Ct(s){const e=new Map;let t;for(const{id:r}of ie(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?(o.directUpstream=o.upstream=new Set,o.enrichments=o.enrichmentTargets=new Set):(o.directUpstream=o.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([o.id]),t.enrichments=t.enrichmentTargets=new Set),t=o}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new cs(e)}function Ye(s,e){const t=new Map,r=new cs(t),o=new Set;for(const{id:n}of ie(s)){const i=e(n);if(i===void 0)continue;const l=jo(i.args,o),a=new Set([...l.upstreams,...r.traverseIds("enrichments",...l.upstreamsRequiringEnrichments)]),c=new Set;for(const{id:p}of ie(s)){if(p===n)break;if(a.has(p)){c.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))c.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(l.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:n,missingReferences:l.missingReferences,upstream:c,directUpstream:l.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(n,d),l.upstreams.forEach(p=>t.get(p).directDownstream.add(n)),c.forEach(p=>t.get(p).downstream.add(n)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(n)}),o.add(n)}return r}function Vo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Et(s,e){if(s.size>e.size)return Et(e,s);for(const t of s)if(e.has(t))return!0;return!1}function pr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Vo(n.upstream,i.upstream)||Et(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?Et(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let pt;async function ls(){if(pt===void 0){const s=await Lt(he.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(s.content).digest("hex");pt={spec:s,hash:e}}return pt}function xo(s,e,t){return st(s,e,!0,{pf:t},["result"]).result}function ft(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class fr{constructor(e,t,r,o){k(this,"currentArgsC",ft(()=>this.fields.currentArgs.modCount,()=>b.cachedDeserialize(this.fields.currentArgs.value)));k(this,"prodArgsC",ft(()=>{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)}));k(this,"productionStaleC",ft(()=>{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=o}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),is,"Input")}}const Uo=s=>{throw new Error(`No new block info for ${s}`)};class et{constructor(e,t,r,o,n,i,l,a,c,u,d,p,f){k(this,"globalModCount",0);k(this,"fieldsChanged",!1);k(this,"lastModifiedChanged",!1);k(this,"structureChanged",!1);k(this,"metaChanged",!1);k(this,"renderingStateChanged",!1);k(this,"changedBlockFrontendStates",new Set);k(this,"blocksWithChangedInputs",new Set);k(this,"stagingGraph");k(this,"pendingProductionGraph");k(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=l,this.renderingState=a,this.blocksInLimbo=c,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}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(z.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=Ct(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let o,n;if(t){if(r.fields.prodArgs===void 0)return;o=r.fields.prodArgs,n=r.prodArgs}else o=b.notEmpty(r.fields.currentArgs),n=r.currentArgs;const i=b.notEmpty(r.fields.blockPack);return g.isResourceId(o.ref)&&g.isResourceId(i.ref)?{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n,{argsRid:o.ref,blockPackRid:i.ref})}:{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ye(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ye(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 ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=g.field(this.rid,K(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(g.field(this.rid,K(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const l=this.tx.createValue(g.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",l,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ar(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ar(this.tx,t)}exportCtx(e){return xo(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 o=t.getTemplate(this.tx),n=ir(this.tx,o,{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,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=ir(this.tx,o,{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,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Uo){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=Ct(e),i=pr(r,n);for(const c of i.onlyInA){const{fields:u}=this.getBlockInfo(c);this.deleteBlockFields(c,...Object.keys(u)),this.blockInfos.delete(c),this.blocksInLimbo.delete(c)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(c)&&this.changedBlockFrontendStates.add(c)}for(const c of i.onlyInB){const u=t(c),d=new fr(c,{},A.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(c,d);const p=dr(this.tx,u.blockPack);this.setBlockField(c,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(c,"blockSettings",this.createJsonFieldValue(z.InitialBlockSettings)),this.setBlockFieldObj(c,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(c,u.uiState),this.changedBlockFrontendStates.add(c)),d.check()}for(const c of i.different)this.resetStaging(c);const l=Ye(e,c=>this.getProductionGraphBlockInfo(c,!0)),a=pr(o,l);o.traverse("downstream",[...a.different],c=>{this.resetOrLimboProduction(c.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 o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const l=i.blocks.findIndex(a=>a.id===r);if(!(l<0)){i.blocks.splice(l,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,dr(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,l=>{r.add(l.id)});else for(const l of r){const a=o.nodes.get(l);if(a===void 0)throw new Error(`Can't find block with id: ${l}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const l of ie(this.structure)){if(!r.has(l.id))continue;let a=this.getBlockInfo(l.id).requireProductionRendering||this.blocksInLimbo.has(l.id);if(!a){for(const c of o.nodes.get(l.id).upstream)if(n.has(c)){a=!0;break}}a&&(this.renderProductionFor(l.id),n.add(l.id))}const i=[...n];return o.traverse("downstream",i,l=>{n.has(l.id)||this.resetOrLimboProduction(l.id)}),this.getStagingGraph().traverse("downstream",i,({id:l})=>{i[0]!==l&&this.resetStaging(l)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,l;const t=this.getActualProductionGraph(),r=new Gr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),c=this.getBlockInfo(a).fields;if(!(((i=c.prodOutput)==null?void 0:i.status)==="Ready"&&((l=c.prodCtx)==null?void 0:l.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(l=>{const a=t.get(l);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,bt(t)):this.tx.setKValue(this.rid,bt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,kt):this.tx.setKValue(this.rid,kt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,De,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,ge,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,Le,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,St(e)):this.tx.setKValue(this.rid,St(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r,o){const n=t.getResourceData(r,!0),i=t.getKValueJson(r,zr),l=t.getKValueJson(r,De),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,ge),u=t.getKValueJson(r,Ze),d=t.listKeyValuesString(r),p=await n,f=new Map;for(const h of p.fields){const S=uo(h.name);if(S===void 0)continue;let v=f.get(S.blockId);v===void 0&&(v={id:S.blockId,fields:{}},f.set(S.blockId,v)),v.fields[S.fieldName]=g.isNullResourceId(h.value)?{modCount:0}:{modCount:0,ref:h.value}}const R=[];f.forEach(h=>{const S=h.fields;for(const[v,P]of Object.entries(S)){if(P.ref===void 0)continue;if(!g.isResource(P.ref)||g.isResourceRef(P.ref))throw new Error("unexpected behaviour");const $=v;R.push([h,$,P,t.getResourceData(P.ref,$=="blockPack")])}});const[y,T,L,U,{stagingRefreshTimestamp:D,blocksInLimbo:q},me]=await Promise.all([i,l,a,c,u,d]);if(y!==Xr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${y}`);const j=[];for(const[h,S,v,P]of R){const $=await P;if(v.value=$.data,g.isNotNullResourceId($.error)?v.status="Error":$.resourceReady||g.isNotNullResourceId($.originalResourceId)?v.status="Ready":v.status="NotReady",S==="blockPack"){const E=$.fields.find(N=>N.name===g.Pl.HolderRefField);if(E===void 0)throw new Error("Block pack ref field is missing");j.push([h,t.getResourceData(g.ensureResourceIdNotNull(E.value),!1)])}}for(const[h,S]of j){const v=await S,P=b.cachedDeserialize(b.notEmpty(v.data));h.blockConfig=A.extractConfig(P.config),h.blockPack=P.source}const Q=await ls(),re=Pt(Q.hash),H=p.fields.find(h=>h.name===re);let se;H!==void 0?se=g.ensureResourceIdNotNull(H.value):(se=g.Pl.wrapInHolder(t,je(t,Q.spec)),t.createField(g.field(r,Pt(Q.hash)),"Dynamic",se));const oe={stagingRefreshTimestamp:D},_=new Set(q),W=new Map;for(const h of me){const S=ao(h.key);S!==void 0&&W.set(S,h.value)}const w=new Map;f.forEach(({id:h,fields:S,blockConfig:v,blockPack:P})=>w.set(h,new fr(h,S,b.notEmpty(v),b.notEmpty(P))));const m=new Set;for(const h of ie(U)){if(!w.has(h.id))throw new Error(`Inconsistent project structure: no inputs for ${h.id}`);m.add(h.id)}w.forEach(h=>{if(!m.has(h.id))throw new Error(`Inconsistent project structure: no structure entry for ${h.id}`);h.check()});const C=new et(r,t,o,y,T,L,U,oe,_,w,W,se,e);return C.fixProblemsAndMigrate(),C}}async function Mo(s,e=ro){const t=s.createEphemeral(so);s.lock(t);const r=String(Date.now());s.setKValue(t,zr,JSON.stringify(Xr)),s.setKValue(t,Dt,r),s.setKValue(t,De,r),s.setKValue(t,Le,JSON.stringify(e)),s.setKValue(t,ge,JSON.stringify(eo)),s.setKValue(t,Ze,JSON.stringify(to));const o=await ls();return s.createField(g.field(t,Pt(o.hash)),"Dynamic",g.Pl.wrapInHolder(s,je(s,o.spec))),t}async function _e(s,e,t,r){return ne(s,e,t,void 0,r)}async function ne(s,e,t,r,o){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async n=>{const i=await et.load(s,n,t,r),l=await o(i);return i.wasModified&&(i.save(),await n.commit()),l});{const n=await et.load(s,e,t,r),i=await o(n);return n.save(),i}}function*Jo(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 gr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Go(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:gr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:gr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:b.assertNever(s)}}const _o=g.resourceType("PColumnData/JsonPartitioned","1"),Ko=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ho=g.resourceType("PColumnData/BinaryPartitioned","1"),qo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Wo=g.resourceType("PColumnData/Json","1");function zo(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,Wo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,_o)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ko)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const l of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(l)]);r[a]=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ho)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const l of i)if(l.endsWith(".index")){const a=l.slice(0,l.length-6),c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[c];u===void 0&&(u={},r[c]=u),r[c].index=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else if(l.endsWith(".values")){const a=l.slice(0,l.length-7),c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[c];u===void 0&&(u={},r[c]=u),r[c].values=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${l}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Xo(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Yo(s,e){const t=ee.createHash("sha256");return t.update(x(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function hr(s,e){return x({__isRef:!0,blockId:s,name:e})}function Qo(s,e){return x({resolvePath:s,name:e})}function us(s,e=!0,t=!1,r=""){var l,a,c;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=b.notEmpty((l=d.groups)==null?void 0:l.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=b.notEmpty((a=d.groups)==null?void 0:a.type);let R=n.get(p);switch(R===void 0&&(R={},n.set(p,R)),f){case"spec":R.spec=(c=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:c.getDataAsJson();break;case"data":R.hasData=!0,R.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Zo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=us(s,e,!1,t);Bs(o.locked);const n={};for(const[i,l]of o.results){if(l.spec===void 0)throw new Error(`no spec for key ${i}`);if(l.hasData!==!0||l.data===void 0)throw new Error(`no data for key ${i}`);const a=l.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;n[i]={id:r.length===0?Yo(l.spec,a.value):Qo(r,i),spec:l.spec,data:a.value}}return n}class jt{constructor(e,t){k(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,l,a,c,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(l=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:l.spec;if(o!==void 0||(o=(u=(c=(a=r.staging)==null?void 0:a.results)==null?void 0:c.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,l,a;const r=this.blocks.get(e);if(r===void 0)return;const o=(l=(i=r.prod)==null?void 0:i.results)==null?void 0:l.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return A.mapValueInVOE(n,c=>({id:hr(e,t),spec:o.spec,data:c}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,l,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const c=a.data();c!==void 0?e.push({ref:Ge(i,l),obj:{id:c.ok?hr(i,l):void 0,spec:a.spec,data:c}}):o(`no_data:${i}:${l}`)}};for(const[i,l]of this.blocks){const a=new Set;if(l.prod!==void 0){l.prod.locked||o(`prod_not_locked:${i}`);for(const[c,u]of l.prod.results)a.add(c),n(i,c,u)}if(l.staging!==void 0){l.staging.locked||o(`staging_not_locked:${i}`);for(const[c,u]of l.staging.results)a.has(c)||n(i,c,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const l=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,c]of i.staging.results)c.spec!==void 0&&(e.push({ref:Ge(n,a),obj:c.spec}),l.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,c]of i.prod.results)l.has(a)||c.spec!==void 0&&e.push({ref:Ge(n,a),obj:c.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[l,a]of i.results)o.has(l)||a.spec===void 0||(o.add(l),A.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+l,ref:Ge(r.info.id,l),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=b.notEmpty(o.getKeyValueAsJson(ge)),l=Ct(n).traverseIds("upstream",r),a=new Map;for(const c of ie(n)){if(!l.has(c.id))continue;const u=mr(o.traverse({field:K(c.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:K(c.id,"prodUiCtx"),stableIfNotFound:!0})),d=mr(o.traverse({field:K(c.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:K(c.id,"stagingUiCtx")}));a.set(c.id,{info:c,prod:u,staging:d})}return new jt(e,a)}}function mr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return us(e.value,!1,!0)}function Vt(s,e){return{blockId:e,args:n=>b.notEmpty(n.accessor(s).node().traverse({field:K(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:K(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(St(e)),blockMeta:n=>{const i=n.accessor(s).node(),l=b.notEmpty(i.getKeyValueAsJson(ge)),a=new Map;for(const c of ie(l))a.set(c.id,c);return a}}}function ds(s,e){return{...Vt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>jt.create(t,s,e)}}function*Z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*Z(t);return;case"MakeArray":for(const t of s.template)yield*Z(t);return;case"GetJsonField":case"GetResourceField":yield*Z(s.source),yield*Z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Z(s.source),yield*Z(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*Z(s.source);return;case"IsEmpty":yield*Z(s.arg);return;case"Not":yield*Z(s.operand);return;case"And":case"Or":yield*Z(s.operand1),yield*Z(s.operand2);return;default:b.assertNever(s)}}function en(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function $e(s,e){return s===void 0?void 0:e(s)}function tn(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function rn(s){for(const e of Z(s))if(tn(e))return!0;return!1}function ot(s){return{type:"ReturnResult",result:s}}function I(s){return()=>ot(s)}const sn=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return I(e)},on=s=>{const e=s.source;if(e===void 0)return I(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return I(t)},nn=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?I(void 0):({cCtx:r})=>{var o;return ot((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function ps(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function an(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):()=>({type:"ScheduleSubroutine",subroutine:fs(r.length),args:ps(r,o=>F({...s,[e.itVar]:o},e.mapping))})}}function fs(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return I(t)}}function cn(s,e){return t=>{const r=t.source;if(r===void 0)return I(void 0);const o={};for(const[n,i]of Object.entries(r)){const l={...s,[e.itVar]:i};o[n]=F(l,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ln,args:o})}}const ln=s=>I(s),un=s=>{const e=s.arg;return I(e===void 0?void 0:e.length===0)},dn=s=>{const e=s.operand;return I(e===void 0?void 0:!e)},pn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e&&t)},fn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e||t)},gn=s=>{const e=s.source;return e===void 0?I(void 0):({cCtx:t})=>{var r;return ot((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},hn=s=>{const e=s.source,t=s.field;return I(e===void 0||t===void 0?void 0:e[t])};function mn(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const l of n.listInputFields()){const a=n.traverse(l);if(a===void 0)i[l]=I(void 0);else{const c={...s,[e.itVar]:a.persist()};i[l]=F(c,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:yn,args:i}}}}const yn=s=>I(s),vn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},wn=s=>{const e=s.source;return e===void 0?I(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:V.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Sn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},bn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},kn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Pn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},Rn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Cn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},En=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},On=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},$n=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function F(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>ot(t(r.cCtx)):I(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ms(t,s,e.cfg)});case"Immediate":return I(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:F(s,e.source),field:F(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:an(s,e),args:{source:F(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:cn(s,e),args:{source:F(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:en(e.template,t=>F(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:fs(e.template.length),args:ps(e.template,t=>F(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:F(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:un,args:{arg:F(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:dn,args:{operand:F(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:mn(s,e),args:{source:F(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:F(s,e.source),field:F(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:gn,args:{source:F(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vn,args:{source:F(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:wn,args:{source:F(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Sn,args:{source:F(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:bn,args:{source:F(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:kn,args:{source:F(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Pn(e.format),args:{source:F(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Rn,args:{source:F(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Cn(e.lines),args:{source:F(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:En(e.patternToSearch),args:{source:F(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:On(e.patternToSearch),args:{source:F(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:$n,args:{source:F(s,e.source)}});default:return b.assertNever(e)}}const Tn=["$prod","$staging"];function In(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 gs=Symbol(),hs="return",Fn={op:gs,arg:hs};function An(s){return s.op==gs&&s.arg==hs}function Dn(){return{pendingSubroutines:new Map}}function yr(s,e,t,r){const o=new Gr(t),n=(l,a)=>{if(An(l))return e.result=a,!1;const c=b.notEmpty(e.pendingSubroutines.get(l.op));if(l.arg in c.args)throw new Error("argument already set");return c.args[l.arg]=a,c.argCounter--,c.argCounter===0&&(e.pendingSubroutines.delete(l.op),o.push({destination:c.destination,operation:c.subroutine(c.args)})),!0},i=[];e:for(;o.length>0;){const l=o.shift(),a=l.operation(s);switch(a.type){case"ReturnResult":if(!n(l.destination,a.result))break e;break;case"ScheduleSubroutine":{const c=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:l.destination,operation:a.subroutine({})});else{for(const[p,f]of u)o.push({destination:{op:c,arg:p},operation:f});e.pendingSubroutines.set(c,{argCounter:d,args:{},subroutine:a.subroutine,destination:l.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:l.destination,computable:a.computable});break;default:b.assertNever(a)}}return i}function Ln(s,e,t,r={}){return ms(s,In(e),t,r)}function ms(s,e,t,r={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Tn.indexOf(n)===-1)),cfg:t});return V.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},l=Dn();return{ir:yr(i,l,[{destination:Fn,operation:F(e,t)}],!0),postprocessValue(c){const u=[];for(const R of c)u.push({destination:R.destination,operation:I(R.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[R,y]of l.pendingSubroutines)p.set(R,{...y,args:{...y.args}});const f={result:l.result,pendingSubroutines:p};if(yr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function vr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Nn{constructor(e,t,r,o){k(this,"computablesToResolve",{});k(this,"computableCtx");k(this,"accessors",new Map);k(this,"meta");k(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,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,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return vr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return vr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Zo(n,t,r,o),l={};for(const[a,c]of Object.entries(i))l[a]=A.mapPObjectData(c,u=>this.wrapAccessor(u));return l}registerComputable(e,t){const r=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=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:A.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:A.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 A.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=>A.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(A.mapPTableDef(e,t=>A.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):A.isDataInfo(e)?A.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=ee.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;fe.Scope.withScope(o=>{const n=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),l=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",o.manage(r.newString(n))),l!==void 0&&r.setProp(e,"uiState",o.manage(r.newString(l))),i!==void 0&&r.setProp(e,"activeArgs",o.manage(r.newString(i)));const a=(c,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const R=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(R)}};r.newFunction(c,d).consume(p=>r.setProp(e,c,p)),r.newFunction(c,u).consume(p=>r.setProp(e,c+"__internal__",p))};a("getAccessorHandleByName",c=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(c)),void 0)),a("resolveWithCommon",(c,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(c),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",c=>t.exportObjectViaJson(this.getResourceType(r.getString(c)),void 0)),a("getInputsLocked",c=>t.exportSingleValue(this.getInputsLocked(r.getString(c)),void 0)),a("getOutputsLocked",c=>t.exportSingleValue(this.getOutputsLocked(r.getString(c)),void 0)),a("getIsReadyOrError",c=>t.exportSingleValue(this.getIsReadyOrError(r.getString(c)),void 0)),a("getIsFinal",c=>t.exportSingleValue(this.getIsFinal(r.getString(c)),void 0)),a("getError",c=>t.exportSingleValue(this.getError(r.getString(c)),void 0)),a("listInputFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("listOutputFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("listDynamicFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("getKeyValueBase64",(c,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(c),r.getString(u)),void 0)),a("getKeyValueAsString",(c,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(c),r.getString(u)),void 0)),a("getDataBase64",c=>t.exportSingleValue(this.getDataBase64(r.getString(c)),void 0)),a("getDataAsString",c=>t.exportSingleValue(this.getDataAsString(r.getString(c)),void 0)),a("parsePObjectCollection",(c,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(c),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",c=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(c)),void 0)),a("getBlobContentAsString",c=>t.exportSingleValue(this.getBlobContentAsString(r.getString(c)),void 0)),a("getDownloadedBlobContentHandle",c=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(c)),void 0)),a("getOnDemandBlobContentHandle",c=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(c)),void 0)),a("extractArchiveAndGetURL",(c,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(c),r.getString(u)),void 0)),a("getImportProgress",c=>t.exportSingleValue(this.getImportProgress(r.getString(c)),void 0)),a("getLastLogs",(c,u)=>t.exportSingleValue(this.getLastLogs(r.getString(c),r.getNumber(u)),void 0)),a("getProgressLog",(c,u)=>t.exportSingleValue(this.getProgressLog(r.getString(c),r.getString(u)),void 0)),a("getProgressLogWithInfo",(c,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(c),r.getString(u)),void 0)),a("getLogHandle",c=>t.exportSingleValue(this.getLogHandle(r.getString(c)),void 0)),a("getBlockLabel",c=>t.exportSingleValue(this.getBlockLabel(r.getString(c)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",c=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(c)),void 0)),a("getSpecFromResultPoolByRef",(c,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(c),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(c,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(c),r.getString(u)),void 0)),a("createPFrame",c=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(c)),void 0)),a("createPTable",c=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(c)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0))})}}function Bn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,o){k(this,"callbackRegistry");k(this,"fnJSONStringify");k(this,"fnJSONParse");k(this,"errorRepo",new jn);k(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(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");o!==void 0&&(this.computableHelper=new Nn(this,o.blockCtx,o.mlEnv,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}),fe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw 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,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Bn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){fe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(A.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class jn{constructor(){k(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=ee.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 fe.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 o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new js.PlQuickJSError(e,o)}}function Be(s,e){return $e(s.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=A.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Ke=process.env.MI_LOG_OUTPUT_STATUS;function Vn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),V.Computable.makeRaw(l=>{const a=new fe.Scope;l.addOnDestroy(()=>a.dispose());const c=a.manage(s.quickJs.newRuntime());c.setMemoryLimit(1024*1024*8),c.setMaxStackSize(1024*320);let u;c.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(c.newContext()),p=new Ne(a,d,y=>{u=y},{computableCtx:l,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let R=0;return Ke&&Ke!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(y,{unstableMarker:T,stable:L})=>{for(const[D,q]of Object.entries(y))p.runCallback(D,q);const U=p.importObjectUniversal(f);return R++,Ke&&(Ke!=="unstable-only"||!L)&&console.log(L?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${R})`:`Unstable output ${t.handle}; marker = ${T}; ${U!==void 0?"defined":"undefined"} (#${R})`),U}}},n)}function xn(s,e,t,...r){const o=new fe.Scope;try{const n=o.manage(s.newRuntime());n.setMemoryLimit(1024*1024*8),n.setMaxStackSize(1024*320);let i;n.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const l=o.manage(n.newContext()),a=new Ne(o,l,c=>{i=c});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{o.dispose()}}function Un(s){return A.isConfigLambda(s)?s.isActive===!0:rn(s)}function Te(s,e,t,r,o,n={}){if(A.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Vn(s,e,t,r,o,n)}else return Ln(s.driverKit,e,t,n)}function Mn(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=rr.omitBy((r,o)=>o.startsWith("__"));return rr.isDeepEqual(t(s),t(e))}function Jn(s,e,t){return V.Computable.make(r=>{var R,y,T,L,U,D,q,me;const o=r.accessor(s).node(),n=b.notEmpty(o.getKeyValueAsJson(Dt)),i=b.notEmpty(o.getKeyValueAsJson(De)),l=b.notEmpty(o.getKeyValueAsJson(Le)),a=b.notEmpty(o.getKeyValueAsJson(ge)),c=b.notEmpty(o.getKeyValueAsJson(Ze)),u=new Map;for(const{id:j}of ie(a)){const Q=o.traverse({field:K(j,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),re=Q.getDataAsJson();let H;const se=o.traverse({field:K(j,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(se!==void 0){const oe=se.getDataAsJson(),_=o.getField({field:K(j,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),W=o.getField({field:K(j,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});H={arguments:oe,stale:!Mn(re,oe),outputError:_.error!==void 0||W.error!==void 0||((R=_.value)==null?void 0:R.getError())!==void 0||((y=W.value)==null?void 0:y.getError())!==void 0,outputsError:((T=_.error)==null?void 0:T.getDataAsString())??((U=(L=_.value)==null?void 0:L.getError())==null?void 0:U.getDataAsString()),exportsError:((D=W.error)==null?void 0:D.getDataAsString())??((me=(q=W.value)==null?void 0:q.getError())==null?void 0:me.getDataAsString()),finished:(_.value!==void 0&&_.value.getIsReadyOrError()||_.error!==void 0&&_.error.getIsReadyOrError())&&(W.value!==void 0&&W.value.getIsReadyOrError()||W.error!==void 0&&W.error.getIsReadyOrError())}}u.set(j,{currentArguments:re,prod:H,argsRid:Q.resourceInfo.id})}const d=Ye(a,j=>{const Q=Be(o,j),re=u.get(j),H=re.currentArguments;return{args:H,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>Q.cfg,()=>H,{argsRid:re.argsRid,blockPackRid:Q.bpResourceId})}}),p=new Set(c.blocksInLimbo),f=[...ie(a)].map(({id:j,label:Q,renderingMode:re})=>{var v,P,$,E,N;const H=b.notEmpty(u.get(j)),se=b.notEmpty(d.nodes.get(j));let oe="NotCalculated";H.prod!==void 0&&(p.has(j)?oe="Limbo":oe=H.prod.finished?"Done":"Running");const _=Be(o,j),{sections:W,title:w,inputsValid:m,sdkVersion:C}=$e(_,({bpId:G,cfg:B})=>{const ue=Vt(s,j);return{sections:Te(t,ue,B.sections,B.code,G).wrap({recover:Re=>(t.logger.error("Error in block model sections"),t.logger.error(Re),[])}),title:$e(B.title,Re=>Te(t,ue,Re,B.code,G).wrap({recover:Is=>(t.logger.error("Error in block model title"),t.logger.error(Is),"Invalid title")})),inputsValid:Te(t,ue,B.inputsValid,B.code,G).wrap({recover:Re=>(t.logger.error("Error in block model argsValid"),t.logger.error(Re),!1)}),sdkVersion:B.sdkVersion}})||{},h=o.traverse({field:K(j,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),S=$e(_,({info:G})=>t.blockUpdateWatcher.get({currentSpec:G.source,settings:h}));return{projectResourceId:g.resourceIdToString(s.rid),id:j,label:w??Q,title:w??Q,renderingMode:re,stale:((v=H.prod)==null?void 0:v.stale)!==!1||oe==="Limbo",missingReference:se.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",j)],downstreams:[...d.traverseIdsExcludingRoots("downstream",j)],calculationStatus:oe,outputErrors:((P=H.prod)==null?void 0:P.outputError)===!0,outputsError:($=H.prod)==null?void 0:$.outputsError,exportsError:(E=H.prod)==null?void 0:E.exportsError,settings:h,sections:W,inputsValid:m,updateInfo:{},currentBlockPack:(N=_==null?void 0:_.info)==null?void 0:N.source,updates:S,sdkVersion:C,navigationState:e.getState(j)}});return{meta:l,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(kt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const l=i.stale||i.upstreams.findIndex(p=>n.has(p))!==-1,a=(l||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>o.has(p))===-1,c={...i,canRun:a,stale:l,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete c.updates,c})}}}).withStableType()}function Gn(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,Nt)){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,Bt)){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 _n(s,e){if(s!==void 0)return V.Computable.make(t=>Gn(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 Kn(s,e,t){return V.Computable.make(r=>{var l;const o=r.accessor(s).node(),n=Be(o,e),i=(l=o.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:as,assertFieldType:"Input"}))==null?void 0:l.persist();return{path:_n(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ys(s,e,t){if(t===void 0)return V.Computable.make(i=>ys(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Vt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(bt(e)),args:b.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?b.deepFreeze(JSON.parse(n)):void 0}}function Hn(s,e,t){return V.Computable.make(r=>{const o=r.accessor(s).node(),n=ds(s,e);return $e(Be(o,e),({cfg:i,bpId:l})=>{const a={};for(const[c,u]of Object.entries(i.outputs)){const d=Te(t,n,u,i.code,l);a[c]=V.Computable.wrapError(d,1)}return a})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function qn(s,e){return V.Computable.make(t=>{const r=t.accessor(s).node(),o=b.notEmpty(r.getKeyValueAsJson(ge)),n=[];for(const{id:i}of ie(o)){const l=Be(r,i);if(l===void 0)continue;const a=Object.entries(l.cfg.outputs).map(([,u])=>u).filter(u=>Un(u)).map(u=>u);if(a.length===0)continue;const c=ds(r.persist(),i);for(const u of a)n.push(V.Computable.wrapError(Te(e,c,u,l.cfg.code,l.bpId)))}return n})}class Wn{constructor(){k(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 V.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...A.DefaultNavigationState},change:new V.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return V.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function wr(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 nt{constructor(e,t,r){k(this,"rid");k(this,"overview");k(this,"navigationStates",new Wn);k(this,"blockComputables",new Map);k(this,"blockFrontends",new Map);k(this,"activeConfigs");k(this,"refreshLoopResult");k(this,"abortController",new AbortController);k(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Jn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=qn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await _e(this.env.projectHelper,this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await _r.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}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,o=void 0,n=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),l=await this.env.bpPreparer.getBlockConfigContainer(t),a=A.extractConfig(l);return await ne(this.env.projectHelper,this.env.pl,this.rid,o,c=>c.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:x(a.initialArgs),uiState:x(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=A.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ne(this.env.projectHelper,this.env.pl,this.rid,o,l=>l.migrateBlockPack(e,n,r?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ne(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 ne(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(l=>{const a=n.blocks.find(c=>c.id===l);if(a===void 0)throw new Error(`Can't find block: ${l}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:x(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ne(this.env.projectHelper,this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ne(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 o=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,K(e,"blockPack")))).value),n=g.ensureResourceIdNotNull((await r.getField(g.field(o,g.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),l=A.extractConfig(b.cachedDeserialize(b.notEmpty(i.data)).config);await ne(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:x(l.initialArgs)}]),a.setUiState(e,x(l.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Hn(this.projectTree.entry(),e,this.env),n={fullState:V.Computable.make(i=>({argsAndUiState:ys(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const l=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,c=l&&Xn(l)&&i.outputs!==void 0?Qn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:c,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Kn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await _e(e.projectHelper,e.pl,t,o=>{});const r=await Qe.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:zn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,l)=>{var a,c;return(((a=l.data)==null?void 0:a.byteLength)??0)-(((c=i.data)==null?void 0:c.byteLength)??0)});const n=Qe.treeDumpStats(o);await Ae.writeFile(`${g.resourceIdToString(t)}.json`,wr(o)),await Ae.writeFile(`${g.resourceIdToString(t)}.stats.json`,wr(n))}return new nt(e,t,r)}}function zn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Xn(s){return!Yn(s,"1.26.0")}function Yn(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 Qn(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:r.moreErrors}}return e}const xt={logger:new b.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ut(s){return{blobDownloadPath:J.join(s,"download"),downloadBlobToURLPath:J.join(s,"downloadToURL"),pframesSpillPath:J.join(s,"pframes")}}const vs={...xt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function ws(s){return{...Ut(s),frontendDownloadPath:J.join(s,"frontend")}}function Zn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ot={exports:{}};const ei="2.0.0",Ss=256,ti=Number.MAX_SAFE_INTEGER||9007199254740991,ri=16,si=Ss-6,oi=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var it={MAX_LENGTH:Ss,MAX_SAFE_COMPONENT_LENGTH:ri,MAX_SAFE_BUILD_LENGTH:si,MAX_SAFE_INTEGER:ti,RELEASE_TYPES:oi,SEMVER_SPEC_VERSION:ei,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const ni=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var at=ni;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=it,n=at;e=s.exports={};const i=e.re=[],l=e.safeRe=[],a=e.src=[],c=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[p,r]],R=T=>{for(const[L,U]of f)T=T.split(`${L}*`).join(`${L}{0,${U}}`).split(`${L}+`).join(`${L}{1,${U}}`);return T},y=(T,L,U)=>{const D=R(L),q=d++;n(T,q,L),u[T]=q,a[q]=L,c[q]=D,i[q]=new RegExp(L,U?"g":void 0),l[q]=new RegExp(D,U?"g":void 0)};y("NUMERICIDENTIFIER","0|[1-9]\\d*"),y("NUMERICIDENTIFIERLOOSE","\\d+"),y("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),y("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),y("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),y("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),y("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),y("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),y("BUILDIDENTIFIER",`${p}+`),y("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),y("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),y("FULL",`^${a[u.FULLPLAIN]}$`),y("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),y("LOOSE",`^${a[u.LOOSEPLAIN]}$`),y("GTLT","((?:<|>)?=?)"),y("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),y("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),y("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),y("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),y("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),y("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),y("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),y("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),y("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),y("COERCERTL",a[u.COERCE],!0),y("COERCERTLFULL",a[u.COERCEFULL],!0),y("LONETILDE","(?:~>?)"),y("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",y("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),y("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),y("LONECARET","(?:\\^)"),y("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",y("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),y("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),y("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),y("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),y("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",y("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),y("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),y("STAR","(<|>)?=?\\s*\\*"),y("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),y("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Ot,Ot.exports);var Ve=Ot.exports;const ii=Object.freeze({loose:!0}),ai=Object.freeze({}),ci=s=>s?typeof s!="object"?ii:s:ai;var Mt=ci;const Sr=/^[0-9]+$/,bs=(s,e)=>{const t=Sr.test(s),r=Sr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},li=(s,e)=>bs(e,s);var ks={compareIdentifiers:bs,rcompareIdentifiers:li};const He=at,{MAX_LENGTH:br,MAX_SAFE_INTEGER:qe}=it,{safeRe:kr,safeSrc:Pr,t:We}=Ve,ui=Mt,{compareIdentifiers:ye}=ks;let di=class le{constructor(e,t){if(t=ui(t),e instanceof le){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>br)throw new TypeError(`version is longer than ${br} characters`);He("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?kr[We.LOOSE]:kr[We.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qe||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<qe)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(He("SemVer.compare",this.version,this.options,e),!(e instanceof le)){if(typeof e=="string"&&e===this.version)return 0;e=new le(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof le||(e=new le(e,this.options)),ye(this.major,e.major)||ye(this.minor,e.minor)||ye(this.patch,e.patch)}comparePre(e){if(e instanceof le||(e=new le(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(He("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ye(r,o)}while(++t)}compareBuild(e){e instanceof le||(e=new le(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(He("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ye(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?Pr[We.PRERELEASELOOSE]:Pr[We.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ye(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Y=di;const Rr=Y,pi=(s,e,t=!1)=>{if(s instanceof Rr)return s;try{return new Rr(s,e)}catch(r){if(!t)return null;throw r}};var Se=pi;const fi=Se,gi=(s,e)=>{const t=fi(s,e);return t?t.version:null};var hi=gi;const mi=Se,yi=(s,e)=>{const t=mi(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var vi=yi;const Cr=Y,wi=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new Cr(s instanceof Cr?s.version:s,t).inc(e,r,o).version}catch{return null}};var Si=wi;const Er=Se,bi=(s,e)=>{const t=Er(s,null,!0),r=Er(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,l=n?r:t,a=!!i.prerelease.length;if(!!l.prerelease.length&&!a){if(!l.patch&&!l.minor)return"major";if(l.compareMain(i)===0)return l.minor&&!l.patch?"minor":"patch"}const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var ki=bi;const Pi=Y,Ri=(s,e)=>new Pi(s,e).major;var Ci=Ri;const Ei=Y,Oi=(s,e)=>new Ei(s,e).minor;var $i=Oi;const Ti=Y,Ii=(s,e)=>new Ti(s,e).patch;var Fi=Ii;const Ai=Se,Di=(s,e)=>{const t=Ai(s,e);return t&&t.prerelease.length?t.prerelease:null};var Li=Di;const Or=Y,Ni=(s,e,t)=>new Or(s,t).compare(new Or(e,t));var ae=Ni;const Bi=ae,ji=(s,e,t)=>Bi(e,s,t);var Vi=ji;const xi=ae,Ui=(s,e)=>xi(s,e,!0);var Mi=Ui;const $r=Y,Ji=(s,e,t)=>{const r=new $r(s,t),o=new $r(e,t);return r.compare(o)||r.compareBuild(o)};var Jt=Ji;const Gi=Jt,_i=(s,e)=>s.sort((t,r)=>Gi(t,r,e));var Ki=_i;const Hi=Jt,qi=(s,e)=>s.sort((t,r)=>Hi(r,t,e));var Wi=qi;const zi=ae,Xi=(s,e,t)=>zi(s,e,t)>0;var ct=Xi;const Yi=ae,Qi=(s,e,t)=>Yi(s,e,t)<0;var Gt=Qi;const Zi=ae,ea=(s,e,t)=>Zi(s,e,t)===0;var Ps=ea;const ta=ae,ra=(s,e,t)=>ta(s,e,t)!==0;var Rs=ra;const sa=ae,oa=(s,e,t)=>sa(s,e,t)>=0;var _t=oa;const na=ae,ia=(s,e,t)=>na(s,e,t)<=0;var Kt=ia;const aa=Ps,ca=Rs,la=ct,ua=_t,da=Gt,pa=Kt,fa=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return aa(s,t,r);case"!=":return ca(s,t,r);case">":return la(s,t,r);case">=":return ua(s,t,r);case"<":return da(s,t,r);case"<=":return pa(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var Cs=fa;const ga=Y,ha=Se,{safeRe:ze,t:Xe}=Ve,ma=(s,e)=>{if(s instanceof ga)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?ze[Xe.COERCEFULL]:ze[Xe.COERCE]);else{const a=e.includePrerelease?ze[Xe.COERCERTLFULL]:ze[Xe.COERCERTL];let c;for(;(c=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),a.lastIndex=c.index+c[1].length+c[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",l=e.includePrerelease&&t[6]?`+${t[6]}`:"";return ha(`${r}.${o}.${n}${i}${l}`,e)};var ya=ma;class va{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var wa=va,gt,Tr;function ce(){if(Tr)return gt;Tr=1;const s=/\s+/g;class e{constructor(m,C){if(C=o(C),m instanceof e)return m.loose===!!C.loose&&m.includePrerelease===!!C.includePrerelease?m:new e(m.raw,C);if(m instanceof n)return this.raw=m.value,this.set=[[m]],this.formatted=void 0,this;if(this.options=C,this.loose=!!C.loose,this.includePrerelease=!!C.includePrerelease,this.raw=m.trim().replace(s," "),this.set=this.raw.split("||").map(h=>this.parseRange(h.trim())).filter(h=>h.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const h=this.set[0];if(this.set=this.set.filter(S=>!y(S[0])),this.set.length===0)this.set=[h];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&T(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let m=0;m<this.set.length;m++){m>0&&(this.formatted+="||");const C=this.set[m];for(let h=0;h<C.length;h++)h>0&&(this.formatted+=" "),this.formatted+=C[h].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(m){const h=((this.options.includePrerelease&&f)|(this.options.loose&&R))+":"+m,S=r.get(h);if(S)return S;const v=this.options.loose,P=v?a[c.HYPHENRANGELOOSE]:a[c.HYPHENRANGE];m=m.replace(P,_(this.options.includePrerelease)),i("hyphen replace",m),m=m.replace(a[c.COMPARATORTRIM],u),i("comparator trim",m),m=m.replace(a[c.TILDETRIM],d),i("tilde trim",m),m=m.replace(a[c.CARETTRIM],p),i("caret trim",m);let $=m.split(" ").map(B=>U(B,this.options)).join(" ").split(/\s+/).map(B=>oe(B,this.options));v&&($=$.filter(B=>(i("loose invalid filter",B,this.options),!!B.match(a[c.COMPARATORLOOSE])))),i("range list",$);const E=new Map,N=$.map(B=>new n(B,this.options));for(const B of N){if(y(B))return[B];E.set(B.value,B)}E.size>1&&E.has("")&&E.delete("");const G=[...E.values()];return r.set(h,G),G}intersects(m,C){if(!(m instanceof e))throw new TypeError("a Range is required");return this.set.some(h=>L(h,C)&&m.set.some(S=>L(S,C)&&h.every(v=>S.every(P=>v.intersects(P,C)))))}test(m){if(!m)return!1;if(typeof m=="string")try{m=new l(m,this.options)}catch{return!1}for(let C=0;C<this.set.length;C++)if(W(this.set[C],m,this.options))return!0;return!1}}gt=e;const t=wa,r=new t,o=Mt,n=lt(),i=at,l=Y,{safeRe:a,t:c,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Ve,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:R}=it,y=w=>w.value==="<0.0.0-0",T=w=>w.value==="",L=(w,m)=>{let C=!0;const h=w.slice();let S=h.pop();for(;C&&h.length;)C=h.every(v=>S.intersects(v,m)),S=h.pop();return C},U=(w,m)=>(i("comp",w,m),w=j(w,m),i("caret",w),w=q(w,m),i("tildes",w),w=re(w,m),i("xrange",w),w=se(w,m),i("stars",w),w),D=w=>!w||w.toLowerCase()==="x"||w==="*",q=(w,m)=>w.trim().split(/\s+/).map(C=>me(C,m)).join(" "),me=(w,m)=>{const C=m.loose?a[c.TILDELOOSE]:a[c.TILDE];return w.replace(C,(h,S,v,P,$)=>{i("tilde",w,h,S,v,P,$);let E;return D(S)?E="":D(v)?E=`>=${S}.0.0 <${+S+1}.0.0-0`:D(P)?E=`>=${S}.${v}.0 <${S}.${+v+1}.0-0`:$?(i("replaceTilde pr",$),E=`>=${S}.${v}.${P}-${$} <${S}.${+v+1}.0-0`):E=`>=${S}.${v}.${P} <${S}.${+v+1}.0-0`,i("tilde return",E),E})},j=(w,m)=>w.trim().split(/\s+/).map(C=>Q(C,m)).join(" "),Q=(w,m)=>{i("caret",w,m);const C=m.loose?a[c.CARETLOOSE]:a[c.CARET],h=m.includePrerelease?"-0":"";return w.replace(C,(S,v,P,$,E)=>{i("caret",w,S,v,P,$,E);let N;return D(v)?N="":D(P)?N=`>=${v}.0.0${h} <${+v+1}.0.0-0`:D($)?v==="0"?N=`>=${v}.${P}.0${h} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.0${h} <${+v+1}.0.0-0`:E?(i("replaceCaret pr",E),v==="0"?P==="0"?N=`>=${v}.${P}.${$}-${E} <${v}.${P}.${+$+1}-0`:N=`>=${v}.${P}.${$}-${E} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.${$}-${E} <${+v+1}.0.0-0`):(i("no pr"),v==="0"?P==="0"?N=`>=${v}.${P}.${$}${h} <${v}.${P}.${+$+1}-0`:N=`>=${v}.${P}.${$}${h} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.${$} <${+v+1}.0.0-0`),i("caret return",N),N})},re=(w,m)=>(i("replaceXRanges",w,m),w.split(/\s+/).map(C=>H(C,m)).join(" ")),H=(w,m)=>{w=w.trim();const C=m.loose?a[c.XRANGELOOSE]:a[c.XRANGE];return w.replace(C,(h,S,v,P,$,E)=>{i("xRange",w,h,S,v,P,$,E);const N=D(v),G=N||D(P),B=G||D($),ue=B;return S==="="&&ue&&(S=""),E=m.includePrerelease?"-0":"",N?S===">"||S==="<"?h="<0.0.0-0":h="*":S&&ue?(G&&(P=0),$=0,S===">"?(S=">=",G?(v=+v+1,P=0,$=0):(P=+P+1,$=0)):S==="<="&&(S="<",G?v=+v+1:P=+P+1),S==="<"&&(E="-0"),h=`${S+v}.${P}.${$}${E}`):G?h=`>=${v}.0.0${E} <${+v+1}.0.0-0`:B&&(h=`>=${v}.${P}.0${E} <${v}.${+P+1}.0-0`),i("xRange return",h),h})},se=(w,m)=>(i("replaceStars",w,m),w.trim().replace(a[c.STAR],"")),oe=(w,m)=>(i("replaceGTE0",w,m),w.trim().replace(a[m.includePrerelease?c.GTE0PRE:c.GTE0],"")),_=w=>(m,C,h,S,v,P,$,E,N,G,B,ue)=>(D(h)?C="":D(S)?C=`>=${h}.0.0${w?"-0":""}`:D(v)?C=`>=${h}.${S}.0${w?"-0":""}`:P?C=`>=${C}`:C=`>=${C}${w?"-0":""}`,D(N)?E="":D(G)?E=`<${+N+1}.0.0-0`:D(B)?E=`<${N}.${+G+1}.0-0`:ue?E=`<=${N}.${G}.${B}-${ue}`:w?E=`<${N}.${G}.${+B+1}-0`:E=`<=${E}`,`${C} ${E}`.trim()),W=(w,m,C)=>{for(let h=0;h<w.length;h++)if(!w[h].test(m))return!1;if(m.prerelease.length&&!C.includePrerelease){for(let h=0;h<w.length;h++)if(i(w[h].semver),w[h].semver!==n.ANY&&w[h].semver.prerelease.length>0){const S=w[h].semver;if(S.major===m.major&&S.minor===m.minor&&S.patch===m.patch)return!0}return!1}return!0};return gt}var ht,Ir;function lt(){if(Ir)return ht;Ir=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[o.COMPARATORLOOSE]:r[o.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 l(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 l(u,this.options)}catch{return!1}return n(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 a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(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("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}ht=e;const t=Mt,{safeRe:r,t:o}=Ve,n=Cs,i=at,l=Y,a=ce();return ht}const Sa=ce(),ba=(s,e,t)=>{try{e=new Sa(e,t)}catch{return!1}return e.test(s)};var ut=ba;const ka=ce(),Pa=(s,e)=>new ka(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Ra=Pa;const Ca=Y,Ea=ce(),Oa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Ea(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Ca(r,t))}),r};var $a=Oa;const Ta=Y,Ia=ce(),Fa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Ia(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Ta(r,t))}),r};var Aa=Fa;const mt=Y,Da=ce(),Fr=ct,La=(s,e)=>{s=new Da(s,e);let t=new mt("0.0.0");if(s.test(t)||(t=new mt("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const l=new mt(i.semver.version);switch(i.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!n||Fr(l,n))&&(n=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Fr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var Na=La;const Ba=ce(),ja=(s,e)=>{try{return new Ba(s,e).range||"*"}catch{return null}};var Va=ja;const xa=Y,Es=lt(),{ANY:Ua}=Es,Ma=ce(),Ja=ut,Ar=ct,Dr=Gt,Ga=Kt,_a=_t,Ka=(s,e,t,r)=>{s=new xa(s,r),e=new Ma(e,r);let o,n,i,l,a;switch(t){case">":o=Ar,n=Ga,i=Dr,l=">",a=">=";break;case"<":o=Dr,n=_a,i=Ar,l="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ja(s,e,r))return!1;for(let c=0;c<e.set.length;++c){const u=e.set[c];let d=null,p=null;if(u.forEach(f=>{f.semver===Ua&&(f=new Es(">=0.0.0")),d=d||f,p=p||f,o(f.semver,d.semver,r)?d=f:i(f.semver,p.semver,r)&&(p=f)}),d.operator===l||d.operator===a||(!p.operator||p.operator===l)&&n(s,p.semver))return!1;if(p.operator===a&&i(s,p.semver))return!1}return!0};var Ht=Ka;const Ha=Ht,qa=(s,e,t)=>Ha(s,e,">",t);var Wa=qa;const za=Ht,Xa=(s,e,t)=>za(s,e,"<",t);var Ya=Xa;const Lr=ce(),Qa=(s,e,t)=>(s=new Lr(s,t),e=new Lr(e,t),s.intersects(e,t));var Za=Qa;const ec=ut,tc=ae;var rc=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>tc(u,d,t));for(const u of i)ec(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const l=[];for(const[u,d]of r)u===d?l.push(u):!d&&u===i[0]?l.push("*"):d?u===i[0]?l.push(`<=${d}`):l.push(`${u} - ${d}`):l.push(`>=${u}`);const a=l.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return a.length<c.length?a:e};const Nr=ce(),qt=lt(),{ANY:yt}=qt,Ce=ut,Wt=ae,sc=(s,e,t={})=>{if(s===e)return!0;s=new Nr(s,t),e=new Nr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=nc(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},oc=[new qt(">=0.0.0-0")],Br=[new qt(">=0.0.0")],nc=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===yt){if(e.length===1&&e[0].semver===yt)return!0;t.includePrerelease?s=oc:s=Br}if(e.length===1&&e[0].semver===yt){if(t.includePrerelease)return!0;e=Br}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=jr(o,f,t):f.operator==="<"||f.operator==="<="?n=Vr(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Wt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!Ce(f,String(o),t)||n&&!Ce(f,String(n),t))return null;for(const R of e)if(!Ce(f,String(R),t))return!1;return!0}let l,a,c,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,p=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",c=c||f.operator==="<"||f.operator==="<=",o){if(p&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===p.major&&f.semver.minor===p.minor&&f.semver.patch===p.patch&&(p=!1),f.operator===">"||f.operator===">="){if(l=jr(o,f,t),l===f&&l!==o)return!1}else if(o.operator===">="&&!Ce(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(a=Vr(n,f,t),a===f&&a!==n)return!1}else if(n.operator==="<="&&!Ce(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&c&&!n&&i!==0||n&&u&&!o&&i!==0||p||d)},jr=(s,e,t)=>{if(!s)return e;const r=Wt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Vr=(s,e,t)=>{if(!s)return e;const r=Wt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var ic=sc;const vt=Ve,xr=it,ac=Y,Ur=ks,cc=Se,lc=hi,uc=vi,dc=Si,pc=ki,fc=Ci,gc=$i,hc=Fi,mc=Li,yc=ae,vc=Vi,wc=Mi,Sc=Jt,bc=Ki,kc=Wi,Pc=ct,Rc=Gt,Cc=Ps,Ec=Rs,Oc=_t,$c=Kt,Tc=Cs,Ic=ya,Fc=lt(),Ac=ce(),Dc=ut,Lc=Ra,Nc=$a,Bc=Aa,jc=Na,Vc=Va,xc=Ht,Uc=Wa,Mc=Ya,Jc=Za,Gc=rc,_c=ic;var Kc={parse:cc,valid:lc,clean:uc,inc:dc,diff:pc,major:fc,minor:gc,patch:hc,prerelease:mc,compare:yc,rcompare:vc,compareLoose:wc,compareBuild:Sc,sort:bc,rsort:kc,gt:Pc,lt:Rc,eq:Cc,neq:Ec,gte:Oc,lte:$c,cmp:Tc,coerce:Ic,Comparator:Fc,Range:Ac,satisfies:Dc,toComparators:Lc,maxSatisfying:Nc,minSatisfying:Bc,minVersion:jc,validRange:Vc,outside:xc,gtr:Uc,ltr:Mc,intersects:Jc,simplifyRange:Gc,subset:_c,SemVer:ac,re:vt.re,src:vt.src,tokens:vt.t,SEMVER_SPEC_VERSION:xr.SEMVER_SPEC_VERSION,RELEASE_TYPES:xr.RELEASE_TYPES,compareIdentifiers:Ur.compareIdentifiers,rcompareIdentifiers:Ur.rcompareIdentifiers};const Hc=Zn(Kc),qc={minDelay:1500},Wc="__no_updates__";class zc extends V.PollComputablePool{constructor(t,r,o={}){super({...o,...qc},r);k(this,"http");k(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${x(t)}`;default:return Wc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await At(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await X.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const l=await rt(i);return l===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:l},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:l}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let c=this.preferredUpdateChannel;if(c===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,z.StableChannel))c=z.StableChannel;else{if(await a.getLatestOverview(n.id,z.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${z.blockPackIdToString(n.id)}`),{suggestions:[]};c=z.AnyChannel}else c=n.channel;const u=await a.getUpdateSuggestions(n.id,c);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(R=>R.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=u.find(R=>R.type==="patch"))==null?void 0:o.update;break}const p=u.map(({type:R,update:y})=>({type:R,update:{...n,id:{...n.id,version:y}}}));if(d===void 0)return{suggestions:p};if(l!==void 0&&Hc.lte(d,l))return{suggestions:p};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(R){this.logger.warn(R)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return x(t)===x(r)}}class Mr{constructor(){k(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Ee;function de(){return Ee||(Ee={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Ee.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Ee)}function Ie(s){return String(s.id)}const Xc=["Int","Long","Float","Double","String","Bytes"];function wt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Oe=(s,e)=>typeof e=="bigint"?e.toString():e;class Yc{constructor(e,t,r,o,n){k(this,"pFrame");k(this,"blobIdToResource",new Map);k(this,"blobHandleComputables",new Map);k(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});k(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});k(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r,this.blobContentCache=o;const i=(a,c)=>this.logger[a](c);for(const a of n)for(const c of Jo(a.data))this.blobIdToResource.set(Ie(c),c);const l=[...new Map(n.map(a=>({...a,data:Go(a.data,Ie)})).map(a=>[x(a),a])).values()];try{const a=new xs.PFrame(this.spillPath,de().logPFrameRequests?i:void 0);a.setDataSource(this);for(const c of l)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(l)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Qc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class zt{constructor(e,t,r){k(this,"pFrames");k(this,"pTables");k(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const o=new $t.LRUCache({maxSize:1e9,fetchMethod:async i=>await Hr.readFile(i),sizeCalculation:i=>i.length}),n=new b.ConcurrencyLimitingExecutor(4);this.concurrencyLimiter=n,this.pFrames=new class extends Mr{constructor(i,l,a){super(),this.blobDriver=i,this.logger=l,this.spillPath=a}createNewResource(i){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Oe)}`),new Yc(this.blobDriver,this.logger,this.spillPath,o,i)}calculateParamsKey(i){return el(i)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Mr{constructor(i){super(),this.pFrames=i}createNewResource(i){const l=i.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Oe)}`);const a=n.run(async()=>{const c=await this.pFrames.getByKey(l).pFrame.createTable({src:Fe(i.def.src),filters:wt(i.def.filters)},i.signal);let u=c;if(i.def.sorting.length>0)try{u=await c.sort(i.def.sorting,i.signal)}finally{c.dispose()}return u});return new Qc(a)}calculateParamsKey(i){return Zc(i)}}(this.pFrames)}static async init(e,t,r){const o=Js.resolve(r);return await b.emptyDir(o),new zt(e,t,o)}createPFrame(e,t){const r=e.filter(n=>Xc.find(i=>i===n.spec.valueType)).map(n=>A.mapPObjectData(n,i=>Qe.isPlTreeNodeAccessor(i)?zo(i):A.isDataInfo(i)?A.mapDataInfo(i,l=>l.resourceInfo):Xo(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(A.extractAllColumns(e.src),t),n=A.mapPTableDef(e,l=>l.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(A.mapPTableDef(e,l=>l.spec),Oe)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[x(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(l=>l.length===0))).map(n=>n.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){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>{const o=await this.pFrames.getByKey(e).pFrame.createTable({src:Fe(t.src),filters:wt(t.filters)},r);let n=o;if(t.sorting.length>0)try{n=await o.sort(t.sorting,r)}finally{o.dispose()}try{const i=n.getSpec(),l=await n.getData([...i.keys()],void 0,r);return i.map((a,c)=>({spec:a,data:l[c]}))}finally{n.dispose()}})}async getUniqueValues(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:wt(t.filters)},r))}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r,o){const n=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await n.getData(t,r,o))}}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 Zc(s){const e=ee.createHash("sha256");return e.update(x(s)),e.digest().toString("hex")}function el(s){const e=[...s].map(r=>A.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([l,a])=>({key:l,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([l,a])=>({key:l,value:Ie(a)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([l,a])=>({key:l,value:[Ie(a.index),Ie(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((l,a)=>l.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function Os(s,e,t){const r={...xt,...Ut(e),...t},o=new b.HmacSha256Signer(r.localSecret),n=M.createDownloadClient(r.logger,s,r.localProjections),i=M.createLogsClient(s,r.logger),l=M.createUploadBlobClient(s,r.logger),a=M.createUploadProgressClient(s,r.logger),c=new M.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new M.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new M.UploadDriver(r.logger,o,l,a,r.uploadDriverOps),p=new M.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new M.LogsDriver(r.logger,p,c),R=await M.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),y=await zt.init(c,r.logger,r.pframesSpillPath);return{blobDriver:c,blobToURLDriver:u,logDriver:f,lsDriver:R,signer:o,uploadDriver:d,pFrameDriver:y}}class tl{constructor(e){k(this,"enrichmentTargetsCache",new $t.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 xn(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const o={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(o);const n=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(n,{context:o}).value}}class Xt{constructor(e,t,r,o,n,i,l,a){k(this,"pl");k(this,"projectList");k(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=l,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Mo(o,e);return o.createField(g.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await g.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ne(this.env.projectHelper,this.pl,e,r,o=>{o.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 nt.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()}static async init(e,t,r){const o={...vs,...ws(t),...r};o.defaultTreeOptions.logStat=de().logTreeStats,o.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async T=>{const L=g.field(T.clientRoot,po);T.createField(L,"Dynamic");const U=await T.getField(L);if(g.isNullResourceId(U.value)){const D=T.createEphemeral(Yr);return T.lock(D),T.setField(L,D),await T.commit(),await D.globalId}else return U.value}),i=o.logger,l=await Os(e,t,o),a=new tt.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),c=new Wr(a),u=new Lo(c,l.signer,a),d=new M.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),p=await fe.getQuickJS(),f={pl:e,signer:l.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:l,blockUpdateWatcher:new zc(c,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:p,projectHelper:new tl(p)},R=new V.WatchableValue([]),y=await go(e,n,R,f);return new Xt(f,l,l.signer,n,R,y.tree,c,y.computable)}}async function rl(s,e){return await be(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function sl(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function ol(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function nl(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function il(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function al(s,e){return await be(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await xe(s.autoUpdateCdnUrl,s,e))}async function be(s,e,t){const r=Date.now(),o=[];for(;Jr(r)<s;){const n=Date.now();let i;try{i={ok:!0,value:await t()}}catch(c){i={ok:!1,error:c}}const l=Jr(n);o.push({elapsedMs:l,response:i});const a=1e3/e-l;a>0&&await _r.setTimeout(a)}return o}async function xe(s,e,t){const{body:r,statusCode:o}=await tt.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Jr(s){return Date.now()-s}function ve(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:o}=cl(s),n=`
1
+ "use strict";var As=Object.defineProperty;var Yt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Qt=s=>{throw TypeError(s)};var Ds=(s,e,t)=>e in s?As(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var k=(s,e,t)=>Ds(s,typeof e!="symbol"?e+"":e,t);var Zt=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Qt("Object expected");var r;t&&(r=e[Yt("asyncDispose")]),r===void 0&&(r=e[Yt("dispose")]),typeof r!="function"&&Qt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},er=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,l,a,c){return c=Error(a),c.name="SuppressedError",c.error=i,c.suppressed=l,c},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var l=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(l).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("@platforma-sdk/model"),z=require("@milaboratories/pl-model-middle-layer"),tr=require("@milaboratories/pl-deployments"),tt=require("undici"),X=require("@platforma-sdk/block-tools"),te=require("node:fs"),J=require("node:path"),Ls=require("yaml"),b=require("@milaboratories/ts-helpers"),Ae=require("node:fs/promises"),Ns=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),Qe=require("@milaboratories/pl-tree"),V=require("@milaboratories/computable"),ee=require("node:crypto"),O=require("@milaboratories/pl-model-backend"),$t=require("lru-cache"),Bs=require("node:worker_threads"),Gr=require("denque"),he=require("@platforma-sdk/workflow-tengo"),x=require("canonicalize"),js=require("node:assert"),fe=require("quickjs-emscripten"),Vs=require("@milaboratories/pl-errors"),xs=require("remeda"),_r=require("node:timers/promises"),M=require("@milaboratories/pl-drivers"),Kr=require("@milaboratories/pframes-rs-node"),Us=require("node:diagnostics_channel"),Ms=require("node:stream/consumers"),Hr=require("node:os");function Tt(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 Js=Tt(J),qr=Tt(Ae),rr=Tt(xs);async function sr(s){try{return await qr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Gs=[X.RegistryV1.PlPackageYamlConfigFile],_s=[X.RegistryV1.PlPackageJsonConfigFile],It=["backend","dist","tengo","tpl","main.plj.gz"],Ft=["config","dist","config.json"],Wr=["frontend","dist"],or="block-model/dist/config.json",Ks="block-ui/package.json",Hs=[It,Ft,Gs,_s,Wr];async function qs(s){return await sr(J.join(s,...Ft))!==void 0||await sr(J.join(s,...It))!==void 0}function dt(s,e){const t=Ns.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function nr(s,e){if(J.isAbsolute(s)||(s=J.resolve(s)),await qs(s))return{workflow:J.join(s,...It),config:J.join(s,...Ft),ui:J.join(s,...Wr)};{const t=dt(s,or),r=dt(s,or),o=dt(s,Ks);return{workflow:t,config:r,ui:J.resolve(o,"..","dist")}}}async function Ws(s){try{return await te.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function zs(s){try{return await te.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function At(s){let e=0n;for(const t of Hs){const r=J.join(s,...t),o=await zs(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function rt(s){const e=await te.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await te.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Xs{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await tt.request(`${r.url}/${X.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const l of i){const{organization:a,package:c,latestMeta:u,latestVersion:d}=l,p={organization:a,name:c,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[z.AnyChannel]:f,[z.StableChannel]:f},allVersions:l.allVersions.map(R=>({version:R,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await te.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=J.join(r.path,o.name),i=await Ws(J.join(n,X.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const l=X.RegistryV1.PlPackageConfigData.parse(Ls.parse(i)),a=await At(n),c={organization:l.organization,name:l.package,version:"DEV"},u={id:c,meta:{title:l.meta.title??"No title",description:l.meta.description??"No Description",organization:{name:l.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:a}};t.push({registryId:e.id,id:c,latestByChannel:{[z.AnyChannel]:u,[z.StableChannel]:u},allVersions:[]})}else{let l=n,a=await X.tryLoadPackDescription(l);if(a===void 0){for(const c of["block","meta"])if(l=J.join(n,c),a=await X.tryLoadPackDescription(l),a!==void 0)break}if(a!==void 0){const c=await rt(a),u={id:a.id,meta:await X.BlockPackMetaEmbedAbsoluteBytes.parseAsync(a.meta),spec:{type:"dev-v2",folder:l,mtime:c}};t.push({registryId:e.id,id:a.id,latestByChannel:{[z.AnyChannel]:u,[z.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 o=(i=this.registries.find(l=>l.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class zr{constructor(e){k(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new X.RegistryV2Reader(X.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ys={type:"remote-v2",url:"https://blocks.pl-open.science/"},Qs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Zs={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"},Xr="SchemaVersion",Yr="1",Dt="ProjectCreated",De="ProjectLastModified",Le="ProjectMeta",ge="ProjectStructure",Ze="BlockRenderingState",oo="BlockFrontendState/",no=/^BlockFrontendState\/(?<blockid>.*)$/;function St(s){return`${oo}${s}`}const io="BlockArgsAuthor/";function bt(s){return`${io}${s}`}const kt="ProjectStructureAuthor";function ao(s){const e=s.match(no);if(e!==null)return e.groups.blockid}const co="__serviceTemplate_";function Pt(s){return`${co}${s}`}function K(s,e){return`${s}-${e}`}const lo=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function uo(s){const e=s.match(lo);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const po="projects",Qr={name:"Projects",version:"1"},fo=s=>g.resourceTypesEqual(s.type,Qr)?s.fields:[];async function go(s,e,t,r){const o=await Qe.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:fo},r.logger);return{computable:V.Computable.make(i=>{const l=i.accessor(o.entry()).node(),a=t.getValue(i);if(l===void 0)return;const c=[];for(const u of l.listDynamicFields()){const d=l.traverse(u);if(d===void 0)continue;const p=b.notEmpty(d.getKeyValueAsJson(Le)),f=b.notEmpty(d.getKeyValueAsJson(Dt)),R=b.notEmpty(d.getKeyValueAsJson(De));c.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(R),opened:a.indexOf(d.id)>=0,meta:p})}return c.sort(u=>-u.lastModified.valueOf()),c}).withStableType(),tree:o}}const ho={name:"EphRenderTemplate",version:"1"},mo={name:"RenderTemplate",version:"1"};function st(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(ho):s.createStruct(mo),i=g.field(n,"template"),l=g.field(n,"inputs");return s.createField(i,"Input",e),s.createField(l,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(n),g.Pl.futureRecord(s,n,o,"Output","outputs/")}const yo={name:"BContextEnd",version:"1"},vo={name:"BContext",version:"1"},wo="id",So="parent/",bo=["context","result"];function ir(s,e,t){return st(s,e,!0,t,bo)}function ko(s){const e=s.createEphemeral(yo);return s.lock(e),e}function ar(s,e){if(e.length===0)return ko(s);if(e.length===1)return e[0];const t=s.createEphemeral(vo);s.createField(g.field(t,wo),"Input",g.Pl.createPlString(s,ee.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${So}${r}`),"Input",e[r]);return s.lock(t),t}function Zr(s,e){const t=new Map,r=(o,n,i)=>{const l=ee.createHash("sha256");n.updateCacheKey(o,l,i);const a=l.digest("hex");if(!t.has(a)){const c=n.render(o,s,r,i);t.set(a,c)}return t.get(a)};return r(e.template,es,e.hashToSource)}const cr={updateCacheKey(s,e,t){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(we(s.name,t,s.sourceHash))},render(s,e,t,r){const o=O.PlTemplateSoftwareV1.fromV3Data(s,we(s.name,r,s.sourceHash)),n=e.createStruct(O.PlTemplateSoftwareV1.type,o.data);return e.setKValue(n,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(n),n}},es={updateCacheKey(s,e,t){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(we(s.name,t,s.sourceHash));const r=o=>(o.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),o);for(const[o,n]of r(Object.entries(s.libs??{})))e.update("lib:"+o),cr.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.software??{})))e.update("soft:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.assets??{})))e.update("asset:"+o),Ue.updateCacheKey(n,e,t);for(const[o,n]of r(Object.entries(s.templates??{})))e.update("tpl:"+o),this.updateCacheKey(n,e,t)},render(s,e,t,r){const o=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV3Data(s,we(s.name,r,s.sourceHash)).data));for(const[l,a]of Object.entries(s.libs??{})){const c=O.PlTemplateV1.libField(o,l);e.createField(c,"Input"),e.setField(c,t(a,cr,r))}for(const[l,a]of Object.entries(s.software??{})){const c=O.PlTemplateV1.swField(o,l);e.createField(c,"Input"),e.setField(c,t(a,Ue,r))}for(const[l,a]of Object.entries(s.assets??{})){const c=O.PlTemplateV1.swField(o,l);e.createField(c,"Input"),e.setField(c,t(a,Ue,r))}for(const[l,a]of Object.entries(s.templates??{})){const c=O.PlTemplateV1.tplField(o,l);e.createField(c,"Input"),e.setField(c,t(a,es,r))}if(e.lock(o),!s.hashOverride)return o;const n=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV3Data(s))),i=O.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,o),e.lock(n),n}};function we(s,e,t){return b.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function Po(s,e){const t=O.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return rs(s,t);case"pl.tengo-template.v3":return Zr(s,t);default:b.assertNever(r)}}function Ro(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return rs(s,t);case"pl.tengo-template.v3":return Zr(s,t);default:b.assertNever(r)}}const lr={hash(s,e){e.update(O.PlTemplateLibV1.type.name).update(O.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(O.PlTemplateLibV1.type,JSON.stringify(O.PlTemplateLibV1.fromV2Data(s).data))}},Me={hash(s,e){e.update(O.PlTemplateSoftwareV1.type.name).update(O.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=O.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(O.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,O.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},ts={hash(s,e){e.update(O.PlTemplateV1.type.name).update(O.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),lr.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Me.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Me.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(O.PlTemplateV1.type,JSON.stringify(O.PlTemplateV1.fromV2Data(s).data));for(const[i,l]of Object.entries(s.libs??{})){const a=O.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(l,lr))}for(const[i,l]of Object.entries(s.software??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(l,Me))}for(const[i,l]of Object.entries(s.assets??{})){const a=O.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(l,Me))}for(const[i,l]of Object.entries(s.templates??{})){const a=O.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(l,ts))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(O.PlTemplateOverrideV1.type,JSON.stringify(O.PlTemplateOverrideV1.fromV2Data(s))),n=O.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(o),o}};function rs(s,e){const t=new Map,r=(o,n)=>{const i=ee.createHash("sha256");n.hash(o,i);const l=i.digest("hex");if(!t.has(l)){const a=n.render(o,s,r);t.set(l,a)}return t.get(l)};return r(e,ts)}const ss={name:"TengoTemplateGet",version:"1"},os="registry",ns="templateURI",is="template",Co={name:"TengoTemplatePack",version:"1"},Eo={name:"TengoTemplatePackConvert",version:"1"},Oo="templatePack",$o="template";async function Lt(s){switch(s.type){case"from-file":return{type:"explicit",content:await te.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return b.assertNever(s)}}function To(s,e){const t=s.createStruct(ss),r=g.field(t,os),o=g.field(t,ns),n=g.field(t,is);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function je(s,e){switch(e.type){case"from-registry":return To(s,e);case"explicit":return Po(s,e);case"prepared":return Ro(s,e);default:return b.assertNever(e)}}const Nt={name:"Frontend/FromUrl",version:"1"},Bt={name:"Frontend/FromFolder",version:"1"};function Io(s,e){switch(e.type){case"url":return s.createValue(Nt,JSON.stringify({url:e.url}));case"local":return s.createValue(Bt,JSON.stringify({path:e.path,signature:e.signature}));default:return b.assertNever(e)}}class Fo{constructor(){k(this,"nextMessageId",0);k(this,"worker");k(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:J.resolve(void 0,"worker.js"),t=this.worker=new Bs.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:n})=>{const{resolve:i,reject:l}=this.pendingRequests.get(r);this.pendingRequests.delete(r),n?l(new Error(n)):i(o)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,o)=>{const n=++this.nextMessageId;this.pendingRequests.set(n,{resolve:r,reject:o}),this.worker.postMessage({id:n,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Ao={name:"BlockPackCustom",version:"1"},as="template",cs="frontend";function ur(s){return s.endsWith("/")?s:`${s}/`}function Do(s){return Buffer.from(s).toString("utf8")}function Je(s){return JSON.parse(Do(s))}class Lo{constructor(e,t,r){k(this,"remoteContentCache",new $t.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await tt.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 nr(e.folder),r=await te.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=await te.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${ur(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Je(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=await this.remoteContentCache.forceFetch(r.model.url);return Je(o)}default:return b.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Zt(o,new Fo,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(n){var i=n,l=!0}finally{var a=er(o,i,l);a&&await a}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await nr(e.folder),r=await te.promises.readFile(t.workflow),o=JSON.parse(await te.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await X.loadPackDescription(e.folder),r=JSON.parse(await te.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await te.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await rt(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=`${ur(e.registryUrl)}${X.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,o=await this.remoteContentCache.forceFetch(r),n=new Uint8Array(o),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),l=Je(i);return{type:"explicit",template:{type:"explicit",content:n},config:l,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Je(await this.remoteContentCache.forceFetch(r.model.url)),n=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,l]=await Promise.all([o(),n()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(l)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return b.assertNever(e)}}}function No(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Ao,JSON.stringify(t));return s.createField(g.field(r,as),"Input",je(s,e.template)),s.createField(g.field(r,cs),"Input",Io(s,e.frontend)),s.lock(r),r}function dr(s,e){switch(e.type){case"prepared":return No(s,e);default:return b.assertNever(e.type)}}function Ge(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Bo(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Rt(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Bo(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)Rt(s,o,t);else for(const[,o]of Object.entries(e))Rt(s,o,t);return;default:b.assertNever(r)}}function jo(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return Rt(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class ls{constructor(e){k(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const l of o){const a=this.nodes.get(l);r(a),a[e].forEach(c=>{n.has(c)||(n.add(c),i.push(c))})}o=i}}}function Ct(s){const e=new Map;let t;for(const{id:r}of ie(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?(o.directUpstream=o.upstream=new Set,o.enrichments=o.enrichmentTargets=new Set):(o.directUpstream=o.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([o.id]),t.enrichments=t.enrichmentTargets=new Set),t=o}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new ls(e)}function Ye(s,e){const t=new Map,r=new ls(t),o=new Set;for(const{id:n}of ie(s)){const i=e(n);if(i===void 0)continue;const l=jo(i.args,o),a=new Set([...l.upstreams,...r.traverseIds("enrichments",...l.upstreamsRequiringEnrichments)]),c=new Set;for(const{id:p}of ie(s)){if(p===n)break;if(a.has(p)){c.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))c.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(l.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:n,missingReferences:l.missingReferences,upstream:c,directUpstream:l.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(n,d),l.upstreams.forEach(p=>t.get(p).directDownstream.add(n)),c.forEach(p=>t.get(p).downstream.add(n)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(n)}),o.add(n)}return r}function Vo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Et(s,e){if(s.size>e.size)return Et(e,s);for(const t of s)if(e.has(t))return!0;return!1}function pr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!Vo(n.upstream,i.upstream)||Et(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?Et(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let pt;async function us(){if(pt===void 0){const s=await Lt(he.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ee.createHash("sha256").update(s.content).digest("hex");pt={spec:s,hash:e}}return pt}function xo(s,e,t){return st(s,e,!0,{pf:t},["result"]).result}function ft(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class fr{constructor(e,t,r,o){k(this,"currentArgsC",ft(()=>this.fields.currentArgs.modCount,()=>b.cachedDeserialize(this.fields.currentArgs.value)));k(this,"prodArgsC",ft(()=>{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)}));k(this,"productionStaleC",ft(()=>{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=o}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),as,"Input")}}const Uo=s=>{throw new Error(`No new block info for ${s}`)};class et{constructor(e,t,r,o,n,i,l,a,c,u,d,p,f){k(this,"globalModCount",0);k(this,"fieldsChanged",!1);k(this,"lastModifiedChanged",!1);k(this,"structureChanged",!1);k(this,"metaChanged",!1);k(this,"renderingStateChanged",!1);k(this,"changedBlockFrontendStates",new Set);k(this,"blocksWithChangedInputs",new Set);k(this,"stagingGraph");k(this,"pendingProductionGraph");k(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=l,this.renderingState=a,this.blocksInLimbo=c,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=p,this.projectHelper=f}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(z.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=Ct(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let o,n;if(t){if(r.fields.prodArgs===void 0)return;o=r.fields.prodArgs,n=r.prodArgs}else o=b.notEmpty(r.fields.currentArgs),n=r.currentArgs;const i=b.notEmpty(r.fields.blockPack);return g.isResourceId(o.ref)&&g.isResourceId(i.ref)?{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n,{argsRid:o.ref,blockPackRid:i.ref})}:{args:n,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>n)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ye(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ye(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 ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=g.field(this.rid,K(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(g.field(this.rid,K(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const l=this.tx.createValue(g.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",l,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var n;const o=this.getBlockInfo(r);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ar(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var n,i;const o=this.getBlockInfo(r);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),ar(this.tx,t)}exportCtx(e){return xo(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 o=t.getTemplate(this.tx),n=ir(this.tx,o,{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,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=ir(this.tx,o,{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,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Uo){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=Ct(e),i=pr(r,n);for(const c of i.onlyInA){const{fields:u}=this.getBlockInfo(c);this.deleteBlockFields(c,...Object.keys(u)),this.blockInfos.delete(c),this.blocksInLimbo.delete(c)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(c)&&this.changedBlockFrontendStates.add(c)}for(const c of i.onlyInB){const u=t(c),d=new fr(c,{},A.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(c,d);const p=dr(this.tx,u.blockPack);this.setBlockField(c,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(c,"blockSettings",this.createJsonFieldValue(z.InitialBlockSettings)),this.setBlockFieldObj(c,"currentArgs",this.createJsonFieldValueByContent(u.args)),u.uiState&&(this.blockFrontendStates.set(c,u.uiState),this.changedBlockFrontendStates.add(c)),d.check()}for(const c of i.different)this.resetStaging(c);const l=Ye(e,c=>this.getProductionGraphBlockInfo(c,!0)),a=pr(o,l);o.traverse("downstream",[...a.different],c=>{this.resetOrLimboProduction(c.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 o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const l=i.blocks.findIndex(a=>a.id===r);if(!(l<0)){i.blocks.splice(l,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,dr(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r.args}]),this.setUiState(e,r.uiState)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,l=>{r.add(l.id)});else for(const l of r){const a=o.nodes.get(l);if(a===void 0)throw new Error(`Can't find block with id: ${l}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const l of ie(this.structure)){if(!r.has(l.id))continue;let a=this.getBlockInfo(l.id).requireProductionRendering||this.blocksInLimbo.has(l.id);if(!a){for(const c of o.nodes.get(l.id).upstream)if(n.has(c)){a=!0;break}}a&&(this.renderProductionFor(l.id),n.add(l.id))}const i=[...n];return o.traverse("downstream",i,l=>{n.has(l.id)||this.resetOrLimboProduction(l.id)}),this.getStagingGraph().traverse("downstream",i,({id:l})=>{i[0]!==l&&this.resetStaging(l)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,l;const t=this.getActualProductionGraph(),r=new Gr(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),c=this.getBlockInfo(a).fields;if(!(((i=c.prodOutput)==null?void 0:i.status)==="Ready"&&((l=c.prodCtx)==null?void 0:l.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(l=>{const a=t.get(l);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,bt(t)):this.tx.setKValue(this.rid,bt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,kt):this.tx.setKValue(this.rid,kt,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,De,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,ge,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,Le,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,St(e)):this.tx.setKValue(this.rid,St(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r,o){const n=t.getResourceData(r,!0),i=t.getKValueJson(r,Xr),l=t.getKValueJson(r,De),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,ge),u=t.getKValueJson(r,Ze),d=t.listKeyValuesString(r),p=await n,f=new Map;for(const h of p.fields){const S=uo(h.name);if(S===void 0)continue;let v=f.get(S.blockId);v===void 0&&(v={id:S.blockId,fields:{}},f.set(S.blockId,v)),v.fields[S.fieldName]=g.isNullResourceId(h.value)?{modCount:0}:{modCount:0,ref:h.value}}const R=[];f.forEach(h=>{const S=h.fields;for(const[v,P]of Object.entries(S)){if(P.ref===void 0)continue;if(!g.isResource(P.ref)||g.isResourceRef(P.ref))throw new Error("unexpected behaviour");const $=v;R.push([h,$,P,t.getResourceData(P.ref,$=="blockPack")])}});const[y,T,L,U,{stagingRefreshTimestamp:D,blocksInLimbo:q},me]=await Promise.all([i,l,a,c,u,d]);if(y!==Yr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${y}`);const j=[];for(const[h,S,v,P]of R){const $=await P;if(v.value=$.data,g.isNotNullResourceId($.error)?v.status="Error":$.resourceReady||g.isNotNullResourceId($.originalResourceId)?v.status="Ready":v.status="NotReady",S==="blockPack"){const E=$.fields.find(N=>N.name===g.Pl.HolderRefField);if(E===void 0)throw new Error("Block pack ref field is missing");j.push([h,t.getResourceData(g.ensureResourceIdNotNull(E.value),!1)])}}for(const[h,S]of j){const v=await S,P=b.cachedDeserialize(b.notEmpty(v.data));h.blockConfig=A.extractConfig(P.config),h.blockPack=P.source}const Q=await us(),re=Pt(Q.hash),H=p.fields.find(h=>h.name===re);let se;H!==void 0?se=g.ensureResourceIdNotNull(H.value):(se=g.Pl.wrapInHolder(t,je(t,Q.spec)),t.createField(g.field(r,Pt(Q.hash)),"Dynamic",se));const oe={stagingRefreshTimestamp:D},_=new Set(q),W=new Map;for(const h of me){const S=ao(h.key);S!==void 0&&W.set(S,h.value)}const w=new Map;f.forEach(({id:h,fields:S,blockConfig:v,blockPack:P})=>w.set(h,new fr(h,S,b.notEmpty(v),b.notEmpty(P))));const m=new Set;for(const h of ie(U)){if(!w.has(h.id))throw new Error(`Inconsistent project structure: no inputs for ${h.id}`);m.add(h.id)}w.forEach(h=>{if(!m.has(h.id))throw new Error(`Inconsistent project structure: no structure entry for ${h.id}`);h.check()});const C=new et(r,t,o,y,T,L,U,oe,_,w,W,se,e);return C.fixProblemsAndMigrate(),C}}async function Mo(s,e=ro){const t=s.createEphemeral(so);s.lock(t);const r=String(Date.now());s.setKValue(t,Xr,JSON.stringify(Yr)),s.setKValue(t,Dt,r),s.setKValue(t,De,r),s.setKValue(t,Le,JSON.stringify(e)),s.setKValue(t,ge,JSON.stringify(eo)),s.setKValue(t,Ze,JSON.stringify(to));const o=await us();return s.createField(g.field(t,Pt(o.hash)),"Dynamic",g.Pl.wrapInHolder(s,je(s,o.spec))),t}async function _e(s,e,t,r){return ne(s,e,t,void 0,r)}async function ne(s,e,t,r,o){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async n=>{const i=await et.load(s,n,t,r),l=await o(i);return i.wasModified&&(i.save(),await n.commit()),l});{const n=await et.load(s,e,t,r),i=await o(n);return n.save(),i}}function*Jo(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 gr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Go(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:gr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:gr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:b.assertNever(s)}}const _o=g.resourceType("PColumnData/JsonPartitioned","1"),Ko=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ho=g.resourceType("PColumnData/BinaryPartitioned","1"),qo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Wo=g.resourceType("PColumnData/Json","1");function zo(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,Wo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(s.resourceType,_o)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ko)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const l of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(l)]);r[a]=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Ho)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,qo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const l of i)if(l.endsWith(".index")){const a=l.slice(0,l.length-6),c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[c];u===void 0&&(u={},r[c]=u),r[c].index=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else if(l.endsWith(".values")){const a=l.slice(0,l.length-7),c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[c];u===void 0&&(u={},r[c]=u),r[c].values=n.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${l}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Xo(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function Yo(s,e){const t=ee.createHash("sha256");return t.update(x(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function hr(s,e){return x({__isRef:!0,blockId:s,name:e})}function Qo(s,e){return x({resolvePath:s,name:e})}function ds(s,e=!0,t=!1,r=""){var l,a,c;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=b.notEmpty((l=d.groups)==null?void 0:l.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=b.notEmpty((a=d.groups)==null?void 0:a.type);let R=n.get(p);switch(R===void 0&&(R={},n.set(p,R)),f){case"spec":R.spec=(c=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:c.getDataAsJson();break;case"data":R.hasData=!0,R.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Zo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=ds(s,e,!1,t);js(o.locked);const n={};for(const[i,l]of o.results){if(l.spec===void 0)throw new Error(`no spec for key ${i}`);if(l.hasData!==!0||l.data===void 0)throw new Error(`no data for key ${i}`);const a=l.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw a.error;n[i]={id:r.length===0?Yo(l.spec,a.value):Qo(r,i),spec:l.spec,data:a.value}}return n}class jt{constructor(e,t){k(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,l,a,c,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(l=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:l.spec;if(o!==void 0||(o=(u=(c=(a=r.staging)==null?void 0:a.results)==null?void 0:c.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,l,a;const r=this.blocks.get(e);if(r===void 0)return;const o=(l=(i=r.prod)==null?void 0:i.results)==null?void 0:l.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return A.mapValueInVOE(n,c=>({id:hr(e,t),spec:o.spec,data:c}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,l,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const c=a.data();c!==void 0?e.push({ref:Ge(i,l),obj:{id:c.ok?hr(i,l):void 0,spec:a.spec,data:c}}):o(`no_data:${i}:${l}`)}};for(const[i,l]of this.blocks){const a=new Set;if(l.prod!==void 0){l.prod.locked||o(`prod_not_locked:${i}`);for(const[c,u]of l.prod.results)a.add(c),n(i,c,u)}if(l.staging!==void 0){l.staging.locked||o(`staging_not_locked:${i}`);for(const[c,u]of l.staging.results)a.has(c)||n(i,c,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const l=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,c]of i.staging.results)c.spec!==void 0&&(e.push({ref:Ge(n,a),obj:c.spec}),l.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,c]of i.prod.results)l.has(a)||c.spec!==void 0&&e.push({ref:Ge(n,a),obj:c.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[l,a]of i.results)o.has(l)||a.spec===void 0||(o.add(l),A.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+l,ref:Ge(r.info.id,l),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=b.notEmpty(o.getKeyValueAsJson(ge)),l=Ct(n).traverseIds("upstream",r),a=new Map;for(const c of ie(n)){if(!l.has(c.id))continue;const u=mr(o.traverse({field:K(c.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:K(c.id,"prodUiCtx"),stableIfNotFound:!0})),d=mr(o.traverse({field:K(c.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:K(c.id,"stagingUiCtx")}));a.set(c.id,{info:c,prod:u,staging:d})}return new jt(e,a)}}function mr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return ds(e.value,!1,!0)}function Vt(s,e){return{blockId:e,args:n=>b.notEmpty(n.accessor(s).node().traverse({field:K(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:K(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(St(e)),blockMeta:n=>{const i=n.accessor(s).node(),l=b.notEmpty(i.getKeyValueAsJson(ge)),a=new Map;for(const c of ie(l))a.set(c.id,c);return a}}}function ps(s,e){return{...Vt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:K(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>jt.create(t,s,e)}}function*Z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*Z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*Z(t);return;case"MakeArray":for(const t of s.template)yield*Z(t);return;case"GetJsonField":case"GetResourceField":yield*Z(s.source),yield*Z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*Z(s.source),yield*Z(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*Z(s.source);return;case"IsEmpty":yield*Z(s.arg);return;case"Not":yield*Z(s.operand);return;case"And":case"Or":yield*Z(s.operand1),yield*Z(s.operand2);return;default:b.assertNever(s)}}function en(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function $e(s,e){return s===void 0?void 0:e(s)}function tn(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function rn(s){for(const e of Z(s))if(tn(e))return!0;return!1}function ot(s){return{type:"ReturnResult",result:s}}function I(s){return()=>ot(s)}const sn=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return I(e)},on=s=>{const e=s.source;if(e===void 0)return I(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return I(t)},nn=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?I(void 0):({cCtx:r})=>{var o;return ot((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function fs(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function an(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):()=>({type:"ScheduleSubroutine",subroutine:gs(r.length),args:fs(r,o=>F({...s,[e.itVar]:o},e.mapping))})}}function gs(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return I(t)}}function cn(s,e){return t=>{const r=t.source;if(r===void 0)return I(void 0);const o={};for(const[n,i]of Object.entries(r)){const l={...s,[e.itVar]:i};o[n]=F(l,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ln,args:o})}}const ln=s=>I(s),un=s=>{const e=s.arg;return I(e===void 0?void 0:e.length===0)},dn=s=>{const e=s.operand;return I(e===void 0?void 0:!e)},pn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e&&t)},fn=s=>{const e=s.operand1,t=s.operand2;return I(e===void 0||t===void 0?void 0:e||t)},gn=s=>{const e=s.source;return e===void 0?I(void 0):({cCtx:t})=>{var r;return ot((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},hn=s=>{const e=s.source,t=s.field;return I(e===void 0||t===void 0?void 0:e[t])};function mn(s,e){return t=>{const r=t.source;return r===void 0?I(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const l of n.listInputFields()){const a=n.traverse(l);if(a===void 0)i[l]=I(void 0);else{const c={...s,[e.itVar]:a.persist()};i[l]=F(c,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:yn,args:i}}}}const yn=s=>I(s),vn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},wn=s=>{const e=s.source;return e===void 0?I(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:V.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Sn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:V.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},bn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},kn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Pn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},Rn=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Cn=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},En=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},On=s=>e=>{const t=e.source;return t===void 0?I(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},$n=s=>{const e=s.source;return e===void 0?I(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function F(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>ot(t(r.cCtx)):I(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:ys(t,s,e.cfg)});case"Immediate":return I(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:hn,args:{source:F(s,e.source),field:F(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:an(s,e),args:{source:F(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:cn(s,e),args:{source:F(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:en(e.template,t=>F(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:gs(e.template.length),args:fs(e.template,t=>F(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:F(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:un,args:{arg:F(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:dn,args:{operand:F(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:pn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:fn,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:mn(s,e),args:{source:F(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:nn,args:{source:F(s,e.source),field:F(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:gn,args:{source:F(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:vn,args:{source:F(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:wn,args:{source:F(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Sn,args:{source:F(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:bn,args:{source:F(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:kn,args:{source:F(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Pn(e.format),args:{source:F(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Rn,args:{source:F(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Cn(e.lines),args:{source:F(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:En(e.patternToSearch),args:{source:F(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:On(e.patternToSearch),args:{source:F(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:$n,args:{source:F(s,e.source)}});default:return b.assertNever(e)}}const Tn=["$prod","$staging"];function In(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 hs=Symbol(),ms="return",Fn={op:hs,arg:ms};function An(s){return s.op==hs&&s.arg==ms}function Dn(){return{pendingSubroutines:new Map}}function yr(s,e,t,r){const o=new Gr(t),n=(l,a)=>{if(An(l))return e.result=a,!1;const c=b.notEmpty(e.pendingSubroutines.get(l.op));if(l.arg in c.args)throw new Error("argument already set");return c.args[l.arg]=a,c.argCounter--,c.argCounter===0&&(e.pendingSubroutines.delete(l.op),o.push({destination:c.destination,operation:c.subroutine(c.args)})),!0},i=[];e:for(;o.length>0;){const l=o.shift(),a=l.operation(s);switch(a.type){case"ReturnResult":if(!n(l.destination,a.result))break e;break;case"ScheduleSubroutine":{const c=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:l.destination,operation:a.subroutine({})});else{for(const[p,f]of u)o.push({destination:{op:c,arg:p},operation:f});e.pendingSubroutines.set(c,{argCounter:d,args:{},subroutine:a.subroutine,destination:l.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:l.destination,computable:a.computable});break;default:b.assertNever(a)}}return i}function Ln(s,e,t,r={}){return ys(s,In(e),t,r)}function ys(s,e,t,r={}){const o=`${e.blockId}#`+x({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Tn.indexOf(n)===-1)),cfg:t});return V.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},l=Dn();return{ir:yr(i,l,[{destination:Fn,operation:F(e,t)}],!0),postprocessValue(c){const u=[];for(const R of c)u.push({destination:R.destination,operation:I(R.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[R,y]of l.pendingSubroutines)p.set(R,{...y,args:{...y.args}});const f={result:l.result,pendingSubroutines:p};if(yr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:o})}function vr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Nn{constructor(e,t,r,o){k(this,"computablesToResolve",{});k(this,"computableCtx");k(this,"accessors",new Map);k(this,"meta");k(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,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,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return vr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return vr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Zo(n,t,r,o),l={};for(const[a,c]of Object.entries(i))l[a]=A.mapPObjectData(c,u=>this.wrapAccessor(u));return l}registerComputable(e,t){const r=`${e}_${ee.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",V.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=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:A.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:A.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 A.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=>A.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(A.mapPTableDef(e,t=>A.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):A.isDataInfo(e)?A.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=ee.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;fe.Scope.withScope(o=>{const n=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),l=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",o.manage(r.newString(n))),l!==void 0&&r.setProp(e,"uiState",o.manage(r.newString(l))),i!==void 0&&r.setProp(e,"activeArgs",o.manage(r.newString(i)));const a=(c,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const R=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(R)}};r.newFunction(c,d).consume(p=>r.setProp(e,c,p)),r.newFunction(c,u).consume(p=>r.setProp(e,c+"__internal__",p))};a("getAccessorHandleByName",c=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(c)),void 0)),a("resolveWithCommon",(c,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(c),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),a("getResourceType",c=>t.exportObjectViaJson(this.getResourceType(r.getString(c)),void 0)),a("getInputsLocked",c=>t.exportSingleValue(this.getInputsLocked(r.getString(c)),void 0)),a("getOutputsLocked",c=>t.exportSingleValue(this.getOutputsLocked(r.getString(c)),void 0)),a("getIsReadyOrError",c=>t.exportSingleValue(this.getIsReadyOrError(r.getString(c)),void 0)),a("getIsFinal",c=>t.exportSingleValue(this.getIsFinal(r.getString(c)),void 0)),a("getError",c=>t.exportSingleValue(this.getError(r.getString(c)),void 0)),a("listInputFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("listOutputFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("listDynamicFields",c=>t.exportObjectViaJson(this.listInputFields(r.getString(c)),void 0)),a("getKeyValueBase64",(c,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(c),r.getString(u)),void 0)),a("getKeyValueAsString",(c,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(c),r.getString(u)),void 0)),a("getDataBase64",c=>t.exportSingleValue(this.getDataBase64(r.getString(c)),void 0)),a("getDataAsString",c=>t.exportSingleValue(this.getDataAsString(r.getString(c)),void 0)),a("parsePObjectCollection",(c,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(c),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),a("getBlobContentAsBase64",c=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(c)),void 0)),a("getBlobContentAsString",c=>t.exportSingleValue(this.getBlobContentAsString(r.getString(c)),void 0)),a("getDownloadedBlobContentHandle",c=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(c)),void 0)),a("getOnDemandBlobContentHandle",c=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(c)),void 0)),a("extractArchiveAndGetURL",(c,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(c),r.getString(u)),void 0)),a("getImportProgress",c=>t.exportSingleValue(this.getImportProgress(r.getString(c)),void 0)),a("getLastLogs",(c,u)=>t.exportSingleValue(this.getLastLogs(r.getString(c),r.getNumber(u)),void 0)),a("getProgressLog",(c,u)=>t.exportSingleValue(this.getProgressLog(r.getString(c),r.getString(u)),void 0)),a("getProgressLogWithInfo",(c,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(c),r.getString(u)),void 0)),a("getLogHandle",c=>t.exportSingleValue(this.getLogHandle(r.getString(c)),void 0)),a("getBlockLabel",c=>t.exportSingleValue(this.getBlockLabel(r.getString(c)),void 0)),a("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),a("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),a("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),a("calculateOptions",c=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(c)),void 0)),a("getSpecFromResultPoolByRef",(c,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(c),r.getString(u)),void 0)),a("getDataFromResultPoolByRef",(c,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(c),r.getString(u)),void 0)),a("createPFrame",c=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(c)),void 0)),a("createPTable",c=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(c)),void 0)),a("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0))})}}function Bn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,o){k(this,"callbackRegistry");k(this,"fnJSONStringify");k(this,"fnJSONParse");k(this,"errorRepo",new jn);k(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(n=>t.getProp(n,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(n=>t.getProp(n,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");o!==void 0&&(this.computableHelper=new Nn(this,o.blockCtx,o.mlEnv,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}),fe.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw 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,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Bn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){fe.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(A.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class jn{constructor(){k(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=ee.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 fe.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 o=this.errorIdToError.get(r);if(o===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new Vs.PlQuickJSError(e,o)}}function Be(s,e){return $e(s.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=A.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const Ke=process.env.MI_LOG_OUTPUT_STATUS;function Vn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),V.Computable.makeRaw(l=>{const a=new fe.Scope;l.addOnDestroy(()=>a.dispose());const c=a.manage(s.quickJs.newRuntime());c.setMemoryLimit(1024*1024*8),c.setMaxStackSize(1024*320);let u;c.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=a.manage(c.newContext()),p=new Ne(a,d,y=>{u=y},{computableCtx:l,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let R=0;return Ke&&Ke!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(y,{unstableMarker:T,stable:L})=>{for(const[D,q]of Object.entries(y))p.runCallback(D,q);const U=p.importObjectUniversal(f);return R++,Ke&&(Ke!=="unstable-only"||!L)&&console.log(L?`Stable output ${t.handle} calculated ${U!==void 0?"defined":"undefined"}; (#${R})`:`Unstable output ${t.handle}; marker = ${T}; ${U!==void 0?"defined":"undefined"} (#${R})`),U}}},n)}function xn(s,e,t,...r){const o=new fe.Scope;try{const n=o.manage(s.newRuntime());n.setMemoryLimit(1024*1024*8),n.setMaxStackSize(1024*320);let i;n.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const l=o.manage(n.newContext()),a=new Ne(o,l,c=>{i=c});return a.evaluateBundle(t.content),a.importObjectUniversal(a.runCallback(e.handle,...r))}finally{o.dispose()}}function Un(s){return A.isConfigLambda(s)?s.isActive===!0:rn(s)}function Te(s,e,t,r,o,n={}){if(A.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Vn(s,e,t,r,o,n)}else return Ln(s.driverKit,e,t,n)}function Mn(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=rr.omitBy((r,o)=>o.startsWith("__"));return rr.isDeepEqual(t(s),t(e))}function Jn(s,e,t){return V.Computable.make(r=>{var R,y,T,L,U,D,q,me;const o=r.accessor(s).node(),n=b.notEmpty(o.getKeyValueAsJson(Dt)),i=b.notEmpty(o.getKeyValueAsJson(De)),l=b.notEmpty(o.getKeyValueAsJson(Le)),a=b.notEmpty(o.getKeyValueAsJson(ge)),c=b.notEmpty(o.getKeyValueAsJson(Ze)),u=new Map;for(const{id:j}of ie(a)){const Q=o.traverse({field:K(j,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),re=Q.getDataAsJson();let H;const se=o.traverse({field:K(j,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(se!==void 0){const oe=se.getDataAsJson(),_=o.getField({field:K(j,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),W=o.getField({field:K(j,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});H={arguments:oe,stale:!Mn(re,oe),outputError:_.error!==void 0||W.error!==void 0||((R=_.value)==null?void 0:R.getError())!==void 0||((y=W.value)==null?void 0:y.getError())!==void 0,outputsError:((T=_.error)==null?void 0:T.getDataAsString())??((U=(L=_.value)==null?void 0:L.getError())==null?void 0:U.getDataAsString()),exportsError:((D=W.error)==null?void 0:D.getDataAsString())??((me=(q=W.value)==null?void 0:q.getError())==null?void 0:me.getDataAsString()),finished:(_.value!==void 0&&_.value.getIsReadyOrError()||_.error!==void 0&&_.error.getIsReadyOrError())&&(W.value!==void 0&&W.value.getIsReadyOrError()||W.error!==void 0&&W.error.getIsReadyOrError())}}u.set(j,{currentArguments:re,prod:H,argsRid:Q.resourceInfo.id})}const d=Ye(a,j=>{const Q=Be(o,j),re=u.get(j),H=re.currentArguments;return{args:H,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>Q.cfg,()=>H,{argsRid:re.argsRid,blockPackRid:Q.bpResourceId})}}),p=new Set(c.blocksInLimbo),f=[...ie(a)].map(({id:j,label:Q,renderingMode:re})=>{var v,P,$,E,N;const H=b.notEmpty(u.get(j)),se=b.notEmpty(d.nodes.get(j));let oe="NotCalculated";H.prod!==void 0&&(p.has(j)?oe="Limbo":oe=H.prod.finished?"Done":"Running");const _=Be(o,j),{sections:W,title:w,inputsValid:m,sdkVersion:C}=$e(_,({bpId:G,cfg:B})=>{const ue=Vt(s,j);return{sections:Te(t,ue,B.sections,B.code,G).wrap({recover:Re=>(t.logger.error("Error in block model sections"),t.logger.error(Re),[])}),title:$e(B.title,Re=>Te(t,ue,Re,B.code,G).wrap({recover:Fs=>(t.logger.error("Error in block model title"),t.logger.error(Fs),"Invalid title")})),inputsValid:Te(t,ue,B.inputsValid,B.code,G).wrap({recover:Re=>(t.logger.error("Error in block model argsValid"),t.logger.error(Re),!1)}),sdkVersion:B.sdkVersion}})||{},h=o.traverse({field:K(j,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),S=$e(_,({info:G})=>t.blockUpdateWatcher.get({currentSpec:G.source,settings:h}));return{projectResourceId:g.resourceIdToString(s.rid),id:j,label:w??Q,title:w??Q,renderingMode:re,stale:((v=H.prod)==null?void 0:v.stale)!==!1||oe==="Limbo",missingReference:se.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",j)],downstreams:[...d.traverseIdsExcludingRoots("downstream",j)],calculationStatus:oe,outputErrors:((P=H.prod)==null?void 0:P.outputError)===!0,outputsError:($=H.prod)==null?void 0:$.outputsError,exportsError:(E=H.prod)==null?void 0:E.exportsError,settings:h,sections:W,inputsValid:m,updateInfo:{},currentBlockPack:(N=_==null?void 0:_.info)==null?void 0:N.source,updates:S,sdkVersion:C,navigationState:e.getState(j)}});return{meta:l,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(kt),blocks:f}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const l=i.stale||i.upstreams.findIndex(p=>n.has(p))!==-1,a=(l||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>o.has(p))===-1,c={...i,canRun:a,stale:l,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete c.updates,c})}}}).withStableType()}function Gn(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,Nt)){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,Bt)){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 _n(s,e){if(s!==void 0)return V.Computable.make(t=>Gn(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 Kn(s,e,t){return V.Computable.make(r=>{var l;const o=r.accessor(s).node(),n=Be(o,e),i=(l=o.traverse({field:K(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:cs,assertFieldType:"Input"}))==null?void 0:l.persist();return{path:_n(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function vs(s,e,t){if(t===void 0)return V.Computable.make(i=>vs(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Vt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(bt(e)),args:b.deepFreeze(JSON.parse(o.args(t))),ui:n!==void 0?b.deepFreeze(JSON.parse(n)):void 0}}function Hn(s,e,t){return V.Computable.make(r=>{const o=r.accessor(s).node(),n=ps(s,e);return $e(Be(o,e),({cfg:i,bpId:l})=>{const a={};for(const[c,u]of Object.entries(i.outputs)){const d=Te(t,n,u,i.code,l);a[c]=V.Computable.wrapError(d,1)}return a})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function qn(s,e){return V.Computable.make(t=>{const r=t.accessor(s).node(),o=b.notEmpty(r.getKeyValueAsJson(ge)),n=[];for(const{id:i}of ie(o)){const l=Be(r,i);if(l===void 0)continue;const a=Object.entries(l.cfg.outputs).map(([,u])=>u).filter(u=>Un(u)).map(u=>u);if(a.length===0)continue;const c=ps(r.persist(),i);for(const u of a)n.push(V.Computable.wrapError(Te(e,c,u,l.cfg.code,l.bpId)))}return n})}class Wn{constructor(){k(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 V.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...A.DefaultNavigationState},change:new V.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return V.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged())}}function wr(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 nt{constructor(e,t,r){k(this,"rid");k(this,"overview");k(this,"navigationStates",new Wn);k(this,"blockComputables",new Map);k(this,"blockFrontends",new Map);k(this,"activeConfigs");k(this,"refreshLoopResult");k(this,"abortController",new AbortController);k(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Jn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=qn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await _e(this.env.projectHelper,this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await _r.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}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,o=void 0,n=ee.randomUUID()){const i=await this.env.bpPreparer.prepare(t),l=await this.env.bpPreparer.getBlockConfigContainer(t),a=A.extractConfig(l);return await ne(this.env.projectHelper,this.env.pl,this.rid,o,c=>c.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:x(a.initialArgs),uiState:x(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=A.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ne(this.env.projectHelper,this.env.pl,this.rid,o,l=>l.migrateBlockPack(e,n,r?{args:x(i.initialArgs),uiState:x(i.initialUiState)}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ne(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 ne(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(l=>{const a=n.blocks.find(c=>c.id===l);if(a===void 0)throw new Error(`Can't find block: ${l}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await _e(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:x(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ne(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:x(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ne(this.env.projectHelper,this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:x(t)}]),n.setUiState(e,x(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ne(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 o=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,K(e,"blockPack")))).value),n=g.ensureResourceIdNotNull((await r.getField(g.field(o,g.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),l=A.extractConfig(b.cachedDeserialize(b.notEmpty(i.data)).config);await ne(this.env.projectHelper,r,this.rid,t,a=>{a.setArgs([{blockId:e,args:x(l.initialArgs)}]),a.setUiState(e,x(l.initialUiState))}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Hn(this.projectTree.entry(),e,this.env),n={fullState:V.Computable.make(i=>({argsAndUiState:vs(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const l=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,c=l&&Xn(l)&&i.outputs!==void 0?Qn(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:c,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Kn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await _e(e.projectHelper,e.pl,t,o=>{});const r=await Qe.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:zn},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((i,l)=>{var a,c;return(((a=l.data)==null?void 0:a.byteLength)??0)-(((c=i.data)==null?void 0:c.byteLength)??0)});const n=Qe.treeDumpStats(o);await Ae.writeFile(`${g.resourceIdToString(t)}.json`,wr(o)),await Ae.writeFile(`${g.resourceIdToString(t)}.stats.json`,wr(n))}return new nt(e,t,r)}}function zn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Xn(s){return!Yn(s,"1.26.0")}function Yn(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 Qn(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(o=>typeof o=="string"?o:o.type=="PlError"&&o.fullMessage!==void 0?o.fullMessage:o.message),moreErrors:r.moreErrors}}return e}const xt={logger:new b.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function Ut(s){return{blobDownloadPath:J.join(s,"download"),downloadBlobToURLPath:J.join(s,"downloadToURL"),pframesSpillPath:J.join(s,"pframes")}}const ws={...xt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Ss(s){return{...Ut(s),frontendDownloadPath:J.join(s,"frontend")}}function Zn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ot={exports:{}};const ei="2.0.0",bs=256,ti=Number.MAX_SAFE_INTEGER||9007199254740991,ri=16,si=bs-6,oi=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var it={MAX_LENGTH:bs,MAX_SAFE_COMPONENT_LENGTH:ri,MAX_SAFE_BUILD_LENGTH:si,MAX_SAFE_INTEGER:ti,RELEASE_TYPES:oi,SEMVER_SPEC_VERSION:ei,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const ni=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var at=ni;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=it,n=at;e=s.exports={};const i=e.re=[],l=e.safeRe=[],a=e.src=[],c=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[p,r]],R=T=>{for(const[L,U]of f)T=T.split(`${L}*`).join(`${L}{0,${U}}`).split(`${L}+`).join(`${L}{1,${U}}`);return T},y=(T,L,U)=>{const D=R(L),q=d++;n(T,q,L),u[T]=q,a[q]=L,c[q]=D,i[q]=new RegExp(L,U?"g":void 0),l[q]=new RegExp(D,U?"g":void 0)};y("NUMERICIDENTIFIER","0|[1-9]\\d*"),y("NUMERICIDENTIFIERLOOSE","\\d+"),y("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),y("MAINVERSION",`(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})\\.(${a[u.NUMERICIDENTIFIER]})`),y("MAINVERSIONLOOSE",`(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})\\.(${a[u.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASEIDENTIFIER",`(?:${a[u.NUMERICIDENTIFIER]}|${a[u.NONNUMERICIDENTIFIER]})`),y("PRERELEASEIDENTIFIERLOOSE",`(?:${a[u.NUMERICIDENTIFIERLOOSE]}|${a[u.NONNUMERICIDENTIFIER]})`),y("PRERELEASE",`(?:-(${a[u.PRERELEASEIDENTIFIER]}(?:\\.${a[u.PRERELEASEIDENTIFIER]})*))`),y("PRERELEASELOOSE",`(?:-?(${a[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[u.PRERELEASEIDENTIFIERLOOSE]})*))`),y("BUILDIDENTIFIER",`${p}+`),y("BUILD",`(?:\\+(${a[u.BUILDIDENTIFIER]}(?:\\.${a[u.BUILDIDENTIFIER]})*))`),y("FULLPLAIN",`v?${a[u.MAINVERSION]}${a[u.PRERELEASE]}?${a[u.BUILD]}?`),y("FULL",`^${a[u.FULLPLAIN]}$`),y("LOOSEPLAIN",`[v=\\s]*${a[u.MAINVERSIONLOOSE]}${a[u.PRERELEASELOOSE]}?${a[u.BUILD]}?`),y("LOOSE",`^${a[u.LOOSEPLAIN]}$`),y("GTLT","((?:<|>)?=?)"),y("XRANGEIDENTIFIERLOOSE",`${a[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),y("XRANGEIDENTIFIER",`${a[u.NUMERICIDENTIFIER]}|x|X|\\*`),y("XRANGEPLAIN",`[v=\\s]*(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:\\.(${a[u.XRANGEIDENTIFIER]})(?:${a[u.PRERELEASE]})?${a[u.BUILD]}?)?)?`),y("XRANGEPLAINLOOSE",`[v=\\s]*(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[u.XRANGEIDENTIFIERLOOSE]})(?:${a[u.PRERELEASELOOSE]})?${a[u.BUILD]}?)?)?`),y("XRANGE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAIN]}$`),y("XRANGELOOSE",`^${a[u.GTLT]}\\s*${a[u.XRANGEPLAINLOOSE]}$`),y("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),y("COERCE",`${a[u.COERCEPLAIN]}(?:$|[^\\d])`),y("COERCEFULL",a[u.COERCEPLAIN]+`(?:${a[u.PRERELEASE]})?(?:${a[u.BUILD]})?(?:$|[^\\d])`),y("COERCERTL",a[u.COERCE],!0),y("COERCERTLFULL",a[u.COERCEFULL],!0),y("LONETILDE","(?:~>?)"),y("TILDETRIM",`(\\s*)${a[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",y("TILDE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAIN]}$`),y("TILDELOOSE",`^${a[u.LONETILDE]}${a[u.XRANGEPLAINLOOSE]}$`),y("LONECARET","(?:\\^)"),y("CARETTRIM",`(\\s*)${a[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",y("CARET",`^${a[u.LONECARET]}${a[u.XRANGEPLAIN]}$`),y("CARETLOOSE",`^${a[u.LONECARET]}${a[u.XRANGEPLAINLOOSE]}$`),y("COMPARATORLOOSE",`^${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]})$|^$`),y("COMPARATOR",`^${a[u.GTLT]}\\s*(${a[u.FULLPLAIN]})$|^$`),y("COMPARATORTRIM",`(\\s*)${a[u.GTLT]}\\s*(${a[u.LOOSEPLAIN]}|${a[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",y("HYPHENRANGE",`^\\s*(${a[u.XRANGEPLAIN]})\\s+-\\s+(${a[u.XRANGEPLAIN]})\\s*$`),y("HYPHENRANGELOOSE",`^\\s*(${a[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[u.XRANGEPLAINLOOSE]})\\s*$`),y("STAR","(<|>)?=?\\s*\\*"),y("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),y("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Ot,Ot.exports);var Ve=Ot.exports;const ii=Object.freeze({loose:!0}),ai=Object.freeze({}),ci=s=>s?typeof s!="object"?ii:s:ai;var Mt=ci;const Sr=/^[0-9]+$/,ks=(s,e)=>{const t=Sr.test(s),r=Sr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},li=(s,e)=>ks(e,s);var Ps={compareIdentifiers:ks,rcompareIdentifiers:li};const He=at,{MAX_LENGTH:br,MAX_SAFE_INTEGER:qe}=it,{safeRe:kr,safeSrc:Pr,t:We}=Ve,ui=Mt,{compareIdentifiers:ye}=Ps;let di=class le{constructor(e,t){if(t=ui(t),e instanceof le){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>br)throw new TypeError(`version is longer than ${br} characters`);He("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?kr[We.LOOSE]:kr[We.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>qe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>qe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>qe||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<qe)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(He("SemVer.compare",this.version,this.options,e),!(e instanceof le)){if(typeof e=="string"&&e===this.version)return 0;e=new le(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof le||(e=new le(e,this.options)),ye(this.major,e.major)||ye(this.minor,e.minor)||ye(this.patch,e.patch)}comparePre(e){if(e instanceof le||(e=new le(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(He("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ye(r,o)}while(++t)}compareBuild(e){e instanceof le||(e=new le(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(He("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ye(r,o)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?Pr[We.PRERELEASELOOSE]:Pr[We.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ye(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var Y=di;const Rr=Y,pi=(s,e,t=!1)=>{if(s instanceof Rr)return s;try{return new Rr(s,e)}catch(r){if(!t)return null;throw r}};var Se=pi;const fi=Se,gi=(s,e)=>{const t=fi(s,e);return t?t.version:null};var hi=gi;const mi=Se,yi=(s,e)=>{const t=mi(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var vi=yi;const Cr=Y,wi=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new Cr(s instanceof Cr?s.version:s,t).inc(e,r,o).version}catch{return null}};var Si=wi;const Er=Se,bi=(s,e)=>{const t=Er(s,null,!0),r=Er(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,l=n?r:t,a=!!i.prerelease.length;if(!!l.prerelease.length&&!a){if(!l.patch&&!l.minor)return"major";if(l.compareMain(i)===0)return l.minor&&!l.patch?"minor":"patch"}const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var ki=bi;const Pi=Y,Ri=(s,e)=>new Pi(s,e).major;var Ci=Ri;const Ei=Y,Oi=(s,e)=>new Ei(s,e).minor;var $i=Oi;const Ti=Y,Ii=(s,e)=>new Ti(s,e).patch;var Fi=Ii;const Ai=Se,Di=(s,e)=>{const t=Ai(s,e);return t&&t.prerelease.length?t.prerelease:null};var Li=Di;const Or=Y,Ni=(s,e,t)=>new Or(s,t).compare(new Or(e,t));var ae=Ni;const Bi=ae,ji=(s,e,t)=>Bi(e,s,t);var Vi=ji;const xi=ae,Ui=(s,e)=>xi(s,e,!0);var Mi=Ui;const $r=Y,Ji=(s,e,t)=>{const r=new $r(s,t),o=new $r(e,t);return r.compare(o)||r.compareBuild(o)};var Jt=Ji;const Gi=Jt,_i=(s,e)=>s.sort((t,r)=>Gi(t,r,e));var Ki=_i;const Hi=Jt,qi=(s,e)=>s.sort((t,r)=>Hi(r,t,e));var Wi=qi;const zi=ae,Xi=(s,e,t)=>zi(s,e,t)>0;var ct=Xi;const Yi=ae,Qi=(s,e,t)=>Yi(s,e,t)<0;var Gt=Qi;const Zi=ae,ea=(s,e,t)=>Zi(s,e,t)===0;var Rs=ea;const ta=ae,ra=(s,e,t)=>ta(s,e,t)!==0;var Cs=ra;const sa=ae,oa=(s,e,t)=>sa(s,e,t)>=0;var _t=oa;const na=ae,ia=(s,e,t)=>na(s,e,t)<=0;var Kt=ia;const aa=Rs,ca=Cs,la=ct,ua=_t,da=Gt,pa=Kt,fa=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return aa(s,t,r);case"!=":return ca(s,t,r);case">":return la(s,t,r);case">=":return ua(s,t,r);case"<":return da(s,t,r);case"<=":return pa(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var Es=fa;const ga=Y,ha=Se,{safeRe:ze,t:Xe}=Ve,ma=(s,e)=>{if(s instanceof ga)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?ze[Xe.COERCEFULL]:ze[Xe.COERCE]);else{const a=e.includePrerelease?ze[Xe.COERCERTLFULL]:ze[Xe.COERCERTL];let c;for(;(c=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||c.index+c[0].length!==t.index+t[0].length)&&(t=c),a.lastIndex=c.index+c[1].length+c[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",l=e.includePrerelease&&t[6]?`+${t[6]}`:"";return ha(`${r}.${o}.${n}${i}${l}`,e)};var ya=ma;class va{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var wa=va,gt,Tr;function ce(){if(Tr)return gt;Tr=1;const s=/\s+/g;class e{constructor(m,C){if(C=o(C),m instanceof e)return m.loose===!!C.loose&&m.includePrerelease===!!C.includePrerelease?m:new e(m.raw,C);if(m instanceof n)return this.raw=m.value,this.set=[[m]],this.formatted=void 0,this;if(this.options=C,this.loose=!!C.loose,this.includePrerelease=!!C.includePrerelease,this.raw=m.trim().replace(s," "),this.set=this.raw.split("||").map(h=>this.parseRange(h.trim())).filter(h=>h.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const h=this.set[0];if(this.set=this.set.filter(S=>!y(S[0])),this.set.length===0)this.set=[h];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&T(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let m=0;m<this.set.length;m++){m>0&&(this.formatted+="||");const C=this.set[m];for(let h=0;h<C.length;h++)h>0&&(this.formatted+=" "),this.formatted+=C[h].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(m){const h=((this.options.includePrerelease&&f)|(this.options.loose&&R))+":"+m,S=r.get(h);if(S)return S;const v=this.options.loose,P=v?a[c.HYPHENRANGELOOSE]:a[c.HYPHENRANGE];m=m.replace(P,_(this.options.includePrerelease)),i("hyphen replace",m),m=m.replace(a[c.COMPARATORTRIM],u),i("comparator trim",m),m=m.replace(a[c.TILDETRIM],d),i("tilde trim",m),m=m.replace(a[c.CARETTRIM],p),i("caret trim",m);let $=m.split(" ").map(B=>U(B,this.options)).join(" ").split(/\s+/).map(B=>oe(B,this.options));v&&($=$.filter(B=>(i("loose invalid filter",B,this.options),!!B.match(a[c.COMPARATORLOOSE])))),i("range list",$);const E=new Map,N=$.map(B=>new n(B,this.options));for(const B of N){if(y(B))return[B];E.set(B.value,B)}E.size>1&&E.has("")&&E.delete("");const G=[...E.values()];return r.set(h,G),G}intersects(m,C){if(!(m instanceof e))throw new TypeError("a Range is required");return this.set.some(h=>L(h,C)&&m.set.some(S=>L(S,C)&&h.every(v=>S.every(P=>v.intersects(P,C)))))}test(m){if(!m)return!1;if(typeof m=="string")try{m=new l(m,this.options)}catch{return!1}for(let C=0;C<this.set.length;C++)if(W(this.set[C],m,this.options))return!0;return!1}}gt=e;const t=wa,r=new t,o=Mt,n=lt(),i=at,l=Y,{safeRe:a,t:c,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=Ve,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:R}=it,y=w=>w.value==="<0.0.0-0",T=w=>w.value==="",L=(w,m)=>{let C=!0;const h=w.slice();let S=h.pop();for(;C&&h.length;)C=h.every(v=>S.intersects(v,m)),S=h.pop();return C},U=(w,m)=>(i("comp",w,m),w=j(w,m),i("caret",w),w=q(w,m),i("tildes",w),w=re(w,m),i("xrange",w),w=se(w,m),i("stars",w),w),D=w=>!w||w.toLowerCase()==="x"||w==="*",q=(w,m)=>w.trim().split(/\s+/).map(C=>me(C,m)).join(" "),me=(w,m)=>{const C=m.loose?a[c.TILDELOOSE]:a[c.TILDE];return w.replace(C,(h,S,v,P,$)=>{i("tilde",w,h,S,v,P,$);let E;return D(S)?E="":D(v)?E=`>=${S}.0.0 <${+S+1}.0.0-0`:D(P)?E=`>=${S}.${v}.0 <${S}.${+v+1}.0-0`:$?(i("replaceTilde pr",$),E=`>=${S}.${v}.${P}-${$} <${S}.${+v+1}.0-0`):E=`>=${S}.${v}.${P} <${S}.${+v+1}.0-0`,i("tilde return",E),E})},j=(w,m)=>w.trim().split(/\s+/).map(C=>Q(C,m)).join(" "),Q=(w,m)=>{i("caret",w,m);const C=m.loose?a[c.CARETLOOSE]:a[c.CARET],h=m.includePrerelease?"-0":"";return w.replace(C,(S,v,P,$,E)=>{i("caret",w,S,v,P,$,E);let N;return D(v)?N="":D(P)?N=`>=${v}.0.0${h} <${+v+1}.0.0-0`:D($)?v==="0"?N=`>=${v}.${P}.0${h} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.0${h} <${+v+1}.0.0-0`:E?(i("replaceCaret pr",E),v==="0"?P==="0"?N=`>=${v}.${P}.${$}-${E} <${v}.${P}.${+$+1}-0`:N=`>=${v}.${P}.${$}-${E} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.${$}-${E} <${+v+1}.0.0-0`):(i("no pr"),v==="0"?P==="0"?N=`>=${v}.${P}.${$}${h} <${v}.${P}.${+$+1}-0`:N=`>=${v}.${P}.${$}${h} <${v}.${+P+1}.0-0`:N=`>=${v}.${P}.${$} <${+v+1}.0.0-0`),i("caret return",N),N})},re=(w,m)=>(i("replaceXRanges",w,m),w.split(/\s+/).map(C=>H(C,m)).join(" ")),H=(w,m)=>{w=w.trim();const C=m.loose?a[c.XRANGELOOSE]:a[c.XRANGE];return w.replace(C,(h,S,v,P,$,E)=>{i("xRange",w,h,S,v,P,$,E);const N=D(v),G=N||D(P),B=G||D($),ue=B;return S==="="&&ue&&(S=""),E=m.includePrerelease?"-0":"",N?S===">"||S==="<"?h="<0.0.0-0":h="*":S&&ue?(G&&(P=0),$=0,S===">"?(S=">=",G?(v=+v+1,P=0,$=0):(P=+P+1,$=0)):S==="<="&&(S="<",G?v=+v+1:P=+P+1),S==="<"&&(E="-0"),h=`${S+v}.${P}.${$}${E}`):G?h=`>=${v}.0.0${E} <${+v+1}.0.0-0`:B&&(h=`>=${v}.${P}.0${E} <${v}.${+P+1}.0-0`),i("xRange return",h),h})},se=(w,m)=>(i("replaceStars",w,m),w.trim().replace(a[c.STAR],"")),oe=(w,m)=>(i("replaceGTE0",w,m),w.trim().replace(a[m.includePrerelease?c.GTE0PRE:c.GTE0],"")),_=w=>(m,C,h,S,v,P,$,E,N,G,B,ue)=>(D(h)?C="":D(S)?C=`>=${h}.0.0${w?"-0":""}`:D(v)?C=`>=${h}.${S}.0${w?"-0":""}`:P?C=`>=${C}`:C=`>=${C}${w?"-0":""}`,D(N)?E="":D(G)?E=`<${+N+1}.0.0-0`:D(B)?E=`<${N}.${+G+1}.0-0`:ue?E=`<=${N}.${G}.${B}-${ue}`:w?E=`<${N}.${G}.${+B+1}-0`:E=`<=${E}`,`${C} ${E}`.trim()),W=(w,m,C)=>{for(let h=0;h<w.length;h++)if(!w[h].test(m))return!1;if(m.prerelease.length&&!C.includePrerelease){for(let h=0;h<w.length;h++)if(i(w[h].semver),w[h].semver!==n.ANY&&w[h].semver.prerelease.length>0){const S=w[h].semver;if(S.major===m.major&&S.minor===m.minor&&S.patch===m.patch)return!0}return!1}return!0};return gt}var ht,Ir;function lt(){if(Ir)return ht;Ir=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[o.COMPARATORLOOSE]:r[o.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 l(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 l(u,this.options)}catch{return!1}return n(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 a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(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("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}ht=e;const t=Mt,{safeRe:r,t:o}=Ve,n=Es,i=at,l=Y,a=ce();return ht}const Sa=ce(),ba=(s,e,t)=>{try{e=new Sa(e,t)}catch{return!1}return e.test(s)};var ut=ba;const ka=ce(),Pa=(s,e)=>new ka(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Ra=Pa;const Ca=Y,Ea=ce(),Oa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Ea(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Ca(r,t))}),r};var $a=Oa;const Ta=Y,Ia=ce(),Fa=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Ia(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Ta(r,t))}),r};var Aa=Fa;const mt=Y,Da=ce(),Fr=ct,La=(s,e)=>{s=new Da(s,e);let t=new mt("0.0.0");if(s.test(t)||(t=new mt("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const l=new mt(i.semver.version);switch(i.operator){case">":l.prerelease.length===0?l.patch++:l.prerelease.push(0),l.raw=l.format();case"":case">=":(!n||Fr(l,n))&&(n=l);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||Fr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var Na=La;const Ba=ce(),ja=(s,e)=>{try{return new Ba(s,e).range||"*"}catch{return null}};var Va=ja;const xa=Y,Os=lt(),{ANY:Ua}=Os,Ma=ce(),Ja=ut,Ar=ct,Dr=Gt,Ga=Kt,_a=_t,Ka=(s,e,t,r)=>{s=new xa(s,r),e=new Ma(e,r);let o,n,i,l,a;switch(t){case">":o=Ar,n=Ga,i=Dr,l=">",a=">=";break;case"<":o=Dr,n=_a,i=Ar,l="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Ja(s,e,r))return!1;for(let c=0;c<e.set.length;++c){const u=e.set[c];let d=null,p=null;if(u.forEach(f=>{f.semver===Ua&&(f=new Os(">=0.0.0")),d=d||f,p=p||f,o(f.semver,d.semver,r)?d=f:i(f.semver,p.semver,r)&&(p=f)}),d.operator===l||d.operator===a||(!p.operator||p.operator===l)&&n(s,p.semver))return!1;if(p.operator===a&&i(s,p.semver))return!1}return!0};var Ht=Ka;const Ha=Ht,qa=(s,e,t)=>Ha(s,e,">",t);var Wa=qa;const za=Ht,Xa=(s,e,t)=>za(s,e,"<",t);var Ya=Xa;const Lr=ce(),Qa=(s,e,t)=>(s=new Lr(s,t),e=new Lr(e,t),s.intersects(e,t));var Za=Qa;const ec=ut,tc=ae;var rc=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>tc(u,d,t));for(const u of i)ec(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const l=[];for(const[u,d]of r)u===d?l.push(u):!d&&u===i[0]?l.push("*"):d?u===i[0]?l.push(`<=${d}`):l.push(`${u} - ${d}`):l.push(`>=${u}`);const a=l.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return a.length<c.length?a:e};const Nr=ce(),qt=lt(),{ANY:yt}=qt,Ce=ut,Wt=ae,sc=(s,e,t={})=>{if(s===e)return!0;s=new Nr(s,t),e=new Nr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=nc(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},oc=[new qt(">=0.0.0-0")],Br=[new qt(">=0.0.0")],nc=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===yt){if(e.length===1&&e[0].semver===yt)return!0;t.includePrerelease?s=oc:s=Br}if(e.length===1&&e[0].semver===yt){if(t.includePrerelease)return!0;e=Br}const r=new Set;let o,n;for(const f of s)f.operator===">"||f.operator===">="?o=jr(o,f,t):f.operator==="<"||f.operator==="<="?n=Vr(n,f,t):r.add(f.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Wt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const f of r){if(o&&!Ce(f,String(o),t)||n&&!Ce(f,String(n),t))return null;for(const R of e)if(!Ce(f,String(R),t))return!1;return!0}let l,a,c,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,p=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",c=c||f.operator==="<"||f.operator==="<=",o){if(p&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===p.major&&f.semver.minor===p.minor&&f.semver.patch===p.patch&&(p=!1),f.operator===">"||f.operator===">="){if(l=jr(o,f,t),l===f&&l!==o)return!1}else if(o.operator===">="&&!Ce(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(a=Vr(n,f,t),a===f&&a!==n)return!1}else if(n.operator==="<="&&!Ce(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&c&&!n&&i!==0||n&&u&&!o&&i!==0||p||d)},jr=(s,e,t)=>{if(!s)return e;const r=Wt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},Vr=(s,e,t)=>{if(!s)return e;const r=Wt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var ic=sc;const vt=Ve,xr=it,ac=Y,Ur=Ps,cc=Se,lc=hi,uc=vi,dc=Si,pc=ki,fc=Ci,gc=$i,hc=Fi,mc=Li,yc=ae,vc=Vi,wc=Mi,Sc=Jt,bc=Ki,kc=Wi,Pc=ct,Rc=Gt,Cc=Rs,Ec=Cs,Oc=_t,$c=Kt,Tc=Es,Ic=ya,Fc=lt(),Ac=ce(),Dc=ut,Lc=Ra,Nc=$a,Bc=Aa,jc=Na,Vc=Va,xc=Ht,Uc=Wa,Mc=Ya,Jc=Za,Gc=rc,_c=ic;var Kc={parse:cc,valid:lc,clean:uc,inc:dc,diff:pc,major:fc,minor:gc,patch:hc,prerelease:mc,compare:yc,rcompare:vc,compareLoose:wc,compareBuild:Sc,sort:bc,rsort:kc,gt:Pc,lt:Rc,eq:Cc,neq:Ec,gte:Oc,lte:$c,cmp:Tc,coerce:Ic,Comparator:Fc,Range:Ac,satisfies:Dc,toComparators:Lc,maxSatisfying:Nc,minSatisfying:Bc,minVersion:jc,validRange:Vc,outside:xc,gtr:Uc,ltr:Mc,intersects:Jc,simplifyRange:Gc,subset:_c,SemVer:ac,re:vt.re,src:vt.src,tokens:vt.t,SEMVER_SPEC_VERSION:xr.SEMVER_SPEC_VERSION,RELEASE_TYPES:xr.RELEASE_TYPES,compareIdentifiers:Ur.compareIdentifiers,rcompareIdentifiers:Ur.rcompareIdentifiers};const Hc=Zn(Kc),qc={minDelay:1500},Wc="__no_updates__";class zc extends V.PollComputablePool{constructor(t,r,o={}){super({...o,...qc},r);k(this,"http");k(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${x(t)}`;default:return Wc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await At(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await X.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const l=await rt(i);return l===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:l},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:l}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let c=this.preferredUpdateChannel;if(c===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,z.StableChannel))c=z.StableChannel;else{if(await a.getLatestOverview(n.id,z.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${z.blockPackIdToString(n.id)}`),{suggestions:[]};c=z.AnyChannel}else c=n.channel;const u=await a.getUpdateSuggestions(n.id,c);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(R=>R.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=u.find(R=>R.type==="patch"))==null?void 0:o.update;break}const p=u.map(({type:R,update:y})=>({type:R,update:{...n,id:{...n.id,version:y}}}));if(d===void 0)return{suggestions:p};if(l!==void 0&&Hc.lte(d,l))return{suggestions:p};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await a.getComponents(f.id)}catch(R){this.logger.warn(R)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return x(t)===x(r)}}class Mr{constructor(){k(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let Ee;function de(){return Ee||(Ee={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0},process.env.MI_LOG_TREE_STAT&&(Ee.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),Ee)}function Ie(s){return String(s.id)}const Xc=["Int","Long","Float","Double","String","Bytes"];function wt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Oe=(s,e)=>typeof e=="bigint"?e.toString():e;class Yc{constructor(e,t,r,o,n){k(this,"pFrame");k(this,"blobIdToResource",new Map);k(this,"blobHandleComputables",new Map);k(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});k(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});k(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.spillPath=r,this.blobContentCache=o;const i=(a,c)=>this.logger[a](c);for(const a of n)for(const c of Jo(a.data))this.blobIdToResource.set(Ie(c),c);const l=[...new Map(n.map(a=>({...a,data:Go(a.data,Ie)})).map(a=>[x(a),a])).values()];try{const a=new Kr.PFrame(this.spillPath,de().logPFrameRequests?i:void 0);a.setDataSource(this);for(const c of l)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(l)}, error: ${a}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Qc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class zt{constructor(e,t,r){k(this,"pFrames");k(this,"pTables");k(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const o=new $t.LRUCache({maxSize:1e9,fetchMethod:async i=>await qr.readFile(i),sizeCalculation:i=>i.length}),n=new b.ConcurrencyLimitingExecutor(4);this.concurrencyLimiter=n,this.pFrames=new class extends Mr{constructor(i,l,a){super(),this.blobDriver=i,this.logger=l,this.spillPath=a}createNewResource(i){return de().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Oe)}`),new Yc(this.blobDriver,this.logger,this.spillPath,o,i)}calculateParamsKey(i){return el(i)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Mr{constructor(i){super(),this.pFrames=i}createNewResource(i){const l=i.pFrameHandle;de().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(i)}): ${JSON.stringify(i,Oe)}`);const a=n.run(async()=>{const c=await this.pFrames.getByKey(l).pFrame.createTable({src:Fe(i.def.src),filters:wt(i.def.filters)},i.signal);let u=c;if(i.def.sorting.length>0)try{u=await c.sort(i.def.sorting,i.signal)}finally{c.dispose()}return u});return new Qc(a)}calculateParamsKey(i){return Zc(i)}}(this.pFrames)}async pprofDump(){return await Kr.PFrame.pprofDump()}static async init(e,t,r){const o=Js.resolve(r);return await b.emptyDir(o),new zt(e,t,o)}createPFrame(e,t){const r=e.filter(n=>Xc.find(i=>i===n.spec.valueType)).map(n=>A.mapPObjectData(n,i=>Qe.isPlTreeNodeAccessor(i)?zo(i):A.isDataInfo(i)?A.mapDataInfo(i,l=>l.resourceInfo):Xo(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,r){const o=this.createPFrame(A.extractAllColumns(e.src),t),n=A.mapPTableDef(e,l=>l.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:r});return de().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(A.mapPTableDef(e,l=>l.spec),Oe)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[x(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(l=>l.length===0))).map(n=>n.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){return de().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>{const o=await this.pFrames.getByKey(e).pFrame.createTable({src:Fe(t.src),filters:wt(t.filters)},r);let n=o;if(t.sorting.length>0)try{n=await o.sort(t.sorting,r)}finally{o.dispose()}try{const i=n.getSpec(),l=await n.getData([...i.keys()],void 0,r);return i.map((a,c)=>({spec:a,data:l[c]}))}finally{n.dispose()}})}async getUniqueValues(e,t,r){return de().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Oe)}`),await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues({...t,filters:wt(t.filters)},r))}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,r,o){const n=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await n.getData(t,r,o))}}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 Zc(s){const e=ee.createHash("sha256");return e.update(x(s)),e.digest().toString("hex")}function el(s){const e=[...s].map(r=>A.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([l,a])=>({key:l,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([l,a])=>({key:l,value:Ie(a)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([l,a])=>({key:l,value:[Ie(a.index),Ie(a.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((l,a)=>l.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ee.createHash("sha256");return t.update(x(e)),t.digest().toString("hex")}async function $s(s,e,t){const r={...xt,...Ut(e),...t},o=new b.HmacSha256Signer(r.localSecret),n=M.createDownloadClient(r.logger,s,r.localProjections),i=M.createLogsClient(s,r.logger),l=M.createUploadBlobClient(s,r.logger),a=M.createUploadProgressClient(s,r.logger),c=new M.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new M.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new M.UploadDriver(r.logger,o,l,a,r.uploadDriverOps),p=new M.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new M.LogsDriver(r.logger,p,c),R=await M.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),y=await zt.init(c,r.logger,r.pframesSpillPath);return{blobDriver:c,blobToURLDriver:u,logDriver:f,lsDriver:R,signer:o,uploadDriver:d,pFrameDriver:y}}class tl{constructor(e){k(this,"enrichmentTargetsCache",new $t.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 xn(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const o={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(o);const n=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(n,{context:o}).value}}class Xt{constructor(e,t,r,o,n,i,l,a){k(this,"pl");k(this,"projectList");k(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=l,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ee.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Mo(o,e);return o.createField(g.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await g.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ne(this.env.projectHelper,this.pl,e,r,o=>{o.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 nt.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()}static async init(e,t,r){const o={...ws,...Ss(t),...r};o.defaultTreeOptions.logStat=de().logTreeStats,o.debugOps.dumpInitialTreeState=de().dumpInitialTreeState;const n=await e.withWriteTx("MLInitialization",async T=>{const L=g.field(T.clientRoot,po);T.createField(L,"Dynamic");const U=await T.getField(L);if(g.isNullResourceId(U.value)){const D=T.createEphemeral(Qr);return T.lock(D),T.setField(L,D),await T.commit(),await D.globalId}else return U.value}),i=o.logger,l=await $s(e,t,o),a=new tt.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),c=new zr(a),u=new Lo(c,l.signer,a),d=new M.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),p=await fe.getQuickJS(),f={pl:e,signer:l.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:l,blockUpdateWatcher:new zc(c,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:p,projectHelper:new tl(p)},R=new V.WatchableValue([]),y=await go(e,n,R,f);return new Xt(f,l,l.signer,n,R,y.tree,c,y.computable)}}async function rl(s,e){return await be(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function sl(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function ol(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function nl(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function il(s,e){return await be(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await xe(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function al(s,e){return await be(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await xe(s.autoUpdateCdnUrl,s,e))}async function be(s,e,t){const r=Date.now(),o=[];for(;Jr(r)<s;){const n=Date.now();let i;try{i={ok:!0,value:await t()}}catch(c){i={ok:!1,error:c}}const l=Jr(n);o.push({elapsedMs:l,response:i});const a=1e3/e-l;a>0&&await _r.setTimeout(a)}return o}async function xe(s,e,t){const{body:r,statusCode:o}=await tt.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Jr(s){return Date.now()-s}function ve(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:o}=cl(s),n=`
2
2
  total: ${s.length};
3
3
  successes: ${e.length};
4
4
  errors: ${t};
@@ -6,7 +6,7 @@
6
6
  median in ms: ${o};
7
7
  `;return{ok:t===0,details:n}}function cl(s){const e=s.map(o=>o.elapsedMs).sort(),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}async function ll(s,e,t){try{const r=await ul(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 ul(s,e,t){var o;const r=await ke(e,he.Templates["check_network.upload_template"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(b.notEmpty((o=(await pe(e,r.greeting)).data)==null?void 0:o.toString()))}finally{r!=null&&await Pe(e,Object.values(r))}}async function dl(s,e,t,r,o,n){try{const i=await pl(s,e,t,r,o,n);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 pl(s,e,t,r,o,n){var a;const i=await t.getLocalFileHandle(n),l=await ke(o,he.Templates["check_network.upload_blob"],!0,c=>({file:c.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const c=await pe(o,l.progress);if(M.isUpload(c)){const u=M.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((a=c.data)==null?void 0:a.toString())));M.isSignMatch(e,u.localPath,u.pathSignature)&&await M.uploadBlob(s,r,c,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await pe(o,l.file)}finally{await Pe(o,Object.values(l))}}async function fl(s,e,t,r,o,n,i){try{const l=await gl(s,e,t,r,o,n);return l!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${l}`}:{status:"ok",message:`File downloading succeeded: ${l}`}}catch(l){return{status:"failed",message:`File downloading failed: error occurred: ${l}`}}}async function gl(s,e,t,r,o,n){var a;const i=await t.getLocalFileHandle(n),l=await ke(e,he.Templates["check_network.download_blob"],!0,c=>({file:c.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const c=await pe(e,l.progress);await M.uploadBlob(s,r,c,M.ImportFileHandleUploadData.parse(JSON.parse(b.notEmpty((a=c.data)==null?void 0:a.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await pe(e,l.file),{content:d}=await o.downloadBlob(u);return await Ms.text(d)}finally{await Pe(e,Object.values(l))}}async function hl(s){try{const e=await ml(s);return e!==`Hello from go binary
8
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 ml(s){var t;const e=await ke(s,he.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return b.notEmpty((t=(await pe(s,e.greeting)).data)==null?void 0:t.toString())}finally{await Pe(s,Object.values(e))}}async function yl(s,e){try{const t=await vl(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 vl(s,e){var r;const t=await ke(s,he.Templates["check_network.run_hello_world_py"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return b.notEmpty((r=(await pe(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Pe(s,Object.values(t))}}async function wl(s,e,t,r){var o,n;try{const i=await t.getStorageList(),l={};for(const a of i){const c=await Sl(t,a,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(c.file===void 0){l[a.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${a.name}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(c)} from storage ${a.name}`);const u=await ke(e,he.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(c.file.handle))}),["workdir"]);try{const d=await pe(e,u.workdir);d.type.name.startsWith("WorkingDirectory")?l[a.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(o=c.file)==null?void 0:o.size}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`}:l[a.name]={status:"failed",message:`Workdir creation failed: ${d.type.name}, size of file: ${(n=c.file)==null?void 0:n.size}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`}}finally{await Pe(e,Object.values(u))}}return l}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function Sl(s,e,t,r,o,n){const i=$s(s,e,"",0);let l,a=0,c=0;for await(const{file:u,nLsRequests:d}of i){if(c=Math.max(c,d),a>=t&&c>n)return{file:l,nLsRequests:c,nCheckedFiles:a};if(a++,r<=u.size&&u.size<=o)return{file:u,nLsRequests:c,nCheckedFiles:a};u.size<r&&(l=u)}return{file:l,nLsRequests:c,nCheckedFiles:a}}async function*$s(s,e,t,r){r++;const o=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const n of o.entries)if(n.type==="file"&&n.fullPath.startsWith(t))yield{file:n,nLsRequests:r};else if(n.type==="dir")for await(const i of $s(s,e,n.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function bl(){const s=J.join(Kr.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=ee.randomBytes(e);return await Ae.appendFile(s,t),{filePath:s}}async function kl(){const s=J.join(Kr.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await Ae.writeFile(s,e),{filePath:s,fileContent:e}}async function ke(s,e,t,r,o){return await s.withWriteTx("TemplateRender",async n=>{const i=await Lt(e),l=je(n,i),a=st(n,l,t,r(n),o),c={};for(const u of o){const d=g.field(s.clientRoot,u);n.createField(d,"Dynamic",a[u]),c[u]=await g.toGlobalFieldId(d)}return await n.commit(),c})}async function pe(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const o=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${o.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Pe(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function Pl(s,e,t,r={}){const o=[];Cl.forEach(n=>{Us.channel(n).subscribe(l=>{var u,d;const a=new Date().toISOString(),c={...l};(u=c==null?void 0:c.response)!=null&&u.headers&&(c.response={...c.response},c.response.headers=c.response.headers.slice(),c.response.headers=c.response.headers.map(p=>p.toString())),(d=c==null?void 0:c.request)!=null&&d.body&&(c.request={...c.request},c.request.body="too big"),o.push(JSON.stringify({timestamp:a,event:n,data:c}))})});try{const{logger:n,plConfig:i,client:l,signer:a,downloadClient:c,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Ts(s,e,t,r),{filePath:R,fileContent:y}=await kl(),{filePath:T}=await bl(),L={plPings:await rl(f,i),blockRegistryOverviewChecks:await sl(f,p),blockGARegistryOverviewChecks:await ol(f,p),blockRegistryUiChecks:await nl(f,p),blockGARegistryUiChecks:await il(f,p),autoUpdateCdnChecks:await al(f,p),uploadTemplateCheck:await ll(n,l,"Jack"),uploadFileCheck:await dl(n,a,d,u,l,T),downloadFileCheck:await fl(n,l,d,u,c,R,y),softwareCheck:await hl(l),pythonSoftwareCheck:await yl(l,"Jack"),storageToDownloadReport:await wl(n,l,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return Rl(L,s,f,o)}catch(n){return`Unhandled error while checking the network: ${n}`}}async function Ts(s,e,t,r={}){const o={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},n=g.plAddressToConfig(s,{defaultRequestTimeout:o.pingTimeoutMs});n.alternativeRoot=`check_network_${Date.now()}`;const i=new g.UnauthenticatedPlClient(n);let l={};e&&t&&(l=await i.login(e,t));const a=await g.PlClient.init(s,{authInformation:l}),c=i.ll.httpDispatcher,u=new b.ConsoleLoggerAdapter,d=new b.HmacSha256Signer("localSecret"),p=M.createDownloadClient(u,a,[]),f=M.createUploadBlobClient(a,u),R=await M.LsDriver.init(u,a,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:n,client:a,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:R,httpClient:c,ops:o,terminate:async()=>{p.close(),f.close(),await c.close(),await a.close()}}}function Rl(s,e,t,r){const o=s.plPings.filter(T=>T.response.ok),n=s.plPings.filter(T=>!T.response.ok),i=[...new Set(o.map(T=>JSON.stringify(T.response.value)))],l=T=>T?"OK":"FAILED",a=T=>T.status==="ok"?"OK":T.status==="warn"?"WARN":"FAILED",c=ve(s.plPings),u=ve(s.blockRegistryOverviewChecks),d=ve(s.blockGARegistryOverviewChecks),p=ve(s.blockRegistryUiChecks),f=ve(s.blockGARegistryUiChecks),R=ve(s.autoUpdateCdnChecks),y=Object.entries(s.storageToDownloadReport).map(([T,L])=>`${a(L)} ${T} storage check`).join(`
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 vl(s,e){var r;const t=await ke(s,he.Templates["check_network.run_hello_world_py"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return b.notEmpty((r=(await pe(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Pe(s,Object.values(t))}}async function wl(s,e,t,r){var o,n;try{const i=await t.getStorageList(),l={};for(const a of i){const c=await Sl(t,a,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(c.file===void 0){l[a.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${a.name}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(c)} from storage ${a.name}`);const u=await ke(e,he.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(c.file.handle))}),["workdir"]);try{const d=await pe(e,u.workdir);d.type.name.startsWith("WorkingDirectory")?l[a.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(o=c.file)==null?void 0:o.size}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`}:l[a.name]={status:"failed",message:`Workdir creation failed: ${d.type.name}, size of file: ${(n=c.file)==null?void 0:n.size}, checked ${c.nCheckedFiles} files, did ${c.nLsRequests} ls requests`}}finally{await Pe(e,Object.values(u))}}return l}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function Sl(s,e,t,r,o,n){const i=Ts(s,e,"",0);let l,a=0,c=0;for await(const{file:u,nLsRequests:d}of i){if(c=Math.max(c,d),a>=t&&c>n)return{file:l,nLsRequests:c,nCheckedFiles:a};if(a++,r<=u.size&&u.size<=o)return{file:u,nLsRequests:c,nCheckedFiles:a};u.size<r&&(l=u)}return{file:l,nLsRequests:c,nCheckedFiles:a}}async function*Ts(s,e,t,r){r++;const o=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const n of o.entries)if(n.type==="file"&&n.fullPath.startsWith(t))yield{file:n,nLsRequests:r};else if(n.type==="dir")for await(const i of Ts(s,e,n.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function bl(){const s=J.join(Hr.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=ee.randomBytes(e);return await Ae.appendFile(s,t),{filePath:s}}async function kl(){const s=J.join(Hr.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await Ae.writeFile(s,e),{filePath:s,fileContent:e}}async function ke(s,e,t,r,o){return await s.withWriteTx("TemplateRender",async n=>{const i=await Lt(e),l=je(n,i),a=st(n,l,t,r(n),o),c={};for(const u of o){const d=g.field(s.clientRoot,u);n.createField(d,"Dynamic",a[u]),c[u]=await g.toGlobalFieldId(d)}return await n.commit(),c})}async function pe(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const o=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${o.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Pe(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function Pl(s,e,t,r={}){const o=[];Cl.forEach(n=>{Us.channel(n).subscribe(l=>{var u,d;const a=new Date().toISOString(),c={...l};(u=c==null?void 0:c.response)!=null&&u.headers&&(c.response={...c.response},c.response.headers=c.response.headers.slice(),c.response.headers=c.response.headers.map(p=>p.toString())),(d=c==null?void 0:c.request)!=null&&d.body&&(c.request={...c.request},c.request.body="too big"),o.push(JSON.stringify({timestamp:a,event:n,data:c}))})});try{const{logger:n,plConfig:i,client:l,signer:a,downloadClient:c,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Is(s,e,t,r),{filePath:R,fileContent:y}=await kl(),{filePath:T}=await bl(),L={plPings:await rl(f,i),blockRegistryOverviewChecks:await sl(f,p),blockGARegistryOverviewChecks:await ol(f,p),blockRegistryUiChecks:await nl(f,p),blockGARegistryUiChecks:await il(f,p),autoUpdateCdnChecks:await al(f,p),uploadTemplateCheck:await ll(n,l,"Jack"),uploadFileCheck:await dl(n,a,d,u,l,T),downloadFileCheck:await fl(n,l,d,u,c,R,y),softwareCheck:await hl(l),pythonSoftwareCheck:await yl(l,"Jack"),storageToDownloadReport:await wl(n,l,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return Rl(L,s,f,o)}catch(n){return`Unhandled error while checking the network: ${n}`}}async function Is(s,e,t,r={}){const o={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},n=g.plAddressToConfig(s,{defaultRequestTimeout:o.pingTimeoutMs});n.alternativeRoot=`check_network_${Date.now()}`;const i=new g.UnauthenticatedPlClient(n);let l={};e&&t&&(l=await i.login(e,t));const a=await g.PlClient.init(s,{authInformation:l}),c=i.ll.httpDispatcher,u=new b.ConsoleLoggerAdapter,d=new b.HmacSha256Signer("localSecret"),p=M.createDownloadClient(u,a,[]),f=M.createUploadBlobClient(a,u),R=await M.LsDriver.init(u,a,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:n,client:a,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:R,httpClient:c,ops:o,terminate:async()=>{p.close(),f.close(),await c.close(),await a.close()}}}function Rl(s,e,t,r){const o=s.plPings.filter(T=>T.response.ok),n=s.plPings.filter(T=>!T.response.ok),i=[...new Set(o.map(T=>JSON.stringify(T.response.value)))],l=T=>T?"OK":"FAILED",a=T=>T.status==="ok"?"OK":T.status==="warn"?"WARN":"FAILED",c=ve(s.plPings),u=ve(s.blockRegistryOverviewChecks),d=ve(s.blockGARegistryOverviewChecks),p=ve(s.blockRegistryUiChecks),f=ve(s.blockGARegistryUiChecks),R=ve(s.autoUpdateCdnChecks),y=Object.entries(s.storageToDownloadReport).map(([T,L])=>`${a(L)} ${T} storage check`).join(`
10
10
  `);return`
11
11
  ${l(c.ok)} pings to Platforma Backend
12
12
  ${l(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 Cl=["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=Xs;exports.CentralBlockRegistry=Ys;exports.DefaultDriverKitOpsPaths=Ut;exports.DefaultDriverKitOpsSettings=xt;exports.DefaultMiddleLayerOpsPaths=ws;exports.DefaultMiddleLayerOpsSettings=vs;exports.FrontendFromFolderResourceType=Bt;exports.FrontendFromUrlResourceType=Nt;exports.MiddleLayer=Xt;exports.Project=nt;exports.TengoTemplateGet=rs;exports.TengoTemplateGetRegistry=ss;exports.TengoTemplateGetTemplate=ns;exports.TengoTemplateGetTemplateURI=os;exports.TengoTemplatePack=Co;exports.TengoTemplatePackConvert=Eo;exports.TengoTemplatePackConvertTemplate=$o;exports.TengoTemplatePackConvertTemplatePack=Oo;exports.V1CentralDevSnapshotRegistry=Zs;exports.V1CentralRegistry=Qs;exports.V2RegistryProvider=Wr;exports.checkNetwork=Pl;exports.createRenderTemplate=st;exports.getDevV1PacketMtime=At;exports.getDevV2PacketMtime=rt;exports.initDriverKit=Os;exports.initNetworkCheck=Ts;exports.loadTemplate=je;exports.prepareTemplateSpec=Lt;Object.keys(A).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>A[s]})});Object.keys(z).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>z[s]})});Object.keys(tr).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>tr[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 Cl=["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=Xs;exports.CentralBlockRegistry=Ys;exports.DefaultDriverKitOpsPaths=Ut;exports.DefaultDriverKitOpsSettings=xt;exports.DefaultMiddleLayerOpsPaths=Ss;exports.DefaultMiddleLayerOpsSettings=ws;exports.FrontendFromFolderResourceType=Bt;exports.FrontendFromUrlResourceType=Nt;exports.MiddleLayer=Xt;exports.Project=nt;exports.TengoTemplateGet=ss;exports.TengoTemplateGetRegistry=os;exports.TengoTemplateGetTemplate=is;exports.TengoTemplateGetTemplateURI=ns;exports.TengoTemplatePack=Co;exports.TengoTemplatePackConvert=Eo;exports.TengoTemplatePackConvertTemplate=$o;exports.TengoTemplatePackConvertTemplatePack=Oo;exports.V1CentralDevSnapshotRegistry=Zs;exports.V1CentralRegistry=Qs;exports.V2RegistryProvider=zr;exports.checkNetwork=Pl;exports.createRenderTemplate=st;exports.getDevV1PacketMtime=At;exports.getDevV2PacketMtime=rt;exports.initDriverKit=$s;exports.initNetworkCheck=Is;exports.loadTemplate=je;exports.prepareTemplateSpec=Lt;Object.keys(A).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>A[s]})});Object.keys(z).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>z[s]})});Object.keys(tr).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>tr[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