@milaboratories/pl-middle-layer 1.41.9 → 1.41.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var An=Object.defineProperty;var $r=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Lr=s=>{throw TypeError(s)};var Nn=(s,e,t)=>e in s?An(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var P=(s,e,t)=>Nn(s,typeof e!="symbol"?e+"":e,t);var Ar=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Lr("Object expected");var r,n;t&&(r=e[$r("asyncDispose")]),r===void 0&&(r=e[$r("dispose")],t&&(n=r)),typeof r!="function"&&Lr("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(i){return Promise.reject(i)}}),s.push([t,r,e])}else t&&s.push([t]);return e},Nr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(o,a,c,l){return l=Error(c),l.name="SuppressedError",l.error=o,l.suppressed=a,l},n=o=>e=t?new r(o,e,"An error was suppressed during disposal"):(t=!0,o),i=o=>{for(;o=s.pop();)try{var a=o[1]&&o[1].call(o[2]);if(o[0])return Promise.resolve(a).then(i,c=>(n(c),i()))}catch(c){n(c)}if(t)throw e};return i()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),jr=require("@milaboratories/pl-deployments"),Ze=require("undici"),Z=require("@platforma-sdk/block-tools"),ae=require("node:fs"),_=require("node:path"),jn=require("yaml"),w=require("@milaboratories/ts-helpers"),De=require("node:fs/promises"),Bn=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),We=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),L=require("@milaboratories/pl-model-backend"),ze=require("lru-cache"),xn=require("node:worker_threads"),zs=require("denque"),me=require("@platforma-sdk/workflow-tengo"),ne=require("canonicalize"),Vn=require("node:assert"),ge=require("quickjs-emscripten"),Un=require("@milaboratories/pl-errors"),Mn=require("remeda"),Xs=require("node:timers/promises"),H=require("@milaboratories/pl-drivers"),Ys=require("@milaboratories/pframes-rs-node"),qn=require("node:diagnostics_channel"),Jn=require("node:stream/consumers"),Qs=require("node:os");function pr(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 Gn=pr(_),Zs=pr(De),Br=pr(Mn);async function xr(s){try{return await Zs.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const _n=[Z.RegistryV1.PlPackageYamlConfigFile],Kn=[Z.RegistryV1.PlPackageJsonConfigFile],fr=["backend","dist","tengo","tpl","main.plj.gz"],hr=["config","dist","config.json"],en=["frontend","dist"],Vr="block-model/dist/config.json",Hn="block-ui/package.json",Wn=[fr,hr,_n,Kn,en];async function zn(s){return await xr(_.join(s,...hr))!==void 0||await xr(_.join(s,...fr))!==void 0}function ut(s,e){const t=Bn.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Ur(s,e){if(_.isAbsolute(s)||(s=_.resolve(s)),await zn(s))return{workflow:_.join(s,...fr),config:_.join(s,...hr),ui:_.join(s,...en)};{const t=ut(s,Vr),r=ut(s,Vr),n=ut(s,Hn);return{workflow:t,config:r,ui:_.resolve(n,"..","dist")}}}async function Xn(s){try{return await ae.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Yn(s){try{return await ae.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function gr(s){let e=0n;for(const t of Wn){const r=_.join(s,...t),n=await Yn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function et(s){const e=await ae.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await ae.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Qn{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const n=this.http!==void 0?{dispatcher:this.http}:{},o=await(await Ze.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const a of o){const{organization:c,package:l,latestMeta:u,latestVersion:d}=a,p={organization:c,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[Q.AnyChannel]:f,[Q.StableChannel]:f},allVersions:a.allVersions.map(y=>({version:y,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(n=>({...n,registryId:e.id}));case"local-dev":for(const n of await ae.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const i=_.join(r.path,n.name),o=await Xn(_.join(i,Z.RegistryV1.PlPackageYamlConfigFile));if(o!==void 0){const a=Z.RegistryV1.PlPackageConfigData.parse(jn.parse(o)),c=await gr(i),l={organization:a.organization,name:a.package,version:"DEV"},u={id:l,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:i,mtime:c}};t.push({registryId:e.id,id:l,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let a=i,c=await Z.tryLoadPackDescription(a);if(c===void 0){for(const l of["block","meta"])if(a=_.join(i,l),c=await Z.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const l=await et(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),featureFlags:c.featureFlags,spec:{type:"dev-v2",folder:a,mtime:l}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return w.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 o;const n=(o=this.registries.find(a=>a.id===e))==null?void 0:o.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class tn{constructor(e){P(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new Z.RegistryV2Reader(Z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Zn={type:"remote-v2",url:"https://blocks.pl-open.science/"},eo={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},to={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},ro={groups:[{id:"default",label:"Default",blocks:[]}]},so={stagingRefreshTimestamp:0,blocksInLimbo:[]},no={label:"New Project"},oo={name:"UserProject",version:"2"},Xe="SchemaVersion",$e="2",mr="ProjectCreated",Le="ProjectLastModified",Ae="ProjectMeta",fe="ProjectStructure",Ye="BlockRenderingState",io="BlockArgsAuthor/";function ir(s){return`${io}${s}`}const ar="ProjectStructureAuthor",ao="__serviceTemplate_";function cr(s){return`${ao}${s}`}const dt=new Set(["blockPack","blockSettings","uiState","prodArgs","currentArgs","prodCtx","prodUiCtx","prodOutput"]);function W(s,e){return`${s}-${e}`}const co=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function lo(s){const e=s.match(co);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const uo="projects",rn={name:"Projects",version:"1"},po=s=>h.resourceTypesEqual(s.type,rn)?s.fields:[];async function fo(s,e,t,r){const n=await We.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:po},r.logger);return{computable:J.Computable.make(o=>{const a=o.accessor(n.entry()).node(),c=t.getValue(o);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const d=a.traverse(u);if(d===void 0)continue;const p=w.notEmpty(d.getKeyValueAsJson(Ae)),f=w.notEmpty(d.getKeyValueAsJson(mr)),y=w.notEmpty(d.getKeyValueAsJson(Le));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:n}}const ho={name:"EphRenderTemplate",version:"1"},go={name:"RenderTemplate",version:"1"};function tt(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const i=t?s.createEphemeral(ho):s.createStruct(go),o=h.field(i,"template"),a=h.field(i,"inputs");return s.createField(o,"Input",e),s.createField(a,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(i),h.Pl.futureRecord(s,i,n,"Output","outputs/")}const mo={name:"BContextEnd",version:"1"},vo={name:"BContext",version:"1"},yo="id",wo="parent/",bo=["context","result"];function Mr(s,e,t){return tt(s,e,!0,t,bo)}function So(s){const e=s.createEphemeral(mo);return s.lock(e),e}function qr(s,e){if(e.length===0)return So(s);if(e.length===1)return e[0];const t=s.createEphemeral(vo);s.createField(h.field(t,yo),"Input",h.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${wo}${r}`),"Input",e[r]);return s.lock(t),t}function sn(s,e){const t=new Map,r=(n,i,o)=>{const a=te.createHash("sha256");i.updateCacheKey(n,a,o);const c=a.digest("hex");if(!t.has(c)){const l=i.render(n,s,r,o);t.set(c,l)}return t.get(c)};return r(e.template,nn,e.hashToSource)}const Jr={updateCacheKey(s,e,t){e.update(L.PlTemplateLibV1.type.name).update(L.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(L.PlTemplateLibV1.type,JSON.stringify(L.PlTemplateLibV1.fromV3Data(s,Se(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update(L.PlTemplateSoftwareV1.type.name).update(L.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash))},render(s,e,t,r){const n=L.PlTemplateSoftwareV1.fromV3Data(s,Se(s.name,r,s.sourceHash)),i=e.createStruct(L.PlTemplateSoftwareV1.type,n.data);return e.setKValue(i,L.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(i),i}},nn={updateCacheKey(s,e,t){e.update(L.PlTemplateV1.type.name).update(L.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash));const r=n=>(n.sort((i,o)=>i[0]===o[0]?0:i[0]<o[0]?-1:1),n);for(const[n,i]of r(Object.entries(s.libs??{})))e.update("lib:"+n),Jr.updateCacheKey(i,e,t);for(const[n,i]of r(Object.entries(s.software??{})))e.update("soft:"+n),Ue.updateCacheKey(i,e,t);for(const[n,i]of r(Object.entries(s.assets??{})))e.update("asset:"+n),Ue.updateCacheKey(i,e,t);for(const[n,i]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(i,e,t)},render(s,e,t,r){const n=e.createStruct(L.PlTemplateV1.type,JSON.stringify(L.PlTemplateV1.fromV3Data(s,Se(s.name,r,s.sourceHash)).data));for(const[a,c]of Object.entries(s.libs??{})){const l=L.PlTemplateV1.libField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Jr,r))}for(const[a,c]of Object.entries(s.software??{})){const l=L.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.assets??{})){const l=L.PlTemplateV1.swField(n,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.templates??{})){const l=L.PlTemplateV1.tplField(n,a);e.createField(l,"Input"),e.setField(l,t(c,nn,r))}if(e.lock(n),!s.hashOverride)return n;const i=e.createStruct(L.PlTemplateOverrideV1.type,JSON.stringify(L.PlTemplateOverrideV1.fromV3Data(s))),o=L.PlTemplateOverrideV1.tplField(i);return e.createField(o,"Service"),e.setField(o,n),e.lock(i),i}};function Se(s,e,t){return w.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function Co(s,e){const t=L.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return an(s,t);case"pl.tengo-template.v3":return sn(s,t);default:w.assertNever(r)}}function Po(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return an(s,t);case"pl.tengo-template.v3":return sn(s,t);default:w.assertNever(r)}}const Gr={hash(s,e){e.update(L.PlTemplateLibV1.type.name).update(L.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(L.PlTemplateLibV1.type,JSON.stringify(L.PlTemplateLibV1.fromV2Data(s).data))}},Me={hash(s,e){e.update(L.PlTemplateSoftwareV1.type.name).update(L.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=L.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct(L.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,L.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},on={hash(s,e){e.update(L.PlTemplateV1.type.name).update(L.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,i)=>n[0]===i[0]?0:n[0]<i[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Gr.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Me.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct(L.PlTemplateV1.type,JSON.stringify(L.PlTemplateV1.fromV2Data(s).data));for(const[o,a]of Object.entries(s.libs??{})){const c=L.PlTemplateV1.libField(r,o);e.createField(c,"Input"),e.setField(c,t(a,Gr))}for(const[o,a]of Object.entries(s.software??{})){const c=L.PlTemplateV1.swField(r,o);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[o,a]of Object.entries(s.assets??{})){const c=L.PlTemplateV1.swField(r,o);e.createField(c,"Input"),e.setField(c,t(a,Me))}for(const[o,a]of Object.entries(s.templates??{})){const c=L.PlTemplateV1.tplField(r,o);e.createField(c,"Input"),e.setField(c,t(a,on))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct(L.PlTemplateOverrideV1.type,JSON.stringify(L.PlTemplateOverrideV1.fromV2Data(s))),i=L.PlTemplateOverrideV1.tplField(n);return e.createField(i,"Service"),e.setField(i,r),e.lock(n),n}};function an(s,e){const t=new Map,r=(n,i)=>{const o=te.createHash("sha256");i.hash(n,o);const a=o.digest("hex");if(!t.has(a)){const c=i.render(n,s,r);t.set(a,c)}return t.get(a)};return r(e,on)}const cn={name:"TengoTemplateGet",version:"1"},ln="registry",un="templateURI",dn="template",Ro={name:"TengoTemplatePack",version:"1"},ko={name:"TengoTemplatePackConvert",version:"1"},Eo="templatePack",Oo="template";async function vr(s){switch(s.type){case"from-file":return{type:"explicit",content:await ae.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return w.assertNever(s)}}function To(s,e){const t=s.createStruct(cn),r=h.field(t,ln),n=h.field(t,un),i=h.field(t,dn);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),i}function Be(s,e){switch(e.type){case"from-registry":return To(s,e);case"explicit":return Co(s,e);case"prepared":return Po(s,e);default:return w.assertNever(e)}}const yr={name:"Frontend/FromUrl",version:"1"},wr={name:"Frontend/FromFolder",version:"1"};function Fo(s,e){switch(e.type){case"url":return s.createValue(yr,JSON.stringify({url:e.url}));case"local":return s.createValue(wr,JSON.stringify({path:e.path,signature:e.signature}));default:return w.assertNever(e)}}class Io{constructor(){P(this,"nextMessageId",0);P(this,"worker");P(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:_.resolve(void 0,"worker.js"),t=this.worker=new xn.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:i})=>{const{resolve:o,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),i?a(new Error(i)):o(n)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,n)=>{const i=++this.nextMessageId;this.pendingRequests.set(i,{resolve:r,reject:n}),this.worker.postMessage({id:i,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Do={name:"BlockPackCustom",version:"1"},pn="template",fn="frontend";function _r(s){return s.endsWith("/")?s:`${s}/`}function $o(s){return Buffer.from(s).toString("utf8")}function qe(s){return JSON.parse($o(s))}class Lo{constructor(e,t,r){P(this,"remoteContentCache",new ze.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await Ze.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 Ur(e.folder),r=await ae.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await ae.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${_r(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return qe(r)}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=await this.remoteContentCache.forceFetch(r.model.url);return qe(n)}default:return w.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Ar(n,new Io,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(i){var o=i,a=!0}finally{var c=Nr(n,o,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Ur(e.folder),r=await ae.promises.readFile(t.workflow),n=JSON.parse(await ae.promises.readFile(t.config,"utf-8")),i=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await ae.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await ae.promises.readFile(t.components.workflow.main.file),i=t.components.ui.folder,o={...e};return e.mtime===void 0&&(o.mtime=await et(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:o}}case"from-registry-v1":{const t=`${_r(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),i=new Uint8Array(n),o=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=qe(o);return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>qe(await this.remoteContentCache.forceFetch(r.model.url)),i=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[o,a]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:o,frontend:{type:"url",url:r.ui.url},source:e}}default:return w.assertNever(e)}}}function Ao(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Do,JSON.stringify(t));return s.createField(h.field(r,pn),"Input",Be(s,e.template)),s.createField(h.field(r,fn),"Input",Fo(s,e.frontend)),s.lock(r),r}function Kr(s,e){switch(e.type){case"prepared":return Ao(s,e);default:return w.assertNever(e.type)}}function Je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function No(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function lr(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(No(e))t===void 0||t.has(e.blockId)?(s.upstreams.add(e.blockId),e.requireEnrichments&&s.upstreamsRequiringEnrichments.add(e.blockId)):s.missingReferences=!0;else if(Array.isArray(e))for(const n of e)lr(s,n,t);else for(const[,n]of Object.entries(e))lr(s,n,t);return;default:w.assertNever(r)}}function jo(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return lr(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class hn{constructor(e){P(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const i=new Set(n);for(;n.length>0;){const o=[];for(const a of n){const c=this.nodes.get(a);r(c),c[e].forEach(l=>{i.has(l)||(i.add(l),o.push(l))})}n=o}}}function ur(s){const e=new Map;let t;for(const{id:r}of oe(s)){const n={id:r,missingReferences:!1};e.set(r,n),t===void 0?(n.directUpstream=n.upstream=new Set,n.enrichments=n.enrichmentTargets=new Set):(n.directUpstream=n.upstream=new Set([t.id]),t.directDownstream=t.downstream=new Set([n.id]),t.enrichments=t.enrichmentTargets=new Set),t=n}return t!==void 0&&(t.directDownstream=t.downstream=new Set),new hn(e)}function Ke(s,e){const t=new Map,r=new hn(t),n=new Set;for(const{id:i}of oe(s)){const o=e(i);if(o===void 0)continue;const a=jo(o.args,n),c=new Set([...a.upstreams,...r.traverseIds("enrichments",...a.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of oe(s)){if(p===i)break;if(c.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=o.enrichmentTargets===void 0?new Set(a.upstreams):new Set(o.enrichmentTargets.map(p=>p.blockId)),d={id:i,missingReferences:a.missingReferences,upstream:l,directUpstream:a.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(i,d),a.upstreams.forEach(p=>t.get(p).directDownstream.add(i)),l.forEach(p=>t.get(p).downstream.add(i)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(i)}),n.add(i)}return r}function Bo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function dr(s,e){if(s.size>e.size)return dr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Hr(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(i=>{const o=e.nodes.get(i.id);o===void 0?t.add(i.id):(!Bo(i.upstream,o.upstream)||dr(i.upstream,n))&&n.add(i.id)}),e.nodes.forEach(i=>{s.nodes.has(i.id)?dr(i.upstream,n)&&n.add(i.id):r.add(i.id)}),{onlyInA:t,onlyInB:r,different:n}}let pt;async function gn(){if(pt===void 0){const s=await vr(me.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=te.createHash("sha256").update(s.content).digest("hex");pt={spec:s,hash:e}}return pt}function xo(s,e,t){return tt(s,e,!0,{pf:t},["result"]).result}let ye;function ee(){return ye||(ye={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0,logProjectMutationStat:process.env.MI_LOG_PROJECT_MUTATION_STAT!==void 0,logOutputRecalculations:process.env.MI_LOG_OUTPUT_RECALCULATIONS!==void 0},process.env.MI_LOG_OUTPUT_STATUS&&(ye.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(ye.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),ye)}function ft(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const i=s();return r!==i&&(r=i,n=e()),e()}}class ht{constructor(e,t,r,n){P(this,"currentArgsC",ft(()=>this.fields.currentArgs.modCount,()=>w.cachedDeserialize(this.fields.currentArgs.value)));P(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 w.cachedDeserialize(e)}));P(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=n}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),pn,"Input")}}const Vo=s=>{throw new Error(`No new block info for ${s}`)};class Qe{constructor(e,t,r,n,i,o,a,c,l,u,d,p){P(this,"globalModCount",0);P(this,"fieldsChanged",!1);P(this,"lastModifiedChanged",!1);P(this,"structureChanged",!1);P(this,"metaChanged",!1);P(this,"renderingStateChanged",!1);P(this,"blocksWithChangedInputs",new Set);P(this,"stagingGraph");P(this,"pendingProductionGraph");P(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=i,this.meta=o,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.ctxExportTplHolder=d,this.projectHelper=p}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=ur(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,i;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,i=r.prodArgs}else n=w.notEmpty(r.fields.currentArgs),i=r.currentArgs;const o=w.notEmpty(r.fields.blockPack);return h.isResourceId(n.ref)&&h.isResourceId(o.ref)?{args:i,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>i,{argsRid:n.ref,blockPackRid:o.ref})}:{args:i,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>i)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=h.field(this.rid,W(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,i){this.setBlockFieldObj(e,t,{ref:r,status:n,value:i})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const i of t){const o=n.fields;i in o&&(this.tx.removeField(h.field(this.rid,W(e,i))),delete o[i],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,n,i;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.stagingUiCtx)==null?void 0:i.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,n,i;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((i=t.prodUiCtx)==null?void 0:i.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs","prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious")}setStates(e){const t=[];let r=!1;for(const n of e){const i=this.getBlockInfo(n.blockId);let o=!1;for(const a of["args","uiState"]){if(!(a in n))continue;const c=n[a];if(c==null)throw new Error(`Can't set ${a} to null or undefined, please omit the key if you don't want to change it`);const l=a==="args"?"currentArgs":"uiState";let u,d=!1;if(a==="args")u=w.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=w.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(i.fields[l].value,u)===0)continue;console.log("setting",l,d,u.length);const p=this.tx.createValue(d?h.Pl.JsonGzObject:h.Pl.JsonObject,u);this.setBlockField(n.blockId,l,p,"Ready",u),o=!0,a==="args"&&t.push(n.blockId)}o&&(this.blocksWithChangedInputs.add(n.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:n})=>this.resetStaging(n)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var i;const n=this.getBlockInfo(r);if(((i=n.fields.prodCtx)==null?void 0:i.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),qr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var i,o;const n=this.getBlockInfo(r);if(((i=n.fields.stagingCtx)==null?void 0:i.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((o=n.fields.prodCtx)==null?void 0:o.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),qr(this.tx,t)}exportCtx(e){return xo(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const n=t.getTemplate(this.tx),i=Mr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"stagingOutput",i.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const n=t.getTemplate(this.tx),i=Mr(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"prodOutput",i.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}initializeNewBlock(e,t){const r=new ht(e,{},O.extractConfig(t.blockPack.config),t.blockPack.source);this.blockInfos.set(e,r);const n=Kr(this.tx,t.blockPack);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,n),"NotReady"),this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(e,"currentArgs",this.createJsonFieldValueByContent(t.args)),this.setBlockFieldObj(e,"uiState",this.createJsonFieldValueByContent(t.uiState??"{}")),r.check()}getFieldNamesToDuplicate(e){var n,i;const t=this.getBlockInfo(e).fields,r=(o,a)=>new Set([...o].filter(c=>!a.has(c)));return((n=t.prodOutput)==null?void 0:n.status)==="Ready"&&((i=t.prodCtx)==null?void 0:i.status)==="Ready"?this.blocksInLimbo.has(e)?dt:r(dt,new Set(["prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"])):r(dt,new Set(["prodOutput","prodCtx","prodUiCtx","prodArgs","prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"]))}initializeBlockDuplicate(e,t){const r=new ht(e,{},t.config,t.source);this.blockInfos.set(e,r);const n=this.getFieldNamesToDuplicate(e);for(const[i,o]of Object.entries(t.fields))n.has(i)&&o&&o.ref&&this.setBlockFieldObj(e,i,{ref:o.ref,status:o.status,value:o.value});this.resetOrLimboProduction(e),r.check()}updateStructure(e,t=Vo){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),i=ur(e),o=Hr(r,i);for(const l of o.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0)}for(const l of o.onlyInB)t(l);for(const l of o.different)this.resetStaging(l);const a=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),c=Hr(n,a);n.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(o.onlyInB.size>0||o.onlyInA.size>0||o.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let i=!1;for(const o of n.groups){const a=o.blocks.findIndex(c=>c.id===r);if(!(a<0)){o.blocks.splice(a,0,e),i=!0;break}}if(!i)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,i=>{if(i!==e.id)throw new Error("Unexpected");this.initializeNewBlock(i,t)})}duplicateBlock(e,t,r){const n=this.getBlock(e),i=this.getBlockInfo(e),o={id:t,label:n.label,renderingMode:n.renderingMode},a=this.structure;if(r===void 0)a.groups[a.groups.length-1].blocks.push(o);else{let c=!1;for(const l of a.groups){const u=l.blocks.findIndex(d=>d.id===r);if(!(u<0)){l.blocks.splice(u+1,0,o),c=!0;break}}if(!c)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(a,c=>{if(c!==t)throw new Error("Unexpected");this.initializeBlockDuplicate(c,i)})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const i=n.blocks.findIndex(o=>o.id===e);if(!(i<0)){n.blocks.splice(i,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,Kr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:i})=>this.resetStaging(i)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:i})=>this.resetOrLimboProduction(i)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=n.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const l of c.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const i=new Set;for(const a of oe(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const l of n.nodes.get(a.id).upstream)if(i.has(l)){c=!0;break}}c&&(this.renderProductionFor(a.id),i.add(a.id))}const o=[...i];return n.traverse("downstream",o,a=>{i.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",o,({id:a})=>{o[0]!==a&&this.resetStaging(a)}),i.size>0&&this.updateLastModified(),i}stopProduction(...e){var o,a;const t=this.getActualProductionGraph(),r=new zs(e),n=new Set(e),i=[];for(;!r.isEmpty();){const c=r.shift(),l=this.getBlockInfo(c).fields;if(!(((o=l.prodOutput)==null?void 0:o.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){i.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))n.has(u)||(r.push(u),n.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...i))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let o=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(a=>{const c=t.get(a);c!==0&&(o=Math.max(c+1,o))}),e(n.id,o),t.set(n.id,o)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let n=0;this.traverseWithStagingLag((i,o)=>{o!==0&&(r===void 0||o<=r)&&(this.renderStagingFor(i),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,i,o;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((i=t.fields.stagingCtx)==null?void 0:i.status)==="Ready"&&((o=t.fields.stagingOutput)==null?void 0:o.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,ir(t)):this.tx.setKValue(this.rid,ir(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,ar):this.tx.setKValue(this.rid,ar,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,Le,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Ye,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Ae,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,n){const i=t.getResourceData(r,!0),o=t.getKValueJson(r,Xe),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,Ae),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,Ye),d=await i,p=new Map;for(const m of d.fields){const v=lo(m.name);if(v===void 0)continue;let C=p.get(v.blockId);C===void 0&&(C={id:v.blockId,fields:{}},p.set(v.blockId,C)),C.fields[v.fieldName]=h.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[C,S]of Object.entries(v)){if(S.ref===void 0)continue;if(!h.isResource(S.ref)||h.isResourceRef(S.ref))throw new Error("unexpected behaviour");const k=C;f.push([m,k,S,t.getResourceData(S.ref,k=="blockPack")])}});const[y,g,b,F,{stagingRefreshTimestamp:x,blocksInLimbo:D}]=await Promise.all([o,a,c,l,u]);if(y!==$e)throw Number(y)<Number($e)?new O.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new O.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const U=[];for(const[m,v,C,S]of f){const k=await S;if(C.value=k.data,h.isNotNullResourceId(k.error)?C.status="Error":k.resourceReady||h.isNotNullResourceId(k.originalResourceId)?C.status="Ready":C.status="NotReady",v==="blockPack"){const R=k.fields.find(I=>I.name===h.Pl.HolderRefField);if(R===void 0)throw new Error("Block pack ref field is missing");U.push([m,t.getResourceData(h.ensureResourceIdNotNull(R.value),!1)])}}for(const[m,v]of U){const C=await v,S=w.cachedDeserialize(w.notEmpty(C.data));m.blockConfig=O.extractConfig(S.config),m.blockPack=S.source}const M=await gn(),T=cr(M.hash),N=d.fields.find(m=>m.name===T);let E;N!==void 0?E=h.ensureResourceIdNotNull(N.value):(E=h.Pl.wrapInHolder(t,Be(t,M.spec)),t.createField(h.field(r,cr(M.hash)),"Dynamic",E));const K={stagingRefreshTimestamp:x},de=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:C,blockPack:S})=>Y.set(m,new ht(m,v,w.notEmpty(C),w.notEmpty(S))));const G=new Set;for(const m of oe(F)){if(!Y.has(m.id))throw new Error(`Inconsistent project structure: no inputs for ${m.id}`);G.add(m.id)}Y.forEach(m=>{if(!G.has(m.id))throw new Error(`Inconsistent project structure: no structure entry for ${m.id}`);m.check()});const X=new Qe(r,t,n,y,g,b,F,K,de,Y,E,e);return X.fixProblemsAndMigrate(),X}}async function Uo(s,e=no){const t=s.createEphemeral(oo);s.lock(t);const r=String(Date.now());s.setKValue(t,Xe,JSON.stringify($e)),s.setKValue(t,mr,r),s.setKValue(t,Le,r),s.setKValue(t,Ae,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(ro)),s.setKValue(t,Ye,JSON.stringify(so));const n=await gn();return s.createField(h.field(t,cr(n.hash)),"Dynamic",h.Pl.wrapInHolder(s,Be(s,n.spec))),t}async function Ge(s,e,t,r){return ie(s,e,t,void 0,r)}async function ie(s,e,t,r,n){if(e instanceof h.PlClient)return await e.withWriteTx("ProjectAction",async i=>{const o=await Qe.load(s,i,t,r),a=await n(o);return o.wasModified&&(o.save(),await i.commit(),ee().logProjectMutationStat&&console.log(JSON.stringify(i.stat))),a});{const i=await Qe.load(s,e,t,r),o=await n(i);return i.save(),o}}function*Mo(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:w.assertNever(s)}}function Wr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function qo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Wr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Wr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:w.assertNever(s)}}const Jo=h.resourceType("PColumnData/JsonPartitioned","1"),Go=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),_o=h.resourceType("PColumnData/BinaryPartitioned","1"),Ko=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Ho=h.resourceType("PColumnData/Json","1");function Wo(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,Ho)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,Jo)){const t=e,r=Object.fromEntries(s.listInputFields().map(n=>[n,s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Go)){const t=e,r={};for(const n of s.listInputFields()){const i=s.traverse({field:n,errorIfFieldNotSet:!0}),o=i.listInputFields();if(o===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of o){const c=JSON.stringify([...JSON.parse(n),...JSON.parse(a)]);r[c]=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,_o)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const i=n.slice(0,n.length-6);let o=r[i];o===void 0&&(o={},r[i]=o),o.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const i=n.slice(0,n.length-7);let o=r[i];o===void 0&&(o={},r[i]=o),o.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,i]of Object.entries(r)){if(i.index===void 0)throw new Error(`no index for part ${n}`);if(i.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Ko)){const t=e,r={};for(const n of s.listInputFields()){const i=s.traverse({field:n,errorIfFieldNotSet:!0}),o=i.listInputFields();if(o===void 0)throw new Error(`no partition keys for super key ${n}`);for(const a of o)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function zo(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:i}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=i}return{type:"Json",keyLength:t,data:r}}function Xo(s,e){const t=te.createHash("sha256");return t.update(ne(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function zr(s,e){return ne({__isRef:!0,blockId:s,name:e})}function Yo(s,e){return ne({resolvePath:s,name:e})}function mn(s,e=!0,t=!1,r=""){var a,c,l;const n=/^(?<name>.*)\.(?<type>spec|data)$/,i=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=w.notEmpty((a=d.groups)==null?void 0:a.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=w.notEmpty((c=d.groups)==null?void 0:c.type);let y=i.get(p);switch(y===void 0&&(y={},i.set(p,y)),f){case"spec":y.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const o=s.getInputsLocked();if(o)for(const[,u]of i)u.data===void 0&&(u.hasData=!1);return{locked:o,results:i}}function Qo(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=mn(s,e,!1,t);Vn(n.locked);const i={};for(const[o,a]of n.results){if(a.spec===void 0)throw new Error(`no spec for key ${o}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${o}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${o}`);if(!c.ok)throw c.error;i[o]={id:r.length===0?Xo(a.spec,c.value):Yo(r,o),spec:a.spec,data:c.value}}return i}class br{constructor(e,t){P(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const i of[n.prod,n.staging])if(i!==void 0){if(!i.locked){r=!1;break e}for(const o of i.results.values())if(o.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var i,o,a,c,l,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(a=(o=(i=r.prod)==null?void 0:i.results)==null?void 0:o.get(t))==null?void 0:a.spec;if(n!==void 0||(n=(u=(l=(c=r.staging)==null?void 0:c.results)==null?void 0:l.get(t))==null?void 0:u.spec,n!==void 0))return n;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var o,a,c;const r=this.blocks.get(e);if(r===void 0)return;const n=(a=(o=r.prod)==null?void 0:o.results)==null?void 0:a.get(t),i=(c=n==null?void 0:n.data)==null?void 0:c.call(n);if(n!==void 0&&n.spec!==void 0&&i!==void 0)return O.mapValueInVOE(i,l=>({id:zr(e,t),spec:n.spec,data:l}));n!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1},i=(o,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:Je(o,a),obj:{id:l.ok?zr(o,a):void 0,spec:c.spec,data:l}}):n(`no_data:${o}:${a}`)}};for(const[o,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||n(`prod_not_locked:${o}`);for(const[l,u]of a.prod.results)c.add(l),i(o,l,u)}if(a.staging!==void 0){a.staging.locked||n(`staging_not_locked:${o}`);for(const[l,u]of a.staging.results)c.has(l)||i(o,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=i=>{r===void 0&&(r=i),t=!1};for(const[i,o]of this.blocks){const a=new Set;if(o.staging!==void 0){o.staging.locked||n(`staging_not_locked:${i}`);for(const[c,l]of o.staging.results)l.spec!==void 0&&(e.push({ref:Je(i,c),obj:l.spec}),a.add(c))}else n(`staging_not_rendered:${i}`);if(o.prod!==void 0){o.prod.locked||n(`prod_not_locked:${i}`);for(const[c,l]of o.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:Je(i,c),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,i=o=>{for(const[a,c]of o.results)n.has(a)||c.spec===void 0||(n.add(a),O.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Je(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&i(r.staging),r.prod!==void 0&&i(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),i=w.notEmpty(n.getKeyValueAsJson(fe)),a=ur(i).traverseIds("upstream",r),c=new Map;for(const l of oe(i)){if(!a.has(l.id))continue;const u=Xr(n.traverse({field:W(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:W(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=Xr(n.traverse({field:W(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:W(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:d})}return new br(e,c)}}function Xr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return mn(e.value,!1,!0)}function Sr(s,e){return{blockId:e,args:i=>w.cachedDecode(w.notEmpty(i.accessor(s).node().traverse({field:W(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:i=>{var a;const o=(a=i.accessor(s).node().traverse({field:W(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:a.getData();return o?w.cachedDecode(o):void 0},uiState:i=>{var a;const o=(a=i.accessor(s).node().traverse({field:W(e,"uiState"),stableIfNotFound:!0}))==null?void 0:a.getData();return o?w.cachedDecode(o):void 0},blockMeta:i=>{const o=i.accessor(s).node(),a=w.notEmpty(o.getKeyValueAsJson(fe)),c=new Map;for(const l of oe(a))c.set(l.id,l);return c}}}function vn(s,e){return{...Sr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var n;const r=(n=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>br.create(t,s,e)}}function*se(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*se(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*se(t);return;case"MakeArray":for(const t of s.template)yield*se(t);return;case"GetJsonField":case"GetResourceField":yield*se(s.source),yield*se(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*se(s.source),yield*se(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*se(s.source);return;case"IsEmpty":yield*se(s.arg);return;case"Not":yield*se(s.operand);return;case"And":case"Or":yield*se(s.operand1),yield*se(s.operand2);return;default:w.assertNever(s)}}function Zo(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Te(s,e){return s===void 0?void 0:e(s)}function ei(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function ti(s){for(const e of se(s))if(ei(e))return!0;return!1}function rt(s){return{type:"ReturnResult",result:s}}function A(s){return()=>rt(s)}const ri=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return A(e)},si=s=>{const e=s.source;if(e===void 0)return A(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return A(t)},ni=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?A(void 0):({cCtx:r})=>{var n;return rt((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function yn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function oi(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):()=>({type:"ScheduleSubroutine",subroutine:wn(r.length),args:yn(r,n=>B({...s,[e.itVar]:n},e.mapping))})}}function wn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return A(t)}}function ii(s,e){return t=>{const r=t.source;if(r===void 0)return A(void 0);const n={};for(const[i,o]of Object.entries(r)){const a={...s,[e.itVar]:o};n[i]=B(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ai,args:n})}}const ai=s=>A(s),ci=s=>{const e=s.arg;return A(e===void 0?void 0:e.length===0)},li=s=>{const e=s.operand;return A(e===void 0?void 0:!e)},ui=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e&&t)},di=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e||t)},pi=s=>{const e=s.source;return e===void 0?A(void 0):({cCtx:t})=>{var r;return rt((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},fi=s=>{const e=s.source,t=s.field;return A(e===void 0||t===void 0?void 0:e[t])};function hi(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):({cCtx:n})=>{const i=n.accessor(r).node(),o={};for(const a of i.listInputFields()){const c=i.traverse(a);if(c===void 0)o[a]=A(void 0);else{const l={...s,[e.itVar]:c.persist()};o[a]=B(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:gi,args:o}}}}const gi=s=>A(s),mi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo),{postprocessValue:async n=>{if(n!==void 0)return await r.blobDriver.getContent(n.handle,s)}})})},vi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({cCtx:r,drivers:n})=>{const i=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(o=>n.blobDriver.getDownloadedBlob(i,o),{postprocessValue:async o=>o===void 0?void 0:(await n.blobDriver.getContent(o.handle,s)).toString()})}}},yi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const i=await r.blobDriver.getContent(n.handle,s);if(i!=null)return JSON.parse(Buffer.from(i).toString())}})})},wi=s=>{const e=s.source;return e===void 0?A(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},bi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Si=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},Ci=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Pi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Ri=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},ki=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Ei=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function B(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>rt(t(r.cCtx)):A(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:Cn(t,s,e.cfg)});case"Immediate":return A(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:fi,args:{source:B(s,e.source),field:B(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:oi(s,e),args:{source:B(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ii(s,e),args:{source:B(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:ri,args:Zo(e.template,t=>B(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:wn(e.template.length),args:yn(e.template,t=>B(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:si,args:{source:B(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ci,args:{arg:B(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:li,args:{operand:B(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:ui,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:di,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:hi(s,e),args:{source:B(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ni,args:{source:B(s,e.source),field:B(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:pi,args:{source:B(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:mi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:vi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:yi(e.range),args:{source:B(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:wi,args:{source:B(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:bi,args:{source:B(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Si(e.format),args:{source:B(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Ci,args:{source:B(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Pi(e.lines),args:{source:B(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Ri(e.patternToSearch),args:{source:B(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:ki(e.patternToSearch),args:{source:B(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Ei,args:{source:B(s,e.source)}});default:return w.assertNever(e)}}const Oi=["$prod","$staging"];function Ti(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 bn=Symbol(),Sn="return",Fi={op:bn,arg:Sn};function Ii(s){return s.op==bn&&s.arg==Sn}function Di(){return{pendingSubroutines:new Map}}function Yr(s,e,t,r){const n=new zs(t),i=(a,c)=>{if(Ii(a))return e.result=c,!1;const l=w.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),n.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},o=[];e:for(;n.length>0;){const a=n.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!i(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)n.push({destination:a.destination,operation:c.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");o.push({destination:a.destination,computable:c.computable});break;default:w.assertNever(c)}}return o}function $i(s,e,t,r={}){return Cn(s,Ti(e),t,r)}function Cn(s,e,t,r={}){const n=`${e.blockId}#`+ne({ctx:Object.fromEntries(Object.entries(e).filter(([i])=>Oi.indexOf(i)===-1)),cfg:t});return J.Computable.makeRaw(i=>{const o={drivers:s,cCtx:i},a=Di();return{ir:Yr(o,a,[{destination:Fi,operation:B(e,t)}],!0),postprocessValue(l){const u=[];for(const y of l)u.push({destination:y.destination,operation:A(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,g]of a.pendingSubroutines)p.set(y,{...g,args:{...g.args}});const f={result:a.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:n})}function Qr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Li{constructor(e,t,r,n,i){P(this,"computablesToResolve",{});P(this,"computableCtx");P(this,"accessors",new Map);P(this,"meta");P(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.featureFlags=n,this.computableCtx=i,this.meta=t.blockMeta(i)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const i=this.blockCtx[n];if(i===void 0)throw new Error("Staging context not available");const o=i(this.computableCtx);o?this.accessors.set(r,this.computableCtx.accessor(o).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 Qr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Qr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const i=this.getAccessor(e);if(!i.getIsReadyOrError())return;const o=Qo(i,t,r,n),a={};for(const[c,l]of Object.entries(o))a[c]=O.mapPObjectData(l,u=>this.wrapAccessor(u));return a}registerComputable(e,t){const r=`${e}_${te.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",J.Computable.make(n=>this.env.driverKit.blobDriver.getDownloadedBlob(r,n),{postprocessValue:async n=>{if(n!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(n.handle,t)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=w.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:O.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:O.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 O.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=>O.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(O.mapPTableDef(e,t=>O.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):O.isDataInfo(e)?O.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=te.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;ge.Scope.withScope(n=>{const i=(o,a)=>{const c=(...l)=>{try{return a(...l)}catch(u){const d=t.errorRepo.setAndRecreateForQuickJS(u);throw r.newError(d)}};r.newFunction(o,c).consume(l=>r.setProp(e,o,l)),r.newFunction(o,a).consume(l=>r.setProp(e,o+"__internal__",l))};if(O.checkBlockFlag(this.featureFlags,"supportsLazyState"))i("args",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.args outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.args(this.computableCtx))}),i("uiState",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.uiState outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.uiState(this.computableCtx)??"{}")}),i("activeArgs",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.activeArgs outside the future lambda. Can't be directly used in this context.");const o=this.blockCtx.activeArgs(this.computableCtx);return o===void 0?r.undefined:r.newString(o)});else{const o=this.blockCtx.args(this.computableCtx),a=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(o))),r.setProp(e,"uiState",n.manage(r.newString(c??"{}"))),a!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(a)))}i("getAccessorHandleByName",o=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(o)),void 0)),i("resolveWithCommon",(o,a,...c)=>t.exportSingleValue(this.resolveWithCommon(r.getString(o),t.importObjectViaJson(a),...c.map(l=>t.importObjectViaJson(l))),void 0)),i("getResourceType",o=>t.exportObjectViaJson(this.getResourceType(r.getString(o)),void 0)),i("getInputsLocked",o=>t.exportSingleValue(this.getInputsLocked(r.getString(o)),void 0)),i("getOutputsLocked",o=>t.exportSingleValue(this.getOutputsLocked(r.getString(o)),void 0)),i("getIsReadyOrError",o=>t.exportSingleValue(this.getIsReadyOrError(r.getString(o)),void 0)),i("getIsFinal",o=>t.exportSingleValue(this.getIsFinal(r.getString(o)),void 0)),i("getError",o=>t.exportSingleValue(this.getError(r.getString(o)),void 0)),i("listInputFields",o=>t.exportObjectViaJson(this.listInputFields(r.getString(o)),void 0)),i("listOutputFields",o=>t.exportObjectViaJson(this.listInputFields(r.getString(o)),void 0)),i("listDynamicFields",o=>t.exportObjectViaJson(this.listInputFields(r.getString(o)),void 0)),i("getKeyValueBase64",(o,a)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(o),r.getString(a)),void 0)),i("getKeyValueAsString",(o,a)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(o),r.getString(a)),void 0)),i("getDataBase64",o=>t.exportSingleValue(this.getDataBase64(r.getString(o)),void 0)),i("getDataAsString",o=>t.exportSingleValue(this.getDataAsString(r.getString(o)),void 0)),i("parsePObjectCollection",(o,a,c,...l)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(o),r.dump(a),r.getString(c),...l.map(u=>r.getString(u))),void 0)),i("getBlobContentAsBase64",(o,a)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(o),t.importObjectUniversal(a)),void 0)),i("getBlobContentAsString",(o,a)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(o),t.importObjectUniversal(a)),void 0)),i("getDownloadedBlobContentHandle",o=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(o)),void 0)),i("getOnDemandBlobContentHandle",o=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(o)),void 0)),i("extractArchiveAndGetURL",(o,a)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(o),r.getString(a)),void 0)),i("getImportProgress",o=>t.exportSingleValue(this.getImportProgress(r.getString(o)),void 0)),i("getLastLogs",(o,a)=>t.exportSingleValue(this.getLastLogs(r.getString(o),r.getNumber(a)),void 0)),i("getProgressLog",(o,a)=>t.exportSingleValue(this.getProgressLog(r.getString(o),r.getString(a)),void 0)),i("getProgressLogWithInfo",(o,a)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(o),r.getString(a)),void 0)),i("getLogHandle",o=>t.exportSingleValue(this.getLogHandle(r.getString(o)),void 0)),i("getBlockLabel",o=>t.exportSingleValue(this.getBlockLabel(r.getString(o)),void 0)),i("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",o=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(o)),void 0)),i("getSpecFromResultPoolByRef",(o,a)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(o),r.getString(a)),void 0)),i("getDataFromResultPoolByRef",(o,a)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(o),r.getString(a)),void 0)),i("createPFrame",o=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(o)),void 0)),i("createPTable",o=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(o)),void 0)),i("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),i("logInfo",o=>{this.logInfo(r.getString(o))}),i("logWarn",o=>{this.logWarn(r.getString(o))}),i("logError",o=>{this.logError(r.getString(o))})})}}function Ai(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,n,i){P(this,"callbackRegistry");P(this,"fnJSONStringify");P(this,"fnJSONParse");P(this,"errorRepo",new Ni);P(this,"computableHelper");if(this.scope=e,this.vm=t,this.deadlineSetter=r,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(o=>t.getProp(o,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");i!==void 0&&(this.computableHelper=new Li(this,i.blockCtx,i.mlEnv,n,i.computableCtx)),this.injectCtx()}resetComputableCtx(){w.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}),ge.Scope.withScope(r=>{const n=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(n)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(n,this.vm.undefined,...t.map(i=>this.exportObjectUniversal(i,r)))))})}catch(r){throw Ne.cleanErrorContext(r),this.errorRepo.getOriginal(r)}finally{this.deadlineSetter(void 0)}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return r}tryExportSingleValue(e,t){let r,n=!1;switch(typeof e){case"string":r=this.vm.newString(e),n=!0;break;case"number":r=this.vm.newNumber(e),n=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Ai(e)){r=this.vm.newArrayBuffer(e),n=!0;break}return}return n&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(n=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,n)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){if(e!==void 0)switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ge.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(O.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Ni{constructor(){P(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=te.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof ge.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;const t=e.cause;if(!(typeof t=="object"&&t!==null&&"name"in t&&typeof t.name=="string"))return console.warn("ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)",h.stringifyWithResourceId(e)),e;const r=t.name,n=r.slice(r.indexOf("/uuid:")+6);if(!n)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${r}, ${h.stringifyWithResourceId(e)}`);const i=this.errorIdToError.get(n);if(i===void 0)throw new Error(`ErrorRepo: errorId not found: ${n}, ${h.stringifyWithResourceId(e)}`);return new Un.PlQuickJSError(e,i)}}function Zr(s,e,t,r,n){ee().logOutputStatus&&(ee().logOutputStatus==="any"||!t)&&console.log(t?`Stable output ${s} calculated ${e!==void 0?"defined":"undefined"}; (#${r})`:`Unstable output ${s}; marker = ${n}; ${e!==void 0?"defined":"undefined"} (#${r})`)}function ji(s,e,t,r,n,i={}){const{code:o,featureFlags:a}=r,c=`${e.blockId}#lambda#${n}#${t.handle}`;return i={...i,key:c},i.mode===void 0&&t.retentive===!0&&(i.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{ee().logOutputRecalculations&&console.log(`Block lambda recalculation : ${c} (${l.changeSourceMarker}; ${l.bodyInvocations} invocations)`);const u=new ge.Scope;let d=!1;l.addOnDestroy(()=>{d&&u.dispose()});try{const p=u.manage(s.quickJs.newRuntime());p.setMemoryLimit(1024*1024*8),p.setMaxStackSize(1024*320);let f;p.setInterruptHandler(()=>f===void 0?!1:Date.now()>f.deadline);const y=u.manage(p.newContext()),g=new Ne(u,y,D=>{f=D},a,{computableCtx:l,blockCtx:e,mlEnv:s});g.evaluateBundle(o.content);const b=g.runCallback(t.handle);g.resetComputableCtx();const F=g.computableHelper.computablesToResolve;if(Object.keys(F).length===0){const D=g.importObjectUniversal(b);return Zr(t.handle,D,l.unstableMarker===void 0,-1,l.unstableMarker),{ir:D}}let x=0;return ee().logOutputStatus&&console.log(`Output ${t.handle} scaffold calculated (not all computables resolved yet).`),d=!0,{ir:F,postprocessValue:(D,{unstableMarker:U,stable:M})=>{for(const[N,E]of Object.entries(D))g.runCallback(N,E);const T=g.importObjectUniversal(b);return x++,Zr(t.handle,T,M,x,U),T}}}catch(p){throw d=!1,p}finally{d||u.dispose()}},i)}function Bi(s,e,t,...r){const{code:n,featureFlags:i}=t,o=new ge.Scope;try{const a=o.manage(s.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let c;a.setInterruptHandler(()=>c===void 0?!1:Date.now()>c.deadline);const l=o.manage(a.newContext()),u=new Ne(o,l,d=>{c=d},i);return u.evaluateBundle(n.content),u.importObjectUniversal(u.runCallback(e.handle,...r))}finally{o.dispose()}}function xi(s){return O.isConfigLambda(s)?s.isActive===!0:ti(s)}function Fe(s,e,t,r,n,i={}){if(O.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return ji(s,e,t,r,n,i)}else return $i(s.driverKit,e,t,i)}function je(s,e){return Te(s.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=O.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}function Vi(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Br.omitBy((r,n)=>n.startsWith("__"));return Br.isDeepEqual(t(s),t(e))}function Ui(s,e,t){return J.Computable.make(r=>{var y,g,b,F,x,D,U,M;const n=r.accessor(s).node(),i=w.notEmpty(n.getKeyValueAsJson(mr)),o=w.notEmpty(n.getKeyValueAsJson(Le)),a=w.notEmpty(n.getKeyValueAsJson(Ae)),c=w.notEmpty(n.getKeyValueAsJson(fe)),l=w.notEmpty(n.getKeyValueAsJson(Ye)),u=new Map;for(const{id:T}of oe(c)){const N=n.traverse({field:W(T,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),E=N.getDataAsJson();let K;const de=n.traverse({field:W(T,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(de!==void 0){const Y=de.getDataAsJson(),G=n.getField({field:W(T,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=n.getField({field:W(T,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:Y,stale:!Vi(E,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((g=X.value)==null?void 0:g.getError())!==void 0,outputsError:((b=G.error)==null?void 0:b.getDataAsString())??((x=(F=G.value)==null?void 0:F.getError())==null?void 0:x.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((M=(U=X.value)==null?void 0:U.getError())==null?void 0:M.getDataAsString()),finished:(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())&&(X.value!==void 0&&X.value.getIsReadyOrError()||X.error!==void 0&&X.error.getIsReadyOrError())}}u.set(T,{currentArguments:E,prod:K,argsRid:N.resourceInfo.id})}const d=Ke(c,T=>{const N=je(n,T),E=u.get(T),K=E.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>N.cfg,()=>K,{argsRid:E.argsRid,blockPackRid:N.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...oe(c)].map(({id:T,label:N,renderingMode:E})=>{var j,$,V,z,q;const K=w.notEmpty(u.get(T)),de=w.notEmpty(d.nodes.get(T));let Y="NotCalculated";K.prod!==void 0&&(p.has(T)?Y="Limbo":Y=K.prod.finished?"Done":"Running");const G=je(n,T),{sections:X,title:m,inputsValid:v,sdkVersion:C,featureFlags:S,isIncompatibleWithRuntime:k}=Te(G,({bpId:ce,cfg:ve})=>{if(!t.runtimeCapabilities.checkCompatibility(ve.featureFlags))return{isIncompatibleWithRuntime:!0,featureFlags:ve.featureFlags};const lt=Sr(s,T),pe=O.extractCodeWithInfo(ve);return{sections:Fe(t,lt,ve.sections,pe,ce).wrap({recover:Ee=>(t.logger.error("Error in block model sections"),t.logger.error(Ee),[])}),title:Te(ve.title,Ee=>Fe(t,lt,Ee,pe,ce).wrap({recover:Ln=>(t.logger.error("Error in block model title"),t.logger.error(Ln),"Invalid title")})),inputsValid:Fe(t,lt,ve.inputsValid,pe,ce).wrap({recover:Ee=>(t.logger.error("Error in block model argsValid"),t.logger.error(Ee),!1)}),sdkVersion:pe==null?void 0:pe.sdkVersion,featureFlags:(pe==null?void 0:pe.featureFlags)??{},isIncompatibleWithRuntime:!1}})||{},R=n.traverse({field:W(T,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),I=Te(G,({info:ce})=>t.blockUpdateWatcher.get({currentSpec:ce.source,settings:R}));return{projectResourceId:h.resourceIdToString(s.rid),id:T,label:m??N,title:m??N,renderingMode:E,stale:((j=K.prod)==null?void 0:j.stale)!==!1||Y==="Limbo",missingReference:de.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",T)],downstreams:[...d.traverseIdsExcludingRoots("downstream",T)],calculationStatus:Y,outputErrors:(($=K.prod)==null?void 0:$.outputError)===!0,outputsError:(V=K.prod)==null?void 0:V.outputsError,exportsError:(z=K.prod)==null?void 0:z.exportsError,settings:R,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(q=G==null?void 0:G.info)==null?void 0:q.source,updates:I,sdkVersion:C,featureFlags:S,isIncompatibleWithRuntime:k,navigationState:e.getState(T)}});return{meta:a,created:new Date(i),lastModified:new Date(o),authorMarker:n.getKeyValueAsJson(ar),blocks:f}},{postprocessValue:r=>{const n=new Set,i=new Set;return{...r,blocks:r.blocks.map(o=>{var u,d;o.inputsValid||n.add(o.id),o.stale&&i.add(o.id);const a=o.stale||o.upstreams.findIndex(p=>i.has(p))!==-1,c=(a||o.outputErrors)&&!!o.inputsValid&&!o.missingReference&&o.upstreams.findIndex(p=>n.has(p))===-1,l={...o,canRun:c,stale:a,updateSuggestions:((u=o.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=o.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Mi(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,yr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getUrl(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,wr)){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 qi(s,e){if(s!==void 0)return J.Computable.make(t=>Mi(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.url}}}).withStableType()}function Ji(s,e,t){return J.Computable.make(r=>{var a;const n=r.accessor(s).node(),i=je(n,e),o=(a=n.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:fn,assertFieldType:"Input"}))==null?void 0:a.persist();return{url:qi(o,t),sdkVersion:i==null?void 0:i.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Pn(s,e,t){if(t===void 0)return J.Computable.make(o=>Pn(s,e,o),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=Sr(s,e),i=n.uiState(t);return{author:r.getKeyValueAsJson(ir(e)),args:w.deepFreeze(JSON.parse(n.args(t))),ui:i!==void 0?w.deepFreeze(JSON.parse(i)):void 0}}function Gi(s,e,t){const r="outputs#"+h.resourceIdToString(s.rid)+"#"+e;return J.Computable.make(n=>{ee().logOutputRecalculations&&console.log(`blockOutput recalculation : ${r} (${n.changeSourceMarker}; ${n.bodyInvocations} invocations)`);const i=n.accessor(s).node(),o=vn(s,e);return Te(je(i,e),({cfg:a,bpId:c})=>{const l={};for(const[u,d]of Object.entries(a.outputs)){const p=Fe(t,o,d,O.extractCodeWithInfo(a),c);l[u]=J.Computable.wrapError(p,1)}return l})},{key:r}).withStableType()}function _i(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),n=w.notEmpty(r.getKeyValueAsJson(fe)),i=[];for(const{id:o}of oe(n)){const a=je(r,o);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,u])=>u).filter(u=>xi(u)).map(u=>u);if(c.length===0)continue;const l=vn(r.persist(),o);for(const u of c)i.push(J.Computable.wrapError(Fe(e,l,u,O.extractCodeWithInfo(a.cfg),a.bpId)))}return i})}class Ki{constructor(){P(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new J.ChangeSource});return}r.state={...t},r.change.markChanged("navigation state changed")}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...O.DefaultNavigationState},change:new J.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return J.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged("block deleted"))}}function Hi(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=w.notEmpty(t.getKeyValueAsJson(fe));return{listOfBlocks:[...oe(r)].map(n=>n.id)}})}const Wi="1",zi="BlockFrontendState/";async function Xi(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,Xe);if(r!==$e){if(r===Wi)await Yi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,Xe,JSON.stringify($e)),await t.commit()}})}async function Yi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,fe),s.listKeyValues(e)]),n=new Map(r.map(i=>[i.key,i.value]));for(const i of oe(t)){const o=zi+i.id,a=n.get(o),c=a?w.cachedDeserialize(a):{},l=s.createJsonGzValue(c),u=h.field(e,W(i.id,"uiState"));s.createField(u,"Dynamic",l),s.deleteKValue(e,o)}}function es(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class st{constructor(e,t,r){P(this,"rid");P(this,"overview");P(this,"overviewLight");P(this,"navigationStates",new Ki);P(this,"blockComputables",new Map);P(this,"blockFrontends",new Map);P(this,"activeConfigs");P(this,"refreshLoopResult");P(this,"abortController",new AbortController);P(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Ui(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=Hi(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=_i(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ge(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Xs.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,i=te.randomUUID()){const o=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=O.extractConfig(a);return await ie(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.addBlock({id:i,label:e,renderingMode:c.renderingMode},{args:ne(c.initialArgs),uiState:ne(c.initialUiState),blockPack:o},r)),await this.projectTree.refreshState(),i}async duplicateBlock(e,t,r=void 0,n=te.randomUUID()){return await ie(this.env.projectHelper,this.env.pl,this.rid,r,i=>i.duplicateBlock(e,n,t)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,n){const i=await this.env.bpPreparer.prepare(t),o=O.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ie(this.env.projectHelper,this.env.pl,this.rid,n,a=>a.migrateBlockPack(e,i,r?{args:o.initialArgs,uiState:o.initialUiState}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ie(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 ie(this.env.projectHelper,this.env.pl,this.rid,t,r=>{const n=r.structure;if(n.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const i=n.groups[0];if(i.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${i.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const o={groups:[{id:i.id,label:i.label,blocks:e.map(a=>{const c=i.blocks.find(l=>l.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(o)}),await this.projectTree.refreshState()}async runBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,args:t}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,n=>n.setStates([{blockId:e,uiState:t}])),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,n){await ie(this.env.projectHelper,this.env.pl,this.rid,n,i=>{i.setStates([{blockId:e,args:t,uiState:r}])}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ie(this.env.projectHelper,this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const n=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,W(e,"blockPack")))).value),i=h.ensureResourceIdNotNull((await r.getField(h.field(n,h.Pl.HolderRefField))).value),o=await r.getResourceData(i,!1),a=O.extractConfig(w.cachedDeserialize(w.notEmpty(o.data)).config);await ie(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:a.initialArgs,uiState:a.initialUiState}])}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=Gi(this.projectTree.entry(),e,this.env),i={fullState:J.Computable.make(o=>({argsAndUiState:Pn(this.projectTree.entry(),e,o),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:o=>{var u,d,p;const a=(p=(d=(u=o.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=a&&Zi(a)&&o.outputs!==void 0?ta(o.outputs):o.outputs;return{...o.argsAndUiState,outputs:l,navigationState:o.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,i),i}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Ji(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Xi(e.pl,t),await Ge(e.projectHelper,e.pl,t,n=>{});const r=await We.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Qi},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((o,a)=>{var c,l;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((l=o.data)==null?void 0:l.byteLength)??0)});const i=We.treeDumpStats(n);await De.writeFile(`${h.resourceIdToString(t)}.json`,es(n)),await De.writeFile(`${h.resourceIdToString(t)}.stats.json`,es(i))}return new st(e,t,r)}}function Qi(s){if(s.type.name.startsWith("StreamWorkdir/"))return[];switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function Zi(s){return!ea(s,"1.26.0")}function ea(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 ta(s){const e={};for(const[t,r]of Object.entries(s)){if(r.ok){e[t]=r;continue}e[t]={ok:!1,errors:r.errors.map(n=>typeof n=="string"?n:n.type=="PlError"&&n.fullMessage!==void 0?n.fullMessage:n.message),moreErrors:r.moreErrors}}return e}const Cr={logger:new w.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},frontendDownloadDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,withGunzip:!0,nConcurrentDownloads:50},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3},pFrameDriverOps:{pFrameConcurrency:1,pTableConcurrency:1,pFrameCacheMaxCount:18,pFramesCacheMaxSize:8*1024*1024*1024}};function Pr(s){return{blobDownloadPath:_.join(s,"download"),blobDownloadRangesCachePath:_.join(s,"downloadRangesCache"),downloadBlobToURLPath:_.join(s,"downloadToURL"),pframesSpillPath:_.join(s,"pframes")}}const Rn={...Cr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function kn(s){return{...Pr(s),frontendDownloadPath:_.join(s,"frontend")}}function ra(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var _e={exports:{}},gt,ts;function nt(){if(ts)return gt;ts=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return gt={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:s,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},gt}var mt,rs;function ot(){return rs||(rs=1,mt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),mt}var ss;function xe(){return ss||(ss=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=nt(),i=ot();e=s.exports={};const o=e.re=[],a=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],y=b=>{for(const[F,x]of f)b=b.split(`${F}*`).join(`${F}{0,${x}}`).split(`${F}+`).join(`${F}{1,${x}}`);return b},g=(b,F,x)=>{const D=y(F),U=d++;i(b,U,F),u[b]=U,c[U]=F,l[U]=D,o[U]=new RegExp(F,x?"g":void 0),a[U]=new RegExp(D,x?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),g("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${p}+`),g("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),g("FULL",`^${c[u.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),g("LOOSE",`^${c[u.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),g("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",c[u.COERCE],!0),g("COERCERTLFULL",c[u.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(_e,_e.exports)),_e.exports}var vt,ns;function Rr(){if(ns)return vt;ns=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return vt=r=>r?typeof r!="object"?s:r:e,vt}var yt,os;function En(){if(os)return yt;os=1;const s=/^[0-9]+$/,e=(r,n)=>{const i=s.test(r),o=s.test(n);return i&&o&&(r=+r,n=+n),r===n?0:i&&!o?-1:o&&!i?1:r<n?-1:1};return yt={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},yt}var wt,is;function re(){if(is)return wt;is=1;const s=ot(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=nt(),{safeRe:r,t:n}=xe(),i=Rr(),{compareIdentifiers:o}=En();class a{constructor(l,u){if(u=i(u),l instanceof a){if(l.loose===!!u.loose&&l.includePrerelease===!!u.includePrerelease)return l;l=l.version}else if(typeof l!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof l}".`);if(l.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",l,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=l.trim().match(u.loose?r[n.LOOSE]:r[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${l}`);if(this.raw=l,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(p=>{if(/^[0-9]+$/.test(p)){const f=+p;if(f>=0&&f<t)return f}return p}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(l){if(s("SemVer.compare",this.version,this.options,l),!(l instanceof a)){if(typeof l=="string"&&l===this.version)return 0;l=new a(l,this.options)}return l.version===this.version?0:this.compareMain(l)||this.comparePre(l)}compareMain(l){return l instanceof a||(l=new a(l,this.options)),o(this.major,l.major)||o(this.minor,l.minor)||o(this.patch,l.patch)}comparePre(l){if(l instanceof a||(l=new a(l,this.options)),this.prerelease.length&&!l.prerelease.length)return-1;if(!this.prerelease.length&&l.prerelease.length)return 1;if(!this.prerelease.length&&!l.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=l.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return o(d,p)}while(++u)}compareBuild(l){l instanceof a||(l=new a(l,this.options));let u=0;do{const d=this.build[u],p=l.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return o(d,p)}while(++u)}inc(l,u,d){if(l.startsWith("pre")){if(!u&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(u){const p=`-${u}`.match(this.options.loose?r[n.PRERELEASELOOSE]:r[n.PRERELEASE]);if(!p||p[1]!==u)throw new Error(`invalid identifier: ${u}`)}}switch(l){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),o(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${l}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return wt=a,wt}var bt,as;function Ce(){if(as)return bt;as=1;const s=re();return bt=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(i){if(!n)return null;throw i}},bt}var St,cs;function sa(){if(cs)return St;cs=1;const s=Ce();return St=(t,r)=>{const n=s(t,r);return n?n.version:null},St}var Ct,ls;function na(){if(ls)return Ct;ls=1;const s=Ce();return Ct=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},Ct}var Pt,us;function oa(){if(us)return Pt;us=1;const s=re();return Pt=(t,r,n,i,o)=>{typeof n=="string"&&(o=i,i=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,i,o).version}catch{return null}},Pt}var Rt,ds;function ia(){if(ds)return Rt;ds=1;const s=Ce();return Rt=(t,r)=>{const n=s(t,null,!0),i=s(r,null,!0),o=n.compare(i);if(o===0)return null;const a=o>0,c=a?n:i,l=a?i:n,u=!!c.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(c)===0)return l.minor&&!l.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==i.major?p+"major":n.minor!==i.minor?p+"minor":n.patch!==i.patch?p+"patch":"prerelease"},Rt}var kt,ps;function aa(){if(ps)return kt;ps=1;const s=re();return kt=(t,r)=>new s(t,r).major,kt}var Et,fs;function ca(){if(fs)return Et;fs=1;const s=re();return Et=(t,r)=>new s(t,r).minor,Et}var Ot,hs;function la(){if(hs)return Ot;hs=1;const s=re();return Ot=(t,r)=>new s(t,r).patch,Ot}var Tt,gs;function ua(){if(gs)return Tt;gs=1;const s=Ce();return Tt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},Tt}var Ft,ms;function le(){if(ms)return Ft;ms=1;const s=re();return Ft=(t,r,n)=>new s(t,n).compare(new s(r,n)),Ft}var It,vs;function da(){if(vs)return It;vs=1;const s=le();return It=(t,r,n)=>s(r,t,n),It}var Dt,ys;function pa(){if(ys)return Dt;ys=1;const s=le();return Dt=(t,r)=>s(t,r,!0),Dt}var $t,ws;function kr(){if(ws)return $t;ws=1;const s=re();return $t=(t,r,n)=>{const i=new s(t,n),o=new s(r,n);return i.compare(o)||i.compareBuild(o)},$t}var Lt,bs;function fa(){if(bs)return Lt;bs=1;const s=kr();return Lt=(t,r)=>t.sort((n,i)=>s(n,i,r)),Lt}var At,Ss;function ha(){if(Ss)return At;Ss=1;const s=kr();return At=(t,r)=>t.sort((n,i)=>s(i,n,r)),At}var Nt,Cs;function it(){if(Cs)return Nt;Cs=1;const s=le();return Nt=(t,r,n)=>s(t,r,n)>0,Nt}var jt,Ps;function Er(){if(Ps)return jt;Ps=1;const s=le();return jt=(t,r,n)=>s(t,r,n)<0,jt}var Bt,Rs;function On(){if(Rs)return Bt;Rs=1;const s=le();return Bt=(t,r,n)=>s(t,r,n)===0,Bt}var xt,ks;function Tn(){if(ks)return xt;ks=1;const s=le();return xt=(t,r,n)=>s(t,r,n)!==0,xt}var Vt,Es;function Or(){if(Es)return Vt;Es=1;const s=le();return Vt=(t,r,n)=>s(t,r,n)>=0,Vt}var Ut,Os;function Tr(){if(Os)return Ut;Os=1;const s=le();return Ut=(t,r,n)=>s(t,r,n)<=0,Ut}var Mt,Ts;function Fn(){if(Ts)return Mt;Ts=1;const s=On(),e=Tn(),t=it(),r=Or(),n=Er(),i=Tr();return Mt=(a,c,l,u)=>{switch(c){case"===":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a===l;case"!==":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a!==l;case"":case"=":case"==":return s(a,l,u);case"!=":return e(a,l,u);case">":return t(a,l,u);case">=":return r(a,l,u);case"<":return n(a,l,u);case"<=":return i(a,l,u);default:throw new TypeError(`Invalid operator: ${c}`)}},Mt}var qt,Fs;function ga(){if(Fs)return qt;Fs=1;const s=re(),e=Ce(),{safeRe:t,t:r}=xe();return qt=(i,o)=>{if(i instanceof s)return i;if(typeof i=="number"&&(i=String(i)),typeof i!="string")return null;o=o||{};let a=null;if(!o.rtl)a=i.match(o.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=o.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(i))&&(!a||a.index+a[0].length!==i.length);)(!a||y.index+y[0].length!==a.index+a[0].length)&&(a=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(a===null)return null;const c=a[2],l=a[3]||"0",u=a[4]||"0",d=o.includePrerelease&&a[5]?`-${a[5]}`:"",p=o.includePrerelease&&a[6]?`+${a[6]}`:"";return e(`${c}.${l}.${u}${d}${p}`,o)},qt}var Jt,Is;function ma(){if(Is)return Jt;Is=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const i=this.map.keys().next().value;this.delete(i)}this.map.set(t,r)}return this}}return Jt=s,Jt}var Gt,Ds;function ue(){if(Ds)return Gt;Ds=1;const s=/\s+/g;class e{constructor(v,C){if(C=n(C),v instanceof e)return v.loose===!!C.loose&&v.includePrerelease===!!C.includePrerelease?v:new e(v.raw,C);if(v instanceof i)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=C,this.loose=!!C.loose,this.includePrerelease=!!C.includePrerelease,this.raw=v.trim().replace(s," "),this.set=this.raw.split("||").map(S=>this.parseRange(S.trim())).filter(S=>S.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const S=this.set[0];if(this.set=this.set.filter(k=>!g(k[0])),this.set.length===0)this.set=[S];else if(this.set.length>1){for(const k of this.set)if(k.length===1&&b(k[0])){this.set=[k];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let v=0;v<this.set.length;v++){v>0&&(this.formatted+="||");const C=this.set[v];for(let S=0;S<C.length;S++)S>0&&(this.formatted+=" "),this.formatted+=C[S].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const S=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,k=r.get(S);if(k)return k;const R=this.options.loose,I=R?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];v=v.replace(I,G(this.options.includePrerelease)),o("hyphen replace",v),v=v.replace(c[l.COMPARATORTRIM],u),o("comparator trim",v),v=v.replace(c[l.TILDETRIM],d),o("tilde trim",v),v=v.replace(c[l.CARETTRIM],p),o("caret trim",v);let j=v.split(" ").map(q=>x(q,this.options)).join(" ").split(/\s+/).map(q=>Y(q,this.options));R&&(j=j.filter(q=>(o("loose invalid filter",q,this.options),!!q.match(c[l.COMPARATORLOOSE])))),o("range list",j);const $=new Map,V=j.map(q=>new i(q,this.options));for(const q of V){if(g(q))return[q];$.set(q.value,q)}$.size>1&&$.has("")&&$.delete("");const z=[...$.values()];return r.set(S,z),z}intersects(v,C){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(S=>F(S,C)&&v.set.some(k=>F(k,C)&&S.every(R=>k.every(I=>R.intersects(I,C)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new a(v,this.options)}catch{return!1}for(let C=0;C<this.set.length;C++)if(X(this.set[C],v,this.options))return!0;return!1}}Gt=e;const t=ma(),r=new t,n=Rr(),i=at(),o=ot(),a=re(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=xe(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=nt(),g=m=>m.value==="<0.0.0-0",b=m=>m.value==="",F=(m,v)=>{let C=!0;const S=m.slice();let k=S.pop();for(;C&&S.length;)C=S.every(R=>k.intersects(R,v)),k=S.pop();return C},x=(m,v)=>(o("comp",m,v),m=T(m,v),o("caret",m),m=U(m,v),o("tildes",m),m=E(m,v),o("xrange",m),m=de(m,v),o("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",U=(m,v)=>m.trim().split(/\s+/).map(C=>M(C,v)).join(" "),M=(m,v)=>{const C=v.loose?c[l.TILDELOOSE]:c[l.TILDE];return m.replace(C,(S,k,R,I,j)=>{o("tilde",m,S,k,R,I,j);let $;return D(k)?$="":D(R)?$=`>=${k}.0.0 <${+k+1}.0.0-0`:D(I)?$=`>=${k}.${R}.0 <${k}.${+R+1}.0-0`:j?(o("replaceTilde pr",j),$=`>=${k}.${R}.${I}-${j} <${k}.${+R+1}.0-0`):$=`>=${k}.${R}.${I} <${k}.${+R+1}.0-0`,o("tilde return",$),$})},T=(m,v)=>m.trim().split(/\s+/).map(C=>N(C,v)).join(" "),N=(m,v)=>{o("caret",m,v);const C=v.loose?c[l.CARETLOOSE]:c[l.CARET],S=v.includePrerelease?"-0":"";return m.replace(C,(k,R,I,j,$)=>{o("caret",m,k,R,I,j,$);let V;return D(R)?V="":D(I)?V=`>=${R}.0.0${S} <${+R+1}.0.0-0`:D(j)?R==="0"?V=`>=${R}.${I}.0${S} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.0${S} <${+R+1}.0.0-0`:$?(o("replaceCaret pr",$),R==="0"?I==="0"?V=`>=${R}.${I}.${j}-${$} <${R}.${I}.${+j+1}-0`:V=`>=${R}.${I}.${j}-${$} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.${j}-${$} <${+R+1}.0.0-0`):(o("no pr"),R==="0"?I==="0"?V=`>=${R}.${I}.${j}${S} <${R}.${I}.${+j+1}-0`:V=`>=${R}.${I}.${j}${S} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.${j} <${+R+1}.0.0-0`),o("caret return",V),V})},E=(m,v)=>(o("replaceXRanges",m,v),m.split(/\s+/).map(C=>K(C,v)).join(" ")),K=(m,v)=>{m=m.trim();const C=v.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return m.replace(C,(S,k,R,I,j,$)=>{o("xRange",m,S,k,R,I,j,$);const V=D(R),z=V||D(I),q=z||D(j),ce=q;return k==="="&&ce&&(k=""),$=v.includePrerelease?"-0":"",V?k===">"||k==="<"?S="<0.0.0-0":S="*":k&&ce?(z&&(I=0),j=0,k===">"?(k=">=",z?(R=+R+1,I=0,j=0):(I=+I+1,j=0)):k==="<="&&(k="<",z?R=+R+1:I=+I+1),k==="<"&&($="-0"),S=`${k+R}.${I}.${j}${$}`):z?S=`>=${R}.0.0${$} <${+R+1}.0.0-0`:q&&(S=`>=${R}.${I}.0${$} <${R}.${+I+1}.0-0`),o("xRange return",S),S})},de=(m,v)=>(o("replaceStars",m,v),m.trim().replace(c[l.STAR],"")),Y=(m,v)=>(o("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?l.GTE0PRE:l.GTE0],"")),G=m=>(v,C,S,k,R,I,j,$,V,z,q,ce)=>(D(S)?C="":D(k)?C=`>=${S}.0.0${m?"-0":""}`:D(R)?C=`>=${S}.${k}.0${m?"-0":""}`:I?C=`>=${C}`:C=`>=${C}${m?"-0":""}`,D(V)?$="":D(z)?$=`<${+V+1}.0.0-0`:D(q)?$=`<${V}.${+z+1}.0-0`:ce?$=`<=${V}.${z}.${q}-${ce}`:m?$=`<${V}.${z}.${+q+1}-0`:$=`<=${$}`,`${C} ${$}`.trim()),X=(m,v,C)=>{for(let S=0;S<m.length;S++)if(!m[S].test(v))return!1;if(v.prerelease.length&&!C.includePrerelease){for(let S=0;S<m.length;S++)if(o(m[S].semver),m[S].semver!==i.ANY&&m[S].semver.prerelease.length>0){const k=m[S].semver;if(k.major===v.major&&k.minor===v.minor&&k.patch===v.patch)return!0}return!1}return!0};return Gt}var _t,$s;function at(){if($s)return _t;$s=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(" "),o("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,o("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new a(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(o("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new a(u,this.options)}catch{return!1}return i(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||i(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||i(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}_t=e;const t=Rr(),{safeRe:r,t:n}=xe(),i=Fn(),o=ot(),a=re(),c=ue();return _t}var Kt,Ls;function ct(){if(Ls)return Kt;Ls=1;const s=ue();return Kt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},Kt}var Ht,As;function va(){if(As)return Ht;As=1;const s=ue();return Ht=(t,r)=>new s(t,r).set.map(n=>n.map(i=>i.value).join(" ").trim().split(" ")),Ht}var Wt,Ns;function ya(){if(Ns)return Wt;Ns=1;const s=re(),e=ue();return Wt=(r,n,i)=>{let o=null,a=null,c=null;try{c=new e(n,i)}catch{return null}return r.forEach(l=>{c.test(l)&&(!o||a.compare(l)===-1)&&(o=l,a=new s(o,i))}),o},Wt}var zt,js;function wa(){if(js)return zt;js=1;const s=re(),e=ue();return zt=(r,n,i)=>{let o=null,a=null,c=null;try{c=new e(n,i)}catch{return null}return r.forEach(l=>{c.test(l)&&(!o||a.compare(l)===1)&&(o=l,a=new s(o,i))}),o},zt}var Xt,Bs;function ba(){if(Bs)return Xt;Bs=1;const s=re(),e=ue(),t=it();return Xt=(n,i)=>{n=new e(n,i);let o=new s("0.0.0");if(n.test(o)||(o=new s("0.0.0-0"),n.test(o)))return o;o=null;for(let a=0;a<n.set.length;++a){const c=n.set[a];let l=null;c.forEach(u=>{const d=new s(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!o||t(o,l))&&(o=l)}return o&&n.test(o)?o:null},Xt}var Yt,xs;function Sa(){if(xs)return Yt;xs=1;const s=ue();return Yt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Yt}var Qt,Vs;function Fr(){if(Vs)return Qt;Vs=1;const s=re(),e=at(),{ANY:t}=e,r=ue(),n=ct(),i=it(),o=Er(),a=Tr(),c=Or();return Qt=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,g,b,F,x;switch(p){case">":y=i,g=a,b=o,F=">",x=">=";break;case"<":y=o,g=c,b=i,F="<",x="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const U=d.set[D];let M=null,T=null;if(U.forEach(N=>{N.semver===t&&(N=new e(">=0.0.0")),M=M||N,T=T||N,y(N.semver,M.semver,f)?M=N:b(N.semver,T.semver,f)&&(T=N)}),M.operator===F||M.operator===x||(!T.operator||T.operator===F)&&g(u,T.semver))return!1;if(T.operator===x&&b(u,T.semver))return!1}return!0},Qt}var Zt,Us;function Ca(){if(Us)return Zt;Us=1;const s=Fr();return Zt=(t,r,n)=>s(t,r,">",n),Zt}var er,Ms;function Pa(){if(Ms)return er;Ms=1;const s=Fr();return er=(t,r,n)=>s(t,r,"<",n),er}var tr,qs;function Ra(){if(qs)return tr;qs=1;const s=ue();return tr=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),tr}var rr,Js;function ka(){if(Js)return rr;Js=1;const s=ct(),e=le();return rr=(t,r,n)=>{const i=[];let o=null,a=null;const c=t.sort((p,f)=>e(p,f,n));for(const p of c)s(p,r,n)?(a=p,o||(o=p)):(a&&i.push([o,a]),a=null,o=null);o&&i.push([o,null]);const l=[];for(const[p,f]of i)p===f?l.push(p):!f&&p===c[0]?l.push("*"):f?p===c[0]?l.push(`<=${f}`):l.push(`${p} - ${f}`):l.push(`>=${p}`);const u=l.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},rr}var sr,Gs;function Ea(){if(Gs)return sr;Gs=1;const s=ue(),e=at(),{ANY:t}=e,r=ct(),n=le(),i=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const g of d.set){for(const b of p.set){const F=c(g,b,f);if(y=y||F!==null,F)continue e}if(y)return!1}return!0},o=[new e(">=0.0.0-0")],a=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=o:d=a}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=a}const y=new Set;let g,b;for(const E of d)E.operator===">"||E.operator===">="?g=l(g,E,f):E.operator==="<"||E.operator==="<="?b=u(b,E,f):y.add(E.semver);if(y.size>1)return null;let F;if(g&&b){if(F=n(g.semver,b.semver,f),F>0)return null;if(F===0&&(g.operator!==">="||b.operator!=="<="))return null}for(const E of y){if(g&&!r(E,String(g),f)||b&&!r(E,String(b),f))return null;for(const K of p)if(!r(E,String(K),f))return!1;return!0}let x,D,U,M,T=b&&!f.includePrerelease&&b.semver.prerelease.length?b.semver:!1,N=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1;T&&T.prerelease.length===1&&b.operator==="<"&&T.prerelease[0]===0&&(T=!1);for(const E of p){if(M=M||E.operator===">"||E.operator===">=",U=U||E.operator==="<"||E.operator==="<=",g){if(N&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===N.major&&E.semver.minor===N.minor&&E.semver.patch===N.patch&&(N=!1),E.operator===">"||E.operator===">="){if(x=l(g,E,f),x===E&&x!==g)return!1}else if(g.operator===">="&&!r(g.semver,String(E),f))return!1}if(b){if(T&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===T.major&&E.semver.minor===T.minor&&E.semver.patch===T.patch&&(T=!1),E.operator==="<"||E.operator==="<="){if(D=u(b,E,f),D===E&&D!==b)return!1}else if(b.operator==="<="&&!r(b.semver,String(E),f))return!1}if(!E.operator&&(b||g)&&F!==0)return!1}return!(g&&U&&!b&&F!==0||b&&M&&!g&&F!==0||N||T)},l=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y>0?d:y<0||p.operator===">"&&d.operator===">="?p:d},u=(d,p,f)=>{if(!d)return p;const y=n(d.semver,p.semver,f);return y<0?d:y>0||p.operator==="<"&&d.operator==="<="?p:d};return sr=i,sr}var nr,_s;function Oa(){if(_s)return nr;_s=1;const s=xe(),e=nt(),t=re(),r=En(),n=Ce(),i=sa(),o=na(),a=oa(),c=ia(),l=aa(),u=ca(),d=la(),p=ua(),f=le(),y=da(),g=pa(),b=kr(),F=fa(),x=ha(),D=it(),U=Er(),M=On(),T=Tn(),N=Or(),E=Tr(),K=Fn(),de=ga(),Y=at(),G=ue(),X=ct(),m=va(),v=ya(),C=wa(),S=ba(),k=Sa(),R=Fr(),I=Ca(),j=Pa(),$=Ra(),V=ka(),z=Ea();return nr={parse:n,valid:i,clean:o,inc:a,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:g,compareBuild:b,sort:F,rsort:x,gt:D,lt:U,eq:M,neq:T,gte:N,lte:E,cmp:K,coerce:de,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:C,minVersion:S,validRange:k,outside:R,gtr:I,ltr:j,intersects:$,simplifyRange:V,subset:z,SemVer:t,re:s.re,src:s.src,tokens:s.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},nr}var Ta=Oa();const Fa=ra(Ta),Ia={minDelay:1500},Da="__no_updates__";class $a extends J.PollComputablePool{constructor(t,r,n={}){super({...n,...Ia},r);P(this,"http");P(this,"preferredUpdateChannel");this.registryProvider=t,this.http=n.http,this.preferredUpdateChannel=n.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${ne(t)}`;default:return Da}}async readValue(t){var r,n;try{const i=t.currentSpec;switch(i.type){case"dev-v1":try{const o=await gr(i.folder);return o===i.mtime?{suggestions:[]}:{mainSuggestion:{...i,mtime:o},suggestions:[]}}catch(o){return this.logger.warn(o),{suggestions:[]}}case"dev-v2":try{const o=await Z.tryLoadPackDescription(i.folder,this.logger);if(o===void 0)return{suggestions:[]};const a=await et(o);return a===i.mtime?{suggestions:[]}:{mainSuggestion:{...i,mtime:a},suggestions:[]}}catch(o){return this.logger.warn(o),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:o,skipVersion:a}=t.settings;if(o==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(i.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(i.channel===void 0)if(await c.getLatestOverview(i.id,Q.StableChannel))l=Q.StableChannel;else{if(await c.getLatestOverview(i.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(i.id)}`),{suggestions:[]};l=Q.AnyChannel}else l=i.channel;const u=await c.getUpdateSuggestions(i.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(o){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(y=>y.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:y,update:g})=>({type:y,update:{...i,id:{...i.id,version:g}}}));if(d===void 0)return{suggestions:p};if(a!==void 0&&Fa.lte(d,a))return{suggestions:p};const f={...i,id:{...i.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(o){return this.logger.warn(o),{suggestions:[]}}default:return{suggestions:[]}}}catch(i){return this.logger.warn(i),{suggestions:[]}}}resultsEqual(t,r){return ne(t)===ne(r)}}class Ks{constructor(){P(this,"resources",new Map);P(this,"disposeQueue",Promise.resolve())}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;w.isDisposable(r)?this.disposeQueue.then(()=>r[Symbol.dispose]()):w.isAsyncDisposable(r)&&this.disposeQueue.then(()=>r[Symbol.asyncDispose]())}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!0,this.check(t))}}}getByKey(e){const t=this.resources.get(e);if(t===void 0)throw new Error(`resource not found, key = ${e}`);return t.resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function Ie(s){return String(s.id)}const La=["Int","Long","Float","Double","String","Bytes"];function Oe(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}function Hs(s){return"partitionFilters"in s?{...s,partitionFilters:Oe(s.partitionFilters),filters:Oe(s.filters)}:{...s,partitionFilters:Oe(s.filters.filter(e=>e.column.type==="axis")),filters:Oe(s.filters.filter(e=>e.column.type==="column"))}}const we=(s,e)=>typeof e=="bigint"?e.toString():e;class Aa{constructor(e,t){P(this,"perFrame",new Map);P(this,"global");P(this,"disposeListeners",new Map);this.logger=e,this.ops=t,this.global=new ze.LRUCache({maxSize:this.ops.pFramesCacheMaxSize,dispose:(r,n,i)=>{var a,c;i==="evict"&&((a=this.perFrame.get(r.resource.pFrame))==null||a.delete(n)),((c=this.perFrame.get(r.resource.pFrame))==null?void 0:c.size)===0&&this.perFrame.delete(r.resource.pFrame);const o=this.disposeListeners.get(n);this.disposeListeners.delete(n),r.resource.disposeSignal.removeEventListener("abort",o),r.unref(),ee().logPFrameRequests&&this.logger.info(`calculateTableData cache - removed PTable ${n}`)}})}cache(e,t){const r=e.key;ee().logPFrameRequests&&this.logger.info(`calculateTableData cache - added PTable ${r} with size ${t}`),this.global.set(r,e,{size:t});let n=this.perFrame.get(e.resource.pFrame);n||(n=new ze.LRUCache({max:this.ops.pFrameCacheMaxCount,dispose:(o,a,c)=>{c==="evict"&&this.global.delete(a)}}),this.perFrame.set(e.resource.pFrame,n)),n.set(r,e);const i=()=>{var o;(o=this.perFrame.get(e.resource.pFrame))==null||o.delete(r),this.global.delete(r)};this.disposeListeners.set(r,i),e.resource.disposeSignal.addEventListener("abort",i)}}class Na{constructor(e,t,r,n){P(this,"pFramePromise");P(this,"abortController",new AbortController);P(this,"blobIdToResource",new Map);P(this,"blobHandleComputables",new Map);P(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)try{await r.awaitStableFullValue(this.disposeSignal)}catch(n){if(O.isAbortError(n))break;throw n}});P(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await Zs.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const i=(a,c)=>this.logger[a](c);for(const a of n)for(const c of Mo(a.data))this.blobIdToResource.set(Ie(c),c);const o=[...new Map(n.map(a=>({...a,data:qo(a.data,Ie)})).map(a=>[ne(a),a])).values()];try{const a=new Ys.PFrame(this.spillPath,i);a.setDataSource(this);const c=[];for(const l of o)a.addColumnSpec(l.id,l.spec),c.push(a.setColumnData(l.id,l.data,{signal:this.disposeSignal}));this.pFramePromise=Promise.all(c).then(()=>a).catch(l=>{throw this.dispose(),a.dispose(),new O.PFrameDriverError(`PFrame creation failed asynchronously, columns: ${JSON.stringify(o)}, error: ${O.ensureError(l)}`)})}catch(a){throw new O.PFrameDriverError(`PFrame creation failed synchronously, columns: ${JSON.stringify(o)}, error: ${O.ensureError(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 O.PFrameDriverError(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}dispose(){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState()}async[Symbol.asyncDispose](){this.dispose(),await this.pFramePromise.then(e=>e.dispose()).catch(()=>{})}}class or{constructor(e,t,r,n){P(this,"abortController",new AbortController);P(this,"combinedDisposeSignal");this.pFrame=e,this.pTablePromise=r,this.predecessor=n,this.combinedDisposeSignal=AbortSignal.any([t,this.abortController.signal])}get disposeSignal(){return this.combinedDisposeSignal}async[Symbol.asyncDispose](){var e;this.abortController.abort(),await this.pTablePromise.then(t=>t.dispose()).catch(()=>{}),(e=this.predecessor)==null||e.unref()}}class Ir{constructor(e,t,r,n){P(this,"pFrames");P(this,"pTables");P(this,"pTableCache");P(this,"frameConcurrencyLimiter");P(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const i=new w.ConcurrencyLimitingExecutor(n.pFrameConcurrency);this.frameConcurrencyLimiter=i,this.tableConcurrencyLimiter=new w.ConcurrencyLimitingExecutor(n.pTableConcurrency),this.pTableCache=new Aa(this.logger,n),this.pFrames=new class extends Ks{constructor(o,a,c){super(),this.blobDriver=o,this.logger=a,this.spillPath=c}acquire(o){return super.acquire(o)}getByKey(o){const a=super.tryGetByKey(o);if(!a)throw new O.PFrameDriverError(`PFrame not found, handle = ${o}`);return a}createNewResource(o){return ee().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,we)}`),new Na(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){try{return Ba(o)}catch(a){throw O.isPFrameDriverError(a)?a:new O.PFrameDriverError(`PFrame handle calculation failed, request: ${JSON.stringify(o,we)}, error: ${O.ensureError(a)}`)}}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Ks{constructor(o){super(),this.pFrames=o}getByKey(o){const a=super.tryGetByKey(o);if(!a)throw new O.PFrameDriverError(`PTable not found, handle = ${o}`);return a}createNewResource(o){ee().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,we)}`);const a=o.pFrameHandle,{pFramePromise:c,disposeSignal:l}=this.pFrames.getByKey(a);if(o.def.sorting.length>0){const d=this.acquire({...o,def:{...o.def,sorting:[]}}),{resource:{pTablePromise:p}}=d,f=p.then(y=>y.sort(o.def.sorting));return new or(a,l,f,d)}if(o.def.filters.length>0){const d=this.acquire({...o,def:{...o.def,filters:[]}}),{resource:{pTablePromise:p}}=d,f=p.then(y=>y.filter(o.def.filters));return new or(a,l,f,d)}const u=c.then(d=>d.createTable({src:He(o.def.src),filters:o.def.partitionFilters}));return new or(a,l,u)}calculateParamsKey(o){try{return ja(o)}catch(a){throw new O.PFrameDriverError(`PTable handle calculation failed, request: ${JSON.stringify(o)}, error: ${O.ensureError(a)}`)}}}(this.pFrames)}async pprofDump(){return await Ys.PFrame.pprofDump()}static async init(e,t,r,n){const i=Gn.resolve(r);return await w.emptyDir(i),new Ir(e,t,i,n)}createPFrame(e,t){const r=e.filter(i=>La.find(o=>o===i.spec.valueType)).map(i=>O.mapPObjectData(i,o=>We.isPlTreeNodeAccessor(o)?Wo(o):O.isDataInfo(o)?O.mapDataInfo(o,a=>a.resourceInfo):zo(i.spec,o))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t){const r=Hs(e),n=this.createPFrame(O.extractAllColumns(r.src),t),i=O.mapPTableDef(r,a=>a.id),o=this.pTables.acquire({def:i,pFrameHandle:n});return ee().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(o)}): ${JSON.stringify(O.mapPTableDef(r,a=>a.spec),we)}`),t.addOnDestroy(o.unref),o.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(a=>[ne(a),a])).values()],qualifications:[]}]:[]},{pFramePromise:n}=this.pFrames.getByKey(e);return{hits:(await(await n).findColumns(r)).hits.filter(a=>a.mappingVariants.length===0||a.mappingVariants.some(c=>c.qualifications.forHit.length===0&&c.qualifications.forQueries.every(l=>l.length===0))).map(a=>a.hit)}}async getColumnSpec(e,t){const{pFramePromise:r}=this.pFrames.getByKey(e);return await(await r).getColumnSpec(t)}async listColumns(e){const{pFramePromise:t}=this.pFrames.getByKey(e);return await(await t).listColumns()}async calculateTableData(e,t,r,n){ee().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,we)}`);const i=this.pTables.acquire({pFrameHandle:e,def:Hs(t)}),{resource:{pTablePromise:o,disposeSignal:a}}=i,c=await o,l=AbortSignal.any([n,a].filter(u=>!!u));return await this.frameConcurrencyLimiter.run(async()=>{try{const u=c.getSpec(),d=await c.getData([...u.keys()],{range:r,signal:l}),p=await c.getFootprint({withPredecessors:!0,signal:l});return this.pTableCache.cache(i,p),u.map((f,y)=>({spec:f,data:d[y]}))}catch(u){throw i.unref(),u}})}async getUniqueValues(e,t,r){ee().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,we)}`);const{pFramePromise:n,disposeSignal:i}=this.pFrames.getByKey(e),o=await n,a=AbortSignal.any([r,i].filter(c=>!!c));return await this.frameConcurrencyLimiter.run(async()=>await o.getUniqueValues({...t,filters:Oe(t.filters)},{signal:a}))}async getSpec(e){const{pTablePromise:t}=this.pTables.getByKey(e);return(await t).getSpec()}async getShape(e,t){const{pTablePromise:r,disposeSignal:n}=this.pTables.getByKey(e),i=await r,o=AbortSignal.any([t,n].filter(a=>!!a));return await this.tableConcurrencyLimiter.run(async()=>await i.getShape({signal:o}))}async getData(e,t,r,n){const{pTablePromise:i,disposeSignal:o}=this.pTables.getByKey(e),a=await i,c=AbortSignal.any([n,o].filter(l=>!!l));return await this.tableConcurrencyLimiter.run(async()=>await a.getData(t,{range:r,signal:c}))}}function He(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>He(e))};case"outer":return{type:"outer",primary:He(s.primary),secondary:s.secondary.map(e=>He(e))};default:w.assertNever(s)}}function ja(s){const e=te.createHash("sha256");return e.update(ne(s)),e.digest().toString("hex")}function Ba(s){const e=[...s].map(r=>O.mapPObjectData(r,n=>{let i;const o=n.type;switch(o){case"Json":i={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":i={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:Ie(c)}))};break;case"BinaryPartitioned":i={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([a,c])=>({key:a,value:[Ie(c.index),Ie(c.values)]}))};break;default:throw new O.PFrameDriverError(`unsupported resource type: ${JSON.stringify(o)}`)}return i.payload.sort((a,c)=>a.key.localeCompare(c.key)),i}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(ne(e)),t.digest().toString("hex")}async function In(s,e,t,r){const n={...Cr,...Pr(e),...r},i=new w.HmacSha256Signer(n.localSecret),o=H.createDownloadClient(n.logger,s,n.localProjections),a=H.createLogsClient(s,n.logger),c=H.createUploadBlobClient(s,n.logger),l=H.createUploadProgressClient(s,n.logger),u=await H.DownloadDriver.init(n.logger,o,a,n.blobDownloadPath,n.blobDownloadRangesCachePath,i,n.blobDriverOps),d=new H.DownloadBlobToURLDriver(n.logger,i,o,n.downloadBlobToURLPath,n.downloadBlobToURLDriverOps),p=new H.UploadDriver(n.logger,i,c,l,n.uploadDriverOps),f=new H.LogsStreamDriver(n.logger,a,n.logStreamDriverOps),y=new H.LogsDriver(n.logger,f,u),g=await H.LsDriver.init(n.logger,s,i,n.localProjections,n.openFileDialogCallback,n.virtualLocalStoragesOverride),b=await Ir.init(u,n.logger,n.pframesSpillPath,n.pFrameDriverOps),F=new H.DownloadUrlDriver(n.logger,s.httpDispatcher,t,i,n.frontendDownloadDriverOps);return{blobDriver:u,blobToURLDriver:d,logDriver:y,lsDriver:g,signer:i,uploadDriver:p,pFrameDriver:b,frontendDriver:F}}class xa{constructor(e){P(this,"enrichmentTargetsCache",new ze.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 Bi(this.quickJs,t.enrichmentTargets,O.extractCodeWithInfo(t),r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const i=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(i,{context:n}).value}}class Dr{constructor(e,t,r,n,i,o,a,c){P(this,"pl");P(this,"projectList");P(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=i,this.projectListTree=o,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}addRuntimeCapability(e,t=!0){this.env.runtimeCapabilities.addSupportedRequirement(e,t)}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const i=await Uo(n,e);return n.createField(h.field(this.projectListResourceId,t),"Dynamic",i),await n.commit(),await h.toGlobalResourceId(i)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ie(this.env.projectHelper,this.pl,e,r,n=>{n.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await st.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 w.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...Rn,...kn(t),...r};n.defaultTreeOptions.logStat=ee().logTreeStats,n.debugOps.dumpInitialTreeState=ee().dumpInitialTreeState;const i=await e.withWriteTx("MLInitialization",async b=>{const F=h.field(b.clientRoot,uo);b.createField(F,"Dynamic");const x=await b.getField(F);if(h.isNullResourceId(x.value)){const D=b.createEphemeral(rn);return b.lock(D),b.setField(F,D),await b.commit(),await D.globalId}else return x.value}),o=n.logger,a=await In(e,t,n.frontendDownloadPath,n),c=new Ze.RetryAgent(e.httpDispatcher),l=new tn(c),u=new Lo(l,a.signer,c),d=await ge.getQuickJS(),p=new O.RuntimeCapabilities;p.addSupportedRequirement("requiresModelAPIVersion",1);const f={pl:e,blockEventDispatcher:new w.BlockEventDispatcher,signer:a.signer,logger:o,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:n,bpPreparer:u,frontendDownloadDriver:a.frontendDriver,driverKit:a,blockUpdateWatcher:new $a(l,o,{minDelay:n.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:n.preferredUpdateChannel}),runtimeCapabilities:p,quickJs:d,projectHelper:new xa(d)},y=new J.WatchableValue([]),g=await fo(e,i,y,f);return new Dr(f,a,a.signer,i,y,g.tree,l,g.computable)}}async function Va(s,e){return await Pe(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new h.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Ua(s,e){return await Pe(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function Ma(s,e){return await Pe(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function qa(s,e){return await Pe(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function Ja(s,e){return await Pe(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Ga(s,e){return await Pe(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Ve(s.autoUpdateCdnUrl,s,e))}async function Pe(s,e,t){const r=Date.now(),n=[];for(;Ws(r)<s;){const i=Date.now();let o;try{o={ok:!0,value:await t()}}catch(l){o={ok:!1,error:l}}const a=Ws(i);n.push({elapsedMs:a,response:o});const c=1e3/e-a;c>0&&await Xs.setTimeout(c)}return n}async function Ve(s,e,t){const{body:r,statusCode:n}=await Ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),i=await r.text();return{statusCode:n,beginningOfBody:i.slice(0,e.bodyLimit)+"..."}}function Ws(s){return Date.now()-s}function be(s){const e=s.filter(o=>o.response.ok),t=s.length-e.length,{mean:r,median:n}=_a(s),i=`
1
+ "use strict";var Ao=Object.defineProperty;var Lr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Ar=s=>{throw TypeError(s)};var No=(s,e,t)=>e in s?Ao(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var C=(s,e,t)=>No(s,typeof e!="symbol"?e+"":e,t);var Nr=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Ar("Object expected");var r,o;t&&(r=e[Lr("asyncDispose")]),r===void 0&&(r=e[Lr("dispose")],t&&(o=r)),typeof r!="function"&&Ar("Object not disposable"),o&&(r=function(){try{o.call(this)}catch(i){return Promise.reject(i)}}),s.push([t,r,e])}else t&&s.push([t]);return e},jr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(n,a,c,l){return l=Error(c),l.name="SuppressedError",l.error=n,l.suppressed=a,l},o=n=>e=t?new r(n,e,"An error was suppressed during disposal"):(t=!0,n),i=n=>{for(;n=s.pop();)try{var a=n[1]&&n[1].call(n[2]);if(n[0])return Promise.resolve(a).then(i,c=>(o(c),i()))}catch(c){o(c)}if(t)throw e};return i()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Br=require("@milaboratories/pl-deployments"),Ze=require("undici"),Z=require("@platforma-sdk/block-tools"),ae=require("node:fs"),_=require("node:path"),jo=require("yaml"),w=require("@milaboratories/ts-helpers"),De=require("node:fs/promises"),Bo=require("@milaboratories/resolve-helper"),h=require("@milaboratories/pl-client"),We=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),L=require("@milaboratories/pl-model-backend"),ze=require("lru-cache"),xo=require("node:worker_threads"),zs=require("denque"),me=require("@platforma-sdk/workflow-tengo"),oe=require("canonicalize"),Vo=require("node:assert"),ge=require("quickjs-emscripten"),Uo=require("@milaboratories/pl-errors"),qo=require("remeda"),Xs=require("node:timers/promises"),H=require("@milaboratories/pl-drivers"),Ys=require("@milaboratories/pframes-rs-node"),Mo=require("node:diagnostics_channel"),Jo=require("node:stream/consumers"),Qs=require("node:os");function fr(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 Go=fr(_),Zs=fr(De),xr=fr(qo);async function Vr(s){try{return await Zs.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const _o=[Z.RegistryV1.PlPackageYamlConfigFile],Ko=[Z.RegistryV1.PlPackageJsonConfigFile],hr=["backend","dist","tengo","tpl","main.plj.gz"],gr=["config","dist","config.json"],eo=["frontend","dist"],Ur="block-model/dist/config.json",Ho="block-ui/package.json",Wo=[hr,gr,_o,Ko,eo];async function zo(s){return await Vr(_.join(s,...gr))!==void 0||await Vr(_.join(s,...hr))!==void 0}function ut(s,e){const t=Bo.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function qr(s,e){if(_.isAbsolute(s)||(s=_.resolve(s)),await zo(s))return{workflow:_.join(s,...hr),config:_.join(s,...gr),ui:_.join(s,...eo)};{const t=ut(s,Ur),r=ut(s,Ur),o=ut(s,Ho);return{workflow:t,config:r,ui:_.resolve(o,"..","dist")}}}async function Xo(s){try{return await ae.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Yo(s){try{return await ae.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function mr(s){let e=0n;for(const t of Wo){const r=_.join(s,...t),o=await Yo(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function et(s){const e=await ae.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await ae.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Qo{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}:{},n=await(await Ze.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of n){const{organization:c,package:l,latestMeta:u,latestVersion:d}=a,p={organization:c,name:l,version:d},f={id:p,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:p,registryUrl:r.url}};t.push({registryId:e.id,id:p,latestByChannel:{[Q.AnyChannel]:f,[Q.StableChannel]:f},allVersions:a.allVersions.map(y=>({version:y,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(o=>({...o,registryId:e.id}));case"local-dev":for(const o of await ae.promises.readdir(r.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const i=_.join(r.path,o.name),n=await Xo(_.join(i,Z.RegistryV1.PlPackageYamlConfigFile));if(n!==void 0){const a=Z.RegistryV1.PlPackageConfigData.parse(jo.parse(n)),c=await mr(i),l={organization:a.organization,name:a.package,version:"DEV"},u={id:l,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:i,mtime:c}};t.push({registryId:e.id,id:l,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let a=i,c=await Z.tryLoadPackDescription(a);if(c===void 0){for(const l of["block","meta"])if(a=_.join(i,l),c=await Z.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const l=await et(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),featureFlags:c.featureFlags,spec:{type:"dev-v2",folder:a,mtime:l}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return w.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 n;const o=(n=this.registries.find(a=>a.id===e))==null?void 0:n.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 to{constructor(e){C(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new Z.RegistryV2Reader(Z.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Zo={type:"remote-v2",url:"https://blocks.pl-open.science/"},en={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},tn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},rn={groups:[{id:"default",label:"Default",blocks:[]}]},sn={stagingRefreshTimestamp:0,blocksInLimbo:[]},on={label:"New Project"},nn={name:"UserProject",version:"2"},Xe="SchemaVersion",$e="2",vr="ProjectCreated",Le="ProjectLastModified",Ae="ProjectMeta",fe="ProjectStructure",Ye="BlockRenderingState",an="BlockArgsAuthor/";function ar(s){return`${an}${s}`}const cr="ProjectStructureAuthor",cn="__serviceTemplate_";function lr(s){return`${cn}${s}`}const dt=new Set(["blockPack","blockSettings","uiState","prodArgs","currentArgs","prodCtx","prodUiCtx","prodOutput"]);function W(s,e){return`${s}-${e}`}const ln=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function un(s){const e=s.match(ln);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const dn="projects",ro={name:"Projects",version:"1"},pn=s=>h.resourceTypesEqual(s.type,ro)?s.fields:[];async function fn(s,e,t,r){const o=await We.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:pn},r.logger);return{computable:J.Computable.make(n=>{const a=n.accessor(o.entry()).node(),c=t.getValue(n);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const d=a.traverse(u);if(d===void 0)continue;const p=w.notEmpty(d.getKeyValueAsJson(Ae)),f=w.notEmpty(d.getKeyValueAsJson(vr)),y=w.notEmpty(d.getKeyValueAsJson(Le));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const hn={name:"EphRenderTemplate",version:"1"},gn={name:"RenderTemplate",version:"1"};function tt(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const i=t?s.createEphemeral(hn):s.createStruct(gn),n=h.field(i,"template"),a=h.field(i,"inputs");return s.createField(n,"Input",e),s.createField(a,"Input",h.Pl.createPlMap(s,r,t)),s.lockInputs(i),h.Pl.futureRecord(s,i,o,"Output","outputs/")}const mn={name:"BContextEnd",version:"1"},vn={name:"BContext",version:"1"},yn="id",wn="parent/",bn=["context","result"];function Mr(s,e,t){return tt(s,e,!0,t,bn)}function Sn(s){const e=s.createEphemeral(mn);return s.lock(e),e}function Jr(s,e){if(e.length===0)return Sn(s);if(e.length===1)return e[0];const t=s.createEphemeral(vn);s.createField(h.field(t,yn),"Input",h.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(h.field(t,`${wn}${r}`),"Input",e[r]);return s.lock(t),t}function so(s,e){const t=new Map,r=(o,i,n)=>{const a=te.createHash("sha256");i.updateCacheKey(o,a,n);const c=a.digest("hex");if(!t.has(c)){const l=i.render(o,s,r,n);t.set(c,l)}return t.get(c)};return r(e.template,oo,e.hashToSource)}const Gr={updateCacheKey(s,e,t){e.update(L.PlTemplateLibV1.type.name).update(L.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue(L.PlTemplateLibV1.type,JSON.stringify(L.PlTemplateLibV1.fromV3Data(s,Se(s.name,r,s.sourceHash)).data))}},Ue={updateCacheKey(s,e,t){e.update(L.PlTemplateSoftwareV1.type.name).update(L.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash))},render(s,e,t,r){const o=L.PlTemplateSoftwareV1.fromV3Data(s,Se(s.name,r,s.sourceHash)),i=e.createStruct(L.PlTemplateSoftwareV1.type,o.data);return e.setKValue(i,L.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(o.name)),e.lock(i),i}},oo={updateCacheKey(s,e,t){e.update(L.PlTemplateV1.type.name).update(L.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(Se(s.name,t,s.sourceHash));const r=o=>(o.sort((i,n)=>i[0]===n[0]?0:i[0]<n[0]?-1:1),o);for(const[o,i]of r(Object.entries(s.libs??{})))e.update("lib:"+o),Gr.updateCacheKey(i,e,t);for(const[o,i]of r(Object.entries(s.software??{})))e.update("soft:"+o),Ue.updateCacheKey(i,e,t);for(const[o,i]of r(Object.entries(s.assets??{})))e.update("asset:"+o),Ue.updateCacheKey(i,e,t);for(const[o,i]of r(Object.entries(s.templates??{})))e.update("tpl:"+o),this.updateCacheKey(i,e,t)},render(s,e,t,r){const o=e.createStruct(L.PlTemplateV1.type,JSON.stringify(L.PlTemplateV1.fromV3Data(s,Se(s.name,r,s.sourceHash)).data));for(const[a,c]of Object.entries(s.libs??{})){const l=L.PlTemplateV1.libField(o,a);e.createField(l,"Input"),e.setField(l,t(c,Gr,r))}for(const[a,c]of Object.entries(s.software??{})){const l=L.PlTemplateV1.swField(o,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.assets??{})){const l=L.PlTemplateV1.swField(o,a);e.createField(l,"Input"),e.setField(l,t(c,Ue,r))}for(const[a,c]of Object.entries(s.templates??{})){const l=L.PlTemplateV1.tplField(o,a);e.createField(l,"Input"),e.setField(l,t(c,oo,r))}if(e.lock(o),!s.hashOverride)return o;const i=e.createStruct(L.PlTemplateOverrideV1.type,JSON.stringify(L.PlTemplateOverrideV1.fromV3Data(s))),n=L.PlTemplateOverrideV1.tplField(i);return e.createField(n,"Service"),e.setField(n,o),e.lock(i),i}};function Se(s,e,t){return w.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function Pn(s,e){const t=L.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return io(s,t);case"pl.tengo-template.v3":return so(s,t);default:w.assertNever(r)}}function Cn(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return io(s,t);case"pl.tengo-template.v3":return so(s,t);default:w.assertNever(r)}}const _r={hash(s,e){e.update(L.PlTemplateLibV1.type.name).update(L.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(L.PlTemplateLibV1.type,JSON.stringify(L.PlTemplateLibV1.fromV2Data(s).data))}},qe={hash(s,e){e.update(L.PlTemplateSoftwareV1.type.name).update(L.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=L.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(L.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,L.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},no={hash(s,e){e.update(L.PlTemplateV1.type.name).update(L.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),_r.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),qe.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),qe.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(L.PlTemplateV1.type,JSON.stringify(L.PlTemplateV1.fromV2Data(s).data));for(const[n,a]of Object.entries(s.libs??{})){const c=L.PlTemplateV1.libField(r,n);e.createField(c,"Input"),e.setField(c,t(a,_r))}for(const[n,a]of Object.entries(s.software??{})){const c=L.PlTemplateV1.swField(r,n);e.createField(c,"Input"),e.setField(c,t(a,qe))}for(const[n,a]of Object.entries(s.assets??{})){const c=L.PlTemplateV1.swField(r,n);e.createField(c,"Input"),e.setField(c,t(a,qe))}for(const[n,a]of Object.entries(s.templates??{})){const c=L.PlTemplateV1.tplField(r,n);e.createField(c,"Input"),e.setField(c,t(a,no))}if(e.lock(r),!s.hashOverride)return r;const o=e.createStruct(L.PlTemplateOverrideV1.type,JSON.stringify(L.PlTemplateOverrideV1.fromV2Data(s))),i=L.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,r),e.lock(o),o}};function io(s,e){const t=new Map,r=(o,i)=>{const n=te.createHash("sha256");i.hash(o,n);const a=n.digest("hex");if(!t.has(a)){const c=i.render(o,s,r);t.set(a,c)}return t.get(a)};return r(e,no)}const ao={name:"TengoTemplateGet",version:"1"},co="registry",lo="templateURI",uo="template",kn={name:"TengoTemplatePack",version:"1"},Rn={name:"TengoTemplatePackConvert",version:"1"},En="templatePack",On="template";async function yr(s){switch(s.type){case"from-file":return{type:"explicit",content:await ae.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return w.assertNever(s)}}function Tn(s,e){const t=s.createStruct(ao),r=h.field(t,co),o=h.field(t,lo),i=h.field(t,uo);return s.setField(r,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(h.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),i}function Be(s,e){switch(e.type){case"from-registry":return Tn(s,e);case"explicit":return Pn(s,e);case"prepared":return Cn(s,e);default:return w.assertNever(e)}}const wr={name:"Frontend/FromUrl",version:"1"},br={name:"Frontend/FromFolder",version:"1"};function Fn(s,e){switch(e.type){case"url":return s.createValue(wr,JSON.stringify({url:e.url}));case"local":return s.createValue(br,JSON.stringify({path:e.path,signature:e.signature}));default:return w.assertNever(e)}}class In{constructor(){C(this,"nextMessageId",0);C(this,"worker");C(this,"pendingRequests",new Map);const e=typeof global<"u"&&"__WORKER_PATH__"in global?global.__WORKER_PATH__:_.resolve(void 0,"worker.js"),t=this.worker=new xo.Worker(e,{workerData:{}});t.on("message",({id:r,data:o,error:i})=>{const{resolve:n,reject:a}=this.pendingRequests.get(r);this.pendingRequests.delete(r),i?a(new Error(i)):n(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 i=++this.nextMessageId;this.pendingRequests.set(i,{resolve:r,reject:o}),this.worker.postMessage({id:i,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Dn={name:"BlockPackCustom",version:"1"},po="template",fo="frontend";function Kr(s){return s.endsWith("/")?s:`${s}/`}function $n(s){return Buffer.from(s).toString("utf8")}function Me(s){return JSON.parse($n(s))}class Ln{constructor(e,t,r){C(this,"remoteContentCache",new ze.LRUCache({max:500,maxSize:128*1024*1024,fetchMethod:async e=>{const t=this.http!==void 0?{dispatcher:this.http}:{};return await(await Ze.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 qr(e.folder),r=await ae.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await ae.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Kr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=await this.remoteContentCache.forceFetch(`${t}/config.json`);return Me(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 Me(o)}default:return w.assertNever(e)}}async prepare(e){var o=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Nr(o,new In,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(i){var n=i,a=!0}finally{var c=jr(o,n,a);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await qr(e.folder),r=await ae.promises.readFile(t.workflow),o=JSON.parse(await ae.promises.readFile(t.config,"utf-8")),i=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await ae.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await ae.promises.readFile(t.components.workflow.main.file),i=t.components.ui.folder,n={...e};return e.mtime===void 0&&(n.mtime=await et(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:i,signature:this.signer.sign(i)},source:n}}case"from-registry-v1":{const t=`${Kr(e.registryUrl)}${Z.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),i=new Uint8Array(o),n=await this.remoteContentCache.forceFetch(`${t}/config.json`),a=Me(n);return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),o=async()=>Me(await this.remoteContentCache.forceFetch(r.model.url)),i=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[n,a]=await Promise.all([o(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:n,frontend:{type:"url",url:r.ui.url},source:e}}default:return w.assertNever(e)}}}function An(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Dn,JSON.stringify(t));return s.createField(h.field(r,po),"Input",Be(s,e.template)),s.createField(h.field(r,fo),"Input",Fn(s,e.frontend)),s.lock(r),r}function Hr(s,e){switch(e.type){case"prepared":return An(s,e);default:return w.assertNever(e.type)}}function Je(s,e,t){return{__isRef:!0,blockId:s,name:e}}function Nn(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function ur(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(Nn(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)ur(s,o,t);else for(const[,o]of Object.entries(e))ur(s,o,t);return;default:w.assertNever(r)}}function jn(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return ur(t,s,e),t}function ne(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class ho{constructor(e){C(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 i=new Set(o);for(;o.length>0;){const n=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(l=>{i.has(l)||(i.add(l),n.push(l))})}o=n}}}function dr(s){const e=new Map;let t;for(const{id:r}of ne(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 ho(e)}function Ke(s,e){const t=new Map,r=new ho(t),o=new Set;for(const{id:i}of ne(s)){const n=e(i);if(n===void 0)continue;const a=jn(n.args,o),c=new Set([...a.upstreams,...r.traverseIds("enrichments",...a.upstreamsRequiringEnrichments)]),l=new Set;for(const{id:p}of ne(s)){if(p===i)break;if(c.has(p)){l.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))l.delete(f)}}const u=n.enrichmentTargets===void 0?new Set(a.upstreams):new Set(n.enrichmentTargets.map(p=>p.blockId)),d={id:i,missingReferences:a.missingReferences,upstream:l,directUpstream:a.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(i,d),a.upstreams.forEach(p=>t.get(p).directDownstream.add(i)),l.forEach(p=>t.get(p).downstream.add(i)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(i)}),o.add(i)}return r}function Bn(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function pr(s,e){if(s.size>e.size)return pr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Wr(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(i=>{const n=e.nodes.get(i.id);n===void 0?t.add(i.id):(!Bn(i.upstream,n.upstream)||pr(i.upstream,o))&&o.add(i.id)}),e.nodes.forEach(i=>{s.nodes.has(i.id)?pr(i.upstream,o)&&o.add(i.id):r.add(i.id)}),{onlyInA:t,onlyInB:r,different:o}}let pt;async function go(){if(pt===void 0){const s=await yr(me.Templates["pframes.export-pframe-for-ui"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=te.createHash("sha256").update(s.content).digest("hex");pt={spec:s,hash:e}}return pt}function xn(s,e,t){return tt(s,e,!0,{pf:t},["result"]).result}let ye;function ee(){return ye||(ye={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,dumpInitialTreeState:process.env.MI_DUMP_INITIAL_TREE_STATE!==void 0,logProjectMutationStat:process.env.MI_LOG_PROJECT_MUTATION_STAT!==void 0,logOutputRecalculations:process.env.MI_LOG_OUTPUT_RECALCULATIONS!==void 0},process.env.MI_LOG_OUTPUT_STATUS&&(ye.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(ye.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),ye)}function ft(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const i=s();return r!==i&&(r=i,o=e()),e()}}class ht{constructor(e,t,r,o){C(this,"currentArgsC",ft(()=>this.fields.currentArgs.modCount,()=>w.cachedDeserialize(this.fields.currentArgs.value)));C(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 w.cachedDeserialize(e)}));C(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(h.Pl.unwrapHolder(e,this.fields.blockPack.ref),po,"Input")}}const Vn=s=>{throw new Error(`No new block info for ${s}`)};class Qe{constructor(e,t,r,o,i,n,a,c,l,u,d,p){C(this,"globalModCount",0);C(this,"fieldsChanged",!1);C(this,"lastModifiedChanged",!1);C(this,"structureChanged",!1);C(this,"metaChanged",!1);C(this,"renderingStateChanged",!1);C(this,"blocksWithChangedInputs",new Set);C(this,"stagingGraph");C(this,"pendingProductionGraph");C(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=i,this.meta=n,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.ctxExportTplHolder=d,this.projectHelper=p}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=dr(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let o,i;if(t){if(r.fields.prodArgs===void 0)return;o=r.fields.prodArgs,i=r.prodArgs}else o=w.notEmpty(r.fields.currentArgs),i=r.currentArgs;const n=w.notEmpty(r.fields.blockPack);return h.isResourceId(o.ref)&&h.isResourceId(n.ref)?{args:i,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>i,{argsRid:o.ref,blockPackRid:n.ref})}:{args:i,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>i)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ke(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(h.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ne(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=h.field(this.rid,W(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(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,i){this.setBlockFieldObj(e,t,{ref:r,status:o,value:i})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const i of t){const n=o.fields;i in n&&(this.tx.removeField(h.field(this.rid,W(e,i))),delete n[i],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,i;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.stagingUiCtx)==null?void 0:i.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,i;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((i=t.prodUiCtx)==null?void 0:i.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","prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious")}setStates(e){const t=[];let r=!1;for(const o of e){const i=this.getBlockInfo(o.blockId);let n=!1;for(const a of["args","uiState"]){if(!(a in o))continue;const c=o[a];if(c==null)throw new Error(`Can't set ${a} to null or undefined, please omit the key if you don't want to change it`);const l=a==="args"?"currentArgs":"uiState";let u,d=!1;if(a==="args")u=w.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=w.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(i.fields[l].value,u)===0)continue;console.log("setting",l,d,u.length);const p=this.tx.createValue(d?h.Pl.JsonGzObject:h.Pl.JsonObject,u);this.setBlockField(o.blockId,l,p,"Ready",u),n=!0,a==="args"&&t.push(o.blockId)}n&&(this.blocksWithChangedInputs.add(o.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:o})=>this.resetStaging(o)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var i;const o=this.getBlockInfo(r);if(((i=o.fields.prodCtx)==null?void 0:i.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Jr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var i,n;const o=this.getBlockInfo(r);if(((i=o.fields.stagingCtx)==null?void 0:i.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(h.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((n=o.fields.prodCtx)==null?void 0:n.ref)!==void 0&&t.push(h.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Jr(this.tx,t)}exportCtx(e){return xn(this.tx,h.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),i=Mr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",h.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"stagingOutput",i.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),i=Mr(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(h.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(h.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",h.Pl.wrapInEphHolder(this.tx,i.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(i.context),"NotReady"),this.setBlockField(e,"prodOutput",i.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}initializeNewBlock(e,t){const r=new ht(e,{},k.extractConfig(t.blockPack.config),t.blockPack.source);this.blockInfos.set(e,r);const o=Hr(this.tx,t.blockPack);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,o),"NotReady"),this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(e,"currentArgs",this.createJsonFieldValueByContent(t.args)),this.setBlockFieldObj(e,"uiState",this.createJsonFieldValueByContent(t.uiState??"{}")),r.check()}getFieldNamesToDuplicate(e){var o,i;const t=this.getBlockInfo(e).fields,r=(n,a)=>new Set([...n].filter(c=>!a.has(c)));return((o=t.prodOutput)==null?void 0:o.status)==="Ready"&&((i=t.prodCtx)==null?void 0:i.status)==="Ready"?this.blocksInLimbo.has(e)?dt:r(dt,new Set(["prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"])):r(dt,new Set(["prodOutput","prodCtx","prodUiCtx","prodArgs","prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"]))}initializeBlockDuplicate(e,t){const r=new ht(e,{},t.config,t.source);this.blockInfos.set(e,r);const o=this.getFieldNamesToDuplicate(e);for(const[i,n]of Object.entries(t.fields))o.has(i)&&n&&n.ref&&this.setBlockFieldObj(e,i,{ref:n.ref,status:n.status,value:n.value});this.resetOrLimboProduction(e),r.check()}updateStructure(e,t=Vn){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),i=dr(e),n=Wr(r,i);for(const l of n.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0)}for(const l of n.onlyInB)t(l);for(const l of n.different)this.resetStaging(l);const a=Ke(e,l=>this.getProductionGraphBlockInfo(l,!0)),c=Wr(o,a);o.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(n.onlyInB.size>0||n.onlyInA.size>0||n.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 i=!1;for(const n of o.groups){const a=n.blocks.findIndex(c=>c.id===r);if(!(a<0)){n.blocks.splice(a,0,e),i=!0;break}}if(!i)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,i=>{if(i!==e.id)throw new Error("Unexpected");this.initializeNewBlock(i,t)})}duplicateBlock(e,t,r){const o=this.getBlock(e),i=this.getBlockInfo(e),n={id:t,label:o.label,renderingMode:o.renderingMode},a=this.structure;if(r===void 0)a.groups[a.groups.length-1].blocks.push(n);else{let c=!1;for(const l of a.groups){const u=l.blocks.findIndex(d=>d.id===r);if(!(u<0)){l.blocks.splice(u+1,0,n),c=!0;break}}if(!c)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(a,c=>{if(c!==t)throw new Error("Unexpected");this.initializeBlockDuplicate(c,i)})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const i=o.blocks.findIndex(n=>n.id===e);if(!(i<0)){o.blocks.splice(i,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",h.Pl.wrapInHolder(this.tx,Hr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:i})=>this.resetStaging(i)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:i})=>this.resetOrLimboProduction(i)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{r.add(a.id)});else for(const a of r){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const l of c.upstream)if(!r.has(l))throw new Error("Can't render blocks not including all upstreams.")}const i=new Set;for(const a of ne(this.structure)){if(!r.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const l of o.nodes.get(a.id).upstream)if(i.has(l)){c=!0;break}}c&&(this.renderProductionFor(a.id),i.add(a.id))}const n=[...i];return o.traverse("downstream",n,a=>{i.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",n,({id:a})=>{n[0]!==a&&this.resetStaging(a)}),i.size>0&&this.updateLastModified(),i}stopProduction(...e){var n,a;const t=this.getActualProductionGraph(),r=new zs(e),o=new Set(e),i=[];for(;!r.isEmpty();){const c=r.shift(),l=this.getBlockInfo(c).fields;if(!(((n=l.prodOutput)==null?void 0:n.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){i.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))o.has(u)||(r.push(u),o.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...i))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let n=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(n=Math.max(c+1,n))}),e(o.id,n),t.set(o.id,n)})}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((i,n)=>{n!==0&&(r===void 0||n<=r)&&(this.renderStagingFor(i),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,i,n;((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"),((i=t.fields.stagingCtx)==null?void 0:i.status)==="Ready"&&((n=t.fields.stagingOutput)==null?void 0:n.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,ar(t)):this.tx.setKValue(this.rid,ar(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,cr):this.tx.setKValue(this.rid,cr,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,Le,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,fe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Ye,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Ae,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,o){const i=t.getResourceData(r,!0),n=t.getKValueJson(r,Xe),a=t.getKValueJson(r,Le),c=t.getKValueJson(r,Ae),l=t.getKValueJson(r,fe),u=t.getKValueJson(r,Ye),d=await i,p=new Map;for(const m of d.fields){const v=un(m.name);if(v===void 0)continue;let P=p.get(v.blockId);P===void 0&&(P={id:v.blockId,fields:{}},p.set(v.blockId,P)),P.fields[v.fieldName]=h.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[P,S]of Object.entries(v)){if(S.ref===void 0)continue;if(!h.isResource(S.ref)||h.isResourceRef(S.ref))throw new Error("unexpected behaviour");const E=P;f.push([m,E,S,t.getResourceData(S.ref,E=="blockPack")])}});const[y,g,b,F,{stagingRefreshTimestamp:x,blocksInLimbo:D}]=await Promise.all([n,a,c,l,u]);if(y!==$e)throw Number(y)<Number($e)?new k.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new k.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const U=[];for(const[m,v,P,S]of f){const E=await S;if(P.value=E.data,h.isNotNullResourceId(E.error)?P.status="Error":E.resourceReady||h.isNotNullResourceId(E.originalResourceId)?P.status="Ready":P.status="NotReady",v==="blockPack"){const R=E.fields.find(I=>I.name===h.Pl.HolderRefField);if(R===void 0)throw new Error("Block pack ref field is missing");U.push([m,t.getResourceData(h.ensureResourceIdNotNull(R.value),!1)])}}for(const[m,v]of U){const P=await v,S=w.cachedDeserialize(w.notEmpty(P.data));m.blockConfig=k.extractConfig(S.config),m.blockPack=S.source}const q=await go(),T=lr(q.hash),N=d.fields.find(m=>m.name===T);let O;N!==void 0?O=h.ensureResourceIdNotNull(N.value):(O=h.Pl.wrapInHolder(t,Be(t,q.spec)),t.createField(h.field(r,lr(q.hash)),"Dynamic",O));const K={stagingRefreshTimestamp:x},de=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:P,blockPack:S})=>Y.set(m,new ht(m,v,w.notEmpty(P),w.notEmpty(S))));const G=new Set;for(const m of ne(F)){if(!Y.has(m.id))throw new Error(`Inconsistent project structure: no inputs for ${m.id}`);G.add(m.id)}Y.forEach(m=>{if(!G.has(m.id))throw new Error(`Inconsistent project structure: no structure entry for ${m.id}`);m.check()});const X=new Qe(r,t,o,y,g,b,F,K,de,Y,O,e);return X.fixProblemsAndMigrate(),X}}async function Un(s,e=on){const t=s.createEphemeral(nn);s.lock(t);const r=String(Date.now());s.setKValue(t,Xe,JSON.stringify($e)),s.setKValue(t,vr,r),s.setKValue(t,Le,r),s.setKValue(t,Ae,JSON.stringify(e)),s.setKValue(t,fe,JSON.stringify(rn)),s.setKValue(t,Ye,JSON.stringify(sn));const o=await go();return s.createField(h.field(t,lr(o.hash)),"Dynamic",h.Pl.wrapInHolder(s,Be(s,o.spec))),t}async function Ge(s,e,t,r){return ie(s,e,t,void 0,r)}async function ie(s,e,t,r,o){if(e instanceof h.PlClient)return await e.withWriteTx("ProjectAction",async i=>{const n=await Qe.load(s,i,t,r),a=await o(n);return n.wasModified&&(n.save(),await i.commit(),ee().logProjectMutationStat&&console.log(JSON.stringify(i.stat))),a});{const i=await Qe.load(s,e,t,r),n=await o(i);return i.save(),n}}function*qn(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;case"ParquetPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;default:w.assertNever(s)}}function gt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Mn(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:gt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:gt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};case"ParquetPartitioned":return{...s,parts:gt(s.parts,e)};default:w.assertNever(s)}}const Jn=h.resourceType("PColumnData/JsonPartitioned","1"),Gn=h.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),_n=h.resourceType("PColumnData/BinaryPartitioned","1"),Kn=h.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Hn=h.resourceType("PColumnData/ParquetPartitioned","1"),Wn=h.resourceType("PColumnData/Partitioned/ParquetPartitioned","1"),zn=h.resourceType("PColumnData/Json","1");function Xn(s){if(!s.getIsReadyOrError())throw new k.PFrameDriverError("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new k.PFrameDriverError("unexpected data info structure, no resource data");if(h.resourceTypesEqual(s.resourceType,zn)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(h.resourceTypesEqual(s.resourceType,Jn)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Gn)){const t=e,r={};for(const o of s.listInputFields()){const i=s.traverse({field:o,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new k.PFrameDriverError(`no partition keys for super key ${o}`);for(const a of n){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,_n)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const i=o.slice(0,o.length-6);let n=r[i];n===void 0&&(n={},r[i]=n),n.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const i=o.slice(0,o.length-7);let n=r[i];n===void 0&&(n={},r[i]=n),n.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new k.PFrameDriverError(`unrecognized part field name: ${o}`);for(const[o,i]of Object.entries(r)){if(i.index===void 0)throw new k.PFrameDriverError(`no index for part ${o}`);if(i.values===void 0)throw new k.PFrameDriverError(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Kn)){const t=e,r={};for(const o of s.listInputFields()){const i=s.traverse({field:o,errorIfFieldNotSet:!0}),n=i.listInputFields();if(n===void 0)throw new k.PFrameDriverError(`no partition keys for super key ${o}`);for(const a of n)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=i.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new k.PFrameDriverError(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Hn)){const t=e,r={};for(const o of s.listInputFields()){const i=s.traverse({field:o,assertFieldType:"Input",errorIfFieldNotSet:!0}),n=i.traverse({field:"blob",assertFieldType:"Service",errorIfFieldNotSet:!0}).resourceInfo,a=i.getDataAsJson(),c=i.traverse({field:"mapping",assertFieldType:"Service",errorIfFieldNotSet:!0}).getDataAsJson();r[o]={data:n,...a,...c}}return{type:"ParquetPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(h.resourceTypesEqual(s.resourceType,Wn)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}).listInputFields();if(n===void 0)throw new k.PFrameDriverError(`no partition keys for super key ${o}`);for(const a of n){const c=s.traverse({field:a,errorIfFieldNotSet:!0}),l=c.traverse({field:"blob",assertFieldType:"Service",errorIfFieldNotSet:!0}).resourceInfo,u=c.getDataAsJson(),d=c.traverse({field:"mapping",assertFieldType:"Service",errorIfFieldNotSet:!0}).getDataAsJson(),p=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[p]={data:l,...u,...d}}}return{type:"ParquetPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new k.PFrameDriverError(`unsupported resource type: ${h.resourceTypeToString(s.resourceType)}`)}function Yn(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:i}of e){if(o.length!==t)throw new k.PFrameDriverError(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=i}return{type:"Json",keyLength:t,data:r}}function Qn(s,e){const t=te.createHash("sha256");return t.update(oe(s)),t.update(String(h.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function zr(s,e){return oe({__isRef:!0,blockId:s,name:e})}function Zn(s,e){return oe({resolvePath:s,name:e})}function mo(s,e=!0,t=!1,r=""){var a,c,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,i=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=w.notEmpty((a=d.groups)==null?void 0:a.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=w.notEmpty((c=d.groups)==null?void 0:c.type);let y=i.get(p);switch(y===void 0&&(y={},i.set(p,y)),f){case"spec":y.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const n=s.getInputsLocked();if(n)for(const[,u]of i)u.data===void 0&&(u.hasData=!1);return{locked:n,results:i}}function ei(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=mo(s,e,!1,t);Vo(o.locked);const i={};for(const[n,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${n}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${n}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${n}`);if(!c.ok)throw c.error;i[n]={id:r.length===0?Qn(a.spec,c.value):Zn(r,n),spec:a.spec,data:c.value}}return i}class Sr{constructor(e,t){C(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const i of[o.prod,o.staging])if(i!==void 0){if(!i.locked){r=!1;break e}for(const n of i.results.values())if(n.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var i,n,a,c,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(n=(i=r.prod)==null?void 0:i.results)==null?void 0:n.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(u=(l=(c=r.staging)==null?void 0:c.results)==null?void 0:l.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 n,a,c;const r=this.blocks.get(e);if(r===void 0)return;const o=(a=(n=r.prod)==null?void 0:n.results)==null?void 0:a.get(t),i=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&i!==void 0)return k.mapValueInVOE(i,l=>({id:zr(e,t),spec:o.spec,data:l}));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=n=>{r===void 0&&(r=n),t=!1},i=(n,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:Je(n,a),obj:{id:l.ok?zr(n,a):void 0,spec:c.spec,data:l}}):o(`no_data:${n}:${a}`)}};for(const[n,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${n}`);for(const[l,u]of a.prod.results)c.add(l),i(n,l,u)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${n}`);for(const[l,u]of a.staging.results)c.has(l)||i(n,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1};for(const[i,n]of this.blocks){const a=new Set;if(n.staging!==void 0){n.staging.locked||o(`staging_not_locked:${i}`);for(const[c,l]of n.staging.results)l.spec!==void 0&&(e.push({ref:Je(i,c),obj:l.spec}),a.add(c))}else o(`staging_not_rendered:${i}`);if(n.prod!==void 0){n.prod.locked||o(`prod_not_locked:${i}`);for(const[c,l]of n.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:Je(i,c),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,i=n=>{for(const[a,c]of n.results)o.has(a)||c.spec===void 0||(o.add(a),k.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:Je(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&i(r.staging),r.prod!==void 0&&i(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),i=w.notEmpty(o.getKeyValueAsJson(fe)),a=dr(i).traverseIds("upstream",r),c=new Map;for(const l of ne(i)){if(!a.has(l.id))continue;const u=Xr(o.traverse({field:W(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:W(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=Xr(o.traverse({field:W(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:W(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:d})}return new Sr(e,c)}}function Xr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return mo(e.value,!1,!0)}function Pr(s,e){return{blockId:e,args:i=>w.cachedDecode(w.notEmpty(i.accessor(s).node().traverse({field:W(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:i=>{var a;const n=(a=i.accessor(s).node().traverse({field:W(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:a.getData();return n?w.cachedDecode(n):void 0},uiState:i=>{var a;const n=(a=i.accessor(s).node().traverse({field:W(e,"uiState"),stableIfNotFound:!0}))==null?void 0:a.getData();return n?w.cachedDecode(n):void 0},blockMeta:i=>{const n=i.accessor(s).node(),a=w.notEmpty(n.getKeyValueAsJson(fe)),c=new Map;for(const l of ne(a))c.set(l.id,l);return c}}}function vo(s,e){return{...Pr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:W(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Sr.create(t,s,e)}}function*se(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*se(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*se(t);return;case"MakeArray":for(const t of s.template)yield*se(t);return;case"GetJsonField":case"GetResourceField":yield*se(s.source),yield*se(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*se(s.source),yield*se(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*se(s.source);return;case"IsEmpty":yield*se(s.arg);return;case"Not":yield*se(s.operand);return;case"And":case"Or":yield*se(s.operand1),yield*se(s.operand2);return;default:w.assertNever(s)}}function ti(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Te(s,e){return s===void 0?void 0:e(s)}function ri(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function si(s){for(const e of se(s))if(ri(e))return!0;return!1}function rt(s){return{type:"ReturnResult",result:s}}function A(s){return()=>rt(s)}const oi=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return A(e)},ni=s=>{const e=s.source;if(e===void 0)return A(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return A(t)},ii=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?A(void 0):({cCtx:r})=>{var o;return rt((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function yo(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function ai(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):()=>({type:"ScheduleSubroutine",subroutine:wo(r.length),args:yo(r,o=>B({...s,[e.itVar]:o},e.mapping))})}}function wo(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return A(t)}}function ci(s,e){return t=>{const r=t.source;if(r===void 0)return A(void 0);const o={};for(const[i,n]of Object.entries(r)){const a={...s,[e.itVar]:n};o[i]=B(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:li,args:o})}}const li=s=>A(s),ui=s=>{const e=s.arg;return A(e===void 0?void 0:e.length===0)},di=s=>{const e=s.operand;return A(e===void 0?void 0:!e)},pi=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e&&t)},fi=s=>{const e=s.operand1,t=s.operand2;return A(e===void 0||t===void 0?void 0:e||t)},hi=s=>{const e=s.source;return e===void 0?A(void 0):({cCtx:t})=>{var r;return rt((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},gi=s=>{const e=s.source,t=s.field;return A(e===void 0||t===void 0?void 0:e[t])};function mi(s,e){return t=>{const r=t.source;return r===void 0?A(void 0):({cCtx:o})=>{const i=o.accessor(r).node(),n={};for(const a of i.listInputFields()){const c=i.traverse(a);if(c===void 0)n[a]=A(void 0);else{const l={...s,[e.itVar]:c.persist()};n[a]=B(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:vi,args:n}}}}const vi=s=>A(s),yi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(o=>r.blobDriver.getDownloadedBlob(o.accessor(t).node().resourceInfo),{postprocessValue:async o=>{if(o!==void 0)return await r.blobDriver.getContent(o.handle,s)}})})},wi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({cCtx:r,drivers:o})=>{const i=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(n=>o.blobDriver.getDownloadedBlob(i,n),{postprocessValue:async n=>n===void 0?void 0:(await o.blobDriver.getContent(n.handle,s)).toString()})}}},bi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(o=>r.blobDriver.getDownloadedBlob(o.accessor(t).node().resourceInfo,o),{postprocessValue:async o=>{if(o==null)return;const i=await r.blobDriver.getContent(o.handle,s);if(i!=null)return JSON.parse(Buffer.from(i).toString())}})})},Si=s=>{const e=s.source;return e===void 0?A(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},Pi=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Ci=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},ki=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Ri=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Ei=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Oi=s=>e=>{const t=e.source;return t===void 0?A(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},Ti=s=>{const e=s.source;return e===void 0?A(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function B(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>rt(t(r.cCtx)):A(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:Po(t,s,e.cfg)});case"Immediate":return A(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:gi,args:{source:B(s,e.source),field:B(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:ai(s,e),args:{source:B(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:ci(s,e),args:{source:B(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:oi,args:ti(e.template,t=>B(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:wo(e.template.length),args:yo(e.template,t=>B(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:ni,args:{source:B(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ui,args:{arg:B(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:di,args:{operand:B(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:pi,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:fi,args:{operand1:B(s,e.operand1),operand2:B(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:mi(s,e),args:{source:B(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{source:B(s,e.source),field:B(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:hi,args:{source:B(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:yi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:wi(e.range),args:{source:B(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:bi(e.range),args:{source:B(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Si,args:{source:B(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Pi,args:{source:B(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Ci(e.format),args:{source:B(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:ki,args:{source:B(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Ri(e.lines),args:{source:B(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Ei(e.patternToSearch),args:{source:B(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:Oi(e.patternToSearch),args:{source:B(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Ti,args:{source:B(s,e.source)}});default:return w.assertNever(e)}}const Fi=["$prod","$staging"];function Ii(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 bo=Symbol(),So="return",Di={op:bo,arg:So};function $i(s){return s.op==bo&&s.arg==So}function Li(){return{pendingSubroutines:new Map}}function Yr(s,e,t,r){const o=new zs(t),i=(a,c)=>{if($i(a))return e.result=c,!1;const l=w.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},n=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(s);switch(c.type){case"ReturnResult":if(!i(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[p,f]of u)o.push({destination:{op:l,arg:p},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");n.push({destination:a.destination,computable:c.computable});break;default:w.assertNever(c)}}return n}function Ai(s,e,t,r={}){return Po(s,Ii(e),t,r)}function Po(s,e,t,r={}){const o=`${e.blockId}#`+oe({ctx:Object.fromEntries(Object.entries(e).filter(([i])=>Fi.indexOf(i)===-1)),cfg:t});return J.Computable.makeRaw(i=>{const n={drivers:s,cCtx:i},a=Li();return{ir:Yr(n,a,[{destination:Di,operation:B(e,t)}],!0),postprocessValue(l){const u=[];for(const y of l)u.push({destination:y.destination,operation:A(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,g]of a.pendingSubroutines)p.set(y,{...g,args:{...g.args}});const f={result:a.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 Qr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ni{constructor(e,t,r,o,i){C(this,"computablesToResolve",{});C(this,"computableCtx");C(this,"accessors",new Map);C(this,"meta");C(this,"_resultPool");this.parent=e,this.blockCtx=t,this.env=r,this.featureFlags=o,this.computableCtx=i,this.meta=t.blockMeta(i)}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 i=this.blockCtx[o];if(i===void 0)throw new Error("Staging context not available");const n=i(this.computableCtx);n?this.accessors.set(r,this.computableCtx.accessor(n).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 Qr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Qr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const i=this.getAccessor(e);if(!i.getIsReadyOrError())return;const n=ei(i,t,r,o),a={};for(const[c,l]of Object.entries(n))a[c]=k.mapPObjectData(l,u=>this.wrapAccessor(u));return a}registerComputable(e,t){const r=`${e}_${te.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",J.Computable.make(o=>this.env.driverKit.blobDriver.getDownloadedBlob(r,o),{postprocessValue:async o=>{if(o!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(o.handle,t)).toString("utf-8")}}))}getBlobContentAsBase64(e,t){const r=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",J.Computable.make(o=>this.env.driverKit.blobDriver.getDownloadedBlob(r,o),{postprocessValue:async o=>{if(o!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(o.handle,t)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getProgressLogWithInfo(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=w.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:k.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:k.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 k.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=>k.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(k.mapPTableDef(e,t=>k.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):k.isDataInfo(e)?k.mapDataInfo(e,t=>this.getAccessor(t)):e}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}logInfo(e){this.env.blockEventDispatcher.logInfo(this.blockCtx.blockId,e)}logWarn(e){this.env.blockEventDispatcher.logWarn(this.blockCtx.blockId,e)}logError(e){this.env.blockEventDispatcher.logError(this.blockCtx.blockId,e)}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=te.randomUUID();return this.accessors.set(t,e),t}}injectCtx(e){const t=this.parent,r=t.vm;ge.Scope.withScope(o=>{const i=(n,a)=>{const c=(...l)=>{try{return a(...l)}catch(u){const d=t.errorRepo.setAndRecreateForQuickJS(u);throw r.newError(d)}};r.newFunction(n,c).consume(l=>r.setProp(e,n,l)),r.newFunction(n,a).consume(l=>r.setProp(e,n+"__internal__",l))};if(k.checkBlockFlag(this.featureFlags,"supportsLazyState"))i("args",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.args outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.args(this.computableCtx))}),i("uiState",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.uiState outside the future lambda. Can't be directly used in this context.");return r.newString(this.blockCtx.uiState(this.computableCtx)??"{}")}),i("activeArgs",()=>{if(this.computableCtx===void 0)throw new Error("Add dummy call to ctx.activeArgs outside the future lambda. Can't be directly used in this context.");const n=this.blockCtx.activeArgs(this.computableCtx);return n===void 0?r.undefined:r.newString(n)});else{const n=this.blockCtx.args(this.computableCtx),a=this.blockCtx.activeArgs(this.computableCtx),c=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",o.manage(r.newString(n))),r.setProp(e,"uiState",o.manage(r.newString(c??"{}"))),a!==void 0&&r.setProp(e,"activeArgs",o.manage(r.newString(a)))}i("getAccessorHandleByName",n=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(n)),void 0)),i("resolveWithCommon",(n,a,...c)=>t.exportSingleValue(this.resolveWithCommon(r.getString(n),t.importObjectViaJson(a),...c.map(l=>t.importObjectViaJson(l))),void 0)),i("getResourceType",n=>t.exportObjectViaJson(this.getResourceType(r.getString(n)),void 0)),i("getInputsLocked",n=>t.exportSingleValue(this.getInputsLocked(r.getString(n)),void 0)),i("getOutputsLocked",n=>t.exportSingleValue(this.getOutputsLocked(r.getString(n)),void 0)),i("getIsReadyOrError",n=>t.exportSingleValue(this.getIsReadyOrError(r.getString(n)),void 0)),i("getIsFinal",n=>t.exportSingleValue(this.getIsFinal(r.getString(n)),void 0)),i("getError",n=>t.exportSingleValue(this.getError(r.getString(n)),void 0)),i("listInputFields",n=>t.exportObjectViaJson(this.listInputFields(r.getString(n)),void 0)),i("listOutputFields",n=>t.exportObjectViaJson(this.listInputFields(r.getString(n)),void 0)),i("listDynamicFields",n=>t.exportObjectViaJson(this.listInputFields(r.getString(n)),void 0)),i("getKeyValueBase64",(n,a)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(n),r.getString(a)),void 0)),i("getKeyValueAsString",(n,a)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(n),r.getString(a)),void 0)),i("getDataBase64",n=>t.exportSingleValue(this.getDataBase64(r.getString(n)),void 0)),i("getDataAsString",n=>t.exportSingleValue(this.getDataAsString(r.getString(n)),void 0)),i("parsePObjectCollection",(n,a,c,...l)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(n),r.dump(a),r.getString(c),...l.map(u=>r.getString(u))),void 0)),i("getBlobContentAsBase64",(n,a)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(n),t.importObjectUniversal(a)),void 0)),i("getBlobContentAsString",(n,a)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(n),t.importObjectUniversal(a)),void 0)),i("getDownloadedBlobContentHandle",n=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(n)),void 0)),i("getOnDemandBlobContentHandle",n=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(n)),void 0)),i("extractArchiveAndGetURL",(n,a)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(n),r.getString(a)),void 0)),i("getImportProgress",n=>t.exportSingleValue(this.getImportProgress(r.getString(n)),void 0)),i("getLastLogs",(n,a)=>t.exportSingleValue(this.getLastLogs(r.getString(n),r.getNumber(a)),void 0)),i("getProgressLog",(n,a)=>t.exportSingleValue(this.getProgressLog(r.getString(n),r.getString(a)),void 0)),i("getProgressLogWithInfo",(n,a)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(n),r.getString(a)),void 0)),i("getLogHandle",n=>t.exportSingleValue(this.getLogHandle(r.getString(n)),void 0)),i("getBlockLabel",n=>t.exportSingleValue(this.getBlockLabel(r.getString(n)),void 0)),i("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",n=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(n)),void 0)),i("getSpecFromResultPoolByRef",(n,a)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(n),r.getString(a)),void 0)),i("getDataFromResultPoolByRef",(n,a)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(n),r.getString(a)),void 0)),i("createPFrame",n=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(n)),void 0)),i("createPTable",n=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(n)),void 0)),i("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),i("logInfo",n=>{this.logInfo(r.getString(n))}),i("logWarn",n=>{this.logWarn(r.getString(n))}),i("logError",n=>{this.logError(r.getString(n))})})}}function ji(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Ne{constructor(e,t,r,o,i){C(this,"callbackRegistry");C(this,"fnJSONStringify");C(this,"fnJSONParse");C(this,"errorRepo",new Bi);C(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.");i!==void 0&&(this.computableHelper=new Ni(this,i.blockCtx,i.mlEnv,o,i.computableCtx)),this.injectCtx()}resetComputableCtx(){w.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}),ge.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(i=>this.exportObjectUniversal(i,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(ji(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){if(e!==void 0)switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ge.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(k.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Bi{constructor(){C(this,"errorIdToError",new Map)}setAndRecreateForQuickJS(e){const t=te.randomUUID();return this.errorIdToError.set(t,e),e instanceof Error?{name:`${e.name}/uuid:${t}`,message:e.message}:{name:`UnknownErrorQuickJS/uuid:${t}`,message:`${e}`}}getOriginal(e){if(!(e instanceof ge.errors.QuickJSUnwrapError))return console.warn("ErrorRepo: quickJSError is not a QuickJSUnwrapError",h.stringifyWithResourceId(e)),e;const t=e.cause;if(!(typeof t=="object"&&t!==null&&"name"in t&&typeof t.name=="string"))return console.warn("ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)",h.stringifyWithResourceId(e)),e;const r=t.name,o=r.slice(r.indexOf("/uuid:")+6);if(!o)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${r}, ${h.stringifyWithResourceId(e)}`);const i=this.errorIdToError.get(o);if(i===void 0)throw new Error(`ErrorRepo: errorId not found: ${o}, ${h.stringifyWithResourceId(e)}`);return new Uo.PlQuickJSError(e,i)}}function Zr(s,e,t,r,o){ee().logOutputStatus&&(ee().logOutputStatus==="any"||!t)&&console.log(t?`Stable output ${s} calculated ${e!==void 0?"defined":"undefined"}; (#${r})`:`Unstable output ${s}; marker = ${o}; ${e!==void 0?"defined":"undefined"} (#${r})`)}function xi(s,e,t,r,o,i={}){const{code:n,featureFlags:a}=r,c=`${e.blockId}#lambda#${o}#${t.handle}`;return i={...i,key:c},i.mode===void 0&&t.retentive===!0&&(i.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{ee().logOutputRecalculations&&console.log(`Block lambda recalculation : ${c} (${l.changeSourceMarker}; ${l.bodyInvocations} invocations)`);const u=new ge.Scope;let d=!1;l.addOnDestroy(()=>{d&&u.dispose()});try{const p=u.manage(s.quickJs.newRuntime());p.setMemoryLimit(1024*1024*8),p.setMaxStackSize(1024*320);let f;p.setInterruptHandler(()=>f===void 0?!1:Date.now()>f.deadline);const y=u.manage(p.newContext()),g=new Ne(u,y,D=>{f=D},a,{computableCtx:l,blockCtx:e,mlEnv:s});g.evaluateBundle(n.content);const b=g.runCallback(t.handle);g.resetComputableCtx();const F=g.computableHelper.computablesToResolve;if(Object.keys(F).length===0){const D=g.importObjectUniversal(b);return Zr(t.handle,D,l.unstableMarker===void 0,-1,l.unstableMarker),{ir:D}}let x=0;return ee().logOutputStatus&&console.log(`Output ${t.handle} scaffold calculated (not all computables resolved yet).`),d=!0,{ir:F,postprocessValue:(D,{unstableMarker:U,stable:q})=>{for(const[N,O]of Object.entries(D))g.runCallback(N,O);const T=g.importObjectUniversal(b);return x++,Zr(t.handle,T,q,x,U),T}}}catch(p){throw d=!1,p}finally{d||u.dispose()}},i)}function Vi(s,e,t,...r){const{code:o,featureFlags:i}=t,n=new ge.Scope;try{const a=n.manage(s.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let c;a.setInterruptHandler(()=>c===void 0?!1:Date.now()>c.deadline);const l=n.manage(a.newContext()),u=new Ne(n,l,d=>{c=d},i);return u.evaluateBundle(o.content),u.importObjectUniversal(u.runCallback(e.handle,...r))}finally{n.dispose()}}function Ui(s){return k.isConfigLambda(s)?s.isActive===!0:si(s)}function Fe(s,e,t,r,o,i={}){if(k.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return xi(s,e,t,r,o,i)}else return Ai(s.driverKit,e,t,i)}function je(s,e){return Te(s.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=k.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}function qi(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=xr.omitBy((r,o)=>o.startsWith("__"));return xr.isDeepEqual(t(s),t(e))}function Mi(s,e,t){return J.Computable.make(r=>{var y,g,b,F,x,D,U,q;const o=r.accessor(s).node(),i=w.notEmpty(o.getKeyValueAsJson(vr)),n=w.notEmpty(o.getKeyValueAsJson(Le)),a=w.notEmpty(o.getKeyValueAsJson(Ae)),c=w.notEmpty(o.getKeyValueAsJson(fe)),l=w.notEmpty(o.getKeyValueAsJson(Ye)),u=new Map;for(const{id:T}of ne(c)){const N=o.traverse({field:W(T,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),O=N.getDataAsJson();let K;const de=o.traverse({field:W(T,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(de!==void 0){const Y=de.getDataAsJson(),G=o.getField({field:W(T,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=o.getField({field:W(T,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});K={arguments:Y,stale:!qi(O,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((g=X.value)==null?void 0:g.getError())!==void 0,outputsError:((b=G.error)==null?void 0:b.getDataAsString())??((x=(F=G.value)==null?void 0:F.getError())==null?void 0:x.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((q=(U=X.value)==null?void 0:U.getError())==null?void 0:q.getDataAsString()),finished:(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())&&(X.value!==void 0&&X.value.getIsReadyOrError()||X.error!==void 0&&X.error.getIsReadyOrError())}}u.set(T,{currentArguments:O,prod:K,argsRid:N.resourceInfo.id})}const d=Ke(c,T=>{const N=je(o,T),O=u.get(T),K=O.currentArguments;return{args:K,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>N.cfg,()=>K,{argsRid:O.argsRid,blockPackRid:N.bpResourceId})}}),p=new Set(l.blocksInLimbo),f=[...ne(c)].map(({id:T,label:N,renderingMode:O})=>{var j,$,V,z,M;const K=w.notEmpty(u.get(T)),de=w.notEmpty(d.nodes.get(T));let Y="NotCalculated";K.prod!==void 0&&(p.has(T)?Y="Limbo":Y=K.prod.finished?"Done":"Running");const G=je(o,T),{sections:X,title:m,inputsValid:v,sdkVersion:P,featureFlags:S,isIncompatibleWithRuntime:E}=Te(G,({bpId:ce,cfg:ve})=>{if(!t.runtimeCapabilities.checkCompatibility(ve.featureFlags))return{isIncompatibleWithRuntime:!0,featureFlags:ve.featureFlags};const lt=Pr(s,T),pe=k.extractCodeWithInfo(ve);return{sections:Fe(t,lt,ve.sections,pe,ce).wrap({recover:Ee=>(t.logger.error("Error in block model sections"),t.logger.error(Ee),[])}),title:Te(ve.title,Ee=>Fe(t,lt,Ee,pe,ce).wrap({recover:Lo=>(t.logger.error("Error in block model title"),t.logger.error(Lo),"Invalid title")})),inputsValid:Fe(t,lt,ve.inputsValid,pe,ce).wrap({recover:Ee=>(t.logger.error("Error in block model argsValid"),t.logger.error(Ee),!1)}),sdkVersion:pe==null?void 0:pe.sdkVersion,featureFlags:(pe==null?void 0:pe.featureFlags)??{},isIncompatibleWithRuntime:!1}})||{},R=o.traverse({field:W(T,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),I=Te(G,({info:ce})=>t.blockUpdateWatcher.get({currentSpec:ce.source,settings:R}));return{projectResourceId:h.resourceIdToString(s.rid),id:T,label:m??N,title:m??N,renderingMode:O,stale:((j=K.prod)==null?void 0:j.stale)!==!1||Y==="Limbo",missingReference:de.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",T)],downstreams:[...d.traverseIdsExcludingRoots("downstream",T)],calculationStatus:Y,outputErrors:(($=K.prod)==null?void 0:$.outputError)===!0,outputsError:(V=K.prod)==null?void 0:V.outputsError,exportsError:(z=K.prod)==null?void 0:z.exportsError,settings:R,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(M=G==null?void 0:G.info)==null?void 0:M.source,updates:I,sdkVersion:P,featureFlags:S,isIncompatibleWithRuntime:E,navigationState:e.getState(T)}});return{meta:a,created:new Date(i),lastModified:new Date(n),authorMarker:o.getKeyValueAsJson(cr),blocks:f}},{postprocessValue:r=>{const o=new Set,i=new Set;return{...r,blocks:r.blocks.map(n=>{var u,d;n.inputsValid||o.add(n.id),n.stale&&i.add(n.id);const a=n.stale||n.upstreams.findIndex(p=>i.has(p))!==-1,c=(a||n.outputErrors)&&!!n.inputsValid&&!n.missingReference&&n.upstreams.findIndex(p=>o.has(p))===-1,l={...n,canRun:c,stale:a,updateSuggestions:((u=n.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=n.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function Ji(s,e){const t=s.node();if(h.resourceTypesEqual(t.resourceType,wr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getUrl(new URL(r.url)).withStableType()}else if(h.resourceTypesEqual(t.resourceType,br)){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 Gi(s,e){if(s!==void 0)return J.Computable.make(t=>Ji(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.url}}}).withStableType()}function _i(s,e,t){return J.Computable.make(r=>{var a;const o=r.accessor(s).node(),i=je(o,e),n=(a=o.traverse({field:W(e,"blockPack"),assertFieldType:"Dynamic"},{field:h.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:fo,assertFieldType:"Input"}))==null?void 0:a.persist();return{url:Gi(n,t),sdkVersion:i==null?void 0:i.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Co(s,e,t){if(t===void 0)return J.Computable.make(n=>Co(s,e,n),{key:`inputs#${h.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Pr(s,e),i=o.uiState(t);return{author:r.getKeyValueAsJson(ar(e)),args:w.deepFreeze(JSON.parse(o.args(t))),ui:i!==void 0?w.deepFreeze(JSON.parse(i)):void 0}}function Ki(s,e,t){const r="outputs#"+h.resourceIdToString(s.rid)+"#"+e;return J.Computable.make(o=>{ee().logOutputRecalculations&&console.log(`blockOutput recalculation : ${r} (${o.changeSourceMarker}; ${o.bodyInvocations} invocations)`);const i=o.accessor(s).node(),n=vo(s,e);return Te(je(i,e),({cfg:a,bpId:c})=>{const l={};for(const[u,d]of Object.entries(a.outputs)){const p=Fe(t,n,d,k.extractCodeWithInfo(a),c);l[u]=J.Computable.wrapError(p,1)}return l})},{key:r}).withStableType()}function Hi(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),o=w.notEmpty(r.getKeyValueAsJson(fe)),i=[];for(const{id:n}of ne(o)){const a=je(r,n);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,u])=>u).filter(u=>Ui(u)).map(u=>u);if(c.length===0)continue;const l=vo(r.persist(),n);for(const u of c)i.push(J.Computable.wrapError(Fe(e,l,u,k.extractCodeWithInfo(a.cfg),a.bpId)))}return i})}class Wi{constructor(){C(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new J.ChangeSource});return}r.state={...t},r.change.markChanged("navigation state changed")}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...k.DefaultNavigationState},change:new J.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return J.Computable.make(t=>this.readState(t,e),{key:`navigationState#${e}`})}deleteBlock(e){const t=this.states.get(e);t!==void 0&&(this.states.delete(e),t.change.markChanged("block deleted"))}}function zi(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=w.notEmpty(t.getKeyValueAsJson(fe));return{listOfBlocks:[...ne(r)].map(o=>o.id)}})}const Xi="1",Yi="BlockFrontendState/";async function Qi(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,Xe);if(r!==$e){if(r===Xi)await Zi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,Xe,JSON.stringify($e)),await t.commit()}})}async function Zi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,fe),s.listKeyValues(e)]),o=new Map(r.map(i=>[i.key,i.value]));for(const i of ne(t)){const n=Yi+i.id,a=o.get(n),c=a?w.cachedDeserialize(a):{},l=s.createJsonGzValue(c),u=h.field(e,W(i.id,"uiState"));s.createField(u,"Dynamic",l),s.deleteKValue(e,n)}}function es(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?h.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class st{constructor(e,t,r){C(this,"rid");C(this,"overview");C(this,"overviewLight");C(this,"navigationStates",new Wi);C(this,"blockComputables",new Map);C(this,"blockFrontends",new Map);C(this,"activeConfigs");C(this,"refreshLoopResult");C(this,"abortController",new AbortController);C(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Mi(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=zi(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Hi(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ge(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await Xs.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const o=this.blockComputables.get(r);o!=null&&o.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(h.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!h.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,i=te.randomUUID()){const n=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=k.extractConfig(a);return await ie(this.env.projectHelper,this.env.pl,this.rid,o,l=>l.addBlock({id:i,label:e,renderingMode:c.renderingMode},{args:oe(c.initialArgs),uiState:oe(c.initialUiState),blockPack:n},r)),await this.projectTree.refreshState(),i}async duplicateBlock(e,t,r=void 0,o=te.randomUUID()){return await ie(this.env.projectHelper,this.env.pl,this.rid,r,i=>i.duplicateBlock(e,o,t)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,o){const i=await this.env.bpPreparer.prepare(t),n=k.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ie(this.env.projectHelper,this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,i,r?{args:n.initialArgs,uiState:n.initialUiState}:void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ie(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 ie(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 i=o.groups[0];if(i.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${i.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const n={groups:[{id:i.id,label:i.label,blocks:e.map(a=>{const c=i.blocks.find(l=>l.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(n)}),await this.projectTree.refreshState()}async runBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ge(this.env.projectHelper,this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setStates([{blockId:e,args:t}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ie(this.env.projectHelper,this.env.pl,this.rid,r,o=>o.setStates([{blockId:e,uiState:t}])),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ie(this.env.projectHelper,this.env.pl,this.rid,o,i=>{i.setStates([{blockId:e,args:t,uiState:r}])}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ie(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=h.ensureResourceIdNotNull((await r.getField(h.field(this.rid,W(e,"blockPack")))).value),i=h.ensureResourceIdNotNull((await r.getField(h.field(o,h.Pl.HolderRefField))).value),n=await r.getResourceData(i,!1),a=k.extractConfig(w.cachedDeserialize(w.notEmpty(n.data)).config);await ie(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:a.initialArgs,uiState:a.initialUiState}])}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===null)throw new Error(`Block ${e} is deleted`);if(t===void 0){const r=Ki(this.projectTree.entry(),e,this.env),i={fullState:J.Computable.make(n=>({argsAndUiState:Co(this.projectTree.entry(),e,n),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:n=>{var u,d,p;const a=(p=(d=(u=n.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,l=a&&ta(a)&&n.outputs!==void 0?sa(n.outputs):n.outputs;return{...n.argsAndUiState,outputs:l,navigationState:n.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,i),i}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=_i(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e!==null&&e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Qi(e.pl,t),await Ge(e.projectHelper,e.pl,t,o=>{});const r=await We.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:ea},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const o=r.dumpState();o.sort((n,a)=>{var c,l;return(((c=a.data)==null?void 0:c.byteLength)??0)-(((l=n.data)==null?void 0:l.byteLength)??0)});const i=We.treeDumpStats(o);await De.writeFile(`${h.resourceIdToString(t)}.json`,es(o)),await De.writeFile(`${h.resourceIdToString(t)}.stats.json`,es(i))}return new st(e,t,r)}}function ea(s){if(s.type.name.startsWith("StreamWorkdir/"))return[];switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}function ta(s){return!ra(s,"1.26.0")}function ra(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 sa(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 Cr={logger:new w.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},frontendDownloadDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,withGunzip:!0,nConcurrentDownloads:50},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3},pFrameDriverOps:{pFrameConcurrency:1,pTableConcurrency:1,pFrameCacheMaxCount:18,pFramesCacheMaxSize:8*1024*1024*1024}};function kr(s){return{blobDownloadPath:_.join(s,"download"),blobDownloadRangesCachePath:_.join(s,"downloadRangesCache"),downloadBlobToURLPath:_.join(s,"downloadToURL"),pframesSpillPath:_.join(s,"pframes")}}const ko={...Cr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function Ro(s){return{...kr(s),frontendDownloadPath:_.join(s,"frontend")}}function oa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var _e={exports:{}},mt,ts;function ot(){if(ts)return mt;ts=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,o=e-6;return mt={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:o,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:s,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},mt}var vt,rs;function nt(){return rs||(rs=1,vt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),vt}var ss;function xe(){return ss||(ss=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=ot(),i=nt();e=s.exports={};const n=e.re=[],a=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[p,r]],y=b=>{for(const[F,x]of f)b=b.split(`${F}*`).join(`${F}{0,${x}}`).split(`${F}+`).join(`${F}{1,${x}}`);return b},g=(b,F,x)=>{const D=y(F),U=d++;i(b,U,F),u[b]=U,c[U]=F,l[U]=D,n[U]=new RegExp(F,x?"g":void 0),a[U]=new RegExp(D,x?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),g("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${p}+`),g("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),g("FULL",`^${c[u.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),g("LOOSE",`^${c[u.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),g("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",c[u.COERCE],!0),g("COERCERTLFULL",c[u.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(_e,_e.exports)),_e.exports}var yt,os;function Rr(){if(os)return yt;os=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return yt=r=>r?typeof r!="object"?s:r:e,yt}var wt,ns;function Eo(){if(ns)return wt;ns=1;const s=/^[0-9]+$/,e=(r,o)=>{const i=s.test(r),n=s.test(o);return i&&n&&(r=+r,o=+o),r===o?0:i&&!n?-1:n&&!i?1:r<o?-1:1};return wt={compareIdentifiers:e,rcompareIdentifiers:(r,o)=>e(o,r)},wt}var bt,is;function re(){if(is)return bt;is=1;const s=nt(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=ot(),{safeRe:r,t:o}=xe(),i=Rr(),{compareIdentifiers:n}=Eo();class a{constructor(l,u){if(u=i(u),l instanceof a){if(l.loose===!!u.loose&&l.includePrerelease===!!u.includePrerelease)return l;l=l.version}else if(typeof l!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof l}".`);if(l.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",l,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=l.trim().match(u.loose?r[o.LOOSE]:r[o.FULL]);if(!d)throw new TypeError(`Invalid Version: ${l}`);if(this.raw=l,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(p=>{if(/^[0-9]+$/.test(p)){const f=+p;if(f>=0&&f<t)return f}return p}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(l){if(s("SemVer.compare",this.version,this.options,l),!(l instanceof a)){if(typeof l=="string"&&l===this.version)return 0;l=new a(l,this.options)}return l.version===this.version?0:this.compareMain(l)||this.comparePre(l)}compareMain(l){return l instanceof a||(l=new a(l,this.options)),n(this.major,l.major)||n(this.minor,l.minor)||n(this.patch,l.patch)}comparePre(l){if(l instanceof a||(l=new a(l,this.options)),this.prerelease.length&&!l.prerelease.length)return-1;if(!this.prerelease.length&&l.prerelease.length)return 1;if(!this.prerelease.length&&!l.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=l.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return n(d,p)}while(++u)}compareBuild(l){l instanceof a||(l=new a(l,this.options));let u=0;do{const d=this.build[u],p=l.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return n(d,p)}while(++u)}inc(l,u,d){if(l.startsWith("pre")){if(!u&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(u){const p=`-${u}`.match(this.options.loose?r[o.PRERELEASELOOSE]:r[o.PRERELEASE]);if(!p||p[1]!==u)throw new Error(`invalid identifier: ${u}`)}}switch(l){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),n(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${l}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return bt=a,bt}var St,as;function Pe(){if(as)return St;as=1;const s=re();return St=(t,r,o=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(i){if(!o)return null;throw i}},St}var Pt,cs;function na(){if(cs)return Pt;cs=1;const s=Pe();return Pt=(t,r)=>{const o=s(t,r);return o?o.version:null},Pt}var Ct,ls;function ia(){if(ls)return Ct;ls=1;const s=Pe();return Ct=(t,r)=>{const o=s(t.trim().replace(/^[=v]+/,""),r);return o?o.version:null},Ct}var kt,us;function aa(){if(us)return kt;us=1;const s=re();return kt=(t,r,o,i,n)=>{typeof o=="string"&&(n=i,i=o,o=void 0);try{return new s(t instanceof s?t.version:t,o).inc(r,i,n).version}catch{return null}},kt}var Rt,ds;function ca(){if(ds)return Rt;ds=1;const s=Pe();return Rt=(t,r)=>{const o=s(t,null,!0),i=s(r,null,!0),n=o.compare(i);if(n===0)return null;const a=n>0,c=a?o:i,l=a?i:o,u=!!c.prerelease.length;if(!!l.prerelease.length&&!u){if(!l.patch&&!l.minor)return"major";if(l.compareMain(c)===0)return l.minor&&!l.patch?"minor":"patch"}const p=u?"pre":"";return o.major!==i.major?p+"major":o.minor!==i.minor?p+"minor":o.patch!==i.patch?p+"patch":"prerelease"},Rt}var Et,ps;function la(){if(ps)return Et;ps=1;const s=re();return Et=(t,r)=>new s(t,r).major,Et}var Ot,fs;function ua(){if(fs)return Ot;fs=1;const s=re();return Ot=(t,r)=>new s(t,r).minor,Ot}var Tt,hs;function da(){if(hs)return Tt;hs=1;const s=re();return Tt=(t,r)=>new s(t,r).patch,Tt}var Ft,gs;function pa(){if(gs)return Ft;gs=1;const s=Pe();return Ft=(t,r)=>{const o=s(t,r);return o&&o.prerelease.length?o.prerelease:null},Ft}var It,ms;function le(){if(ms)return It;ms=1;const s=re();return It=(t,r,o)=>new s(t,o).compare(new s(r,o)),It}var Dt,vs;function fa(){if(vs)return Dt;vs=1;const s=le();return Dt=(t,r,o)=>s(r,t,o),Dt}var $t,ys;function ha(){if(ys)return $t;ys=1;const s=le();return $t=(t,r)=>s(t,r,!0),$t}var Lt,ws;function Er(){if(ws)return Lt;ws=1;const s=re();return Lt=(t,r,o)=>{const i=new s(t,o),n=new s(r,o);return i.compare(n)||i.compareBuild(n)},Lt}var At,bs;function ga(){if(bs)return At;bs=1;const s=Er();return At=(t,r)=>t.sort((o,i)=>s(o,i,r)),At}var Nt,Ss;function ma(){if(Ss)return Nt;Ss=1;const s=Er();return Nt=(t,r)=>t.sort((o,i)=>s(i,o,r)),Nt}var jt,Ps;function it(){if(Ps)return jt;Ps=1;const s=le();return jt=(t,r,o)=>s(t,r,o)>0,jt}var Bt,Cs;function Or(){if(Cs)return Bt;Cs=1;const s=le();return Bt=(t,r,o)=>s(t,r,o)<0,Bt}var xt,ks;function Oo(){if(ks)return xt;ks=1;const s=le();return xt=(t,r,o)=>s(t,r,o)===0,xt}var Vt,Rs;function To(){if(Rs)return Vt;Rs=1;const s=le();return Vt=(t,r,o)=>s(t,r,o)!==0,Vt}var Ut,Es;function Tr(){if(Es)return Ut;Es=1;const s=le();return Ut=(t,r,o)=>s(t,r,o)>=0,Ut}var qt,Os;function Fr(){if(Os)return qt;Os=1;const s=le();return qt=(t,r,o)=>s(t,r,o)<=0,qt}var Mt,Ts;function Fo(){if(Ts)return Mt;Ts=1;const s=Oo(),e=To(),t=it(),r=Tr(),o=Or(),i=Fr();return Mt=(a,c,l,u)=>{switch(c){case"===":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a===l;case"!==":return typeof a=="object"&&(a=a.version),typeof l=="object"&&(l=l.version),a!==l;case"":case"=":case"==":return s(a,l,u);case"!=":return e(a,l,u);case">":return t(a,l,u);case">=":return r(a,l,u);case"<":return o(a,l,u);case"<=":return i(a,l,u);default:throw new TypeError(`Invalid operator: ${c}`)}},Mt}var Jt,Fs;function va(){if(Fs)return Jt;Fs=1;const s=re(),e=Pe(),{safeRe:t,t:r}=xe();return Jt=(i,n)=>{if(i instanceof s)return i;if(typeof i=="number"&&(i=String(i)),typeof i!="string")return null;n=n||{};let a=null;if(!n.rtl)a=i.match(n.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=n.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(i))&&(!a||a.index+a[0].length!==i.length);)(!a||y.index+y[0].length!==a.index+a[0].length)&&(a=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(a===null)return null;const c=a[2],l=a[3]||"0",u=a[4]||"0",d=n.includePrerelease&&a[5]?`-${a[5]}`:"",p=n.includePrerelease&&a[6]?`+${a[6]}`:"";return e(`${c}.${l}.${u}${d}${p}`,n)},Jt}var Gt,Is;function ya(){if(Is)return Gt;Is=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const i=this.map.keys().next().value;this.delete(i)}this.map.set(t,r)}return this}}return Gt=s,Gt}var _t,Ds;function ue(){if(Ds)return _t;Ds=1;const s=/\s+/g;class e{constructor(v,P){if(P=o(P),v instanceof e)return v.loose===!!P.loose&&v.includePrerelease===!!P.includePrerelease?v:new e(v.raw,P);if(v instanceof i)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=P,this.loose=!!P.loose,this.includePrerelease=!!P.includePrerelease,this.raw=v.trim().replace(s," "),this.set=this.raw.split("||").map(S=>this.parseRange(S.trim())).filter(S=>S.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const S=this.set[0];if(this.set=this.set.filter(E=>!g(E[0])),this.set.length===0)this.set=[S];else if(this.set.length>1){for(const E of this.set)if(E.length===1&&b(E[0])){this.set=[E];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let v=0;v<this.set.length;v++){v>0&&(this.formatted+="||");const P=this.set[v];for(let S=0;S<P.length;S++)S>0&&(this.formatted+=" "),this.formatted+=P[S].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const S=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,E=r.get(S);if(E)return E;const R=this.options.loose,I=R?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];v=v.replace(I,G(this.options.includePrerelease)),n("hyphen replace",v),v=v.replace(c[l.COMPARATORTRIM],u),n("comparator trim",v),v=v.replace(c[l.TILDETRIM],d),n("tilde trim",v),v=v.replace(c[l.CARETTRIM],p),n("caret trim",v);let j=v.split(" ").map(M=>x(M,this.options)).join(" ").split(/\s+/).map(M=>Y(M,this.options));R&&(j=j.filter(M=>(n("loose invalid filter",M,this.options),!!M.match(c[l.COMPARATORLOOSE])))),n("range list",j);const $=new Map,V=j.map(M=>new i(M,this.options));for(const M of V){if(g(M))return[M];$.set(M.value,M)}$.size>1&&$.has("")&&$.delete("");const z=[...$.values()];return r.set(S,z),z}intersects(v,P){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(S=>F(S,P)&&v.set.some(E=>F(E,P)&&S.every(R=>E.every(I=>R.intersects(I,P)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new a(v,this.options)}catch{return!1}for(let P=0;P<this.set.length;P++)if(X(this.set[P],v,this.options))return!0;return!1}}_t=e;const t=ya(),r=new t,o=Rr(),i=at(),n=nt(),a=re(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=xe(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=ot(),g=m=>m.value==="<0.0.0-0",b=m=>m.value==="",F=(m,v)=>{let P=!0;const S=m.slice();let E=S.pop();for(;P&&S.length;)P=S.every(R=>E.intersects(R,v)),E=S.pop();return P},x=(m,v)=>(n("comp",m,v),m=T(m,v),n("caret",m),m=U(m,v),n("tildes",m),m=O(m,v),n("xrange",m),m=de(m,v),n("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",U=(m,v)=>m.trim().split(/\s+/).map(P=>q(P,v)).join(" "),q=(m,v)=>{const P=v.loose?c[l.TILDELOOSE]:c[l.TILDE];return m.replace(P,(S,E,R,I,j)=>{n("tilde",m,S,E,R,I,j);let $;return D(E)?$="":D(R)?$=`>=${E}.0.0 <${+E+1}.0.0-0`:D(I)?$=`>=${E}.${R}.0 <${E}.${+R+1}.0-0`:j?(n("replaceTilde pr",j),$=`>=${E}.${R}.${I}-${j} <${E}.${+R+1}.0-0`):$=`>=${E}.${R}.${I} <${E}.${+R+1}.0-0`,n("tilde return",$),$})},T=(m,v)=>m.trim().split(/\s+/).map(P=>N(P,v)).join(" "),N=(m,v)=>{n("caret",m,v);const P=v.loose?c[l.CARETLOOSE]:c[l.CARET],S=v.includePrerelease?"-0":"";return m.replace(P,(E,R,I,j,$)=>{n("caret",m,E,R,I,j,$);let V;return D(R)?V="":D(I)?V=`>=${R}.0.0${S} <${+R+1}.0.0-0`:D(j)?R==="0"?V=`>=${R}.${I}.0${S} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.0${S} <${+R+1}.0.0-0`:$?(n("replaceCaret pr",$),R==="0"?I==="0"?V=`>=${R}.${I}.${j}-${$} <${R}.${I}.${+j+1}-0`:V=`>=${R}.${I}.${j}-${$} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.${j}-${$} <${+R+1}.0.0-0`):(n("no pr"),R==="0"?I==="0"?V=`>=${R}.${I}.${j}${S} <${R}.${I}.${+j+1}-0`:V=`>=${R}.${I}.${j}${S} <${R}.${+I+1}.0-0`:V=`>=${R}.${I}.${j} <${+R+1}.0.0-0`),n("caret return",V),V})},O=(m,v)=>(n("replaceXRanges",m,v),m.split(/\s+/).map(P=>K(P,v)).join(" ")),K=(m,v)=>{m=m.trim();const P=v.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return m.replace(P,(S,E,R,I,j,$)=>{n("xRange",m,S,E,R,I,j,$);const V=D(R),z=V||D(I),M=z||D(j),ce=M;return E==="="&&ce&&(E=""),$=v.includePrerelease?"-0":"",V?E===">"||E==="<"?S="<0.0.0-0":S="*":E&&ce?(z&&(I=0),j=0,E===">"?(E=">=",z?(R=+R+1,I=0,j=0):(I=+I+1,j=0)):E==="<="&&(E="<",z?R=+R+1:I=+I+1),E==="<"&&($="-0"),S=`${E+R}.${I}.${j}${$}`):z?S=`>=${R}.0.0${$} <${+R+1}.0.0-0`:M&&(S=`>=${R}.${I}.0${$} <${R}.${+I+1}.0-0`),n("xRange return",S),S})},de=(m,v)=>(n("replaceStars",m,v),m.trim().replace(c[l.STAR],"")),Y=(m,v)=>(n("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?l.GTE0PRE:l.GTE0],"")),G=m=>(v,P,S,E,R,I,j,$,V,z,M,ce)=>(D(S)?P="":D(E)?P=`>=${S}.0.0${m?"-0":""}`:D(R)?P=`>=${S}.${E}.0${m?"-0":""}`:I?P=`>=${P}`:P=`>=${P}${m?"-0":""}`,D(V)?$="":D(z)?$=`<${+V+1}.0.0-0`:D(M)?$=`<${V}.${+z+1}.0-0`:ce?$=`<=${V}.${z}.${M}-${ce}`:m?$=`<${V}.${z}.${+M+1}-0`:$=`<=${$}`,`${P} ${$}`.trim()),X=(m,v,P)=>{for(let S=0;S<m.length;S++)if(!m[S].test(v))return!1;if(v.prerelease.length&&!P.includePrerelease){for(let S=0;S<m.length;S++)if(n(m[S].semver),m[S].semver!==i.ANY&&m[S].semver.prerelease.length>0){const E=m[S].semver;if(E.major===v.major&&E.minor===v.minor&&E.patch===v.patch)return!0}return!1}return!0};return _t}var Kt,$s;function at(){if($s)return Kt;$s=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(" "),n("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,n("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 a(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(n("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new a(u,this.options)}catch{return!1}return i(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||i(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||i(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}Kt=e;const t=Rr(),{safeRe:r,t:o}=xe(),i=Fo(),n=nt(),a=re(),c=ue();return Kt}var Ht,Ls;function ct(){if(Ls)return Ht;Ls=1;const s=ue();return Ht=(t,r,o)=>{try{r=new s(r,o)}catch{return!1}return r.test(t)},Ht}var Wt,As;function wa(){if(As)return Wt;As=1;const s=ue();return Wt=(t,r)=>new s(t,r).set.map(o=>o.map(i=>i.value).join(" ").trim().split(" ")),Wt}var zt,Ns;function ba(){if(Ns)return zt;Ns=1;const s=re(),e=ue();return zt=(r,o,i)=>{let n=null,a=null,c=null;try{c=new e(o,i)}catch{return null}return r.forEach(l=>{c.test(l)&&(!n||a.compare(l)===-1)&&(n=l,a=new s(n,i))}),n},zt}var Xt,js;function Sa(){if(js)return Xt;js=1;const s=re(),e=ue();return Xt=(r,o,i)=>{let n=null,a=null,c=null;try{c=new e(o,i)}catch{return null}return r.forEach(l=>{c.test(l)&&(!n||a.compare(l)===1)&&(n=l,a=new s(n,i))}),n},Xt}var Yt,Bs;function Pa(){if(Bs)return Yt;Bs=1;const s=re(),e=ue(),t=it();return Yt=(o,i)=>{o=new e(o,i);let n=new s("0.0.0");if(o.test(n)||(n=new s("0.0.0-0"),o.test(n)))return n;n=null;for(let a=0;a<o.set.length;++a){const c=o.set[a];let l=null;c.forEach(u=>{const d=new s(u.semver.version);switch(u.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!l||t(d,l))&&(l=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),l&&(!n||t(n,l))&&(n=l)}return n&&o.test(n)?n:null},Yt}var Qt,xs;function Ca(){if(xs)return Qt;xs=1;const s=ue();return Qt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Qt}var Zt,Vs;function Ir(){if(Vs)return Zt;Vs=1;const s=re(),e=at(),{ANY:t}=e,r=ue(),o=ct(),i=it(),n=Or(),a=Fr(),c=Tr();return Zt=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,g,b,F,x;switch(p){case">":y=i,g=a,b=n,F=">",x=">=";break;case"<":y=n,g=c,b=i,F="<",x="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const U=d.set[D];let q=null,T=null;if(U.forEach(N=>{N.semver===t&&(N=new e(">=0.0.0")),q=q||N,T=T||N,y(N.semver,q.semver,f)?q=N:b(N.semver,T.semver,f)&&(T=N)}),q.operator===F||q.operator===x||(!T.operator||T.operator===F)&&g(u,T.semver))return!1;if(T.operator===x&&b(u,T.semver))return!1}return!0},Zt}var er,Us;function ka(){if(Us)return er;Us=1;const s=Ir();return er=(t,r,o)=>s(t,r,">",o),er}var tr,qs;function Ra(){if(qs)return tr;qs=1;const s=Ir();return tr=(t,r,o)=>s(t,r,"<",o),tr}var rr,Ms;function Ea(){if(Ms)return rr;Ms=1;const s=ue();return rr=(t,r,o)=>(t=new s(t,o),r=new s(r,o),t.intersects(r,o)),rr}var sr,Js;function Oa(){if(Js)return sr;Js=1;const s=ct(),e=le();return sr=(t,r,o)=>{const i=[];let n=null,a=null;const c=t.sort((p,f)=>e(p,f,o));for(const p of c)s(p,r,o)?(a=p,n||(n=p)):(a&&i.push([n,a]),a=null,n=null);n&&i.push([n,null]);const l=[];for(const[p,f]of i)p===f?l.push(p):!f&&p===c[0]?l.push("*"):f?p===c[0]?l.push(`<=${f}`):l.push(`${p} - ${f}`):l.push(`>=${p}`);const u=l.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},sr}var or,Gs;function Ta(){if(Gs)return or;Gs=1;const s=ue(),e=at(),{ANY:t}=e,r=ct(),o=le(),i=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const g of d.set){for(const b of p.set){const F=c(g,b,f);if(y=y||F!==null,F)continue e}if(y)return!1}return!0},n=[new e(">=0.0.0-0")],a=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=n:d=a}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=a}const y=new Set;let g,b;for(const O of d)O.operator===">"||O.operator===">="?g=l(g,O,f):O.operator==="<"||O.operator==="<="?b=u(b,O,f):y.add(O.semver);if(y.size>1)return null;let F;if(g&&b){if(F=o(g.semver,b.semver,f),F>0)return null;if(F===0&&(g.operator!==">="||b.operator!=="<="))return null}for(const O of y){if(g&&!r(O,String(g),f)||b&&!r(O,String(b),f))return null;for(const K of p)if(!r(O,String(K),f))return!1;return!0}let x,D,U,q,T=b&&!f.includePrerelease&&b.semver.prerelease.length?b.semver:!1,N=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1;T&&T.prerelease.length===1&&b.operator==="<"&&T.prerelease[0]===0&&(T=!1);for(const O of p){if(q=q||O.operator===">"||O.operator===">=",U=U||O.operator==="<"||O.operator==="<=",g){if(N&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===N.major&&O.semver.minor===N.minor&&O.semver.patch===N.patch&&(N=!1),O.operator===">"||O.operator===">="){if(x=l(g,O,f),x===O&&x!==g)return!1}else if(g.operator===">="&&!r(g.semver,String(O),f))return!1}if(b){if(T&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===T.major&&O.semver.minor===T.minor&&O.semver.patch===T.patch&&(T=!1),O.operator==="<"||O.operator==="<="){if(D=u(b,O,f),D===O&&D!==b)return!1}else if(b.operator==="<="&&!r(b.semver,String(O),f))return!1}if(!O.operator&&(b||g)&&F!==0)return!1}return!(g&&U&&!b&&F!==0||b&&q&&!g&&F!==0||N||T)},l=(d,p,f)=>{if(!d)return p;const y=o(d.semver,p.semver,f);return y>0?d:y<0||p.operator===">"&&d.operator===">="?p:d},u=(d,p,f)=>{if(!d)return p;const y=o(d.semver,p.semver,f);return y<0?d:y>0||p.operator==="<"&&d.operator==="<="?p:d};return or=i,or}var nr,_s;function Fa(){if(_s)return nr;_s=1;const s=xe(),e=ot(),t=re(),r=Eo(),o=Pe(),i=na(),n=ia(),a=aa(),c=ca(),l=la(),u=ua(),d=da(),p=pa(),f=le(),y=fa(),g=ha(),b=Er(),F=ga(),x=ma(),D=it(),U=Or(),q=Oo(),T=To(),N=Tr(),O=Fr(),K=Fo(),de=va(),Y=at(),G=ue(),X=ct(),m=wa(),v=ba(),P=Sa(),S=Pa(),E=Ca(),R=Ir(),I=ka(),j=Ra(),$=Ea(),V=Oa(),z=Ta();return nr={parse:o,valid:i,clean:n,inc:a,diff:c,major:l,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:g,compareBuild:b,sort:F,rsort:x,gt:D,lt:U,eq:q,neq:T,gte:N,lte:O,cmp:K,coerce:de,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:P,minVersion:S,validRange:E,outside:R,gtr:I,ltr:j,intersects:$,simplifyRange:V,subset:z,SemVer:t,re:s.re,src:s.src,tokens:s.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},nr}var Ia=Fa();const Da=oa(Ia),$a={minDelay:1500},La="__no_updates__";class Aa extends J.PollComputablePool{constructor(t,r,o={}){super({...o,...$a},r);C(this,"http");C(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_${oe(t)}`;default:return La}}async readValue(t){var r,o;try{const i=t.currentSpec;switch(i.type){case"dev-v1":try{const n=await mr(i.folder);return n===i.mtime?{suggestions:[]}:{mainSuggestion:{...i,mtime:n},suggestions:[]}}catch(n){return this.logger.warn(n),{suggestions:[]}}case"dev-v2":try{const n=await Z.tryLoadPackDescription(i.folder,this.logger);if(n===void 0)return{suggestions:[]};const a=await et(n);return a===i.mtime?{suggestions:[]}:{mainSuggestion:{...i,mtime:a},suggestions:[]}}catch(n){return this.logger.warn(n),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:n,skipVersion:a}=t.settings;if(n==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(i.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(i.channel===void 0)if(await c.getLatestOverview(i.id,Q.StableChannel))l=Q.StableChannel;else{if(await c.getLatestOverview(i.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(i.id)}`),{suggestions:[]};l=Q.AnyChannel}else l=i.channel;const u=await c.getUpdateSuggestions(i.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(n){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(o=u.find(y=>y.type==="patch"))==null?void 0:o.update;break}const p=u.map(({type:y,update:g})=>({type:y,update:{...i,id:{...i.id,version:g}}}));if(d===void 0)return{suggestions:p};if(a!==void 0&&Da.lte(d,a))return{suggestions:p};const f={...i,id:{...i.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(n){return this.logger.warn(n),{suggestions:[]}}default:return{suggestions:[]}}}catch(i){return this.logger.warn(i),{suggestions:[]}}}resultsEqual(t,r){return oe(t)===oe(r)}}class Ks{constructor(){C(this,"resources",new Map);C(this,"disposeQueue",Promise.resolve())}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;w.isDisposable(r)?this.disposeQueue.then(()=>r[Symbol.dispose]()):w.isAsyncDisposable(r)&&this.disposeQueue.then(()=>r[Symbol.asyncDispose]())}}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){const t=this.resources.get(e);if(t===void 0)throw new Error(`resource not found, key = ${e}`);return t.resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function Ie(s){return String(s.id)}const Na=["Int","Long","Float","Double","String","Bytes"];function Oe(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}function Hs(s){return"partitionFilters"in s?{...s,partitionFilters:Oe(s.partitionFilters),filters:Oe(s.filters)}:{...s,partitionFilters:Oe(s.filters.filter(e=>e.column.type==="axis")),filters:Oe(s.filters.filter(e=>e.column.type==="column"))}}const we=(s,e)=>typeof e=="bigint"?e.toString():e;class ja{constructor(e,t){C(this,"perFrame",new Map);C(this,"global");C(this,"disposeListeners",new Map);this.logger=e,this.ops=t,this.global=new ze.LRUCache({maxSize:this.ops.pFramesCacheMaxSize,dispose:(r,o,i)=>{var a,c;i==="evict"&&((a=this.perFrame.get(r.resource.pFrame))==null||a.delete(o)),((c=this.perFrame.get(r.resource.pFrame))==null?void 0:c.size)===0&&this.perFrame.delete(r.resource.pFrame);const n=this.disposeListeners.get(o);this.disposeListeners.delete(o),r.resource.disposeSignal.removeEventListener("abort",n),r.unref(),ee().logPFrameRequests&&this.logger.info(`calculateTableData cache - removed PTable ${o}`)}})}cache(e,t){const r=e.key;ee().logPFrameRequests&&this.logger.info(`calculateTableData cache - added PTable ${r} with size ${t}`),this.global.set(r,e,{size:t});let o=this.perFrame.get(e.resource.pFrame);o||(o=new ze.LRUCache({max:this.ops.pFrameCacheMaxCount,dispose:(n,a,c)=>{c==="evict"&&this.global.delete(a)}}),this.perFrame.set(e.resource.pFrame,o)),o.set(r,e);const i=()=>{var n;(n=this.perFrame.get(e.resource.pFrame))==null||n.delete(r),this.global.delete(r)};this.disposeListeners.set(r,i),e.resource.disposeSignal.addEventListener("abort",i)}}class Ba{constructor(e,t,r,o){C(this,"pFramePromise");C(this,"abortController",new AbortController);C(this,"blobIdToResource",new Map);C(this,"blobHandleComputables",new Map);C(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)try{await r.awaitStableFullValue(this.disposeSignal)}catch(o){if(k.isAbortError(o))break;throw o}});C(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await Zs.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const i=(a,c)=>this.logger[a](c);for(const a of o)for(const c of qn(a.data))this.blobIdToResource.set(Ie(c),c);const n=[...new Map(o.map(a=>({...a,data:Mn(a.data,Ie)})).map(a=>[oe(a),a])).values()];try{const a=new Ys.PFrame(this.spillPath,i);a.setDataSource(this);const c=[];for(const l of n){if(a.addColumnSpec(l.id,l.spec),l.data.type==="ParquetPartitioned")throw new k.PFrameDriverError(`ParquetPartitioned data is not supported yet, column: ${JSON.stringify(l)}, data: ${JSON.stringify(l.data)}`);c.push(a.setColumnData(l.id,l.data,{signal:this.disposeSignal}))}this.pFramePromise=Promise.all(c).then(()=>a).catch(l=>{throw this.dispose(),a.dispose(),new k.PFrameDriverError(`PFrame creation failed asynchronously, columns: ${JSON.stringify(n)}, error: ${k.ensureError(l)}`)})}catch(a){throw new k.PFrameDriverError(`PFrame creation failed synchronously, columns: ${JSON.stringify(n)}, error: ${k.ensureError(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 k.PFrameDriverError(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}dispose(){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState()}async[Symbol.asyncDispose](){this.dispose(),await this.pFramePromise.then(e=>e.dispose()).catch(()=>{})}}class ir{constructor(e,t,r,o){C(this,"abortController",new AbortController);C(this,"combinedDisposeSignal");this.pFrame=e,this.pTablePromise=r,this.predecessor=o,this.combinedDisposeSignal=AbortSignal.any([t,this.abortController.signal])}get disposeSignal(){return this.combinedDisposeSignal}async[Symbol.asyncDispose](){var e;this.abortController.abort(),await this.pTablePromise.then(t=>t.dispose()).catch(()=>{}),(e=this.predecessor)==null||e.unref()}}class Dr{constructor(e,t,r,o){C(this,"pFrames");C(this,"pTables");C(this,"pTableCache");C(this,"frameConcurrencyLimiter");C(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const i=new w.ConcurrencyLimitingExecutor(o.pFrameConcurrency);this.frameConcurrencyLimiter=i,this.tableConcurrencyLimiter=new w.ConcurrencyLimitingExecutor(o.pTableConcurrency),this.pTableCache=new ja(this.logger,o),this.pFrames=new class extends Ks{constructor(n,a,c){super(),this.blobDriver=n,this.logger=a,this.spillPath=c}acquire(n){return super.acquire(n)}getByKey(n){const a=super.tryGetByKey(n);if(!a)throw new k.PFrameDriverError(`PFrame not found, handle = ${n}`);return a}createNewResource(n){return ee().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`),new Ba(this.blobDriver,this.logger,this.spillPath,n)}calculateParamsKey(n){try{return Va(n)}catch(a){throw k.isPFrameDriverError(a)?a:new k.PFrameDriverError(`PFrame handle calculation failed, request: ${JSON.stringify(n,we)}, error: ${k.ensureError(a)}`)}}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends Ks{constructor(n){super(),this.pFrames=n}getByKey(n){const a=super.tryGetByKey(n);if(!a)throw new k.PFrameDriverError(`PTable not found, handle = ${n}`);return a}createNewResource(n){ee().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`);const a=n.pFrameHandle,{pFramePromise:c,disposeSignal:l}=this.pFrames.getByKey(a);if(n.def.sorting.length>0){const d=this.acquire({...n,def:{...n.def,sorting:[]}}),{resource:{pTablePromise:p}}=d,f=p.then(y=>y.sort(n.def.sorting));return new ir(a,l,f,d)}if(n.def.filters.length>0){const d=this.acquire({...n,def:{...n.def,filters:[]}}),{resource:{pTablePromise:p}}=d,f=p.then(y=>y.filter(n.def.filters));return new ir(a,l,f,d)}const u=c.then(d=>d.createTable({src:He(n.def.src),filters:n.def.partitionFilters}));return new ir(a,l,u)}calculateParamsKey(n){try{return xa(n)}catch(a){throw new k.PFrameDriverError(`PTable handle calculation failed, request: ${JSON.stringify(n)}, error: ${k.ensureError(a)}`)}}}(this.pFrames)}async pprofDump(){return await Ys.PFrame.pprofDump()}static async init(e,t,r,o){const i=Go.resolve(r);return await w.emptyDir(i),new Dr(e,t,i,o)}createPFrame(e,t){const r=e.filter(i=>Na.find(n=>n===i.spec.valueType)).map(i=>k.mapPObjectData(i,n=>We.isPlTreeNodeAccessor(n)?Xn(n):k.isDataInfo(n)?k.mapDataInfo(n,a=>a.resourceInfo):Yn(i.spec,n))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=Hs(e),o=this.createPFrame(k.extractAllColumns(r.src),t),i=k.mapPTableDef(r,a=>a.id),n=this.pTables.acquire({def:i,pFrameHandle:o});return ee().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(n)}): ${JSON.stringify(k.mapPTableDef(r,a=>a.spec),we)}`),t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(a=>[oe(a),a])).values()],qualifications:[]}]:[]},{pFramePromise:o}=this.pFrames.getByKey(e);return{hits:(await(await o).findColumns(r)).hits.filter(a=>a.mappingVariants.length===0||a.mappingVariants.some(c=>c.qualifications.forHit.length===0&&c.qualifications.forQueries.every(l=>l.length===0))).map(a=>a.hit)}}async getColumnSpec(e,t){const{pFramePromise:r}=this.pFrames.getByKey(e);return await(await r).getColumnSpec(t)}async listColumns(e){const{pFramePromise:t}=this.pFrames.getByKey(e);return await(await t).listColumns()}async calculateTableData(e,t,r,o){ee().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,we)}`);const i=this.pTables.acquire({pFrameHandle:e,def:Hs(t)}),{resource:{pTablePromise:n,disposeSignal:a}}=i,c=await n,l=AbortSignal.any([o,a].filter(u=>!!u));return await this.frameConcurrencyLimiter.run(async()=>{try{const u=c.getSpec(),d=await c.getData([...u.keys()],{range:r,signal:l}),p=await c.getFootprint({withPredecessors:!0,signal:l});return this.pTableCache.cache(i,p),u.map((f,y)=>({spec:f,data:d[y]}))}catch(u){throw i.unref(),u}})}async getUniqueValues(e,t,r){ee().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,we)}`);const{pFramePromise:o,disposeSignal:i}=this.pFrames.getByKey(e),n=await o,a=AbortSignal.any([r,i].filter(c=>!!c));return await this.frameConcurrencyLimiter.run(async()=>await n.getUniqueValues({...t,filters:Oe(t.filters)},{signal:a}))}async getSpec(e){const{pTablePromise:t}=this.pTables.getByKey(e);return(await t).getSpec()}async getShape(e,t){const{pTablePromise:r,disposeSignal:o}=this.pTables.getByKey(e),i=await r,n=AbortSignal.any([t,o].filter(a=>!!a));return await this.tableConcurrencyLimiter.run(async()=>await i.getShape({signal:n}))}async getData(e,t,r,o){const{pTablePromise:i,disposeSignal:n}=this.pTables.getByKey(e),a=await i,c=AbortSignal.any([o,n].filter(l=>!!l));return await this.tableConcurrencyLimiter.run(async()=>await a.getData(t,{range:r,signal:c}))}}function He(s){switch(s.type){case"column":return{type:"column",columnId:s.column};case"slicedColumn":return{type:"slicedColumn",columnId:s.column,newId:s.newId,axisFilters:s.axisFilters};case"inlineColumn":return{type:"inlineColumn",newId:s.column.id,spec:s.column.spec,dataInfo:{type:"Json",keyLength:s.column.spec.axesSpec.length,data:s.column.data.reduce((e,t)=>(e[JSON.stringify(t.key)]=t.val,e),{})}};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>He(e))};case"outer":return{type:"outer",primary:He(s.primary),secondary:s.secondary.map(e=>He(e))};default:w.assertNever(s)}}function xa(s){const e=te.createHash("sha256");return e.update(oe(s)),e.digest().toString("hex")}function Va(s){const e=[...s].map(r=>k.mapPObjectData(r,o=>{let i;const n=o.type;switch(n){case"Json":i={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":i={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:Ie(c)}))};break;case"BinaryPartitioned":i={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[Ie(c.index),Ie(c.values)]}))};break;case"ParquetPartitioned":throw new k.PFrameDriverError(`unsupported resource type: ${JSON.stringify(n)}`);default:throw new k.PFrameDriverError(`unsupported resource type: ${JSON.stringify(n)}`)}return i.payload.sort((a,c)=>a.key.localeCompare(c.key)),i}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=te.createHash("sha256");return t.update(oe(e)),t.digest().toString("hex")}async function Io(s,e,t,r){const o={...Cr,...kr(e),...r},i=new w.HmacSha256Signer(o.localSecret),n=H.createDownloadClient(o.logger,s,o.localProjections),a=H.createLogsClient(s,o.logger),c=H.createUploadBlobClient(s,o.logger),l=H.createUploadProgressClient(s,o.logger),u=await H.DownloadDriver.init(o.logger,n,a,o.blobDownloadPath,o.blobDownloadRangesCachePath,i,o.blobDriverOps),d=new H.DownloadBlobToURLDriver(o.logger,i,n,o.downloadBlobToURLPath,o.downloadBlobToURLDriverOps),p=new H.UploadDriver(o.logger,i,c,l,o.uploadDriverOps),f=new H.LogsStreamDriver(o.logger,a,o.logStreamDriverOps),y=new H.LogsDriver(o.logger,f,u),g=await H.LsDriver.init(o.logger,s,i,o.localProjections,o.openFileDialogCallback,o.virtualLocalStoragesOverride),b=await Dr.init(u,o.logger,o.pframesSpillPath,o.pFrameDriverOps),F=new H.DownloadUrlDriver(o.logger,s.httpDispatcher,t,i,o.frontendDownloadDriverOps);return{blobDriver:u,blobToURLDriver:d,logDriver:y,lsDriver:g,signer:i,uploadDriver:p,pFrameDriver:b,frontendDriver:F}}class Ua{constructor(e){C(this,"enrichmentTargetsCache",new ze.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 Vi(this.quickJs,t.enrichmentTargets,k.extractCodeWithInfo(t),r)}getEnrichmentTargets(e,t,r){const o={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(o);const i=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(i,{context:o}).value}}class $r{constructor(e,t,r,o,i,n,a,c){C(this,"pl");C(this,"projectList");C(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=i,this.projectListTree=n,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}addRuntimeCapability(e,t=!0){this.env.runtimeCapabilities.addSupportedRequirement(e,t)}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const i=await Un(o,e);return o.createField(h.field(this.projectListResourceId,t),"Dynamic",i),await o.commit(),await h.toGlobalResourceId(i)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ie(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(h.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(h.field(this.projectListResourceId,e))).value;if(h.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await st.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 w.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const o={...ko,...Ro(t),...r};o.defaultTreeOptions.logStat=ee().logTreeStats,o.debugOps.dumpInitialTreeState=ee().dumpInitialTreeState;const i=await e.withWriteTx("MLInitialization",async b=>{const F=h.field(b.clientRoot,dn);b.createField(F,"Dynamic");const x=await b.getField(F);if(h.isNullResourceId(x.value)){const D=b.createEphemeral(ro);return b.lock(D),b.setField(F,D),await b.commit(),await D.globalId}else return x.value}),n=o.logger,a=await Io(e,t,o.frontendDownloadPath,o),c=new Ze.RetryAgent(e.httpDispatcher),l=new to(c),u=new Ln(l,a.signer,c),d=await ge.getQuickJS(),p=new k.RuntimeCapabilities;p.addSupportedRequirement("requiresModelAPIVersion",1);const f={pl:e,blockEventDispatcher:new w.BlockEventDispatcher,signer:a.signer,logger:n,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:u,frontendDownloadDriver:a.frontendDriver,driverKit:a,blockUpdateWatcher:new Aa(l,n,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),runtimeCapabilities:p,quickJs:d,projectHelper:new Ua(d)},y=new J.WatchableValue([]),g=await fn(e,i,y,f);return new $r(f,a,a.signer,i,y,g.tree,l,g.computable)}}async function qa(s,e){return await Ce(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new h.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Ma(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function Ja(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function Ga(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function _a(s,e){return await Ce(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Ve(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Ka(s,e){return await Ce(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Ve(s.autoUpdateCdnUrl,s,e))}async function Ce(s,e,t){const r=Date.now(),o=[];for(;Ws(r)<s;){const i=Date.now();let n;try{n={ok:!0,value:await t()}}catch(l){n={ok:!1,error:l}}const a=Ws(i);o.push({elapsedMs:a,response:n});const c=1e3/e-a;c>0&&await Xs.setTimeout(c)}return o}async function Ve(s,e,t){const{body:r,statusCode:o}=await Ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),i=await r.text();return{statusCode:o,beginningOfBody:i.slice(0,e.bodyLimit)+"..."}}function Ws(s){return Date.now()-s}function be(s){const e=s.filter(n=>n.response.ok),t=s.length-e.length,{mean:r,median:o}=Ha(s),i=`
2
2
  total: ${s.length};
3
3
  successes: ${e.length};
4
4
  errors: ${t};
5
5
  mean in ms: ${r};
6
- median in ms: ${n};
7
- `;return{ok:t===0,details:i}}function _a(s){const e=s.map(n=>n.elapsedMs).sort(),t=e.reduce((n,i)=>n+i)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}async function Ka(s,e,t){try{const r=await Ha(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 Ha(s,e,t){var n;const r=await Re(e,me.Templates["check_network.upload_template"],!0,i=>({name:i.createValue(h.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(w.notEmpty((n=(await he(e,r.greeting)).data)==null?void 0:n.toString()))}finally{r!=null&&await ke(e,Object.values(r))}}async function Wa(s,e,t,r,n,i){try{const o=await za(s,e,t,r,n,i);return o.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${o.type.name}`}:{status:"ok",message:`File uploading succeeded: ${o.type.name}`}}catch(o){return{status:"failed",message:`File uploading failed: error occurred: ${o}`}}}async function za(s,e,t,r,n,i){var c;const o=await t.getLocalFileHandle(i),a=await Re(n,me.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(h.Pl.JsonObject,JSON.stringify(o))}),["progress","file"]);try{const l=await he(n,a.progress);if(H.isUpload(l)){const u=H.ImportFileHandleUploadData.parse(JSON.parse(w.notEmpty((c=l.data)==null?void 0:c.toString())));H.isSignMatch(e,u.localPath,u.pathSignature)&&await H.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await he(n,a.file)}finally{await ke(n,Object.values(a))}}async function Xa(s,e,t,r,n,i,o){try{const a=await Ya(s,e,t,r,n,i);return a!==o?{status:"failed",message:`File downloading failed: expected: ${o}, got: ${a}`}:{status:"ok",message:`File downloading succeeded: ${a}`}}catch(a){return{status:"failed",message:`File downloading failed: error occurred: ${a}`}}}async function Ya(s,e,t,r,n,i){var c;const o=await t.getLocalFileHandle(i),a=await Re(e,me.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(h.Pl.JsonObject,JSON.stringify(o))}),["progress","file"]);try{const l=await he(e,a.progress);await H.uploadBlob(s,r,l,H.ImportFileHandleUploadData.parse(JSON.parse(w.notEmpty((c=l.data)==null?void 0:c.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await he(e,a.file);return await n.withBlobContent(u,{},{},async d=>await Jn.text(d))}finally{await ke(e,Object.values(a))}}async function Qa(s){try{const e=await Za(s);return e!==`Hello from go binary
8
- `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function Za(s){var t;const e=await Re(s,me.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return w.notEmpty((t=(await he(s,e.greeting)).data)==null?void 0:t.toString())}finally{await ke(s,Object.values(e))}}async function ec(s,e){try{const t=await tc(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 tc(s,e){var r;const t=await Re(s,me.Templates["check_network.run_hello_world_py"],!0,n=>({name:n.createValue(h.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return w.notEmpty((r=(await he(s,t.greeting)).data)==null?void 0:r.toString())}finally{await ke(s,Object.values(t))}}async function rc(s,e,t,r){var n,i;try{const o=await t.getStorageList(),a={};for(const c of o){const l=await sc(t,c,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){a[c.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${c.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${c.name}`);const u=await Re(e,me.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(h.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdirTypeName"]);try{const d=JSON.parse(Buffer.from((await he(e,u.workdirTypeName)).data).toString());d!=null&&d.startsWith("WorkingDirectory")?a[c.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(n=l.file)==null?void 0:n.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:a[c.name]={status:"failed",message:`Workdir creation failed: ${d}, size of file: ${(i=l.file)==null?void 0:i.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await ke(e,Object.values(u))}}return a}catch(o){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${o}`}}}}async function sc(s,e,t,r,n,i){const o=Dn(s,e,"",0);let a,c=0,l=0;for await(const{file:u,nLsRequests:d}of o){if(l=Math.max(l,d),c>=t&&l>i)return{file:a,nLsRequests:l,nCheckedFiles:c};if(c++,r<=u.size&&u.size<=n)return{file:u,nLsRequests:l,nCheckedFiles:c};u.size<r&&(a=u)}return{file:a,nLsRequests:l,nCheckedFiles:c}}async function*Dn(s,e,t,r){r++;const n=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const i of n.entries)if(i.type==="file"&&i.fullPath.startsWith(t))yield{file:i,nLsRequests:r};else if(i.type==="dir")for await(const o of Dn(s,e,i.fullPath,r))r=Math.max(o.nLsRequests,r),yield o}async function nc(){const s=_.join(Qs.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await De.appendFile(s,t),{filePath:s}}async function oc(){const s=_.join(Qs.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await De.writeFile(s,e),{filePath:s,fileContent:e}}async function Re(s,e,t,r,n){return await s.withWriteTx("TemplateRender",async i=>{const o=await vr(e),a=Be(i,o),c=tt(i,a,t,r(i),n),l={};for(const u of n){const d=h.field(s.clientRoot,u);i.createField(d,"Dynamic",c[u]),l[u]=await h.toGlobalFieldId(d)}return await i.commit(),l})}async function he(s,e){return await h.poll(s,async t=>{const r=await t.tx.getField(e);if(h.isNotNullResourceId(r.error)){const n=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${n.data}`)}if(h.isNullResourceId(r.value))throw new h.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function ke(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function ic(s,e,t,r={}){const n=[];cc.forEach(i=>{qn.channel(i).subscribe(a=>{var u,d;const c=new Date().toISOString(),l={...a};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),n.push(JSON.stringify({timestamp:c,event:i,data:l}))})});try{const{logger:i,plConfig:o,client:a,signer:c,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await $n(s,e,t,r),{filePath:y,fileContent:g}=await oc(),{filePath:b}=await nc(),F={plPings:await Va(f,o),blockRegistryOverviewChecks:await Ua(f,p),blockGARegistryOverviewChecks:await Ma(f,p),blockRegistryUiChecks:await qa(f,p),blockGARegistryUiChecks:await Ja(f,p),autoUpdateCdnChecks:await Ga(f,p),uploadTemplateCheck:await Ka(i,a,"Jack"),uploadFileCheck:await Wa(i,c,d,u,a,b),downloadFileCheck:await Xa(i,a,d,u,l,y,g),softwareCheck:await Qa(a),pythonSoftwareCheck:await ec(a,"Jack"),storageToDownloadReport:await rc(i,a,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return ac(F,s,f,n)}catch(i){return`Unhandled error while checking the network: ${i}`}}async function $n(s,e,t,r={}){const n={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},i=h.plAddressToConfig(s,{defaultRequestTimeout:n.pingTimeoutMs});i.alternativeRoot=`check_network_${te.randomUUID()}`;const o=new h.UnauthenticatedPlClient(i);let a={};e&&t&&(a=await o.login(e,t));const c=await h.PlClient.init(s,{authInformation:a}),l=o.ll.httpDispatcher,u=new w.ConsoleLoggerAdapter,d=new w.HmacSha256Signer("localSecret"),p=H.createDownloadClient(u,c,[]),f=H.createUploadBlobClient(c,u),y=await H.LsDriver.init(u,c,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:i,client:c,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:y,httpClient:l,ops:n,terminate:async()=>{p.close(),f.close(),await l.close(),await c.close()}}}function ac(s,e,t,r){const n=s.plPings.filter(b=>b.response.ok),i=s.plPings.filter(b=>!b.response.ok),o=[...new Set(n.map(b=>JSON.stringify(b.response.value)))],a=b=>b?"OK":"FAILED",c=b=>b.status==="ok"?"OK":b.status==="warn"?"WARN":"FAILED",l=be(s.plPings),u=be(s.blockRegistryOverviewChecks),d=be(s.blockGARegistryOverviewChecks),p=be(s.blockRegistryUiChecks),f=be(s.blockGARegistryUiChecks),y=be(s.autoUpdateCdnChecks),g=Object.entries(s.storageToDownloadReport).map(([b,F])=>`${c(F)} ${b} storage check`).join(`
6
+ median in ms: ${o};
7
+ `;return{ok:t===0,details:i}}function Ha(s){const e=s.map(o=>o.elapsedMs).sort(),t=e.reduce((o,i)=>o+i)/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 Wa(s,e,t){try{const r=await za(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 za(s,e,t){var o;const r=await ke(e,me.Templates["check_network.upload_template"],!0,i=>({name:i.createValue(h.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(w.notEmpty((o=(await he(e,r.greeting)).data)==null?void 0:o.toString()))}finally{r!=null&&await Re(e,Object.values(r))}}async function Xa(s,e,t,r,o,i){try{const n=await Ya(s,e,t,r,o,i);return n.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${n.type.name}`}:{status:"ok",message:`File uploading succeeded: ${n.type.name}`}}catch(n){return{status:"failed",message:`File uploading failed: error occurred: ${n}`}}}async function Ya(s,e,t,r,o,i){var c;const n=await t.getLocalFileHandle(i),a=await ke(o,me.Templates["check_network.upload_blob"],!0,l=>({file:l.createValue(h.Pl.JsonObject,JSON.stringify(n))}),["progress","file"]);try{const l=await he(o,a.progress);if(H.isUpload(l)){const u=H.ImportFileHandleUploadData.parse(JSON.parse(w.notEmpty((c=l.data)==null?void 0:c.toString())));H.isSignMatch(e,u.localPath,u.pathSignature)&&await H.uploadBlob(s,r,l,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await he(o,a.file)}finally{await Re(o,Object.values(a))}}async function Qa(s,e,t,r,o,i,n){try{const a=await Za(s,e,t,r,o,i);return a!==n?{status:"failed",message:`File downloading failed: expected: ${n}, got: ${a}`}:{status:"ok",message:`File downloading succeeded: ${a}`}}catch(a){return{status:"failed",message:`File downloading failed: error occurred: ${a}`}}}async function Za(s,e,t,r,o,i){var c;const n=await t.getLocalFileHandle(i),a=await ke(e,me.Templates["check_network.download_blob"],!0,l=>({file:l.createValue(h.Pl.JsonObject,JSON.stringify(n))}),["progress","file"]);try{const l=await he(e,a.progress);await H.uploadBlob(s,r,l,H.ImportFileHandleUploadData.parse(JSON.parse(w.notEmpty((c=l.data)==null?void 0:c.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await he(e,a.file);return await o.withBlobContent(u,{},{},async d=>await Jo.text(d))}finally{await Re(e,Object.values(a))}}async function ec(s){try{const e=await tc(s);return e!==`Hello from go binary
8
+ `?{status:"failed",message:`Software check failed: got: ${e}`}:{status:"ok",message:`Software check succeeded: ${e}`}}catch(e){return{status:"failed",message:`Software check failed: error occurred: ${e}`}}}async function tc(s){var t;const e=await ke(s,me.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return w.notEmpty((t=(await he(s,e.greeting)).data)==null?void 0:t.toString())}finally{await Re(s,Object.values(e))}}async function rc(s,e){try{const t=await sc(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 sc(s,e){var r;const t=await ke(s,me.Templates["check_network.run_hello_world_py"],!0,o=>({name:o.createValue(h.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return w.notEmpty((r=(await he(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Re(s,Object.values(t))}}async function oc(s,e,t,r){var o,i;try{const n=await t.getStorageList(),a={};for(const c of n){const l=await nc(t,c,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(l.file===void 0){a[c.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${c.name}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(l)} from storage ${c.name}`);const u=await ke(e,me.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(h.Pl.JsonObject,JSON.stringify(l.file.handle))}),["workdirTypeName"]);try{const d=JSON.parse(Buffer.from((await he(e,u.workdirTypeName)).data).toString());d!=null&&d.startsWith("WorkingDirectory")?a[c.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(o=l.file)==null?void 0:o.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}:a[c.name]={status:"failed",message:`Workdir creation failed: ${d}, size of file: ${(i=l.file)==null?void 0:i.size}, checked ${l.nCheckedFiles} files, did ${l.nLsRequests} ls requests`}}finally{await Re(e,Object.values(u))}}return a}catch(n){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${n}`}}}}async function nc(s,e,t,r,o,i){const n=Do(s,e,"",0);let a,c=0,l=0;for await(const{file:u,nLsRequests:d}of n){if(l=Math.max(l,d),c>=t&&l>i)return{file:a,nLsRequests:l,nCheckedFiles:c};if(c++,r<=u.size&&u.size<=o)return{file:u,nLsRequests:l,nCheckedFiles:c};u.size<r&&(a=u)}return{file:a,nLsRequests:l,nCheckedFiles:c}}async function*Do(s,e,t,r){r++;const o=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const i of o.entries)if(i.type==="file"&&i.fullPath.startsWith(t))yield{file:i,nLsRequests:r};else if(i.type==="dir")for await(const n of Do(s,e,i.fullPath,r))r=Math.max(n.nLsRequests,r),yield n}async function ic(){const s=_.join(Qs.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await De.appendFile(s,t),{filePath:s}}async function ac(){const s=_.join(Qs.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await De.writeFile(s,e),{filePath:s,fileContent:e}}async function ke(s,e,t,r,o){return await s.withWriteTx("TemplateRender",async i=>{const n=await yr(e),a=Be(i,n),c=tt(i,a,t,r(i),o),l={};for(const u of o){const d=h.field(s.clientRoot,u);i.createField(d,"Dynamic",c[u]),l[u]=await h.toGlobalFieldId(d)}return await i.commit(),l})}async function he(s,e){return await h.poll(s,async t=>{const r=await t.tx.getField(e);if(h.isNotNullResourceId(r.error)){const o=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${o.data}`)}if(h.isNullResourceId(r.value))throw new h.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Re(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function cc(s,e,t,r={}){const o=[];uc.forEach(i=>{Mo.channel(i).subscribe(a=>{var u,d;const c=new Date().toISOString(),l={...a};(u=l==null?void 0:l.response)!=null&&u.headers&&(l.response={...l.response},l.response.headers=l.response.headers.slice(),l.response.headers=l.response.headers.map(p=>p.toString())),(d=l==null?void 0:l.request)!=null&&d.body&&(l.request={...l.request},l.request.body="too big"),o.push(JSON.stringify({timestamp:c,event:i,data:l}))})});try{const{logger:i,plConfig:n,client:a,signer:c,downloadClient:l,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await $o(s,e,t,r),{filePath:y,fileContent:g}=await ac(),{filePath:b}=await ic(),F={plPings:await qa(f,n),blockRegistryOverviewChecks:await Ma(f,p),blockGARegistryOverviewChecks:await Ja(f,p),blockRegistryUiChecks:await Ga(f,p),blockGARegistryUiChecks:await _a(f,p),autoUpdateCdnChecks:await Ka(f,p),uploadTemplateCheck:await Wa(i,a,"Jack"),uploadFileCheck:await Xa(i,c,d,u,a,b),downloadFileCheck:await Qa(i,a,d,u,l,y,g),softwareCheck:await ec(a),pythonSoftwareCheck:await rc(a,"Jack"),storageToDownloadReport:await oc(i,a,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return lc(F,s,f,o)}catch(i){return`Unhandled error while checking the network: ${i}`}}async function $o(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},i=h.plAddressToConfig(s,{defaultRequestTimeout:o.pingTimeoutMs});i.alternativeRoot=`check_network_${te.randomUUID()}`;const n=new h.UnauthenticatedPlClient(i);let a={};e&&t&&(a=await n.login(e,t));const c=await h.PlClient.init(s,{authInformation:a}),l=n.ll.httpDispatcher,u=new w.ConsoleLoggerAdapter,d=new w.HmacSha256Signer("localSecret"),p=H.createDownloadClient(u,c,[]),f=H.createUploadBlobClient(c,u),y=await H.LsDriver.init(u,c,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:i,client:c,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:y,httpClient:l,ops:o,terminate:async()=>{p.close(),f.close(),await l.close(),await c.close()}}}function lc(s,e,t,r){const o=s.plPings.filter(b=>b.response.ok),i=s.plPings.filter(b=>!b.response.ok),n=[...new Set(o.map(b=>JSON.stringify(b.response.value)))],a=b=>b?"OK":"FAILED",c=b=>b.status==="ok"?"OK":b.status==="warn"?"WARN":"FAILED",l=be(s.plPings),u=be(s.blockRegistryOverviewChecks),d=be(s.blockGARegistryOverviewChecks),p=be(s.blockRegistryUiChecks),f=be(s.blockGARegistryUiChecks),y=be(s.autoUpdateCdnChecks),g=Object.entries(s.storageToDownloadReport).map(([b,F])=>`${c(F)} ${b} storage check`).join(`
10
10
  `);return`
11
11
  ${a(l.ok)} pings to Platforma Backend
12
12
  ${a(u.ok)} block registry overview
@@ -67,10 +67,10 @@ Platforma pings error dumps:
67
67
  ${JSON.stringify(i,null,2)}
68
68
 
69
69
  Platforma pings success dump examples:
70
- ${JSON.stringify(o,null,2)}
70
+ ${JSON.stringify(n,null,2)}
71
71
 
72
72
  Undici logs:
73
73
  ${r.join(`
74
74
  `)}
75
- `}const cc=["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=Qn;exports.CentralBlockRegistry=Zn;exports.DefaultDriverKitOpsPaths=Pr;exports.DefaultDriverKitOpsSettings=Cr;exports.DefaultMiddleLayerOpsPaths=kn;exports.DefaultMiddleLayerOpsSettings=Rn;exports.FrontendFromFolderResourceType=wr;exports.FrontendFromUrlResourceType=yr;exports.MiddleLayer=Dr;exports.Project=st;exports.TengoTemplateGet=cn;exports.TengoTemplateGetRegistry=ln;exports.TengoTemplateGetTemplate=dn;exports.TengoTemplateGetTemplateURI=un;exports.TengoTemplatePack=Ro;exports.TengoTemplatePackConvert=ko;exports.TengoTemplatePackConvertTemplate=Oo;exports.TengoTemplatePackConvertTemplatePack=Eo;exports.V1CentralDevSnapshotRegistry=to;exports.V1CentralRegistry=eo;exports.V2RegistryProvider=tn;exports.checkNetwork=ic;exports.createRenderTemplate=tt;exports.getDevV1PacketMtime=gr;exports.getDevV2PacketMtime=et;exports.initDriverKit=In;exports.initNetworkCheck=$n;exports.loadTemplate=Be;exports.prepareTemplateSpec=vr;Object.keys(O).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>O[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(jr).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>jr[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
75
+ `}const uc=["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=Qo;exports.CentralBlockRegistry=Zo;exports.DefaultDriverKitOpsPaths=kr;exports.DefaultDriverKitOpsSettings=Cr;exports.DefaultMiddleLayerOpsPaths=Ro;exports.DefaultMiddleLayerOpsSettings=ko;exports.FrontendFromFolderResourceType=br;exports.FrontendFromUrlResourceType=wr;exports.MiddleLayer=$r;exports.Project=st;exports.TengoTemplateGet=ao;exports.TengoTemplateGetRegistry=co;exports.TengoTemplateGetTemplate=uo;exports.TengoTemplateGetTemplateURI=lo;exports.TengoTemplatePack=kn;exports.TengoTemplatePackConvert=Rn;exports.TengoTemplatePackConvertTemplate=On;exports.TengoTemplatePackConvertTemplatePack=En;exports.V1CentralDevSnapshotRegistry=tn;exports.V1CentralRegistry=en;exports.V2RegistryProvider=to;exports.checkNetwork=cc;exports.createRenderTemplate=tt;exports.getDevV1PacketMtime=mr;exports.getDevV2PacketMtime=et;exports.initDriverKit=Io;exports.initNetworkCheck=$o;exports.loadTemplate=Be;exports.prepareTemplateSpec=yr;Object.keys(k).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>k[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(Br).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Br[s]})});Object.keys(h).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>h[s]})});
76
76
  //# sourceMappingURL=index.js.map