@milaboratories/pl-middle-layer 1.37.99 → 1.37.100
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 +5 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +88 -81
- package/dist/index.mjs.map +1 -1
- package/dist/pool/driver.d.ts +1 -1
- package/dist/pool/driver.d.ts.map +1 -1
- package/package.json +12 -12
- package/src/pool/driver.ts +17 -2
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var On=Object.defineProperty;var Pr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Er=s=>{throw TypeError(s)};var Tn=(s,e,t)=>e in s?On(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var P=(s,e,t)=>Tn(s,typeof e!="symbol"?e+"":e,t);var Or=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Er("Object expected");var r,n;t&&(r=e[Pr("asyncDispose")]),r===void 0&&(r=e[Pr("dispose")],t&&(n=r)),typeof r!="function"&&Er("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(o){return Promise.reject(o)}}),s.push([t,r,e])}else t&&s.push([t]);return e},Tr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,l,c,a){return a=Error(c),a.name="SuppressedError",a.error=i,a.suppressed=l,a},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var l=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(l).then(o,c=>(n(c),o()))}catch(c){n(c)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Ir=require("@milaboratories/pl-deployments"),ze=require("undici"),Z=require("@platforma-sdk/block-tools"),oe=require("node:fs"),K=require("node:path"),In=require("yaml"),S=require("@milaboratories/ts-helpers"),Ie=require("node:fs/promises"),Fn=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),$=require("@milaboratories/pl-model-backend"),Ms=require("lru-cache"),$n=require("node:worker_threads"),Js=require("denque"),he=require("@platforma-sdk/workflow-tengo"),se=require("canonicalize"),Dn=require("node:assert"),ge=require("quickjs-emscripten"),Ln=require("@milaboratories/pl-errors"),An=require("remeda"),qs=require("node:timers/promises"),W=require("@milaboratories/pl-drivers"),Gs=require("@milaboratories/pframes-rs-node"),Nn=require("node:diagnostics_channel"),jn=require("node:stream/consumers"),_s=require("node:os");function or(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 Bn=or(K),Ks=or(Ie),Fr=or(An);async function $r(s){try{return await Ks.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Vn=[Z.RegistryV1.PlPackageYamlConfigFile],xn=[Z.RegistryV1.PlPackageJsonConfigFile],ir=["backend","dist","tengo","tpl","main.plj.gz"],ar=["config","dist","config.json"],Hs=["frontend","dist"],Dr="block-model/dist/config.json",Un="block-ui/package.json",Mn=[ir,ar,Vn,xn,Hs];async function Jn(s){return await $r(K.join(s,...ar))!==void 0||await $r(K.join(s,...ir))!==void 0}function ot(s,e){const t=Fn.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Lr(s,e){if(K.isAbsolute(s)||(s=K.resolve(s)),await Jn(s))return{workflow:K.join(s,...ir),config:K.join(s,...ar),ui:K.join(s,...Hs)};{const t=ot(s,Dr),r=ot(s,Dr),n=ot(s,Un);return{workflow:t,config:r,ui:K.resolve(n,"..","dist")}}}async function qn(s){try{return await oe.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Gn(s){try{return await oe.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function cr(s){let e=0n;for(const t of Mn){const r=K.join(s,...t),n=await Gn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function Xe(s){const e=await oe.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await oe.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class _n{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ze.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const l of i){const{organization:c,package:a,latestMeta:u,latestVersion:d}=l,p={organization:c,name:a,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:l.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 oe.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=K.join(r.path,n.name),i=await qn(K.join(o,Z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const l=Z.RegistryV1.PlPackageConfigData.parse(In.parse(i)),c=await cr(o),a={organization:l.organization,name:l.package,version:"DEV"},u={id:a,meta:{title:l.meta.title??"No title",description:l.meta.description??"No Description",organization:{name:l.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:o,mtime:c}};t.push({registryId:e.id,id:a,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let l=o,c=await Z.tryLoadPackDescription(l);if(c===void 0){for(const a of["block","meta"])if(l=K.join(o,a),c=await Z.tryLoadPackDescription(l),c!==void 0)break}if(c!==void 0){const a=await Xe(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:l,mtime:a}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return S.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const n=(i=this.registries.find(l=>l.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Ws{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 Kn={type:"remote-v2",url:"https://blocks.pl-open.science/"},Hn={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Wn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},zn={groups:[{id:"default",label:"Default",blocks:[]}]},Xn={stagingRefreshTimestamp:0,blocksInLimbo:[]},Yn={label:"New Project"},Qn={name:"UserProject",version:"2"},Ke="SchemaVersion",Fe="2",lr="ProjectCreated",$e="ProjectLastModified",De="ProjectMeta",pe="ProjectStructure",He="BlockRenderingState",Zn="BlockArgsAuthor/";function Zt(s){return`${Zn}${s}`}const er="ProjectStructureAuthor",eo="__serviceTemplate_";function tr(s){return`${eo}${s}`}function z(s,e){return`${s}-${e}`}const to=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ro(s){const e=s.match(to);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const so="projects",zs={name:"Projects",version:"1"},no=s=>g.resourceTypesEqual(s.type,zs)?s.fields:[];async function oo(s,e,t,r){const n=await _e.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:no},r.logger);return{computable:J.Computable.make(i=>{const l=i.accessor(n.entry()).node(),c=t.getValue(i);if(l===void 0)return;const a=[];for(const u of l.listDynamicFields()){const d=l.traverse(u);if(d===void 0)continue;const p=S.notEmpty(d.getKeyValueAsJson(De)),f=S.notEmpty(d.getKeyValueAsJson(lr)),y=S.notEmpty(d.getKeyValueAsJson($e));a.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return a.sort(u=>-u.lastModified.valueOf()),a}).withStableType(),tree:n}}const io={name:"EphRenderTemplate",version:"1"},ao={name:"RenderTemplate",version:"1"};function Ye(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(io):s.createStruct(ao),i=g.field(o,"template"),l=g.field(o,"inputs");return s.createField(i,"Input",e),s.createField(l,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(o),g.Pl.futureRecord(s,o,n,"Output","outputs/")}const co={name:"BContextEnd",version:"1"},lo={name:"BContext",version:"1"},uo="id",po="parent/",fo=["context","result"];function Ar(s,e,t){return Ye(s,e,!0,t,fo)}function go(s){const e=s.createEphemeral(co);return s.lock(e),e}function Nr(s,e){if(e.length===0)return go(s);if(e.length===1)return e[0];const t=s.createEphemeral(lo);s.createField(g.field(t,uo),"Input",g.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${po}${r}`),"Input",e[r]);return s.lock(t),t}function Xs(s,e){const t=new Map,r=(n,o,i)=>{const l=te.createHash("sha256");o.updateCacheKey(n,l,i);const c=l.digest("hex");if(!t.has(c)){const a=o.render(n,s,r,i);t.set(c,a)}return t.get(c)};return r(e.template,Ys,e.hashToSource)}const jr={updateCacheKey(s,e,t){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data))}},Ve={updateCacheKey(s,e,t){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){const n=$.PlTemplateSoftwareV1.fromV3Data(s,ye(s.name,r,s.sourceHash)),o=e.createStruct($.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},Ys={updateCacheKey(s,e,t){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),jr.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),Ve.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),Ve.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data));for(const[l,c]of Object.entries(s.libs??{})){const a=$.PlTemplateV1.libField(n,l);e.createField(a,"Input"),e.setField(a,t(c,jr,r))}for(const[l,c]of Object.entries(s.software??{})){const a=$.PlTemplateV1.swField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ve,r))}for(const[l,c]of Object.entries(s.assets??{})){const a=$.PlTemplateV1.swField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ve,r))}for(const[l,c]of Object.entries(s.templates??{})){const a=$.PlTemplateV1.tplField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ys,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV3Data(s))),i=$.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function ye(s,e,t){return S.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function ho(s,e){const t=$.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Zs(s,t);case"pl.tengo-template.v3":return Xs(s,t);default:S.assertNever(r)}}function mo(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Zs(s,t);case"pl.tengo-template.v3":return Xs(s,t);default:S.assertNever(r)}}const Br={hash(s,e){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV2Data(s).data))}},xe={hash(s,e){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=$.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct($.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},Qs={hash(s,e){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Br.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV2Data(s).data));for(const[i,l]of Object.entries(s.libs??{})){const c=$.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(l,Br))}for(const[i,l]of Object.entries(s.software??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(l,xe))}for(const[i,l]of Object.entries(s.assets??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(l,xe))}for(const[i,l]of Object.entries(s.templates??{})){const c=$.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(l,Qs))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV2Data(s))),o=$.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function Zs(s,e){const t=new Map,r=(n,o)=>{const i=te.createHash("sha256");o.hash(n,i);const l=i.digest("hex");if(!t.has(l)){const c=o.render(n,s,r);t.set(l,c)}return t.get(l)};return r(e,Qs)}const en={name:"TengoTemplateGet",version:"1"},tn="registry",rn="templateURI",sn="template",vo={name:"TengoTemplatePack",version:"1"},yo={name:"TengoTemplatePackConvert",version:"1"},wo="templatePack",So="template";async function ur(s){switch(s.type){case"from-file":return{type:"explicit",content:await oe.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return S.assertNever(s)}}function bo(s,e){const t=s.createStruct(en),r=g.field(t,tn),n=g.field(t,rn),o=g.field(t,sn);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Ne(s,e){switch(e.type){case"from-registry":return bo(s,e);case"explicit":return ho(s,e);case"prepared":return mo(s,e);default:return S.assertNever(e)}}const dr={name:"Frontend/FromUrl",version:"1"},pr={name:"Frontend/FromFolder",version:"1"};function Ro(s,e){switch(e.type){case"url":return s.createValue(dr,JSON.stringify({url:e.url}));case"local":return s.createValue(pr,JSON.stringify({path:e.path,signature:e.signature}));default:return S.assertNever(e)}}class ko{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__:K.resolve(void 0,"worker.js"),t=this.worker=new $n.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:l}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?l(new Error(o)):i(n)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Co={name:"BlockPackCustom",version:"1"},nn="template",on="frontend";function Vr(s){return s.endsWith("/")?s:`${s}/`}function Po(s){return Buffer.from(s).toString("utf8")}function Ue(s){return JSON.parse(Po(s))}class Eo{constructor(e,t,r){P(this,"remoteContentCache",new Ms.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 Lr(e.folder),r=await oe.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Vr(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 Ue(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 Ue(n)}default:return S.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Or(n,new ko,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,l=!0}finally{var c=Tr(n,i,l);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Lr(e.folder),r=await oe.promises.readFile(t.workflow),n=JSON.parse(await oe.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await oe.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Xe(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${Vr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),l=Ue(i);return{type:"explicit",template:{type:"explicit",content:o},config:l,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>Ue(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,l]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(l)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return S.assertNever(e)}}}function Oo(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Co,JSON.stringify(t));return s.createField(g.field(r,nn),"Input",Ne(s,e.template)),s.createField(g.field(r,on),"Input",Ro(s,e.frontend)),s.lock(r),r}function xr(s,e){switch(e.type){case"prepared":return Oo(s,e);default:return S.assertNever(e.type)}}function Me(s,e,t){return{__isRef:!0,blockId:s,name:e}}function To(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function rr(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(To(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)rr(s,n,t);else for(const[,n]of Object.entries(e))rr(s,n,t);return;default:S.assertNever(r)}}function Io(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return rr(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 an{constructor(e){P(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const l of n){const c=this.nodes.get(l);r(c),c[e].forEach(a=>{o.has(a)||(o.add(a),i.push(a))})}n=i}}}function sr(s){const e=new Map;let t;for(const{id:r}of ne(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 an(e)}function Ge(s,e){const t=new Map,r=new an(t),n=new Set;for(const{id:o}of ne(s)){const i=e(o);if(i===void 0)continue;const l=Io(i.args,n),c=new Set([...l.upstreams,...r.traverseIds("enrichments",...l.upstreamsRequiringEnrichments)]),a=new Set;for(const{id:p}of ne(s)){if(p===o)break;if(c.has(p)){a.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))a.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(l.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:l.missingReferences,upstream:a,directUpstream:l.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),l.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),a.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function Fo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function nr(s,e){if(s.size>e.size)return nr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Ur(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!Fo(o.upstream,i.upstream)||nr(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?nr(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let it;async function cn(){if(it===void 0){const s=await ur(he.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");it={spec:s,hash:e}}return it}function $o(s,e,t){return Ye(s,e,!0,{pf:t},["result"]).result}let me;function ae(){return me||(me={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},process.env.MI_LOG_OUTPUT_STATUS&&(me.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(me.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),me)}function at(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class Mr{constructor(e,t,r,n){P(this,"currentArgsC",at(()=>this.fields.currentArgs.modCount,()=>S.cachedDeserialize(this.fields.currentArgs.value)));P(this,"prodArgsC",at(()=>{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 S.cachedDeserialize(e)}));P(this,"productionStaleC",at(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t,this.config=r,this.source=n}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),nn,"Input")}}const Do=s=>{throw new Error(`No new block info for ${s}`)};class We{constructor(e,t,r,n,o,i,l,c,a,u,d,p){P(this,"globalModCount",0);P(this,"fieldsChanged",!1);P(this,"lastModifiedChanged",!1);P(this,"structureChanged",!1);P(this,"metaChanged",!1);P(this,"renderingStateChanged",!1);P(this,"blocksWithChangedInputs",new Set);P(this,"stagingGraph");P(this,"pendingProductionGraph");P(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=l,this.renderingState=c,this.blocksInLimbo=a,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=sr(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=S.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=S.notEmpty(r.fields.blockPack);return g.isResourceId(n.ref)&&g.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ge(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ge(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ne(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=g.field(this.rid,z(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(g.field(this.rid,z(e,o))),delete i[o],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setStates(e){const t=[];let r=!1;for(const n of e){const o=this.getBlockInfo(n.blockId);let i=!1;for(const l of["args","uiState"]){if(!(l in n))continue;const c=n[l];if(c==null)throw new Error(`Can't set ${l} to null or undefined, please omit the key if you don't want to change it`);const a=l==="args"?"currentArgs":"uiState";let u,d=!1;if(l==="args")u=S.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=S.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(o.fields[a].value,u)===0)continue;console.log("setting",a,d,u.length);const p=this.tx.createValue(d?g.Pl.JsonGzObject:g.Pl.JsonObject,u);this.setBlockField(n.blockId,a,p,"Ready",u),i=!0,l==="args"&&t.push(n.blockId)}i&&(this.blocksWithChangedInputs.add(n.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:n})=>this.resetStaging(n)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}exportCtx(e){return $o(this.tx,g.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Do){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=sr(e),i=Ur(r,o);for(const a of i.onlyInA){const{fields:u}=this.getBlockInfo(a);this.deleteBlockFields(a,...Object.keys(u)),this.blockInfos.delete(a),this.blocksInLimbo.delete(a)&&(this.renderingStateChanged=!0)}for(const a of i.onlyInB){const u=t(a),d=new Mr(a,{},j.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(a,d);const p=xr(this.tx,u.blockPack);this.setBlockField(a,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(a,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(a,"currentArgs",this.createJsonFieldValueByContent(u.args)),this.setBlockFieldObj(a,"uiState",this.createJsonFieldValueByContent(u.uiState??"{}")),d.check()}for(const a of i.different)this.resetStaging(a);const l=Ge(e,a=>this.getProductionGraphBlockInfo(a,!0)),c=Ur(n,l);n.traverse("downstream",[...c.different],a=>{this.resetOrLimboProduction(a.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const l=i.blocks.findIndex(c=>c.id===r);if(!(l<0)){i.blocks.splice(l,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,xr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,l=>{r.add(l.id)});else for(const l of r){const c=n.nodes.get(l);if(c===void 0)throw new Error(`Can't find block with id: ${l}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const l of ne(this.structure)){if(!r.has(l.id))continue;let c=this.getBlockInfo(l.id).requireProductionRendering||this.blocksInLimbo.has(l.id);if(!c){for(const a of n.nodes.get(l.id).upstream)if(o.has(a)){c=!0;break}}c&&(this.renderProductionFor(l.id),o.add(l.id))}const i=[...o];return n.traverse("downstream",i,l=>{o.has(l.id)||this.resetOrLimboProduction(l.id)}),this.getStagingGraph().traverse("downstream",i,({id:l})=>{i[0]!==l&&this.resetStaging(l)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,l;const t=this.getActualProductionGraph(),r=new Js(e),n=new Set(e),o=[];for(;!r.isEmpty();){const c=r.shift(),a=this.getBlockInfo(c).fields;if(!(((i=a.prodOutput)==null?void 0:i.status)==="Ready"&&((l=a.prodCtx)==null?void 0:l.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))n.has(u)||(r.push(u),n.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(l=>{const c=t.get(l);c!==0&&(i=Math.max(c+1,i))}),e(n.id,i),t.set(n.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,Zt(t)):this.tx.setKValue(this.rid,Zt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,er):this.tx.setKValue(this.rid,er,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,pe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,He,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,De,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,Ke),l=t.getKValueJson(r,$e),c=t.getKValueJson(r,De),a=t.getKValueJson(r,pe),u=t.getKValueJson(r,He),d=await o,p=new Map;for(const m of d.fields){const v=ro(m.name);if(v===void 0)continue;let b=p.get(v.blockId);b===void 0&&(b={id:v.blockId,fields:{}},p.set(v.blockId,b)),b.fields[v.fieldName]=g.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[b,w]of Object.entries(v)){if(w.ref===void 0)continue;if(!g.isResource(w.ref)||g.isResourceRef(w.ref))throw new Error("unexpected behaviour");const C=b;f.push([m,C,w,t.getResourceData(w.ref,C=="blockPack")])}});const[y,h,R,T,{stagingRefreshTimestamp:V,blocksInLimbo:D}]=await Promise.all([i,l,c,a,u]);if(y!==Fe)throw Number(y)<Number(Fe)?new j.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new j.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const M=[];for(const[m,v,b,w]of f){const C=await w;if(b.value=C.data,g.isNotNullResourceId(C.error)?b.status="Error":C.resourceReady||g.isNotNullResourceId(C.originalResourceId)?b.status="Ready":b.status="NotReady",v==="blockPack"){const k=C.fields.find(O=>O.name===g.Pl.HolderRefField);if(k===void 0)throw new Error("Block pack ref field is missing");M.push([m,t.getResourceData(g.ensureResourceIdNotNull(k.value),!1)])}}for(const[m,v]of M){const b=await v,w=S.cachedDeserialize(S.notEmpty(b.data));m.blockConfig=j.extractConfig(w.config),m.blockPack=w.source}const q=await cn(),I=tr(q.hash),B=d.fields.find(m=>m.name===I);let E;B!==void 0?E=g.ensureResourceIdNotNull(B.value):(E=g.Pl.wrapInHolder(t,Ne(t,q.spec)),t.createField(g.field(r,tr(q.hash)),"Dynamic",E));const H={stagingRefreshTimestamp:V},ue=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:b,blockPack:w})=>Y.set(m,new Mr(m,v,S.notEmpty(b),S.notEmpty(w))));const G=new Set;for(const m of ne(T)){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 We(r,t,n,y,h,R,T,H,ue,Y,E,e);return X.fixProblemsAndMigrate(),X}}async function Lo(s,e=Yn){const t=s.createEphemeral(Qn);s.lock(t);const r=String(Date.now());s.setKValue(t,Ke,JSON.stringify(Fe)),s.setKValue(t,lr,r),s.setKValue(t,$e,r),s.setKValue(t,De,JSON.stringify(e)),s.setKValue(t,pe,JSON.stringify(zn)),s.setKValue(t,He,JSON.stringify(Xn));const n=await cn();return s.createField(g.field(t,tr(n.hash)),"Dynamic",g.Pl.wrapInHolder(s,Ne(s,n.spec))),t}async function Je(s,e,t,r){return ie(s,e,t,void 0,r)}async function ie(s,e,t,r,n){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await We.load(s,o,t,r),l=await n(i);return i.wasModified&&(i.save(),await o.commit(),ae().logProjectMutationStat&&console.log(JSON.stringify(o.stat))),l});{const o=await We.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Ao(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:S.assertNever(s)}}function Jr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function No(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Jr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Jr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:S.assertNever(s)}}const jo=g.resourceType("PColumnData/JsonPartitioned","1"),Bo=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Vo=g.resourceType("PColumnData/BinaryPartitioned","1"),xo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Uo=g.resourceType("PColumnData/Json","1");function Mo(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(g.resourceTypesEqual(s.resourceType,Uo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.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(g.resourceTypesEqual(s.resourceType,Bo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const l of i){const c=JSON.stringify([...JSON.parse(n),...JSON.parse(l)]);r[c]=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Vo)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,xo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const l of i)if(l.endsWith(".index")){const c=l.slice(0,l.length-6),a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[a];u===void 0&&(u={},r[a]=u),r[a].index=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else if(l.endsWith(".values")){const c=l.slice(0,l.length-7),a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[a];u===void 0&&(u={},r[a]=u),r[a].values=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${l}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Jo(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function qo(s,e){const t=te.createHash("sha256");return t.update(se(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function qr(s,e){return se({__isRef:!0,blockId:s,name:e})}function Go(s,e){return se({resolvePath:s,name:e})}function ln(s,e=!0,t=!1,r=""){var l,c,a;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=S.notEmpty((l=d.groups)==null?void 0:l.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=S.notEmpty((c=d.groups)==null?void 0:c.type);let y=o.get(p);switch(y===void 0&&(y={},o.set(p,y)),f){case"spec":y.spec=(a=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:a.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function _o(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=ln(s,e,!1,t);Dn(n.locked);const o={};for(const[i,l]of n.results){if(l.spec===void 0)throw new Error(`no spec for key ${i}`);if(l.hasData!==!0||l.data===void 0)throw new Error(`no data for key ${i}`);const c=l.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw c.error;o[i]={id:r.length===0?qo(l.spec,c.value):Go(r,i),spec:l.spec,data:c.value}}return o}class fr{constructor(e,t){P(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,l,c,a,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(l=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:l.spec;if(n!==void 0||(n=(u=(a=(c=r.staging)==null?void 0:c.results)==null?void 0:a.get(t))==null?void 0:u.spec,n!==void 0))return n;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,l,c;const r=this.blocks.get(e);if(r===void 0)return;const n=(l=(i=r.prod)==null?void 0:i.results)==null?void 0:l.get(t),o=(c=n==null?void 0:n.data)==null?void 0:c.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return j.mapValueInVOE(o,a=>({id:qr(e,t),spec:n.spec,data:a}));n!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const n=i=>{r===void 0&&(r=i),t=!1},o=(i,l,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const a=c.data();a!==void 0?e.push({ref:Me(i,l),obj:{id:a.ok?qr(i,l):void 0,spec:c.spec,data:a}}):n(`no_data:${i}:${l}`)}};for(const[i,l]of this.blocks){const c=new Set;if(l.prod!==void 0){l.prod.locked||n(`prod_not_locked:${i}`);for(const[a,u]of l.prod.results)c.add(a),o(i,a,u)}if(l.staging!==void 0){l.staging.locked||n(`staging_not_locked:${i}`);for(const[a,u]of l.staging.results)c.has(a)||o(i,a,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const l=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[c,a]of i.staging.results)a.spec!==void 0&&(e.push({ref:Me(o,c),obj:a.spec}),l.add(c))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[c,a]of i.prod.results)l.has(c)||a.spec!==void 0&&e.push({ref:Me(o,c),obj:a.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[l,c]of i.results)n.has(l)||c.spec===void 0||(n.add(l),j.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+l,ref:Me(r.info.id,l),spec:c.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=S.notEmpty(n.getKeyValueAsJson(pe)),l=sr(o).traverseIds("upstream",r),c=new Map;for(const a of ne(o)){if(!l.has(a.id))continue;const u=Gr(n.traverse({field:z(a.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:z(a.id,"prodUiCtx"),stableIfNotFound:!0})),d=Gr(n.traverse({field:z(a.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:z(a.id,"stagingUiCtx")}));c.set(a.id,{info:a,prod:u,staging:d})}return new fr(e,c)}}function Gr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return ln(e.value,!1,!0)}function gr(s,e){return{blockId:e,args:o=>S.cachedDecode(S.notEmpty(o.accessor(s).node().traverse({field:z(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:o=>{var l;const i=(l=o.accessor(s).node().traverse({field:z(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:l.getData();return i?S.cachedDecode(i):void 0},uiState:o=>{var l;const i=(l=o.accessor(s).node().traverse({field:z(e,"uiState"),stableIfNotFound:!0}))==null?void 0:l.getData();return i?S.cachedDecode(i):void 0},blockMeta:o=>{const i=o.accessor(s).node(),l=S.notEmpty(i.getKeyValueAsJson(pe)),c=new Map;for(const a of ne(l))c.set(a.id,a);return c}}}function un(s,e){return{...gr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:z(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:z(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>fr.create(t,s,e)}}function*re(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*re(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*re(t);return;case"MakeArray":for(const t of s.template)yield*re(t);return;case"GetJsonField":case"GetResourceField":yield*re(s.source),yield*re(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*re(s.source),yield*re(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*re(s.source);return;case"IsEmpty":yield*re(s.arg);return;case"Not":yield*re(s.operand);return;case"And":case"Or":yield*re(s.operand1),yield*re(s.operand2);return;default:S.assertNever(s)}}function Ko(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Pe(s,e){return s===void 0?void 0:e(s)}function Ho(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Wo(s){for(const e of re(s))if(Ho(e))return!0;return!1}function Qe(s){return{type:"ReturnResult",result:s}}function L(s){return()=>Qe(s)}const zo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return L(e)},Xo=s=>{const e=s.source;if(e===void 0)return L(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return L(t)},Yo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?L(void 0):({cCtx:r})=>{var n;return Qe((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function dn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function Qo(s,e){return t=>{const r=t.source;return r===void 0?L(void 0):()=>({type:"ScheduleSubroutine",subroutine:pn(r.length),args:dn(r,n=>N({...s,[e.itVar]:n},e.mapping))})}}function pn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return L(t)}}function Zo(s,e){return t=>{const r=t.source;if(r===void 0)return L(void 0);const n={};for(const[o,i]of Object.entries(r)){const l={...s,[e.itVar]:i};n[o]=N(l,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ei,args:n})}}const ei=s=>L(s),ti=s=>{const e=s.arg;return L(e===void 0?void 0:e.length===0)},ri=s=>{const e=s.operand;return L(e===void 0?void 0:!e)},si=s=>{const e=s.operand1,t=s.operand2;return L(e===void 0||t===void 0?void 0:e&&t)},ni=s=>{const e=s.operand1,t=s.operand2;return L(e===void 0||t===void 0?void 0:e||t)},oi=s=>{const e=s.source;return e===void 0?L(void 0):({cCtx:t})=>{var r;return Qe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},ii=s=>{const e=s.source,t=s.field;return L(e===void 0||t===void 0?void 0:e[t])};function ai(s,e){return t=>{const r=t.source;return r===void 0?L(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const l of o.listInputFields()){const c=o.traverse(l);if(c===void 0)i[l]=L(void 0);else{const a={...s,[e.itVar]:c.persist()};i[l]=N(a,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ci,args:i}}}}const ci=s=>L(s),li=s=>e=>{const t=e.source;return t===void 0?L(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)}})})},ui=s=>e=>{const t=e.source;return t===void 0?L(void 0):({cCtx:r,drivers:n})=>{const o=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(i=>n.blobDriver.getDownloadedBlob(o,i),{postprocessValue:async i=>i===void 0?void 0:(await n.blobDriver.getContent(i.handle,s)).toString()})}}},di=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const o=await r.blobDriver.getContent(n.handle,s);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},pi=s=>{const e=s.source;return e===void 0?L(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},fi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},gi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},hi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},mi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},vi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},yi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},wi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function N(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>Qe(t(r.cCtx)):L(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:hn(t,s,e.cfg)});case"Immediate":return L(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{source:N(s,e.source),field:N(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Qo(s,e),args:{source:N(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Zo(s,e),args:{source:N(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:Ko(e.template,t=>N(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:pn(e.template.length),args:dn(e.template,t=>N(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:N(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ti,args:{arg:N(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:ri,args:{operand:N(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:si,args:{operand1:N(s,e.operand1),operand2:N(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:ni,args:{operand1:N(s,e.operand1),operand2:N(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:ai(s,e),args:{source:N(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:N(s,e.source),field:N(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:oi,args:{source:N(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:li(e.range),args:{source:N(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:ui(e.range),args:{source:N(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:di(e.range),args:{source:N(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:pi,args:{source:N(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:fi,args:{source:N(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:gi(e.format),args:{source:N(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:hi,args:{source:N(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:mi(e.lines),args:{source:N(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:vi(e.patternToSearch),args:{source:N(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:yi(e.patternToSearch),args:{source:N(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:wi,args:{source:N(s,e.source)}});default:return S.assertNever(e)}}const Si=["$prod","$staging"];function bi(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 fn=Symbol(),gn="return",Ri={op:fn,arg:gn};function ki(s){return s.op==fn&&s.arg==gn}function Ci(){return{pendingSubroutines:new Map}}function _r(s,e,t,r){const n=new Js(t),o=(l,c)=>{if(ki(l))return e.result=c,!1;const a=S.notEmpty(e.pendingSubroutines.get(l.op));if(l.arg in a.args)throw new Error("argument already set");return a.args[l.arg]=c,a.argCounter--,a.argCounter===0&&(e.pendingSubroutines.delete(l.op),n.push({destination:a.destination,operation:a.subroutine(a.args)})),!0},i=[];e:for(;n.length>0;){const l=n.shift(),c=l.operation(s);switch(c.type){case"ReturnResult":if(!o(l.destination,c.result))break e;break;case"ScheduleSubroutine":{const a=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)n.push({destination:l.destination,operation:c.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:a,arg:p},operation:f});e.pendingSubroutines.set(a,{argCounter:d,args:{},subroutine:c.subroutine,destination:l.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:l.destination,computable:c.computable});break;default:S.assertNever(c)}}return i}function Pi(s,e,t,r={}){return hn(s,bi(e),t,r)}function hn(s,e,t,r={}){const n=`${e.blockId}#`+se({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Si.indexOf(o)===-1)),cfg:t});return J.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},l=Ci();return{ir:_r(i,l,[{destination:Ri,operation:N(e,t)}],!0),postprocessValue(a){const u=[];for(const y of a)u.push({destination:y.destination,operation:L(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,h]of l.pendingSubroutines)p.set(y,{...h,args:{...h.args}});const f={result:l.result,pendingSubroutines:p};if(_r(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function Kr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ei{constructor(e,t,r,n){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.computableCtx=n,this.meta=t.blockMeta(n)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return Kr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Kr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=_o(o,t,r,n),l={};for(const[c,a]of Object.entries(i))l[c]=j.mapPObjectData(a,u=>this.wrapAccessor(u));return l}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=S.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:j.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:j.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 j.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=>j.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(j.mapPTableDef(e,t=>j.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):j.isDataInfo(e)?j.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 o=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),l=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(o))),l!==void 0&&r.setProp(e,"uiState",n.manage(r.newString(l))),i!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(i)));const c=(a,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const y=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(y)}};r.newFunction(a,d).consume(p=>r.setProp(e,a,p)),r.newFunction(a,u).consume(p=>r.setProp(e,a+"__internal__",p))};c("getAccessorHandleByName",a=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(a)),void 0)),c("resolveWithCommon",(a,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(a),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),c("getResourceType",a=>t.exportObjectViaJson(this.getResourceType(r.getString(a)),void 0)),c("getInputsLocked",a=>t.exportSingleValue(this.getInputsLocked(r.getString(a)),void 0)),c("getOutputsLocked",a=>t.exportSingleValue(this.getOutputsLocked(r.getString(a)),void 0)),c("getIsReadyOrError",a=>t.exportSingleValue(this.getIsReadyOrError(r.getString(a)),void 0)),c("getIsFinal",a=>t.exportSingleValue(this.getIsFinal(r.getString(a)),void 0)),c("getError",a=>t.exportSingleValue(this.getError(r.getString(a)),void 0)),c("listInputFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("listOutputFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("listDynamicFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("getKeyValueBase64",(a,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(a),r.getString(u)),void 0)),c("getKeyValueAsString",(a,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(a),r.getString(u)),void 0)),c("getDataBase64",a=>t.exportSingleValue(this.getDataBase64(r.getString(a)),void 0)),c("getDataAsString",a=>t.exportSingleValue(this.getDataAsString(r.getString(a)),void 0)),c("parsePObjectCollection",(a,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(a),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),c("getBlobContentAsBase64",(a,u)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(a),t.importObjectUniversal(u)),void 0)),c("getBlobContentAsString",(a,u)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(a),t.importObjectUniversal(u)),void 0)),c("getDownloadedBlobContentHandle",a=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(a)),void 0)),c("getOnDemandBlobContentHandle",a=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(a)),void 0)),c("extractArchiveAndGetURL",(a,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(a),r.getString(u)),void 0)),c("getImportProgress",a=>t.exportSingleValue(this.getImportProgress(r.getString(a)),void 0)),c("getLastLogs",(a,u)=>t.exportSingleValue(this.getLastLogs(r.getString(a),r.getNumber(u)),void 0)),c("getProgressLog",(a,u)=>t.exportSingleValue(this.getProgressLog(r.getString(a),r.getString(u)),void 0)),c("getProgressLogWithInfo",(a,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(a),r.getString(u)),void 0)),c("getLogHandle",a=>t.exportSingleValue(this.getLogHandle(r.getString(a)),void 0)),c("getBlockLabel",a=>t.exportSingleValue(this.getBlockLabel(r.getString(a)),void 0)),c("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),c("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),c("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),c("calculateOptions",a=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(a)),void 0)),c("getSpecFromResultPoolByRef",(a,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(a),r.getString(u)),void 0)),c("getDataFromResultPoolByRef",(a,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(a),r.getString(u)),void 0)),c("createPFrame",a=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(a)),void 0)),c("createPTable",a=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(a)),void 0)),c("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),c("logInfo",a=>{this.logInfo(r.getString(a))}),c("logWarn",a=>{this.logWarn(r.getString(a))}),c("logError",a=>{this.logError(r.getString(a))})})}}function Oi(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Le{constructor(e,t,r,n){P(this,"callbackRegistry");P(this,"fnJSONStringify");P(this,"fnJSONParse");P(this,"errorRepo",new Ti);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.");n!==void 0&&(this.computableHelper=new Ei(this,n.blockCtx,n.mlEnv,n.computableCtx)),this.injectCtx()}resetComputableCtx(){S.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 Le.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(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw Le.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(Oi(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(j.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Ti{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",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${g.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new Ln.PlQuickJSError(e,n)}}function Ii(s,e,t,r,n,o={}){const i=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:i},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{const c=new ge.Scope;l.addOnDestroy(()=>c.dispose());const a=c.manage(s.quickJs.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let u;a.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=c.manage(a.newContext()),p=new Le(c,d,h=>{u=h},{computableCtx:l,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let y=0;return ae().logOutputStatus==="any"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(h,{unstableMarker:R,stable:T})=>{for(const[D,M]of Object.entries(h))p.runCallback(D,M);const V=p.importObjectUniversal(f);return y++,ae().logOutputStatus&&(ae().logOutputStatus==="any"||!T)&&console.log(T?`Stable output ${t.handle} calculated ${V!==void 0?"defined":"undefined"}; (#${y})`:`Unstable output ${t.handle}; marker = ${R}; ${V!==void 0?"defined":"undefined"} (#${y})`),V}}},o)}function Fi(s,e,t,...r){const n=new ge.Scope;try{const o=n.manage(s.newRuntime());o.setMemoryLimit(1024*1024*8),o.setMaxStackSize(1024*320);let i;o.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const l=n.manage(o.newContext()),c=new Le(n,l,a=>{i=a});return c.evaluateBundle(t.content),c.importObjectUniversal(c.runCallback(e.handle,...r))}finally{n.dispose()}}function $i(s){return j.isConfigLambda(s)?s.isActive===!0:Wo(s)}function Ee(s,e,t,r,n,o={}){if(j.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Ii(s,e,t,r,n,o)}else return Pi(s.driverKit,e,t,o)}function Ae(s,e){return Pe(s.traverse({field:z(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=j.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}function Di(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Fr.omitBy((r,n)=>n.startsWith("__"));return Fr.isDeepEqual(t(s),t(e))}function Li(s,e,t){return J.Computable.make(r=>{var y,h,R,T,V,D,M,q;const n=r.accessor(s).node(),o=S.notEmpty(n.getKeyValueAsJson(lr)),i=S.notEmpty(n.getKeyValueAsJson($e)),l=S.notEmpty(n.getKeyValueAsJson(De)),c=S.notEmpty(n.getKeyValueAsJson(pe)),a=S.notEmpty(n.getKeyValueAsJson(He)),u=new Map;for(const{id:I}of ne(c)){const B=n.traverse({field:z(I,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),E=B.getDataAsJson();let H;const ue=n.traverse({field:z(I,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(ue!==void 0){const Y=ue.getDataAsJson(),G=n.getField({field:z(I,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=n.getField({field:z(I,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});H={arguments:Y,stale:!Di(E,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((h=X.value)==null?void 0:h.getError())!==void 0,outputsError:((R=G.error)==null?void 0:R.getDataAsString())??((V=(T=G.value)==null?void 0:T.getError())==null?void 0:V.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((q=(M=X.value)==null?void 0:M.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(I,{currentArguments:E,prod:H,argsRid:B.resourceInfo.id})}const d=Ge(c,I=>{const B=Ae(n,I),E=u.get(I),H=E.currentArguments;return{args:H,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>B.cfg,()=>H,{argsRid:E.argsRid,blockPackRid:B.bpResourceId})}}),p=new Set(a.blocksInLimbo),f=[...ne(c)].map(({id:I,label:B,renderingMode:E})=>{var k,O,A,F,x;const H=S.notEmpty(u.get(I)),ue=S.notEmpty(d.nodes.get(I));let Y="NotCalculated";H.prod!==void 0&&(p.has(I)?Y="Limbo":Y=H.prod.finished?"Done":"Running");const G=Ae(n,I),{sections:X,title:m,inputsValid:v,sdkVersion:b}=Pe(G,({bpId:_,cfg:U})=>{const de=gr(s,I);return{sections:Ee(t,de,U.sections,U.code,_).wrap({recover:ke=>(t.logger.error("Error in block model sections"),t.logger.error(ke),[])}),title:Pe(U.title,ke=>Ee(t,de,ke,U.code,_).wrap({recover:En=>(t.logger.error("Error in block model title"),t.logger.error(En),"Invalid title")})),inputsValid:Ee(t,de,U.inputsValid,U.code,_).wrap({recover:ke=>(t.logger.error("Error in block model argsValid"),t.logger.error(ke),!1)}),sdkVersion:U.sdkVersion}})||{},w=n.traverse({field:z(I,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),C=Pe(G,({info:_})=>t.blockUpdateWatcher.get({currentSpec:_.source,settings:w}));return{projectResourceId:g.resourceIdToString(s.rid),id:I,label:m??B,title:m??B,renderingMode:E,stale:((k=H.prod)==null?void 0:k.stale)!==!1||Y==="Limbo",missingReference:ue.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",I)],downstreams:[...d.traverseIdsExcludingRoots("downstream",I)],calculationStatus:Y,outputErrors:((O=H.prod)==null?void 0:O.outputError)===!0,outputsError:(A=H.prod)==null?void 0:A.outputsError,exportsError:(F=H.prod)==null?void 0:F.exportsError,settings:w,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(x=G==null?void 0:G.info)==null?void 0:x.source,updates:C,sdkVersion:b,navigationState:e.getState(I)}});return{meta:l,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(er),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const l=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,c=(l||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,a={...i,canRun:c,stale:l,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete a.updates,a})}}}).withStableType()}function Ai(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,dr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(g.resourceTypesEqual(t.resourceType,pr)){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 Ni(s,e){if(s!==void 0)return J.Computable.make(t=>Ai(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function ji(s,e,t){return J.Computable.make(r=>{var l;const n=r.accessor(s).node(),o=Ae(n,e),i=(l=n.traverse({field:z(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:on,assertFieldType:"Input"}))==null?void 0:l.persist();return{path:Ni(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function mn(s,e,t){if(t===void 0)return J.Computable.make(i=>mn(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=gr(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(Zt(e)),args:S.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?S.deepFreeze(JSON.parse(o)):void 0}}function Bi(s,e,t){return J.Computable.make(r=>{const n=r.accessor(s).node(),o=un(s,e);return Pe(Ae(n,e),({cfg:i,bpId:l})=>{const c={};for(const[a,u]of Object.entries(i.outputs)){const d=Ee(t,o,u,i.code,l);c[a]=J.Computable.wrapError(d,1)}return c})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Vi(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),n=S.notEmpty(r.getKeyValueAsJson(pe)),o=[];for(const{id:i}of ne(n)){const l=Ae(r,i);if(l===void 0)continue;const c=Object.entries(l.cfg.outputs).map(([,u])=>u).filter(u=>$i(u)).map(u=>u);if(c.length===0)continue;const a=un(r.persist(),i);for(const u of c)o.push(J.Computable.wrapError(Ee(e,a,u,l.cfg.code,l.bpId)))}return o})}class xi{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()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...j.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())}}function Ui(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=S.notEmpty(t.getKeyValueAsJson(pe));return{listOfBlocks:[...ne(r)].map(n=>n.id)}})}const Mi="1",Ji="BlockFrontendState/";async function qi(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,Ke);if(r!==Fe){if(r===Mi)await Gi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,Ke,JSON.stringify(Fe)),await t.commit()}})}async function Gi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,pe),s.listKeyValues(e)]),n=new Map(r.map(o=>[o.key,o.value]));for(const o of ne(t)){const i=Ji+o.id,l=n.get(i),c=l?S.cachedDeserialize(l):{},a=s.createJsonGzValue(c),u=g.field(e,z(o.id,"uiState"));s.createField(u,"Dynamic",a),s.deleteKValue(e,i)}}function Hr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class Ze{constructor(e,t,r){P(this,"rid");P(this,"overview");P(this,"overviewLight");P(this,"navigationStates",new xi);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=Li(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=Ui(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Vi(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Je(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await qs.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=te.randomUUID()){const i=await this.env.bpPreparer.prepare(t),l=await this.env.bpPreparer.getBlockConfigContainer(t),c=j.extractConfig(l);return await ie(this.env.projectHelper,this.env.pl,this.rid,n,a=>a.addBlock({id:o,label:e,renderingMode:c.renderingMode},{args:se(c.initialArgs),uiState:se(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=j.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ie(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.migrateBlockPack(e,o,r?{args:i.initialArgs,uiState:i.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 o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(l=>{const c=o.blocks.find(a=>a.id===l);if(c===void 0)throw new Error(`Can't find block: ${l}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Je(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Je(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,o=>{o.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=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,z(e,"blockPack")))).value),o=g.ensureResourceIdNotNull((await r.getField(g.field(n,g.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),l=j.extractConfig(S.cachedDeserialize(S.notEmpty(i.data)).config);await ie(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:l.initialArgs,uiState:l.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=Bi(this.projectTree.entry(),e,this.env),o={fullState:J.Computable.make(i=>({argsAndUiState:mn(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const l=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,a=l&&Ki(l)&&i.outputs!==void 0?Wi(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:a,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=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 qi(e.pl,t),await Je(e.projectHelper,e.pl,t,n=>{});const r=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:_i},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,l)=>{var c,a;return(((c=l.data)==null?void 0:c.byteLength)??0)-(((a=i.data)==null?void 0:a.byteLength)??0)});const o=_e.treeDumpStats(n);await Ie.writeFile(`${g.resourceIdToString(t)}.json`,Hr(n)),await Ie.writeFile(`${g.resourceIdToString(t)}.stats.json`,Hr(o))}return new Ze(e,t,r)}}function _i(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 Ki(s){return!Hi(s,"1.26.0")}function Hi(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 Wi(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 hr={logger:new S.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function mr(s){return{blobDownloadPath:K.join(s,"download"),blobDownloadRangesCachePath:K.join(s,"downloadRangesCache"),downloadBlobToURLPath:K.join(s,"downloadToURL"),pframesSpillPath:K.join(s,"pframes")}}const vn={...hr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function yn(s){return{...mr(s),frontendDownloadPath:K.join(s,"frontend")}}function zi(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qe={exports:{}},ct,Wr;function et(){if(Wr)return ct;Wr=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return ct={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},ct}var lt,zr;function tt(){return zr||(zr=1,lt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),lt}var Xr;function je(){return Xr||(Xr=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=et(),o=tt();e=s.exports={};const i=e.re=[],l=e.safeRe=[],c=e.src=[],a=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],y=R=>{for(const[T,V]of f)R=R.split(`${T}*`).join(`${T}{0,${V}}`).split(`${T}+`).join(`${T}{1,${V}}`);return R},h=(R,T,V)=>{const D=y(T),M=d++;o(R,M,T),u[R]=M,c[M]=T,a[M]=D,i[M]=new RegExp(T,V?"g":void 0),l[M]=new RegExp(D,V?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(qe,qe.exports)),qe.exports}var ut,Yr;function vr(){if(Yr)return ut;Yr=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return ut=r=>r?typeof r!="object"?s:r:e,ut}var dt,Qr;function wn(){if(Qr)return dt;Qr=1;const s=/^[0-9]+$/,e=(r,n)=>{const o=s.test(r),i=s.test(n);return o&&i&&(r=+r,n=+n),r===n?0:o&&!i?-1:i&&!o?1:r<n?-1:1};return dt={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},dt}var pt,Zr;function ee(){if(Zr)return pt;Zr=1;const s=tt(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=et(),{safeRe:r,t:n}=je(),o=vr(),{compareIdentifiers:i}=wn();class l{constructor(a,u){if(u=o(u),a instanceof l){if(a.loose===!!u.loose&&a.includePrerelease===!!u.includePrerelease)return a;a=a.version}else if(typeof a!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof a}".`);if(a.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",a,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=a.trim().match(u.loose?r[n.LOOSE]:r[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${a}`);if(this.raw=a,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(a){if(s("SemVer.compare",this.version,this.options,a),!(a instanceof l)){if(typeof a=="string"&&a===this.version)return 0;a=new l(a,this.options)}return a.version===this.version?0:this.compareMain(a)||this.comparePre(a)}compareMain(a){return a instanceof l||(a=new l(a,this.options)),i(this.major,a.major)||i(this.minor,a.minor)||i(this.patch,a.patch)}comparePre(a){if(a instanceof l||(a=new l(a,this.options)),this.prerelease.length&&!a.prerelease.length)return-1;if(!this.prerelease.length&&a.prerelease.length)return 1;if(!this.prerelease.length&&!a.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=a.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}compareBuild(a){a instanceof l||(a=new l(a,this.options));let u=0;do{const d=this.build[u],p=a.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}inc(a,u,d){if(a.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(a){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),i(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${a}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return pt=l,pt}var ft,es;function we(){if(es)return ft;es=1;const s=ee();return ft=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(o){if(!n)return null;throw o}},ft}var gt,ts;function Xi(){if(ts)return gt;ts=1;const s=we();return gt=(t,r)=>{const n=s(t,r);return n?n.version:null},gt}var ht,rs;function Yi(){if(rs)return ht;rs=1;const s=we();return ht=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},ht}var mt,ss;function Qi(){if(ss)return mt;ss=1;const s=ee();return mt=(t,r,n,o,i)=>{typeof n=="string"&&(i=o,o=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,o,i).version}catch{return null}},mt}var vt,ns;function Zi(){if(ns)return vt;ns=1;const s=we();return vt=(t,r)=>{const n=s(t,null,!0),o=s(r,null,!0),i=n.compare(o);if(i===0)return null;const l=i>0,c=l?n:o,a=l?o:n,u=!!c.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(c)===0)return a.minor&&!a.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==o.major?p+"major":n.minor!==o.minor?p+"minor":n.patch!==o.patch?p+"patch":"prerelease"},vt}var yt,os;function ea(){if(os)return yt;os=1;const s=ee();return yt=(t,r)=>new s(t,r).major,yt}var wt,is;function ta(){if(is)return wt;is=1;const s=ee();return wt=(t,r)=>new s(t,r).minor,wt}var St,as;function ra(){if(as)return St;as=1;const s=ee();return St=(t,r)=>new s(t,r).patch,St}var bt,cs;function sa(){if(cs)return bt;cs=1;const s=we();return bt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},bt}var Rt,ls;function ce(){if(ls)return Rt;ls=1;const s=ee();return Rt=(t,r,n)=>new s(t,n).compare(new s(r,n)),Rt}var kt,us;function na(){if(us)return kt;us=1;const s=ce();return kt=(t,r,n)=>s(r,t,n),kt}var Ct,ds;function oa(){if(ds)return Ct;ds=1;const s=ce();return Ct=(t,r)=>s(t,r,!0),Ct}var Pt,ps;function yr(){if(ps)return Pt;ps=1;const s=ee();return Pt=(t,r,n)=>{const o=new s(t,n),i=new s(r,n);return o.compare(i)||o.compareBuild(i)},Pt}var Et,fs;function ia(){if(fs)return Et;fs=1;const s=yr();return Et=(t,r)=>t.sort((n,o)=>s(n,o,r)),Et}var Ot,gs;function aa(){if(gs)return Ot;gs=1;const s=yr();return Ot=(t,r)=>t.sort((n,o)=>s(o,n,r)),Ot}var Tt,hs;function rt(){if(hs)return Tt;hs=1;const s=ce();return Tt=(t,r,n)=>s(t,r,n)>0,Tt}var It,ms;function wr(){if(ms)return It;ms=1;const s=ce();return It=(t,r,n)=>s(t,r,n)<0,It}var Ft,vs;function Sn(){if(vs)return Ft;vs=1;const s=ce();return Ft=(t,r,n)=>s(t,r,n)===0,Ft}var $t,ys;function bn(){if(ys)return $t;ys=1;const s=ce();return $t=(t,r,n)=>s(t,r,n)!==0,$t}var Dt,ws;function Sr(){if(ws)return Dt;ws=1;const s=ce();return Dt=(t,r,n)=>s(t,r,n)>=0,Dt}var Lt,Ss;function br(){if(Ss)return Lt;Ss=1;const s=ce();return Lt=(t,r,n)=>s(t,r,n)<=0,Lt}var At,bs;function Rn(){if(bs)return At;bs=1;const s=Sn(),e=bn(),t=rt(),r=Sr(),n=wr(),o=br();return At=(l,c,a,u)=>{switch(c){case"===":return typeof l=="object"&&(l=l.version),typeof a=="object"&&(a=a.version),l===a;case"!==":return typeof l=="object"&&(l=l.version),typeof a=="object"&&(a=a.version),l!==a;case"":case"=":case"==":return s(l,a,u);case"!=":return e(l,a,u);case">":return t(l,a,u);case">=":return r(l,a,u);case"<":return n(l,a,u);case"<=":return o(l,a,u);default:throw new TypeError(`Invalid operator: ${c}`)}},At}var Nt,Rs;function ca(){if(Rs)return Nt;Rs=1;const s=ee(),e=we(),{safeRe:t,t:r}=je();return Nt=(o,i)=>{if(o instanceof s)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let l=null;if(!i.rtl)l=o.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(o))&&(!l||l.index+l[0].length!==o.length);)(!l||y.index+y[0].length!==l.index+l[0].length)&&(l=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(l===null)return null;const c=l[2],a=l[3]||"0",u=l[4]||"0",d=i.includePrerelease&&l[5]?`-${l[5]}`:"",p=i.includePrerelease&&l[6]?`+${l[6]}`:"";return e(`${c}.${a}.${u}${d}${p}`,i)},Nt}var jt,ks;function la(){if(ks)return jt;ks=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}}return jt=s,jt}var Bt,Cs;function le(){if(Cs)return Bt;Cs=1;const s=/\s+/g;class e{constructor(v,b){if(b=n(b),v instanceof e)return v.loose===!!b.loose&&v.includePrerelease===!!b.includePrerelease?v:new e(v.raw,b);if(v instanceof o)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=b,this.loose=!!b.loose,this.includePrerelease=!!b.includePrerelease,this.raw=v.trim().replace(s," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(C=>!h(C[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const C of this.set)if(C.length===1&&R(C[0])){this.set=[C];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 b=this.set[v];for(let w=0;w<b.length;w++)w>0&&(this.formatted+=" "),this.formatted+=b[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const w=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,C=r.get(w);if(C)return C;const k=this.options.loose,O=k?c[a.HYPHENRANGELOOSE]:c[a.HYPHENRANGE];v=v.replace(O,G(this.options.includePrerelease)),i("hyphen replace",v),v=v.replace(c[a.COMPARATORTRIM],u),i("comparator trim",v),v=v.replace(c[a.TILDETRIM],d),i("tilde trim",v),v=v.replace(c[a.CARETTRIM],p),i("caret trim",v);let A=v.split(" ").map(U=>V(U,this.options)).join(" ").split(/\s+/).map(U=>Y(U,this.options));k&&(A=A.filter(U=>(i("loose invalid filter",U,this.options),!!U.match(c[a.COMPARATORLOOSE])))),i("range list",A);const F=new Map,x=A.map(U=>new o(U,this.options));for(const U of x){if(h(U))return[U];F.set(U.value,U)}F.size>1&&F.has("")&&F.delete("");const _=[...F.values()];return r.set(w,_),_}intersects(v,b){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>T(w,b)&&v.set.some(C=>T(C,b)&&w.every(k=>C.every(O=>k.intersects(O,b)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new l(v,this.options)}catch{return!1}for(let b=0;b<this.set.length;b++)if(X(this.set[b],v,this.options))return!0;return!1}}Bt=e;const t=la(),r=new t,n=vr(),o=st(),i=tt(),l=ee(),{safeRe:c,t:a,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=je(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=et(),h=m=>m.value==="<0.0.0-0",R=m=>m.value==="",T=(m,v)=>{let b=!0;const w=m.slice();let C=w.pop();for(;b&&w.length;)b=w.every(k=>C.intersects(k,v)),C=w.pop();return b},V=(m,v)=>(i("comp",m,v),m=I(m,v),i("caret",m),m=M(m,v),i("tildes",m),m=E(m,v),i("xrange",m),m=ue(m,v),i("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",M=(m,v)=>m.trim().split(/\s+/).map(b=>q(b,v)).join(" "),q=(m,v)=>{const b=v.loose?c[a.TILDELOOSE]:c[a.TILDE];return m.replace(b,(w,C,k,O,A)=>{i("tilde",m,w,C,k,O,A);let F;return D(C)?F="":D(k)?F=`>=${C}.0.0 <${+C+1}.0.0-0`:D(O)?F=`>=${C}.${k}.0 <${C}.${+k+1}.0-0`:A?(i("replaceTilde pr",A),F=`>=${C}.${k}.${O}-${A} <${C}.${+k+1}.0-0`):F=`>=${C}.${k}.${O} <${C}.${+k+1}.0-0`,i("tilde return",F),F})},I=(m,v)=>m.trim().split(/\s+/).map(b=>B(b,v)).join(" "),B=(m,v)=>{i("caret",m,v);const b=v.loose?c[a.CARETLOOSE]:c[a.CARET],w=v.includePrerelease?"-0":"";return m.replace(b,(C,k,O,A,F)=>{i("caret",m,C,k,O,A,F);let x;return D(k)?x="":D(O)?x=`>=${k}.0.0${w} <${+k+1}.0.0-0`:D(A)?k==="0"?x=`>=${k}.${O}.0${w} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.0${w} <${+k+1}.0.0-0`:F?(i("replaceCaret pr",F),k==="0"?O==="0"?x=`>=${k}.${O}.${A}-${F} <${k}.${O}.${+A+1}-0`:x=`>=${k}.${O}.${A}-${F} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.${A}-${F} <${+k+1}.0.0-0`):(i("no pr"),k==="0"?O==="0"?x=`>=${k}.${O}.${A}${w} <${k}.${O}.${+A+1}-0`:x=`>=${k}.${O}.${A}${w} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.${A} <${+k+1}.0.0-0`),i("caret return",x),x})},E=(m,v)=>(i("replaceXRanges",m,v),m.split(/\s+/).map(b=>H(b,v)).join(" ")),H=(m,v)=>{m=m.trim();const b=v.loose?c[a.XRANGELOOSE]:c[a.XRANGE];return m.replace(b,(w,C,k,O,A,F)=>{i("xRange",m,w,C,k,O,A,F);const x=D(k),_=x||D(O),U=_||D(A),de=U;return C==="="&&de&&(C=""),F=v.includePrerelease?"-0":"",x?C===">"||C==="<"?w="<0.0.0-0":w="*":C&&de?(_&&(O=0),A=0,C===">"?(C=">=",_?(k=+k+1,O=0,A=0):(O=+O+1,A=0)):C==="<="&&(C="<",_?k=+k+1:O=+O+1),C==="<"&&(F="-0"),w=`${C+k}.${O}.${A}${F}`):_?w=`>=${k}.0.0${F} <${+k+1}.0.0-0`:U&&(w=`>=${k}.${O}.0${F} <${k}.${+O+1}.0-0`),i("xRange return",w),w})},ue=(m,v)=>(i("replaceStars",m,v),m.trim().replace(c[a.STAR],"")),Y=(m,v)=>(i("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?a.GTE0PRE:a.GTE0],"")),G=m=>(v,b,w,C,k,O,A,F,x,_,U,de)=>(D(w)?b="":D(C)?b=`>=${w}.0.0${m?"-0":""}`:D(k)?b=`>=${w}.${C}.0${m?"-0":""}`:O?b=`>=${b}`:b=`>=${b}${m?"-0":""}`,D(x)?F="":D(_)?F=`<${+x+1}.0.0-0`:D(U)?F=`<${x}.${+_+1}.0-0`:de?F=`<=${x}.${_}.${U}-${de}`:m?F=`<${x}.${_}.${+U+1}-0`:F=`<=${F}`,`${b} ${F}`.trim()),X=(m,v,b)=>{for(let w=0;w<m.length;w++)if(!m[w].test(v))return!1;if(v.prerelease.length&&!b.includePrerelease){for(let w=0;w<m.length;w++)if(i(m[w].semver),m[w].semver!==o.ANY&&m[w].semver.prerelease.length>0){const C=m[w].semver;if(C.major===v.major&&C.minor===v.minor&&C.patch===v.patch)return!0}return!1}return!0};return Bt}var Vt,Ps;function st(){if(Ps)return Vt;Ps=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new l(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new l(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}Vt=e;const t=vr(),{safeRe:r,t:n}=je(),o=Rn(),i=tt(),l=ee(),c=le();return Vt}var xt,Es;function nt(){if(Es)return xt;Es=1;const s=le();return xt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},xt}var Ut,Os;function ua(){if(Os)return Ut;Os=1;const s=le();return Ut=(t,r)=>new s(t,r).set.map(n=>n.map(o=>o.value).join(" ").trim().split(" ")),Ut}var Mt,Ts;function da(){if(Ts)return Mt;Ts=1;const s=ee(),e=le();return Mt=(r,n,o)=>{let i=null,l=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(a=>{c.test(a)&&(!i||l.compare(a)===-1)&&(i=a,l=new s(i,o))}),i},Mt}var Jt,Is;function pa(){if(Is)return Jt;Is=1;const s=ee(),e=le();return Jt=(r,n,o)=>{let i=null,l=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(a=>{c.test(a)&&(!i||l.compare(a)===1)&&(i=a,l=new s(i,o))}),i},Jt}var qt,Fs;function fa(){if(Fs)return qt;Fs=1;const s=ee(),e=le(),t=rt();return qt=(n,o)=>{n=new e(n,o);let i=new s("0.0.0");if(n.test(i)||(i=new s("0.0.0-0"),n.test(i)))return i;i=null;for(let l=0;l<n.set.length;++l){const c=n.set[l];let a=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">=":(!a||t(d,a))&&(a=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),a&&(!i||t(i,a))&&(i=a)}return i&&n.test(i)?i:null},qt}var Gt,$s;function ga(){if($s)return Gt;$s=1;const s=le();return Gt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Gt}var _t,Ds;function Rr(){if(Ds)return _t;Ds=1;const s=ee(),e=st(),{ANY:t}=e,r=le(),n=nt(),o=rt(),i=wr(),l=br(),c=Sr();return _t=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,h,R,T,V;switch(p){case">":y=o,h=l,R=i,T=">",V=">=";break;case"<":y=i,h=c,R=o,T="<",V="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const M=d.set[D];let q=null,I=null;if(M.forEach(B=>{B.semver===t&&(B=new e(">=0.0.0")),q=q||B,I=I||B,y(B.semver,q.semver,f)?q=B:R(B.semver,I.semver,f)&&(I=B)}),q.operator===T||q.operator===V||(!I.operator||I.operator===T)&&h(u,I.semver))return!1;if(I.operator===V&&R(u,I.semver))return!1}return!0},_t}var Kt,Ls;function ha(){if(Ls)return Kt;Ls=1;const s=Rr();return Kt=(t,r,n)=>s(t,r,">",n),Kt}var Ht,As;function ma(){if(As)return Ht;As=1;const s=Rr();return Ht=(t,r,n)=>s(t,r,"<",n),Ht}var Wt,Ns;function va(){if(Ns)return Wt;Ns=1;const s=le();return Wt=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),Wt}var zt,js;function ya(){if(js)return zt;js=1;const s=nt(),e=ce();return zt=(t,r,n)=>{const o=[];let i=null,l=null;const c=t.sort((p,f)=>e(p,f,n));for(const p of c)s(p,r,n)?(l=p,i||(i=p)):(l&&o.push([i,l]),l=null,i=null);i&&o.push([i,null]);const a=[];for(const[p,f]of o)p===f?a.push(p):!f&&p===c[0]?a.push("*"):f?p===c[0]?a.push(`<=${f}`):a.push(`${p} - ${f}`):a.push(`>=${p}`);const u=a.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},zt}var Xt,Bs;function wa(){if(Bs)return Xt;Bs=1;const s=le(),e=st(),{ANY:t}=e,r=nt(),n=ce(),o=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const h of d.set){for(const R of p.set){const T=c(h,R,f);if(y=y||T!==null,T)continue e}if(y)return!1}return!0},i=[new e(">=0.0.0-0")],l=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=i:d=l}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=l}const y=new Set;let h,R;for(const E of d)E.operator===">"||E.operator===">="?h=a(h,E,f):E.operator==="<"||E.operator==="<="?R=u(R,E,f):y.add(E.semver);if(y.size>1)return null;let T;if(h&&R){if(T=n(h.semver,R.semver,f),T>0)return null;if(T===0&&(h.operator!==">="||R.operator!=="<="))return null}for(const E of y){if(h&&!r(E,String(h),f)||R&&!r(E,String(R),f))return null;for(const H of p)if(!r(E,String(H),f))return!1;return!0}let V,D,M,q,I=R&&!f.includePrerelease&&R.semver.prerelease.length?R.semver:!1,B=h&&!f.includePrerelease&&h.semver.prerelease.length?h.semver:!1;I&&I.prerelease.length===1&&R.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(const E of p){if(q=q||E.operator===">"||E.operator===">=",M=M||E.operator==="<"||E.operator==="<=",h){if(B&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===B.major&&E.semver.minor===B.minor&&E.semver.patch===B.patch&&(B=!1),E.operator===">"||E.operator===">="){if(V=a(h,E,f),V===E&&V!==h)return!1}else if(h.operator===">="&&!r(h.semver,String(E),f))return!1}if(R){if(I&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===I.major&&E.semver.minor===I.minor&&E.semver.patch===I.patch&&(I=!1),E.operator==="<"||E.operator==="<="){if(D=u(R,E,f),D===E&&D!==R)return!1}else if(R.operator==="<="&&!r(R.semver,String(E),f))return!1}if(!E.operator&&(R||h)&&T!==0)return!1}return!(h&&M&&!R&&T!==0||R&&q&&!h&&T!==0||B||I)},a=(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 Xt=o,Xt}var Yt,Vs;function Sa(){if(Vs)return Yt;Vs=1;const s=je(),e=et(),t=ee(),r=wn(),n=we(),o=Xi(),i=Yi(),l=Qi(),c=Zi(),a=ea(),u=ta(),d=ra(),p=sa(),f=ce(),y=na(),h=oa(),R=yr(),T=ia(),V=aa(),D=rt(),M=wr(),q=Sn(),I=bn(),B=Sr(),E=br(),H=Rn(),ue=ca(),Y=st(),G=le(),X=nt(),m=ua(),v=da(),b=pa(),w=fa(),C=ga(),k=Rr(),O=ha(),A=ma(),F=va(),x=ya(),_=wa();return Yt={parse:n,valid:o,clean:i,inc:l,diff:c,major:a,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:h,compareBuild:R,sort:T,rsort:V,gt:D,lt:M,eq:q,neq:I,gte:B,lte:E,cmp:H,coerce:ue,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:b,minVersion:w,validRange:C,outside:k,gtr:O,ltr:A,intersects:F,simplifyRange:x,subset:_,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},Yt}var ba=Sa();const Ra=zi(ba),ka={minDelay:1500},Ca="__no_updates__";class Pa extends J.PollComputablePool{constructor(t,r,n={}){super({...n,...ka},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_${se(t)}`;default:return Ca}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await cr(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await Z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const l=await Xe(i);return l===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:l},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:l}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(o.registryUrl);let a=this.preferredUpdateChannel;if(a===void 0)if(o.channel===void 0)if(await c.getLatestOverview(o.id,Q.StableChannel))a=Q.StableChannel;else{if(await c.getLatestOverview(o.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(o.id)}`),{suggestions:[]};a=Q.AnyChannel}else a=o.channel;const u=await c.getUpdateSuggestions(o.id,a);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(y=>y.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:y,update:h})=>({type:y,update:{...o,id:{...o.id,version:h}}}));if(d===void 0)return{suggestions:p};if(l!==void 0&&Ra.lte(d,l))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return se(t)===se(r)}}class xs{constructor(){P(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(n=>n!=null&&typeof n[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function Oe(s){return String(s.id)}const Ea=["Int","Long","Float","Double","String","Bytes"];function Qt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return t}const Ce=(s,e)=>typeof e=="bigint"?e.toString():e;class Oa{constructor(e,t,r,n){P(this,"pFrame");P(this,"abortController",new AbortController);P(this,"blobIdToResource",new Map);P(this,"blobHandleComputables",new Map);P(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue(this.disposeSignal)});P(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await Ks.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const o=(l,c)=>this.logger[l](c);for(const l of n)for(const c of Ao(l.data))this.blobIdToResource.set(Oe(c),c);const i=[...new Map(n.map(l=>({...l,data:No(l.data,Oe)})).map(l=>[se(l),l])).values()];try{const l=new Gs.PFrame(this.spillPath,o);l.setDataSource(this);for(const c of i)l.addColumnSpec(c.id,c.spec),l.setColumnData(c.id,c.data);this.pFrame=l}catch(l){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${l}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Ta{constructor(e,t){this.pTable=e,this.abortController=t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort(),this.pTable.dispose()}}class kr{constructor(e,t,r){P(this,"pFrames");P(this,"pTables");P(this,"frameConcurrencyLimiter");P(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new S.ConcurrencyLimitingExecutor(1);this.frameConcurrencyLimiter=n,this.tableConcurrencyLimiter=new S.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends xs{constructor(o,i,l){super(),this.blobDriver=o,this.logger=i,this.spillPath=l}createNewResource(o){return ae().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`),new Oa(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){return Fa(o)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends xs{constructor(o){super(),this.pFrames=o}createNewResource(o){const i=o.pFrameHandle;ae().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`);const l=this.pFrames.getByKey(i),c=new AbortController,a=l.pFrame.createTable({src:Te(o.def.src),filters:Qt(o.def.filters)});let u=a;if(o.def.sorting.length>0)try{u=a.sort(o.def.sorting)}finally{a.dispose()}return new Ta(u,c)}calculateParamsKey(o){return Ia(o)}}(this.pFrames)}async pprofDump(){return await Gs.PFrame.pprofDump()}static async init(e,t,r){const n=Bn.resolve(r);return await S.emptyDir(n),new kr(e,t,n)}createPFrame(e,t){const r=e.filter(o=>Ea.find(i=>i===o.spec.valueType)).map(o=>j.mapPObjectData(o,i=>_e.isPlTreeNodeAccessor(i)?Mo(i):j.isDataInfo(i)?j.mapDataInfo(i,l=>l.resourceInfo):Jo(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t){const r=this.createPFrame(j.extractAllColumns(e.src),t),n=j.mapPTableDef(e,i=>i.id),o=this.pTables.acquire({def:n,pFrameHandle:r});return ae().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${r}; pTableHandle = ${JSON.stringify(o)}): ${JSON.stringify(j.mapPTableDef(e,i=>i.spec),Ce)}`),t.addOnDestroy(o.unref),o.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(o=>[se(o),o])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(o=>o.mappingVariants.length===0||o.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(l=>l.length===0))).map(o=>o.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r,n){return ae().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.frameConcurrencyLimiter.run(async()=>{const o=this.pFrames.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(a=>!!a)),l=o.pFrame.createTable({src:Te(t.src),filters:Qt(t.filters)});let c=l;if(t.sorting.length>0)try{c=l.sort(t.sorting)}finally{l.dispose()}try{const a=c.getSpec(),u=await c.getData([...a.keys()],{range:r,signal:i});return a.map((d,p)=>({spec:d,data:u[p]}))}finally{c.dispose()}})}async getUniqueValues(e,t,r){return ae().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.frameConcurrencyLimiter.run(async()=>{const n=this.pFrames.getByKey(e),o=AbortSignal.any([r,n.disposeSignal].filter(i=>!!i));return await n.pFrame.getUniqueValues({...t,filters:Qt(t.filters)},{signal:o})})}getSpec(e){const t=this.pTables.getByKey(e).pTable;return Promise.resolve(t.getSpec())}async getShape(e,t){return await this.tableConcurrencyLimiter.run(async()=>{const r=this.pTables.getByKey(e),n=AbortSignal.any([t,r.disposeSignal].filter(o=>!!o));return await r.pTable.getShape({signal:n})})}async getData(e,t,r,n){return await this.tableConcurrencyLimiter.run(async()=>{const o=this.pTables.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(l=>!!l));return await o.pTable.getData(t,{range:r,signal:i})})}}function Te(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=>Te(e))};case"outer":return{type:"outer",primary:Te(s.primary),secondary:s.secondary.map(e=>Te(e))};default:S.assertNever(s)}}function Ia(s){const e=te.createHash("sha256");return e.update(se(s)),e.digest().toString("hex")}function Fa(s){const e=[...s].map(r=>j.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([l,c])=>({key:l,value:c}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([l,c])=>({key:l,value:Oe(c)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([l,c])=>({key:l,value:[Oe(c.index),Oe(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((l,c)=>l.key.localeCompare(c.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(se(e)),t.digest().toString("hex")}async function kn(s,e,t){const r={...hr,...mr(e),...t},n=new S.HmacSha256Signer(r.localSecret),o=W.createDownloadClient(r.logger,s,r.localProjections),i=W.createLogsClient(s,r.logger),l=W.createUploadBlobClient(s,r.logger),c=W.createUploadProgressClient(s,r.logger),a=await W.DownloadDriver.init(r.logger,o,i,r.blobDownloadPath,r.blobDownloadRangesCachePath,n,r.blobDriverOps),u=new W.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new W.UploadDriver(r.logger,n,l,c,r.uploadDriverOps),p=new W.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new W.LogsDriver(r.logger,p,a),y=await W.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),h=await kr.init(a,r.logger,r.pframesSpillPath);return{blobDriver:a,blobToURLDriver:u,logDriver:f,lsDriver:y,signer:n,uploadDriver:d,pFrameDriver:h}}class $a{constructor(e){P(this,"enrichmentTargetsCache",new Ms.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 Fi(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Cr{constructor(e,t,r,n,o,i,l,c){P(this,"pl");P(this,"projectList");P(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=l,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await Lo(n,e);return n.createField(g.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await g.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await 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(g.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(g.field(this.projectListResourceId,e))).value;if(g.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await Ze.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 S.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...vn,...yn(t),...r};n.defaultTreeOptions.logStat=ae().logTreeStats,n.debugOps.dumpInitialTreeState=ae().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async R=>{const T=g.field(R.clientRoot,so);R.createField(T,"Dynamic");const V=await R.getField(T);if(g.isNullResourceId(V.value)){const D=R.createEphemeral(zs);return R.lock(D),R.setField(T,D),await R.commit(),await D.globalId}else return V.value}),i=n.logger,l=await kn(e,t,n),c=new ze.RetryAgent(e.httpDispatcher),a=new Ws(c),u=new Eo(a,l.signer,c),d=new W.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await ge.getQuickJS(),f={pl:e,blockEventDispatcher:new S.BlockEventDispatcher,signer:l.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:l,blockUpdateWatcher:new Pa(a,i,{minDelay:n.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:n.preferredUpdateChannel}),quickJs:p,projectHelper:new $a(p)},y=new J.WatchableValue([]),h=await oo(e,o,y,f);return new Cr(f,l,l.signer,o,y,h.tree,a,h.computable)}}async function Da(s,e){return await Se(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function La(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function Aa(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function Na(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function ja(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Ba(s,e){return await Se(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Be(s.autoUpdateCdnUrl,s,e))}async function Se(s,e,t){const r=Date.now(),n=[];for(;Us(r)<s;){const o=Date.now();let i;try{i={ok:!0,value:await t()}}catch(a){i={ok:!1,error:a}}const l=Us(o);n.push({elapsedMs:l,response:i});const c=1e3/e-l;c>0&&await qs.setTimeout(c)}return n}async function Be(s,e,t){const{body:r,statusCode:n}=await ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Us(s){return Date.now()-s}function ve(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:n}=Va(s),o=`
|
|
1
|
+
"use strict";var On=Object.defineProperty;var Pr=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Er=s=>{throw TypeError(s)};var Tn=(s,e,t)=>e in s?On(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var P=(s,e,t)=>Tn(s,typeof e!="symbol"?e+"":e,t);var Or=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Er("Object expected");var r,n;t&&(r=e[Pr("asyncDispose")]),r===void 0&&(r=e[Pr("dispose")],t&&(n=r)),typeof r!="function"&&Er("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(o){return Promise.reject(o)}}),s.push([t,r,e])}else t&&s.push([t]);return e},Tr=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,l,c,a){return a=Error(c),a.name="SuppressedError",a.error=i,a.suppressed=l,a},n=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),o=i=>{for(;i=s.pop();)try{var l=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(l).then(o,c=>(n(c),o()))}catch(c){n(c)}if(t)throw e};return o()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),Ir=require("@milaboratories/pl-deployments"),ze=require("undici"),Z=require("@platforma-sdk/block-tools"),oe=require("node:fs"),K=require("node:path"),In=require("yaml"),S=require("@milaboratories/ts-helpers"),Ie=require("node:fs/promises"),Fn=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),J=require("@milaboratories/computable"),te=require("node:crypto"),$=require("@milaboratories/pl-model-backend"),Ms=require("lru-cache"),$n=require("node:worker_threads"),Js=require("denque"),he=require("@platforma-sdk/workflow-tengo"),se=require("canonicalize"),Dn=require("node:assert"),ge=require("quickjs-emscripten"),Ln=require("@milaboratories/pl-errors"),An=require("remeda"),qs=require("node:timers/promises"),W=require("@milaboratories/pl-drivers"),Gs=require("@milaboratories/pframes-rs-node"),Nn=require("node:diagnostics_channel"),jn=require("node:stream/consumers"),_s=require("node:os");function or(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 Bn=or(K),Ks=or(Ie),Fr=or(An);async function $r(s){try{return await Ks.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Vn=[Z.RegistryV1.PlPackageYamlConfigFile],xn=[Z.RegistryV1.PlPackageJsonConfigFile],ir=["backend","dist","tengo","tpl","main.plj.gz"],ar=["config","dist","config.json"],Hs=["frontend","dist"],Dr="block-model/dist/config.json",Un="block-ui/package.json",Mn=[ir,ar,Vn,xn,Hs];async function Jn(s){return await $r(K.join(s,...ar))!==void 0||await $r(K.join(s,...ir))!==void 0}function ot(s,e){const t=Fn.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Lr(s,e){if(K.isAbsolute(s)||(s=K.resolve(s)),await Jn(s))return{workflow:K.join(s,...ir),config:K.join(s,...ar),ui:K.join(s,...Hs)};{const t=ot(s,Dr),r=ot(s,Dr),n=ot(s,Un);return{workflow:t,config:r,ui:K.resolve(n,"..","dist")}}}async function qn(s){try{return await oe.promises.readFile(s,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Gn(s){try{return await oe.promises.stat(s,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function cr(s){let e=0n;for(const t of Mn){const r=K.join(s,...t),n=await Gn(r);n!==void 0&&e<n.mtimeNs&&(e=n.mtimeNs)}return e.toString()}async function Xe(s){const e=await oe.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await oe.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class _n{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":{const n=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ze.request(`${r.url}/${Z.RegistryV1.GlobalOverviewPath}`,n)).body.json();for(const l of i){const{organization:c,package:a,latestMeta:u,latestVersion:d}=l,p={organization:c,name:a,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:l.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 oe.promises.readdir(r.path,{withFileTypes:!0})){if(!n.isDirectory())continue;const o=K.join(r.path,n.name),i=await qn(K.join(o,Z.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const l=Z.RegistryV1.PlPackageConfigData.parse(In.parse(i)),c=await cr(o),a={organization:l.organization,name:l.package,version:"DEV"},u={id:a,meta:{title:l.meta.title??"No title",description:l.meta.description??"No Description",organization:{name:l.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:o,mtime:c}};t.push({registryId:e.id,id:a,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}else{let l=o,c=await Z.tryLoadPackDescription(l);if(c===void 0){for(const a of["block","meta"])if(l=K.join(o,a),c=await Z.tryLoadPackDescription(l),c!==void 0)break}if(c!==void 0){const a=await Xe(c),u={id:c.id,meta:await Z.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:l,mtime:a}};t.push({registryId:e.id,id:c.id,latestByChannel:{[Q.AnyChannel]:u,[Q.StableChannel]:u},allVersions:[]})}}}return t;default:return S.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const n=(i=this.registries.find(l=>l.id===e))==null?void 0:i.spec;if(!n)throw new Error(`Registry with id "${e}" not found`);if(n.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(n.url).getSpecificOverview(t,r)}}class Ws{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 Kn={type:"remote-v2",url:"https://blocks.pl-open.science/"},Hn={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Wn={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},zn={groups:[{id:"default",label:"Default",blocks:[]}]},Xn={stagingRefreshTimestamp:0,blocksInLimbo:[]},Yn={label:"New Project"},Qn={name:"UserProject",version:"2"},Ke="SchemaVersion",Fe="2",lr="ProjectCreated",$e="ProjectLastModified",De="ProjectMeta",pe="ProjectStructure",He="BlockRenderingState",Zn="BlockArgsAuthor/";function Zt(s){return`${Zn}${s}`}const er="ProjectStructureAuthor",eo="__serviceTemplate_";function tr(s){return`${eo}${s}`}function z(s,e){return`${s}-${e}`}const to=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|uiState|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function ro(s){const e=s.match(to);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const so="projects",zs={name:"Projects",version:"1"},no=s=>g.resourceTypesEqual(s.type,zs)?s.fields:[];async function oo(s,e,t,r){const n=await _e.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:no},r.logger);return{computable:J.Computable.make(i=>{const l=i.accessor(n.entry()).node(),c=t.getValue(i);if(l===void 0)return;const a=[];for(const u of l.listDynamicFields()){const d=l.traverse(u);if(d===void 0)continue;const p=S.notEmpty(d.getKeyValueAsJson(De)),f=S.notEmpty(d.getKeyValueAsJson(lr)),y=S.notEmpty(d.getKeyValueAsJson($e));a.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(y),opened:c.indexOf(d.id)>=0,meta:p})}return a.sort(u=>-u.lastModified.valueOf()),a}).withStableType(),tree:n}}const io={name:"EphRenderTemplate",version:"1"},ao={name:"RenderTemplate",version:"1"};function Ye(s,e,t,r,n){if(n.length===0)throw new Error("Zero output names provided");const o=t?s.createEphemeral(io):s.createStruct(ao),i=g.field(o,"template"),l=g.field(o,"inputs");return s.createField(i,"Input",e),s.createField(l,"Input",g.Pl.createPlMap(s,r,t)),s.lockInputs(o),g.Pl.futureRecord(s,o,n,"Output","outputs/")}const co={name:"BContextEnd",version:"1"},lo={name:"BContext",version:"1"},uo="id",po="parent/",fo=["context","result"];function Ar(s,e,t){return Ye(s,e,!0,t,fo)}function go(s){const e=s.createEphemeral(co);return s.lock(e),e}function Nr(s,e){if(e.length===0)return go(s);if(e.length===1)return e[0];const t=s.createEphemeral(lo);s.createField(g.field(t,uo),"Input",g.Pl.createPlString(s,te.randomUUID()));for(let r=0;r<e.length;r++)s.createField(g.field(t,`${po}${r}`),"Input",e[r]);return s.lock(t),t}function Xs(s,e){const t=new Map,r=(n,o,i)=>{const l=te.createHash("sha256");o.updateCacheKey(n,l,i);const c=l.digest("hex");if(!t.has(c)){const a=o.render(n,s,r,i);t.set(c,a)}return t.get(c)};return r(e.template,Ys,e.hashToSource)}const jr={updateCacheKey(s,e,t){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data))}},Ve={updateCacheKey(s,e,t){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash))},render(s,e,t,r){const n=$.PlTemplateSoftwareV1.fromV3Data(s,ye(s.name,r,s.sourceHash)),o=e.createStruct($.PlTemplateSoftwareV1.type,n.data);return e.setKValue(o,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(n.name)),e.lock(o),o}},Ys={updateCacheKey(s,e,t){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(ye(s.name,t,s.sourceHash));const r=n=>(n.sort((o,i)=>o[0]===i[0]?0:o[0]<i[0]?-1:1),n);for(const[n,o]of r(Object.entries(s.libs??{})))e.update("lib:"+n),jr.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.software??{})))e.update("soft:"+n),Ve.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.assets??{})))e.update("asset:"+n),Ve.updateCacheKey(o,e,t);for(const[n,o]of r(Object.entries(s.templates??{})))e.update("tpl:"+n),this.updateCacheKey(o,e,t)},render(s,e,t,r){const n=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV3Data(s,ye(s.name,r,s.sourceHash)).data));for(const[l,c]of Object.entries(s.libs??{})){const a=$.PlTemplateV1.libField(n,l);e.createField(a,"Input"),e.setField(a,t(c,jr,r))}for(const[l,c]of Object.entries(s.software??{})){const a=$.PlTemplateV1.swField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ve,r))}for(const[l,c]of Object.entries(s.assets??{})){const a=$.PlTemplateV1.swField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ve,r))}for(const[l,c]of Object.entries(s.templates??{})){const a=$.PlTemplateV1.tplField(n,l);e.createField(a,"Input"),e.setField(a,t(c,Ys,r))}if(e.lock(n),!s.hashOverride)return n;const o=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV3Data(s))),i=$.PlTemplateOverrideV1.tplField(o);return e.createField(i,"Service"),e.setField(i,n),e.lock(o),o}};function ye(s,e,t){return S.notEmpty(e[t],`trying to get "${s}" source: sources map doesn't contain source hash ${t}`)}function ho(s,e){const t=$.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return Zs(s,t);case"pl.tengo-template.v3":return Xs(s,t);default:S.assertNever(r)}}function mo(s,e){const t=e.data,r=t.type;switch(r){case"pl.tengo-template.v2":return Zs(s,t);case"pl.tengo-template.v3":return Xs(s,t);default:S.assertNever(r)}}const Br={hash(s,e){e.update($.PlTemplateLibV1.type.name).update($.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue($.PlTemplateLibV1.type,JSON.stringify($.PlTemplateLibV1.fromV2Data(s).data))}},xe={hash(s,e){e.update($.PlTemplateSoftwareV1.type.name).update($.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=$.PlTemplateSoftwareV1.fromV2Data(s),n=e.createStruct($.PlTemplateSoftwareV1.type,r.data);return e.setKValue(n,$.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(n),n}},Qs={hash(s,e){e.update($.PlTemplateV1.type.name).update($.PlTemplateV1.type.version).update(s.hashOverride??"no-override").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((n,o)=>n[0]===o[0]?0:n[0]<o[0]?-1:1),r);for(const[r,n]of t(Object.entries(s.libs??{})))e.update("lib:"+r),Br.hash(n,e);for(const[r,n]of t(Object.entries(s.software??{})))e.update("soft:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.assets??{})))e.update("asset:"+r),xe.hash(n,e);for(const[r,n]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(n,e)},render(s,e,t){const r=e.createStruct($.PlTemplateV1.type,JSON.stringify($.PlTemplateV1.fromV2Data(s).data));for(const[i,l]of Object.entries(s.libs??{})){const c=$.PlTemplateV1.libField(r,i);e.createField(c,"Input"),e.setField(c,t(l,Br))}for(const[i,l]of Object.entries(s.software??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(l,xe))}for(const[i,l]of Object.entries(s.assets??{})){const c=$.PlTemplateV1.swField(r,i);e.createField(c,"Input"),e.setField(c,t(l,xe))}for(const[i,l]of Object.entries(s.templates??{})){const c=$.PlTemplateV1.tplField(r,i);e.createField(c,"Input"),e.setField(c,t(l,Qs))}if(e.lock(r),!s.hashOverride)return r;const n=e.createStruct($.PlTemplateOverrideV1.type,JSON.stringify($.PlTemplateOverrideV1.fromV2Data(s))),o=$.PlTemplateOverrideV1.tplField(n);return e.createField(o,"Service"),e.setField(o,r),e.lock(n),n}};function Zs(s,e){const t=new Map,r=(n,o)=>{const i=te.createHash("sha256");o.hash(n,i);const l=i.digest("hex");if(!t.has(l)){const c=o.render(n,s,r);t.set(l,c)}return t.get(l)};return r(e,Qs)}const en={name:"TengoTemplateGet",version:"1"},tn="registry",rn="templateURI",sn="template",vo={name:"TengoTemplatePack",version:"1"},yo={name:"TengoTemplatePackConvert",version:"1"},wo="templatePack",So="template";async function ur(s){switch(s.type){case"from-file":return{type:"explicit",content:await oe.promises.readFile(s.path)};case"from-registry":case"explicit":return s;case"prepared":return s;default:return S.assertNever(s)}}function bo(s,e){const t=s.createStruct(en),r=g.field(t,tn),n=g.field(t,rn),o=g.field(t,sn);return s.setField(r,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(n,s.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),o}function Ne(s,e){switch(e.type){case"from-registry":return bo(s,e);case"explicit":return ho(s,e);case"prepared":return mo(s,e);default:return S.assertNever(e)}}const dr={name:"Frontend/FromUrl",version:"1"},pr={name:"Frontend/FromFolder",version:"1"};function Ro(s,e){switch(e.type){case"url":return s.createValue(dr,JSON.stringify({url:e.url}));case"local":return s.createValue(pr,JSON.stringify({path:e.path,signature:e.signature}));default:return S.assertNever(e)}}class ko{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__:K.resolve(void 0,"worker.js"),t=this.worker=new $n.Worker(e,{workerData:{}});t.on("message",({id:r,data:n,error:o})=>{const{resolve:i,reject:l}=this.pendingRequests.get(r);this.pendingRequests.delete(r),o?l(new Error(o)):i(n)}),t.on("error",r=>{console.error("Worker error",r),this.rejectAllPendingRequests(r)})}rejectAllPendingRequests(e){Array.from(this.pendingRequests.values()).map(({reject:t})=>{t(e)})}async process(e,...t){return new Promise((r,n)=>{const o=++this.nextMessageId;this.pendingRequests.set(o,{resolve:r,reject:n}),this.worker.postMessage({id:o,type:e,args:t})})}async terminate(){this.rejectAllPendingRequests(new Error("Worker terminated")),await this.worker.terminate()}[Symbol.asyncDispose](){return this.terminate()}}const Co={name:"BlockPackCustom",version:"1"},nn="template",on="frontend";function Vr(s){return s.endsWith("/")?s:`${s}/`}function Po(s){return Buffer.from(s).toString("utf8")}function Ue(s){return JSON.parse(Po(s))}class Eo{constructor(e,t,r){P(this,"remoteContentCache",new Ms.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 Lr(e.folder),r=await oe.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=`${Vr(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 Ue(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 Ue(n)}default:return S.assertNever(e)}}async prepare(e){var n=[];try{if(e.type==="prepared")return e;const t=await this.prepareWithoutUnpacking(e);const r=Or(n,new ko,!0);return{...t,type:"prepared",template:{type:"prepared",data:await r.process("parseTemplate",t.template.content)}}}catch(o){var i=o,l=!0}finally{var c=Tr(n,i,l);c&&await c}}async prepareWithoutUnpacking(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Lr(e.folder),r=await oe.promises.readFile(t.workflow),n=JSON.parse(await oe.promises.readFile(t.config,"utf-8")),o=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:n,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:e}}case"dev-v2":{const t=await Z.loadPackDescription(e.folder),r=JSON.parse(await oe.promises.readFile(t.components.model.file,{encoding:"utf-8"})),n=await oe.promises.readFile(t.components.workflow.main.file),o=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Xe(t)),{type:"explicit",template:{type:"explicit",content:n},config:r,frontend:{type:"local",path:o,signature:this.signer.sign(o)},source:i}}case"from-registry-v1":{const t=`${Vr(e.registryUrl)}${Z.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,r=`${t}/template.plj.gz`,n=await this.remoteContentCache.forceFetch(r),o=new Uint8Array(n),i=await this.remoteContentCache.forceFetch(`${t}/config.json`),l=Ue(i);return{type:"explicit",template:{type:"explicit",content:o},config:l,frontend:{type:"url",url:`${t}/frontend.tgz`},source:e}}case"from-registry-v2":{const r=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>Ue(await this.remoteContentCache.forceFetch(r.model.url)),o=async()=>await this.remoteContentCache.forceFetch(r.workflow.main.url),[i,l]=await Promise.all([n(),o()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(l)},config:i,frontend:{type:"url",url:r.ui.url},source:e}}default:return S.assertNever(e)}}}function Oo(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Co,JSON.stringify(t));return s.createField(g.field(r,nn),"Input",Ne(s,e.template)),s.createField(g.field(r,on),"Input",Ro(s,e.frontend)),s.lock(r),r}function xr(s,e){switch(e.type){case"prepared":return Oo(s,e);default:return S.assertNever(e.type)}}function Me(s,e,t){return{__isRef:!0,blockId:s,name:e}}function To(s){return typeof s=="object"&&s!==null&&"__isRef"in s&&s.__isRef===!0&&"blockId"in s&&"name"in s}function rr(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(To(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)rr(s,n,t);else for(const[,n]of Object.entries(e))rr(s,n,t);return;default:S.assertNever(r)}}function Io(s,e){const t={upstreams:new Set,upstreamsRequiringEnrichments:new Set,missingReferences:!1};return rr(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 an{constructor(e){P(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,n=>r.add(n.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const n of t)r.delete(n);return r}traverse(e,t,r){let n=[...t];const o=new Set(n);for(;n.length>0;){const i=[];for(const l of n){const c=this.nodes.get(l);r(c),c[e].forEach(a=>{o.has(a)||(o.add(a),i.push(a))})}n=i}}}function sr(s){const e=new Map;let t;for(const{id:r}of ne(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 an(e)}function Ge(s,e){const t=new Map,r=new an(t),n=new Set;for(const{id:o}of ne(s)){const i=e(o);if(i===void 0)continue;const l=Io(i.args,n),c=new Set([...l.upstreams,...r.traverseIds("enrichments",...l.upstreamsRequiringEnrichments)]),a=new Set;for(const{id:p}of ne(s)){if(p===o)break;if(c.has(p)){a.add(p);for(const f of r.traverseIdsExcludingRoots("upstream",p))a.delete(f)}}const u=i.enrichmentTargets===void 0?new Set(l.upstreams):new Set(i.enrichmentTargets.map(p=>p.blockId)),d={id:o,missingReferences:l.missingReferences,upstream:a,directUpstream:l.upstreams,enrichmentTargets:u,downstream:new Set,directDownstream:new Set,enrichments:new Set};t.set(o,d),l.upstreams.forEach(p=>t.get(p).directDownstream.add(o)),a.forEach(p=>t.get(p).downstream.add(o)),u.forEach(p=>{var f;return(f=t.get(p))==null?void 0:f.enrichments.add(o)}),n.add(o)}return r}function Fo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function nr(s,e){if(s.size>e.size)return nr(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Ur(s,e){const t=new Set,r=new Set,n=new Set;return s.nodes.forEach(o=>{const i=e.nodes.get(o.id);i===void 0?t.add(o.id):(!Fo(o.upstream,i.upstream)||nr(o.upstream,n))&&n.add(o.id)}),e.nodes.forEach(o=>{s.nodes.has(o.id)?nr(o.upstream,n)&&n.add(o.id):r.add(o.id)}),{onlyInA:t,onlyInB:r,different:n}}let it;async function cn(){if(it===void 0){const s=await ur(he.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");it={spec:s,hash:e}}return it}function $o(s,e,t){return Ye(s,e,!0,{pf:t},["result"]).result}let me;function ae(){return me||(me={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},process.env.MI_LOG_OUTPUT_STATUS&&(me.logOutputStatus=process.env.MI_LOG_OUTPUT_STATUS==="unstable-only"?"unstable-only":"any"),process.env.MI_LOG_TREE_STAT&&(me.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),me)}function at(s,e){let t=!1,r,n;return()=>{if(!t)return t=!0,r=s(),n=e(),n;const o=s();return r!==o&&(r=o,n=e()),e()}}class Mr{constructor(e,t,r,n){P(this,"currentArgsC",at(()=>this.fields.currentArgs.modCount,()=>S.cachedDeserialize(this.fields.currentArgs.value)));P(this,"prodArgsC",at(()=>{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 S.cachedDeserialize(e)}));P(this,"productionStaleC",at(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t,this.config=r,this.source=n}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentArgs(){return this.currentArgsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get prodArgs(){return this.prodArgsC()}getTemplate(e){return e.getFutureFieldValue(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),nn,"Input")}}const Do=s=>{throw new Error(`No new block info for ${s}`)};class We{constructor(e,t,r,n,o,i,l,c,a,u,d,p){P(this,"globalModCount",0);P(this,"fieldsChanged",!1);P(this,"lastModifiedChanged",!1);P(this,"structureChanged",!1);P(this,"metaChanged",!1);P(this,"renderingStateChanged",!1);P(this,"blocksWithChangedInputs",new Set);P(this,"stagingGraph");P(this,"pendingProductionGraph");P(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=n,this.lastModified=o,this.meta=i,this.struct=l,this.renderingState=c,this.blocksInLimbo=a,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=sr(this.struct)),this.stagingGraph}getProductionGraphBlockInfo(e,t){const r=this.getBlockInfo(e);let n,o;if(t){if(r.fields.prodArgs===void 0)return;n=r.fields.prodArgs,o=r.prodArgs}else n=S.notEmpty(r.fields.currentArgs),o=r.currentArgs;const i=S.notEmpty(r.fields.blockPack);return g.isResourceId(n.ref)&&g.isResourceId(i.ref)?{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o,{argsRid:n.ref,blockPackRid:i.ref})}:{args:o,enrichmentTargets:this.projectHelper.getEnrichmentTargets(()=>r.config,()=>o)}}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ge(this.struct,e=>this.getProductionGraphBlockInfo(e,!1))),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ge(this.struct,e=>this.getProductionGraphBlockInfo(e,!0))),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ne(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const n=g.field(this.rid,z(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(n,"Dynamic",r.ref):this.tx.setField(n,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,n,o){this.setBlockFieldObj(e,t,{ref:r,status:n,value:o})}deleteBlockFields(e,...t){let r=!1;const n=this.getBlockInfo(e);for(const o of t){const i=n.fields;o in i&&(this.tx.removeField(g.field(this.rid,z(e,o))),delete i[o],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((n=t.stagingCtx)==null?void 0:n.status)==="Ready"&&((o=t.stagingUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,n,o;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"&&((o=t.prodUiCtx)==null?void 0:o.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,n;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((n=t.prodCtx)==null?void 0:n.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setStates(e){const t=[];let r=!1;for(const n of e){const o=this.getBlockInfo(n.blockId);let i=!1;for(const l of["args","uiState"]){if(!(l in n))continue;const c=n[l];if(c==null)throw new Error(`Can't set ${l} to null or undefined, please omit the key if you don't want to change it`);const a=l==="args"?"currentArgs":"uiState";let u,d=!1;if(l==="args")u=S.canonicalJsonBytes(c);else{const{data:f,isGzipped:y}=S.canonicalJsonGzBytes(c);u=f,d=y}if(Buffer.compare(o.fields[a].value,u)===0)continue;console.log("setting",a,d,u.length);const p=this.tx.createValue(d?g.Pl.JsonGzObject:g.Pl.JsonObject,u);this.setBlockField(n.blockId,a,p,"Ready",u),i=!0,l==="args"&&t.push(n.blockId)}i&&(this.blocksWithChangedInputs.add(n.blockId),r=!0)}this.getStagingGraph().traverse("downstream",t,({id:n})=>this.resetStaging(n)),r&&this.updateLastModified()}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(r=>{var o;const n=this.getBlockInfo(r);if(((o=n.fields.prodCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(r=>{var o,i;const n=this.getBlockInfo(r);if(((o=n.fields.stagingCtx)==null?void 0:o.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,n.fields.stagingCtx.ref)),((i=n.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,n.fields.prodCtx.ref))}),Nr(this.tx,t)}exportCtx(e){return $o(this.tx,g.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"stagingOutput",o.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const n=t.getTemplate(this.tx),o=Ar(this.tx,n,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,o.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(o.context),"NotReady"),this.setBlockField(e,"prodOutput",o.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=Do){const r=this.getStagingGraph(),n=this.getActualProductionGraph(),o=sr(e),i=Ur(r,o);for(const a of i.onlyInA){const{fields:u}=this.getBlockInfo(a);this.deleteBlockFields(a,...Object.keys(u)),this.blockInfos.delete(a),this.blocksInLimbo.delete(a)&&(this.renderingStateChanged=!0)}for(const a of i.onlyInB){const u=t(a),d=new Mr(a,{},j.extractConfig(u.blockPack.config),u.blockPack.source);this.blockInfos.set(a,d);const p=xr(this.tx,u.blockPack);this.setBlockField(a,"blockPack",g.Pl.wrapInHolder(this.tx,p),"NotReady"),this.setBlockFieldObj(a,"blockSettings",this.createJsonFieldValue(Q.InitialBlockSettings)),this.setBlockFieldObj(a,"currentArgs",this.createJsonFieldValueByContent(u.args)),this.setBlockFieldObj(a,"uiState",this.createJsonFieldValueByContent(u.uiState??"{}")),d.check()}for(const a of i.different)this.resetStaging(a);const l=Ge(e,a=>this.getProductionGraphBlockInfo(a,!0)),c=Ur(n,l);n.traverse("downstream",[...c.different],a=>{this.resetOrLimboProduction(a.id)}),(i.onlyInB.size>0||i.onlyInA.size>0||i.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const n=this.structure;if(r===void 0)n.groups[n.groups.length-1].blocks.push(e);else{let o=!1;for(const i of n.groups){const l=i.blocks.findIndex(c=>c.id===r);if(!(l<0)){i.blocks.splice(l,0,e),o=!0;break}}if(!o)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(n,o=>{if(o!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const n of t.groups){const o=n.blocks.findIndex(i=>i.id===e);if(!(o<0)){n.blocks.splice(o,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const n=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,xr(this.tx,t)),"NotReady"),r!==void 0?this.setStates([{blockId:e,args:r.args,uiState:r.uiState}]):this.getStagingGraph().traverse("downstream",[e],({id:o})=>this.resetStaging(o)),n.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:o})=>this.resetOrLimboProduction(o)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),n=this.getPendingProductionGraph();if(t)n.traverse("upstream",e,l=>{r.add(l.id)});else for(const l of r){const c=n.nodes.get(l);if(c===void 0)throw new Error(`Can't find block with id: ${l}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const o=new Set;for(const l of ne(this.structure)){if(!r.has(l.id))continue;let c=this.getBlockInfo(l.id).requireProductionRendering||this.blocksInLimbo.has(l.id);if(!c){for(const a of n.nodes.get(l.id).upstream)if(o.has(a)){c=!0;break}}c&&(this.renderProductionFor(l.id),o.add(l.id))}const i=[...o];return n.traverse("downstream",i,l=>{o.has(l.id)||this.resetOrLimboProduction(l.id)}),this.getStagingGraph().traverse("downstream",i,({id:l})=>{i[0]!==l&&this.resetStaging(l)}),o.size>0&&this.updateLastModified(),o}stopProduction(...e){var i,l;const t=this.getActualProductionGraph(),r=new Js(e),n=new Set(e),o=[];for(;!r.isEmpty();){const c=r.shift(),a=this.getBlockInfo(c).fields;if(!(((i=a.prodOutput)==null?void 0:i.status)==="Ready"&&((l=a.prodCtx)==null?void 0:l.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){o.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))n.has(u)||(r.push(u),n.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...o))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(n=>{let i=this.getBlockInfo(n.id).stagingRendered?0:1;n.upstream.forEach(l=>{const c=t.get(l);c!==0&&(i=Math.max(c+1,i))}),e(n.id,i),t.set(n.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let n=0;this.traverseWithStagingLag((o,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(o),n++)}),n>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,n,o,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((n=t.fields.prodOutput)==null?void 0:n.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((o=t.fields.stagingCtx)==null?void 0:o.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,Zt(t)):this.tx.setKValue(this.rid,Zt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,er):this.tx.setKValue(this.rid,er,e))}save(){this.wasModified&&(this.lastModifiedChanged&&this.tx.setKValue(this.rid,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,pe,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,He,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,De,JSON.stringify(this.meta)),this.assignAuthorMarkers())}static async load(e,t,r,n){const o=t.getResourceData(r,!0),i=t.getKValueJson(r,Ke),l=t.getKValueJson(r,$e),c=t.getKValueJson(r,De),a=t.getKValueJson(r,pe),u=t.getKValueJson(r,He),d=await o,p=new Map;for(const m of d.fields){const v=ro(m.name);if(v===void 0)continue;let b=p.get(v.blockId);b===void 0&&(b={id:v.blockId,fields:{}},p.set(v.blockId,b)),b.fields[v.fieldName]=g.isNullResourceId(m.value)?{modCount:0}:{modCount:0,ref:m.value}}const f=[];p.forEach(m=>{const v=m.fields;for(const[b,w]of Object.entries(v)){if(w.ref===void 0)continue;if(!g.isResource(w.ref)||g.isResourceRef(w.ref))throw new Error("unexpected behaviour");const C=b;f.push([m,C,w,t.getResourceData(w.ref,C=="blockPack")])}});const[y,h,R,T,{stagingRefreshTimestamp:V,blocksInLimbo:D}]=await Promise.all([i,l,c,a,u]);if(y!==Fe)throw Number(y)<Number(Fe)?new j.UiError("Can't perform this action on this project because it has older schema. Try (re)loading the project to update it."):new j.UiError("Can't perform this action on this project because it has newer schema. Upgrade your desktop app to the latest version.");const M=[];for(const[m,v,b,w]of f){const C=await w;if(b.value=C.data,g.isNotNullResourceId(C.error)?b.status="Error":C.resourceReady||g.isNotNullResourceId(C.originalResourceId)?b.status="Ready":b.status="NotReady",v==="blockPack"){const k=C.fields.find(O=>O.name===g.Pl.HolderRefField);if(k===void 0)throw new Error("Block pack ref field is missing");M.push([m,t.getResourceData(g.ensureResourceIdNotNull(k.value),!1)])}}for(const[m,v]of M){const b=await v,w=S.cachedDeserialize(S.notEmpty(b.data));m.blockConfig=j.extractConfig(w.config),m.blockPack=w.source}const q=await cn(),I=tr(q.hash),B=d.fields.find(m=>m.name===I);let E;B!==void 0?E=g.ensureResourceIdNotNull(B.value):(E=g.Pl.wrapInHolder(t,Ne(t,q.spec)),t.createField(g.field(r,tr(q.hash)),"Dynamic",E));const H={stagingRefreshTimestamp:V},ue=new Set(D),Y=new Map;p.forEach(({id:m,fields:v,blockConfig:b,blockPack:w})=>Y.set(m,new Mr(m,v,S.notEmpty(b),S.notEmpty(w))));const G=new Set;for(const m of ne(T)){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 We(r,t,n,y,h,R,T,H,ue,Y,E,e);return X.fixProblemsAndMigrate(),X}}async function Lo(s,e=Yn){const t=s.createEphemeral(Qn);s.lock(t);const r=String(Date.now());s.setKValue(t,Ke,JSON.stringify(Fe)),s.setKValue(t,lr,r),s.setKValue(t,$e,r),s.setKValue(t,De,JSON.stringify(e)),s.setKValue(t,pe,JSON.stringify(zn)),s.setKValue(t,He,JSON.stringify(Xn));const n=await cn();return s.createField(g.field(t,tr(n.hash)),"Dynamic",g.Pl.wrapInHolder(s,Ne(s,n.spec))),t}async function Je(s,e,t,r){return ie(s,e,t,void 0,r)}async function ie(s,e,t,r,n){if(e instanceof g.PlClient)return await e.withWriteTx("ProjectAction",async o=>{const i=await We.load(s,o,t,r),l=await n(i);return i.wasModified&&(i.save(),await o.commit(),ae().logProjectMutationStat&&console.log(JSON.stringify(o.stat))),l});{const o=await We.load(s,e,t,r),i=await n(o);return o.save(),i}}function*Ao(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:S.assertNever(s)}}function Jr(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function No(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Jr(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Jr(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:S.assertNever(s)}}const jo=g.resourceType("PColumnData/JsonPartitioned","1"),Bo=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Vo=g.resourceType("PColumnData/BinaryPartitioned","1"),xo=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Uo=g.resourceType("PColumnData/Json","1");function Mo(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(g.resourceTypesEqual(s.resourceType,Uo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.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(g.resourceTypesEqual(s.resourceType,Bo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const l of i){const c=JSON.stringify([...JSON.parse(n),...JSON.parse(l)]);r[c]=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,Vo)){const t=e,r={};for(const n of s.listInputFields())if(n.endsWith(".index")){const o=n.slice(0,n.length-6);let i=r[o];i===void 0&&(i={},r[o]=i),i.index=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else if(n.endsWith(".values")){const o=n.slice(0,n.length-7);let i=r[o];i===void 0&&(i={},r[o]=i),i.values=s.traverse({field:n,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${n}`);for(const[n,o]of Object.entries(r)){if(o.index===void 0)throw new Error(`no index for part ${n}`);if(o.values===void 0)throw new Error(`no values for part ${n}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(g.resourceTypesEqual(s.resourceType,xo)){const t=e,r={};for(const n of s.listInputFields()){const o=s.traverse({field:n,errorIfFieldNotSet:!0}),i=o.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${n}`);for(const l of i)if(l.endsWith(".index")){const c=l.slice(0,l.length-6),a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[a];u===void 0&&(u={},r[a]=u),r[a].index=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else if(l.endsWith(".values")){const c=l.slice(0,l.length-7),a=JSON.stringify([...JSON.parse(n),...JSON.parse(c)]);let u=r[a];u===void 0&&(u={},r[a]=u),r[a].values=o.traverse({field:l,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${l}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(s.resourceType)}`)}function Jo(s,e){const t=s.axesSpec.length,r={};for(const{key:n,val:o}of e){if(n.length!==t)throw new Error(`inline column key length ${n.length} differs from axes count ${t}`);r[JSON.stringify(n)]=o}return{type:"Json",keyLength:t,data:r}}function qo(s,e){const t=te.createHash("sha256");return t.update(se(s)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function qr(s,e){return se({__isRef:!0,blockId:s,name:e})}function Go(s,e){return se({resolvePath:s,name:e})}function ln(s,e=!0,t=!1,r=""){var l,c,a;const n=/^(?<name>.*)\.(?<type>spec|data)$/,o=new Map;for(const u of s.listInputFields()){const d=u.match(n);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let p=S.notEmpty((l=d.groups)==null?void 0:l.name);if(!p.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}p=p.slice(r.length);const f=S.notEmpty((c=d.groups)==null?void 0:c.type);let y=o.get(p);switch(y===void 0&&(y={},o.set(p,y)),f){case"spec":y.spec=(a=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:a.getDataAsJson();break;case"data":y.hasData=!0,y.data=()=>s.traverseOrError({field:u,ignoreError:t});break}}const i=s.getInputsLocked();if(i)for(const[,u]of o)u.data===void 0&&(u.hasData=!1);return{locked:i,results:o}}function _o(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const n=ln(s,e,!1,t);Dn(n.locked);const o={};for(const[i,l]of n.results){if(l.spec===void 0)throw new Error(`no spec for key ${i}`);if(l.hasData!==!0||l.data===void 0)throw new Error(`no data for key ${i}`);const c=l.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw c.error;o[i]={id:r.length===0?qo(l.spec,c.value):Go(r,i),spec:l.spec,data:c.value}}return o}class fr{constructor(e,t){P(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const n of t.values())for(const o of[n.prod,n.staging])if(o!==void 0){if(!o.locked){r=!1;break e}for(const i of o.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var o,i,l,c,a,u;const r=this.blocks.get(e);if(r===void 0)return;let n=(l=(i=(o=r.prod)==null?void 0:o.results)==null?void 0:i.get(t))==null?void 0:l.spec;if(n!==void 0||(n=(u=(a=(c=r.staging)==null?void 0:c.results)==null?void 0:a.get(t))==null?void 0:u.spec,n!==void 0))return n;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,l,c;const r=this.blocks.get(e);if(r===void 0)return;const n=(l=(i=r.prod)==null?void 0:i.results)==null?void 0:l.get(t),o=(c=n==null?void 0:n.data)==null?void 0:c.call(n);if(n!==void 0&&n.spec!==void 0&&o!==void 0)return j.mapValueInVOE(o,a=>({id:qr(e,t),spec:n.spec,data:a}));n!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const n=i=>{r===void 0&&(r=i),t=!1},o=(i,l,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const a=c.data();a!==void 0?e.push({ref:Me(i,l),obj:{id:a.ok?qr(i,l):void 0,spec:c.spec,data:a}}):n(`no_data:${i}:${l}`)}};for(const[i,l]of this.blocks){const c=new Set;if(l.prod!==void 0){l.prod.locked||n(`prod_not_locked:${i}`);for(const[a,u]of l.prod.results)c.add(a),o(i,a,u)}if(l.staging!==void 0){l.staging.locked||n(`staging_not_locked:${i}`);for(const[a,u]of l.staging.results)c.has(a)||o(i,a,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const n=o=>{r===void 0&&(r=o),t=!1};for(const[o,i]of this.blocks){const l=new Set;if(i.staging!==void 0){i.staging.locked||n(`staging_not_locked:${o}`);for(const[c,a]of i.staging.results)a.spec!==void 0&&(e.push({ref:Me(o,c),obj:a.spec}),l.add(c))}else n(`staging_not_rendered:${o}`);if(i.prod!==void 0){i.prod.locked||n(`prod_not_locked:${o}`);for(const[c,a]of i.prod.results)l.has(c)||a.spec!==void 0&&e.push({ref:Me(o,c),obj:a.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const n=new Set,o=i=>{for(const[l,c]of i.results)n.has(l)||c.spec===void 0||(n.add(l),j.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+l,ref:Me(r.info.id,l),spec:c.spec}))};r.staging!==void 0&&o(r.staging),r.prod!==void 0&&o(r.prod)}return t}static create(e,t,r){const n=e.accessor(t).node(),o=S.notEmpty(n.getKeyValueAsJson(pe)),l=sr(o).traverseIds("upstream",r),c=new Map;for(const a of ne(o)){if(!l.has(a.id))continue;const u=Gr(n.traverse({field:z(a.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,n.traverseOrError({field:z(a.id,"prodUiCtx"),stableIfNotFound:!0})),d=Gr(n.traverse({field:z(a.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,n.traverseOrError({field:z(a.id,"stagingUiCtx")}));c.set(a.id,{info:a,prod:u,staging:d})}return new fr(e,c)}}function Gr(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return ln(e.value,!1,!0)}function gr(s,e){return{blockId:e,args:o=>S.cachedDecode(S.notEmpty(o.accessor(s).node().traverse({field:z(e,"currentArgs"),errorIfFieldNotSet:!0}).getData())),activeArgs:o=>{var l;const i=(l=o.accessor(s).node().traverse({field:z(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:l.getData();return i?S.cachedDecode(i):void 0},uiState:o=>{var l;const i=(l=o.accessor(s).node().traverse({field:z(e,"uiState"),stableIfNotFound:!0}))==null?void 0:l.getData();return i?S.cachedDecode(i):void 0},blockMeta:o=>{const i=o.accessor(s).node(),l=S.notEmpty(i.getKeyValueAsJson(pe)),c=new Map;for(const a of ne(l))c.set(a.id,a);return c}}}function un(s,e){return{...gr(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:z(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:z(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>fr.create(t,s,e)}}function*re(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*re(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*re(t);return;case"MakeArray":for(const t of s.template)yield*re(t);return;case"GetJsonField":case"GetResourceField":yield*re(s.source),yield*re(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*re(s.source),yield*re(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*re(s.source);return;case"IsEmpty":yield*re(s.arg);return;case"Not":yield*re(s.operand);return;case"And":case"Or":yield*re(s.operand1),yield*re(s.operand2);return;default:S.assertNever(s)}}function Ko(s,e){const t={};for(const[r,n]of Object.entries(s))t[r]=e(n);return t}function Pe(s,e){return s===void 0?void 0:e(s)}function Ho(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Wo(s){for(const e of re(s))if(Ho(e))return!0;return!1}function Qe(s){return{type:"ReturnResult",result:s}}function L(s){return()=>Qe(s)}const zo=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return L(e)},Xo=s=>{const e=s.source;if(e===void 0)return L(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return L(t)},Yo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?L(void 0):({cCtx:r})=>{var n;return Qe((n=r.accessor(e).node().traverse(t))==null?void 0:n.persist())}};function dn(s,e){const t={},r=s.length;for(let n=0;n<r;n++)t[String(n)]=e(s[n]);return t}function Qo(s,e){return t=>{const r=t.source;return r===void 0?L(void 0):()=>({type:"ScheduleSubroutine",subroutine:pn(r.length),args:dn(r,n=>N({...s,[e.itVar]:n},e.mapping))})}}function pn(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return L(t)}}function Zo(s,e){return t=>{const r=t.source;if(r===void 0)return L(void 0);const n={};for(const[o,i]of Object.entries(r)){const l={...s,[e.itVar]:i};n[o]=N(l,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ei,args:n})}}const ei=s=>L(s),ti=s=>{const e=s.arg;return L(e===void 0?void 0:e.length===0)},ri=s=>{const e=s.operand;return L(e===void 0?void 0:!e)},si=s=>{const e=s.operand1,t=s.operand2;return L(e===void 0||t===void 0?void 0:e&&t)},ni=s=>{const e=s.operand1,t=s.operand2;return L(e===void 0||t===void 0?void 0:e||t)},oi=s=>{const e=s.source;return e===void 0?L(void 0):({cCtx:t})=>{var r;return Qe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},ii=s=>{const e=s.source,t=s.field;return L(e===void 0||t===void 0?void 0:e[t])};function ai(s,e){return t=>{const r=t.source;return r===void 0?L(void 0):({cCtx:n})=>{const o=n.accessor(r).node(),i={};for(const l of o.listInputFields()){const c=o.traverse(l);if(c===void 0)i[l]=L(void 0);else{const a={...s,[e.itVar]:c.persist()};i[l]=N(a,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ci,args:i}}}}const ci=s=>L(s),li=s=>e=>{const t=e.source;return t===void 0?L(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)}})})},ui=s=>e=>{const t=e.source;return t===void 0?L(void 0):({cCtx:r,drivers:n})=>{const o=r.accessor(t).node().resourceInfo;return{type:"ScheduleComputable",computable:J.Computable.make(i=>n.blobDriver.getDownloadedBlob(o,i),{postprocessValue:async i=>i===void 0?void 0:(await n.blobDriver.getContent(i.handle,s)).toString()})}}},di=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:J.Computable.make(n=>r.blobDriver.getDownloadedBlob(n.accessor(t).node().resourceInfo,n),{postprocessValue:async n=>{if(n==null)return;const o=await r.blobDriver.getContent(n.handle,s);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},pi=s=>{const e=s.source;return e===void 0?L(void 0):t=>({type:"ScheduleComputable",computable:t.drivers.blobDriver.getDownloadedBlob(e)})},fi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},gi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},hi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},mi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},vi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},yi=s=>e=>{const t=e.source;return t===void 0?L(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLogWithInfo(t,s)})},wi=s=>{const e=s.source;return e===void 0?L(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function N(s,e){switch(e.type){case"GetFromCtx":{const t=s[e.variable];return typeof t=="function"?r=>Qe(t(r.cCtx)):L(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:hn(t,s,e.cfg)});case"Immediate":return L(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:ii,args:{source:N(s,e.source),field:N(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Qo(s,e),args:{source:N(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Zo(s,e),args:{source:N(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:Ko(e.template,t=>N(s,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:pn(e.template.length),args:dn(e.template,t=>N(s,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:N(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ti,args:{arg:N(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:ri,args:{operand:N(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:si,args:{operand1:N(s,e.operand1),operand2:N(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:ni,args:{operand1:N(s,e.operand1),operand2:N(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:ai(s,e),args:{source:N(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:N(s,e.source),field:N(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:oi,args:{source:N(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:li(e.range),args:{source:N(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:ui(e.range),args:{source:N(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:di(e.range),args:{source:N(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:pi,args:{source:N(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:fi,args:{source:N(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:gi(e.format),args:{source:N(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:hi,args:{source:N(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:mi(e.lines),args:{source:N(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:vi(e.patternToSearch),args:{source:N(s,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:yi(e.patternToSearch),args:{source:N(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:wi,args:{source:N(s,e.source)}});default:return S.assertNever(e)}}const Si=["$prod","$staging"];function bi(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 fn=Symbol(),gn="return",Ri={op:fn,arg:gn};function ki(s){return s.op==fn&&s.arg==gn}function Ci(){return{pendingSubroutines:new Map}}function _r(s,e,t,r){const n=new Js(t),o=(l,c)=>{if(ki(l))return e.result=c,!1;const a=S.notEmpty(e.pendingSubroutines.get(l.op));if(l.arg in a.args)throw new Error("argument already set");return a.args[l.arg]=c,a.argCounter--,a.argCounter===0&&(e.pendingSubroutines.delete(l.op),n.push({destination:a.destination,operation:a.subroutine(a.args)})),!0},i=[];e:for(;n.length>0;){const l=n.shift(),c=l.operation(s);switch(c.type){case"ReturnResult":if(!o(l.destination,c.result))break e;break;case"ScheduleSubroutine":{const a=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)n.push({destination:l.destination,operation:c.subroutine({})});else{for(const[p,f]of u)n.push({destination:{op:a,arg:p},operation:f});e.pendingSubroutines.set(a,{argCounter:d,args:{},subroutine:c.subroutine,destination:l.destination})}}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:l.destination,computable:c.computable});break;default:S.assertNever(c)}}return i}function Pi(s,e,t,r={}){return hn(s,bi(e),t,r)}function hn(s,e,t,r={}){const n=`${e.blockId}#`+se({ctx:Object.fromEntries(Object.entries(e).filter(([o])=>Si.indexOf(o)===-1)),cfg:t});return J.Computable.makeRaw(o=>{const i={drivers:s,cCtx:o},l=Ci();return{ir:_r(i,l,[{destination:Ri,operation:N(e,t)}],!0),postprocessValue(a){const u=[];for(const y of a)u.push({destination:y.destination,operation:L(y.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},p=new Map;for(const[y,h]of l.pendingSubroutines)p.set(y,{...h,args:{...h.args}});const f={result:l.result,pendingSubroutines:p};if(_r(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...r,key:n})}function Kr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Ei{constructor(e,t,r,n){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.computableCtx=n,this.meta=t.blockMeta(n)}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,n)=>{if(!this.accessors.has(r)){const o=this.blockCtx[n];if(o===void 0)throw new Error("Staging context not available");const i=o(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return Kr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return Kr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...n){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const i=_o(o,t,r,n),l={};for(const[c,a]of Object.entries(i))l[c]=j.mapPObjectData(a,u=>this.wrapAccessor(u));return l}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=S.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:j.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:j.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 j.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=>j.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(j.mapPTableDef(e,t=>j.mapPObjectData(t,r=>this.transformInputPData(r))),this.computableCtx)}transformInputPData(e){return typeof e=="string"?this.getAccessor(e):j.isDataInfo(e)?j.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 o=this.blockCtx.args(this.computableCtx),i=this.blockCtx.activeArgs(this.computableCtx),l=this.blockCtx.uiState(this.computableCtx);r.setProp(e,"args",n.manage(r.newString(o))),l!==void 0&&r.setProp(e,"uiState",n.manage(r.newString(l))),i!==void 0&&r.setProp(e,"activeArgs",n.manage(r.newString(i)));const c=(a,u)=>{const d=(...p)=>{try{return u(...p)}catch(f){const y=t.errorRepo.setAndRecreateForQuickJS(f);throw r.newError(y)}};r.newFunction(a,d).consume(p=>r.setProp(e,a,p)),r.newFunction(a,u).consume(p=>r.setProp(e,a+"__internal__",p))};c("getAccessorHandleByName",a=>t.exportSingleValue(this.getAccessorHandleByName(r.getString(a)),void 0)),c("resolveWithCommon",(a,u,...d)=>t.exportSingleValue(this.resolveWithCommon(r.getString(a),t.importObjectViaJson(u),...d.map(p=>t.importObjectViaJson(p))),void 0)),c("getResourceType",a=>t.exportObjectViaJson(this.getResourceType(r.getString(a)),void 0)),c("getInputsLocked",a=>t.exportSingleValue(this.getInputsLocked(r.getString(a)),void 0)),c("getOutputsLocked",a=>t.exportSingleValue(this.getOutputsLocked(r.getString(a)),void 0)),c("getIsReadyOrError",a=>t.exportSingleValue(this.getIsReadyOrError(r.getString(a)),void 0)),c("getIsFinal",a=>t.exportSingleValue(this.getIsFinal(r.getString(a)),void 0)),c("getError",a=>t.exportSingleValue(this.getError(r.getString(a)),void 0)),c("listInputFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("listOutputFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("listDynamicFields",a=>t.exportObjectViaJson(this.listInputFields(r.getString(a)),void 0)),c("getKeyValueBase64",(a,u)=>t.exportSingleValue(this.getKeyValueBase64(r.getString(a),r.getString(u)),void 0)),c("getKeyValueAsString",(a,u)=>t.exportSingleValue(this.getKeyValueAsString(r.getString(a),r.getString(u)),void 0)),c("getDataBase64",a=>t.exportSingleValue(this.getDataBase64(r.getString(a)),void 0)),c("getDataAsString",a=>t.exportSingleValue(this.getDataAsString(r.getString(a)),void 0)),c("parsePObjectCollection",(a,u,d,...p)=>t.exportObjectUniversal(this.parsePObjectCollection(r.getString(a),r.dump(u),r.getString(d),...p.map(f=>r.getString(f))),void 0)),c("getBlobContentAsBase64",(a,u)=>t.exportSingleValue(this.getBlobContentAsBase64(r.getString(a),t.importObjectUniversal(u)),void 0)),c("getBlobContentAsString",(a,u)=>t.exportSingleValue(this.getBlobContentAsString(r.getString(a),t.importObjectUniversal(u)),void 0)),c("getDownloadedBlobContentHandle",a=>t.exportSingleValue(this.getDownloadedBlobContentHandle(r.getString(a)),void 0)),c("getOnDemandBlobContentHandle",a=>t.exportSingleValue(this.getOnDemandBlobContentHandle(r.getString(a)),void 0)),c("extractArchiveAndGetURL",(a,u)=>t.exportSingleValue(this.extractArchiveAndGetURL(r.getString(a),r.getString(u)),void 0)),c("getImportProgress",a=>t.exportSingleValue(this.getImportProgress(r.getString(a)),void 0)),c("getLastLogs",(a,u)=>t.exportSingleValue(this.getLastLogs(r.getString(a),r.getNumber(u)),void 0)),c("getProgressLog",(a,u)=>t.exportSingleValue(this.getProgressLog(r.getString(a),r.getString(u)),void 0)),c("getProgressLogWithInfo",(a,u)=>t.exportSingleValue(this.getProgressLogWithInfo(r.getString(a),r.getString(u)),void 0)),c("getLogHandle",a=>t.exportSingleValue(this.getLogHandle(r.getString(a)),void 0)),c("getBlockLabel",a=>t.exportSingleValue(this.getBlockLabel(r.getString(a)),void 0)),c("getDataFromResultPool",()=>t.exportObjectUniversal(this.getDataFromResultPool(),void 0)),c("getDataWithErrorsFromResultPool",()=>t.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),c("getSpecsFromResultPool",()=>t.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),c("calculateOptions",a=>t.exportObjectUniversal(this.calculateOptions(t.importObjectViaJson(a)),void 0)),c("getSpecFromResultPoolByRef",(a,u)=>t.exportObjectUniversal(this.getSpecFromResultPoolByRef(r.getString(a),r.getString(u)),void 0)),c("getDataFromResultPoolByRef",(a,u)=>t.exportObjectUniversal(this.getDataFromResultPoolByRef(r.getString(a),r.getString(u)),void 0)),c("createPFrame",a=>t.exportSingleValue(this.createPFrame(t.importObjectViaJson(a)),void 0)),c("createPTable",a=>t.exportSingleValue(this.createPTable(t.importObjectViaJson(a)),void 0)),c("getCurrentUnstableMarker",()=>t.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),c("logInfo",a=>{this.logInfo(r.getString(a))}),c("logWarn",a=>{this.logWarn(r.getString(a))}),c("logError",a=>{this.logError(r.getString(a))})})}}function Oi(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}class Le{constructor(e,t,r,n){P(this,"callbackRegistry");P(this,"fnJSONStringify");P(this,"fnJSONParse");P(this,"errorRepo",new Ti);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.");n!==void 0&&(this.computableHelper=new Ei(this,n.blockCtx,n.mlEnv,n.computableCtx)),this.injectCtx()}resetComputableCtx(){S.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 Le.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(o=>this.exportObjectUniversal(o,r)))))})}catch(r){throw Le.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(Oi(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(j.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e)),this.computableHelper!==void 0&&this.computableHelper.injectCtx(t),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}class Ti{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",g.stringifyWithResourceId(e)),e;if(!("name"in e.cause))return console.warn("ErrorRepo: quickJSError.cause is not an Error",g.stringifyWithResourceId(e)),e;const t=e.cause.name,r=t.slice(t.indexOf("/uuid:")+6);if(!r)throw new Error(`ErrorRepo: quickJSError.cause.name does not contain errorId: ${t}, ${g.stringifyWithResourceId(e)}`);const n=this.errorIdToError.get(r);if(n===void 0)throw new Error(`ErrorRepo: errorId not found: ${r}, ${g.stringifyWithResourceId(e)}`);return new Ln.PlQuickJSError(e,n)}}function Ii(s,e,t,r,n,o={}){const i=`${e.blockId}#lambda#${n}#${t.handle}`;return o={...o,key:i},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),J.Computable.makeRaw(l=>{const c=new ge.Scope;l.addOnDestroy(()=>c.dispose());const a=c.manage(s.quickJs.newRuntime());a.setMemoryLimit(1024*1024*8),a.setMaxStackSize(1024*320);let u;a.setInterruptHandler(()=>u===void 0?!1:Date.now()>u.deadline);const d=c.manage(a.newContext()),p=new Le(c,d,h=>{u=h},{computableCtx:l,blockCtx:e,mlEnv:s});p.evaluateBundle(r.content);const f=p.runCallback(t.handle);p.resetComputableCtx();let y=0;return ae().logOutputStatus==="any"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:p.computableHelper.computablesToResolve,postprocessValue:(h,{unstableMarker:R,stable:T})=>{for(const[D,M]of Object.entries(h))p.runCallback(D,M);const V=p.importObjectUniversal(f);return y++,ae().logOutputStatus&&(ae().logOutputStatus==="any"||!T)&&console.log(T?`Stable output ${t.handle} calculated ${V!==void 0?"defined":"undefined"}; (#${y})`:`Unstable output ${t.handle}; marker = ${R}; ${V!==void 0?"defined":"undefined"} (#${y})`),V}}},o)}function Fi(s,e,t,...r){const n=new ge.Scope;try{const o=n.manage(s.newRuntime());o.setMemoryLimit(1024*1024*8),o.setMaxStackSize(1024*320);let i;o.setInterruptHandler(()=>i===void 0?!1:Date.now()>i.deadline);const l=n.manage(o.newContext()),c=new Le(n,l,a=>{i=a});return c.evaluateBundle(t.content),c.importObjectUniversal(c.runCallback(e.handle,...r))}finally{n.dispose()}}function $i(s){return j.isConfigLambda(s)?s.isActive===!0:Wo(s)}function Ee(s,e,t,r,n,o={}){if(j.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Ii(s,e,t,r,n,o)}else return Pi(s.driverKit,e,t,o)}function Ae(s,e){return Pe(s.traverse({field:z(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),n=j.extractConfig(r.config);return{bpResourceId:t.resourceInfo.id,bpId:t.resourceInfo.id.toString(),info:r,cfg:n}})}function Di(s,e){if(s===e)return!0;if(s===void 0||e===void 0)return!1;const t=Fr.omitBy((r,n)=>n.startsWith("__"));return Fr.isDeepEqual(t(s),t(e))}function Li(s,e,t){return J.Computable.make(r=>{var y,h,R,T,V,D,M,q;const n=r.accessor(s).node(),o=S.notEmpty(n.getKeyValueAsJson(lr)),i=S.notEmpty(n.getKeyValueAsJson($e)),l=S.notEmpty(n.getKeyValueAsJson(De)),c=S.notEmpty(n.getKeyValueAsJson(pe)),a=S.notEmpty(n.getKeyValueAsJson(He)),u=new Map;for(const{id:I}of ne(c)){const B=n.traverse({field:z(I,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}),E=B.getDataAsJson();let H;const ue=n.traverse({field:z(I,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(ue!==void 0){const Y=ue.getDataAsJson(),G=n.getField({field:z(I,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),X=n.getField({field:z(I,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});H={arguments:Y,stale:!Di(E,Y),outputError:G.error!==void 0||X.error!==void 0||((y=G.value)==null?void 0:y.getError())!==void 0||((h=X.value)==null?void 0:h.getError())!==void 0,outputsError:((R=G.error)==null?void 0:R.getDataAsString())??((V=(T=G.value)==null?void 0:T.getError())==null?void 0:V.getDataAsString()),exportsError:((D=X.error)==null?void 0:D.getDataAsString())??((q=(M=X.value)==null?void 0:M.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(I,{currentArguments:E,prod:H,argsRid:B.resourceInfo.id})}const d=Ge(c,I=>{const B=Ae(n,I),E=u.get(I),H=E.currentArguments;return{args:H,enrichmentTargets:t.projectHelper.getEnrichmentTargets(()=>B.cfg,()=>H,{argsRid:E.argsRid,blockPackRid:B.bpResourceId})}}),p=new Set(a.blocksInLimbo),f=[...ne(c)].map(({id:I,label:B,renderingMode:E})=>{var k,O,A,F,x;const H=S.notEmpty(u.get(I)),ue=S.notEmpty(d.nodes.get(I));let Y="NotCalculated";H.prod!==void 0&&(p.has(I)?Y="Limbo":Y=H.prod.finished?"Done":"Running");const G=Ae(n,I),{sections:X,title:m,inputsValid:v,sdkVersion:b}=Pe(G,({bpId:_,cfg:U})=>{const de=gr(s,I);return{sections:Ee(t,de,U.sections,U.code,_).wrap({recover:ke=>(t.logger.error("Error in block model sections"),t.logger.error(ke),[])}),title:Pe(U.title,ke=>Ee(t,de,ke,U.code,_).wrap({recover:En=>(t.logger.error("Error in block model title"),t.logger.error(En),"Invalid title")})),inputsValid:Ee(t,de,U.inputsValid,U.code,_).wrap({recover:ke=>(t.logger.error("Error in block model argsValid"),t.logger.error(ke),!1)}),sdkVersion:U.sdkVersion}})||{},w=n.traverse({field:z(I,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),C=Pe(G,({info:_})=>t.blockUpdateWatcher.get({currentSpec:_.source,settings:w}));return{projectResourceId:g.resourceIdToString(s.rid),id:I,label:m??B,title:m??B,renderingMode:E,stale:((k=H.prod)==null?void 0:k.stale)!==!1||Y==="Limbo",missingReference:ue.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",I)],downstreams:[...d.traverseIdsExcludingRoots("downstream",I)],calculationStatus:Y,outputErrors:((O=H.prod)==null?void 0:O.outputError)===!0,outputsError:(A=H.prod)==null?void 0:A.outputsError,exportsError:(F=H.prod)==null?void 0:F.exportsError,settings:w,sections:X,inputsValid:v,updateInfo:{},currentBlockPack:(x=G==null?void 0:G.info)==null?void 0:x.source,updates:C,sdkVersion:b,navigationState:e.getState(I)}});return{meta:l,created:new Date(o),lastModified:new Date(i),authorMarker:n.getKeyValueAsJson(er),blocks:f}},{postprocessValue:r=>{const n=new Set,o=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||n.add(i.id),i.stale&&o.add(i.id);const l=i.stale||i.upstreams.findIndex(p=>o.has(p))!==-1,c=(l||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(p=>n.has(p))===-1,a={...i,canRun:c,stale:l,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete a.updates,a})}}}).withStableType()}function Ai(s,e){const t=s.node();if(g.resourceTypesEqual(t.resourceType,dr)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(g.resourceTypesEqual(t.resourceType,pr)){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 Ni(s,e){if(s!==void 0)return J.Computable.make(t=>Ai(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function ji(s,e,t){return J.Computable.make(r=>{var l;const n=r.accessor(s).node(),o=Ae(n,e),i=(l=n.traverse({field:z(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:on,assertFieldType:"Input"}))==null?void 0:l.persist();return{path:Ni(i,t),sdkVersion:o==null?void 0:o.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function mn(s,e,t){if(t===void 0)return J.Computable.make(i=>mn(s,e,i),{key:`inputs#${g.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),n=gr(s,e),o=n.uiState(t);return{author:r.getKeyValueAsJson(Zt(e)),args:S.deepFreeze(JSON.parse(n.args(t))),ui:o!==void 0?S.deepFreeze(JSON.parse(o)):void 0}}function Bi(s,e,t){return J.Computable.make(r=>{const n=r.accessor(s).node(),o=un(s,e);return Pe(Ae(n,e),({cfg:i,bpId:l})=>{const c={};for(const[a,u]of Object.entries(i.outputs)){const d=Ee(t,o,u,i.code,l);c[a]=J.Computable.wrapError(d,1)}return c})},{key:"outputs#"+g.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Vi(s,e){return J.Computable.make(t=>{const r=t.accessor(s).node(),n=S.notEmpty(r.getKeyValueAsJson(pe)),o=[];for(const{id:i}of ne(n)){const l=Ae(r,i);if(l===void 0)continue;const c=Object.entries(l.cfg.outputs).map(([,u])=>u).filter(u=>$i(u)).map(u=>u);if(c.length===0)continue;const a=un(r.persist(),i);for(const u of c)o.push(J.Computable.wrapError(Ee(e,a,u,l.cfg.code,l.bpId)))}return o})}class xi{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()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...j.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())}}function Ui(s){return J.Computable.make(e=>{const t=e.accessor(s).node(),r=S.notEmpty(t.getKeyValueAsJson(pe));return{listOfBlocks:[...ne(r)].map(n=>n.id)}})}const Mi="1",Ji="BlockFrontendState/";async function qi(s,e){await s.withWriteTx("ProjectMigration",async t=>{const r=await t.getKValueJson(e,Ke);if(r!==Fe){if(r===Mi)await Gi(t,e);else throw new Error(`Unknown project schema version: ${r}`);t.setKValue(e,Ke,JSON.stringify(Fe)),await t.commit()}})}async function Gi(s,e){const[t,r]=await Promise.all([s.getKValueJson(e,pe),s.listKeyValues(e)]),n=new Map(r.map(o=>[o.key,o.value]));for(const o of ne(t)){const i=Ji+o.id,l=n.get(i),c=l?S.cachedDeserialize(l):{},a=s.createJsonGzValue(c),u=g.field(e,z(o.id,"uiState"));s.createField(u,"Dynamic",a),s.deleteKValue(e,i)}}function Hr(s){return JSON.stringify(s,(e,t)=>typeof t=="bigint"?g.resourceIdToString(t):ArrayBuffer.isView(t)||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array||t instanceof Float64Array||t instanceof BigInt64Array||t instanceof BigUint64Array?Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"):Buffer.isBuffer(t)?t.toString("base64"):t)}class Ze{constructor(e,t,r){P(this,"rid");P(this,"overview");P(this,"overviewLight");P(this,"navigationStates",new xi);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=Li(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.overviewLight=Ui(r.entry()).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Vi(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Je(this.env.projectHelper,this.env.pl,this.rid,r=>{r.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await qs.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal);const e=await this.overviewLight.getValue(),t=new Set(e.listOfBlocks);for(const r of this.blockComputables.keys())if(!t.has(r)){const n=this.blockComputables.get(r);n!=null&&n.fullState.resetState(),this.blockComputables.set(r,null)}}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,n=void 0,o=te.randomUUID()){const i=await this.env.bpPreparer.prepare(t),l=await this.env.bpPreparer.getBlockConfigContainer(t),c=j.extractConfig(l);return await ie(this.env.projectHelper,this.env.pl,this.rid,n,a=>a.addBlock({id:o,label:e,renderingMode:c.renderingMode},{args:se(c.initialArgs),uiState:se(c.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),o}async updateBlockPack(e,t,r=!1,n){const o=await this.env.bpPreparer.prepare(t),i=j.extractConfig(await this.env.bpPreparer.getBlockConfigContainer(t));await ie(this.env.projectHelper,this.env.pl,this.rid,n,l=>l.migrateBlockPack(e,o,r?{args:i.initialArgs,uiState:i.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 o=n.groups[0];if(o.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${o.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:o.id,label:o.label,blocks:e.map(l=>{const c=o.blocks.find(a=>a.id===l);if(c===void 0)throw new Error(`Can't find block: ${l}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Je(this.env.projectHelper,this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Je(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,o=>{o.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=g.ensureResourceIdNotNull((await r.getField(g.field(this.rid,z(e,"blockPack")))).value),o=g.ensureResourceIdNotNull((await r.getField(g.field(n,g.Pl.HolderRefField))).value),i=await r.getResourceData(o,!1),l=j.extractConfig(S.cachedDeserialize(S.notEmpty(i.data)).config);await ie(this.env.projectHelper,r,this.rid,t,c=>{c.setStates([{blockId:e,args:l.initialArgs,uiState:l.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=Bi(this.projectTree.entry(),e,this.env),o={fullState:J.Computable.make(i=>({argsAndUiState:mn(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e),overview:this.overview}),{postprocessValue:i=>{var u,d,p;const l=(p=(d=(u=i.overview)==null?void 0:u.blocks)==null?void 0:d.find(f=>f.id==e))==null?void 0:p.sdkVersion,a=l&&Ki(l)&&i.outputs!==void 0?Wi(i.outputs):i.outputs;return{...i.argsAndUiState,outputs:a,navigationState:i.navigationState}}}).withPreCalculatedValueTree()};return this.blockComputables.set(e,o),o}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=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 qi(e.pl,t),await Je(e.projectHelper,e.pl,t,n=>{});const r=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:_i},e.logger);if(e.ops.debugOps.dumpInitialTreeState){const n=r.dumpState();n.sort((i,l)=>{var c,a;return(((c=l.data)==null?void 0:c.byteLength)??0)-(((a=i.data)==null?void 0:a.byteLength)??0)});const o=_e.treeDumpStats(n);await Ie.writeFile(`${g.resourceIdToString(t)}.json`,Hr(n)),await Ie.writeFile(`${g.resourceIdToString(t)}.stats.json`,Hr(o))}return new Ze(e,t,r)}}function _i(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 Ki(s){return!Hi(s,"1.26.0")}function Hi(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 Wi(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 hr={logger:new S.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:8*1024*1024*1024,rangesCacheMaxSizeBytes:8*1024*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:1*1024*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function mr(s){return{blobDownloadPath:K.join(s,"download"),blobDownloadRangesCachePath:K.join(s,"downloadRangesCache"),downloadBlobToURLPath:K.join(s,"downloadToURL"),pframesSpillPath:K.join(s,"pframes")}}const vn={...hr,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500,initialTreeLoadingTimeout:100*60*60*1e3},debugOps:{dumpInitialTreeState:!1},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function yn(s){return{...mr(s),frontendDownloadPath:K.join(s,"frontend")}}function zi(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qe={exports:{}},ct,Wr;function et(){if(Wr)return ct;Wr=1;const s="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,n=e-6;return ct={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},ct}var lt,zr;function tt(){return zr||(zr=1,lt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{}),lt}var Xr;function je(){return Xr||(Xr=1,function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:n}=et(),o=tt();e=s.exports={};const i=e.re=[],l=e.safeRe=[],c=e.src=[],a=e.safeSrc=[],u=e.t={};let d=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",n],[p,r]],y=R=>{for(const[T,V]of f)R=R.split(`${T}*`).join(`${T}{0,${V}}`).split(`${T}+`).join(`${T}{1,${V}}`);return R},h=(R,T,V)=>{const D=y(T),M=d++;o(R,M,T),u[R]=M,c[M]=T,a[M]=D,i[M]=new RegExp(T,V?"g":void 0),l[M]=new RegExp(D,V?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),h("MAINVERSION",`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASE",`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${p}+`),h("BUILD",`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h("FULL",`^${c[u.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h("LOOSE",`^${c[u.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h("XRANGE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[u.COERCE],!0),h("COERCERTLFULL",c[u.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(qe,qe.exports)),qe.exports}var ut,Yr;function vr(){if(Yr)return ut;Yr=1;const s=Object.freeze({loose:!0}),e=Object.freeze({});return ut=r=>r?typeof r!="object"?s:r:e,ut}var dt,Qr;function wn(){if(Qr)return dt;Qr=1;const s=/^[0-9]+$/,e=(r,n)=>{const o=s.test(r),i=s.test(n);return o&&i&&(r=+r,n=+n),r===n?0:o&&!i?-1:i&&!o?1:r<n?-1:1};return dt={compareIdentifiers:e,rcompareIdentifiers:(r,n)=>e(n,r)},dt}var pt,Zr;function ee(){if(Zr)return pt;Zr=1;const s=tt(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=et(),{safeRe:r,t:n}=je(),o=vr(),{compareIdentifiers:i}=wn();class l{constructor(a,u){if(u=o(u),a instanceof l){if(a.loose===!!u.loose&&a.includePrerelease===!!u.includePrerelease)return a;a=a.version}else if(typeof a!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof a}".`);if(a.length>e)throw new TypeError(`version is longer than ${e} characters`);s("SemVer",a,u),this.options=u,this.loose=!!u.loose,this.includePrerelease=!!u.includePrerelease;const d=a.trim().match(u.loose?r[n.LOOSE]:r[n.FULL]);if(!d)throw new TypeError(`Invalid Version: ${a}`);if(this.raw=a,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(a){if(s("SemVer.compare",this.version,this.options,a),!(a instanceof l)){if(typeof a=="string"&&a===this.version)return 0;a=new l(a,this.options)}return a.version===this.version?0:this.compareMain(a)||this.comparePre(a)}compareMain(a){return a instanceof l||(a=new l(a,this.options)),i(this.major,a.major)||i(this.minor,a.minor)||i(this.patch,a.patch)}comparePre(a){if(a instanceof l||(a=new l(a,this.options)),this.prerelease.length&&!a.prerelease.length)return-1;if(!this.prerelease.length&&a.prerelease.length)return 1;if(!this.prerelease.length&&!a.prerelease.length)return 0;let u=0;do{const d=this.prerelease[u],p=a.prerelease[u];if(s("prerelease compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}compareBuild(a){a instanceof l||(a=new l(a,this.options));let u=0;do{const d=this.build[u],p=a.build[u];if(s("build compare",u,d,p),d===void 0&&p===void 0)return 0;if(p===void 0)return 1;if(d===void 0)return-1;if(d===p)continue;return i(d,p)}while(++u)}inc(a,u,d){if(a.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(a){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",u,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",u,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",u,d),this.inc("pre",u,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",u,d),this.inc("pre",u,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const p=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[p];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(u===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(p)}}if(u){let f=[u,p];d===!1&&(f=[u]),i(this.prerelease[0],u)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${a}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return pt=l,pt}var ft,es;function we(){if(es)return ft;es=1;const s=ee();return ft=(t,r,n=!1)=>{if(t instanceof s)return t;try{return new s(t,r)}catch(o){if(!n)return null;throw o}},ft}var gt,ts;function Xi(){if(ts)return gt;ts=1;const s=we();return gt=(t,r)=>{const n=s(t,r);return n?n.version:null},gt}var ht,rs;function Yi(){if(rs)return ht;rs=1;const s=we();return ht=(t,r)=>{const n=s(t.trim().replace(/^[=v]+/,""),r);return n?n.version:null},ht}var mt,ss;function Qi(){if(ss)return mt;ss=1;const s=ee();return mt=(t,r,n,o,i)=>{typeof n=="string"&&(i=o,o=n,n=void 0);try{return new s(t instanceof s?t.version:t,n).inc(r,o,i).version}catch{return null}},mt}var vt,ns;function Zi(){if(ns)return vt;ns=1;const s=we();return vt=(t,r)=>{const n=s(t,null,!0),o=s(r,null,!0),i=n.compare(o);if(i===0)return null;const l=i>0,c=l?n:o,a=l?o:n,u=!!c.prerelease.length;if(!!a.prerelease.length&&!u){if(!a.patch&&!a.minor)return"major";if(a.compareMain(c)===0)return a.minor&&!a.patch?"minor":"patch"}const p=u?"pre":"";return n.major!==o.major?p+"major":n.minor!==o.minor?p+"minor":n.patch!==o.patch?p+"patch":"prerelease"},vt}var yt,os;function ea(){if(os)return yt;os=1;const s=ee();return yt=(t,r)=>new s(t,r).major,yt}var wt,is;function ta(){if(is)return wt;is=1;const s=ee();return wt=(t,r)=>new s(t,r).minor,wt}var St,as;function ra(){if(as)return St;as=1;const s=ee();return St=(t,r)=>new s(t,r).patch,St}var bt,cs;function sa(){if(cs)return bt;cs=1;const s=we();return bt=(t,r)=>{const n=s(t,r);return n&&n.prerelease.length?n.prerelease:null},bt}var Rt,ls;function ce(){if(ls)return Rt;ls=1;const s=ee();return Rt=(t,r,n)=>new s(t,n).compare(new s(r,n)),Rt}var kt,us;function na(){if(us)return kt;us=1;const s=ce();return kt=(t,r,n)=>s(r,t,n),kt}var Ct,ds;function oa(){if(ds)return Ct;ds=1;const s=ce();return Ct=(t,r)=>s(t,r,!0),Ct}var Pt,ps;function yr(){if(ps)return Pt;ps=1;const s=ee();return Pt=(t,r,n)=>{const o=new s(t,n),i=new s(r,n);return o.compare(i)||o.compareBuild(i)},Pt}var Et,fs;function ia(){if(fs)return Et;fs=1;const s=yr();return Et=(t,r)=>t.sort((n,o)=>s(n,o,r)),Et}var Ot,gs;function aa(){if(gs)return Ot;gs=1;const s=yr();return Ot=(t,r)=>t.sort((n,o)=>s(o,n,r)),Ot}var Tt,hs;function rt(){if(hs)return Tt;hs=1;const s=ce();return Tt=(t,r,n)=>s(t,r,n)>0,Tt}var It,ms;function wr(){if(ms)return It;ms=1;const s=ce();return It=(t,r,n)=>s(t,r,n)<0,It}var Ft,vs;function Sn(){if(vs)return Ft;vs=1;const s=ce();return Ft=(t,r,n)=>s(t,r,n)===0,Ft}var $t,ys;function bn(){if(ys)return $t;ys=1;const s=ce();return $t=(t,r,n)=>s(t,r,n)!==0,$t}var Dt,ws;function Sr(){if(ws)return Dt;ws=1;const s=ce();return Dt=(t,r,n)=>s(t,r,n)>=0,Dt}var Lt,Ss;function br(){if(Ss)return Lt;Ss=1;const s=ce();return Lt=(t,r,n)=>s(t,r,n)<=0,Lt}var At,bs;function Rn(){if(bs)return At;bs=1;const s=Sn(),e=bn(),t=rt(),r=Sr(),n=wr(),o=br();return At=(l,c,a,u)=>{switch(c){case"===":return typeof l=="object"&&(l=l.version),typeof a=="object"&&(a=a.version),l===a;case"!==":return typeof l=="object"&&(l=l.version),typeof a=="object"&&(a=a.version),l!==a;case"":case"=":case"==":return s(l,a,u);case"!=":return e(l,a,u);case">":return t(l,a,u);case">=":return r(l,a,u);case"<":return n(l,a,u);case"<=":return o(l,a,u);default:throw new TypeError(`Invalid operator: ${c}`)}},At}var Nt,Rs;function ca(){if(Rs)return Nt;Rs=1;const s=ee(),e=we(),{safeRe:t,t:r}=je();return Nt=(o,i)=>{if(o instanceof s)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;i=i||{};let l=null;if(!i.rtl)l=o.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let y;for(;(y=f.exec(o))&&(!l||l.index+l[0].length!==o.length);)(!l||y.index+y[0].length!==l.index+l[0].length)&&(l=y),f.lastIndex=y.index+y[1].length+y[2].length;f.lastIndex=-1}if(l===null)return null;const c=l[2],a=l[3]||"0",u=l[4]||"0",d=i.includePrerelease&&l[5]?`-${l[5]}`:"",p=i.includePrerelease&&l[6]?`+${l[6]}`:"";return e(`${c}.${a}.${u}${d}${p}`,i)},Nt}var jt,ks;function la(){if(ks)return jt;ks=1;class s{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(t,r)}return this}}return jt=s,jt}var Bt,Cs;function le(){if(Cs)return Bt;Cs=1;const s=/\s+/g;class e{constructor(v,b){if(b=n(b),v instanceof e)return v.loose===!!b.loose&&v.includePrerelease===!!b.includePrerelease?v:new e(v.raw,b);if(v instanceof o)return this.raw=v.value,this.set=[[v]],this.formatted=void 0,this;if(this.options=b,this.loose=!!b.loose,this.includePrerelease=!!b.includePrerelease,this.raw=v.trim().replace(s," "),this.set=this.raw.split("||").map(w=>this.parseRange(w.trim())).filter(w=>w.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const w=this.set[0];if(this.set=this.set.filter(C=>!h(C[0])),this.set.length===0)this.set=[w];else if(this.set.length>1){for(const C of this.set)if(C.length===1&&R(C[0])){this.set=[C];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 b=this.set[v];for(let w=0;w<b.length;w++)w>0&&(this.formatted+=" "),this.formatted+=b[w].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(v){const w=((this.options.includePrerelease&&f)|(this.options.loose&&y))+":"+v,C=r.get(w);if(C)return C;const k=this.options.loose,O=k?c[a.HYPHENRANGELOOSE]:c[a.HYPHENRANGE];v=v.replace(O,G(this.options.includePrerelease)),i("hyphen replace",v),v=v.replace(c[a.COMPARATORTRIM],u),i("comparator trim",v),v=v.replace(c[a.TILDETRIM],d),i("tilde trim",v),v=v.replace(c[a.CARETTRIM],p),i("caret trim",v);let A=v.split(" ").map(U=>V(U,this.options)).join(" ").split(/\s+/).map(U=>Y(U,this.options));k&&(A=A.filter(U=>(i("loose invalid filter",U,this.options),!!U.match(c[a.COMPARATORLOOSE])))),i("range list",A);const F=new Map,x=A.map(U=>new o(U,this.options));for(const U of x){if(h(U))return[U];F.set(U.value,U)}F.size>1&&F.has("")&&F.delete("");const _=[...F.values()];return r.set(w,_),_}intersects(v,b){if(!(v instanceof e))throw new TypeError("a Range is required");return this.set.some(w=>T(w,b)&&v.set.some(C=>T(C,b)&&w.every(k=>C.every(O=>k.intersects(O,b)))))}test(v){if(!v)return!1;if(typeof v=="string")try{v=new l(v,this.options)}catch{return!1}for(let b=0;b<this.set.length;b++)if(X(this.set[b],v,this.options))return!0;return!1}}Bt=e;const t=la(),r=new t,n=vr(),o=st(),i=tt(),l=ee(),{safeRe:c,t:a,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:p}=je(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:y}=et(),h=m=>m.value==="<0.0.0-0",R=m=>m.value==="",T=(m,v)=>{let b=!0;const w=m.slice();let C=w.pop();for(;b&&w.length;)b=w.every(k=>C.intersects(k,v)),C=w.pop();return b},V=(m,v)=>(i("comp",m,v),m=I(m,v),i("caret",m),m=M(m,v),i("tildes",m),m=E(m,v),i("xrange",m),m=ue(m,v),i("stars",m),m),D=m=>!m||m.toLowerCase()==="x"||m==="*",M=(m,v)=>m.trim().split(/\s+/).map(b=>q(b,v)).join(" "),q=(m,v)=>{const b=v.loose?c[a.TILDELOOSE]:c[a.TILDE];return m.replace(b,(w,C,k,O,A)=>{i("tilde",m,w,C,k,O,A);let F;return D(C)?F="":D(k)?F=`>=${C}.0.0 <${+C+1}.0.0-0`:D(O)?F=`>=${C}.${k}.0 <${C}.${+k+1}.0-0`:A?(i("replaceTilde pr",A),F=`>=${C}.${k}.${O}-${A} <${C}.${+k+1}.0-0`):F=`>=${C}.${k}.${O} <${C}.${+k+1}.0-0`,i("tilde return",F),F})},I=(m,v)=>m.trim().split(/\s+/).map(b=>B(b,v)).join(" "),B=(m,v)=>{i("caret",m,v);const b=v.loose?c[a.CARETLOOSE]:c[a.CARET],w=v.includePrerelease?"-0":"";return m.replace(b,(C,k,O,A,F)=>{i("caret",m,C,k,O,A,F);let x;return D(k)?x="":D(O)?x=`>=${k}.0.0${w} <${+k+1}.0.0-0`:D(A)?k==="0"?x=`>=${k}.${O}.0${w} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.0${w} <${+k+1}.0.0-0`:F?(i("replaceCaret pr",F),k==="0"?O==="0"?x=`>=${k}.${O}.${A}-${F} <${k}.${O}.${+A+1}-0`:x=`>=${k}.${O}.${A}-${F} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.${A}-${F} <${+k+1}.0.0-0`):(i("no pr"),k==="0"?O==="0"?x=`>=${k}.${O}.${A}${w} <${k}.${O}.${+A+1}-0`:x=`>=${k}.${O}.${A}${w} <${k}.${+O+1}.0-0`:x=`>=${k}.${O}.${A} <${+k+1}.0.0-0`),i("caret return",x),x})},E=(m,v)=>(i("replaceXRanges",m,v),m.split(/\s+/).map(b=>H(b,v)).join(" ")),H=(m,v)=>{m=m.trim();const b=v.loose?c[a.XRANGELOOSE]:c[a.XRANGE];return m.replace(b,(w,C,k,O,A,F)=>{i("xRange",m,w,C,k,O,A,F);const x=D(k),_=x||D(O),U=_||D(A),de=U;return C==="="&&de&&(C=""),F=v.includePrerelease?"-0":"",x?C===">"||C==="<"?w="<0.0.0-0":w="*":C&&de?(_&&(O=0),A=0,C===">"?(C=">=",_?(k=+k+1,O=0,A=0):(O=+O+1,A=0)):C==="<="&&(C="<",_?k=+k+1:O=+O+1),C==="<"&&(F="-0"),w=`${C+k}.${O}.${A}${F}`):_?w=`>=${k}.0.0${F} <${+k+1}.0.0-0`:U&&(w=`>=${k}.${O}.0${F} <${k}.${+O+1}.0-0`),i("xRange return",w),w})},ue=(m,v)=>(i("replaceStars",m,v),m.trim().replace(c[a.STAR],"")),Y=(m,v)=>(i("replaceGTE0",m,v),m.trim().replace(c[v.includePrerelease?a.GTE0PRE:a.GTE0],"")),G=m=>(v,b,w,C,k,O,A,F,x,_,U,de)=>(D(w)?b="":D(C)?b=`>=${w}.0.0${m?"-0":""}`:D(k)?b=`>=${w}.${C}.0${m?"-0":""}`:O?b=`>=${b}`:b=`>=${b}${m?"-0":""}`,D(x)?F="":D(_)?F=`<${+x+1}.0.0-0`:D(U)?F=`<${x}.${+_+1}.0-0`:de?F=`<=${x}.${_}.${U}-${de}`:m?F=`<${x}.${_}.${+U+1}-0`:F=`<=${F}`,`${b} ${F}`.trim()),X=(m,v,b)=>{for(let w=0;w<m.length;w++)if(!m[w].test(v))return!1;if(v.prerelease.length&&!b.includePrerelease){for(let w=0;w<m.length;w++)if(i(m[w].semver),m[w].semver!==o.ANY&&m[w].semver.prerelease.length>0){const C=m[w].semver;if(C.major===v.major&&C.minor===v.minor&&C.patch===v.patch)return!0}return!1}return!0};return Bt}var Vt,Ps;function st(){if(Ps)return Vt;Ps=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[n.COMPARATORLOOSE]:r[n.COMPARATOR],p=u.match(d);if(!p)throw new TypeError(`Invalid comparator: ${u}`);this.operator=p[1]!==void 0?p[1]:"",this.operator==="="&&(this.operator=""),p[2]?this.semver=new l(p[2],this.options.loose):this.semver=s}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===s||u===s)return!0;if(typeof u=="string")try{u=new l(u,this.options)}catch{return!1}return o(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||o(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||o(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}Vt=e;const t=vr(),{safeRe:r,t:n}=je(),o=Rn(),i=tt(),l=ee(),c=le();return Vt}var xt,Es;function nt(){if(Es)return xt;Es=1;const s=le();return xt=(t,r,n)=>{try{r=new s(r,n)}catch{return!1}return r.test(t)},xt}var Ut,Os;function ua(){if(Os)return Ut;Os=1;const s=le();return Ut=(t,r)=>new s(t,r).set.map(n=>n.map(o=>o.value).join(" ").trim().split(" ")),Ut}var Mt,Ts;function da(){if(Ts)return Mt;Ts=1;const s=ee(),e=le();return Mt=(r,n,o)=>{let i=null,l=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(a=>{c.test(a)&&(!i||l.compare(a)===-1)&&(i=a,l=new s(i,o))}),i},Mt}var Jt,Is;function pa(){if(Is)return Jt;Is=1;const s=ee(),e=le();return Jt=(r,n,o)=>{let i=null,l=null,c=null;try{c=new e(n,o)}catch{return null}return r.forEach(a=>{c.test(a)&&(!i||l.compare(a)===1)&&(i=a,l=new s(i,o))}),i},Jt}var qt,Fs;function fa(){if(Fs)return qt;Fs=1;const s=ee(),e=le(),t=rt();return qt=(n,o)=>{n=new e(n,o);let i=new s("0.0.0");if(n.test(i)||(i=new s("0.0.0-0"),n.test(i)))return i;i=null;for(let l=0;l<n.set.length;++l){const c=n.set[l];let a=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">=":(!a||t(d,a))&&(a=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),a&&(!i||t(i,a))&&(i=a)}return i&&n.test(i)?i:null},qt}var Gt,$s;function ga(){if($s)return Gt;$s=1;const s=le();return Gt=(t,r)=>{try{return new s(t,r).range||"*"}catch{return null}},Gt}var _t,Ds;function Rr(){if(Ds)return _t;Ds=1;const s=ee(),e=st(),{ANY:t}=e,r=le(),n=nt(),o=rt(),i=wr(),l=br(),c=Sr();return _t=(u,d,p,f)=>{u=new s(u,f),d=new r(d,f);let y,h,R,T,V;switch(p){case">":y=o,h=l,R=i,T=">",V=">=";break;case"<":y=i,h=c,R=o,T="<",V="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(n(u,d,f))return!1;for(let D=0;D<d.set.length;++D){const M=d.set[D];let q=null,I=null;if(M.forEach(B=>{B.semver===t&&(B=new e(">=0.0.0")),q=q||B,I=I||B,y(B.semver,q.semver,f)?q=B:R(B.semver,I.semver,f)&&(I=B)}),q.operator===T||q.operator===V||(!I.operator||I.operator===T)&&h(u,I.semver))return!1;if(I.operator===V&&R(u,I.semver))return!1}return!0},_t}var Kt,Ls;function ha(){if(Ls)return Kt;Ls=1;const s=Rr();return Kt=(t,r,n)=>s(t,r,">",n),Kt}var Ht,As;function ma(){if(As)return Ht;As=1;const s=Rr();return Ht=(t,r,n)=>s(t,r,"<",n),Ht}var Wt,Ns;function va(){if(Ns)return Wt;Ns=1;const s=le();return Wt=(t,r,n)=>(t=new s(t,n),r=new s(r,n),t.intersects(r,n)),Wt}var zt,js;function ya(){if(js)return zt;js=1;const s=nt(),e=ce();return zt=(t,r,n)=>{const o=[];let i=null,l=null;const c=t.sort((p,f)=>e(p,f,n));for(const p of c)s(p,r,n)?(l=p,i||(i=p)):(l&&o.push([i,l]),l=null,i=null);i&&o.push([i,null]);const a=[];for(const[p,f]of o)p===f?a.push(p):!f&&p===c[0]?a.push("*"):f?p===c[0]?a.push(`<=${f}`):a.push(`${p} - ${f}`):a.push(`>=${p}`);const u=a.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return u.length<d.length?u:r},zt}var Xt,Bs;function wa(){if(Bs)return Xt;Bs=1;const s=le(),e=st(),{ANY:t}=e,r=nt(),n=ce(),o=(d,p,f={})=>{if(d===p)return!0;d=new s(d,f),p=new s(p,f);let y=!1;e:for(const h of d.set){for(const R of p.set){const T=c(h,R,f);if(y=y||T!==null,T)continue e}if(y)return!1}return!0},i=[new e(">=0.0.0-0")],l=[new e(">=0.0.0")],c=(d,p,f)=>{if(d===p)return!0;if(d.length===1&&d[0].semver===t){if(p.length===1&&p[0].semver===t)return!0;f.includePrerelease?d=i:d=l}if(p.length===1&&p[0].semver===t){if(f.includePrerelease)return!0;p=l}const y=new Set;let h,R;for(const E of d)E.operator===">"||E.operator===">="?h=a(h,E,f):E.operator==="<"||E.operator==="<="?R=u(R,E,f):y.add(E.semver);if(y.size>1)return null;let T;if(h&&R){if(T=n(h.semver,R.semver,f),T>0)return null;if(T===0&&(h.operator!==">="||R.operator!=="<="))return null}for(const E of y){if(h&&!r(E,String(h),f)||R&&!r(E,String(R),f))return null;for(const H of p)if(!r(E,String(H),f))return!1;return!0}let V,D,M,q,I=R&&!f.includePrerelease&&R.semver.prerelease.length?R.semver:!1,B=h&&!f.includePrerelease&&h.semver.prerelease.length?h.semver:!1;I&&I.prerelease.length===1&&R.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(const E of p){if(q=q||E.operator===">"||E.operator===">=",M=M||E.operator==="<"||E.operator==="<=",h){if(B&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===B.major&&E.semver.minor===B.minor&&E.semver.patch===B.patch&&(B=!1),E.operator===">"||E.operator===">="){if(V=a(h,E,f),V===E&&V!==h)return!1}else if(h.operator===">="&&!r(h.semver,String(E),f))return!1}if(R){if(I&&E.semver.prerelease&&E.semver.prerelease.length&&E.semver.major===I.major&&E.semver.minor===I.minor&&E.semver.patch===I.patch&&(I=!1),E.operator==="<"||E.operator==="<="){if(D=u(R,E,f),D===E&&D!==R)return!1}else if(R.operator==="<="&&!r(R.semver,String(E),f))return!1}if(!E.operator&&(R||h)&&T!==0)return!1}return!(h&&M&&!R&&T!==0||R&&q&&!h&&T!==0||B||I)},a=(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 Xt=o,Xt}var Yt,Vs;function Sa(){if(Vs)return Yt;Vs=1;const s=je(),e=et(),t=ee(),r=wn(),n=we(),o=Xi(),i=Yi(),l=Qi(),c=Zi(),a=ea(),u=ta(),d=ra(),p=sa(),f=ce(),y=na(),h=oa(),R=yr(),T=ia(),V=aa(),D=rt(),M=wr(),q=Sn(),I=bn(),B=Sr(),E=br(),H=Rn(),ue=ca(),Y=st(),G=le(),X=nt(),m=ua(),v=da(),b=pa(),w=fa(),C=ga(),k=Rr(),O=ha(),A=ma(),F=va(),x=ya(),_=wa();return Yt={parse:n,valid:o,clean:i,inc:l,diff:c,major:a,minor:u,patch:d,prerelease:p,compare:f,rcompare:y,compareLoose:h,compareBuild:R,sort:T,rsort:V,gt:D,lt:M,eq:q,neq:I,gte:B,lte:E,cmp:H,coerce:ue,Comparator:Y,Range:G,satisfies:X,toComparators:m,maxSatisfying:v,minSatisfying:b,minVersion:w,validRange:C,outside:k,gtr:O,ltr:A,intersects:F,simplifyRange:x,subset:_,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},Yt}var ba=Sa();const Ra=zi(ba),ka={minDelay:1500},Ca="__no_updates__";class Pa extends J.PollComputablePool{constructor(t,r,n={}){super({...n,...ka},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_${se(t)}`;default:return Ca}}async readValue(t){var r,n;try{const o=t.currentSpec;switch(o.type){case"dev-v1":try{const i=await cr(o.folder);return i===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await Z.tryLoadPackDescription(o.folder,this.logger);if(i===void 0)return{suggestions:[]};const l=await Xe(i);return l===o.mtime?{suggestions:[]}:{mainSuggestion:{...o,mtime:l},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:l}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(o.registryUrl);let a=this.preferredUpdateChannel;if(a===void 0)if(o.channel===void 0)if(await c.getLatestOverview(o.id,Q.StableChannel))a=Q.StableChannel;else{if(await c.getLatestOverview(o.id,Q.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${Q.blockPackIdToString(o.id)}`),{suggestions:[]};a=Q.AnyChannel}else a=o.channel;const u=await c.getUpdateSuggestions(o.id,a);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(r=u.find(y=>y.type!=="major"))==null?void 0:r.update;break;case"minor":d=(n=u.find(y=>y.type==="patch"))==null?void 0:n.update;break}const p=u.map(({type:y,update:h})=>({type:y,update:{...o,id:{...o.id,version:h}}}));if(d===void 0)return{suggestions:p};if(l!==void 0&&Ra.lte(d,l))return{suggestions:p};const f={...o,id:{...o.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(y){this.logger.warn(y)}})(),{suggestions:p,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(o){return this.logger.warn(o),{suggestions:[]}}}resultsEqual(t,r){return se(t)===se(r)}}class xs{constructor(){P(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(n=>n!=null&&typeof n[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let n=!1;return{resource:r.resource,key:t,unref:()=>{n||(r.refCount--,n=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function Oe(s){return String(s.id)}const Ea=["Int","Long","Float","Double","String","Bytes"];function Qt(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 Oa(s){return"partitionFilters"in s?s:{...s,partitionFilters:s.filters,filters:[]}}const Ce=(s,e)=>typeof e=="bigint"?e.toString():e;class Ta{constructor(e,t,r,n){P(this,"pFrame");P(this,"abortController",new AbortController);P(this,"blobIdToResource",new Map);P(this,"blobHandleComputables",new Map);P(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue(this.disposeSignal)});P(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue(this.disposeSignal)).handle);return await Ks.readFile(r)});this.blobDriver=e,this.logger=t,this.spillPath=r;const o=(l,c)=>this.logger[l](c);for(const l of n)for(const c of Ao(l.data))this.blobIdToResource.set(Oe(c),c);const i=[...new Map(n.map(l=>({...l,data:No(l.data,Oe)})).map(l=>[se(l),l])).values()];try{const l=new Gs.PFrame(this.spillPath,o);l.setDataSource(this);for(const c of i)l.addColumnSpec(c.id,c.spec),l.setColumnData(c.id,c.data);this.pFrame=l}catch(l){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${l}`)}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort();for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Ia{constructor(e,t){this.pTable=e,this.abortController=t}get disposeSignal(){return this.abortController.signal}[Symbol.dispose](){this.abortController.abort(),this.pTable.dispose()}}class kr{constructor(e,t,r){P(this,"pFrames");P(this,"pTables");P(this,"frameConcurrencyLimiter");P(this,"tableConcurrencyLimiter");this.blobDriver=e,this.logger=t,this.spillPath=r;const n=new S.ConcurrencyLimitingExecutor(1);this.frameConcurrencyLimiter=n,this.tableConcurrencyLimiter=new S.ConcurrencyLimitingExecutor(1),this.pFrames=new class extends xs{constructor(o,i,l){super(),this.blobDriver=o,this.logger=i,this.spillPath=l}createNewResource(o){return ae().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`),new Ta(this.blobDriver,this.logger,this.spillPath,o)}calculateParamsKey(o){return $a(o)}}(this.blobDriver,this.logger,this.spillPath),this.pTables=new class extends xs{constructor(o){super(),this.pFrames=o}createNewResource(o){const i=o.pFrameHandle;ae().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(o)}): ${JSON.stringify(o,Ce)}`);const l=this.pFrames.getByKey(i),c=new AbortController,a=l.pFrame.createTable({src:Te(o.def.src),filters:Qt([...o.def.partitionFilters,...o.def.filters])});let u=a;if(o.def.sorting.length>0)try{u=a.sort(o.def.sorting)}finally{a.dispose()}return new Ia(u,c)}calculateParamsKey(o){return Fa(o)}}(this.pFrames)}async pprofDump(){return await Gs.PFrame.pprofDump()}static async init(e,t,r){const n=Bn.resolve(r);return await S.emptyDir(n),new kr(e,t,n)}createPFrame(e,t){const r=e.filter(o=>Ea.find(i=>i===o.spec.valueType)).map(o=>j.mapPObjectData(o,i=>_e.isPlTreeNodeAccessor(i)?Mo(i):j.isDataInfo(i)?j.mapDataInfo(i,l=>l.resourceInfo):Jo(o.spec,i))),n=this.pFrames.acquire(r);return t.addOnDestroy(n.unref),n.key}createPTable(e,t){const r=Oa(e),n=this.createPFrame(j.extractAllColumns(r.src),t),o=j.mapPTableDef(r,l=>l.id),i=this.pTables.acquire({def:o,pFrameHandle:n});return ae().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${n}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(j.mapPTableDef(r,l=>l.spec),Ce)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(o=>[se(o),o])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).pFrame.findColumns(r)).hits.filter(o=>o.mappingVariants.length===0||o.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(l=>l.length===0))).map(o=>o.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).pFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).pFrame.listColumns()}async calculateTableData(e,t,r,n){return ae().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.frameConcurrencyLimiter.run(async()=>{const o=this.pFrames.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(a=>!!a)),l=o.pFrame.createTable({src:Te(t.src),filters:Qt(t.filters)});let c=l;if(t.sorting.length>0)try{c=l.sort(t.sorting)}finally{l.dispose()}try{const a=c.getSpec(),u=await c.getData([...a.keys()],{range:r,signal:i});return a.map((d,p)=>({spec:d,data:u[p]}))}finally{c.dispose()}})}async getUniqueValues(e,t,r){return ae().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),await this.frameConcurrencyLimiter.run(async()=>{const n=this.pFrames.getByKey(e),o=AbortSignal.any([r,n.disposeSignal].filter(i=>!!i));return await n.pFrame.getUniqueValues({...t,filters:Qt(t.filters)},{signal:o})})}getSpec(e){const t=this.pTables.getByKey(e).pTable;return Promise.resolve(t.getSpec())}async getShape(e,t){return await this.tableConcurrencyLimiter.run(async()=>{const r=this.pTables.getByKey(e),n=AbortSignal.any([t,r.disposeSignal].filter(o=>!!o));return await r.pTable.getShape({signal:n})})}async getData(e,t,r,n){return await this.tableConcurrencyLimiter.run(async()=>{const o=this.pTables.getByKey(e),i=AbortSignal.any([n,o.disposeSignal].filter(l=>!!l));return await o.pTable.getData(t,{range:r,signal:i})})}}function Te(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=>Te(e))};case"outer":return{type:"outer",primary:Te(s.primary),secondary:s.secondary.map(e=>Te(e))};default:S.assertNever(s)}}function Fa(s){const e=te.createHash("sha256");return e.update(se(s)),e.digest().toString("hex")}function $a(s){const e=[...s].map(r=>j.mapPObjectData(r,n=>{let o;const i=n.type;switch(i){case"Json":o={type:n.type,keyLength:n.keyLength,payload:Object.entries(n.data).map(([l,c])=>({key:l,value:c}))};break;case"JsonPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([l,c])=>({key:l,value:Oe(c)}))};break;case"BinaryPartitioned":o={type:n.type,keyLength:n.partitionKeyLength,payload:Object.entries(n.parts).map(([l,c])=>({key:l,value:[Oe(c.index),Oe(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return o.payload.sort((l,c)=>l.key.localeCompare(c.key)),o}));e.sort((r,n)=>r.id.localeCompare(n.id));const t=te.createHash("sha256");return t.update(se(e)),t.digest().toString("hex")}async function kn(s,e,t){const r={...hr,...mr(e),...t},n=new S.HmacSha256Signer(r.localSecret),o=W.createDownloadClient(r.logger,s,r.localProjections),i=W.createLogsClient(s,r.logger),l=W.createUploadBlobClient(s,r.logger),c=W.createUploadProgressClient(s,r.logger),a=await W.DownloadDriver.init(r.logger,o,i,r.blobDownloadPath,r.blobDownloadRangesCachePath,n,r.blobDriverOps),u=new W.DownloadBlobToURLDriver(r.logger,n,o,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new W.UploadDriver(r.logger,n,l,c,r.uploadDriverOps),p=new W.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new W.LogsDriver(r.logger,p,a),y=await W.LsDriver.init(r.logger,s,n,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),h=await kr.init(a,r.logger,r.pframesSpillPath);return{blobDriver:a,blobToURLDriver:u,logDriver:f,lsDriver:y,signer:n,uploadDriver:d,pFrameDriver:h}}class Da{constructor(e){P(this,"enrichmentTargetsCache",new Ms.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 Fi(this.quickJs,t.enrichmentTargets,t.code,r)}getEnrichmentTargets(e,t,r){const n={blockConfig:e,args:t};if(r===void 0)return this.calculateEnrichmentTargets(n);const o=`${r.argsRid}:${r.blockPackRid}`;return this.enrichmentTargetsCache.memo(o,{context:n}).value}}class Cr{constructor(e,t,r,n,o,i,l,c){P(this,"pl");P(this,"projectList");P(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=n,this.openedProjectsList=o,this.projectListTree=i,this.blockRegistryProvider=l,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=te.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async n=>{const o=await Lo(n,e);return n.createField(g.field(this.projectListResourceId,t),"Dynamic",o),await n.commit(),await g.toGlobalResourceId(o)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await 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(g.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(g.field(this.projectListResourceId,e))).value;if(g.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await Ze.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 S.HmacSha256Signer.generateSecret()}get blockEventDispatcher(){return this.env.blockEventDispatcher}static async init(e,t,r){const n={...vn,...yn(t),...r};n.defaultTreeOptions.logStat=ae().logTreeStats,n.debugOps.dumpInitialTreeState=ae().dumpInitialTreeState;const o=await e.withWriteTx("MLInitialization",async R=>{const T=g.field(R.clientRoot,so);R.createField(T,"Dynamic");const V=await R.getField(T);if(g.isNullResourceId(V.value)){const D=R.createEphemeral(zs);return R.lock(D),R.setField(T,D),await R.commit(),await D.globalId}else return V.value}),i=n.logger,l=await kn(e,t,n),c=new ze.RetryAgent(e.httpDispatcher),a=new Ws(c),u=new Eo(a,l.signer,c),d=new W.DownloadUrlDriver(i,e.httpDispatcher,n.frontendDownloadPath),p=await ge.getQuickJS(),f={pl:e,blockEventDispatcher:new S.BlockEventDispatcher,signer:l.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:n,bpPreparer:u,frontendDownloadDriver:d,driverKit:l,blockUpdateWatcher:new Pa(a,i,{minDelay:n.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:n.preferredUpdateChannel}),quickJs:p,projectHelper:new Da(p)},y=new J.WatchableValue([]),h=await oo(e,o,y,f);return new Cr(f,l,l.signer,o,y,h.tree,a,h.computable)}}async function La(s,e){return await Se(s.pingCheckDurationMs,s.maxPingsPerSecond,async()=>{const r=await new g.UnauthenticatedPlClient(e).ping();return JSON.stringify(r).slice(0,s.bodyLimit)+"..."})}async function Aa(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockRegistryUrl),s,e))}async function Na(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockOverviewPath,s.blockGARegistryUrl),s,e))}async function ja(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockRegistryUrl),s,e))}async function Ba(s,e){return await Se(s.blockRegistryDurationMs,s.maxRegistryChecksPerSecond,async()=>await Be(new URL(s.blockUiPath,s.blockGARegistryUrl),s,e))}async function Va(s,e){return await Se(s.autoUpdateCdnDurationMs,s.maxAutoUpdateCdnChecksPerSecond,async()=>await Be(s.autoUpdateCdnUrl,s,e))}async function Se(s,e,t){const r=Date.now(),n=[];for(;Us(r)<s;){const o=Date.now();let i;try{i={ok:!0,value:await t()}}catch(a){i={ok:!1,error:a}}const l=Us(o);n.push({elapsedMs:l,response:i});const c=1e3/e-l;c>0&&await qs.setTimeout(c)}return n}async function Be(s,e,t){const{body:r,statusCode:n}=await ze.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),o=await r.text();return{statusCode:n,beginningOfBody:o.slice(0,e.bodyLimit)+"..."}}function Us(s){return Date.now()-s}function ve(s){const e=s.filter(i=>i.response.ok),t=s.length-e.length,{mean:r,median:n}=xa(s),o=`
|
|
2
2
|
total: ${s.length};
|
|
3
3
|
successes: ${e.length};
|
|
4
4
|
errors: ${t};
|
|
5
5
|
mean in ms: ${r};
|
|
6
6
|
median in ms: ${n};
|
|
7
|
-
`;return{ok:t===0,details:o}}function
|
|
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
|
|
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
|
|
7
|
+
`;return{ok:t===0,details:o}}function xa(s){const e=s.map(n=>n.elapsedMs).sort(),t=e.reduce((n,o)=>n+o)/e.length;let r;if(e.length>0){const n=Math.floor(e.length/2);r=e.length%2?e[n]:(e[n-1]+e[n])/2}return{mean:t,median:r}}async function Ua(s,e,t){try{const r=await Ma(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 Ma(s,e,t){var n;const r=await be(e,he.Templates["check_network.upload_template"],!0,o=>({name:o.createValue(g.Pl.JsonObject,JSON.stringify(t))}),["greeting"]);try{return JSON.parse(S.notEmpty((n=(await fe(e,r.greeting)).data)==null?void 0:n.toString()))}finally{r!=null&&await Re(e,Object.values(r))}}async function Ja(s,e,t,r,n,o){try{const i=await qa(s,e,t,r,n,o);return i.type.name!=="Blob"?{status:"failed",message:`File uploading failed: ${i.type.name}`}:{status:"ok",message:`File uploading succeeded: ${i.type.name}`}}catch(i){return{status:"failed",message:`File uploading failed: error occurred: ${i}`}}}async function qa(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),l=await be(n,he.Templates["check_network.upload_blob"],!0,a=>({file:a.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const a=await fe(n,l.progress);if(W.isUpload(a)){const u=W.ImportFileHandleUploadData.parse(JSON.parse(S.notEmpty((c=a.data)==null?void 0:c.toString())));W.isSignMatch(e,u.localPath,u.pathSignature)&&await W.uploadBlob(s,r,a,u,()=>!1,{nPartsWithThisUploadSpeed:10,nPartsToIncreaseUpload:10,currentSpeed:10,maxSpeed:10})}return await fe(n,l.file)}finally{await Re(n,Object.values(l))}}async function Ga(s,e,t,r,n,o,i){try{const l=await _a(s,e,t,r,n,o);return l!==i?{status:"failed",message:`File downloading failed: expected: ${i}, got: ${l}`}:{status:"ok",message:`File downloading succeeded: ${l}`}}catch(l){return{status:"failed",message:`File downloading failed: error occurred: ${l}`}}}async function _a(s,e,t,r,n,o){var c;const i=await t.getLocalFileHandle(o),l=await be(e,he.Templates["check_network.download_blob"],!0,a=>({file:a.createValue(g.Pl.JsonObject,JSON.stringify(i))}),["progress","file"]);try{const a=await fe(e,l.progress);await W.uploadBlob(s,r,a,W.ImportFileHandleUploadData.parse(JSON.parse(S.notEmpty((c=a.data)==null?void 0:c.toString()))),()=>!1,{nPartsWithThisUploadSpeed:1,nPartsToIncreaseUpload:1,currentSpeed:1,maxSpeed:1});const u=await fe(e,l.file),{content:d}=await n.downloadBlob(u);return await jn.text(d)}finally{await Re(e,Object.values(l))}}async function Ka(s){try{const e=await Ha(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 Ha(s){var t;const e=await be(s,he.Templates["check_network.run_hello_world"],!0,r=>({}),["greeting"]);try{return S.notEmpty((t=(await fe(s,e.greeting)).data)==null?void 0:t.toString())}finally{await Re(s,Object.values(e))}}async function Wa(s,e){try{const t=await za(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 za(s,e){var r;const t=await be(s,he.Templates["check_network.run_hello_world_py"],!0,n=>({name:n.createValue(g.Pl.JsonObject,JSON.stringify(e))}),["greeting"]);try{return S.notEmpty((r=(await fe(s,t.greeting)).data)==null?void 0:r.toString())}finally{await Re(s,Object.values(t))}}async function Xa(s,e,t,r){var n,o;try{const i=await t.getStorageList(),l={};for(const c of i){const a=await Ya(t,c,r.nFilesToCheck,r.minFileSize,r.maxFileSize,r.minLsRequests);if(a.file===void 0){l[c.name]={status:"warn",message:`No file between ${r.minFileSize} and ${r.maxFileSize} bytes found in storage ${c.name}, checked ${a.nCheckedFiles} files, did ${a.nLsRequests} ls requests`};continue}s.info(`Downloading file ${JSON.stringify(a)} from storage ${c.name}`);const u=await be(e,he.Templates["check_network.create_workdir_from_storage"],!0,d=>({file:d.createValue(g.Pl.JsonObject,JSON.stringify(a.file.handle))}),["workdirTypeName"]);try{const d=JSON.parse(Buffer.from((await fe(e,u.workdirTypeName)).data).toString());d!=null&&d.startsWith("WorkingDirectory")?l[c.name]={status:"ok",message:`Workdir creation succeeded, size of file: ${(n=a.file)==null?void 0:n.size}, checked ${a.nCheckedFiles} files, did ${a.nLsRequests} ls requests`}:l[c.name]={status:"failed",message:`Workdir creation failed: ${d}, size of file: ${(o=a.file)==null?void 0:o.size}, checked ${a.nCheckedFiles} files, did ${a.nLsRequests} ls requests`}}finally{await Re(e,Object.values(u))}}return l}catch(i){return{unknown:{status:"failed",message:`Download from every storage failed: error occurred: ${i}`}}}}async function Ya(s,e,t,r,n,o){const i=Cn(s,e,"",0);let l,c=0,a=0;for await(const{file:u,nLsRequests:d}of i){if(a=Math.max(a,d),c>=t&&a>o)return{file:l,nLsRequests:a,nCheckedFiles:c};if(c++,r<=u.size&&u.size<=n)return{file:u,nLsRequests:a,nCheckedFiles:c};u.size<r&&(l=u)}return{file:l,nLsRequests:a,nCheckedFiles:c}}async function*Cn(s,e,t,r){r++;const n=await s.listRemoteFilesWithAdditionalInfo(e.handle,t);for(const o of n.entries)if(o.type==="file"&&o.fullPath.startsWith(t))yield{file:o,nLsRequests:r};else if(o.type==="dir")for await(const i of Cn(s,e,o.fullPath,r))r=Math.max(i.nLsRequests,r),yield i}async function Qa(){const s=K.join(_s.tmpdir(),`check-network-big-temp-${Date.now()}.bin`),e=20*1024*1024,t=te.randomBytes(e);return await Ie.appendFile(s,t),{filePath:s}}async function Za(){const s=K.join(_s.tmpdir(),`check-network-temp-${Date.now()}.txt`),e="Hello, world! "+new Date().toISOString();return await Ie.writeFile(s,e),{filePath:s,fileContent:e}}async function be(s,e,t,r,n){return await s.withWriteTx("TemplateRender",async o=>{const i=await ur(e),l=Ne(o,i),c=Ye(o,l,t,r(o),n),a={};for(const u of n){const d=g.field(s.clientRoot,u);o.createField(d,"Dynamic",c[u]),a[u]=await g.toGlobalFieldId(d)}return await o.commit(),a})}async function fe(s,e){return await g.poll(s,async t=>{const r=await t.tx.getField(e);if(g.isNotNullResourceId(r.error)){const n=await t.tx.getResourceData(r.error,!0);throw new Error(`getFieldValue of "${e.fieldName}" field failed: ${n.data}`)}if(g.isNullResourceId(r.value))throw new g.ContinuePolling;return await t.tx.getResourceData(r.value,!0)})}async function Re(s,e){await s.withWriteTx("DeleteFields",async t=>{for(const r of e)t.resetField(r);await t.commit()})}async function ec(s,e,t,r={}){const n=[];rc.forEach(o=>{Nn.channel(o).subscribe(l=>{var u,d;const c=new Date().toISOString(),a={...l};(u=a==null?void 0:a.response)!=null&&u.headers&&(a.response={...a.response},a.response.headers=a.response.headers.slice(),a.response.headers=a.response.headers.map(p=>p.toString())),(d=a==null?void 0:a.request)!=null&&d.body&&(a.request={...a.request},a.request.body="too big"),n.push(JSON.stringify({timestamp:c,event:o,data:a}))})});try{const{logger:o,plConfig:i,client:l,signer:c,downloadClient:a,uploadBlobClient:u,lsDriver:d,httpClient:p,ops:f}=await Pn(s,e,t,r),{filePath:y,fileContent:h}=await Za(),{filePath:R}=await Qa(),T={plPings:await La(f,i),blockRegistryOverviewChecks:await Aa(f,p),blockGARegistryOverviewChecks:await Na(f,p),blockRegistryUiChecks:await ja(f,p),blockGARegistryUiChecks:await Ba(f,p),autoUpdateCdnChecks:await Va(f,p),uploadTemplateCheck:await Ua(o,l,"Jack"),uploadFileCheck:await Ja(o,c,d,u,l,R),downloadFileCheck:await Ga(o,l,d,u,a,y,h),softwareCheck:await Ka(l),pythonSoftwareCheck:await Wa(l,"Jack"),storageToDownloadReport:await Xa(o,l,d,{minLsRequests:f.everyStorageMinLsRequests,bytesLimit:f.everyStorageBytesLimit,minFileSize:f.everyStorageMinFileSize,maxFileSize:f.everyStorageMaxFileSize,nFilesToCheck:f.everyStorageNFilesToCheck})};return tc(T,s,f,n)}catch(o){return`Unhandled error while checking the network: ${o}`}}async function Pn(s,e,t,r={}){const n={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,everyStorageBytesLimit:1024,everyStorageMinFileSize:1024,everyStorageMaxFileSize:209715200,everyStorageNFilesToCheck:300,everyStorageMinLsRequests:50,...r},o=g.plAddressToConfig(s,{defaultRequestTimeout:n.pingTimeoutMs});o.alternativeRoot=`check_network_${te.randomUUID()}`;const i=new g.UnauthenticatedPlClient(o);let l={};e&&t&&(l=await i.login(e,t));const c=await g.PlClient.init(s,{authInformation:l}),a=i.ll.httpDispatcher,u=new S.ConsoleLoggerAdapter,d=new S.HmacSha256Signer("localSecret"),p=W.createDownloadClient(u,c,[]),f=W.createUploadBlobClient(c,u),y=await W.LsDriver.init(u,c,d,[],()=>Promise.resolve([]),[]);return{logger:u,plConfig:o,client:c,signer:d,downloadClient:p,uploadBlobClient:f,lsDriver:y,httpClient:a,ops:n,terminate:async()=>{p.close(),f.close(),await a.close(),await c.close()}}}function tc(s,e,t,r){const n=s.plPings.filter(R=>R.response.ok),o=s.plPings.filter(R=>!R.response.ok),i=[...new Set(n.map(R=>JSON.stringify(R.response.value)))],l=R=>R?"OK":"FAILED",c=R=>R.status==="ok"?"OK":R.status==="warn"?"WARN":"FAILED",a=ve(s.plPings),u=ve(s.blockRegistryOverviewChecks),d=ve(s.blockGARegistryOverviewChecks),p=ve(s.blockRegistryUiChecks),f=ve(s.blockGARegistryUiChecks),y=ve(s.autoUpdateCdnChecks),h=Object.entries(s.storageToDownloadReport).map(([R,T])=>`${c(T)} ${R} storage check`).join(`
|
|
10
10
|
`);return`
|
|
11
11
|
${l(a.ok)} pings to Platforma Backend
|
|
12
12
|
${l(u.ok)} block registry overview
|
|
@@ -72,5 +72,5 @@ ${JSON.stringify(i,null,2)}
|
|
|
72
72
|
Undici logs:
|
|
73
73
|
${r.join(`
|
|
74
74
|
`)}
|
|
75
|
-
`}const
|
|
75
|
+
`}const rc=["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=_n;exports.CentralBlockRegistry=Kn;exports.DefaultDriverKitOpsPaths=mr;exports.DefaultDriverKitOpsSettings=hr;exports.DefaultMiddleLayerOpsPaths=yn;exports.DefaultMiddleLayerOpsSettings=vn;exports.FrontendFromFolderResourceType=pr;exports.FrontendFromUrlResourceType=dr;exports.MiddleLayer=Cr;exports.Project=Ze;exports.TengoTemplateGet=en;exports.TengoTemplateGetRegistry=tn;exports.TengoTemplateGetTemplate=sn;exports.TengoTemplateGetTemplateURI=rn;exports.TengoTemplatePack=vo;exports.TengoTemplatePackConvert=yo;exports.TengoTemplatePackConvertTemplate=So;exports.TengoTemplatePackConvertTemplatePack=wo;exports.V1CentralDevSnapshotRegistry=Wn;exports.V1CentralRegistry=Hn;exports.V2RegistryProvider=Ws;exports.checkNetwork=ec;exports.createRenderTemplate=Ye;exports.getDevV1PacketMtime=cr;exports.getDevV2PacketMtime=Xe;exports.initDriverKit=kn;exports.initNetworkCheck=Pn;exports.loadTemplate=Ne;exports.prepareTemplateSpec=ur;Object.keys(j).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>j[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(Ir).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Ir[s]})});Object.keys(g).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>g[s]})});
|
|
76
76
|
//# sourceMappingURL=index.js.map
|