@milaboratories/pl-middle-layer 1.26.5 → 1.26.6
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/debug/index.d.ts +1 -0
- package/dist/debug/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +712 -696
- package/dist/index.mjs.map +1 -1
- package/dist/pool/driver.d.ts.map +1 -1
- package/package.json +11 -10
- package/src/debug/index.ts +5 -3
- package/src/pool/driver.ts +28 -11
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var us=Object.defineProperty;var Ut=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Jt=s=>{throw TypeError(s)};var ds=(s,e,t)=>e in s?us(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var w=(s,e,t)=>ds(s,typeof e!="symbol"?e+"":e,t);var Te=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Jt("Object expected");var r;t&&(r=e[Ut("asyncDispose")]),r===void 0&&(r=e[Ut("dispose")]),typeof r!="function"&&Jt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Ie=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("@platforma-sdk/model"),U=require("@milaboratories/pl-model-middle-layer"),ie=require("undici"),_=require("@platforma-sdk/block-tools"),Q=require("node:fs"),K=require("node:path"),ps=require("yaml"),k=require("@milaboratories/ts-helpers"),hs=require("node:fs/promises"),fs=require("@milaboratories/resolve-helper"),m=require("@milaboratories/pl-client"),_e=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ne=require("node:crypto"),N=require("@milaboratories/pl-model-backend"),Or=require("denque"),gs=require("@platforma-sdk/workflow-tengo"),ae=require("canonicalize"),ms=require("node:assert"),Ue=require("quickjs-emscripten"),$r=require("node:timers/promises"),Z=require("@milaboratories/pl-drivers"),Gt=require("@milaboratories/pframes-node"),vs=require("lru-cache"),ys=require("node:diagnostics_channel");function Ss(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 Tr=Ss(hs);async function Mt(s){try{return await Tr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const bs=[_.RegistryV1.PlPackageYamlConfigFile],ws=[_.RegistryV1.PlPackageJsonConfigFile],bt=["backend","dist","tengo","tpl","main.plj.gz"],wt=["config","dist","config.json"],Ir=["frontend","dist"],_t="block-model/dist/config.json",Ps="block-ui/package.json",Cs=[bt,wt,bs,ws,Ir];async function Rs(s){return await Mt(K.join(s,...wt))!==void 0||await Mt(K.join(s,...bt))!==void 0}function rt(s,e){const t=fs.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Kt(s,e){if(K.isAbsolute(s)||(s=K.resolve(s)),await Rs(s))return{workflow:K.join(s,...bt),config:K.join(s,...wt),ui:K.join(s,...Ir)};{const t=rt(s,_t),r=rt(s,_t),o=rt(s,Ps);return{workflow:t,config:r,ui:K.resolve(o,"..","dist")}}}async function Es(s){try{return await Q.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function ks(s){try{return await Q.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Pt(s){let e=0n;for(const t of Cs){const r=K.join(s,...t),o=await ks(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function Ke(s){const e=await Q.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Q.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Os{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ie.request(`${r.url}/${_.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,f={organization:a,name:l,version:d},h={id:f,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:f,registryUrl:r.url}};t.push({registryId:e.id,id:f,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:c.allVersions.map(g=>({version:g,channels:[]}))})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(c=>c.latestByChannel[U.StableChannel]?{...c,registryId:e.id}:{...c,latestByChannel:{...c.latestByChannel,[U.StableChannel]:(a=>a.spec.type==="from-registry-v2"?{...a,spec:{...a.spec,channel:U.StableChannel}}:a)(c.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const c of await Q.promises.readdir(r.path,{withFileTypes:!0})){if(!c.isDirectory())continue;const a=K.join(r.path,c.name),l=await Es(K.join(a,_.RegistryV1.PlPackageYamlConfigFile));if(l!==void 0){const u=_.RegistryV1.PlPackageConfigData.parse(ps.parse(l)),d=await Pt(a),f={organization:u.organization,name:u.package,version:"DEV"},h={id:f,meta:{title:u.meta.title??"No title",description:u.meta.description??"No Description",organization:{name:u.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:a,mtime:d}};t.push({registryId:e.id,id:f,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}else{let u=a,d=await _.tryLoadPackDescription(u);if(d===void 0){for(const f of["block","meta"])if(u=K.join(a,f),d=await _.tryLoadPackDescription(u),d!==void 0)break}if(d!==void 0){const f=await Ke(d),h={id:d.id,meta:await _.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:u,mtime:f}};t.push({registryId:e.id,id:d.id,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}}}return t;default:return k.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class Fr{constructor(e){w(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new _.RegistryV2Reader(_.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const $s={type:"remote-v2",url:"https://blocks.pl-open.science/"},Ts={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Is={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Fs={groups:[{id:"default",label:"Default",blocks:[]}]},As={stagingRefreshTimestamp:0,blocksInLimbo:[]},Ls={label:"New Project"},Ds={name:"UserProject",version:"2"},Ar="SchemaVersion",Lr="1",Ct="ProjectCreated",ke="ProjectLastModified",Oe="ProjectMeta",de="ProjectStructure",Je="BlockRenderingState",Ns="BlockFrontendState/",Bs=/^BlockFrontendState\/(?<blockid>.*)$/;function dt(s){return`${Ns}${s}`}const js="BlockArgsAuthor/";function pt(s){return`${js}${s}`}const ht="ProjectStructureAuthor";function xs(s){const e=s.match(Bs);if(e!==null)return e.groups.blockid}const Vs="__serviceTemplate_";function ft(s){return`${Vs}${s}`}function G(s,e){return`${s}-${e}`}const Us=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Js(s){const e=s.match(Us);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Gs="projects",Dr={name:"Projects",version:"1"},Ms=s=>m.resourceTypesEqual(s.type,Dr)?s.fields:[];async function _s(s,e,t,r){const o=await _e.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Ms},r.logger);return{computable:j.Computable.make(i=>{const c=i.accessor(o.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const f=k.notEmpty(d.getKeyValueAsJson(Oe)),h=k.notEmpty(d.getKeyValueAsJson(Ct)),g=k.notEmpty(d.getKeyValueAsJson(ke));l.push({id:u,rid:d.id,created:new Date(h),lastModified:new Date(g),opened:a.indexOf(d.id)>=0,meta:f})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const Ks={name:"EphRenderTemplate",version:"1"},Hs={name:"RenderTemplate",version:"1"};function Rt(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Ks):s.createStruct(Hs),i=m.field(n,"template"),c=m.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",m.Pl.createPlMap(s,r,t)),s.lockInputs(n),m.Pl.futureRecord(s,n,o,"Output","outputs/")}const qs={name:"BContextEnd",version:"1"},Ws={name:"BContext",version:"1"},zs="id",Xs="parent/",Ys=["context","result"];function Ht(s,e,t){return Rt(s,e,!0,t,Ys)}function Qs(s){const e=s.createEphemeral(qs);return s.lock(e),e}function Zs(s,e){if(e.length===0)return Qs(s);if(e.length===1)return e[0];const t=s.createEphemeral(Ws);s.createField(m.field(t,zs),"Input",m.Pl.createPlString(s,ne.randomUUID()));for(let r=0;r<e.length;r++)s.createField(m.field(t,`${Xs}${r}`),"Input",e[r]);return s.lock(t),t}function eo(s,e){const t=N.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return ro(s,t);default:k.assertNever(r)}}const qt={hash(s,e){e.update(N.PlTemplateLibV1.type.name).update(N.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(N.PlTemplateLibV1.type,JSON.stringify(N.PlTemplateLibV1.fromV2Data(s).data))}},Fe={hash(s,e){e.update(N.PlTemplateSoftwareV1.type.name).update(N.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=N.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(N.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,N.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},to={hash(s,e){e.update(N.PlTemplateOverrideV1.type.name).update(N.PlTemplateOverrideV1.type.version).update(s.hashOverride??"")},render(s,e,t){return e.createStruct(N.PlTemplateOverrideV1.type,JSON.stringify(N.PlTemplateOverrideV1.fromV2Data(s)))}},Nr={hash(s,e){e.update(N.PlTemplateV1.type.name).update(N.PlTemplateV1.type.version).update(s.hashOverride??"").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),qt.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Fe.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Fe.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(N.PlTemplateV1.type,JSON.stringify(N.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=N.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,qt))}for(const[i,c]of Object.entries(s.software??{})){const a=N.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Fe))}for(const[i,c]of Object.entries(s.assets??{})){const a=N.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Fe))}for(const[i,c]of Object.entries(s.templates??{})){const a=N.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Nr))}if(e.lock(r),!s.hashOverride)return r;const o=t(s,to),n=N.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(r),o}};function ro(s,e){const t=new Map,r=(o,n)=>{const i=ne.createHash("sha256");n.hash(o,i);const c=i.digest("hex");if(!t.has(c)){const a=n.render(o,s,r);t.set(c,a)}return t.get(c)};return r(e,Nr)}const Br={name:"TengoTemplateGet",version:"1"},jr="registry",xr="templateURI",Vr="template",so={name:"TengoTemplatePack",version:"1"},oo={name:"TengoTemplatePackConvert",version:"1"},no="templatePack",io="template";async function Ur(s){switch(s.type){case"from-file":return{type:"explicit",content:await Q.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return k.assertNever(s)}}function ao(s,e){const t=s.createStruct(Br),r=m.field(t,jr),o=m.field(t,xr),n=m.field(t,Vr);return s.setField(r,s.createValue(m.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(m.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function He(s,e){switch(e.type){case"from-registry":return ao(s,e);case"explicit":return eo(s,e);default:return k.assertNever(e)}}const Et={name:"Frontend/FromUrl",version:"1"},kt={name:"Frontend/FromFolder",version:"1"};function co(s,e){switch(e.type){case"url":return s.createValue(Et,JSON.stringify({url:e.url}));case"local":return s.createValue(kt,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}const lo={name:"BlockPackCustom",version:"1"},Jr="template",Gr="frontend";function Wt(s){return s.endsWith("/")?s:`${s}/`}class uo{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Kt(e.folder),r=await Q.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await _.loadPackDescription(e.folder),r=await Q.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${Wt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await ie.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await ie.request(o.model.url,t)).body.json()}default:return k.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Kt(e.folder),r=await Q.promises.readFile(t.workflow),o=JSON.parse(await Q.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await _.loadPackDescription(e.folder),r=JSON.parse(await Q.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Q.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await Ke(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${Wt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await ie.request(o,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${o} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),a=await(await ie.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await ie.request(o.model.url,t)).body.json(),i=async()=>await(await ie.request(o.workflow.main.url,t)).body.arrayBuffer(),[c,a]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:c,frontend:{type:"url",url:o.ui.url},source:e}}default:return k.assertNever(e)}}}function po(s,e){const t={config:e.config,source:e.source},r=s.createStruct(lo,JSON.stringify(t));return s.createField(m.field(r,Jr),"Input",He(s,e.template)),s.createField(m.field(r,Gr),"Input",co(s,e.frontend)),s.lock(r),r}function zt(s,e){switch(e.type){case"explicit":return po(s,e);default:return k.assertNever(e.type)}}function Ae(s,e){return{__isRef:!0,blockId:s,name:e}}function ho(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function gt(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(ho(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)gt(s,o,t);else for(const[,o]of Object.entries(e))gt(s,o,t);return;default:k.assertNever(r)}}function fo(s,e){const t={upstreams:new Set,missingReferences:!1};return gt(t,s,e),t}function oe(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Mr{constructor(e){w(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){let i=[];for(const c of o){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{n.has(l)||(n.add(l),i.push(l))})}o=i}}}function mt(s){const e=new Map;let t;for(const{id:r}of oe(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Mr(e)}function Ve(s,e){const t=new Map,r=new Set;for(const{id:o}of oe(s)){const n=e(o);if(n===void 0)continue;const i=fo(n,r),c={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,c),i.upstreams.forEach(a=>t.get(a).downstream.add(o)),r.add(o)}return new Mr(t)}function go(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function vt(s,e){if(s.size>e.size)return vt(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Xt(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!go(n.upstream,i.upstream)||vt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?vt(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let st;async function _r(){if(st===void 0){const s=await Ur(gs.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ne.createHash("sha256").update(s.content).digest("hex");st={spec:s,hash:e}}return st}function mo(s,e,t){return Rt(s,e,!0,{pf:t},["result"]).result}function ot(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class Yt{constructor(e,t){w(this,"currentInputsC",ot(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));w(this,"actualProductionInputsC",ot(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return JSON.parse(Buffer.from(e).toString())}));w(this,"productionStaleC",ot(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(m.Pl.unwrapHolder(e,this.fields.blockPack.ref),Jr,"Input")}}const vo=s=>{throw new Error(`No new block info for ${s}`)};class Ge{constructor(e,t,r,o,n,i,c,a,l,u,d,f){w(this,"globalModCount",0);w(this,"fieldsChanged",!1);w(this,"lastModifiedChanged",!1);w(this,"structureChanged",!1);w(this,"metaChanged",!1);w(this,"renderingStateChanged",!1);w(this,"changedBlockFrontendStates",new Set);w(this,"blocksWithChangedInputs",new Set);w(this,"stagingGraph");w(this,"pendingProductionGraph");w(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(U.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=mt(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ve(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ve(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(m.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of oe(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=m.field(this.rid,G(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(m.field(this.rid,G(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(m.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(m.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Zs(this.tx,r)}exportCtx(e){return mo(this.tx,m.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Ht(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(m.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(m.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",m.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Ht(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(m.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(m.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",m.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=vo){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=mt(e),i=Ve(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),c=Xt(r,n),a=Xt(o,i);for(const l of c.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of c.onlyInB){const u=new Yt(l,{});this.blockInfos.set(l,u);const d=t(l),f=zt(this.tx,d.blockPack);this.setBlockField(l,"blockPack",m.Pl.wrapInHolder(this.tx,f),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(U.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(l,d.uiState),this.changedBlockFrontendStates.add(l)),u.check()}for(const l of c.different)this.resetStaging(l);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(c.onlyInB.size>0||c.onlyInA.size>0||c.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",m.Pl.wrapInHolder(this.tx,zt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const c=o.nodes.get(i);if(c===void 0)throw new Error(`Can't find block with id: ${i}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of oe(this.structure)){if(!r.has(i.id))continue;let c=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!c){for(const a of o.nodes.get(i.id).upstream)if(n.has(a)){c=!0;break}}c&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new Or(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,pt(t)):this.tx.setKValue(this.rid,pt(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,ht):this.tx.setKValue(this.rid,ht,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,ke,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Je,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Oe,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,dt(e)):this.tx.setKValue(this.rid,dt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Ar),i=e.getKValueJson(t,ke),c=e.getKValueJson(t,Oe),a=e.getKValueJson(t,de),l=e.getKValueJson(t,Je),u=e.listKeyValuesString(t),[d,f,h,g,R,{stagingRefreshTimestamp:A,blocksInLimbo:x},q]=await Promise.all([o,n,i,c,a,l,u]);if(f!==Lr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${f}`);const $=new Map;for(const p of d.fields){const S=Js(p.name);if(S===void 0)continue;let v=$.get(S.blockId);v===void 0&&(v={id:S.blockId,fields:{}},$.set(S.blockId,v)),v.fields[S.fieldName]=m.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const ce=await _r(),pe=ft(ce.hash),D=d.fields.find(p=>p.name===pe);let X;D!==void 0?X=m.ensureResourceIdNotNull(D.value):(X=m.Pl.wrapInHolder(e,He(e,ce.spec)),e.createField(m.field(t,ft(ce.hash)),"Dynamic",X));const le={stagingRefreshTimestamp:A},W=new Set(x),M=new Map;for(const p of q){const S=xs(p.key);S!==void 0&&M.set(S,p.value)}const J=[];$.forEach(({id:p,fields:S})=>{for(const[,v]of Object.entries(S))if(v.ref!==void 0){if(!m.isResource(v.ref)||m.isResourceRef(v.ref))throw new Error("unexpected behaviour");J.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,S]of J){const v=await S;p.value=v.data,m.isNotNullResourceId(v.error)?p.status="Error":v.resourceReady||m.isNotNullResourceId(v.originalResourceId)?p.status="Ready":p.status="NotReady"}const Y=new Map;$.forEach(({id:p,fields:S})=>Y.set(p,new Yt(p,S)));const he=new Set;for(const p of oe(R)){if(!Y.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);he.add(p.id)}Y.forEach(p=>{if(!he.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new Ge(t,e,r,f,h,g,R,le,W,Y,M,X);return y.fixProblemsAndMigrate(),y}}async function yo(s,e=Ls){const t=s.createEphemeral(Ds);s.lock(t);const r=String(Date.now());s.setKValue(t,Ar,JSON.stringify(Lr)),s.setKValue(t,Ct,r),s.setKValue(t,ke,r),s.setKValue(t,Oe,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(Fs)),s.setKValue(t,Je,JSON.stringify(As));const o=await _r();return s.createField(m.field(t,ft(o.hash)),"Dynamic",m.Pl.wrapInHolder(s,He(s,o.spec))),t}async function Le(s,e,t){return ee(s,e,void 0,t)}async function ee(s,e,t,r){if(s instanceof m.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await Ge.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await Ge.load(s,e,t),n=await r(o);return o.save(),n}}function*So(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:k.assertNever(s)}}function Qt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function bo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Qt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Qt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(s)}}const wo=m.resourceType("PColumnData/JsonPartitioned","1"),Po=m.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Co=m.resourceType("PColumnData/BinaryPartitioned","1"),Ro=m.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Eo=m.resourceType("PColumnData/Json","1");function ko(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(m.resourceTypesEqual(s.resourceType,Eo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(m.resourceTypesEqual(s.resourceType,wo)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Po)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);r[a]=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Co)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Ro)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${m.resourceTypeToString(s.resourceType)}`)}function Oo(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function $o(s,e){const t=ne.createHash("sha256");return t.update(ae(s)),t.update(String(m.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Zt(s,e){return ae({__isRef:!0,blockId:s,name:e})}function To(s,e){return ae({resolvePath:s,name:e})}function Kr(s,e=!0,t=!1,r=""){var c,a,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let f=k.notEmpty((c=d.groups)==null?void 0:c.name);if(!f.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}f=f.slice(r.length);const h=k.notEmpty((a=d.groups)==null?void 0:a.type);let g=n.get(f);switch(g===void 0&&(g={},n.set(f,g)),h){case"spec":g.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":g.hasData=!0,g.data=()=>s.traverseOrError({field:u,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Io(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Kr(s,e,!1,t);ms(o.locked);const n={};for(const[i,c]of o.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw new _e.PlError(a.error);n[i]={id:r.length===0?$o(c.spec,a.value):To(r,i),spec:c.spec,data:a.value}}return n}class Ot{constructor(e,t){w(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(o!==void 0||(o=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return B.mapValueInVOE(n,l=>({id:Zt(e,t),spec:o.spec,data:l}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:Ae(i,c),obj:{id:l.ok?Zt(i,c):void 0,spec:a.spec,data:l}}):o(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||o(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),n(i,l,u)}if(c.staging!==void 0){c.staging.locked||o(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||n(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Ae(n,a),obj:l.spec}),c.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:Ae(n,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[c,a]of i.results)o.has(c)||a.spec===void 0||(o.add(c),B.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:Ae(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=k.notEmpty(o.getKeyValueAsJson(de)),c=mt(n).traverseIds("upstream",r),a=new Map;for(const l of oe(n)){if(!c.has(l.id))continue;const u=er(o.traverse({field:G(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:G(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=er(o.traverse({field:G(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:G(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new Ot(e,a)}}function er(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Kr(e.value,!1,!0)}function $t(s,e){return{blockId:e,args:n=>k.notEmpty(n.accessor(s).node().traverse({field:G(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:G(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(dt(e)),blockMeta:n=>{const i=n.accessor(s).node(),c=k.notEmpty(i.getKeyValueAsJson(de)),a=new Map;for(const l of oe(c))a.set(l.id,l);return a}}}function Hr(s,e){return{...$t(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:G(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:G(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>Ot.create(t,s,e)}}function*z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*z(t);return;case"MakeArray":for(const t of s.template)yield*z(t);return;case"GetJsonField":case"GetResourceField":yield*z(s.source),yield*z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*z(s.source),yield*z(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*z(s.source);return;case"IsEmpty":yield*z(s.arg);return;case"Not":yield*z(s.operand);return;case"And":case"Or":yield*z(s.operand1),yield*z(s.operand2);return;default:k.assertNever(s)}}function Fo(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Ce(s,e){return s===void 0?void 0:e(s)}function Ao(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function Lo(s){for(const e of z(s))if(Ao(e))return!0;return!1}function qe(s){return{type:"ReturnResult",result:s}}function O(s){return()=>qe(s)}const Do=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return O(e)},No=s=>{const e=s.source;if(e===void 0)return O(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return O(t)},Bo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?O(void 0):({cCtx:r})=>{var o;return qe((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function qr(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function jo(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):()=>({type:"ScheduleSubroutine",subroutine:Wr(r.length),args:qr(r,o=>I({...s,[e.itVar]:o},e.mapping))})}}function Wr(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return O(t)}}function xo(s,e){return t=>{const r=t.source;if(r===void 0)return O(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=I(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Vo,args:o})}}const Vo=s=>O(s),Uo=s=>{const e=s.arg;return O(e===void 0?void 0:e.length===0)},Jo=s=>{const e=s.operand;return O(e===void 0?void 0:!e)},Go=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e&&t)},Mo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e||t)},_o=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t})=>{var r;return qe((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Ko=s=>{const e=s.source,t=s.field;return O(e===void 0||t===void 0?void 0:e[t])};function Ho(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const c of n.listInputFields()){const a=n.traverse(c);if(a===void 0)i[c]=O(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=I(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:qo,args:i}}}}const qo=s=>O(s),Wo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},zo=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Xo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},Yo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Qo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Zo=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},en=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},tn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},rn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},sn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function I(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>qe(t(r.cCtx)):O(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Yr(r,s,e.cfg)});case"Immediate":return O(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{source:I(s,e.source),field:I(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:jo(s,e),args:{source:I(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:xo(s,e),args:{source:I(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Do,args:Fo(e.template,r=>I(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Wr(e.template.length),args:qr(e.template,r=>I(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:No,args:{source:I(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Uo,args:{arg:I(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:{operand:I(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:Go,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{operand1:I(s,e.operand1),operand2:I(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:Ho(s,e),args:{source:I(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:{source:I(s,e.source),field:I(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{source:I(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{source:I(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:{source:I(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:I(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:I(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:I(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:Zo(e.format),args:{source:I(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:en,args:{source:I(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:tn(e.lines),args:{source:I(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:rn(e.patternToSearch),args:{source:I(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{source:I(s,e.source)}});default:return k.assertNever(e)}}const on=["$prod","$staging"];function nn(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 zr=Symbol(),Xr="return",an={op:zr,arg:Xr};function cn(s){return s.op==zr&&s.arg==Xr}function ln(){return{pendingSubroutines:new Map}}function tr(s,e,t,r){const o=new Or(t),n=(c,a)=>{if(cn(c))return e.result=a,!1;const l=k.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;o.length>0;){const c=o.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!n(c.destination,a.result))break e;break;case"ScheduleSubroutine":const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:c.destination,operation:a.subroutine({})});else{for(const[f,h]of u)o.push({destination:{op:l,arg:f},operation:h});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:k.assertNever(a)}}return i}function un(s,e,t,r={}){return Yr(s,nn(e),t,r)}function Yr(s,e,t,r={}){const o=`${e.blockId}#`+ae({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>on.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=ln();return{ir:tr(i,c,[{destination:an,operation:I(e,t)}],!0),async postprocessValue(l){const u=[];for(const g of l)u.push({destination:g.destination,operation:O(g.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},f=new Map;for(const[g,R]of c.pendingSubroutines)f.set(g,{...R,args:{...R.args}});const h={result:c.result,pendingSubroutines:f};if(tr(d,h,u,!1),!("result"in h))throw new Error("illegal cfg rendering stack state, no result");return h.result}}},{...r,key:o})}function dn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function rr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class Me{constructor(e,t,r,o,n){w(this,"callbackRegistry");w(this,"fnJSONStringify");w(this,"fnJSONParse");w(this,"computablesToResolve",{});w(this,"computableCtx");w(this,"accessors",new Map);w(this,"meta");w(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw Me.cleanErrorContext(t),t}}runCallback(e,...t){try{return Ue.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw Me.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return rr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return rr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Io(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=B.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ne.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=k.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:B.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:B.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 B.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=>B.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):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(B.mapPTableDef(e,t=>B.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):r)),this.computableCtx)}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=ne.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(dn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Ue.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(B.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(c,a)=>{this.vm.newFunction(c,a).consume(l=>this.vm.setProp(t,c,l))};i("getAccessorHandleByName",c=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(c)),void 0)),i("resolveWithCommon",(c,a,...l)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(c),this.importObjectViaJson(a),...l.map(u=>this.importObjectViaJson(u))),void 0)),i("getResourceType",c=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(c)),void 0)),i("getInputsLocked",c=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(c)),void 0)),i("getOutputsLocked",c=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(c)),void 0)),i("getIsReadyOrError",c=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(c)),void 0)),i("getIsFinal",c=>this.exportSingleValue(this.getIsFinal(this.vm.getString(c)),void 0)),i("getError",c=>this.exportSingleValue(this.getError(this.vm.getString(c)),void 0)),i("listInputFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("listOutputFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("listDynamicFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("getKeyValueBase64",(c,a)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getKeyValueAsString",(c,a)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getDataBase64",c=>this.exportSingleValue(this.getDataBase64(this.vm.getString(c)),void 0)),i("getDataAsString",c=>this.exportSingleValue(this.getDataAsString(this.vm.getString(c)),void 0)),i("parsePObjectCollection",(c,a,l,...u)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(c),this.vm.dump(a),this.vm.getString(l),...u.map(this.vm.getString)),void 0)),i("getBlobContentAsBase64",c=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(c)),void 0)),i("getBlobContentAsString",c=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(c)),void 0)),i("getDownloadedBlobContentHandle",c=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(c)),void 0)),i("getOnDemandBlobContentHandle",c=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(c)),void 0)),i("extractArchiveAndGetURL",(c,a)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getImportProgress",c=>this.exportSingleValue(this.getImportProgress(this.vm.getString(c)),void 0)),i("getLastLogs",(c,a)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(c),this.vm.getNumber(a)),void 0)),i("getProgressLog",(c,a)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getLogHandle",c=>this.exportSingleValue(this.getLogHandle(this.vm.getString(c)),void 0)),i("getBlockLabel",c=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(c)),void 0)),i("getDataFromResultPool",c=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",c=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",c=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",c=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(c)),void 0)),i("getSpecFromResultPoolByRef",(c,a)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getDataFromResultPoolByRef",(c,a)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(c),this.vm.getString(a)),void 0)),i("createPFrame",c=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(c)),void 0)),i("createPTable",c=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(c)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function We(s,e){return Ce(s.traverse({field:G(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:m.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=B.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const De=process.env.MI_LOG_OUTPUT_STATUS;function pn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),j.Computable.makeRaw(c=>{const a=new Ue.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*640),l.setMaxStackSize(1024*320);const u=a.manage(l.newContext()),d=new Me(a,u,e,s,c);d.evaluateBundle(r.content);const f=d.runCallback(t.handle);d.resetComputableCtx();let h=0;return De&&De!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:async(g,{unstableMarker:R,stable:A})=>{for(const[q,$]of Object.entries(g))d.runCallback(q,$);const x=d.importObjectUniversal(f);return h++,De&&(De!=="unstable-only"||!A)&&console.log(A?`Stable output ${t.handle} calculated ${x!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${R}; ${x!==void 0?"defined":"undefined"} (#${h})`),x}}},n)}function hn(s){return B.isConfigLambda(s)?s.isActive===!0:Lo(s)}function Re(s,e,t,r,o,n={}){if(B.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return pn(s,e,t,r,o,n)}else return un(s.driverKit,e,t,n)}function fn(s,e,t){return j.Computable.make(r=>{var g,R,A,x,q,$,ce,pe;const o=r.accessor(s).node(),n=k.notEmpty(o.getKeyValueAsJson(Ct)),i=k.notEmpty(o.getKeyValueAsJson(ke)),c=k.notEmpty(o.getKeyValueAsJson(Oe)),a=k.notEmpty(o.getKeyValueAsJson(de)),l=k.notEmpty(o.getKeyValueAsJson(Je)),u=new Map;for(const{id:D}of oe(a)){const X=o.traverse({field:G(D,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let le;const W=o.traverse({field:G(D,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(W!==void 0){const M=o.getField({field:G(D,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),J=o.getField({field:G(D,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});le={arguments:W.getDataAsJson(),stale:X.id!==W.id,outputError:M.error!==void 0||J.error!==void 0||((g=M.value)==null?void 0:g.getError())!==void 0||((R=J.value)==null?void 0:R.getError())!==void 0,outputsError:((A=M.error)==null?void 0:A.getDataAsString())??((q=(x=M.value)==null?void 0:x.getError())==null?void 0:q.getDataAsString()),exportsError:(($=J.error)==null?void 0:$.getDataAsString())??((pe=(ce=J.value)==null?void 0:ce.getError())==null?void 0:pe.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(J.value!==void 0&&J.value.getIsReadyOrError()||J.error!==void 0&&J.error.getIsReadyOrError())}}u.set(D,{currentArguments:X.getDataAsJson(),prod:le})}const d=Ve(a,D=>u.get(D).currentArguments),f=new Set(l.blocksInLimbo),h=[...oe(a)].map(({id:D,label:X,renderingMode:le})=>{var b,C,T,E,L;const W=k.notEmpty(u.get(D)),M=k.notEmpty(d.nodes.get(D));let J="NotCalculated";W.prod!==void 0&&(f.has(D)?J="Limbo":J=W.prod.finished?"Done":"Running");const Y=We(o,D),{sections:he,title:y,inputsValid:p,sdkVersion:S}=Ce(Y,({bpId:V,cfg:F,info:fe})=>{const tt=$t(s,D);return{sections:Re(t,tt,F.sections,F.code,V),title:Ce(F.title,ls=>Re(t,tt,ls,F.code,V)),inputsValid:Re(t,tt,F.inputsValid,F.code,V),sdkVersion:F.sdkVersion}})||{},v=o.traverse({field:G(D,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ce(Y,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:v}));return{id:D,label:y??X,title:y??X,renderingMode:le,stale:((b=W.prod)==null?void 0:b.stale)!==!1||J==="Limbo",missingReference:M.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",D)],downstreams:[...d.traverseIdsExcludingRoots("downstream",D)],calculationStatus:J,outputErrors:((C=W.prod)==null?void 0:C.outputError)===!0,outputsError:(T=W.prod)==null?void 0:T.outputsError,exportsError:(E=W.prod)==null?void 0:E.exportsError,settings:v,sections:he,inputsValid:p,updateInfo:{},currentBlockPack:(L=Y==null?void 0:Y.info)==null?void 0:L.source,updates:P,sdkVersion:S,navigationState:e.getState(D)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ht),blocks:h}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(f=>n.has(f))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(f=>o.has(f))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function gn(s,e){const t=s.node();if(m.resourceTypesEqual(t.resourceType,Et)){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(m.resourceTypesEqual(t.resourceType,kt)){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 mn(s,e){if(s!==void 0)return j.Computable.make(t=>gn(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function vn(s,e,t){return j.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=We(o,e),i=(c=o.traverse({field:G(e,"blockPack"),assertFieldType:"Dynamic"},{field:m.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Gr,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:mn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Qr(s,e,t){if(t===void 0)return j.Computable.make(i=>Qr(s,e,i),{key:`inputs#${m.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=$t(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(pt(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function yn(s,e,t){return j.Computable.make(r=>{const o=r.accessor(s).node(),n=Hr(s,e);return Ce(We(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Re(t,n,u,i.code,c);a[l]=j.Computable.wrapError(d)}return a})},{key:"outputs#"+m.resourceIdToString(s.rid)+"#"+e}).withStableType()}function Sn(s,e){return j.Computable.make(t=>{const r=t.accessor(s).node(),o=k.notEmpty(r.getKeyValueAsJson(de)),n=[];for(const{id:i,renderingMode:c}of oe(o)){const a=We(r,i);if(a===void 0)continue;const l=Object.entries(a.cfg.outputs).map(([,d])=>d).filter(d=>hn(d)).map(d=>d);if(l.length===0)continue;const u=Hr(r.persist(),i);for(const d of l)n.push(j.Computable.wrapError(Re(e,u,d,a.cfg.code,a.bpId)))}return n})}class bn{constructor(){w(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:{...B.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())}}class ze{constructor(e,t,r){w(this,"rid");w(this,"overview");w(this,"navigationStates",new bn);w(this,"blockComputables",new Map);w(this,"blockFrontends",new Map);w(this,"activeConfigs");w(this,"refreshLoopResult");w(this,"abortController",new AbortController);w(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=fn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Sn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Le(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await $r.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(m.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!m.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=ne.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=B.extractConfig(c);return await ee(this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),uiState:JSON.stringify(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await ee(this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ee(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ee(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(c=>{const a=n.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Le(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Le(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ee(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ee(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ee(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ee(this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=m.ensureResourceIdNotNull((await r.getField(m.field(this.rid,G(e,"blockPack")))).value),n=m.ensureResourceIdNotNull((await r.getField(m.field(o,m.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=JSON.parse(Buffer.from(k.notEmpty(i.data)).toString("utf-8"));await ee(r,this.rid,t,a=>{a.setArgs([{blockId:e,args:JSON.stringify(c.config.initialArgs)}]),a.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=yn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:Qr(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,navigationState:i.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=vn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Le(e.pl,t,o=>{});const r=await _e.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:wn},e.logger);return new ze(e,t,r)}}function wn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}const Tt={logger:new k.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function It(s){return{blobDownloadPath:K.join(s,"download"),downloadBlobToURLPath:K.join(s,"downloadToURL")}}const Zr={...Tt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function es(s){return{...It(s),frontendDownloadPath:K.join(s,"frontend")}}function Pn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var yt={exports:{}};const Cn="2.0.0",ts=256,Rn=Number.MAX_SAFE_INTEGER||9007199254740991,En=16,kn=ts-6,On=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Xe={MAX_LENGTH:ts,MAX_SAFE_COMPONENT_LENGTH:En,MAX_SAFE_BUILD_LENGTH:kn,MAX_SAFE_INTEGER:Rn,RELEASE_TYPES:On,SEMVER_SPEC_VERSION:Cn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const $n=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var Ye=$n;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=Xe,n=Ye;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.t={};let u=0;const d="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[d,r]],h=R=>{for(const[A,x]of f)R=R.split(`${A}*`).join(`${A}{0,${x}}`).split(`${A}+`).join(`${A}{1,${x}}`);return R},g=(R,A,x)=>{const q=h(A),$=u++;n(R,$,A),l[R]=$,a[$]=A,i[$]=new RegExp(A,x?"g":void 0),c[$]=new RegExp(q,x?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),g("MAINVERSION",`(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${a[l.NUMERICIDENTIFIER]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${a[l.NUMERICIDENTIFIERLOOSE]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASE",`(?:-(${a[l.PRERELEASEIDENTIFIER]}(?:\\.${a[l.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${a[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[l.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${d}+`),g("BUILD",`(?:\\+(${a[l.BUILDIDENTIFIER]}(?:\\.${a[l.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${a[l.MAINVERSION]}${a[l.PRERELEASE]}?${a[l.BUILD]}?`),g("FULL",`^${a[l.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${a[l.MAINVERSIONLOOSE]}${a[l.PRERELEASELOOSE]}?${a[l.BUILD]}?`),g("LOOSE",`^${a[l.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${a[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${a[l.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:${a[l.PRERELEASE]})?${a[l.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:${a[l.PRERELEASELOOSE]})?${a[l.BUILD]}?)?)?`),g("XRANGE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${a[l.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",a[l.COERCEPLAIN]+`(?:${a[l.PRERELEASE]})?(?:${a[l.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",a[l.COERCE],!0),g("COERCERTLFULL",a[l.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${a[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${a[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${a[l.LONECARET]}${a[l.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${a[l.LONECARET]}${a[l.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${a[l.GTLT]}\\s*(${a[l.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]}|${a[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${a[l.XRANGEPLAIN]})\\s+-\\s+(${a[l.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${a[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[l.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(yt,yt.exports);var $e=yt.exports;const Tn=Object.freeze({loose:!0}),In=Object.freeze({}),Fn=s=>s?typeof s!="object"?Tn:s:In;var Ft=Fn;const sr=/^[0-9]+$/,rs=(s,e)=>{const t=sr.test(s),r=sr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},An=(s,e)=>rs(e,s);var ss={compareIdentifiers:rs,rcompareIdentifiers:An};const Ne=Ye,{MAX_LENGTH:or,MAX_SAFE_INTEGER:Be}=Xe,{safeRe:nr,t:ir}=$e,Ln=Ft,{compareIdentifiers:ge}=ss;let Dn=class se{constructor(e,t){if(t=Ln(t),e instanceof se){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>or)throw new TypeError(`version is longer than ${or} characters`);Ne("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?nr[ir.LOOSE]:nr[ir.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Be||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Be||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Be||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<Be)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Ne("SemVer.compare",this.version,this.options,e),!(e instanceof se)){if(typeof e=="string"&&e===this.version)return 0;e=new se(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof se||(e=new se(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof se||(e=new se(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(Ne("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}compareBuild(e){e instanceof se||(e=new se(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Ne("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}inc(e,t,r){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ge(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var H=Dn;const ar=H,Nn=(s,e,t=!1)=>{if(s instanceof ar)return s;try{return new ar(s,e)}catch(r){if(!t)return null;throw r}};var ye=Nn;const Bn=ye,jn=(s,e)=>{const t=Bn(s,e);return t?t.version:null};var xn=jn;const Vn=ye,Un=(s,e)=>{const t=Vn(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Jn=Un;const cr=H,Gn=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new cr(s instanceof cr?s.version:s,t).inc(e,r,o).version}catch{return null}};var Mn=Gn;const lr=ye,_n=(s,e)=>{const t=lr(s,null,!0),r=lr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a)return!c.patch&&!c.minor?"major":i.patch?"patch":i.minor?"minor":"major";const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var Kn=_n;const Hn=H,qn=(s,e)=>new Hn(s,e).major;var Wn=qn;const zn=H,Xn=(s,e)=>new zn(s,e).minor;var Yn=Xn;const Qn=H,Zn=(s,e)=>new Qn(s,e).patch;var ei=Zn;const ti=ye,ri=(s,e)=>{const t=ti(s,e);return t&&t.prerelease.length?t.prerelease:null};var si=ri;const ur=H,oi=(s,e,t)=>new ur(s,t).compare(new ur(e,t));var te=oi;const ni=te,ii=(s,e,t)=>ni(e,s,t);var ai=ii;const ci=te,li=(s,e)=>ci(s,e,!0);var ui=li;const dr=H,di=(s,e,t)=>{const r=new dr(s,t),o=new dr(e,t);return r.compare(o)||r.compareBuild(o)};var At=di;const pi=At,hi=(s,e)=>s.sort((t,r)=>pi(t,r,e));var fi=hi;const gi=At,mi=(s,e)=>s.sort((t,r)=>gi(r,t,e));var vi=mi;const yi=te,Si=(s,e,t)=>yi(s,e,t)>0;var Qe=Si;const bi=te,wi=(s,e,t)=>bi(s,e,t)<0;var Lt=wi;const Pi=te,Ci=(s,e,t)=>Pi(s,e,t)===0;var os=Ci;const Ri=te,Ei=(s,e,t)=>Ri(s,e,t)!==0;var ns=Ei;const ki=te,Oi=(s,e,t)=>ki(s,e,t)>=0;var Dt=Oi;const $i=te,Ti=(s,e,t)=>$i(s,e,t)<=0;var Nt=Ti;const Ii=os,Fi=ns,Ai=Qe,Li=Dt,Di=Lt,Ni=Nt,Bi=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return Ii(s,t,r);case"!=":return Fi(s,t,r);case">":return Ai(s,t,r);case">=":return Li(s,t,r);case"<":return Di(s,t,r);case"<=":return Ni(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var is=Bi;const ji=H,xi=ye,{safeRe:je,t:xe}=$e,Vi=(s,e)=>{if(s instanceof ji)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?je[xe.COERCEFULL]:je[xe.COERCE]);else{const a=e.includePrerelease?je[xe.COERCERTLFULL]:je[xe.COERCERTL];let l;for(;(l=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",c=e.includePrerelease&&t[6]?`+${t[6]}`:"";return xi(`${r}.${o}.${n}${i}${c}`,e)};var Ui=Vi;class Ji{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var Gi=Ji,nt,pr;function re(){if(pr)return nt;pr=1;const s=/\s+/g;class e{constructor(p,S){if(S=o(S),p instanceof e)return p.loose===!!S.loose&&p.includePrerelease===!!S.includePrerelease?p:new e(p.raw,S);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(v=>this.parseRange(v.trim())).filter(v=>v.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const v=this.set[0];if(this.set=this.set.filter(P=>!R(P[0])),this.set.length===0)this.set=[v];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&A(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const S=this.set[p];for(let v=0;v<S.length;v++)v>0&&(this.formatted+=" "),this.formatted+=S[v].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const v=((this.options.includePrerelease&&h)|(this.options.loose&&g))+":"+p,P=r.get(v);if(P)return P;const b=this.options.loose,C=b?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];p=p.replace(C,Y(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(a[l.COMPARATORTRIM],u),i("comparator trim",p),p=p.replace(a[l.TILDETRIM],d),i("tilde trim",p),p=p.replace(a[l.CARETTRIM],f),i("caret trim",p);let T=p.split(" ").map(F=>q(F,this.options)).join(" ").split(/\s+/).map(F=>J(F,this.options));b&&(T=T.filter(F=>(i("loose invalid filter",F,this.options),!!F.match(a[l.COMPARATORLOOSE])))),i("range list",T);const E=new Map,L=T.map(F=>new n(F,this.options));for(const F of L){if(R(F))return[F];E.set(F.value,F)}E.size>1&&E.has("")&&E.delete("");const V=[...E.values()];return r.set(v,V),V}intersects(p,S){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(v=>x(v,S)&&p.set.some(P=>x(P,S)&&v.every(b=>P.every(C=>b.intersects(C,S)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new c(p,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(he(this.set[S],p,this.options))return!0;return!1}}nt=e;const t=Gi,r=new t,o=Ft,n=Ze(),i=Ye,c=H,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=$e,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:g}=Xe,R=y=>y.value==="<0.0.0-0",A=y=>y.value==="",x=(y,p)=>{let S=!0;const v=y.slice();let P=v.pop();for(;S&&v.length;)S=v.every(b=>P.intersects(b,p)),P=v.pop();return S},q=(y,p)=>(i("comp",y,p),y=D(y,p),i("caret",y),y=ce(y,p),i("tildes",y),y=le(y,p),i("xrange",y),y=M(y,p),i("stars",y),y),$=y=>!y||y.toLowerCase()==="x"||y==="*",ce=(y,p)=>y.trim().split(/\s+/).map(S=>pe(S,p)).join(" "),pe=(y,p)=>{const S=p.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(S,(v,P,b,C,T)=>{i("tilde",y,v,P,b,C,T);let E;return $(P)?E="":$(b)?E=`>=${P}.0.0 <${+P+1}.0.0-0`:$(C)?E=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:T?(i("replaceTilde pr",T),E=`>=${P}.${b}.${C}-${T} <${P}.${+b+1}.0-0`):E=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",E),E})},D=(y,p)=>y.trim().split(/\s+/).map(S=>X(S,p)).join(" "),X=(y,p)=>{i("caret",y,p);const S=p.loose?a[l.CARETLOOSE]:a[l.CARET],v=p.includePrerelease?"-0":"";return y.replace(S,(P,b,C,T,E)=>{i("caret",y,P,b,C,T,E);let L;return $(b)?L="":$(C)?L=`>=${b}.0.0${v} <${+b+1}.0.0-0`:$(T)?b==="0"?L=`>=${b}.${C}.0${v} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.0${v} <${+b+1}.0.0-0`:E?(i("replaceCaret pr",E),b==="0"?C==="0"?L=`>=${b}.${C}.${T}-${E} <${b}.${C}.${+T+1}-0`:L=`>=${b}.${C}.${T}-${E} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${T}-${E} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?L=`>=${b}.${C}.${T}${v} <${b}.${C}.${+T+1}-0`:L=`>=${b}.${C}.${T}${v} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${T} <${+b+1}.0.0-0`),i("caret return",L),L})},le=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(S=>W(S,p)).join(" ")),W=(y,p)=>{y=y.trim();const S=p.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(S,(v,P,b,C,T,E)=>{i("xRange",y,v,P,b,C,T,E);const L=$(b),V=L||$(C),F=V||$(T),fe=F;return P==="="&&fe&&(P=""),E=p.includePrerelease?"-0":"",L?P===">"||P==="<"?v="<0.0.0-0":v="*":P&&fe?(V&&(C=0),T=0,P===">"?(P=">=",V?(b=+b+1,C=0,T=0):(C=+C+1,T=0)):P==="<="&&(P="<",V?b=+b+1:C=+C+1),P==="<"&&(E="-0"),v=`${P+b}.${C}.${T}${E}`):V?v=`>=${b}.0.0${E} <${+b+1}.0.0-0`:F&&(v=`>=${b}.${C}.0${E} <${b}.${+C+1}.0-0`),i("xRange return",v),v})},M=(y,p)=>(i("replaceStars",y,p),y.trim().replace(a[l.STAR],"")),J=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(a[p.includePrerelease?l.GTE0PRE:l.GTE0],"")),Y=y=>(p,S,v,P,b,C,T,E,L,V,F,fe)=>($(v)?S="":$(P)?S=`>=${v}.0.0${y?"-0":""}`:$(b)?S=`>=${v}.${P}.0${y?"-0":""}`:C?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,$(L)?E="":$(V)?E=`<${+L+1}.0.0-0`:$(F)?E=`<${L}.${+V+1}.0-0`:fe?E=`<=${L}.${V}.${F}-${fe}`:y?E=`<${L}.${V}.${+F+1}-0`:E=`<=${E}`,`${S} ${E}`.trim()),he=(y,p,S)=>{for(let v=0;v<y.length;v++)if(!y[v].test(p))return!1;if(p.prerelease.length&&!S.includePrerelease){for(let v=0;v<y.length;v++)if(i(y[v].semver),y[v].semver!==n.ANY&&y[v].semver.prerelease.length>0){const P=y[v].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return nt}var it,hr;function Ze(){if(hr)return it;hr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],f=u.match(d);if(!f)throw new TypeError(`Invalid comparator: ${u}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new c(f[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 c(u,this.options)}catch{return!1}return n(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}it=e;const t=Ft,{safeRe:r,t:o}=$e,n=is,i=Ye,c=H,a=re();return it}const Mi=re(),_i=(s,e,t)=>{try{e=new Mi(e,t)}catch{return!1}return e.test(s)};var et=_i;const Ki=re(),Hi=(s,e)=>new Ki(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var qi=Hi;const Wi=H,zi=re(),Xi=(s,e,t)=>{let r=null,o=null,n=null;try{n=new zi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new Wi(r,t))}),r};var Yi=Xi;const Qi=H,Zi=re(),ea=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Zi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Qi(r,t))}),r};var ta=ea;const at=H,ra=re(),fr=Qe,sa=(s,e)=>{s=new ra(s,e);let t=new at("0.0.0");if(s.test(t)||(t=new at("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const c=new at(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||fr(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||fr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var oa=sa;const na=re(),ia=(s,e)=>{try{return new na(s,e).range||"*"}catch{return null}};var aa=ia;const ca=H,as=Ze(),{ANY:la}=as,ua=re(),da=et,gr=Qe,mr=Lt,pa=Nt,ha=Dt,fa=(s,e,t,r)=>{s=new ca(s,r),e=new ua(e,r);let o,n,i,c,a;switch(t){case">":o=gr,n=pa,i=mr,c=">",a=">=";break;case"<":o=mr,n=ha,i=gr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(da(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,f=null;if(u.forEach(h=>{h.semver===la&&(h=new as(">=0.0.0")),d=d||h,f=f||h,o(h.semver,d.semver,r)?d=h:i(h.semver,f.semver,r)&&(f=h)}),d.operator===c||d.operator===a||(!f.operator||f.operator===c)&&n(s,f.semver))return!1;if(f.operator===a&&i(s,f.semver))return!1}return!0};var Bt=fa;const ga=Bt,ma=(s,e,t)=>ga(s,e,">",t);var va=ma;const ya=Bt,Sa=(s,e,t)=>ya(s,e,"<",t);var ba=Sa;const vr=re(),wa=(s,e,t)=>(s=new vr(s,t),e=new vr(e,t),s.intersects(e,t));var Pa=wa;const Ca=et,Ra=te;var Ea=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>Ra(u,d,t));for(const u of i)Ca(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const c=[];for(const[u,d]of r)u===d?c.push(u):!d&&u===i[0]?c.push("*"):d?u===i[0]?c.push(`<=${d}`):c.push(`${u} - ${d}`):c.push(`>=${u}`);const a=c.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return a.length<l.length?a:e};const yr=re(),jt=Ze(),{ANY:ct}=jt,Se=et,xt=te,ka=(s,e,t={})=>{if(s===e)return!0;s=new yr(s,t),e=new yr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=$a(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},Oa=[new jt(">=0.0.0-0")],Sr=[new jt(">=0.0.0")],$a=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===ct){if(e.length===1&&e[0].semver===ct)return!0;t.includePrerelease?s=Oa:s=Sr}if(e.length===1&&e[0].semver===ct){if(t.includePrerelease)return!0;e=Sr}const r=new Set;let o,n;for(const h of s)h.operator===">"||h.operator===">="?o=br(o,h,t):h.operator==="<"||h.operator==="<="?n=wr(n,h,t):r.add(h.semver);if(r.size>1)return null;let i;if(o&&n){if(i=xt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const h of r){if(o&&!Se(h,String(o),t)||n&&!Se(h,String(n),t))return null;for(const g of e)if(!Se(h,String(g),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,f=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const h of e){if(u=u||h.operator===">"||h.operator===">=",l=l||h.operator==="<"||h.operator==="<=",o){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(c=br(o,h,t),c===h&&c!==o)return!1}else if(o.operator===">="&&!Se(o.semver,String(h),t))return!1}if(n){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(a=wr(n,h,t),a===h&&a!==n)return!1}else if(n.operator==="<="&&!Se(n.semver,String(h),t))return!1}if(!h.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||f||d)},br=(s,e,t)=>{if(!s)return e;const r=xt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},wr=(s,e,t)=>{if(!s)return e;const r=xt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Ta=ka;const lt=$e,Pr=Xe,Ia=H,Cr=ss,Fa=ye,Aa=xn,La=Jn,Da=Mn,Na=Kn,Ba=Wn,ja=Yn,xa=ei,Va=si,Ua=te,Ja=ai,Ga=ui,Ma=At,_a=fi,Ka=vi,Ha=Qe,qa=Lt,Wa=os,za=ns,Xa=Dt,Ya=Nt,Qa=is,Za=Ui,ec=Ze(),tc=re(),rc=et,sc=qi,oc=Yi,nc=ta,ic=oa,ac=aa,cc=Bt,lc=va,uc=ba,dc=Pa,pc=Ea,hc=Ta;var fc={parse:Fa,valid:Aa,clean:La,inc:Da,diff:Na,major:Ba,minor:ja,patch:xa,prerelease:Va,compare:Ua,rcompare:Ja,compareLoose:Ga,compareBuild:Ma,sort:_a,rsort:Ka,gt:Ha,lt:qa,eq:Wa,neq:za,gte:Xa,lte:Ya,cmp:Qa,coerce:Za,Comparator:ec,Range:tc,satisfies:rc,toComparators:sc,maxSatisfying:oc,minSatisfying:nc,minVersion:ic,validRange:ac,outside:cc,gtr:lc,ltr:uc,intersects:dc,simplifyRange:pc,subset:hc,SemVer:Ia,re:lt.re,src:lt.src,tokens:lt.t,SEMVER_SPEC_VERSION:Pr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Pr.RELEASE_TYPES,compareIdentifiers:Cr.compareIdentifiers,rcompareIdentifiers:Cr.rcompareIdentifiers};const gc=Pn(fc),mc={minDelay:1500},vc="__no_updates__";class yc extends j.PollComputablePool{constructor(t,r,o={}){super({...o,...mc},r);w(this,"http");w(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${ae(t)}`;default:return vc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Pt(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await _.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await Ke(i);return c===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let l,u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,U.StableChannel))u=U.StableChannel;else{if(await a.getLatestOverview(n.id,U.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${U.blockPackIdToString(n.id)}`),{suggestions:[]};u=U.AnyChannel}else u=n.channel;const d=await a.getUpdateSuggestions(n.id,u);if(d===void 0||d.length===0)return{suggestions:[]};d.reverse();let f;switch(i){case void 0:f=d[0].update;break;case"major":f=(r=d.find(R=>R.type!=="major"))==null?void 0:r.update;break;case"minor":f=(o=d.find(R=>R.type==="patch"))==null?void 0:o.update;break}const h=d.map(({type:R,update:A})=>({type:R,update:{...n,id:{...n.id,version:A}}}));if(f===void 0)return{suggestions:h};if(c!==void 0&&gc.lte(f,c))return{suggestions:h};const g={...n,id:{...n.id,version:f}};return(async()=>{try{await a.getComponents(g.id)}catch(R){this.logger.warn(R)}})(),{suggestions:h,mainSuggestion:g}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return ae(t)===ae(r)}}class Rr{constructor(){w(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let be;function ue(){return be||(be={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0},process.env.MI_LOG_TREE_STAT&&(be.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),be)}function Er(s){return String(s.id)}const Sc=["Int","Long","Float","Double","String","Bytes"];function ut(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 s}const we=(s,e)=>typeof e=="bigint"?e.toString():e;class bc{constructor(e,t,r,o){w(this,"specPFrame");w(this,"blobIdToResource",new Map);w(this,"blobHandleComputables",new Map);w(this,"createDataPFrame");w(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});w(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});w(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=r,this.columns=o;const n=(a,l)=>{switch(a){default:case"info":return this.logger.info(l);case"warn":return this.logger.warn(l);case"error":return this.logger.error(l)}};for(const a of o)for(const l of So(a.data))this.blobIdToResource.set(Er(l),l);const i=()=>{const a=ue().logPFrameRequests?new Gt.PFrame(n):new Gt.PFrame;for(const l of o)try{a.addColumnSpec(l.id,l.spec)}catch(u){throw new Error(`Adding column ${l.id} to PFrame failed: ${u}; Spec: ${JSON.stringify(l.spec)}.`)}return a},c=()=>{const a=i();a.setDataSource(this);for(const l of o){const u=bo(l.data,Er);try{a.setColumnData(l.id,u)}catch(d){throw new Error(`Setting column ${l.id} data to PFrame failed: ${d}; Spec: ${JSON.stringify(l.spec)}, DataInfo: ${JSON.stringify(u)}.`)}}return a};this.specPFrame=i(),this.createDataPFrame=c}get disposableDataPFrame(){const e=this.createDataPFrame();return{dataPFrame:e,[Symbol.dispose]:()=>{e.dispose()}}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.specPFrame.dispose()}}class wc{constructor(e,t){w(this,"pFrames");w(this,"pTables");w(this,"blobContentCache");w(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const r=new vs.LRUCache({maxSize:1e9,fetchMethod:async n=>await Tr.readFile(n),sizeCalculation:n=>n.length}),o=new k.ConcurrencyLimitingExecutor(1);this.blobContentCache=r,this.concurrencyLimiter=o,this.pFrames=new class extends Rr{constructor(n,i){super(),this.blobDriver=n,this.logger=i}createNewResource(n){return ue().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`),new bc(this.blobDriver,this.logger,r,n)}calculateParamsKey(n){return Cc(n)}}(this.blobDriver,this.logger),this.pTables=new class extends Rr{constructor(n){super(),this.pFrames=n}async createNewResource(n){const i=n.pFrameHandle,c=await o.run(async()=>{var l=[];try{ue().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`);const a=Te(l,this.pFrames.getByKey(i).disposableDataPFrame);return await a.dataPFrame.createTable({src:Ee(n.def.src),filters:ut(n.def.filters)})}catch(u){var d=u,f=!0}finally{Ie(l,d,f)}});return n.def.sorting.length!==0?c.sort(n.def.sorting):c}calculateParamsKey(n){return Pc(n)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>Sc.find(i=>i===n.spec.valueType)).map(n=>B.mapPObjectData(n,i=>_e.isPlTreeNodeAccessor(i)?ko(i):Oo(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(B.extractAllColumns(e.src),t),o=B.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return ue().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${r}; pTableHandle = ${JSON.stringify(n)}): ${JSON.stringify(B.mapPTableDef(e,i=>i.spec),we)}`),t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:t.compatibleWith,qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.findColumns(r))).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>{var c=[];try{ue().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,we)}`);const i=Te(c,this.pFrames.getByKey(e).disposableDataPFrame);return await i.dataPFrame.createTable({src:Ee(t.src),filters:ut(t.filters)})}catch(a){var l=a,u=!0}finally{Ie(c,l,u)}});if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,c)=>({spec:i,data:n[c]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>{var o=[];try{ue().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,we)}`);const r=Te(o,this.pFrames.getByKey(e).disposableDataPFrame);return await r.dataPFrame.getUniqueValues({...t,filters:ut(t.filters)})}catch(n){var i=n,c=!0}finally{Ie(o,i,c)}})}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function Ee(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Ee(e))};case"outer":return{type:"outer",primary:Ee(s.primary),secondary:s.secondary.map(e=>Ee(e))};default:k.assertNever(s)}}function Pc(s){const e=ne.createHash("sha256");return e.update(ae(s)),e.digest().toString("hex")}function Cc(s){const e=[...s].map(r=>B.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:a.id.toString()}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[a.index.id.toString(),a.values.id.toString()]}))};break;default:throw Error(`unsupported resource type: ${i}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ne.createHash("sha256");return t.update(ae(e)),t.digest().toString("hex")}async function cs(s,e,t){const r={...Tt,...It(e),...t},o=new k.HmacSha256Signer(r.localSecret),n=Z.createDownloadClient(r.logger,s,r.localProjections),i=Z.createLogsClient(s,r.logger),c=Z.createUploadBlobClient(s,r.logger),a=Z.createUploadProgressClient(s,r.logger),l=new Z.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new Z.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new Z.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),f=new Z.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),h=new Z.LogsDriver(r.logger,f,l),g=await Z.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),R=new wc(l,r.logger);return{blobDriver:l,blobToURLDriver:u,logDriver:h,lsDriver:g,signer:o,uploadDriver:d,pFrameDriver:R}}class Vt{constructor(e,t,r,o,n,i,c,a){w(this,"pl");w(this,"projectList");w(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ne.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await yo(o,e);return o.createField(m.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await m.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ee(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(m.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(m.field(this.projectListResourceId,e))).value;if(m.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 k.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...Zr,...es(t),...r};o.defaultTreeOptions.logStat=ue().logTreeStats;const n=await e.withWriteTx("MLInitialization",async R=>{const A=m.field(R.clientRoot,Gs);R.createField(A,"Dynamic");const x=await R.getField(A);if(m.isNullResourceId(x.value)){const q=R.createEphemeral(Dr);return R.lock(q),R.setField(A,q),await R.commit(),await q.globalId}else return x.value}),i=o.logger,c=await cs(e,t,o),a=new ie.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Fr(a),u=new uo(l,c.signer,a),d=new Z.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),f={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new yc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Ue.getQuickJS()},h=new j.WatchableValue([]),g=await _s(e,n,h,f);return new Vt(f,c,c.signer,n,h,g.tree,l,g.computable)}}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"];async function Ec(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,...e},r=[];Rc.forEach(a=>{ys.channel(a).subscribe(u=>{var f;const d=new Date().toISOString();(f=u==null?void 0:u.response)!=null&&f.headers&&(u.response.headers=u.response.headers.map(h=>h.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=m.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await me(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new m.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new m.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),o.blockGARegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),o.blockRegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),o.blockGARegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),o.autoUpdateCdnChecks=await me(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Pe(t.autoUpdateCdnUrl,t,c)),kc(o,s,t,r)}async function me(s,e,t){const r=St(),o=[];for(;kr(r)<s;){const n=St();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=kr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await $r.setTimeout(a)}return o}async function Pe(s,e,t){const{body:r,statusCode:o}=await ie.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function kc(s,e,t,r){const o=s.plPings.filter(c=>c.response.ok),n=s.plPings.filter(c=>!c.response.ok),i=[...new Set(o.map(c=>JSON.stringify(c.response.value)))];return`
|
|
1
|
+
"use strict";var us=Object.defineProperty;var Jt=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Gt=s=>{throw TypeError(s)};var ds=(s,e,t)=>e in s?us(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var w=(s,e,t)=>ds(s,typeof e!="symbol"?e+"":e,t);var Te=(s,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Gt("Object expected");var r;t&&(r=e[Jt("asyncDispose")]),r===void 0&&(r=e[Jt("dispose")]),typeof r!="function"&&Gt("Object not disposable"),s.push([t,r,e])}else t&&s.push([t]);return e},Fe=(s,e,t)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(i,c,a,l){return l=Error(a),l.name="SuppressedError",l.error=i,l.suppressed=c,l},o=i=>e=t?new r(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=s.pop();)try{var c=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(c).then(n,a=>(o(a),n()))}catch(a){o(a)}if(t)throw e};return n()};Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("@platforma-sdk/model"),U=require("@milaboratories/pl-model-middle-layer"),ce=require("undici"),_=require("@platforma-sdk/block-tools"),Q=require("node:fs"),K=require("node:path"),ps=require("yaml"),k=require("@milaboratories/ts-helpers"),hs=require("node:fs/promises"),fs=require("@milaboratories/resolve-helper"),m=require("@milaboratories/pl-client"),Ke=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ae=require("node:crypto"),D=require("@milaboratories/pl-model-backend"),Or=require("denque"),gs=require("@platforma-sdk/workflow-tengo"),ne=require("canonicalize"),ms=require("node:assert"),Je=require("quickjs-emscripten"),$r=require("node:timers/promises"),Z=require("@milaboratories/pl-drivers"),Ie=require("@milaboratories/pframes-node"),vs=require("@milaboratories/pframes-rs-node"),ys=require("lru-cache"),Ss=require("node:diagnostics_channel");function bs(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 Tr=bs(hs);async function Mt(s){try{return await Tr.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const ws=[_.RegistryV1.PlPackageYamlConfigFile],Ps=[_.RegistryV1.PlPackageJsonConfigFile],wt=["backend","dist","tengo","tpl","main.plj.gz"],Pt=["config","dist","config.json"],Fr=["frontend","dist"],_t="block-model/dist/config.json",Cs="block-ui/package.json",Rs=[wt,Pt,ws,Ps,Fr];async function Es(s){return await Mt(K.join(s,...Pt))!==void 0||await Mt(K.join(s,...wt))!==void 0}function st(s,e){const t=fs.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Kt(s,e){if(K.isAbsolute(s)||(s=K.resolve(s)),await Es(s))return{workflow:K.join(s,...wt),config:K.join(s,...Pt),ui:K.join(s,...Fr)};{const t=st(s,_t),r=st(s,_t),o=st(s,Cs);return{workflow:t,config:r,ui:K.resolve(o,"..","dist")}}}async function ks(s){try{return await Q.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function Os(s){try{return await Q.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ct(s){let e=0n;for(const t of Rs){const r=K.join(s,...t),o=await Os(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function He(s){const e=await Q.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await Q.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class $s{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ce.request(`${r.url}/${_.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const c of i){const{organization:a,package:l,latestMeta:u,latestVersion:d}=c,f={organization:a,name:l,version:d},h={id:f,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:a,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:f,registryUrl:r.url}};t.push({registryId:e.id,id:f,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:c.allVersions.map(g=>({version:g,channels:[]}))})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(c=>c.latestByChannel[U.StableChannel]?{...c,registryId:e.id}:{...c,latestByChannel:{...c.latestByChannel,[U.StableChannel]:(a=>a.spec.type==="from-registry-v2"?{...a,spec:{...a.spec,channel:U.StableChannel}}:a)(c.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const c of await Q.promises.readdir(r.path,{withFileTypes:!0})){if(!c.isDirectory())continue;const a=K.join(r.path,c.name),l=await ks(K.join(a,_.RegistryV1.PlPackageYamlConfigFile));if(l!==void 0){const u=_.RegistryV1.PlPackageConfigData.parse(ps.parse(l)),d=await Ct(a),f={organization:u.organization,name:u.package,version:"DEV"},h={id:f,meta:{title:u.meta.title??"No title",description:u.meta.description??"No Description",organization:{name:u.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:a,mtime:d}};t.push({registryId:e.id,id:f,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}else{let u=a,d=await _.tryLoadPackDescription(u);if(d===void 0){for(const f of["block","meta"])if(u=K.join(a,f),d=await _.tryLoadPackDescription(u),d!==void 0)break}if(d!==void 0){const f=await He(d),h={id:d.id,meta:await _.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:u,mtime:f}};t.push({registryId:e.id,id:d.id,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:[]})}}}return t;default:return k.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}async getOverview(e,t,r){var i;const o=(i=this.registries.find(c=>c.id===e))==null?void 0:i.spec;if(!o)throw new Error(`Registry with id "${e}" not found`);if(o.type!=="remote-v2")throw new Error('Only "remote-v2" registries support specific package version overview retrieval.');return await this.v2Provider.getRegistry(o.url).getSpecificOverview(t,r)}}class Ir{constructor(e){w(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new _.RegistryV2Reader(_.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const Ts={type:"remote-v2",url:"https://blocks.pl-open.science/"},Fs={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Is={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},As={groups:[{id:"default",label:"Default",blocks:[]}]},Ls={stagingRefreshTimestamp:0,blocksInLimbo:[]},Ns={label:"New Project"},Ds={name:"UserProject",version:"2"},Ar="SchemaVersion",Lr="1",Rt="ProjectCreated",ke="ProjectLastModified",Oe="ProjectMeta",de="ProjectStructure",Ge="BlockRenderingState",Bs="BlockFrontendState/",js=/^BlockFrontendState\/(?<blockid>.*)$/;function pt(s){return`${Bs}${s}`}const xs="BlockArgsAuthor/";function ht(s){return`${xs}${s}`}const ft="ProjectStructureAuthor";function Vs(s){const e=s.match(js);if(e!==null)return e.groups.blockid}const Us="__serviceTemplate_";function gt(s){return`${Us}${s}`}function G(s,e){return`${s}-${e}`}const Js=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Gs(s){const e=s.match(Js);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Ms="projects",Nr={name:"Projects",version:"1"},_s=s=>m.resourceTypesEqual(s.type,Nr)?s.fields:[];async function Ks(s,e,t,r){const o=await Ke.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:_s},r.logger);return{computable:j.Computable.make(i=>{const c=i.accessor(o.entry()).node(),a=t.getValue(i);if(c===void 0)return;const l=[];for(const u of c.listDynamicFields()){const d=c.traverse(u);if(d===void 0)continue;const f=k.notEmpty(d.getKeyValueAsJson(Oe)),h=k.notEmpty(d.getKeyValueAsJson(Rt)),g=k.notEmpty(d.getKeyValueAsJson(ke));l.push({id:u,rid:d.id,created:new Date(h),lastModified:new Date(g),opened:a.indexOf(d.id)>=0,meta:f})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const Hs={name:"EphRenderTemplate",version:"1"},qs={name:"RenderTemplate",version:"1"};function Et(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Hs):s.createStruct(qs),i=m.field(n,"template"),c=m.field(n,"inputs");return s.createField(i,"Input",e),s.createField(c,"Input",m.Pl.createPlMap(s,r,t)),s.lockInputs(n),m.Pl.futureRecord(s,n,o,"Output","outputs/")}const Ws={name:"BContextEnd",version:"1"},zs={name:"BContext",version:"1"},Xs="id",Ys="parent/",Qs=["context","result"];function Ht(s,e,t){return Et(s,e,!0,t,Qs)}function Zs(s){const e=s.createEphemeral(Ws);return s.lock(e),e}function eo(s,e){if(e.length===0)return Zs(s);if(e.length===1)return e[0];const t=s.createEphemeral(zs);s.createField(m.field(t,Xs),"Input",m.Pl.createPlString(s,ae.randomUUID()));for(let r=0;r<e.length;r++)s.createField(m.field(t,`${Ys}${r}`),"Input",e[r]);return s.lock(t),t}function to(s,e){const t=D.parseTemplate(e.content),r=t.type;switch(r){case"pl.tengo-template.v2":return so(s,t);default:k.assertNever(r)}}const qt={hash(s,e){e.update(D.PlTemplateLibV1.type.name).update(D.PlTemplateLibV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){return e.createValue(D.PlTemplateLibV1.type,JSON.stringify(D.PlTemplateLibV1.fromV2Data(s).data))}},Ae={hash(s,e){e.update(D.PlTemplateSoftwareV1.type.name).update(D.PlTemplateSoftwareV1.type.version).update(s.name).update(s.version).update(s.src)},render(s,e,t){const r=D.PlTemplateSoftwareV1.fromV2Data(s),o=e.createStruct(D.PlTemplateSoftwareV1.type,r.data);return e.setKValue(o,D.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(r.name)),e.lock(o),o}},ro={hash(s,e){e.update(D.PlTemplateOverrideV1.type.name).update(D.PlTemplateOverrideV1.type.version).update(s.hashOverride??"")},render(s,e,t){return e.createStruct(D.PlTemplateOverrideV1.type,JSON.stringify(D.PlTemplateOverrideV1.fromV2Data(s)))}},Dr={hash(s,e){e.update(D.PlTemplateV1.type.name).update(D.PlTemplateV1.type.version).update(s.hashOverride??"").update(s.name).update(s.version).update(s.src);const t=r=>(r.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),r);for(const[r,o]of t(Object.entries(s.libs??{})))e.update("lib:"+r),qt.hash(o,e);for(const[r,o]of t(Object.entries(s.software??{})))e.update("soft:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.assets??{})))e.update("asset:"+r),Ae.hash(o,e);for(const[r,o]of t(Object.entries(s.templates??{})))e.update("tpl:"+r),this.hash(o,e)},render(s,e,t){const r=e.createStruct(D.PlTemplateV1.type,JSON.stringify(D.PlTemplateV1.fromV2Data(s).data));for(const[i,c]of Object.entries(s.libs??{})){const a=D.PlTemplateV1.libField(r,i);e.createField(a,"Input"),e.setField(a,t(c,qt))}for(const[i,c]of Object.entries(s.software??{})){const a=D.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ae))}for(const[i,c]of Object.entries(s.assets??{})){const a=D.PlTemplateV1.swField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Ae))}for(const[i,c]of Object.entries(s.templates??{})){const a=D.PlTemplateV1.tplField(r,i);e.createField(a,"Input"),e.setField(a,t(c,Dr))}if(e.lock(r),!s.hashOverride)return r;const o=t(s,ro),n=D.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,r),e.lock(r),o}};function so(s,e){const t=new Map,r=(o,n)=>{const i=ae.createHash("sha256");n.hash(o,i);const c=i.digest("hex");if(!t.has(c)){const a=n.render(o,s,r);t.set(c,a)}return t.get(c)};return r(e,Dr)}const Br={name:"TengoTemplateGet",version:"1"},jr="registry",xr="templateURI",Vr="template",oo={name:"TengoTemplatePack",version:"1"},no={name:"TengoTemplatePackConvert",version:"1"},io="templatePack",ao="template";async function Ur(s){switch(s.type){case"from-file":return{type:"explicit",content:await Q.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return k.assertNever(s)}}function co(s,e){const t=s.createStruct(Br),r=m.field(t,jr),o=m.field(t,xr),n=m.field(t,Vr);return s.setField(r,s.createValue(m.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(m.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function qe(s,e){switch(e.type){case"from-registry":return co(s,e);case"explicit":return to(s,e);default:return k.assertNever(e)}}const kt={name:"Frontend/FromUrl",version:"1"},Ot={name:"Frontend/FromFolder",version:"1"};function lo(s,e){switch(e.type){case"url":return s.createValue(kt,JSON.stringify({url:e.url}));case"local":return s.createValue(Ot,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}const uo={name:"BlockPackCustom",version:"1"},Jr="template",Gr="frontend";function Wt(s){return s.endsWith("/")?s:`${s}/`}class po{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Kt(e.folder),r=await Q.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await _.loadPackDescription(e.folder),r=await Q.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${Wt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await ce.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await ce.request(o.model.url,t)).body.json()}default:return k.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Kt(e.folder),r=await Q.promises.readFile(t.workflow),o=JSON.parse(await Q.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await _.loadPackDescription(e.folder),r=JSON.parse(await Q.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Q.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await He(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${Wt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await ce.request(o,t);if(n.statusCode!==200)throw new Error(`Block not found in registry (url = ${o} ; code = ${n.statusCode}): `+JSON.stringify(e));const i=new Uint8Array(await n.body.arrayBuffer()),a=await(await ce.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:a,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await ce.request(o.model.url,t)).body.json(),i=async()=>await(await ce.request(o.workflow.main.url,t)).body.arrayBuffer(),[c,a]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(a)},config:c,frontend:{type:"url",url:o.ui.url},source:e}}default:return k.assertNever(e)}}}function ho(s,e){const t={config:e.config,source:e.source},r=s.createStruct(uo,JSON.stringify(t));return s.createField(m.field(r,Jr),"Input",qe(s,e.template)),s.createField(m.field(r,Gr),"Input",lo(s,e.frontend)),s.lock(r),r}function zt(s,e){switch(e.type){case"explicit":return ho(s,e);default:return k.assertNever(e.type)}}function Le(s,e){return{__isRef:!0,blockId:s,name:e}}function fo(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function mt(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(fo(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)mt(s,o,t);else for(const[,o]of Object.entries(e))mt(s,o,t);return;default:k.assertNever(r)}}function go(s,e){const t={upstreams:new Set,missingReferences:!1};return mt(t,s,e),t}function ie(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Mr{constructor(e){w(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){let i=[];for(const c of o){const a=this.nodes.get(c);r(a),a[e].forEach(l=>{n.has(l)||(n.add(l),i.push(l))})}o=i}}}function vt(s){const e=new Map;let t;for(const{id:r}of ie(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Mr(e)}function Ue(s,e){const t=new Map,r=new Set;for(const{id:o}of ie(s)){const n=e(o);if(n===void 0)continue;const i=go(n,r),c={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,c),i.upstreams.forEach(a=>t.get(a).downstream.add(o)),r.add(o)}return new Mr(t)}function mo(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function yt(s,e){if(s.size>e.size)return yt(e,s);for(const t of s)if(e.has(t))return!0;return!1}function Xt(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!mo(n.upstream,i.upstream)||yt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?yt(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let ot;async function _r(){if(ot===void 0){const s=await Ur(gs.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ae.createHash("sha256").update(s.content).digest("hex");ot={spec:s,hash:e}}return ot}function vo(s,e,t){return Et(s,e,!0,{pf:t},["result"]).result}function nt(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class Yt{constructor(e,t){w(this,"currentInputsC",nt(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));w(this,"actualProductionInputsC",nt(()=>{var e;return(e=this.fields.prodArgs)==null?void 0:e.modCount},()=>{var t;const e=(t=this.fields.prodArgs)==null?void 0:t.value;if(e!==void 0)return JSON.parse(Buffer.from(e).toString())}));w(this,"productionStaleC",nt(()=>{var e;return`${this.fields.currentArgs.modCount}_${(e=this.fields.prodArgs)==null?void 0:e.modCount}`},()=>this.fields.prodArgs===void 0||Buffer.compare(this.fields.currentArgs.value,this.fields.prodArgs.value)!==0));this.id=e,this.fields=t}check(){if(this.fields.prodOutput===void 0!=(this.fields.prodCtx===void 0))throw new Error("inconsistent prod fields");if(this.fields.stagingOutput===void 0!=(this.fields.stagingCtx===void 0))throw new Error("inconsistent stage fields");if(this.fields.prodOutputPrevious===void 0!=(this.fields.prodCtxPrevious===void 0))throw new Error("inconsistent prod cache fields");if(this.fields.stagingOutputPrevious===void 0!=(this.fields.stagingCtxPrevious===void 0))throw new Error("inconsistent stage cache fields");if(this.fields.blockPack===void 0)throw new Error("no block pack field");if(this.fields.currentArgs===void 0)throw new Error("no current args field")}get currentInputs(){return this.currentInputsC()}get stagingRendered(){return this.fields.stagingCtx!==void 0}get productionRendered(){return this.fields.prodCtx!==void 0}get productionHasErrors(){var e;return((e=this.fields.prodUiCtx)==null?void 0:e.status)==="Error"}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()||this.productionHasErrors}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(m.Pl.unwrapHolder(e,this.fields.blockPack.ref),Jr,"Input")}}const yo=s=>{throw new Error(`No new block info for ${s}`)};class Me{constructor(e,t,r,o,n,i,c,a,l,u,d,f){w(this,"globalModCount",0);w(this,"fieldsChanged",!1);w(this,"lastModifiedChanged",!1);w(this,"structureChanged",!1);w(this,"metaChanged",!1);w(this,"renderingStateChanged",!1);w(this,"changedBlockFrontendStates",new Set);w(this,"blocksWithChangedInputs",new Set);w(this,"stagingGraph");w(this,"pendingProductionGraph");w(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=c,this.renderingState=a,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=f}fixProblemsAndMigrate(){this.blockInfos.forEach(t=>{(t.fields.prodArgs===void 0||t.fields.prodOutput===void 0||t.fields.prodCtx===void 0)&&this.deleteBlockFields(t.id,"prodArgs","prodOutput","prodCtx")});let e;this.blockInfos.forEach(t=>{t.fields.blockSettings===void 0&&(e===void 0&&(e=this.createJsonFieldValue(U.InitialBlockSettings)),this.setBlockFieldObj(t.id,"blockSettings",e))})}get wasModified(){return this.lastModifiedChanged||this.structureChanged||this.fieldsChanged||this.metaChanged||this.renderingStateChanged||this.changedBlockFrontendStates.size>0}get structure(){return JSON.parse(JSON.stringify(this.struct))}getStagingGraph(){return this.stagingGraph===void 0&&(this.stagingGraph=vt(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=Ue(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ue(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){const t=this.blockInfos.get(e);if(t===void 0)throw new Error(`No such block: ${e}`);return t}createJsonFieldValueByContent(e){const t=Buffer.from(e);return{ref:this.tx.createValue(m.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=m.field(this.rid,G(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(m.field(this.rid,G(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const c=this.tx.createValue(m.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",c,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(m.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),eo(this.tx,r)}exportCtx(e){return vo(this.tx,m.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Ht(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(m.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(m.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",m.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Ht(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(m.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(m.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",m.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=yo){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=vt(e),i=Ue(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),c=Xt(r,n),a=Xt(o,i);for(const l of c.onlyInA){const{fields:u}=this.getBlockInfo(l);this.deleteBlockFields(l,...Object.keys(u)),this.blockInfos.delete(l),this.blocksInLimbo.delete(l)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(l)&&this.changedBlockFrontendStates.add(l)}for(const l of c.onlyInB){const u=new Yt(l,{});this.blockInfos.set(l,u);const d=t(l),f=zt(this.tx,d.blockPack);this.setBlockField(l,"blockPack",m.Pl.wrapInHolder(this.tx,f),"NotReady"),this.setBlockFieldObj(l,"blockSettings",this.createJsonFieldValue(U.InitialBlockSettings)),this.setBlockFieldObj(l,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(l,d.uiState),this.changedBlockFrontendStates.add(l)),u.check()}for(const l of c.different)this.resetStaging(l);o.traverse("downstream",[...a.different],l=>{this.resetOrLimboProduction(l.id)}),(c.onlyInB.size>0||c.onlyInA.size>0||c.different.size>0)&&this.resetStagingRefreshTimestamp(),this.struct=e,this.structureChanged=!0,this.stagingGraph=void 0,this.pendingProductionGraph=void 0,this.actualProductionGraph=void 0,this.updateLastModified()}addBlock(e,t,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const c=i.blocks.findIndex(a=>a.id===r);if(!(c<0)){i.blocks.splice(c,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",m.Pl.wrapInHolder(this.tx,zt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const c=o.nodes.get(i);if(c===void 0)throw new Error(`Can't find block with id: ${i}`);for(const a of c.upstream)if(!r.has(a))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of ie(this.structure)){if(!r.has(i.id))continue;let c=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!c){for(const a of o.nodes.get(i.id).upstream)if(n.has(a)){c=!0;break}}c&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,c;const t=this.getActualProductionGraph(),r=new Or(e),o=new Set(e),n=[];for(;!r.isEmpty();){const a=r.shift(),l=this.getBlockInfo(a).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((c=l.prodCtx)==null?void 0:c.status)==="Ready")&&this.deleteBlockFields(a,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(a);for(const u of t.traverseIdsExcludingRoots("downstream",a))o.has(u)||(r.push(u),o.add(u))}}for(const a of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(a)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(c=>{const a=t.get(c);a!==0&&(i=Math.max(a+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,ht(t)):this.tx.setKValue(this.rid,ht(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,ft):this.tx.setKValue(this.rid,ft,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,ke,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,de,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Ge,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Oe,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,pt(e)):this.tx.setKValue(this.rid,pt(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Ar),i=e.getKValueJson(t,ke),c=e.getKValueJson(t,Oe),a=e.getKValueJson(t,de),l=e.getKValueJson(t,Ge),u=e.listKeyValuesString(t),[d,f,h,g,R,{stagingRefreshTimestamp:A,blocksInLimbo:x},q]=await Promise.all([o,n,i,c,a,l,u]);if(f!==Lr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${f}`);const $=new Map;for(const p of d.fields){const S=Gs(p.name);if(S===void 0)continue;let v=$.get(S.blockId);v===void 0&&(v={id:S.blockId,fields:{}},$.set(S.blockId,v)),v.fields[S.fieldName]=m.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const le=await _r(),pe=gt(le.hash),N=d.fields.find(p=>p.name===pe);let X;N!==void 0?X=m.ensureResourceIdNotNull(N.value):(X=m.Pl.wrapInHolder(e,qe(e,le.spec)),e.createField(m.field(t,gt(le.hash)),"Dynamic",X));const ue={stagingRefreshTimestamp:A},W=new Set(x),M=new Map;for(const p of q){const S=Vs(p.key);S!==void 0&&M.set(S,p.value)}const J=[];$.forEach(({id:p,fields:S})=>{for(const[,v]of Object.entries(S))if(v.ref!==void 0){if(!m.isResource(v.ref)||m.isResourceRef(v.ref))throw new Error("unexpected behaviour");J.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,S]of J){const v=await S;p.value=v.data,m.isNotNullResourceId(v.error)?p.status="Error":v.resourceReady||m.isNotNullResourceId(v.originalResourceId)?p.status="Ready":p.status="NotReady"}const Y=new Map;$.forEach(({id:p,fields:S})=>Y.set(p,new Yt(p,S)));const he=new Set;for(const p of ie(R)){if(!Y.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);he.add(p.id)}Y.forEach(p=>{if(!he.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new Me(t,e,r,f,h,g,R,ue,W,Y,M,X);return y.fixProblemsAndMigrate(),y}}async function So(s,e=Ns){const t=s.createEphemeral(Ds);s.lock(t);const r=String(Date.now());s.setKValue(t,Ar,JSON.stringify(Lr)),s.setKValue(t,Rt,r),s.setKValue(t,ke,r),s.setKValue(t,Oe,JSON.stringify(e)),s.setKValue(t,de,JSON.stringify(As)),s.setKValue(t,Ge,JSON.stringify(Ls));const o=await _r();return s.createField(m.field(t,gt(o.hash)),"Dynamic",m.Pl.wrapInHolder(s,qe(s,o.spec))),t}async function Ne(s,e,t){return ee(s,e,void 0,t)}async function ee(s,e,t,r){if(s instanceof m.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await Me.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await Me.load(s,e,t),n=await r(o);return o.save(),n}}function*bo(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:k.assertNever(s)}}function Qt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function wo(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:Qt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:Qt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(s)}}const Po=m.resourceType("PColumnData/JsonPartitioned","1"),Co=m.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Ro=m.resourceType("PColumnData/BinaryPartitioned","1"),Eo=m.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),ko=m.resourceType("PColumnData/Json","1");function Oo(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(m.resourceTypesEqual(s.resourceType,ko)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(m.resourceTypesEqual(s.resourceType,Po)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Co)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i){const a=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);r[a]=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Ro)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(m.resourceTypesEqual(s.resourceType,Eo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const c of i)if(c.endsWith(".index")){const a=c.slice(0,c.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].index=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else if(c.endsWith(".values")){const a=c.slice(0,c.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);let u=r[l];u===void 0&&(u={},r[l]=u),r[l].values=n.traverse({field:c,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${c}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}throw new Error(`unsupported resource type: ${m.resourceTypeToString(s.resourceType)}`)}function $o(s,e){const t=s.axesSpec.length,r={};for(const{key:o,val:n}of e){if(o.length!==t)throw new Error(`inline column key length ${o.length} differs from axes count ${t}`);r[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:r}}function To(s,e){const t=ae.createHash("sha256");return t.update(ne(s)),t.update(String(m.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function Zt(s,e){return ne({__isRef:!0,blockId:s,name:e})}function Fo(s,e){return ne({resolvePath:s,name:e})}function Kr(s,e=!0,t=!1,r=""){var c,a,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of s.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let f=k.notEmpty((c=d.groups)==null?void 0:c.name);if(!f.startsWith(r)){if(e)throw new Error(`unexpected field name ${u}`);continue}f=f.slice(r.length);const h=k.notEmpty((a=d.groups)==null?void 0:a.type);let g=n.get(f);switch(g===void 0&&(g={},n.set(f,g)),h){case"spec":g.spec=(l=s.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":g.hasData=!0,g.data=()=>s.traverseOrError({field:u,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Io(s,e=!0,t="",r){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const o=Kr(s,e,!1,t);ms(o.locked);const n={};for(const[i,c]of o.results){if(c.spec===void 0)throw new Error(`no spec for key ${i}`);if(c.hasData!==!0||c.data===void 0)throw new Error(`no data for key ${i}`);const a=c.data();if(a===void 0)throw new Error(`no data for key ${i}`);if(!a.ok)throw new Ke.PlError(a.error);n[i]={id:r.length===0?To(c.spec,a.value):Fo(r,i),spec:c.spec,data:a.value}}return n}class $t{constructor(e,t){w(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,c,a,l,u;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:c.spec;if(o!==void 0||(o=(u=(l=(a=r.staging)==null?void 0:a.results)==null?void 0:l.get(t))==null?void 0:u.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,c,a;const r=this.blocks.get(e);if(r===void 0)return;let o=(c=(i=r.prod)==null?void 0:i.results)==null?void 0:c.get(t),n=(a=o==null?void 0:o.data)==null?void 0:a.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return B.mapValueInVOE(n,l=>({id:Zt(e,t),spec:o.spec,data:l}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,c,a)=>{if(a.spec!==void 0&&a.hasData===!0&&a.data!==void 0){const l=a.data();l!==void 0?e.push({ref:Le(i,c),obj:{id:l.ok?Zt(i,c):void 0,spec:a.spec,data:l}}):o(`no_data:${i}:${c}`)}};for(const[i,c]of this.blocks){const a=new Set;if(c.prod!==void 0){c.prod.locked||o(`prod_not_locked:${i}`);for(const[l,u]of c.prod.results)a.add(l),n(i,l,u)}if(c.staging!==void 0){c.staging.locked||o(`staging_not_locked:${i}`);for(const[l,u]of c.staging.results)a.has(l)||n(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const c=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[a,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:Le(n,a),obj:l.spec}),c.add(a))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[a,l]of i.prod.results)c.has(a)||l.spec!==void 0&&e.push({ref:Le(n,a),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[c,a]of i.results)o.has(c)||a.spec===void 0||(o.add(c),B.executePSpecPredicate(e,a.spec)&&t.push({label:r.info.label+" / "+c,ref:Le(r.info.id,c),spec:a.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=k.notEmpty(o.getKeyValueAsJson(de)),c=vt(n).traverseIds("upstream",r),a=new Map;for(const l of ie(n)){if(!c.has(l.id))continue;const u=er(o.traverse({field:G(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:G(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=er(o.traverse({field:G(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:G(l.id,"stagingUiCtx")}));a.set(l.id,{info:l,prod:u,staging:d})}return new $t(e,a)}}function er(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return Kr(e.value,!1,!0)}function Tt(s,e){return{blockId:e,args:n=>k.notEmpty(n.accessor(s).node().traverse({field:G(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(s).node().traverse({field:G(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(s).node().getKeyValueAsString(pt(e)),blockMeta:n=>{const i=n.accessor(s).node(),c=k.notEmpty(i.getKeyValueAsJson(de)),a=new Map;for(const l of ie(c))a.set(l.id,l);return a}}}function Hr(s,e){return{...Tt(s,e),prod:t=>{var r;return(r=t.accessor(s).node({ignoreError:!0}).traverse({field:G(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:r.persist()},staging:t=>{var o;const r=(o=t.accessor(s).node({ignoreError:!0}).traverse({field:G(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return r===void 0&&t.markUnstable("staging_not_rendered"),r},getResultsPool:t=>$t.create(t,s,e)}}function*z(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*z(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*z(t);return;case"MakeArray":for(const t of s.template)yield*z(t);return;case"GetJsonField":case"GetResourceField":yield*z(s.source),yield*z(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*z(s.source),yield*z(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*z(s.source);return;case"IsEmpty":yield*z(s.arg);return;case"Not":yield*z(s.operand);return;case"And":case"Or":yield*z(s.operand1),yield*z(s.operand2);return;default:k.assertNever(s)}}function Ao(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Ce(s,e){return s===void 0?void 0:e(s)}function Lo(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function No(s){for(const e of z(s))if(Lo(e))return!0;return!1}function We(s){return{type:"ReturnResult",result:s}}function O(s){return()=>We(s)}const Do=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return O(e)},Bo=s=>{const e=s.source;if(e===void 0)return O(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return O(t)},jo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?O(void 0):({cCtx:r})=>{var o;return We((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function qr(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function xo(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):()=>({type:"ScheduleSubroutine",subroutine:Wr(r.length),args:qr(r,o=>F({...s,[e.itVar]:o},e.mapping))})}}function Wr(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return O(t)}}function Vo(s,e){return t=>{const r=t.source;if(r===void 0)return O(void 0);const o={};for(const[n,i]of Object.entries(r)){const c={...s,[e.itVar]:i};o[n]=F(c,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Uo,args:o})}}const Uo=s=>O(s),Jo=s=>{const e=s.arg;return O(e===void 0?void 0:e.length===0)},Go=s=>{const e=s.operand;return O(e===void 0?void 0:!e)},Mo=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e&&t)},_o=s=>{const e=s.operand1,t=s.operand2;return O(e===void 0||t===void 0?void 0:e||t)},Ko=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t})=>{var r;return We((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},Ho=s=>{const e=s.source,t=s.field;return O(e===void 0||t===void 0?void 0:e[t])};function qo(s,e){return t=>{const r=t.source;return r===void 0?O(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const c of n.listInputFields()){const a=n.traverse(c);if(a===void 0)i[c]=O(void 0);else{const l={...s,[e.itVar]:a.persist()};i[c]=F(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Wo,args:i}}}}const Wo=s=>O(s),zo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},Xo=s=>{const e=s.source;return e===void 0?O(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Yo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},Qo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Zo=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},en=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.blobToURLDriver.extractArchiveAndGetURL(t,s)})},tn=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},rn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},sn=s=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},on=s=>{const e=s.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function F(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>We(t(r.cCtx)):O(t);case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Yr(r,s,e.cfg)});case"Immediate":return O(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Ho,args:{source:F(s,e.source),field:F(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:xo(s,e),args:{source:F(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Vo(s,e),args:{source:F(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Do,args:Ao(e.template,r=>F(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Wr(e.template.length),args:qr(e.template,r=>F(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:{source:F(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:{arg:F(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:Go,args:{operand:F(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{operand1:F(s,e.operand1),operand2:F(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:qo(s,e),args:{source:F(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:{source:F(s,e.source),field:F(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{source:F(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:zo,args:{source:F(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:F(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:F(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:F(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:F(s,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:en(e.format),args:{source:F(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:tn,args:{source:F(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:rn(e.lines),args:{source:F(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:sn(e.patternToSearch),args:{source:F(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:on,args:{source:F(s,e.source)}});default:return k.assertNever(e)}}const nn=["$prod","$staging"];function an(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 zr=Symbol(),Xr="return",cn={op:zr,arg:Xr};function ln(s){return s.op==zr&&s.arg==Xr}function un(){return{pendingSubroutines:new Map}}function tr(s,e,t,r){const o=new Or(t),n=(c,a)=>{if(ln(c))return e.result=a,!1;const l=k.notEmpty(e.pendingSubroutines.get(c.op));if(c.arg in l.args)throw new Error("argument already set");return l.args[c.arg]=a,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(c.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;o.length>0;){const c=o.shift(),a=c.operation(s);switch(a.type){case"ReturnResult":if(!n(c.destination,a.result))break e;break;case"ScheduleSubroutine":const l=Symbol(),u=Object.entries(a.args),d=u.length;if(d===0)o.push({destination:c.destination,operation:a.subroutine({})});else{for(const[f,h]of u)o.push({destination:{op:l,arg:f},operation:h});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:a.subroutine,destination:c.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:c.destination,computable:a.computable});break;default:k.assertNever(a)}}return i}function dn(s,e,t,r={}){return Yr(s,an(e),t,r)}function Yr(s,e,t,r={}){const o=`${e.blockId}#`+ne({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>nn.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},c=un();return{ir:tr(i,c,[{destination:cn,operation:F(e,t)}],!0),async postprocessValue(l){const u=[];for(const g of l)u.push({destination:g.destination,operation:O(g.computable)});const d={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},f=new Map;for(const[g,R]of c.pendingSubroutines)f.set(g,{...R,args:{...R.args}});const h={result:c.result,pendingSubroutines:f};if(tr(d,h,u,!1),!("result"in h))throw new Error("illegal cfg rendering stack state, no result");return h.result}}},{...r,key:o})}function pn(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function rr(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class _e{constructor(e,t,r,o,n){w(this,"callbackRegistry");w(this,"fnJSONStringify");w(this,"fnJSONParse");w(this,"computablesToResolve",{});w(this,"computableCtx");w(this,"accessors",new Map);w(this,"meta");w(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw _e.cleanErrorContext(t),t}}runCallback(e,...t){try{return Je.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw _e.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return rr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return rr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Io(n,t,r,o),c={};for(const[a,l]of Object.entries(i))c[a]=B.mapPObjectData(l,u=>this.wrapAccessor(u));return c}registerComputable(e,t){const r=`${e}_${ae.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}extractArchiveAndGetURL(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(r,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=k.notEmpty(this.blockCtx.getResultsPool,"getResultsPool")(this.computableCtx)}return this._resultPool}calculateOptions(e){return this.resultPool.calculateOptions(e)}getDataFromResultPool(){const e=this.resultPool.getData();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:B.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:B.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 B.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=>B.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):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(B.mapPTableDef(e,t=>B.mapPObjectData(t,r=>typeof r=="string"?this.getAccessor(r):r)),this.computableCtx)}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=ae.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(pn(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Je.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),r=this.blockCtx.args(this.computableCtx),o=this.blockCtx.activeArgs(this.computableCtx),n=this.blockCtx.uiState(this.computableCtx);this.vm.setProp(t,"args",e.manage(this.vm.newString(r))),n!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(n))),o!==void 0&&this.vm.setProp(t,"activeArgs",e.manage(this.vm.newString(o))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry),this.vm.setProp(t,"featureFlags",this.exportObjectUniversal(B.JsRenderInternal.GlobalCfgRenderCtxFeatureFlags,e));const i=(c,a)=>{this.vm.newFunction(c,a).consume(l=>this.vm.setProp(t,c,l))};i("getAccessorHandleByName",c=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(c)),void 0)),i("resolveWithCommon",(c,a,...l)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(c),this.importObjectViaJson(a),...l.map(u=>this.importObjectViaJson(u))),void 0)),i("getResourceType",c=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(c)),void 0)),i("getInputsLocked",c=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(c)),void 0)),i("getOutputsLocked",c=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(c)),void 0)),i("getIsReadyOrError",c=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(c)),void 0)),i("getIsFinal",c=>this.exportSingleValue(this.getIsFinal(this.vm.getString(c)),void 0)),i("getError",c=>this.exportSingleValue(this.getError(this.vm.getString(c)),void 0)),i("listInputFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("listOutputFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("listDynamicFields",c=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(c)),void 0)),i("getKeyValueBase64",(c,a)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getKeyValueAsString",(c,a)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getDataBase64",c=>this.exportSingleValue(this.getDataBase64(this.vm.getString(c)),void 0)),i("getDataAsString",c=>this.exportSingleValue(this.getDataAsString(this.vm.getString(c)),void 0)),i("parsePObjectCollection",(c,a,l,...u)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(c),this.vm.dump(a),this.vm.getString(l),...u.map(this.vm.getString)),void 0)),i("getBlobContentAsBase64",c=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(c)),void 0)),i("getBlobContentAsString",c=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(c)),void 0)),i("getDownloadedBlobContentHandle",c=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(c)),void 0)),i("getOnDemandBlobContentHandle",c=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(c)),void 0)),i("extractArchiveAndGetURL",(c,a)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getImportProgress",c=>this.exportSingleValue(this.getImportProgress(this.vm.getString(c)),void 0)),i("getLastLogs",(c,a)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(c),this.vm.getNumber(a)),void 0)),i("getProgressLog",(c,a)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getLogHandle",c=>this.exportSingleValue(this.getLogHandle(this.vm.getString(c)),void 0)),i("getBlockLabel",c=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(c)),void 0)),i("getDataFromResultPool",c=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",c=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",c=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",c=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(c)),void 0)),i("getSpecFromResultPoolByRef",(c,a)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(c),this.vm.getString(a)),void 0)),i("getDataFromResultPoolByRef",(c,a)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(c),this.vm.getString(a)),void 0)),i("createPFrame",c=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(c)),void 0)),i("createPTable",c=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(c)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function ze(s,e){return Ce(s.traverse({field:G(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:m.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const r=t.getDataAsJson(),o=B.extractConfig(r.config);return{bpId:t.resourceInfo.id.toString(),info:r,cfg:o}})}const De=process.env.MI_LOG_OUTPUT_STATUS;function hn(s,e,t,r,o,n={}){const i=`${e.blockId}#lambda#${o}#${t.handle}`;return n={...n,key:i},n.mode===void 0&&t.retentive===!0&&(n.mode="StableOnlyRetentive"),j.Computable.makeRaw(c=>{const a=new Je.Scope;c.addOnDestroy(()=>a.dispose());const l=a.manage(s.quickJs.newRuntime());l.setMemoryLimit(1024*640),l.setMaxStackSize(1024*320);const u=a.manage(l.newContext()),d=new _e(a,u,e,s,c);d.evaluateBundle(r.content);const f=d.runCallback(t.handle);d.resetComputableCtx();let h=0;return De&&De!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:async(g,{unstableMarker:R,stable:A})=>{for(const[q,$]of Object.entries(g))d.runCallback(q,$);const x=d.importObjectUniversal(f);return h++,De&&(De!=="unstable-only"||!A)&&console.log(A?`Stable output ${t.handle} calculated ${x!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${R}; ${x!==void 0?"defined":"undefined"} (#${h})`),x}}},n)}function fn(s){return B.isConfigLambda(s)?s.isActive===!0:No(s)}function Re(s,e,t,r,o,n={}){if(B.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return hn(s,e,t,r,o,n)}else return dn(s.driverKit,e,t,n)}function gn(s,e,t){return j.Computable.make(r=>{var g,R,A,x,q,$,le,pe;const o=r.accessor(s).node(),n=k.notEmpty(o.getKeyValueAsJson(Rt)),i=k.notEmpty(o.getKeyValueAsJson(ke)),c=k.notEmpty(o.getKeyValueAsJson(Oe)),a=k.notEmpty(o.getKeyValueAsJson(de)),l=k.notEmpty(o.getKeyValueAsJson(Ge)),u=new Map;for(const{id:N}of ie(a)){const X=o.traverse({field:G(N,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let ue;const W=o.traverse({field:G(N,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(W!==void 0){const M=o.getField({field:G(N,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),J=o.getField({field:G(N,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});ue={arguments:W.getDataAsJson(),stale:X.id!==W.id,outputError:M.error!==void 0||J.error!==void 0||((g=M.value)==null?void 0:g.getError())!==void 0||((R=J.value)==null?void 0:R.getError())!==void 0,outputsError:((A=M.error)==null?void 0:A.getDataAsString())??((q=(x=M.value)==null?void 0:x.getError())==null?void 0:q.getDataAsString()),exportsError:(($=J.error)==null?void 0:$.getDataAsString())??((pe=(le=J.value)==null?void 0:le.getError())==null?void 0:pe.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(J.value!==void 0&&J.value.getIsReadyOrError()||J.error!==void 0&&J.error.getIsReadyOrError())}}u.set(N,{currentArguments:X.getDataAsJson(),prod:ue})}const d=Ue(a,N=>u.get(N).currentArguments),f=new Set(l.blocksInLimbo),h=[...ie(a)].map(({id:N,label:X,renderingMode:ue})=>{var b,C,T,E,L;const W=k.notEmpty(u.get(N)),M=k.notEmpty(d.nodes.get(N));let J="NotCalculated";W.prod!==void 0&&(f.has(N)?J="Limbo":J=W.prod.finished?"Done":"Running");const Y=ze(o,N),{sections:he,title:y,inputsValid:p,sdkVersion:S}=Ce(Y,({bpId:V,cfg:I,info:fe})=>{const rt=Tt(s,N);return{sections:Re(t,rt,I.sections,I.code,V),title:Ce(I.title,ls=>Re(t,rt,ls,I.code,V)),inputsValid:Re(t,rt,I.inputsValid,I.code,V),sdkVersion:I.sdkVersion}})||{},v=o.traverse({field:G(N,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ce(Y,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:v}));return{id:N,label:y??X,title:y??X,renderingMode:ue,stale:((b=W.prod)==null?void 0:b.stale)!==!1||J==="Limbo",missingReference:M.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",N)],downstreams:[...d.traverseIdsExcludingRoots("downstream",N)],calculationStatus:J,outputErrors:((C=W.prod)==null?void 0:C.outputError)===!0,outputsError:(T=W.prod)==null?void 0:T.outputsError,exportsError:(E=W.prod)==null?void 0:E.exportsError,settings:v,sections:he,inputsValid:p,updateInfo:{},currentBlockPack:(L=Y==null?void 0:Y.info)==null?void 0:L.source,updates:P,sdkVersion:S,navigationState:e.getState(N)}});return{meta:c,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ft),blocks:h}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const c=i.stale||i.upstreams.findIndex(f=>n.has(f))!==-1,a=(c||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(f=>o.has(f))===-1,l={...i,canRun:a,stale:c,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function mn(s,e){const t=s.node();if(m.resourceTypesEqual(t.resourceType,kt)){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(m.resourceTypesEqual(t.resourceType,Ot)){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 vn(s,e){if(s!==void 0)return j.Computable.make(t=>mn(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 yn(s,e,t){return j.Computable.make(r=>{var c;const o=r.accessor(s).node(),n=ze(o,e),i=(c=o.traverse({field:G(e,"blockPack"),assertFieldType:"Dynamic"},{field:m.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Gr,assertFieldType:"Input"}))==null?void 0:c.persist();return{path:vn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function Qr(s,e,t){if(t===void 0)return j.Computable.make(i=>Qr(s,e,i),{key:`inputs#${m.resourceIdToString(s.rid)}#${e}`});const r=t.accessor(s).node(),o=Tt(s,e),n=o.uiState(t);return{author:r.getKeyValueAsJson(ht(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function Sn(s,e,t){return j.Computable.make(r=>{const o=r.accessor(s).node(),n=Hr(s,e);return Ce(ze(o,e),({cfg:i,bpId:c})=>{const a={};for(const[l,u]of Object.entries(i.outputs)){const d=Re(t,n,u,i.code,c);a[l]=j.Computable.wrapError(d)}return a})},{key:"outputs#"+m.resourceIdToString(s.rid)+"#"+e}).withStableType()}function bn(s,e){return j.Computable.make(t=>{const r=t.accessor(s).node(),o=k.notEmpty(r.getKeyValueAsJson(de)),n=[];for(const{id:i,renderingMode:c}of ie(o)){const a=ze(r,i);if(a===void 0)continue;const l=Object.entries(a.cfg.outputs).map(([,d])=>d).filter(d=>fn(d)).map(d=>d);if(l.length===0)continue;const u=Hr(r.persist(),i);for(const d of l)n.push(j.Computable.wrapError(Re(e,u,d,a.cfg.code,a.bpId)))}return n})}class wn{constructor(){w(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:{...B.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())}}class Xe{constructor(e,t,r){w(this,"rid");w(this,"overview");w(this,"navigationStates",new wn);w(this,"blockComputables",new Map);w(this,"blockFrontends",new Map);w(this,"activeConfigs");w(this,"refreshLoopResult");w(this,"abortController",new AbortController);w(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=gn(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=bn(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Ne(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await $r.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(m.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!m.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=ae.randomUUID()){const i=await this.env.bpPreparer.prepare(t),c=await this.env.bpPreparer.getBlockConfigContainer(t),a=B.extractConfig(c);return await ee(this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),uiState:JSON.stringify(a.initialUiState),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await ee(this.env.pl,this.rid,o,c=>c.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ee(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ee(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(c=>{const a=n.blocks.find(l=>l.id===c);if(a===void 0)throw new Error(`Can't find block: ${c}`);return a})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Ne(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Ne(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await ee(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await ee(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await ee(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ee(this.env.pl,this.rid,void 0,r=>{r.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=m.ensureResourceIdNotNull((await r.getField(m.field(this.rid,G(e,"blockPack")))).value),n=m.ensureResourceIdNotNull((await r.getField(m.field(o,m.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),c=JSON.parse(Buffer.from(k.notEmpty(i.data)).toString("utf-8"));await ee(r,this.rid,t,a=>{a.setArgs([{blockId:e,args:JSON.stringify(c.config.initialArgs)}]),a.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Sn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:Qr(this.projectTree.entry(),e,i),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,navigationState:i.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=yn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){await Ne(e.pl,t,o=>{});const r=await Ke.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Pn},e.logger);return new Xe(e,t,r)}}function Pn(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}const Ft={logger:new k.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},downloadBlobToURLDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function It(s){return{blobDownloadPath:K.join(s,"download"),downloadBlobToURLPath:K.join(s,"downloadToURL")}}const Zr={...Ft,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function es(s){return{...It(s),frontendDownloadPath:K.join(s,"frontend")}}function Cn(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var St={exports:{}};const Rn="2.0.0",ts=256,En=Number.MAX_SAFE_INTEGER||9007199254740991,kn=16,On=ts-6,$n=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Ye={MAX_LENGTH:ts,MAX_SAFE_COMPONENT_LENGTH:kn,MAX_SAFE_BUILD_LENGTH:On,MAX_SAFE_INTEGER:En,RELEASE_TYPES:$n,SEMVER_SPEC_VERSION:Rn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const Tn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...s)=>console.error("SEMVER",...s):()=>{};var Qe=Tn;(function(s,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:o}=Ye,n=Qe;e=s.exports={};const i=e.re=[],c=e.safeRe=[],a=e.src=[],l=e.t={};let u=0;const d="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",o],[d,r]],h=R=>{for(const[A,x]of f)R=R.split(`${A}*`).join(`${A}{0,${x}}`).split(`${A}+`).join(`${A}{1,${x}}`);return R},g=(R,A,x)=>{const q=h(A),$=u++;n(R,$,A),l[R]=$,a[$]=A,i[$]=new RegExp(A,x?"g":void 0),c[$]=new RegExp(q,x?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),g("MAINVERSION",`(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})\\.(${a[l.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})\\.(${a[l.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${a[l.NUMERICIDENTIFIER]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${a[l.NUMERICIDENTIFIERLOOSE]}|${a[l.NONNUMERICIDENTIFIER]})`),g("PRERELEASE",`(?:-(${a[l.PRERELEASEIDENTIFIER]}(?:\\.${a[l.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${a[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${a[l.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${d}+`),g("BUILD",`(?:\\+(${a[l.BUILDIDENTIFIER]}(?:\\.${a[l.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${a[l.MAINVERSION]}${a[l.PRERELEASE]}?${a[l.BUILD]}?`),g("FULL",`^${a[l.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${a[l.MAINVERSIONLOOSE]}${a[l.PRERELEASELOOSE]}?${a[l.BUILD]}?`),g("LOOSE",`^${a[l.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${a[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${a[l.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:\\.(${a[l.XRANGEIDENTIFIER]})(?:${a[l.PRERELEASE]})?${a[l.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${a[l.XRANGEIDENTIFIERLOOSE]})(?:${a[l.PRERELEASELOOSE]})?${a[l.BUILD]}?)?)?`),g("XRANGE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${a[l.GTLT]}\\s*${a[l.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),g("COERCE",`${a[l.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",a[l.COERCEPLAIN]+`(?:${a[l.PRERELEASE]})?(?:${a[l.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",a[l.COERCE],!0),g("COERCERTLFULL",a[l.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${a[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",g("TILDE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${a[l.LONETILDE]}${a[l.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${a[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",g("CARET",`^${a[l.LONECARET]}${a[l.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${a[l.LONECARET]}${a[l.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${a[l.GTLT]}\\s*(${a[l.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${a[l.GTLT]}\\s*(${a[l.LOOSEPLAIN]}|${a[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${a[l.XRANGEPLAIN]})\\s+-\\s+(${a[l.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${a[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${a[l.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(St,St.exports);var $e=St.exports;const Fn=Object.freeze({loose:!0}),In=Object.freeze({}),An=s=>s?typeof s!="object"?Fn:s:In;var At=An;const sr=/^[0-9]+$/,rs=(s,e)=>{const t=sr.test(s),r=sr.test(e);return t&&r&&(s=+s,e=+e),s===e?0:t&&!r?-1:r&&!t?1:s<e?-1:1},Ln=(s,e)=>rs(e,s);var ss={compareIdentifiers:rs,rcompareIdentifiers:Ln};const Be=Qe,{MAX_LENGTH:or,MAX_SAFE_INTEGER:je}=Ye,{safeRe:nr,t:ir}=$e,Nn=At,{compareIdentifiers:ge}=ss;let Dn=class se{constructor(e,t){if(t=Nn(t),e instanceof se){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>or)throw new TypeError(`version is longer than ${or} characters`);Be("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const r=e.trim().match(t.loose?nr[ir.LOOSE]:nr[ir.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>je||this.major<0)throw new TypeError("Invalid major version");if(this.minor>je||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>je||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<je)return n}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(Be("SemVer.compare",this.version,this.options,e),!(e instanceof se)){if(typeof e=="string"&&e===this.version)return 0;e=new se(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof se||(e=new se(e,this.options)),ge(this.major,e.major)||ge(this.minor,e.minor)||ge(this.patch,e.patch)}comparePre(e){if(e instanceof se||(e=new se(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const r=this.prerelease[t],o=e.prerelease[t];if(Be("prerelease compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}compareBuild(e){e instanceof se||(e=new se(e,this.options));let t=0;do{const r=this.build[t],o=e.build[t];if(Be("build compare",t,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return ge(r,o)}while(++t)}inc(e,t,r){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,r),this.inc("pre",t,r);break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(r)?1:0;if(!t&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];r===!1&&(n=[t]),ge(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};var H=Dn;const ar=H,Bn=(s,e,t=!1)=>{if(s instanceof ar)return s;try{return new ar(s,e)}catch(r){if(!t)return null;throw r}};var ye=Bn;const jn=ye,xn=(s,e)=>{const t=jn(s,e);return t?t.version:null};var Vn=xn;const Un=ye,Jn=(s,e)=>{const t=Un(s.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Gn=Jn;const cr=H,Mn=(s,e,t,r,o)=>{typeof t=="string"&&(o=r,r=t,t=void 0);try{return new cr(s instanceof cr?s.version:s,t).inc(e,r,o).version}catch{return null}};var _n=Mn;const lr=ye,Kn=(s,e)=>{const t=lr(s,null,!0),r=lr(e,null,!0),o=t.compare(r);if(o===0)return null;const n=o>0,i=n?t:r,c=n?r:t,a=!!i.prerelease.length;if(!!c.prerelease.length&&!a)return!c.patch&&!c.minor?"major":i.patch?"patch":i.minor?"minor":"major";const u=a?"pre":"";return t.major!==r.major?u+"major":t.minor!==r.minor?u+"minor":t.patch!==r.patch?u+"patch":"prerelease"};var Hn=Kn;const qn=H,Wn=(s,e)=>new qn(s,e).major;var zn=Wn;const Xn=H,Yn=(s,e)=>new Xn(s,e).minor;var Qn=Yn;const Zn=H,ei=(s,e)=>new Zn(s,e).patch;var ti=ei;const ri=ye,si=(s,e)=>{const t=ri(s,e);return t&&t.prerelease.length?t.prerelease:null};var oi=si;const ur=H,ni=(s,e,t)=>new ur(s,t).compare(new ur(e,t));var te=ni;const ii=te,ai=(s,e,t)=>ii(e,s,t);var ci=ai;const li=te,ui=(s,e)=>li(s,e,!0);var di=ui;const dr=H,pi=(s,e,t)=>{const r=new dr(s,t),o=new dr(e,t);return r.compare(o)||r.compareBuild(o)};var Lt=pi;const hi=Lt,fi=(s,e)=>s.sort((t,r)=>hi(t,r,e));var gi=fi;const mi=Lt,vi=(s,e)=>s.sort((t,r)=>mi(r,t,e));var yi=vi;const Si=te,bi=(s,e,t)=>Si(s,e,t)>0;var Ze=bi;const wi=te,Pi=(s,e,t)=>wi(s,e,t)<0;var Nt=Pi;const Ci=te,Ri=(s,e,t)=>Ci(s,e,t)===0;var os=Ri;const Ei=te,ki=(s,e,t)=>Ei(s,e,t)!==0;var ns=ki;const Oi=te,$i=(s,e,t)=>Oi(s,e,t)>=0;var Dt=$i;const Ti=te,Fi=(s,e,t)=>Ti(s,e,t)<=0;var Bt=Fi;const Ii=os,Ai=ns,Li=Ze,Ni=Dt,Di=Nt,Bi=Bt,ji=(s,e,t,r)=>{switch(e){case"===":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s===t;case"!==":return typeof s=="object"&&(s=s.version),typeof t=="object"&&(t=t.version),s!==t;case"":case"=":case"==":return Ii(s,t,r);case"!=":return Ai(s,t,r);case">":return Li(s,t,r);case">=":return Ni(s,t,r);case"<":return Di(s,t,r);case"<=":return Bi(s,t,r);default:throw new TypeError(`Invalid operator: ${e}`)}};var is=ji;const xi=H,Vi=ye,{safeRe:xe,t:Ve}=$e,Ui=(s,e)=>{if(s instanceof xi)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;e=e||{};let t=null;if(!e.rtl)t=s.match(e.includePrerelease?xe[Ve.COERCEFULL]:xe[Ve.COERCE]);else{const a=e.includePrerelease?xe[Ve.COERCERTLFULL]:xe[Ve.COERCERTL];let l;for(;(l=a.exec(s))&&(!t||t.index+t[0].length!==s.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),a.lastIndex=l.index+l[1].length+l[2].length;a.lastIndex=-1}if(t===null)return null;const r=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",c=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Vi(`${r}.${o}.${n}${i}${c}`,e)};var Ji=Ui;class Gi{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){const o=this.map.keys().next().value;this.delete(o)}this.map.set(e,t)}return this}}var Mi=Gi,it,pr;function re(){if(pr)return it;pr=1;const s=/\s+/g;class e{constructor(p,S){if(S=o(S),p instanceof e)return p.loose===!!S.loose&&p.includePrerelease===!!S.includePrerelease?p:new e(p.raw,S);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=S,this.loose=!!S.loose,this.includePrerelease=!!S.includePrerelease,this.raw=p.trim().replace(s," "),this.set=this.raw.split("||").map(v=>this.parseRange(v.trim())).filter(v=>v.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const v=this.set[0];if(this.set=this.set.filter(P=>!R(P[0])),this.set.length===0)this.set=[v];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&A(P[0])){this.set=[P];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let p=0;p<this.set.length;p++){p>0&&(this.formatted+="||");const S=this.set[p];for(let v=0;v<S.length;v++)v>0&&(this.formatted+=" "),this.formatted+=S[v].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const v=((this.options.includePrerelease&&h)|(this.options.loose&&g))+":"+p,P=r.get(v);if(P)return P;const b=this.options.loose,C=b?a[l.HYPHENRANGELOOSE]:a[l.HYPHENRANGE];p=p.replace(C,Y(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(a[l.COMPARATORTRIM],u),i("comparator trim",p),p=p.replace(a[l.TILDETRIM],d),i("tilde trim",p),p=p.replace(a[l.CARETTRIM],f),i("caret trim",p);let T=p.split(" ").map(I=>q(I,this.options)).join(" ").split(/\s+/).map(I=>J(I,this.options));b&&(T=T.filter(I=>(i("loose invalid filter",I,this.options),!!I.match(a[l.COMPARATORLOOSE])))),i("range list",T);const E=new Map,L=T.map(I=>new n(I,this.options));for(const I of L){if(R(I))return[I];E.set(I.value,I)}E.size>1&&E.has("")&&E.delete("");const V=[...E.values()];return r.set(v,V),V}intersects(p,S){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(v=>x(v,S)&&p.set.some(P=>x(P,S)&&v.every(b=>P.every(C=>b.intersects(C,S)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new c(p,this.options)}catch{return!1}for(let S=0;S<this.set.length;S++)if(he(this.set[S],p,this.options))return!0;return!1}}it=e;const t=Mi,r=new t,o=At,n=et(),i=Qe,c=H,{safeRe:a,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=$e,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:g}=Ye,R=y=>y.value==="<0.0.0-0",A=y=>y.value==="",x=(y,p)=>{let S=!0;const v=y.slice();let P=v.pop();for(;S&&v.length;)S=v.every(b=>P.intersects(b,p)),P=v.pop();return S},q=(y,p)=>(i("comp",y,p),y=N(y,p),i("caret",y),y=le(y,p),i("tildes",y),y=ue(y,p),i("xrange",y),y=M(y,p),i("stars",y),y),$=y=>!y||y.toLowerCase()==="x"||y==="*",le=(y,p)=>y.trim().split(/\s+/).map(S=>pe(S,p)).join(" "),pe=(y,p)=>{const S=p.loose?a[l.TILDELOOSE]:a[l.TILDE];return y.replace(S,(v,P,b,C,T)=>{i("tilde",y,v,P,b,C,T);let E;return $(P)?E="":$(b)?E=`>=${P}.0.0 <${+P+1}.0.0-0`:$(C)?E=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:T?(i("replaceTilde pr",T),E=`>=${P}.${b}.${C}-${T} <${P}.${+b+1}.0-0`):E=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",E),E})},N=(y,p)=>y.trim().split(/\s+/).map(S=>X(S,p)).join(" "),X=(y,p)=>{i("caret",y,p);const S=p.loose?a[l.CARETLOOSE]:a[l.CARET],v=p.includePrerelease?"-0":"";return y.replace(S,(P,b,C,T,E)=>{i("caret",y,P,b,C,T,E);let L;return $(b)?L="":$(C)?L=`>=${b}.0.0${v} <${+b+1}.0.0-0`:$(T)?b==="0"?L=`>=${b}.${C}.0${v} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.0${v} <${+b+1}.0.0-0`:E?(i("replaceCaret pr",E),b==="0"?C==="0"?L=`>=${b}.${C}.${T}-${E} <${b}.${C}.${+T+1}-0`:L=`>=${b}.${C}.${T}-${E} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${T}-${E} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?L=`>=${b}.${C}.${T}${v} <${b}.${C}.${+T+1}-0`:L=`>=${b}.${C}.${T}${v} <${b}.${+C+1}.0-0`:L=`>=${b}.${C}.${T} <${+b+1}.0.0-0`),i("caret return",L),L})},ue=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(S=>W(S,p)).join(" ")),W=(y,p)=>{y=y.trim();const S=p.loose?a[l.XRANGELOOSE]:a[l.XRANGE];return y.replace(S,(v,P,b,C,T,E)=>{i("xRange",y,v,P,b,C,T,E);const L=$(b),V=L||$(C),I=V||$(T),fe=I;return P==="="&&fe&&(P=""),E=p.includePrerelease?"-0":"",L?P===">"||P==="<"?v="<0.0.0-0":v="*":P&&fe?(V&&(C=0),T=0,P===">"?(P=">=",V?(b=+b+1,C=0,T=0):(C=+C+1,T=0)):P==="<="&&(P="<",V?b=+b+1:C=+C+1),P==="<"&&(E="-0"),v=`${P+b}.${C}.${T}${E}`):V?v=`>=${b}.0.0${E} <${+b+1}.0.0-0`:I&&(v=`>=${b}.${C}.0${E} <${b}.${+C+1}.0-0`),i("xRange return",v),v})},M=(y,p)=>(i("replaceStars",y,p),y.trim().replace(a[l.STAR],"")),J=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(a[p.includePrerelease?l.GTE0PRE:l.GTE0],"")),Y=y=>(p,S,v,P,b,C,T,E,L,V,I,fe)=>($(v)?S="":$(P)?S=`>=${v}.0.0${y?"-0":""}`:$(b)?S=`>=${v}.${P}.0${y?"-0":""}`:C?S=`>=${S}`:S=`>=${S}${y?"-0":""}`,$(L)?E="":$(V)?E=`<${+L+1}.0.0-0`:$(I)?E=`<${L}.${+V+1}.0-0`:fe?E=`<=${L}.${V}.${I}-${fe}`:y?E=`<${L}.${V}.${+I+1}-0`:E=`<=${E}`,`${S} ${E}`.trim()),he=(y,p,S)=>{for(let v=0;v<y.length;v++)if(!y[v].test(p))return!1;if(p.prerelease.length&&!S.includePrerelease){for(let v=0;v<y.length;v++)if(i(y[v].semver),y[v].semver!==n.ANY&&y[v].semver.prerelease.length>0){const P=y[v].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return it}var at,hr;function et(){if(hr)return at;hr=1;const s=Symbol("SemVer ANY");class e{static get ANY(){return s}constructor(u,d){if(d=t(d),u instanceof e){if(u.loose===!!d.loose)return u;u=u.value}u=u.trim().split(/\s+/).join(" "),i("comparator",u,d),this.options=d,this.loose=!!d.loose,this.parse(u),this.semver===s?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?r[o.COMPARATORLOOSE]:r[o.COMPARATOR],f=u.match(d);if(!f)throw new TypeError(`Invalid comparator: ${u}`);this.operator=f[1]!==void 0?f[1]:"",this.operator==="="&&(this.operator=""),f[2]?this.semver=new c(f[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 c(u,this.options)}catch{return!1}return n(u,this.operator,this.semver,this.options)}intersects(u,d){if(!(u instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new a(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new a(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||n(this.semver,"<",u.semver,d)&&this.operator.startsWith(">")&&u.operator.startsWith("<")||n(this.semver,">",u.semver,d)&&this.operator.startsWith("<")&&u.operator.startsWith(">")))}}at=e;const t=At,{safeRe:r,t:o}=$e,n=is,i=Qe,c=H,a=re();return at}const _i=re(),Ki=(s,e,t)=>{try{e=new _i(e,t)}catch{return!1}return e.test(s)};var tt=Ki;const Hi=re(),qi=(s,e)=>new Hi(s,e).set.map(t=>t.map(r=>r.value).join(" ").trim().split(" "));var Wi=qi;const zi=H,Xi=re(),Yi=(s,e,t)=>{let r=null,o=null,n=null;try{n=new Xi(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===-1)&&(r=i,o=new zi(r,t))}),r};var Qi=Yi;const Zi=H,ea=re(),ta=(s,e,t)=>{let r=null,o=null,n=null;try{n=new ea(e,t)}catch{return null}return s.forEach(i=>{n.test(i)&&(!r||o.compare(i)===1)&&(r=i,o=new Zi(r,t))}),r};var ra=ta;const ct=H,sa=re(),fr=Ze,oa=(s,e)=>{s=new sa(s,e);let t=new ct("0.0.0");if(s.test(t)||(t=new ct("0.0.0-0"),s.test(t)))return t;t=null;for(let r=0;r<s.set.length;++r){const o=s.set[r];let n=null;o.forEach(i=>{const c=new ct(i.semver.version);switch(i.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!n||fr(c,n))&&(n=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||fr(t,n))&&(t=n)}return t&&s.test(t)?t:null};var na=oa;const ia=re(),aa=(s,e)=>{try{return new ia(s,e).range||"*"}catch{return null}};var ca=aa;const la=H,as=et(),{ANY:ua}=as,da=re(),pa=tt,gr=Ze,mr=Nt,ha=Bt,fa=Dt,ga=(s,e,t,r)=>{s=new la(s,r),e=new da(e,r);let o,n,i,c,a;switch(t){case">":o=gr,n=ha,i=mr,c=">",a=">=";break;case"<":o=mr,n=fa,i=gr,c="<",a="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(pa(s,e,r))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,f=null;if(u.forEach(h=>{h.semver===ua&&(h=new as(">=0.0.0")),d=d||h,f=f||h,o(h.semver,d.semver,r)?d=h:i(h.semver,f.semver,r)&&(f=h)}),d.operator===c||d.operator===a||(!f.operator||f.operator===c)&&n(s,f.semver))return!1;if(f.operator===a&&i(s,f.semver))return!1}return!0};var jt=ga;const ma=jt,va=(s,e,t)=>ma(s,e,">",t);var ya=va;const Sa=jt,ba=(s,e,t)=>Sa(s,e,"<",t);var wa=ba;const vr=re(),Pa=(s,e,t)=>(s=new vr(s,t),e=new vr(e,t),s.intersects(e,t));var Ca=Pa;const Ra=tt,Ea=te;var ka=(s,e,t)=>{const r=[];let o=null,n=null;const i=s.sort((u,d)=>Ea(u,d,t));for(const u of i)Ra(u,e,t)?(n=u,o||(o=u)):(n&&r.push([o,n]),n=null,o=null);o&&r.push([o,null]);const c=[];for(const[u,d]of r)u===d?c.push(u):!d&&u===i[0]?c.push("*"):d?u===i[0]?c.push(`<=${d}`):c.push(`${u} - ${d}`):c.push(`>=${u}`);const a=c.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return a.length<l.length?a:e};const yr=re(),xt=et(),{ANY:lt}=xt,Se=tt,Vt=te,Oa=(s,e,t={})=>{if(s===e)return!0;s=new yr(s,t),e=new yr(e,t);let r=!1;e:for(const o of s.set){for(const n of e.set){const i=Ta(o,n,t);if(r=r||i!==null,i)continue e}if(r)return!1}return!0},$a=[new xt(">=0.0.0-0")],Sr=[new xt(">=0.0.0")],Ta=(s,e,t)=>{if(s===e)return!0;if(s.length===1&&s[0].semver===lt){if(e.length===1&&e[0].semver===lt)return!0;t.includePrerelease?s=$a:s=Sr}if(e.length===1&&e[0].semver===lt){if(t.includePrerelease)return!0;e=Sr}const r=new Set;let o,n;for(const h of s)h.operator===">"||h.operator===">="?o=br(o,h,t):h.operator==="<"||h.operator==="<="?n=wr(n,h,t):r.add(h.semver);if(r.size>1)return null;let i;if(o&&n){if(i=Vt(o.semver,n.semver,t),i>0)return null;if(i===0&&(o.operator!==">="||n.operator!=="<="))return null}for(const h of r){if(o&&!Se(h,String(o),t)||n&&!Se(h,String(n),t))return null;for(const g of e)if(!Se(h,String(g),t))return!1;return!0}let c,a,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,f=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const h of e){if(u=u||h.operator===">"||h.operator===">=",l=l||h.operator==="<"||h.operator==="<=",o){if(f&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===f.major&&h.semver.minor===f.minor&&h.semver.patch===f.patch&&(f=!1),h.operator===">"||h.operator===">="){if(c=br(o,h,t),c===h&&c!==o)return!1}else if(o.operator===">="&&!Se(o.semver,String(h),t))return!1}if(n){if(d&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===d.major&&h.semver.minor===d.minor&&h.semver.patch===d.patch&&(d=!1),h.operator==="<"||h.operator==="<="){if(a=wr(n,h,t),a===h&&a!==n)return!1}else if(n.operator==="<="&&!Se(n.semver,String(h),t))return!1}if(!h.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||f||d)},br=(s,e,t)=>{if(!s)return e;const r=Vt(s.semver,e.semver,t);return r>0?s:r<0||e.operator===">"&&s.operator===">="?e:s},wr=(s,e,t)=>{if(!s)return e;const r=Vt(s.semver,e.semver,t);return r<0?s:r>0||e.operator==="<"&&s.operator==="<="?e:s};var Fa=Oa;const ut=$e,Pr=Ye,Ia=H,Cr=ss,Aa=ye,La=Vn,Na=Gn,Da=_n,Ba=Hn,ja=zn,xa=Qn,Va=ti,Ua=oi,Ja=te,Ga=ci,Ma=di,_a=Lt,Ka=gi,Ha=yi,qa=Ze,Wa=Nt,za=os,Xa=ns,Ya=Dt,Qa=Bt,Za=is,ec=Ji,tc=et(),rc=re(),sc=tt,oc=Wi,nc=Qi,ic=ra,ac=na,cc=ca,lc=jt,uc=ya,dc=wa,pc=Ca,hc=ka,fc=Fa;var gc={parse:Aa,valid:La,clean:Na,inc:Da,diff:Ba,major:ja,minor:xa,patch:Va,prerelease:Ua,compare:Ja,rcompare:Ga,compareLoose:Ma,compareBuild:_a,sort:Ka,rsort:Ha,gt:qa,lt:Wa,eq:za,neq:Xa,gte:Ya,lte:Qa,cmp:Za,coerce:ec,Comparator:tc,Range:rc,satisfies:sc,toComparators:oc,maxSatisfying:nc,minSatisfying:ic,minVersion:ac,validRange:cc,outside:lc,gtr:uc,ltr:dc,intersects:pc,simplifyRange:hc,subset:fc,SemVer:Ia,re:ut.re,src:ut.src,tokens:ut.t,SEMVER_SPEC_VERSION:Pr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Pr.RELEASE_TYPES,compareIdentifiers:Cr.compareIdentifiers,rcompareIdentifiers:Cr.rcompareIdentifiers};const mc=Cn(gc),vc={minDelay:1500},yc="__no_updates__";class Sc extends j.PollComputablePool{constructor(t,r,o={}){super({...o,...vc},r);w(this,"http");w(this,"preferredUpdateChannel");this.registryProvider=t,this.http=o.http,this.preferredUpdateChannel=o.preferredUpdateChannel}getKey(t){switch(t.currentSpec.type){case"dev-v1":return`dev_1_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"dev-v2":return`dev_2_${t.currentSpec.folder}_${t.currentSpec.mtime}`;case"from-registry-v2":return`from_registry_v2_${ne(t)}`;default:return yc}}async readValue(t){var r,o;try{const n=t.currentSpec;switch(n.type){case"dev-v1":try{const i=await Ct(n.folder);return i===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:i},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"dev-v2":try{const i=await _.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const c=await He(i);return c===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:c},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:c}=t.settings;if(i==="patch")return{suggestions:[]};const a=this.registryProvider.getRegistry(n.registryUrl);let l,u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await a.getLatestOverview(n.id,U.StableChannel))u=U.StableChannel;else{if(await a.getLatestOverview(n.id,U.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${U.blockPackIdToString(n.id)}`),{suggestions:[]};u=U.AnyChannel}else u=n.channel;const d=await a.getUpdateSuggestions(n.id,u);if(d===void 0||d.length===0)return{suggestions:[]};d.reverse();let f;switch(i){case void 0:f=d[0].update;break;case"major":f=(r=d.find(R=>R.type!=="major"))==null?void 0:r.update;break;case"minor":f=(o=d.find(R=>R.type==="patch"))==null?void 0:o.update;break}const h=d.map(({type:R,update:A})=>({type:R,update:{...n,id:{...n.id,version:A}}}));if(f===void 0)return{suggestions:h};if(c!==void 0&&mc.lte(f,c))return{suggestions:h};const g={...n,id:{...n.id,version:f}};return(async()=>{try{await a.getComponents(g.id)}catch(R){this.logger.warn(R)}})(),{suggestions:h,mainSuggestion:g}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,r){return ne(t)===ne(r)}}class Rr{constructor(){w(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}let be;function oe(){return be||(be={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,usePFrameRs:process.env.MI_USE_PFRAMES_RS!==void 0},process.env.MI_LOG_TREE_STAT&&(be.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),be)}function Er(s){return String(s.id)}const bc=["Int","Long","Float","Double","String","Bytes"];function dt(s){const e=[],t=[];for(const r of s)r.type==="bySingleColumn"?(e.push(r),t.push({...r,type:"bySingleColumnV2"})):t.push(r);if(e.length>0){const r=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${r}`)}return s}const we=(s,e)=>typeof e=="bigint"?e.toString():e;class wc{constructor(e,t,r,o){w(this,"specPFrame");w(this,"blobIdToResource",new Map);w(this,"blobHandleComputables",new Map);w(this,"createDataPFrame");w(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});w(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});w(this,"resolveBlobContent",async e=>{try{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)}catch(t){const r=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${r}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=r,this.columns=o;const n=(a,l)=>{switch(a){default:case"info":return this.logger.info(l);case"warn":return this.logger.warn(l);case"error":return this.logger.error(l)}};for(const a of o)for(const l of bo(a.data))this.blobIdToResource.set(Er(l),l);const i=()=>{if(oe().usePFrameRs){const a=new vs.PFrame(oe().logPFrameRequests?n:void 0);for(const l of o)a.addColumnSpec(l.id,l.spec);return a}else{const a=oe().logPFrameRequests?new Ie.PFrame(n):new Ie.PFrame;for(const l of o)try{a.addColumnSpec(l.id,l.spec)}catch(u){throw new Error(`Adding column ${l.id} to PFrame failed: ${u}; Spec: ${JSON.stringify(l.spec)}.`)}return a}},c=()=>{const a=oe().logPFrameRequests?new Ie.PFrame(n):new Ie.PFrame;a.setDataSource(this);for(const l of o){const u=wo(l.data,Er);try{a.addColumnSpec(l.id,l.spec),a.setColumnData(l.id,u)}catch(d){throw new Error(`Adding column ${l.id} to PFrame failed: ${d}; Spec: ${JSON.stringify(l.spec)}, DataInfo: ${JSON.stringify(u)}.`)}}return a};this.specPFrame=i(),this.createDataPFrame=c}get disposableDataPFrame(){const e=this.createDataPFrame();return{dataPFrame:e,[Symbol.dispose]:()=>{e.dispose()}}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.specPFrame.dispose()}}class Pc{constructor(e,t){w(this,"pFrames");w(this,"pTables");w(this,"blobContentCache");w(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const r=new ys.LRUCache({maxSize:1e9,fetchMethod:async n=>await Tr.readFile(n),sizeCalculation:n=>n.length}),o=new k.ConcurrencyLimitingExecutor(1);this.blobContentCache=r,this.concurrencyLimiter=o,this.pFrames=new class extends Rr{constructor(n,i){super(),this.blobDriver=n,this.logger=i}createNewResource(n){return oe().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`),new wc(this.blobDriver,this.logger,r,n)}calculateParamsKey(n){return Rc(n)}}(this.blobDriver,this.logger),this.pTables=new class extends Rr{constructor(n){super(),this.pFrames=n}async createNewResource(n){const i=n.pFrameHandle,c=await o.run(async()=>{var l=[];try{oe().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,we)}`);const a=Te(l,this.pFrames.getByKey(i).disposableDataPFrame);return await a.dataPFrame.createTable({src:Ee(n.def.src),filters:dt(n.def.filters)})}catch(u){var d=u,f=!0}finally{Fe(l,d,f)}});return n.def.sorting.length!==0?c.sort(n.def.sorting):c}calculateParamsKey(n){return Cc(n)}}(this.pFrames)}createPFrame(e,t){const r=e.filter(n=>bc.find(i=>i===n.spec.valueType)).map(n=>B.mapPObjectData(n,i=>Ke.isPlTreeNodeAccessor(i)?Oo(i):$o(n.spec,i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(B.extractAllColumns(e.src),t),o=B.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return oe().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${r}; pTableHandle = ${JSON.stringify(n)}): ${JSON.stringify(B.mapPTableDef(e,i=>i.spec),we)}`),t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[ne(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.findColumns(r))).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(c=>c.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).specPFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>{var c=[];try{oe().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,we)}`);const i=Te(c,this.pFrames.getByKey(e).disposableDataPFrame);return await i.dataPFrame.createTable({src:Ee(t.src),filters:dt(t.filters)})}catch(a){var l=a,u=!0}finally{Fe(c,l,u)}});if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,c)=>({spec:i,data:n[c]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>{var o=[];try{oe().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,we)}`);const r=Te(o,this.pFrames.getByKey(e).disposableDataPFrame);return await r.dataPFrame.getUniqueValues({...t,filters:dt(t.filters)})}catch(n){var i=n,c=!0}finally{Fe(o,i,c)}})}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function Ee(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Ee(e))};case"outer":return{type:"outer",primary:Ee(s.primary),secondary:s.secondary.map(e=>Ee(e))};default:k.assertNever(s)}}function Cc(s){const e=ae.createHash("sha256");return e.update(ne(s)),e.digest().toString("hex")}function Rc(s){const e=[...s].map(r=>B.mapPObjectData(r,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([c,a])=>({key:c,value:a}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:a.id.toString()}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([c,a])=>({key:c,value:[a.index.id.toString(),a.values.id.toString()]}))};break;default:throw Error(`unsupported resource type: ${i}`)}return n.payload.sort((c,a)=>c.key.localeCompare(a.key)),n}));e.sort((r,o)=>r.id.localeCompare(o.id));const t=ae.createHash("sha256");return t.update(ne(e)),t.digest().toString("hex")}async function cs(s,e,t){const r={...Ft,...It(e),...t},o=new k.HmacSha256Signer(r.localSecret),n=Z.createDownloadClient(r.logger,s,r.localProjections),i=Z.createLogsClient(s,r.logger),c=Z.createUploadBlobClient(s,r.logger),a=Z.createUploadProgressClient(s,r.logger),l=new Z.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),u=new Z.DownloadBlobToURLDriver(r.logger,o,n,r.downloadBlobToURLPath,r.downloadBlobToURLDriverOps),d=new Z.UploadDriver(r.logger,o,c,a,r.uploadDriverOps),f=new Z.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),h=new Z.LogsDriver(r.logger,f,l),g=await Z.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),R=new Pc(l,r.logger);return{blobDriver:l,blobToURLDriver:u,logDriver:h,lsDriver:g,signer:o,uploadDriver:d,pFrameDriver:R}}class Ut{constructor(e,t,r,o,n,i,c,a){w(this,"pl");w(this,"projectList");w(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=c,this.projectList=a,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ae.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await So(o,e);return o.createField(m.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await m.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await ee(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(m.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(m.field(this.projectListResourceId,e))).value;if(m.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 Xe.init(this.env,t)),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}async closeProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);this.openedProjectsByRid.delete(e),await t.destroy(),this.openedProjectsList.setValue([...this.openedProjectsByRid.keys()])}getOpenedProject(e){const t=this.openedProjectsByRid.get(e);if(t===void 0)throw new Error(`Project ${e} not found among opened projects`);return t}async close(){await Promise.all([...this.openedProjectsByRid.values()].map(e=>e.destroy())),await this.projectListTree.terminate(),await this.env.retryHttpDispatcher.destroy(),await this.pl.close()}async closeAndAwaitTermination(){await this.close()}static generateLocalSecret(){return k.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...Zr,...es(t),...r};o.defaultTreeOptions.logStat=oe().logTreeStats;const n=await e.withWriteTx("MLInitialization",async R=>{const A=m.field(R.clientRoot,Ms);R.createField(A,"Dynamic");const x=await R.getField(A);if(m.isNullResourceId(x.value)){const q=R.createEphemeral(Nr);return R.lock(q),R.setField(A,q),await R.commit(),await q.globalId}else return x.value}),i=o.logger,c=await cs(e,t,o),a=new ce.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Ir(a),u=new po(l,c.signer,a),d=new Z.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),f={pl:e,signer:c.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:a,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:c,blockUpdateWatcher:new Sc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:a,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Je.getQuickJS()},h=new j.WatchableValue([]),g=await Ks(e,n,h,f);return new Ut(f,c,c.signer,n,h,g.tree,l,g.computable)}}const Ec=["undici:request:create","undici:request:bodySent","undici:request:headers","undici:request:error","undici:request:trailers","undici:client:sendHeaders","undici:client:beforeConnect","undici:client:connected","undici:client:connectError","undici:socket:close","undici:socket:connect","undici:socket:error","undici:pool:request","undici:pool:connect","undici:pool:disconnect","undici:pool:destroy","undici:dispatcher:request","undici:dispatcher:connect","undici:dispatcher:disconnect","undici:dispatcher:retry"];async function kc(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:3e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science",blockGARegistryUrl:"https://blocks-ga.pl-open.science",blockOverviewPath:"v2/overview.json",blockUiPath:"v2/milaboratories/samples-and-data/1.7.0/ui.tgz",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",bodyLimit:300,...e},r=[];Ec.forEach(a=>{Ss.channel(a).subscribe(u=>{var f;const d=new Date().toISOString();(f=u==null?void 0:u.response)!=null&&f.headers&&(u.response.headers=u.response.headers.map(h=>h.toString())),r.push(JSON.stringify({timestamp:d,event:a,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=m.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await me(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new m.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const c=new m.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,c)),o.blockGARegistryOverviewChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,c)),o.blockRegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockRegistryUrl),t,c)),o.blockGARegistryUiChecks=await me(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Pe(new URL(t.blockUiPath,t.blockGARegistryUrl),t,c)),o.autoUpdateCdnChecks=await me(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Pe(t.autoUpdateCdnUrl,t,c)),Oc(o,s,t,r)}async function me(s,e,t){const r=bt(),o=[];for(;kr(r)<s;){const n=bt();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const c=kr(n);o.push({elapsedMs:c,response:i});const a=1e3/e-c;a>0&&await $r.setTimeout(a)}return o}async function Pe(s,e,t){const{body:r,statusCode:o}=await ce.request(s,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await r.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Oc(s,e,t,r){const o=s.plPings.filter(c=>c.response.ok),n=s.plPings.filter(c=>!c.response.ok),i=[...new Set(o.map(c=>JSON.stringify(c.response.value)))];return`
|
|
2
2
|
Network report:
|
|
3
3
|
pl endpoint: ${e};
|
|
4
4
|
options: ${JSON.stringify(t,null,2)}.
|
|
@@ -39,11 +39,11 @@ ${JSON.stringify(i,null,2)}
|
|
|
39
39
|
Undici logs:
|
|
40
40
|
${r.join(`
|
|
41
41
|
`)}
|
|
42
|
-
`}function ve(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}
|
|
42
|
+
`}function ve(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=$c(s);return`
|
|
43
43
|
total: ${s.length};
|
|
44
44
|
successes: ${e.length};
|
|
45
45
|
errors: ${s.length-e.length};
|
|
46
46
|
mean in ms: ${t};
|
|
47
47
|
median in ms: ${r};
|
|
48
|
-
`}function
|
|
48
|
+
`}function $c(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function bt(){return Date.now()}function kr(s){return bt()-s}exports.BlockPackRegistry=$s;exports.CentralBlockRegistry=Ts;exports.DefaultDriverKitOpsPaths=It;exports.DefaultDriverKitOpsSettings=Ft;exports.DefaultMiddleLayerOpsPaths=es;exports.DefaultMiddleLayerOpsSettings=Zr;exports.FrontendFromFolderResourceType=Ot;exports.FrontendFromUrlResourceType=kt;exports.MiddleLayer=Ut;exports.Project=Xe;exports.TengoTemplateGet=Br;exports.TengoTemplateGetRegistry=jr;exports.TengoTemplateGetTemplate=Vr;exports.TengoTemplateGetTemplateURI=xr;exports.TengoTemplatePack=oo;exports.TengoTemplatePackConvert=no;exports.TengoTemplatePackConvertTemplate=ao;exports.TengoTemplatePackConvertTemplatePack=io;exports.V1CentralDevSnapshotRegistry=Is;exports.V1CentralRegistry=Fs;exports.V2RegistryProvider=Ir;exports.checkNetwork=kc;exports.createRenderTemplate=Et;exports.getDevV1PacketMtime=Ct;exports.getDevV2PacketMtime=He;exports.initDriverKit=cs;exports.loadTemplate=qe;exports.prepareTemplateSpec=Ur;Object.keys(B).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>B[s]})});Object.keys(U).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>U[s]})});Object.keys(m).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>m[s]})});
|
|
49
49
|
//# sourceMappingURL=index.js.map
|