@milaboratories/pl-middle-layer 1.28.18 → 1.28.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1225 -1209
- package/dist/index.mjs.map +1 -1
- package/dist/pool/driver.d.ts.map +1 -1
- package/package.json +8 -8
- package/src/pool/driver.ts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ps=Object.defineProperty;var Ut=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Gt=r=>{throw TypeError(r)};var hs=(r,e,t)=>e in r?ps(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>hs(r,typeof e!="symbol"?e+"":e,t);var Ie=(r,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Gt("Object expected");var s;t&&(s=e[Ut("asyncDispose")]),s===void 0&&(s=e[Ut("dispose")]),typeof s!="function"&&Gt("Object not disposable"),r.push([t,s,e])}else t&&r.push([t]);return e},Ae=(r,e,t)=>{var s=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,l){return l=Error(c),l.name="SuppressedError",l.error=i,l.suppressed=a,l},o=i=>e=t?new s(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=r.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}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"),Jt=require("@milaboratories/pl-deployments"),le=require("undici"),_=require("@platforma-sdk/block-tools"),Q=require("node:fs"),K=require("node:path"),fs=require("yaml"),E=require("@milaboratories/ts-helpers"),gs=require("node:fs/promises"),ms=require("@milaboratories/resolve-helper"),g=require("@milaboratories/pl-client"),He=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ae=require("node:crypto"),N=require("@milaboratories/pl-model-backend"),Tr=require("denque"),vs=require("@platforma-sdk/workflow-tengo"),te=require("canonicalize"),ys=require("node:assert"),Je=require("quickjs-emscripten"),Fr=require("node:timers/promises"),Z=require("@milaboratories/pl-drivers"),Mt=require("@milaboratories/pframes-node"),Ss=require("@milaboratories/pframes-rs-node"),bs=require("lru-cache"),ws=require("node:diagnostics_channel");function Ps(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Ir=Ps(gs);async function _t(r){try{return await Ir.stat(r,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Cs=[_.RegistryV1.PlPackageYamlConfigFile],Rs=[_.RegistryV1.PlPackageJsonConfigFile],bt=["backend","dist","tengo","tpl","main.plj.gz"],wt=["config","dist","config.json"],Ar=["frontend","dist"],Kt="block-model/dist/config.json",Es="block-ui/package.json",ks=[bt,wt,Cs,Rs,Ar];async function Os(r){return await _t(K.join(r,...wt))!==void 0||await _t(K.join(r,...bt))!==void 0}function st(r,e){const t=ms.tryResolve(r,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${r}`);return t}async function Ht(r,e){if(K.isAbsolute(r)||(r=K.resolve(r)),await Os(r))return{workflow:K.join(r,...bt),config:K.join(r,...wt),ui:K.join(r,...Ar)};{const t=st(r,Kt),s=st(r,Kt),o=st(r,Es);return{workflow:t,config:s,ui:K.resolve(o,"..","dist")}}}async function $s(r){try{return await Q.promises.readFile(r,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Ts(r){try{return await Q.promises.stat(r,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Pt(r){let e=0n;for(const t of ks){const s=K.join(r,...t),o=await Ts(s);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function qe(r){const e=await Q.promises.stat(r.components.workflow.main.file,{bigint:!0}),t=await Q.promises.stat(r.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Fs{constructor(e,t,s){this.v2Provider=e,this.registries=t,this.http=s}async getPackagesForRoot(e){const t=[],s=e.spec;switch(s.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await le.request(`${s.url}/${_.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:l,latestMeta:u,latestVersion:d}=a,m={organization:c,name:l,version:d},f={id:m,meta:{title:u.title??"No title",description:u.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:m,registryUrl:s.url}};t.push({registryId:e.id,id:m,latestByChannel:{[U.AnyChannel]:f,[U.StableChannel]:f},allVersions:a.allVersions.map(h=>({version:h,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(s.url).listBlockPacks()).map(o=>o.latestByChannel[U.StableChannel]?{...o,registryId:e.id}:{...o,latestByChannel:{...o.latestByChannel,[U.StableChannel]:(n=>n.spec.type==="from-registry-v2"?{...n,spec:{...n.spec,channel:U.StableChannel}}:n)(o.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const o of await Q.promises.readdir(s.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=K.join(s.path,o.name),i=await $s(K.join(n,_.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=_.RegistryV1.PlPackageConfigData.parse(fs.parse(i)),c=await Pt(n),l={organization:a.organization,name:a.package,version:"DEV"},u={id:l,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:l,latestByChannel:{[U.AnyChannel]:u,[U.StableChannel]:u},allVersions:[]})}else{let a=n,c=await _.tryLoadPackDescription(a);if(c===void 0){for(const l of["block","meta"])if(a=K.join(n,l),c=await _.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const l=await qe(c),u={id:c.id,meta:await _.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:l}};t.push({registryId:e.id,id:c.id,latestByChannel:{[U.AnyChannel]:u,[U.StableChannel]:u},allVersions:[]})}}}return t;default:return E.assertNever(s)}}async listBlockPacks(){const e=[],t=[];for(const s of this.registries)t.push({...s,status:"online"}),e.push(...await this.getPackagesForRoot(s));return{registries:t,blockPacks:e}}async getOverview(e,t,s){var i;const o=(i=this.registries.find(a=>a.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,s)}}class Lr{constructor(e){w(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const s=new _.RegistryV2Reader(_.folderReaderByUrl(e,this.http));return this.registries.set(e,s),s}}const Is={type:"remote-v2",url:"https://blocks.pl-open.science/"},As={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Ls={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Ds={groups:[{id:"default",label:"Default",blocks:[]}]},Ns={stagingRefreshTimestamp:0,blocksInLimbo:[]},Bs={label:"New Project"},js={name:"UserProject",version:"2"},Dr="SchemaVersion",Nr="1",Ct="ProjectCreated",$e="ProjectLastModified",Te="ProjectMeta",he="ProjectStructure",Me="BlockRenderingState",xs="BlockFrontendState/",Vs=/^BlockFrontendState\/(?<blockid>.*)$/;function dt(r){return`${xs}${r}`}const Us="BlockArgsAuthor/";function pt(r){return`${Us}${r}`}const ht="ProjectStructureAuthor";function Gs(r){const e=r.match(Vs);if(e!==null)return e.groups.blockid}const Js="__serviceTemplate_";function ft(r){return`${Js}${r}`}function J(r,e){return`${r}-${e}`}const Ms=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function _s(r){const e=r.match(Ms);if(e===null)return;const{blockId:t,fieldName:s}=e.groups;return{blockId:t,fieldName:s}}const Ks="projects",Br={name:"Projects",version:"1"},Hs=r=>g.resourceTypesEqual(r.type,Br)?r.fields:[];async function qs(r,e,t,s){const o=await He.SynchronizedTreeState.init(r,e,{...s.ops.defaultTreeOptions,pruning:Hs},s.logger);return{computable:j.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const l=[];for(const u of a.listDynamicFields()){const d=a.traverse(u);if(d===void 0)continue;const m=E.notEmpty(d.getKeyValueAsJson(Te)),f=E.notEmpty(d.getKeyValueAsJson(Ct)),h=E.notEmpty(d.getKeyValueAsJson($e));l.push({id:u,rid:d.id,created:new Date(f),lastModified:new Date(h),opened:c.indexOf(d.id)>=0,meta:m})}return l.sort(u=>-u.lastModified.valueOf()),l}).withStableType(),tree:o}}const Ws={name:"EphRenderTemplate",version:"1"},zs={name:"RenderTemplate",version:"1"};function Rt(r,e,t,s,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?r.createEphemeral(Ws):r.createStruct(zs),i=g.field(n,"template"),a=g.field(n,"inputs");return r.createField(i,"Input",e),r.createField(a,"Input",g.Pl.createPlMap(r,s,t)),r.lockInputs(n),g.Pl.futureRecord(r,n,o,"Output","outputs/")}const Xs={name:"BContextEnd",version:"1"},Ys={name:"BContext",version:"1"},Qs="id",Zs="parent/",eo=["context","result"];function qt(r,e,t){return Rt(r,e,!0,t,eo)}function to(r){const e=r.createEphemeral(Xs);return r.lock(e),e}function Wt(r,e){if(e.length===0)return to(r);if(e.length===1)return e[0];const t=r.createEphemeral(Ys);r.createField(g.field(t,Qs),"Input",g.Pl.createPlString(r,ae.randomUUID()));for(let s=0;s<e.length;s++)r.createField(g.field(t,`${Zs}${s}`),"Input",e[s]);return r.lock(t),t}function ro(r,e){const t=N.parseTemplate(e.content),s=t.type;switch(s){case"pl.tengo-template.v2":return oo(r,t);default:E.assertNever(s)}}const zt={hash(r,e){e.update(N.PlTemplateLibV1.type.name).update(N.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){return e.createValue(N.PlTemplateLibV1.type,JSON.stringify(N.PlTemplateLibV1.fromV2Data(r).data))}},Le={hash(r,e){e.update(N.PlTemplateSoftwareV1.type.name).update(N.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){const s=N.PlTemplateSoftwareV1.fromV2Data(r),o=e.createStruct(N.PlTemplateSoftwareV1.type,s.data);return e.setKValue(o,N.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(s.name)),e.lock(o),o}},so={hash(r,e){e.update(N.PlTemplateOverrideV1.type.name).update(N.PlTemplateOverrideV1.type.version).update(r.hashOverride??"")},render(r,e,t){return e.createStruct(N.PlTemplateOverrideV1.type,JSON.stringify(N.PlTemplateOverrideV1.fromV2Data(r)))}},jr={hash(r,e){e.update(N.PlTemplateV1.type.name).update(N.PlTemplateV1.type.version).update(r.hashOverride??"").update(r.name).update(r.version).update(r.src);const t=s=>(s.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),s);for(const[s,o]of t(Object.entries(r.libs??{})))e.update("lib:"+s),zt.hash(o,e);for(const[s,o]of t(Object.entries(r.software??{})))e.update("soft:"+s),Le.hash(o,e);for(const[s,o]of t(Object.entries(r.assets??{})))e.update("asset:"+s),Le.hash(o,e);for(const[s,o]of t(Object.entries(r.templates??{})))e.update("tpl:"+s),this.hash(o,e)},render(r,e,t){const s=e.createStruct(N.PlTemplateV1.type,JSON.stringify(N.PlTemplateV1.fromV2Data(r).data));for(const[i,a]of Object.entries(r.libs??{})){const c=N.PlTemplateV1.libField(s,i);e.createField(c,"Input"),e.setField(c,t(a,zt))}for(const[i,a]of Object.entries(r.software??{})){const c=N.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Le))}for(const[i,a]of Object.entries(r.assets??{})){const c=N.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Le))}for(const[i,a]of Object.entries(r.templates??{})){const c=N.PlTemplateV1.tplField(s,i);e.createField(c,"Input"),e.setField(c,t(a,jr))}if(e.lock(s),!r.hashOverride)return s;const o=t(r,so),n=N.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,s),e.lock(s),o}};function oo(r,e){const t=new Map,s=(o,n)=>{const i=ae.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,r,s);t.set(a,c)}return t.get(a)};return s(e,jr)}const xr={name:"TengoTemplateGet",version:"1"},Vr="registry",Ur="templateURI",Gr="template",no={name:"TengoTemplatePack",version:"1"},io={name:"TengoTemplatePackConvert",version:"1"},ao="templatePack",co="template";async function Jr(r){switch(r.type){case"from-file":return{type:"explicit",content:await Q.promises.readFile(r.path)};case"from-registry":case"explicit":return r;default:return E.assertNever(r)}}function lo(r,e){const t=r.createStruct(xr),s=g.field(t,Vr),o=g.field(t,Ur),n=g.field(t,Gr);return r.setField(s,r.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),r.setField(o,r.createValue(g.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function We(r,e){switch(e.type){case"from-registry":return lo(r,e);case"explicit":return ro(r,e);default:return E.assertNever(e)}}const Et={name:"Frontend/FromUrl",version:"1"},kt={name:"Frontend/FromFolder",version:"1"};function uo(r,e){switch(e.type){case"url":return r.createValue(Et,JSON.stringify({url:e.url}));case"local":return r.createValue(kt,JSON.stringify({path:e.path,signature:e.signature}));default:return E.assertNever(e)}}const po={name:"BlockPackCustom",version:"1"},Mr="template",_r="frontend";function Xt(r){return r.endsWith("/")?r:`${r}/`}class ho{constructor(e,t,s){this.v2RegistryProvider=e,this.signer=t,this.http=s}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Ht(e.folder),s=await Q.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(s)}case"dev-v2":{const t=await _.loadPackDescription(e.folder),s=await Q.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(s)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},s=`${Xt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await le.request(`${s}/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 le.request(o.model.url,t)).body.json()}default:return E.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Ht(e.folder),s=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:s},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await _.loadPackDescription(e.folder),s=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 qe(t)),{type:"explicit",template:{type:"explicit",content:o},config:s,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}:{},s=`${Xt(e.registryUrl)}${_.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${s}/template.plj.gz`,n=await le.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()),c=await(await le.request(`${s}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:c,frontend:{type:"url",url:`${s}/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 le.request(o.model.url,t)).body.json(),i=async()=>await(await le.request(o.workflow.main.url,t)).body.arrayBuffer(),[a,c]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:a,frontend:{type:"url",url:o.ui.url},source:e}}default:return E.assertNever(e)}}}function fo(r,e){const t={config:e.config,source:e.source},s=r.createStruct(po,JSON.stringify(t));return r.createField(g.field(s,Mr),"Input",We(r,e.template)),r.createField(g.field(s,_r),"Input",uo(r,e.frontend)),r.lock(s),s}function Yt(r,e){switch(e.type){case"explicit":return fo(r,e);default:return E.assertNever(e.type)}}function De(r,e){return{__isRef:!0,blockId:r,name:e}}function go(r){return typeof r=="object"&&r!==null&&"__isRef"in r&&r.__isRef===!0&&"blockId"in r&&"name"in r}function gt(r,e,t){const s=typeof e;switch(s){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(go(e))t===void 0||t.has(e.blockId)?r.upstreams.add(e.blockId):r.missingReferences=!0;else if(Array.isArray(e))for(const o of e)gt(r,o,t);else for(const[,o]of Object.entries(e))gt(r,o,t);return;default:E.assertNever(s)}}function mo(r,e){const t={upstreams:new Set,missingReferences:!1};return gt(t,r,e),t}function ie(r){return{*[Symbol.iterator](){for(const e of r.groups)for(const t of e.blocks)yield t}}}class Kr{constructor(e){w(this,"nodes");this.nodes=e}traverseIds(e,...t){const s=new Set;return this.traverse(e,t,o=>s.add(o.id)),s}traverseIdsExcludingRoots(e,...t){const s=this.traverseIds(e,...t);for(const o of t)s.delete(o);return s}traverse(e,t,s){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);s(c),c[e].forEach(l=>{n.has(l)||(n.add(l),i.push(l))})}o=i}}}function mt(r){const e=new Map;let t;for(const{id:s}of ie(r)){const o={id:s,missingReferences:!1};e.set(s,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 Kr(e)}function Ge(r,e){const t=new Map,s=new Set;for(const{id:o}of ie(r)){const n=e(o);if(n===void 0)continue;const i=mo(n,s),a={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,a),i.upstreams.forEach(c=>t.get(c).downstream.add(o)),s.add(o)}return new Kr(t)}function vo(r,e){if(r.size!==e.size)return!1;for(const t of r)if(!e.has(t))return!1;return!0}function vt(r,e){if(r.size>e.size)return vt(e,r);for(const t of r)if(e.has(t))return!0;return!1}function Qt(r,e){const t=new Set,s=new Set,o=new Set;return r.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!vo(n.upstream,i.upstream)||vt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{r.nodes.has(n.id)?vt(n.upstream,o)&&o.add(n.id):s.add(n.id)}),{onlyInA:t,onlyInB:s,different:o}}let ot;async function Hr(){if(ot===void 0){const r=await Jr(vs.Templates["pframes.export-pframe"]);if(r.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ae.createHash("sha256").update(r.content).digest("hex");ot={spec:r,hash:e}}return ot}function yo(r,e,t){return Rt(r,e,!0,{pf:t},["result"]).result}function nt(r,e){let t=!1,s,o;return()=>{if(!t)return t=!0,s=r(),o=e(),o;const n=r();return s!==n&&(s=n,o=e()),e()}}class Zt{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(g.Pl.unwrapHolder(e,this.fields.blockPack.ref),Mr,"Input")}}const So=r=>{throw new Error(`No new block info for ${r}`)};class _e{constructor(e,t,s,o,n,i,a,c,l,u,d,m){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=s,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=l,this.blockInfos=u,this.blockFrontendStates=d,this.ctxExportTplHolder=m}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=Ge(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Ge(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(g.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ie(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,s){const o=g.field(this.rid,J(e,t));if(s.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",s.ref):this.tx.setField(o,s.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...s},this.fieldsChanged=!0}setBlockField(e,t,s,o,n){this.setBlockFieldObj(e,t,{ref:s,status:o,value:n})}deleteBlockFields(e,...t){let s=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(g.field(this.rid,J(e,n))),delete i[n],this.fieldsChanged=!0,s=!0)}return s}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var s,o,n;const t=this.getBlockInfo(e).fields;((s=t.stagingOutput)==null?void 0:s.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 s,o,n;const t=this.getBlockInfo(e).fields;((s=t.prodOutput)==null?void 0:s.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 s,o;const t=this.getBlockInfo(e).fields;return((s=t.prodOutput)==null?void 0:s.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:s,args:o}of e){const n=this.getBlockInfo(s);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(g.Pl.JsonObject,i);this.setBlockField(s,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(s),t.push(s)}this.getStagingGraph().traverse("downstream",t,({id:s})=>this.resetStaging(s)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(s=>{var n;const o=this.getBlockInfo(s);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Wt(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(s=>{var n,i;const o=this.getBlockInfo(s);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(g.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(g.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),Wt(this.tx,t)}exportCtx(e){return yo(this.tx,g.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),s=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=qt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!1)),context:s});this.setBlockField(e,"stagingCtx",g.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),s=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=qt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(g.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(g.Pl.JsonBool,JSON.stringify(!0)),context:s});this.setBlockField(e,"prodCtx",g.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"prodUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"prodOutput",n.result,"NotReady"),this.setBlockFieldObj(e,"prodArgs",t.fields.currentArgs),this.blocksInLimbo.delete(e)&&(this.renderingStateChanged=!0)}updateStructure(e,t=So){const s=this.getStagingGraph(),o=this.getActualProductionGraph(),n=mt(e),i=Ge(e,l=>{var u;return(u=this.blockInfos.get(l))==null?void 0:u.actualProductionInputs}),a=Qt(s,n),c=Qt(o,i);for(const l of a.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 a.onlyInB){const u=new Zt(l,{});this.blockInfos.set(l,u);const d=t(l),m=Yt(this.tx,d.blockPack);this.setBlockField(l,"blockPack",g.Pl.wrapInHolder(this.tx,m),"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 a.different)this.resetStaging(l);o.traverse("downstream",[...c.different],l=>{this.resetOrLimboProduction(l.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.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,s){const o=this.structure;if(s===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===s);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${s}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let s=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),s=!0;break}}if(!s)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,s){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",g.Pl.wrapInHolder(this.tx,Yt(this.tx,t)),"NotReady"),s!==void 0?(this.setArgs([{blockId:e,args:s}]),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 s=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{s.add(a.id)});else for(const a of s){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const l of c.upstream)if(!s.has(l))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of ie(this.structure)){if(!s.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const l of o.nodes.get(a.id).upstream)if(n.has(l)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),s=new Tr(e),o=new Set(e),n=[];for(;!s.isEmpty();){const c=s.shift(),l=this.getBlockInfo(c).fields;if(!(((i=l.prodOutput)==null?void 0:i.status)==="Ready"&&((a=l.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const u of t.traverseIdsExcludingRoots("downstream",c))o.has(u)||(s.push(u),o.add(u))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,s=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(s===void 0||i<=s)&&(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 s,o,n,i;((s=t.fields.prodCtx)==null?void 0:s.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,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,he,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,Me,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Te,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,s){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Dr),i=e.getKValueJson(t,$e),a=e.getKValueJson(t,Te),c=e.getKValueJson(t,he),l=e.getKValueJson(t,Me),u=e.listKeyValuesString(t),[d,m,f,h,O,{stagingRefreshTimestamp:L,blocksInLimbo:x},q]=await Promise.all([o,n,i,a,c,l,u]);if(m!==Nr)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${m}`);const T=new Map;for(const p of d.fields){const v=_s(p.name);if(v===void 0)continue;let S=T.get(v.blockId);S===void 0&&(S={id:v.blockId,fields:{}},T.set(v.blockId,S)),S.fields[v.fieldName]=g.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const ue=await Hr(),fe=ft(ue.hash),D=d.fields.find(p=>p.name===fe);let X;D!==void 0?X=g.ensureResourceIdNotNull(D.value):(X=g.Pl.wrapInHolder(e,We(e,ue.spec)),e.createField(g.field(t,ft(ue.hash)),"Dynamic",X));const de={stagingRefreshTimestamp:L},W=new Set(x),M=new Map;for(const p of q){const v=Gs(p.key);v!==void 0&&M.set(v,p.value)}const G=[];T.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!g.isResource(v.ref)||g.isResourceRef(v.ref))throw new Error("unexpected behaviour");G.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of G){const S=await v;p.value=S.data,g.isNotNullResourceId(S.error)?p.status="Error":S.resourceReady||g.isNotNullResourceId(S.originalResourceId)?p.status="Ready":p.status="NotReady"}const Y=new Map;T.forEach(({id:p,fields:v})=>Y.set(p,new Zt(p,v)));const ge=new Set;for(const p of ie(O)){if(!Y.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);ge.add(p.id)}Y.forEach(p=>{if(!ge.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new _e(t,e,s,m,f,h,O,de,W,Y,M,X);return y.fixProblemsAndMigrate(),y}}async function bo(r,e=Bs){const t=r.createEphemeral(js);r.lock(t);const s=String(Date.now());r.setKValue(t,Dr,JSON.stringify(Nr)),r.setKValue(t,Ct,s),r.setKValue(t,$e,s),r.setKValue(t,Te,JSON.stringify(e)),r.setKValue(t,he,JSON.stringify(Ds)),r.setKValue(t,Me,JSON.stringify(Ns));const o=await Hr();return r.createField(g.field(t,ft(o.hash)),"Dynamic",g.Pl.wrapInHolder(r,We(r,o.spec))),t}async function Ne(r,e,t){return ee(r,e,void 0,t)}async function ee(r,e,t,s){if(r instanceof g.PlClient)return await r.withWriteTx("ProjectAction",async o=>{const n=await _e.load(o,e,t),i=await s(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await _e.load(r,e,t),n=await s(o);return o.save(),n}}function*wo(r){switch(r.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(r.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(r.parts))yield e,yield t;return;default:E.assertNever(r)}}function er(r,e){return Object.fromEntries(Object.entries(r).map(([t,s])=>[t,e(s,t)]))}function Po(r,e){switch(r.type){case"Json":return{...r};case"JsonPartitioned":return{...r,parts:er(r.parts,e)};case"BinaryPartitioned":return{...r,parts:er(r.parts,t=>({index:e(t.index),values:e(t.values)}))};default:E.assertNever(r)}}const Co=g.resourceType("PColumnData/JsonPartitioned","1"),Ro=g.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Eo=g.resourceType("PColumnData/BinaryPartitioned","1"),ko=g.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Oo=g.resourceType("PColumnData/Json","1");function $o(r){if(!r.getIsReadyOrError())throw new Error("Data not ready.");const e=r.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(g.resourceTypesEqual(r.resourceType,Oo)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(g.resourceTypesEqual(r.resourceType,Co)){const t=e,s=Object.fromEntries(r.listInputFields().map(o=>[o,r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:s}}else if(g.resourceTypesEqual(r.resourceType,Ro)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);s[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}else if(g.resourceTypesEqual(r.resourceType,Eo)){const t=e,s={};for(const o of r.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=s[n];i===void 0&&(i={},s[n]=i),i.index=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=s[n];i===void 0&&(i={},s[n]=i),i.values=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(s)){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:s}}else if(g.resourceTypesEqual(r.resourceType,ko)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=s[l];u===void 0&&(u={},s[l]=u),s[l].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),l=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let u=s[l];u===void 0&&(u={},s[l]=u),s[l].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}throw new Error(`unsupported resource type: ${g.resourceTypeToString(r.resourceType)}`)}function To(r,e){const t=r.axesSpec.length,s={};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}`);s[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:s}}function Fo(r,e){const t=ae.createHash("sha256");return t.update(te(r)),t.update(String(g.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function tr(r,e){return te({__isRef:!0,blockId:r,name:e})}function Io(r,e){return te({resolvePath:r,name:e})}function qr(r,e=!0,t=!1,s=""){var a,c,l;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const u of r.listInputFields()){const d=u.match(o);if(!d){if(e)throw new Error(`unexpected field name ${u}`);continue}let m=E.notEmpty((a=d.groups)==null?void 0:a.name);if(!m.startsWith(s)){if(e)throw new Error(`unexpected field name ${u}`);continue}m=m.slice(s.length);const f=E.notEmpty((c=d.groups)==null?void 0:c.type);let h=n.get(m);switch(h===void 0&&(h={},n.set(m,h)),f){case"spec":h.spec=(l=r.traverse({field:u,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:l.getDataAsJson();break;case"data":h.hasData=!0,h.data=()=>r.traverseOrError({field:u,ignoreError:t});break}}const i=r.getInputsLocked();if(i)for(const[,u]of n)u.data===void 0&&(u.hasData=!1);return{locked:i,results:n}}function Ao(r,e=!0,t="",s){if(!r.getIsReadyOrError())throw new Error("resource is not ready");const o=qr(r,e,!1,t);ys(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw new He.PlError(c.error);n[i]={id:s.length===0?Fo(a.spec,c.value):Io(s,i),spec:a.spec,data:c.value}}return n}class Ot{constructor(e,t){w(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let s=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){s=!1;break e}for(const i of n.results.values())if(i.spec===void 0){s=!1;break e}}this.allSpecsAvailable=s}getSpecByRef(e,t){var n,i,a,c,l,u;const s=this.blocks.get(e);if(s===void 0)return;let o=(a=(i=(n=s.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(u=(l=(c=s.staging)==null?void 0:c.results)==null?void 0:l.get(t))==null?void 0:u.spec,o!==void 0))return o;s.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):s.staging.locked?s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const s=this.blocks.get(e);if(s===void 0)return;const o=(a=(i=s.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return B.mapValueInVOE(n,l=>({id:tr(e,t),spec:o.spec,data:l}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const s=this.getDataOrErrorByRef(e,t);if(!(s===void 0||!s.ok))return s.value}getData(){const e=this.getDataWithErrors(),t=[];for(const s of e.entries)s.obj.id!==void 0&&s.obj.data.ok&&t.push({ref:s.ref,obj:{id:s.obj.id,spec:s.obj.spec,data:s.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,s;const o=i=>{s===void 0&&(s=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const l=c.data();l!==void 0?e.push({ref:De(i,a),obj:{id:l.ok?tr(i,a):void 0,spec:c.spec,data:l}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[l,u]of a.prod.results)c.add(l),n(i,l,u)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[l,u]of a.staging.results)c.has(l)||n(i,l,u)}}return{entries:e,isComplete:t,instabilityMarker:s}}getSpecs(){const e=[];let t=!0,s;const o=n=>{s===void 0&&(s=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,l]of i.staging.results)l.spec!==void 0&&(e.push({ref:De(n,c),obj:l.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,l]of i.prod.results)a.has(c)||l.spec!==void 0&&e.push({ref:De(n,c),obj:l.spec})}}return{entries:e,isComplete:t,instabilityMarker:s}}calculateOptions(e){const t=[];for(const s of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),B.executePSpecPredicate(e,c.spec)&&t.push({label:s.info.label+" / "+a,ref:De(s.info.id,a),spec:c.spec}))};s.staging!==void 0&&n(s.staging),s.prod!==void 0&&n(s.prod)}return t}static create(e,t,s){const o=e.accessor(t).node(),n=E.notEmpty(o.getKeyValueAsJson(he)),a=mt(n).traverseIds("upstream",s),c=new Map;for(const l of ie(n)){if(!a.has(l.id))continue;const u=rr(o.traverse({field:J(l.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:J(l.id,"prodUiCtx"),stableIfNotFound:!0})),d=rr(o.traverse({field:J(l.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:J(l.id,"stagingUiCtx")}));c.set(l.id,{info:l,prod:u,staging:d})}return new Ot(e,c)}}function rr(r,e){if(e===void 0)return r?{locked:!1,results:new Map}:void 0;if(e.ok)return qr(e.value,!1,!0)}function $t(r,e){return{blockId:e,args:n=>E.notEmpty(n.accessor(r).node().traverse({field:J(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(r).node().traverse({field:J(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(r).node().getKeyValueAsString(dt(e)),blockMeta:n=>{const i=n.accessor(r).node(),a=E.notEmpty(i.getKeyValueAsJson(he)),c=new Map;for(const l of ie(a))c.set(l.id,l);return c}}}function Wr(r,e){return{...$t(r,e),prod:t=>{var s;return(s=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:t=>{var o;const s=(o=t.accessor(r).node({ignoreError:!0}).traverse({field:J(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return s===void 0&&t.markUnstable("staging_not_rendered"),s},getResultsPool:t=>Ot.create(t,r,e)}}function*z(r,e){switch(yield r,r.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*z(r.cfg);return;case"MakeObject":for(const[,t]of Object.entries(r.template))yield*z(t);return;case"MakeArray":for(const t of r.template)yield*z(t);return;case"GetJsonField":case"GetResourceField":yield*z(r.source),yield*z(r.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*z(r.source),yield*z(r.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*z(r.source);return;case"IsEmpty":yield*z(r.arg);return;case"Not":yield*z(r.operand);return;case"And":case"Or":yield*z(r.operand1),yield*z(r.operand2);return;default:E.assertNever(r)}}function Lo(r,e){const t={};for(const[s,o]of Object.entries(r))t[s]=e(o);return t}function Ee(r,e){return r===void 0?void 0:e(r)}function Do(r){switch(r.type){case"GetImportProgress":return!0;default:return!1}}function No(r){for(const e of z(r))if(Do(e))return!0;return!1}function ze(r){return{type:"ReturnResult",result:r}}function k(r){return()=>ze(r)}const Bo=r=>{const e={};for(const[t,s]of Object.entries(r))e[t]=s;return k(e)},jo=r=>{const e=r.source;if(e===void 0)return k(void 0);const t=[];for(const s of e)s instanceof Array?t.push(...s):t.push(s);return k(t)},xo=r=>{const e=r.source,t=r.field;return e===void 0||t===void 0?k(void 0):({cCtx:s})=>{var o;return ze((o=s.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function zr(r,e){const t={},s=r.length;for(let o=0;o<s;o++)t[String(o)]=e(r[o]);return t}function Vo(r,e){return t=>{const s=t.source;return s===void 0?k(void 0):()=>({type:"ScheduleSubroutine",subroutine:Xr(s.length),args:zr(s,o=>$({...r,[e.itVar]:o},e.mapping))})}}function Xr(r){return e=>{const t=[];for(let s=0;s<r;s++)t.push(e[String(s)]);return k(t)}}function Uo(r,e){return t=>{const s=t.source;if(s===void 0)return k(void 0);const o={};for(const[n,i]of Object.entries(s)){const a={...r,[e.itVar]:i};o[n]=$(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Go,args:o})}}const Go=r=>k(r),Jo=r=>{const e=r.arg;return k(e===void 0?void 0:e.length===0)},Mo=r=>{const e=r.operand;return k(e===void 0?void 0:!e)},_o=r=>{const e=r.operand1,t=r.operand2;return k(e===void 0||t===void 0?void 0:e&&t)},Ko=r=>{const e=r.operand1,t=r.operand2;return k(e===void 0||t===void 0?void 0:e||t)},Ho=r=>{const e=r.source;return e===void 0?k(void 0):({cCtx:t})=>{var s;return ze((s=t.accessor(e).node())==null?void 0:s.getDataAsJson())}},qo=r=>{const e=r.source,t=r.field;return k(e===void 0||t===void 0?void 0:e[t])};function Wo(r,e){return t=>{const s=t.source;return s===void 0?k(void 0):({cCtx:o})=>{const n=o.accessor(s).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=k(void 0);else{const l={...r,[e.itVar]:c.persist()};i[a]=$(l,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:zo,args:i}}}}const zo=r=>k(r),Xo=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s!==void 0)return await t.blobDriver.getContent(s.handle)}})})},Yo=r=>{const e=r.source;return e===void 0?k(void 0):({cCtx:t,drivers:s})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>s.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await s.blobDriver.getContent(n.handle)).toString()})}}},Qo=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s==null)return;const o=await t.blobDriver.getContent(s.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},Zo=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},en=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},tn=r=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.blobToURLDriver.extractArchiveAndGetURL(t,r)})},rn=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},sn=r=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getLastLogs(t,r)})},on=r=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLog(t,r)})},nn=r=>e=>{const t=e.source;return t===void 0?k(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLogWithInfo(t,r)})},an=r=>{const e=r.source;return e===void 0?k(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function $(r,e){switch(e.type){case"GetFromCtx":{const t=r[e.variable];return typeof t=="function"?s=>ze(t(s.cCtx)):k(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:Zr(t,r,e.cfg)});case"Immediate":return k(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:qo,args:{source:$(r,e.source),field:$(r,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Vo(r,e),args:{source:$(r,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Uo(r,e),args:{source:$(r,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:Bo,args:Lo(e.template,t=>$(r,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Xr(e.template.length),args:zr(e.template,t=>$(r,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:{source:$(r,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:{arg:$(r,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{operand:$(r,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{operand1:$(r,e.operand1),operand2:$(r,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{operand1:$(r,e.operand1),operand2:$(r,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:Wo(r,e),args:{source:$(r,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:xo,args:{source:$(r,e.source),field:$(r,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Ho,args:{source:$(r,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Xo,args:{source:$(r,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:$(r,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:$(r,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:$(r,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:en,args:{source:$(r,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:tn(e.format),args:{source:$(r,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:rn,args:{source:$(r,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:sn(e.lines),args:{source:$(r,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:on(e.patternToSearch),args:{source:$(r,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:nn(e.patternToSearch),args:{source:$(r,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:an,args:{source:$(r,e.source)}});default:return E.assertNever(e)}}const cn=["$prod","$staging"];function ln(r){return{$blockId:r.blockId,$args:e=>JSON.parse(r.args(e)),$ui:e=>{const t=r.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:r.prod,$staging:r.staging}}const Yr=Symbol(),Qr="return",un={op:Yr,arg:Qr};function dn(r){return r.op==Yr&&r.arg==Qr}function pn(){return{pendingSubroutines:new Map}}function sr(r,e,t,s){const o=new Tr(t),n=(a,c)=>{if(dn(a))return e.result=c,!1;const l=E.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in l.args)throw new Error("argument already set");return l.args[a.arg]=c,l.argCounter--,l.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:l.destination,operation:l.subroutine(l.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(r);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const l=Symbol(),u=Object.entries(c.args),d=u.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[m,f]of u)o.push({destination:{op:l,arg:m},operation:f});e.pendingSubroutines.set(l,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!s)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:E.assertNever(c)}}return i}function hn(r,e,t,s={}){return Zr(r,ln(e),t,s)}function Zr(r,e,t,s={}){const o=`${e.blockId}#`+te({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>cn.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:r,cCtx:n},a=pn();return{ir:sr(i,a,[{destination:un,operation:$(e,t)}],!0),postprocessValue(l){const u=[];for(const h of l)u.push({destination:h.destination,operation:k(h.computable)});const d={drivers:r,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},m=new Map;for(const[h,O]of a.pendingSubroutines)m.set(h,{...O,args:{...O.args}});const f={result:a.result,pendingSubroutines:m};if(sr(d,f,u,!1),!("result"in f))throw new Error("illegal cfg rendering stack state, no result");return f.result}}},{...s,key:o})}function fn(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function or(r){return r!==void 0?Buffer.from(r).toString("base64"):void 0}class Ke{constructor(e,t,s,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=s,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=s.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 Ke.cleanErrorContext(t),t}}runCallback(e,...t){try{return Je.Scope.withScope(s=>{const o=s.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,s)))))})}catch(s){throw Ke.cleanErrorContext(s),s}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(s,o)=>{if(!this.accessors.has(s)){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(s,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(s,void 0)}return this.accessors.get(s)?s:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...s){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...s))}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 or(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return or(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,s,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Ao(n,t,s,o),a={};for(const[c,l]of Object.entries(i))a[c]=B.mapPObjectData(l,u=>this.wrapAccessor(u));return a}registerComputable(e,t){const s=`${e}_${ae.randomUUID()}`;return this.computablesToResolve[s]=t,s}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.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 s=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(s,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(s,t))}getProgressLog(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(s,t))}getProgressLogWithInfo(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(s,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=E.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,s=>this.wrapAccessor(s))}))}}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,s=>this.wrapAccessor(s))}}))}}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),s=>this.wrapAccessor(s))}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,s=>typeof s=="string"?this.getAccessor(s):s)),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,s=>typeof s=="string"?this.getAccessor(s):s)),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 s=this.tryExportSingleValue(e,t);if(s===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return s}tryExportSingleValue(e,t){let s,o=!1;switch(typeof e){case"string":s=this.vm.newString(e),o=!0;break;case"number":s=this.vm.newNumber(e),o=!0;break;case"undefined":s=this.vm.undefined;break;case"boolean":s=e?this.vm.true:this.vm.false;break;default:if(e===null){s=this.vm.null;break}if(fn(e)){s=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(s):s}exportObjectUniversal(e,t){const s=this.tryExportSingleValue(e,t);return s!==void 0?s:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const s=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(s):s}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(s=>this.vm.getString(s));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Je.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),s=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(s))),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=(a,c)=>{this.vm.newFunction(a,c).consume(l=>this.vm.setProp(t,a,l))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...l)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...l.map(u=>this.importObjectViaJson(u))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,l,...u)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(l),...u.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Xe(r,e){return Ee(r.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const s=t.getDataAsJson(),o=B.extractConfig(s.config);return{bpId:t.resourceInfo.id.toString(),info:s,cfg:o}})}const Be=process.env.MI_LOG_OUTPUT_STATUS;function gn(r,e,t,s,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(a=>{const c=new Je.Scope;a.addOnDestroy(()=>c.dispose());const l=c.manage(r.quickJs.newRuntime());l.setMemoryLimit(1024*640),l.setMaxStackSize(1024*320);const u=c.manage(l.newContext()),d=new Ke(c,u,e,r,a);d.evaluateBundle(s.content);const m=d.runCallback(t.handle);d.resetComputableCtx();let f=0;return Be&&Be!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:(h,{unstableMarker:O,stable:L})=>{for(const[q,T]of Object.entries(h))d.runCallback(q,T);const x=d.importObjectUniversal(m);return f++,Be&&(Be!=="unstable-only"||!L)&&console.log(L?`Stable output ${t.handle} calculated ${x!==void 0?"defined":"undefined"}; (#${f})`:`Unstable output ${t.handle}; marker = ${O}; ${x!==void 0?"defined":"undefined"} (#${f})`),x}}},n)}function mn(r){return B.isConfigLambda(r)?r.isActive===!0:No(r)}function ke(r,e,t,s,o,n={}){if(B.isConfigLambda(t)){if(s===void 0)throw new Error("No code bundle.");return gn(r,e,t,s,o,n)}else return hn(r.driverKit,e,t,n)}function vn(r,e,t){return j.Computable.make(s=>{var h,O,L,x,q,T,ue,fe;const o=s.accessor(r).node(),n=E.notEmpty(o.getKeyValueAsJson(Ct)),i=E.notEmpty(o.getKeyValueAsJson($e)),a=E.notEmpty(o.getKeyValueAsJson(Te)),c=E.notEmpty(o.getKeyValueAsJson(he)),l=E.notEmpty(o.getKeyValueAsJson(Me)),u=new Map;for(const{id:D}of ie(c)){const X=o.traverse({field:J(D,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let de;const W=o.traverse({field:J(D,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(W!==void 0){const M=o.getField({field:J(D,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),G=o.getField({field:J(D,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});de={arguments:W.getDataAsJson(),stale:X.id!==W.id,outputError:M.error!==void 0||G.error!==void 0||((h=M.value)==null?void 0:h.getError())!==void 0||((O=G.value)==null?void 0:O.getError())!==void 0,outputsError:((L=M.error)==null?void 0:L.getDataAsString())??((q=(x=M.value)==null?void 0:x.getError())==null?void 0:q.getDataAsString()),exportsError:((T=G.error)==null?void 0:T.getDataAsString())??((fe=(ue=G.value)==null?void 0:ue.getError())==null?void 0:fe.getDataAsString()),finished:(M.value!==void 0&&M.value.getIsReadyOrError()||M.error!==void 0&&M.error.getIsReadyOrError())&&(G.value!==void 0&&G.value.getIsReadyOrError()||G.error!==void 0&&G.error.getIsReadyOrError())}}u.set(D,{currentArguments:X.getDataAsJson(),prod:de})}const d=Ge(c,D=>u.get(D).currentArguments),m=new Set(l.blocksInLimbo),f=[...ie(c)].map(({id:D,label:X,renderingMode:de})=>{var b,C,F,R,A;const W=E.notEmpty(u.get(D)),M=E.notEmpty(d.nodes.get(D));let G="NotCalculated";W.prod!==void 0&&(m.has(D)?G="Limbo":G=W.prod.finished?"Done":"Running");const Y=Xe(o,D),{sections:ge,title:y,inputsValid:p,sdkVersion:v}=Ee(Y,({bpId:V,cfg:I})=>{const ce=$t(r,D);return{sections:ke(t,ce,I.sections,I.code,V),title:Ee(I.title,ds=>ke(t,ce,ds,I.code,V)),inputsValid:ke(t,ce,I.inputsValid,I.code,V),sdkVersion:I.sdkVersion}})||{},S=o.traverse({field:J(D,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ee(Y,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:S}));return{id:D,label:y??X,title:y??X,renderingMode:de,stale:((b=W.prod)==null?void 0:b.stale)!==!1||G==="Limbo",missingReference:M.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",D)],downstreams:[...d.traverseIdsExcludingRoots("downstream",D)],calculationStatus:G,outputErrors:((C=W.prod)==null?void 0:C.outputError)===!0,outputsError:(F=W.prod)==null?void 0:F.outputsError,exportsError:(R=W.prod)==null?void 0:R.exportsError,settings:S,sections:ge,inputsValid:p,updateInfo:{},currentBlockPack:(A=Y==null?void 0:Y.info)==null?void 0:A.source,updates:P,sdkVersion:v,navigationState:e.getState(D)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ht),blocks:f}},{postprocessValue:s=>{const o=new Set,n=new Set;return{...s,blocks:s.blocks.map(i=>{var u,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(m=>n.has(m))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(m=>o.has(m))===-1,l={...i,canRun:c,stale:a,updateSuggestions:((u=i.updates)==null?void 0:u.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete l.updates,l})}}}).withStableType()}function yn(r,e){const t=r.node();if(g.resourceTypesEqual(t.resourceType,Et)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(s.url)).withStableType()}else if(g.resourceTypesEqual(t.resourceType,kt)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.signer.verify(s.path,s.signature,`Frontend path signature mismatch for: ${s.path}`),s.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Sn(r,e){if(r!==void 0)return j.Computable.make(t=>yn(t.accessor(r),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 bn(r,e,t){return j.Computable.make(s=>{var a;const o=s.accessor(r).node(),n=Xe(o,e),i=(a=o.traverse({field:J(e,"blockPack"),assertFieldType:"Dynamic"},{field:g.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:_r,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Sn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function es(r,e,t){if(t===void 0)return j.Computable.make(i=>es(r,e,i),{key:`inputs#${g.resourceIdToString(r.rid)}#${e}`});const s=t.accessor(r).node(),o=$t(r,e),n=o.uiState(t);return{author:s.getKeyValueAsJson(pt(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function wn(r,e,t){return j.Computable.make(s=>{const o=s.accessor(r).node(),n=Wr(r,e);return Ee(Xe(o,e),({cfg:i,bpId:a})=>{const c={};for(const[l,u]of Object.entries(i.outputs)){const d=ke(t,n,u,i.code,a);c[l]=j.Computable.wrapError(d)}return c})},{key:"outputs#"+g.resourceIdToString(r.rid)+"#"+e}).withStableType()}function Pn(r,e){return j.Computable.make(t=>{const s=t.accessor(r).node(),o=E.notEmpty(s.getKeyValueAsJson(he)),n=[];for(const{id:i}of ie(o)){const a=Xe(s,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,u])=>u).filter(u=>mn(u)).map(u=>u);if(c.length===0)continue;const l=Wr(s.persist(),i);for(const u of c)n.push(j.Computable.wrapError(ke(e,l,u,a.cfg.code,a.bpId)))}return n})}class Cn{constructor(){w(this,"states",new Map)}setState(e,t){const s=this.states.get(e);if(s===void 0){this.states.set(e,{state:t,change:new j.ChangeSource});return}s.state={...t},s.change.markChanged()}readState(e,t){let s=this.states.get(t);return s===void 0&&(s={state:{...B.DefaultNavigationState},change:new j.ChangeSource},this.states.set(t,s)),s.change.attachWatcher(e.watcher),s.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 Ye{constructor(e,t,s){w(this,"rid");w(this,"overview");w(this,"navigationStates",new Cn);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=s,this.overview=vn(s.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Pn(s.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 Fr.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(g.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!g.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,s,o=void 0,n=ae.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=B.extractConfig(a);return await ee(this.env.pl,this.rid,o,l=>l.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:i},s)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,s=!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,a=>a.migrateBlockPack(e,n,s?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await ee(this.env.pl,this.rid,t,s=>s.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await ee(this.env.pl,this.rid,t,s=>{const o=s.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(a=>{const c=n.blocks.find(l=>l.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};s.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,s){await ee(this.env.pl,this.rid,s,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,s){await ee(this.env.pl,this.rid,s,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,s,o){await ee(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(s))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await ee(this.env.pl,this.rid,void 0,s=>{s.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async s=>{const o=g.ensureResourceIdNotNull((await s.getField(g.field(this.rid,J(e,"blockPack")))).value),n=g.ensureResourceIdNotNull((await s.getField(g.field(o,g.Pl.HolderRefField))).value),i=await s.getResourceData(n,!1),a=JSON.parse(Buffer.from(E.notEmpty(i.data)).toString("utf-8"));await ee(s,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await s.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const s=wn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:es(this.projectTree.entry(),e,i),outputs:s,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 s=bn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,s),s}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 s=await He.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Rn},e.logger);return new Ye(e,t,s)}}function Rn(r){switch(r.type.name){case"BlockPackCustom":return r.fields.filter(e=>e.name!=="template");case"UserProject":return r.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return r.fields}}const Tt={logger:new E.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 Ft(r){return{blobDownloadPath:K.join(r,"download"),downloadBlobToURLPath:K.join(r,"downloadToURL")}}const ts={...Tt,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function rs(r){return{...Ft(r),frontendDownloadPath:K.join(r,"frontend")}}function En(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var yt={exports:{}};const kn="2.0.0",ss=256,On=Number.MAX_SAFE_INTEGER||9007199254740991,$n=16,Tn=ss-6,Fn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Qe={MAX_LENGTH:ss,MAX_SAFE_COMPONENT_LENGTH:$n,MAX_SAFE_BUILD_LENGTH:Tn,MAX_SAFE_INTEGER:On,RELEASE_TYPES:Fn,SEMVER_SPEC_VERSION:kn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const In=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};var Ze=In;(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=Qe,n=Ze;e=r.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],l=e.t={};let u=0;const d="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",o],[d,s]],f=O=>{for(const[L,x]of m)O=O.split(`${L}*`).join(`${L}{0,${x}}`).split(`${L}+`).join(`${L}{1,${x}}`);return O},h=(O,L,x)=>{const q=f(L),T=u++;n(O,T,L),l[O]=T,c[T]=L,i[T]=new RegExp(L,x?"g":void 0),a[T]=new RegExp(q,x?"g":void 0)};h("NUMERICIDENTIFIER","0|[1-9]\\d*"),h("NUMERICIDENTIFIERLOOSE","\\d+"),h("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d}*`),h("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),h("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),h("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),h("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),h("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),h("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),h("BUILDIDENTIFIER",`${d}+`),h("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),h("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),h("FULL",`^${c[l.FULLPLAIN]}$`),h("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),h("LOOSE",`^${c[l.LOOSEPLAIN]}$`),h("GTLT","((?:<|>)?=?)"),h("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),h("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),h("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),h("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),h("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),h("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),h("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),h("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),h("COERCERTL",c[l.COERCE],!0),h("COERCERTLFULL",c[l.COERCEFULL],!0),h("LONETILDE","(?:~>?)"),h("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",h("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),h("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),h("LONECARET","(?:\\^)"),h("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",h("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),h("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),h("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),h("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),h("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",h("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),h("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),h("STAR","(<|>)?=?\\s*\\*"),h("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),h("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(yt,yt.exports);var Fe=yt.exports;const An=Object.freeze({loose:!0}),Ln=Object.freeze({}),Dn=r=>r?typeof r!="object"?An:r:Ln;var It=Dn;const nr=/^[0-9]+$/,os=(r,e)=>{const t=nr.test(r),s=nr.test(e);return t&&s&&(r=+r,e=+e),r===e?0:t&&!s?-1:s&&!t?1:r<e?-1:1},Nn=(r,e)=>os(e,r);var ns={compareIdentifiers:os,rcompareIdentifiers:Nn};const je=Ze,{MAX_LENGTH:ir,MAX_SAFE_INTEGER:xe}=Qe,{safeRe:ar,t:cr}=Fe,Bn=It,{compareIdentifiers:me}=ns;let jn=class oe{constructor(e,t){if(t=Bn(t),e instanceof oe){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>ir)throw new TypeError(`version is longer than ${ir} characters`);je("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const s=e.trim().match(t.loose?ar[cr.LOOSE]:ar[cr.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>xe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xe||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<xe)return n}return o}):this.prerelease=[],this.build=s[5]?s[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(je("SemVer.compare",this.version,this.options,e),!(e instanceof oe)){if(typeof e=="string"&&e===this.version)return 0;e=new oe(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof oe||(e=new oe(e,this.options)),me(this.major,e.major)||me(this.minor,e.minor)||me(this.patch,e.patch)}comparePre(e){if(e instanceof oe||(e=new oe(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 s=this.prerelease[t],o=e.prerelease[t];if(je("prerelease compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return me(s,o)}while(++t)}compareBuild(e){e instanceof oe||(e=new oe(e,this.options));let t=0;do{const s=this.build[t],o=e.build[t];if(je("build compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return me(s,o)}while(++t)}inc(e,t,s){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);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(s)?1:0;if(!t&&s===!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(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];s===!1&&(n=[t]),me(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=jn;const lr=H,xn=(r,e,t=!1)=>{if(r instanceof lr)return r;try{return new lr(r,e)}catch(s){if(!t)return null;throw s}};var Se=xn;const Vn=Se,Un=(r,e)=>{const t=Vn(r,e);return t?t.version:null};var Gn=Un;const Jn=Se,Mn=(r,e)=>{const t=Jn(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var _n=Mn;const ur=H,Kn=(r,e,t,s,o)=>{typeof t=="string"&&(o=s,s=t,t=void 0);try{return new ur(r instanceof ur?r.version:r,t).inc(e,s,o).version}catch{return null}};var Hn=Kn;const dr=Se,qn=(r,e)=>{const t=dr(r,null,!0),s=dr(e,null,!0),o=t.compare(s);if(o===0)return null;const n=o>0,i=n?t:s,a=n?s:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c)return!a.patch&&!a.minor?"major":i.patch?"patch":i.minor?"minor":"major";const u=c?"pre":"";return t.major!==s.major?u+"major":t.minor!==s.minor?u+"minor":t.patch!==s.patch?u+"patch":"prerelease"};var Wn=qn;const zn=H,Xn=(r,e)=>new zn(r,e).major;var Yn=Xn;const Qn=H,Zn=(r,e)=>new Qn(r,e).minor;var ei=Zn;const ti=H,ri=(r,e)=>new ti(r,e).patch;var si=ri;const oi=Se,ni=(r,e)=>{const t=oi(r,e);return t&&t.prerelease.length?t.prerelease:null};var ii=ni;const pr=H,ai=(r,e,t)=>new pr(r,t).compare(new pr(e,t));var re=ai;const ci=re,li=(r,e,t)=>ci(e,r,t);var ui=li;const di=re,pi=(r,e)=>di(r,e,!0);var hi=pi;const hr=H,fi=(r,e,t)=>{const s=new hr(r,t),o=new hr(e,t);return s.compare(o)||s.compareBuild(o)};var At=fi;const gi=At,mi=(r,e)=>r.sort((t,s)=>gi(t,s,e));var vi=mi;const yi=At,Si=(r,e)=>r.sort((t,s)=>yi(s,t,e));var bi=Si;const wi=re,Pi=(r,e,t)=>wi(r,e,t)>0;var et=Pi;const Ci=re,Ri=(r,e,t)=>Ci(r,e,t)<0;var Lt=Ri;const Ei=re,ki=(r,e,t)=>Ei(r,e,t)===0;var is=ki;const Oi=re,$i=(r,e,t)=>Oi(r,e,t)!==0;var as=$i;const Ti=re,Fi=(r,e,t)=>Ti(r,e,t)>=0;var Dt=Fi;const Ii=re,Ai=(r,e,t)=>Ii(r,e,t)<=0;var Nt=Ai;const Li=is,Di=as,Ni=et,Bi=Dt,ji=Lt,xi=Nt,Vi=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Li(r,t,s);case"!=":return Di(r,t,s);case">":return Ni(r,t,s);case">=":return Bi(r,t,s);case"<":return ji(r,t,s);case"<=":return xi(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};var cs=Vi;const Ui=H,Gi=Se,{safeRe:Ve,t:Ue}=Fe,Ji=(r,e)=>{if(r instanceof Ui)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Ve[Ue.COERCEFULL]:Ve[Ue.COERCE]);else{const c=e.includePrerelease?Ve[Ue.COERCERTLFULL]:Ve[Ue.COERCERTL];let l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;const s=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Gi(`${s}.${o}.${n}${i}${a}`,e)};var Mi=Ji;class _i{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 Ki=_i,it,fr;function se(){if(fr)return it;fr=1;const r=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(r," "),this.set=this.raw.split("||").map(S=>this.parseRange(S.trim())).filter(S=>S.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const S=this.set[0];if(this.set=this.set.filter(P=>!O(P[0])),this.set.length===0)this.set=[S];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&L(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 v=this.set[p];for(let S=0;S<v.length;S++)S>0&&(this.formatted+=" "),this.formatted+=v[S].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const S=((this.options.includePrerelease&&f)|(this.options.loose&&h))+":"+p,P=s.get(S);if(P)return P;const b=this.options.loose,C=b?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];p=p.replace(C,Y(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[l.COMPARATORTRIM],u),i("comparator trim",p),p=p.replace(c[l.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[l.CARETTRIM],m),i("caret trim",p);let F=p.split(" ").map(I=>q(I,this.options)).join(" ").split(/\s+/).map(I=>G(I,this.options));b&&(F=F.filter(I=>(i("loose invalid filter",I,this.options),!!I.match(c[l.COMPARATORLOOSE])))),i("range list",F);const R=new Map,A=F.map(I=>new n(I,this.options));for(const I of A){if(O(I))return[I];R.set(I.value,I)}R.size>1&&R.has("")&&R.delete("");const V=[...R.values()];return s.set(S,V),V}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(S=>x(S,v)&&p.set.some(P=>x(P,v)&&S.every(b=>P.every(C=>b.intersects(C,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(ge(this.set[v],p,this.options))return!0;return!1}}it=e;const t=Ki,s=new t,o=It,n=tt(),i=Ze,a=H,{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:m}=Fe,{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:h}=Qe,O=y=>y.value==="<0.0.0-0",L=y=>y.value==="",x=(y,p)=>{let v=!0;const S=y.slice();let P=S.pop();for(;v&&S.length;)v=S.every(b=>P.intersects(b,p)),P=S.pop();return v},q=(y,p)=>(i("comp",y,p),y=D(y,p),i("caret",y),y=ue(y,p),i("tildes",y),y=de(y,p),i("xrange",y),y=M(y,p),i("stars",y),y),T=y=>!y||y.toLowerCase()==="x"||y==="*",ue=(y,p)=>y.trim().split(/\s+/).map(v=>fe(v,p)).join(" "),fe=(y,p)=>{const v=p.loose?c[l.TILDELOOSE]:c[l.TILDE];return y.replace(v,(S,P,b,C,F)=>{i("tilde",y,S,P,b,C,F);let R;return T(P)?R="":T(b)?R=`>=${P}.0.0 <${+P+1}.0.0-0`:T(C)?R=`>=${P}.${b}.0 <${P}.${+b+1}.0-0`:F?(i("replaceTilde pr",F),R=`>=${P}.${b}.${C}-${F} <${P}.${+b+1}.0-0`):R=`>=${P}.${b}.${C} <${P}.${+b+1}.0-0`,i("tilde return",R),R})},D=(y,p)=>y.trim().split(/\s+/).map(v=>X(v,p)).join(" "),X=(y,p)=>{i("caret",y,p);const v=p.loose?c[l.CARETLOOSE]:c[l.CARET],S=p.includePrerelease?"-0":"";return y.replace(v,(P,b,C,F,R)=>{i("caret",y,P,b,C,F,R);let A;return T(b)?A="":T(C)?A=`>=${b}.0.0${S} <${+b+1}.0.0-0`:T(F)?b==="0"?A=`>=${b}.${C}.0${S} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.0${S} <${+b+1}.0.0-0`:R?(i("replaceCaret pr",R),b==="0"?C==="0"?A=`>=${b}.${C}.${F}-${R} <${b}.${C}.${+F+1}-0`:A=`>=${b}.${C}.${F}-${R} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.${F}-${R} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?A=`>=${b}.${C}.${F}${S} <${b}.${C}.${+F+1}-0`:A=`>=${b}.${C}.${F}${S} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.${F} <${+b+1}.0.0-0`),i("caret return",A),A})},de=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>W(v,p)).join(" ")),W=(y,p)=>{y=y.trim();const v=p.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return y.replace(v,(S,P,b,C,F,R)=>{i("xRange",y,S,P,b,C,F,R);const A=T(b),V=A||T(C),I=V||T(F),ce=I;return P==="="&&ce&&(P=""),R=p.includePrerelease?"-0":"",A?P===">"||P==="<"?S="<0.0.0-0":S="*":P&&ce?(V&&(C=0),F=0,P===">"?(P=">=",V?(b=+b+1,C=0,F=0):(C=+C+1,F=0)):P==="<="&&(P="<",V?b=+b+1:C=+C+1),P==="<"&&(R="-0"),S=`${P+b}.${C}.${F}${R}`):V?S=`>=${b}.0.0${R} <${+b+1}.0.0-0`:I&&(S=`>=${b}.${C}.0${R} <${b}.${+C+1}.0-0`),i("xRange return",S),S})},M=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[l.STAR],"")),G=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?l.GTE0PRE:l.GTE0],"")),Y=y=>(p,v,S,P,b,C,F,R,A,V,I,ce)=>(T(S)?v="":T(P)?v=`>=${S}.0.0${y?"-0":""}`:T(b)?v=`>=${S}.${P}.0${y?"-0":""}`:C?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,T(A)?R="":T(V)?R=`<${+A+1}.0.0-0`:T(I)?R=`<${A}.${+V+1}.0-0`:ce?R=`<=${A}.${V}.${I}-${ce}`:y?R=`<${A}.${V}.${+I+1}-0`:R=`<=${R}`,`${v} ${R}`.trim()),ge=(y,p,v)=>{for(let S=0;S<y.length;S++)if(!y[S].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let S=0;S<y.length;S++)if(i(y[S].semver),y[S].semver!==n.ANY&&y[S].semver.prerelease.length>0){const P=y[S].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return it}var at,gr;function tt(){if(gr)return at;gr=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}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===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(u){const d=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],m=u.match(d);if(!m)throw new TypeError(`Invalid comparator: ${u}`);this.operator=m[1]!==void 0?m[1]:"",this.operator==="="&&(this.operator=""),m[2]?this.semver=new a(m[2],this.options.loose):this.semver=r}toString(){return this.value}test(u){if(i("Comparator.test",u,this.options.loose),this.semver===r||u===r)return!0;if(typeof u=="string")try{u=new a(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 c(u.value,d).test(this.value):u.operator===""?u.value===""?!0:new c(this.value,d).test(u.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||u.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||u.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&u.operator.startsWith(">")||this.operator.startsWith("<")&&u.operator.startsWith("<")||this.semver.version===u.semver.version&&this.operator.includes("=")&&u.operator.includes("=")||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=It,{safeRe:s,t:o}=Fe,n=cs,i=Ze,a=H,c=se();return at}const Hi=se(),qi=(r,e,t)=>{try{e=new Hi(e,t)}catch{return!1}return e.test(r)};var rt=qi;const Wi=se(),zi=(r,e)=>new Wi(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));var Xi=zi;const Yi=H,Qi=se(),Zi=(r,e,t)=>{let s=null,o=null,n=null;try{n=new Qi(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===-1)&&(s=i,o=new Yi(s,t))}),s};var ea=Zi;const ta=H,ra=se(),sa=(r,e,t)=>{let s=null,o=null,n=null;try{n=new ra(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===1)&&(s=i,o=new ta(s,t))}),s};var oa=sa;const ct=H,na=se(),mr=et,ia=(r,e)=>{r=new na(r,e);let t=new ct("0.0.0");if(r.test(t)||(t=new ct("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s<r.set.length;++s){const o=r.set[s];let n=null;o.forEach(i=>{const a=new ct(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||mr(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||mr(t,n))&&(t=n)}return t&&r.test(t)?t:null};var aa=ia;const ca=se(),la=(r,e)=>{try{return new ca(r,e).range||"*"}catch{return null}};var ua=la;const da=H,ls=tt(),{ANY:pa}=ls,ha=se(),fa=rt,vr=et,yr=Lt,ga=Nt,ma=Dt,va=(r,e,t,s)=>{r=new da(r,s),e=new ha(e,s);let o,n,i,a,c;switch(t){case">":o=vr,n=ga,i=yr,a=">",c=">=";break;case"<":o=yr,n=ma,i=vr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fa(r,e,s))return!1;for(let l=0;l<e.set.length;++l){const u=e.set[l];let d=null,m=null;if(u.forEach(f=>{f.semver===pa&&(f=new ls(">=0.0.0")),d=d||f,m=m||f,o(f.semver,d.semver,s)?d=f:i(f.semver,m.semver,s)&&(m=f)}),d.operator===a||d.operator===c||(!m.operator||m.operator===a)&&n(r,m.semver))return!1;if(m.operator===c&&i(r,m.semver))return!1}return!0};var Bt=va;const ya=Bt,Sa=(r,e,t)=>ya(r,e,">",t);var ba=Sa;const wa=Bt,Pa=(r,e,t)=>wa(r,e,"<",t);var Ca=Pa;const Sr=se(),Ra=(r,e,t)=>(r=new Sr(r,t),e=new Sr(e,t),r.intersects(e,t));var Ea=Ra;const ka=rt,Oa=re;var $a=(r,e,t)=>{const s=[];let o=null,n=null;const i=r.sort((u,d)=>Oa(u,d,t));for(const u of i)ka(u,e,t)?(n=u,o||(o=u)):(n&&s.push([o,n]),n=null,o=null);o&&s.push([o,null]);const a=[];for(const[u,d]of s)u===d?a.push(u):!d&&u===i[0]?a.push("*"):d?u===i[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);const c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length<l.length?c:e};const br=se(),jt=tt(),{ANY:lt}=jt,be=rt,xt=re,Ta=(r,e,t={})=>{if(r===e)return!0;r=new br(r,t),e=new br(e,t);let s=!1;e:for(const o of r.set){for(const n of e.set){const i=Ia(o,n,t);if(s=s||i!==null,i)continue e}if(s)return!1}return!0},Fa=[new jt(">=0.0.0-0")],wr=[new jt(">=0.0.0")],Ia=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===lt){if(e.length===1&&e[0].semver===lt)return!0;t.includePrerelease?r=Fa:r=wr}if(e.length===1&&e[0].semver===lt){if(t.includePrerelease)return!0;e=wr}const s=new Set;let o,n;for(const f of r)f.operator===">"||f.operator===">="?o=Pr(o,f,t):f.operator==="<"||f.operator==="<="?n=Cr(n,f,t):s.add(f.semver);if(s.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 f of s){if(o&&!be(f,String(o),t)||n&&!be(f,String(n),t))return null;for(const h of e)if(!be(f,String(h),t))return!1;return!0}let a,c,l,u,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,m=o&&!t.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&n.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(const f of e){if(u=u||f.operator===">"||f.operator===">=",l=l||f.operator==="<"||f.operator==="<=",o){if(m&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===m.major&&f.semver.minor===m.minor&&f.semver.patch===m.patch&&(m=!1),f.operator===">"||f.operator===">="){if(a=Pr(o,f,t),a===f&&a!==o)return!1}else if(o.operator===">="&&!be(o.semver,String(f),t))return!1}if(n){if(d&&f.semver.prerelease&&f.semver.prerelease.length&&f.semver.major===d.major&&f.semver.minor===d.minor&&f.semver.patch===d.patch&&(d=!1),f.operator==="<"||f.operator==="<="){if(c=Cr(n,f,t),c===f&&c!==n)return!1}else if(n.operator==="<="&&!be(n.semver,String(f),t))return!1}if(!f.operator&&(n||o)&&i!==0)return!1}return!(o&&l&&!n&&i!==0||n&&u&&!o&&i!==0||m||d)},Pr=(r,e,t)=>{if(!r)return e;const s=xt(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},Cr=(r,e,t)=>{if(!r)return e;const s=xt(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};var Aa=Ta;const ut=Fe,Rr=Qe,La=H,Er=ns,Da=Se,Na=Gn,Ba=_n,ja=Hn,xa=Wn,Va=Yn,Ua=ei,Ga=si,Ja=ii,Ma=re,_a=ui,Ka=hi,Ha=At,qa=vi,Wa=bi,za=et,Xa=Lt,Ya=is,Qa=as,Za=Dt,ec=Nt,tc=cs,rc=Mi,sc=tt(),oc=se(),nc=rt,ic=Xi,ac=ea,cc=oa,lc=aa,uc=ua,dc=Bt,pc=ba,hc=Ca,fc=Ea,gc=$a,mc=Aa;var vc={parse:Da,valid:Na,clean:Ba,inc:ja,diff:xa,major:Va,minor:Ua,patch:Ga,prerelease:Ja,compare:Ma,rcompare:_a,compareLoose:Ka,compareBuild:Ha,sort:qa,rsort:Wa,gt:za,lt:Xa,eq:Ya,neq:Qa,gte:Za,lte:ec,cmp:tc,coerce:rc,Comparator:sc,Range:oc,satisfies:nc,toComparators:ic,maxSatisfying:ac,minSatisfying:cc,minVersion:lc,validRange:uc,outside:dc,gtr:pc,ltr:hc,intersects:fc,simplifyRange:gc,subset:mc,SemVer:La,re:ut.re,src:ut.src,tokens:ut.t,SEMVER_SPEC_VERSION:Rr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Rr.RELEASE_TYPES,compareIdentifiers:Er.compareIdentifiers,rcompareIdentifiers:Er.rcompareIdentifiers};const yc=En(vc),Sc={minDelay:1500},bc="__no_updates__";class wc extends j.PollComputablePool{constructor(t,s,o={}){super({...o,...Sc},s);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_${te(t)}`;default:return bc}}async readValue(t){var s,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 a=await qe(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let l=this.preferredUpdateChannel;if(l===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,U.StableChannel))l=U.StableChannel;else{if(await c.getLatestOverview(n.id,U.AnyChannel)===void 0)return this.logger.error(`No "any" channel record for ${U.blockPackIdToString(n.id)}`),{suggestions:[]};l=U.AnyChannel}else l=n.channel;const u=await c.getUpdateSuggestions(n.id,l);if(u===void 0||u.length===0)return{suggestions:[]};u.reverse();let d;switch(i){case void 0:d=u[0].update;break;case"major":d=(s=u.find(h=>h.type!=="major"))==null?void 0:s.update;break;case"minor":d=(o=u.find(h=>h.type==="patch"))==null?void 0:o.update;break}const m=u.map(({type:h,update:O})=>({type:h,update:{...n,id:{...n.id,version:O}}}));if(d===void 0)return{suggestions:m};if(a!==void 0&&yc.lte(d,a))return{suggestions:m};const f={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(f.id)}catch(h){this.logger.warn(h)}})(),{suggestions:m,mainSuggestion:f}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,s){return te(t)===te(s)}}class kr{constructor(){w(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let s=this.resources.get(t);s===void 0&&(s={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,s)),s.refCount++;let o=!1;return{resource:s.resource,key:t,unref:()=>{o||(s.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 we;function ne(){return we||(we={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,usePFrameRs:process.env.MI_USE_PFRAMES_RS!==void 0},process.env.MI_LOG_TREE_STAT&&(we.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),we)}function Oe(r){return String(r.id)}const Pc=["Int","Long","Float","Double","String","Bytes"];function Pe(r){const e=[],t=[];for(const s of r)s.type==="bySingleColumn"?(e.push(s),t.push({...s,type:"bySingleColumnV2"})):t.push(s);if(e.length>0){const s=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${s}`)}return t}function Or(r){const e=t=>{switch(t.operator){case"Matches":case"StringContainsFuzzy":case"StringIContainsFuzzy":return!1;case"Not":return e(t.operand);case"And":case"Or":return t.operands.every(s=>e(s));default:return!0}};return r.every(t=>e(t.predicate))}const Ce=(r,e)=>typeof e=="bigint"?e.toString():e;class Cc{constructor(e,t,s,o){w(this,"rustPFrame");w(this,"blobIdToResource",new Map);w(this,"blobHandleComputables",new Map);w(this,"createDataPFrame");w(this,"preloadBlob",async e=>{const t=e.map(s=>this.getOrCreateComputableForBlob(s));for(const s of t)await s.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),s=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(s)}catch(t){const s=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${s}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=s;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of wo(a.data))this.blobIdToResource.set(Oe(c),c);const i=[...new Map(o.map(a=>({...a,data:Po(a.data,Oe)})).map(a=>[te(a),a])).values()];this.rustPFrame=(()=>{try{const a=new Ss.PFrame(ne().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);return a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}})(),this.createDataPFrame=()=>{try{const a=ne().logPFrameRequests?new Mt.PFrame(n):new Mt.PFrame;a.setDataSource(this);for(const c of i)try{a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data)}catch(l){throw new Error(`Adding column ${c.id} to PFrame failed: ${l}; Spec: ${JSON.stringify(c.spec)}, DataInfo: ${JSON.stringify(c.data)}.`)}return a}catch(a){throw new Error(`Data PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}}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 s=this.blobIdToResource.get(e);if(s===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(s).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Rc{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class Ec{constructor(e,t){w(this,"pFrames");w(this,"pTables");w(this,"blobContentCache");w(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const s=new bs.LRUCache({maxSize:1e9,fetchMethod:async n=>await Ir.readFile(n),sizeCalculation:n=>n.length});this.blobContentCache=s;const o=new E.ConcurrencyLimitingExecutor(1);this.concurrencyLimiter=o,this.pFrames=new class extends kr{constructor(n,i){super(),this.blobDriver=n,this.logger=i}createNewResource(n){return ne().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Ce)}`),new Cc(this.blobDriver,this.logger,s,n)}calculateParamsKey(n){return Oc(n)}}(this.blobDriver,this.logger),this.pTables=new class extends kr{constructor(n){super(),this.pFrames=n}createNewResource(n){const i=n.pFrameHandle,a=o.run(async()=>{if(ne().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Ce)}`),ne().usePFrameRs&&Or(n.def.filters))return await this.pFrames.getByKey(i).rustPFrame.createTable({src:pe(n.def.src),filters:Pe(n.def.filters)},n.signal);var c=[];try{const m=Ie(c,this.pFrames.getByKey(i).disposableDataPFrame);return await m.dataPFrame.createTable({src:pe(n.def.src),filters:Pe(n.def.filters)},n.signal)}catch(l){var u=l,d=!0}finally{Ae(c,u,d)}}).then(async c=>n.def.sorting.length!==0?await c.sort(n.def.sorting,n.signal):c);return new Rc(a)}calculateParamsKey(n){return kc(n)}}(this.pFrames)}createPFrame(e,t){const s=e.filter(n=>Pc.find(i=>i===n.spec.valueType)).map(n=>B.mapPObjectData(n,i=>He.isPlTreeNodeAccessor(i)?$o(i):To(n.spec,i))),o=this.pFrames.acquire(s);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,s){const o=this.createPFrame(B.extractAllColumns(e.src),t),n=B.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:s});return ne().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(B.mapPTableDef(e,a=>a.spec),Ce)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const s={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[te(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).rustPFrame.findColumns(s)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,s){let o=await this.concurrencyLimiter.run(async()=>{if(ne().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),ne().usePFrameRs&&Or(t.filters))return await this.pFrames.getByKey(e).rustPFrame.createTable({src:pe(t.src),filters:Pe(t.filters)},s);var a=[];try{const d=Ie(a,this.pFrames.getByKey(e).disposableDataPFrame);return await d.dataPFrame.createTable({src:pe(t.src),filters:Pe(t.filters)},s)}catch(c){var l=c,u=!0}finally{Ae(a,l,u)}});if(t.sorting.length>0){const a=await this.concurrencyLimiter.run(async()=>await o.sort(t.sorting,s));o.dispose(),o=a}const n=o.getSpec(),i=await this.concurrencyLimiter.run(async()=>await o.getData([...n.keys()]));return o.dispose(),n.map((a,c)=>({spec:a,data:i[c]}))}async getUniqueValues(e,t,s){return await this.concurrencyLimiter.run(async()=>{var n=[];try{ne().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ce)}`);const o=Ie(n,this.pFrames.getByKey(e).disposableDataPFrame);return await o.dataPFrame.getUniqueValues({...t,filters:Pe(t.filters)},s)}catch(i){var a=i,c=!0}finally{Ae(n,a,c)}})}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,s){const o=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await o.getData(t,s))}}function pe(r){switch(r.type){case"column":return{type:"column",columnId:r.column,qualifications:[]};case"inner":case"full":return{type:r.type,entries:r.entries.map(e=>pe(e))};case"outer":return{type:"outer",primary:pe(r.primary),secondary:r.secondary.map(e=>pe(e))};default:E.assertNever(r)}}function kc(r){const e=ae.createHash("sha256");return e.update(te(r)),e.digest().toString("hex")}function Oc(r){const e=[...r].map(s=>B.mapPObjectData(s,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:Oe(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[Oe(c.index),Oe(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((s,o)=>s.id.localeCompare(o.id));const t=ae.createHash("sha256");return t.update(te(e)),t.digest().toString("hex")}async function us(r,e,t){const s={...Tt,...Ft(e),...t},o=new E.HmacSha256Signer(s.localSecret),n=Z.createDownloadClient(s.logger,r,s.localProjections),i=Z.createLogsClient(r,s.logger),a=Z.createUploadBlobClient(r,s.logger),c=Z.createUploadProgressClient(r,s.logger),l=new Z.DownloadDriver(s.logger,n,i,s.blobDownloadPath,o,s.blobDriverOps),u=new Z.DownloadBlobToURLDriver(s.logger,o,n,s.downloadBlobToURLPath,s.downloadBlobToURLDriverOps),d=new Z.UploadDriver(s.logger,o,a,c,s.uploadDriverOps),m=new Z.LogsStreamDriver(s.logger,i,s.logStreamDriverOps),f=new Z.LogsDriver(s.logger,m,l),h=await Z.LsDriver.init(s.logger,r,o,s.localProjections,s.openFileDialogCallback,s.virtualLocalStoragesOverride),O=new Ec(l,s.logger);return{blobDriver:l,blobToURLDriver:u,logDriver:f,lsDriver:h,signer:o,uploadDriver:d,pFrameDriver:O}}class Vt{constructor(e,t,s,o,n,i,a,c){w(this,"pl");w(this,"projectList");w(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=s,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ae.randomUUID()){const s=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await bo(o,e);return o.createField(g.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await g.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),s}async setProjectMeta(e,t,s){await ee(this.pl,e,s,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(g.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const s=(await t.getField(g.field(this.projectListResourceId,e))).value;if(g.isNullResourceId(s))throw new Error("Unexpected project list structure.");return s})}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 Ye.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 E.HmacSha256Signer.generateSecret()}static async init(e,t,s){const o={...ts,...rs(t),...s};o.defaultTreeOptions.logStat=ne().logTreeStats;const n=await e.withWriteTx("MLInitialization",async O=>{const L=g.field(O.clientRoot,Ks);O.createField(L,"Dynamic");const x=await O.getField(L);if(g.isNullResourceId(x.value)){const q=O.createEphemeral(Br);return O.lock(q),O.setField(L,q),await O.commit(),await q.globalId}else return x.value}),i=o.logger,a=await us(e,t,o),c=new le.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),l=new Lr(c),u=new ho(l,a.signer,c),d=new Z.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),m={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:u,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new wc(l,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Je.getQuickJS()},f=new j.WatchableValue([]),h=await qs(e,n,f,m);return new Vt(m,a,a.signer,n,f,h.tree,l,h.computable)}}const $c=["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 Tc(r,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},s=[];$c.forEach(c=>{ws.channel(c).subscribe(u=>{var m;const d=new Date().toISOString();(m=u==null?void 0:u.response)!=null&&m.headers&&(u.response.headers=u.response.headers.map(f=>f.toString())),s.push(JSON.stringify({timestamp:d,event:c,data:u}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=g.plAddressToConfig(r,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ve(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const l=await new g.UnauthenticatedPlClient(n).ping();return JSON.stringify(l).slice(0,t.bodyLimit)+"..."});const a=new g.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ve(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Re(t.autoUpdateCdnUrl,t,a)),Fc(o,r,t,s)}async function ve(r,e,t){const s=St(),o=[];for(;$r(s)<r;){const n=St();let i;try{i={ok:!0,value:await t()}}catch(l){i={ok:!1,error:l}}const a=$r(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Fr.setTimeout(c)}return o}async function Re(r,e,t){const{body:s,statusCode:o}=await le.request(r,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await s.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Fc(r,e,t,s){const o=r.plPings.filter(a=>a.response.ok),n=r.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.response.value)))];return`
|
|
1
|
+
"use strict";var hs=Object.defineProperty;var Gt=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Jt=r=>{throw TypeError(r)};var fs=(r,e,t)=>e in r?hs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>fs(r,typeof e!="symbol"?e+"":e,t);var Ie=(r,e,t)=>{if(e!=null){typeof e!="object"&&typeof e!="function"&&Jt("Object expected");var s;t&&(s=e[Gt("asyncDispose")]),s===void 0&&(s=e[Gt("dispose")]),typeof s!="function"&&Jt("Object not disposable"),r.push([t,s,e])}else t&&r.push([t]);return e},Ae=(r,e,t)=>{var s=typeof SuppressedError=="function"?SuppressedError:function(i,a,c,u){return u=Error(c),u.name="SuppressedError",u.error=i,u.suppressed=a,u},o=i=>e=t?new s(i,e,"An error was suppressed during disposal"):(t=!0,i),n=i=>{for(;i=r.pop();)try{var a=i[1]&&i[1].call(i[2]);if(i[0])return Promise.resolve(a).then(n,c=>(o(c),n()))}catch(c){o(c)}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"),Mt=require("@milaboratories/pl-deployments"),ue=require("undici"),H=require("@platforma-sdk/block-tools"),Z=require("node:fs"),q=require("node:path"),gs=require("yaml"),k=require("@milaboratories/ts-helpers"),ms=require("node:fs/promises"),vs=require("@milaboratories/resolve-helper"),f=require("@milaboratories/pl-client"),qe=require("@milaboratories/pl-tree"),j=require("@milaboratories/computable"),ce=require("node:crypto"),N=require("@milaboratories/pl-model-backend"),Fr=require("denque"),ys=require("@platforma-sdk/workflow-tengo"),re=require("canonicalize"),Ss=require("node:assert"),Me=require("quickjs-emscripten"),Ir=require("node:timers/promises"),ee=require("@milaboratories/pl-drivers"),_t=require("@milaboratories/pframes-node"),bs=require("@milaboratories/pframes-rs-node"),ws=require("lru-cache"),Ps=require("node:diagnostics_channel");function Cs(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Ar=Cs(ms);async function Kt(r){try{return await Ar.stat(r,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const Rs=[H.RegistryV1.PlPackageYamlConfigFile],Es=[H.RegistryV1.PlPackageJsonConfigFile],wt=["backend","dist","tengo","tpl","main.plj.gz"],Pt=["config","dist","config.json"],Lr=["frontend","dist"],Ht="block-model/dist/config.json",ks="block-ui/package.json",Os=[wt,Pt,Rs,Es,Lr];async function $s(r){return await Kt(q.join(r,...Pt))!==void 0||await Kt(q.join(r,...wt))!==void 0}function ot(r,e){const t=vs.tryResolve(r,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${r}`);return t}async function qt(r,e){if(q.isAbsolute(r)||(r=q.resolve(r)),await $s(r))return{workflow:q.join(r,...wt),config:q.join(r,...Pt),ui:q.join(r,...Lr)};{const t=ot(r,Ht),s=ot(r,Ht),o=ot(r,ks);return{workflow:t,config:s,ui:q.resolve(o,"..","dist")}}}async function Ts(r){try{return await Z.promises.readFile(r,"utf8")}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Fs(r){try{return await Z.promises.stat(r,{bigint:!0})}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return;throw e}}async function Ct(r){let e=0n;for(const t of Os){const s=q.join(r,...t),o=await Fs(s);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function We(r){const e=await Z.promises.stat(r.components.workflow.main.file,{bigint:!0}),t=await Z.promises.stat(r.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class Is{constructor(e,t,s){this.v2Provider=e,this.registries=t,this.http=s}async getPackagesForRoot(e){const t=[],s=e.spec;switch(s.type){case"remote-v1":{const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await ue.request(`${s.url}/${H.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:l,latestVersion:d}=a,g={organization:c,name:u,version:d},h={id:g,meta:{title:l.title??"No title",description:l.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:g,registryUrl:s.url}};t.push({registryId:e.id,id:g,latestByChannel:{[U.AnyChannel]:h,[U.StableChannel]:h},allVersions:a.allVersions.map(R=>({version:R,channels:[]}))})}return t}case"remote-v2":return(await this.v2Provider.getRegistry(s.url).listBlockPacks()).map(o=>o.latestByChannel[U.StableChannel]?{...o,registryId:e.id}:{...o,latestByChannel:{...o.latestByChannel,[U.StableChannel]:(n=>n.spec.type==="from-registry-v2"?{...n,spec:{...n.spec,channel:U.StableChannel}}:n)(o.latestByChannel[U.AnyChannel])},registryId:e.id});case"local-dev":for(const o of await Z.promises.readdir(s.path,{withFileTypes:!0})){if(!o.isDirectory())continue;const n=q.join(s.path,o.name),i=await Ts(q.join(n,H.RegistryV1.PlPackageYamlConfigFile));if(i!==void 0){const a=H.RegistryV1.PlPackageConfigData.parse(gs.parse(i)),c=await Ct(n),u={organization:a.organization,name:a.package,version:"DEV"},l={id:u,meta:{title:a.meta.title??"No title",description:a.meta.description??"No Description",organization:{name:a.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:n,mtime:c}};t.push({registryId:e.id,id:u,latestByChannel:{[U.AnyChannel]:l,[U.StableChannel]:l},allVersions:[]})}else{let a=n,c=await H.tryLoadPackDescription(a);if(c===void 0){for(const u of["block","meta"])if(a=q.join(n,u),c=await H.tryLoadPackDescription(a),c!==void 0)break}if(c!==void 0){const u=await We(c),l={id:c.id,meta:await H.BlockPackMetaEmbedAbsoluteBytes.parseAsync(c.meta),spec:{type:"dev-v2",folder:a,mtime:u}};t.push({registryId:e.id,id:c.id,latestByChannel:{[U.AnyChannel]:l,[U.StableChannel]:l},allVersions:[]})}}}return t;default:return k.assertNever(s)}}async listBlockPacks(){const e=[],t=[];for(const s of this.registries)t.push({...s,status:"online"}),e.push(...await this.getPackagesForRoot(s));return{registries:t,blockPacks:e}}async getOverview(e,t,s){var i;const o=(i=this.registries.find(a=>a.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,s)}}class Dr{constructor(e){w(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const s=new H.RegistryV2Reader(H.folderReaderByUrl(e,this.http));return this.registries.set(e,s),s}}const As={type:"remote-v2",url:"https://blocks.pl-open.science/"},Ls={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},Ds={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},Ns={groups:[{id:"default",label:"Default",blocks:[]}]},Bs={stagingRefreshTimestamp:0,blocksInLimbo:[]},js={label:"New Project"},xs={name:"UserProject",version:"2"},Nr="SchemaVersion",Br="1",Rt="ProjectCreated",$e="ProjectLastModified",Te="ProjectMeta",he="ProjectStructure",_e="BlockRenderingState",Vs="BlockFrontendState/",Us=/^BlockFrontendState\/(?<blockid>.*)$/;function pt(r){return`${Vs}${r}`}const Gs="BlockArgsAuthor/";function ht(r){return`${Gs}${r}`}const ft="ProjectStructureAuthor";function Js(r){const e=r.match(Us);if(e!==null)return e.groups.blockid}const Ms="__serviceTemplate_";function gt(r){return`${Ms}${r}`}function M(r,e){return`${r}-${e}`}const _s=/^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Ks(r){const e=r.match(_s);if(e===null)return;const{blockId:t,fieldName:s}=e.groups;return{blockId:t,fieldName:s}}const Hs="projects",jr={name:"Projects",version:"1"},qs=r=>f.resourceTypesEqual(r.type,jr)?r.fields:[];async function Ws(r,e,t,s){const o=await qe.SynchronizedTreeState.init(r,e,{...s.ops.defaultTreeOptions,pruning:qs},s.logger);return{computable:j.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const l of a.listDynamicFields()){const d=a.traverse(l);if(d===void 0)continue;const g=k.notEmpty(d.getKeyValueAsJson(Te)),h=k.notEmpty(d.getKeyValueAsJson(Rt)),R=k.notEmpty(d.getKeyValueAsJson($e));u.push({id:l,rid:d.id,created:new Date(h),lastModified:new Date(R),opened:c.indexOf(d.id)>=0,meta:g})}return u.sort(l=>-l.lastModified.valueOf()),u}).withStableType(),tree:o}}const zs={name:"EphRenderTemplate",version:"1"},Xs={name:"RenderTemplate",version:"1"};function Et(r,e,t,s,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?r.createEphemeral(zs):r.createStruct(Xs),i=f.field(n,"template"),a=f.field(n,"inputs");return r.createField(i,"Input",e),r.createField(a,"Input",f.Pl.createPlMap(r,s,t)),r.lockInputs(n),f.Pl.futureRecord(r,n,o,"Output","outputs/")}const Ys={name:"BContextEnd",version:"1"},Qs={name:"BContext",version:"1"},Zs="id",eo="parent/",to=["context","result"];function Wt(r,e,t){return Et(r,e,!0,t,to)}function ro(r){const e=r.createEphemeral(Ys);return r.lock(e),e}function zt(r,e){if(e.length===0)return ro(r);if(e.length===1)return e[0];const t=r.createEphemeral(Qs);r.createField(f.field(t,Zs),"Input",f.Pl.createPlString(r,ce.randomUUID()));for(let s=0;s<e.length;s++)r.createField(f.field(t,`${eo}${s}`),"Input",e[s]);return r.lock(t),t}function so(r,e){const t=N.parseTemplate(e.content),s=t.type;switch(s){case"pl.tengo-template.v2":return no(r,t);default:k.assertNever(s)}}const Xt={hash(r,e){e.update(N.PlTemplateLibV1.type.name).update(N.PlTemplateLibV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){return e.createValue(N.PlTemplateLibV1.type,JSON.stringify(N.PlTemplateLibV1.fromV2Data(r).data))}},Le={hash(r,e){e.update(N.PlTemplateSoftwareV1.type.name).update(N.PlTemplateSoftwareV1.type.version).update(r.name).update(r.version).update(r.src)},render(r,e,t){const s=N.PlTemplateSoftwareV1.fromV2Data(r),o=e.createStruct(N.PlTemplateSoftwareV1.type,s.data);return e.setKValue(o,N.PlTemplateSoftwareV1.metaNameKey,JSON.stringify(s.name)),e.lock(o),o}},oo={hash(r,e){e.update(N.PlTemplateOverrideV1.type.name).update(N.PlTemplateOverrideV1.type.version).update(r.hashOverride??"")},render(r,e,t){return e.createStruct(N.PlTemplateOverrideV1.type,JSON.stringify(N.PlTemplateOverrideV1.fromV2Data(r)))}},xr={hash(r,e){e.update(N.PlTemplateV1.type.name).update(N.PlTemplateV1.type.version).update(r.hashOverride??"").update(r.name).update(r.version).update(r.src);const t=s=>(s.sort((o,n)=>o[0]===n[0]?0:o[0]<n[0]?-1:1),s);for(const[s,o]of t(Object.entries(r.libs??{})))e.update("lib:"+s),Xt.hash(o,e);for(const[s,o]of t(Object.entries(r.software??{})))e.update("soft:"+s),Le.hash(o,e);for(const[s,o]of t(Object.entries(r.assets??{})))e.update("asset:"+s),Le.hash(o,e);for(const[s,o]of t(Object.entries(r.templates??{})))e.update("tpl:"+s),this.hash(o,e)},render(r,e,t){const s=e.createStruct(N.PlTemplateV1.type,JSON.stringify(N.PlTemplateV1.fromV2Data(r).data));for(const[i,a]of Object.entries(r.libs??{})){const c=N.PlTemplateV1.libField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Xt))}for(const[i,a]of Object.entries(r.software??{})){const c=N.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Le))}for(const[i,a]of Object.entries(r.assets??{})){const c=N.PlTemplateV1.swField(s,i);e.createField(c,"Input"),e.setField(c,t(a,Le))}for(const[i,a]of Object.entries(r.templates??{})){const c=N.PlTemplateV1.tplField(s,i);e.createField(c,"Input"),e.setField(c,t(a,xr))}if(e.lock(s),!r.hashOverride)return s;const o=t(r,oo),n=N.PlTemplateOverrideV1.tplField(o);return e.createField(n,"Service"),e.setField(n,s),e.lock(s),o}};function no(r,e){const t=new Map,s=(o,n)=>{const i=ce.createHash("sha256");n.hash(o,i);const a=i.digest("hex");if(!t.has(a)){const c=n.render(o,r,s);t.set(a,c)}return t.get(a)};return s(e,xr)}const Vr={name:"TengoTemplateGet",version:"1"},Ur="registry",Gr="templateURI",Jr="template",io={name:"TengoTemplatePack",version:"1"},ao={name:"TengoTemplatePackConvert",version:"1"},co="templatePack",lo="template";async function Mr(r){switch(r.type){case"from-file":return{type:"explicit",content:await Z.promises.readFile(r.path)};case"from-registry":case"explicit":return r;default:return k.assertNever(r)}}function uo(r,e){const t=r.createStruct(Vr),s=f.field(t,Ur),o=f.field(t,Gr),n=f.field(t,Jr);return r.setField(s,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),r.setField(o,r.createValue(f.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function ze(r,e){switch(e.type){case"from-registry":return uo(r,e);case"explicit":return so(r,e);default:return k.assertNever(e)}}const kt={name:"Frontend/FromUrl",version:"1"},Ot={name:"Frontend/FromFolder",version:"1"};function po(r,e){switch(e.type){case"url":return r.createValue(kt,JSON.stringify({url:e.url}));case"local":return r.createValue(Ot,JSON.stringify({path:e.path,signature:e.signature}));default:return k.assertNever(e)}}const ho={name:"BlockPackCustom",version:"1"},_r="template",Kr="frontend";function Yt(r){return r.endsWith("/")?r:`${r}/`}class fo{constructor(e,t,s){this.v2RegistryProvider=e,this.signer=t,this.http=s}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await qt(e.folder),s=await Z.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(s)}case"dev-v2":{const t=await H.loadPackDescription(e.folder),s=await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(s)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},s=`${Yt(e.registryUrl)}${H.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await ue.request(`${s}/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 ue.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 qt(e.folder),s=await Z.promises.readFile(t.workflow),o=JSON.parse(await Z.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:s},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await H.loadPackDescription(e.folder),s=JSON.parse(await Z.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await Z.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await We(t)),{type:"explicit",template:{type:"explicit",content:o},config:s,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}:{},s=`${Yt(e.registryUrl)}${H.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${s}/template.plj.gz`,n=await ue.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()),c=await(await ue.request(`${s}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:c,frontend:{type:"url",url:`${s}/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 ue.request(o.model.url,t)).body.json(),i=async()=>await(await ue.request(o.workflow.main.url,t)).body.arrayBuffer(),[a,c]=await Promise.all([n(),i()]);return{type:"explicit",template:{type:"explicit",content:Buffer.from(c)},config:a,frontend:{type:"url",url:o.ui.url},source:e}}default:return k.assertNever(e)}}}function go(r,e){const t={config:e.config,source:e.source},s=r.createStruct(ho,JSON.stringify(t));return r.createField(f.field(s,_r),"Input",ze(r,e.template)),r.createField(f.field(s,Kr),"Input",po(r,e.frontend)),r.lock(s),s}function Qt(r,e){switch(e.type){case"explicit":return go(r,e);default:return k.assertNever(e.type)}}function De(r,e){return{__isRef:!0,blockId:r,name:e}}function mo(r){return typeof r=="object"&&r!==null&&"__isRef"in r&&r.__isRef===!0&&"blockId"in r&&"name"in r}function mt(r,e,t){const s=typeof e;switch(s){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(mo(e))t===void 0||t.has(e.blockId)?r.upstreams.add(e.blockId):r.missingReferences=!0;else if(Array.isArray(e))for(const o of e)mt(r,o,t);else for(const[,o]of Object.entries(e))mt(r,o,t);return;default:k.assertNever(s)}}function vo(r,e){const t={upstreams:new Set,missingReferences:!1};return mt(t,r,e),t}function ae(r){return{*[Symbol.iterator](){for(const e of r.groups)for(const t of e.blocks)yield t}}}class Hr{constructor(e){w(this,"nodes");this.nodes=e}traverseIds(e,...t){const s=new Set;return this.traverse(e,t,o=>s.add(o.id)),s}traverseIdsExcludingRoots(e,...t){const s=this.traverseIds(e,...t);for(const o of t)s.delete(o);return s}traverse(e,t,s){let o=[...t];const n=new Set(o);for(;o.length>0;){const i=[];for(const a of o){const c=this.nodes.get(a);s(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function vt(r){const e=new Map;let t;for(const{id:s}of ae(r)){const o={id:s,missingReferences:!1};e.set(s,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 Hr(e)}function Je(r,e){const t=new Map,s=new Set;for(const{id:o}of ae(r)){const n=e(o);if(n===void 0)continue;const i=vo(n,s),a={id:o,missingReferences:i.missingReferences,upstream:i.upstreams,downstream:new Set};t.set(o,a),i.upstreams.forEach(c=>t.get(c).downstream.add(o)),s.add(o)}return new Hr(t)}function yo(r,e){if(r.size!==e.size)return!1;for(const t of r)if(!e.has(t))return!1;return!0}function yt(r,e){if(r.size>e.size)return yt(e,r);for(const t of r)if(e.has(t))return!0;return!1}function Zt(r,e){const t=new Set,s=new Set,o=new Set;return r.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!yo(n.upstream,i.upstream)||yt(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{r.nodes.has(n.id)?yt(n.upstream,o)&&o.add(n.id):s.add(n.id)}),{onlyInA:t,onlyInB:s,different:o}}let nt;async function qr(){if(nt===void 0){const r=await Mr(ys.Templates["pframes.export-pframe"]);if(r.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=ce.createHash("sha256").update(r.content).digest("hex");nt={spec:r,hash:e}}return nt}function So(r,e,t){return Et(r,e,!0,{pf:t},["result"]).result}function it(r,e){let t=!1,s,o;return()=>{if(!t)return t=!0,s=r(),o=e(),o;const n=r();return s!==n&&(s=n,o=e()),e()}}class er{constructor(e,t){w(this,"currentInputsC",it(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));w(this,"actualProductionInputsC",it(()=>{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",it(()=>{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(f.Pl.unwrapHolder(e,this.fields.blockPack.ref),_r,"Input")}}const bo=r=>{throw new Error(`No new block info for ${r}`)};class Ke{constructor(e,t,s,o,n,i,a,c,u,l,d,g){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=s,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=l,this.blockFrontendStates=d,this.ctxExportTplHolder=g}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=Je(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=Je(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(f.Pl.JsonObject,t),value:t,status:"Ready"}}createJsonFieldValue(e){return this.createJsonFieldValueByContent(JSON.stringify(e))}getBlock(e){for(const t of ae(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,s){const o=f.field(this.rid,M(e,t));if(s.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",s.ref):this.tx.setField(o,s.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...s},this.fieldsChanged=!0}setBlockField(e,t,s,o,n){this.setBlockFieldObj(e,t,{ref:s,status:o,value:n})}deleteBlockFields(e,...t){let s=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(f.field(this.rid,M(e,n))),delete i[n],this.fieldsChanged=!0,s=!0)}return s}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var s,o,n;const t=this.getBlockInfo(e).fields;((s=t.stagingOutput)==null?void 0:s.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 s,o,n;const t=this.getBlockInfo(e).fields;((s=t.prodOutput)==null?void 0:s.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 s,o;const t=this.getBlockInfo(e).fields;return((s=t.prodOutput)==null?void 0:s.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:s,args:o}of e){const n=this.getBlockInfo(s);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(f.Pl.JsonObject,i);this.setBlockField(s,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(s),t.push(s)}this.getStagingGraph().traverse("downstream",t,({id:s})=>this.resetStaging(s)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockSettings(e,t){this.setBlockFieldObj(e,"blockSettings",this.createJsonFieldValue(t)),this.updateLastModified()}createProdCtx(e){const t=[];return e.forEach(s=>{var n;const o=this.getBlockInfo(s);if(((n=o.fields.prodCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),zt(this.tx,t)}createStagingCtx(e){const t=[];return e.forEach(s=>{var n,i;const o=this.getBlockInfo(s);if(((n=o.fields.stagingCtx)==null?void 0:n.ref)===void 0)throw new Error("One of the upstreams staging is not rendered.");t.push(f.Pl.unwrapHolder(this.tx,o.fields.stagingCtx.ref)),((i=o.fields.prodCtx)==null?void 0:i.ref)!==void 0&&t.push(f.Pl.unwrapHolder(this.tx,o.fields.prodCtx.ref))}),zt(this.tx,t)}exportCtx(e){return So(this.tx,f.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),s=this.createStagingCtx(this.getStagingGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Wt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!1)),context:s});this.setBlockField(e,"stagingCtx",f.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),s=this.createProdCtx(this.getPendingProductionGraph().nodes.get(e).upstream);if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Wt(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(f.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(f.Pl.JsonBool,JSON.stringify(!0)),context:s});this.setBlockField(e,"prodCtx",f.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=bo){const s=this.getStagingGraph(),o=this.getActualProductionGraph(),n=vt(e),i=Je(e,u=>{var l;return(l=this.blockInfos.get(u))==null?void 0:l.actualProductionInputs}),a=Zt(s,n),c=Zt(o,i);for(const u of a.onlyInA){const{fields:l}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(l)),this.blockInfos.delete(u),this.blocksInLimbo.delete(u)&&(this.renderingStateChanged=!0),this.blockFrontendStates.delete(u)&&this.changedBlockFrontendStates.add(u)}for(const u of a.onlyInB){const l=new er(u,{});this.blockInfos.set(u,l);const d=t(u),g=Qt(this.tx,d.blockPack);this.setBlockField(u,"blockPack",f.Pl.wrapInHolder(this.tx,g),"NotReady"),this.setBlockFieldObj(u,"blockSettings",this.createJsonFieldValue(U.InitialBlockSettings)),this.setBlockFieldObj(u,"currentArgs",this.createJsonFieldValueByContent(d.args)),d.uiState&&(this.blockFrontendStates.set(u,d.uiState),this.changedBlockFrontendStates.add(u)),l.check()}for(const u of a.different)this.resetStaging(u);o.traverse("downstream",[...c.different],u=>{this.resetOrLimboProduction(u.id)}),(a.onlyInB.size>0||a.onlyInA.size>0||a.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,s){const o=this.structure;if(s===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===s);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${s}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let s=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),s=!0;break}}if(!s)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,s){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",f.Pl.wrapInHolder(this.tx,Qt(this.tx,t)),"NotReady"),s!==void 0?(this.setArgs([{blockId:e,args:s}]),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 s=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,a=>{s.add(a.id)});else for(const a of s){const c=o.nodes.get(a);if(c===void 0)throw new Error(`Can't find block with id: ${a}`);for(const u of c.upstream)if(!s.has(u))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const a of ae(this.structure)){if(!s.has(a.id))continue;let c=this.getBlockInfo(a.id).requireProductionRendering||this.blocksInLimbo.has(a.id);if(!c){for(const u of o.nodes.get(a.id).upstream)if(n.has(u)){c=!0;break}}c&&(this.renderProductionFor(a.id),n.add(a.id))}const i=[...n];return o.traverse("downstream",i,a=>{n.has(a.id)||this.resetOrLimboProduction(a.id)}),this.getStagingGraph().traverse("downstream",i,({id:a})=>{i[0]!==a&&this.resetStaging(a)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),s=new Fr(e),o=new Set(e),n=[];for(;!s.isEmpty();){const c=s.shift(),u=this.getBlockInfo(c).fields;if(!(((i=u.prodOutput)==null?void 0:i.status)==="Ready"&&((a=u.prodCtx)==null?void 0:a.status)==="Ready")&&this.deleteBlockFields(c,"prodOutput","prodCtx","prodUiCtx","prodArgs")){n.push(c);for(const l of t.traverseIdsExcludingRoots("downstream",c))o.has(l)||(s.push(l),o.add(l))}}for(const c of t.traverseIdsExcludingRoots("downstream",...n))this.resetOrLimboProduction(c)}traverseWithStagingLag(e){const t=new Map;this.getStagingGraph().nodes.forEach(o=>{let i=this.getBlockInfo(o.id).stagingRendered?0:1;o.upstream.forEach(a=>{const c=t.get(a);c!==0&&(i=Math.max(c+1,i))}),e(o.id,i),t.set(o.id,i)})}refreshStagings(e){const t=Date.now()-this.renderingState.stagingRefreshTimestamp,s=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(s===void 0||i<=s)&&(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 s,o,n,i;((s=t.fields.prodCtx)==null?void 0:s.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,$e,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,he,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,_e,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,Te,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,s){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,Nr),i=e.getKValueJson(t,$e),a=e.getKValueJson(t,Te),c=e.getKValueJson(t,he),u=e.getKValueJson(t,_e),l=e.listKeyValuesString(t),[d,g,h,R,m,{stagingRefreshTimestamp:x,blocksInLimbo:L},G]=await Promise.all([o,n,i,a,c,u,l]);if(g!==Br)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${g}`);const F=new Map;for(const p of d.fields){const v=Ks(p.name);if(v===void 0)continue;let S=F.get(v.blockId);S===void 0&&(S={id:v.blockId,fields:{}},F.set(v.blockId,S)),S.fields[v.fieldName]=f.isNullResourceId(p.value)?{modCount:0}:{modCount:0,ref:p.value}}const _=await qr(),fe=gt(_.hash),D=d.fields.find(p=>p.name===fe);let Y;D!==void 0?Y=f.ensureResourceIdNotNull(D.value):(Y=f.Pl.wrapInHolder(e,ze(e,_.spec)),e.createField(f.field(t,gt(_.hash)),"Dynamic",Y));const de={stagingRefreshTimestamp:x},z=new Set(L),K=new Map;for(const p of G){const v=Js(p.key);v!==void 0&&K.set(v,p.value)}const J=[];F.forEach(({fields:p})=>{for(const[,v]of Object.entries(p))if(v.ref!==void 0){if(!f.isResource(v.ref)||f.isResourceRef(v.ref))throw new Error("unexpected behaviour");J.push([v,e.getResourceData(v.ref,!1)])}});for(const[p,v]of J){const S=await v;p.value=S.data,f.isNotNullResourceId(S.error)?p.status="Error":S.resourceReady||f.isNotNullResourceId(S.originalResourceId)?p.status="Ready":p.status="NotReady"}const Q=new Map;F.forEach(({id:p,fields:v})=>Q.set(p,new er(p,v)));const ge=new Set;for(const p of ae(m)){if(!Q.has(p.id))throw new Error(`Inconsistent project structure: no inputs for ${p.id}`);ge.add(p.id)}Q.forEach(p=>{if(!ge.has(p.id))throw new Error(`Inconsistent project structure: no structure entry for ${p.id}`);p.check()});const y=new Ke(t,e,s,g,h,R,m,de,z,Q,K,Y);return y.fixProblemsAndMigrate(),y}}async function wo(r,e=js){const t=r.createEphemeral(xs);r.lock(t);const s=String(Date.now());r.setKValue(t,Nr,JSON.stringify(Br)),r.setKValue(t,Rt,s),r.setKValue(t,$e,s),r.setKValue(t,Te,JSON.stringify(e)),r.setKValue(t,he,JSON.stringify(Ns)),r.setKValue(t,_e,JSON.stringify(Bs));const o=await qr();return r.createField(f.field(t,gt(o.hash)),"Dynamic",f.Pl.wrapInHolder(r,ze(r,o.spec))),t}async function Ne(r,e,t){return te(r,e,void 0,t)}async function te(r,e,t,s){if(r instanceof f.PlClient)return await r.withWriteTx("ProjectAction",async o=>{const n=await Ke.load(o,e,t),i=await s(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await Ke.load(r,e,t),n=await s(o);return o.save(),n}}function*Po(r){switch(r.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(r.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(r.parts))yield e,yield t;return;default:k.assertNever(r)}}function tr(r,e){return Object.fromEntries(Object.entries(r).map(([t,s])=>[t,e(s,t)]))}function Co(r,e){switch(r.type){case"Json":return{...r};case"JsonPartitioned":return{...r,parts:tr(r.parts,e)};case"BinaryPartitioned":return{...r,parts:tr(r.parts,t=>({index:e(t.index),values:e(t.values)}))};default:k.assertNever(r)}}const Ro=f.resourceType("PColumnData/JsonPartitioned","1"),Eo=f.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),ko=f.resourceType("PColumnData/BinaryPartitioned","1"),Oo=f.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),$o=f.resourceType("PColumnData/Json","1");function To(r){if(!r.getIsReadyOrError())throw new Error("Data not ready.");const e=r.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(f.resourceTypesEqual(r.resourceType,$o)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(f.resourceTypesEqual(r.resourceType,Ro)){const t=e,s=Object.fromEntries(r.listInputFields().map(o=>[o,r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,Eo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);s[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}else if(f.resourceTypesEqual(r.resourceType,ko)){const t=e,s={};for(const o of r.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=s[n];i===void 0&&(i={},s[n]=i),i.index=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=s[n];i===void 0&&(i={},s[n]=i),i.values=r.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(s)){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:s}}else if(f.resourceTypesEqual(r.resourceType,Oo)){const t=e,s={};for(const o of r.listInputFields()){const n=r.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i)if(a.endsWith(".index")){const c=a.slice(0,a.length-6),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].index=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else if(a.endsWith(".values")){const c=a.slice(0,a.length-7),u=JSON.stringify([...JSON.parse(o),...JSON.parse(c)]);let l=s[u];l===void 0&&(l={},s[u]=l),s[u].values=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${a}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:s}}throw new Error(`unsupported resource type: ${f.resourceTypeToString(r.resourceType)}`)}function Fo(r,e){const t=r.axesSpec.length,s={};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}`);s[JSON.stringify(o)]=n}return{type:"Json",keyLength:t,data:s}}function Io(r,e){const t=ce.createHash("sha256");return t.update(re(r)),t.update(String(f.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function rr(r,e){return re({__isRef:!0,blockId:r,name:e})}function Ao(r,e){return re({resolvePath:r,name:e})}function Wr(r,e=!0,t=!1,s=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const l of r.listInputFields()){const d=l.match(o);if(!d){if(e)throw new Error(`unexpected field name ${l}`);continue}let g=k.notEmpty((a=d.groups)==null?void 0:a.name);if(!g.startsWith(s)){if(e)throw new Error(`unexpected field name ${l}`);continue}g=g.slice(s.length);const h=k.notEmpty((c=d.groups)==null?void 0:c.type);let R=n.get(g);switch(R===void 0&&(R={},n.set(g,R)),h){case"spec":R.spec=(u=r.traverse({field:l,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":R.hasData=!0,R.data=()=>r.traverseOrError({field:l,ignoreError:t});break}}const i=r.getInputsLocked();if(i)for(const[,l]of n)l.data===void 0&&(l.hasData=!1);return{locked:i,results:n}}function Lo(r,e=!0,t="",s){if(!r.getIsReadyOrError())throw new Error("resource is not ready");const o=Wr(r,e,!1,t);Ss(o.locked);const n={};for(const[i,a]of o.results){if(a.spec===void 0)throw new Error(`no spec for key ${i}`);if(a.hasData!==!0||a.data===void 0)throw new Error(`no data for key ${i}`);const c=a.data();if(c===void 0)throw new Error(`no data for key ${i}`);if(!c.ok)throw new qe.PlError(c.error);n[i]={id:s.length===0?Io(a.spec,c.value):Ao(s,i),spec:a.spec,data:c.value}}return n}class $t{constructor(e,t){w(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let s=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){s=!1;break e}for(const i of n.results.values())if(i.spec===void 0){s=!1;break e}}this.allSpecsAvailable=s}getSpecByRef(e,t){var n,i,a,c,u,l;const s=this.blocks.get(e);if(s===void 0)return;let o=(a=(i=(n=s.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(l=(u=(c=s.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:l.spec,o!==void 0))return o;s.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):s.staging.locked?s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const s=this.blocks.get(e);if(s===void 0)return;const o=(a=(i=s.prod)==null?void 0:i.results)==null?void 0:a.get(t),n=(c=o==null?void 0:o.data)==null?void 0:c.call(o);if(o!==void 0&&o.spec!==void 0&&n!==void 0)return B.mapValueInVOE(n,u=>({id:rr(e,t),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),s.prod!==void 0&&!s.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const s=this.getDataOrErrorByRef(e,t);if(!(s===void 0||!s.ok))return s.value}getData(){const e=this.getDataWithErrors(),t=[];for(const s of e.entries)s.obj.id!==void 0&&s.obj.data.ok&&t.push({ref:s.ref,obj:{id:s.obj.id,spec:s.obj.spec,data:s.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,s;const o=i=>{s===void 0&&(s=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:De(i,a),obj:{id:u.ok?rr(i,a):void 0,spec:c.spec,data:u}}):o(`no_data:${i}:${a}`)}};for(const[i,a]of this.blocks){const c=new Set;if(a.prod!==void 0){a.prod.locked||o(`prod_not_locked:${i}`);for(const[u,l]of a.prod.results)c.add(u),n(i,u,l)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,l]of a.staging.results)c.has(u)||n(i,u,l)}}return{entries:e,isComplete:t,instabilityMarker:s}}getSpecs(){const e=[];let t=!0,s;const o=n=>{s===void 0&&(s=n),t=!1};for(const[n,i]of this.blocks){const a=new Set;if(i.staging!==void 0){i.staging.locked||o(`staging_not_locked:${n}`);for(const[c,u]of i.staging.results)u.spec!==void 0&&(e.push({ref:De(n,c),obj:u.spec}),a.add(c))}else o(`staging_not_rendered:${n}`);if(i.prod!==void 0){i.prod.locked||o(`prod_not_locked:${n}`);for(const[c,u]of i.prod.results)a.has(c)||u.spec!==void 0&&e.push({ref:De(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:s}}calculateOptions(e){const t=[];for(const s of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),B.executePSpecPredicate(e,c.spec)&&t.push({label:s.info.label+" / "+a,ref:De(s.info.id,a),spec:c.spec}))};s.staging!==void 0&&n(s.staging),s.prod!==void 0&&n(s.prod)}return t}static create(e,t,s){const o=e.accessor(t).node(),n=k.notEmpty(o.getKeyValueAsJson(he)),a=vt(n).traverseIds("upstream",s),c=new Map;for(const u of ae(n)){if(!a.has(u.id))continue;const l=sr(o.traverse({field:M(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:M(u.id,"prodUiCtx"),stableIfNotFound:!0})),d=sr(o.traverse({field:M(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:M(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:l,staging:d})}return new $t(e,c)}}function sr(r,e){if(e===void 0)return r?{locked:!1,results:new Map}:void 0;if(e.ok)return Wr(e.value,!1,!0)}function Tt(r,e){return{blockId:e,args:n=>k.notEmpty(n.accessor(r).node().traverse({field:M(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),activeArgs:n=>{var i;return(i=n.accessor(r).node().traverse({field:M(e,"prodArgs"),stableIfNotFound:!0}))==null?void 0:i.getDataAsString()},uiState:n=>n.accessor(r).node().getKeyValueAsString(pt(e)),blockMeta:n=>{const i=n.accessor(r).node(),a=k.notEmpty(i.getKeyValueAsJson(he)),c=new Map;for(const u of ae(a))c.set(u.id,u);return c}}}function zr(r,e){return{...Tt(r,e),prod:t=>{var s;return(s=t.accessor(r).node({ignoreError:!0}).traverse({field:M(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:s.persist()},staging:t=>{var o;const s=(o=t.accessor(r).node({ignoreError:!0}).traverse({field:M(e,"stagingOutput"),ignoreError:!0}))==null?void 0:o.persist();return s===void 0&&t.markUnstable("staging_not_rendered"),s},getResultsPool:t=>$t.create(t,r,e)}}function*X(r,e){switch(yield r,r.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*X(r.cfg);return;case"MakeObject":for(const[,t]of Object.entries(r.template))yield*X(t);return;case"MakeArray":for(const t of r.template)yield*X(t);return;case"GetJsonField":case"GetResourceField":yield*X(r.source),yield*X(r.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*X(r.source),yield*X(r.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"ExtractArchiveAndGetURL":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetProgressLogWithInfo":case"GetLogHandle":yield*X(r.source);return;case"IsEmpty":yield*X(r.arg);return;case"Not":yield*X(r.operand);return;case"And":case"Or":yield*X(r.operand1),yield*X(r.operand2);return;default:k.assertNever(r)}}function Do(r,e){const t={};for(const[s,o]of Object.entries(r))t[s]=e(o);return t}function Ee(r,e){return r===void 0?void 0:e(r)}function No(r){switch(r.type){case"GetImportProgress":return!0;default:return!1}}function Bo(r){for(const e of X(r))if(No(e))return!0;return!1}function Xe(r){return{type:"ReturnResult",result:r}}function O(r){return()=>Xe(r)}const jo=r=>{const e={};for(const[t,s]of Object.entries(r))e[t]=s;return O(e)},xo=r=>{const e=r.source;if(e===void 0)return O(void 0);const t=[];for(const s of e)s instanceof Array?t.push(...s):t.push(s);return O(t)},Vo=r=>{const e=r.source,t=r.field;return e===void 0||t===void 0?O(void 0):({cCtx:s})=>{var o;return Xe((o=s.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function Xr(r,e){const t={},s=r.length;for(let o=0;o<s;o++)t[String(o)]=e(r[o]);return t}function Uo(r,e){return t=>{const s=t.source;return s===void 0?O(void 0):()=>({type:"ScheduleSubroutine",subroutine:Yr(s.length),args:Xr(s,o=>$({...r,[e.itVar]:o},e.mapping))})}}function Yr(r){return e=>{const t=[];for(let s=0;s<r;s++)t.push(e[String(s)]);return O(t)}}function Go(r,e){return t=>{const s=t.source;if(s===void 0)return O(void 0);const o={};for(const[n,i]of Object.entries(s)){const a={...r,[e.itVar]:i};o[n]=$(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:Jo,args:o})}}const Jo=r=>O(r),Mo=r=>{const e=r.arg;return O(e===void 0?void 0:e.length===0)},_o=r=>{const e=r.operand;return O(e===void 0?void 0:!e)},Ko=r=>{const e=r.operand1,t=r.operand2;return O(e===void 0||t===void 0?void 0:e&&t)},Ho=r=>{const e=r.operand1,t=r.operand2;return O(e===void 0||t===void 0?void 0:e||t)},qo=r=>{const e=r.source;return e===void 0?O(void 0):({cCtx:t})=>{var s;return Xe((s=t.accessor(e).node())==null?void 0:s.getDataAsJson())}},Wo=r=>{const e=r.source,t=r.field;return O(e===void 0||t===void 0?void 0:e[t])};function zo(r,e){return t=>{const s=t.source;return s===void 0?O(void 0):({cCtx:o})=>{const n=o.accessor(s).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=O(void 0);else{const u={...r,[e.itVar]:c.persist()};i[a]=$(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:Xo,args:i}}}}const Xo=r=>O(r),Yo=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s!==void 0)return await t.blobDriver.getContent(s.handle)}})})},Qo=r=>{const e=r.source;return e===void 0?O(void 0):({cCtx:t,drivers:s})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:j.Computable.make(()=>s.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await s.blobDriver.getContent(n.handle)).toString()})}}},Zo=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:j.Computable.make(s=>t.blobDriver.getDownloadedBlob(s.accessor(e).node().resourceInfo),{postprocessValue:async s=>{if(s==null)return;const o=await t.blobDriver.getContent(s.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},en=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},tn=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},rn=r=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.blobToURLDriver.extractArchiveAndGetURL(t,r)})},sn=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},on=r=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getLastLogs(t,r)})},nn=r=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLog(t,r)})},an=r=>e=>{const t=e.source;return t===void 0?O(void 0):({drivers:s})=>({type:"ScheduleComputable",computable:s.logDriver.getProgressLogWithInfo(t,r)})},cn=r=>{const e=r.source;return e===void 0?O(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function $(r,e){switch(e.type){case"GetFromCtx":{const t=r[e.variable];return typeof t=="function"?s=>Xe(t(s.cCtx)):O(t)}case"Isolate":return({drivers:t})=>({type:"ScheduleComputable",computable:es(t,r,e.cfg)});case"Immediate":return O(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:Wo,args:{source:$(r,e.source),field:$(r,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:Uo(r,e),args:{source:$(r,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:Go(r,e),args:{source:$(r,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:jo,args:Do(e.template,t=>$(r,t))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Yr(e.template.length),args:Xr(e.template,t=>$(r,t))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:xo,args:{source:$(r,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:Mo,args:{arg:$(r,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:_o,args:{operand:$(r,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:Ko,args:{operand1:$(r,e.operand1),operand2:$(r,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:Ho,args:{operand1:$(r,e.operand1),operand2:$(r,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:zo(r,e),args:{source:$(r,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:Vo,args:{source:$(r,e.source),field:$(r,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:qo,args:{source:$(r,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Yo,args:{source:$(r,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Qo,args:{source:$(r,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Zo,args:{source:$(r,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:en,args:{source:$(r,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:tn,args:{source:$(r,e.source)}});case"ExtractArchiveAndGetURL":return()=>({type:"ScheduleSubroutine",subroutine:rn(e.format),args:{source:$(r,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:sn,args:{source:$(r,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:on(e.lines),args:{source:$(r,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:nn(e.patternToSearch),args:{source:$(r,e.source)}});case"GetProgressLogWithInfo":return()=>({type:"ScheduleSubroutine",subroutine:an(e.patternToSearch),args:{source:$(r,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:cn,args:{source:$(r,e.source)}});default:return k.assertNever(e)}}const ln=["$prod","$staging"];function un(r){return{$blockId:r.blockId,$args:e=>JSON.parse(r.args(e)),$ui:e=>{const t=r.uiState(e);return t!==void 0?JSON.parse(t):void 0},$prod:r.prod,$staging:r.staging}}const Qr=Symbol(),Zr="return",dn={op:Qr,arg:Zr};function pn(r){return r.op==Qr&&r.arg==Zr}function hn(){return{pendingSubroutines:new Map}}function or(r,e,t,s){const o=new Fr(t),n=(a,c)=>{if(pn(a))return e.result=c,!1;const u=k.notEmpty(e.pendingSubroutines.get(a.op));if(a.arg in u.args)throw new Error("argument already set");return u.args[a.arg]=c,u.argCounter--,u.argCounter===0&&(e.pendingSubroutines.delete(a.op),o.push({destination:u.destination,operation:u.subroutine(u.args)})),!0},i=[];e:for(;o.length>0;){const a=o.shift(),c=a.operation(r);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":{const u=Symbol(),l=Object.entries(c.args),d=l.length;if(d===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[g,h]of l)o.push({destination:{op:u,arg:g},operation:h});e.pendingSubroutines.set(u,{argCounter:d,args:{},subroutine:c.subroutine,destination:a.destination})}}break;case"ScheduleComputable":if(!s)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:k.assertNever(c)}}return i}function fn(r,e,t,s={}){return es(r,un(e),t,s)}function es(r,e,t,s={}){const o=`${e.blockId}#`+re({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>ln.indexOf(n)===-1)),cfg:t});return j.Computable.makeRaw(n=>{const i={drivers:r,cCtx:n},a=hn();return{ir:or(i,a,[{destination:dn,operation:$(e,t)}],!0),postprocessValue(u){const l=[];for(const R of u)l.push({destination:R.destination,operation:O(R.computable)});const d={drivers:r,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},g=new Map;for(const[R,m]of a.pendingSubroutines)g.set(R,{...m,args:{...m.args}});const h={result:a.result,pendingSubroutines:g};if(or(d,h,l,!1),!("result"in h))throw new Error("illegal cfg rendering stack state, no result");return h.result}}},{...s,key:o})}function gn(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function nr(r){return r!==void 0?Buffer.from(r).toString("base64"):void 0}class He{constructor(e,t,s,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=s,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=s.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 He.cleanErrorContext(t),t}}runCallback(e,...t){try{return Me.Scope.withScope(s=>{const o=s.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,s)))))})}catch(s){throw He.cleanErrorContext(s),s}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(s,o)=>{if(!this.accessors.has(s)){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(s,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(s,void 0)}return this.accessors.get(s)?s:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...s){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...s))}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 nr(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return nr(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,s,...o){const n=this.getAccessor(e);if(!n.getIsReadyOrError())return;const i=Lo(n,t,s,o),a={};for(const[c,u]of Object.entries(i))a[c]=B.mapPObjectData(u,l=>this.wrapAccessor(l));return a}registerComputable(e,t){const s=`${e}_${ce.randomUUID()}`;return this.computablesToResolve[s]=t,s}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",j.Computable.make(s=>this.env.driverKit.blobDriver.getDownloadedBlob(t,s),{postprocessValue:async s=>{if(s!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(s.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 s=this.getAccessor(e).persist();return this.registerComputable("extractArchiveAndGetURL",this.env.driverKit.blobToURLDriver.extractArchiveAndGetURL(s,t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(s,t))}getProgressLog(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(s,t))}getProgressLogWithInfo(e,t){const s=this.getAccessor(e).persist();return this.registerComputable("getProgressLogWithInfo",this.env.driverKit.logDriver.getProgressLogWithInfo(s,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,s=>this.wrapAccessor(s))}))}}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,s=>this.wrapAccessor(s))}}))}}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),s=>this.wrapAccessor(s))}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,s=>typeof s=="string"?this.getAccessor(s):s)),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,s=>typeof s=="string"?this.getAccessor(s):s)),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=ce.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const s=this.tryExportSingleValue(e,t);if(s===void 0)throw new Error(`Can't export value: ${e===void 0?"undefined":JSON.stringify(e)}`);return s}tryExportSingleValue(e,t){let s,o=!1;switch(typeof e){case"string":s=this.vm.newString(e),o=!0;break;case"number":s=this.vm.newNumber(e),o=!0;break;case"undefined":s=this.vm.undefined;break;case"boolean":s=e?this.vm.true:this.vm.false;break;default:if(e===null){s=this.vm.null;break}if(gn(e)){s=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(s):s}exportObjectUniversal(e,t){const s=this.tryExportSingleValue(e,t);return s!==void 0?s:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const s=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(s):s}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(s=>this.vm.getString(s));if(t!=="undefined")return JSON.parse(t)}injectCtx(){Me.Scope.withScope(e=>{const t=e.manage(this.vm.newObject()),s=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(s))),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=(a,c)=>{this.vm.newFunction(a,c).consume(u=>this.vm.setProp(t,a,u))};i("getAccessorHandleByName",a=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(a)),void 0)),i("resolveWithCommon",(a,c,...u)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(a),this.importObjectViaJson(c),...u.map(l=>this.importObjectViaJson(l))),void 0)),i("getResourceType",a=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(a)),void 0)),i("getInputsLocked",a=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(a)),void 0)),i("getOutputsLocked",a=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(a)),void 0)),i("getIsReadyOrError",a=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(a)),void 0)),i("getIsFinal",a=>this.exportSingleValue(this.getIsFinal(this.vm.getString(a)),void 0)),i("getError",a=>this.exportSingleValue(this.getError(this.vm.getString(a)),void 0)),i("listInputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listOutputFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("listDynamicFields",a=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(a)),void 0)),i("getKeyValueBase64",(a,c)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getKeyValueAsString",(a,c)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataBase64",a=>this.exportSingleValue(this.getDataBase64(this.vm.getString(a)),void 0)),i("getDataAsString",a=>this.exportSingleValue(this.getDataAsString(this.vm.getString(a)),void 0)),i("parsePObjectCollection",(a,c,u,...l)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(a),this.vm.dump(c),this.vm.getString(u),...l.map(d=>this.vm.getString(d))),void 0)),i("getBlobContentAsBase64",a=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(a)),void 0)),i("getBlobContentAsString",a=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(a)),void 0)),i("getDownloadedBlobContentHandle",a=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(a)),void 0)),i("getOnDemandBlobContentHandle",a=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(a)),void 0)),i("extractArchiveAndGetURL",(a,c)=>this.exportSingleValue(this.extractArchiveAndGetURL(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getImportProgress",a=>this.exportSingleValue(this.getImportProgress(this.vm.getString(a)),void 0)),i("getLastLogs",(a,c)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(a),this.vm.getNumber(c)),void 0)),i("getProgressLog",(a,c)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getProgressLogWithInfo",(a,c)=>this.exportSingleValue(this.getProgressLogWithInfo(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getLogHandle",a=>this.exportSingleValue(this.getLogHandle(this.vm.getString(a)),void 0)),i("getBlockLabel",a=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(a)),void 0)),i("getDataFromResultPool",()=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),i("getDataWithErrorsFromResultPool",()=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),i("getSpecsFromResultPool",()=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),i("calculateOptions",a=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(a)),void 0)),i("getSpecFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("getDataFromResultPoolByRef",(a,c)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(a),this.vm.getString(c)),void 0)),i("createPFrame",a=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(a)),void 0)),i("createPTable",a=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(a)),void 0)),i("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Ye(r,e){return Ee(r.traverse({field:M(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),t=>{const s=t.getDataAsJson(),o=B.extractConfig(s.config);return{bpId:t.resourceInfo.id.toString(),info:s,cfg:o}})}const Be=process.env.MI_LOG_OUTPUT_STATUS;function mn(r,e,t,s,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(a=>{const c=new Me.Scope;a.addOnDestroy(()=>c.dispose());const u=c.manage(r.quickJs.newRuntime());u.setMemoryLimit(1024*640),u.setMaxStackSize(1024*320);const l=c.manage(u.newContext()),d=new He(c,l,e,r,a);d.evaluateBundle(s.content);const g=d.runCallback(t.handle);d.resetComputableCtx();let h=0;return Be&&Be!=="unstable-only"&&console.log(`Output ${t.handle} scaffold calculated.`),{ir:d.computablesToResolve,postprocessValue:(R,{unstableMarker:m,stable:x})=>{for(const[G,F]of Object.entries(R))d.runCallback(G,F);const L=d.importObjectUniversal(g);return h++,Be&&(Be!=="unstable-only"||!x)&&console.log(x?`Stable output ${t.handle} calculated ${L!==void 0?"defined":"undefined"}; (#${h})`:`Unstable output ${t.handle}; marker = ${m}; ${L!==void 0?"defined":"undefined"} (#${h})`),L}}},n)}function vn(r){return B.isConfigLambda(r)?r.isActive===!0:Bo(r)}function ke(r,e,t,s,o,n={}){if(B.isConfigLambda(t)){if(s===void 0)throw new Error("No code bundle.");return mn(r,e,t,s,o,n)}else return fn(r.driverKit,e,t,n)}function yn(r,e,t){return j.Computable.make(s=>{var R,m,x,L,G,F,_,fe;const o=s.accessor(r).node(),n=k.notEmpty(o.getKeyValueAsJson(Rt)),i=k.notEmpty(o.getKeyValueAsJson($e)),a=k.notEmpty(o.getKeyValueAsJson(Te)),c=k.notEmpty(o.getKeyValueAsJson(he)),u=k.notEmpty(o.getKeyValueAsJson(_e)),l=new Map;for(const{id:D}of ae(c)){const Y=o.traverse({field:M(D,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let de;const z=o.traverse({field:M(D,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(z!==void 0){const K=o.getField({field:M(D,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),J=o.getField({field:M(D,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});de={arguments:z.getDataAsJson(),stale:Y.id!==z.id,outputError:K.error!==void 0||J.error!==void 0||((R=K.value)==null?void 0:R.getError())!==void 0||((m=J.value)==null?void 0:m.getError())!==void 0,outputsError:((x=K.error)==null?void 0:x.getDataAsString())??((G=(L=K.value)==null?void 0:L.getError())==null?void 0:G.getDataAsString()),exportsError:((F=J.error)==null?void 0:F.getDataAsString())??((fe=(_=J.value)==null?void 0:_.getError())==null?void 0:fe.getDataAsString()),finished:(K.value!==void 0&&K.value.getIsReadyOrError()||K.error!==void 0&&K.error.getIsReadyOrError())&&(J.value!==void 0&&J.value.getIsReadyOrError()||J.error!==void 0&&J.error.getIsReadyOrError())}}l.set(D,{currentArguments:Y.getDataAsJson(),prod:de})}const d=Je(c,D=>l.get(D).currentArguments),g=new Set(u.blocksInLimbo),h=[...ae(c)].map(({id:D,label:Y,renderingMode:de})=>{var b,C,T,E,A;const z=k.notEmpty(l.get(D)),K=k.notEmpty(d.nodes.get(D));let J="NotCalculated";z.prod!==void 0&&(g.has(D)?J="Limbo":J=z.prod.finished?"Done":"Running");const Q=Ye(o,D),{sections:ge,title:y,inputsValid:p,sdkVersion:v}=Ee(Q,({bpId:V,cfg:I})=>{const le=Tt(r,D);return{sections:ke(t,le,I.sections,I.code,V),title:Ee(I.title,ps=>ke(t,le,ps,I.code,V)),inputsValid:ke(t,le,I.inputsValid,I.code,V),sdkVersion:I.sdkVersion}})||{},S=o.traverse({field:M(D,"blockSettings"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0}).getDataAsJson(),P=Ee(Q,({info:V})=>t.blockUpdateWatcher.get({currentSpec:V.source,settings:S}));return{id:D,label:y??Y,title:y??Y,renderingMode:de,stale:((b=z.prod)==null?void 0:b.stale)!==!1||J==="Limbo",missingReference:K.missingReferences,upstreams:[...d.traverseIdsExcludingRoots("upstream",D)],downstreams:[...d.traverseIdsExcludingRoots("downstream",D)],calculationStatus:J,outputErrors:((C=z.prod)==null?void 0:C.outputError)===!0,outputsError:(T=z.prod)==null?void 0:T.outputsError,exportsError:(E=z.prod)==null?void 0:E.exportsError,settings:S,sections:ge,inputsValid:p,updateInfo:{},currentBlockPack:(A=Q==null?void 0:Q.info)==null?void 0:A.source,updates:P,sdkVersion:v,navigationState:e.getState(D)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(ft),blocks:h}},{postprocessValue:s=>{const o=new Set,n=new Set;return{...s,blocks:s.blocks.map(i=>{var l,d;i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(g=>n.has(g))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(g=>o.has(g))===-1,u={...i,canRun:c,stale:a,updateSuggestions:((l=i.updates)==null?void 0:l.suggestions)??[],updatedBlockPack:(d=i.updates)==null?void 0:d.mainSuggestion};return delete u.updates,u})}}}).withStableType()}function Sn(r,e){const t=r.node();if(f.resourceTypesEqual(t.resourceType,kt)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(s.url)).withStableType()}else if(f.resourceTypesEqual(t.resourceType,Ot)){const s=t.getDataAsJson();if(s===void 0)throw new Error("No resource data.");return e.signer.verify(s.path,s.signature,`Frontend path signature mismatch for: ${s.path}`),s.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function bn(r,e){if(r!==void 0)return j.Computable.make(t=>Sn(t.accessor(r),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 wn(r,e,t){return j.Computable.make(s=>{var a;const o=s.accessor(r).node(),n=Ye(o,e),i=(a=o.traverse({field:M(e,"blockPack"),assertFieldType:"Dynamic"},{field:f.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Kr,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:bn(i,t),sdkVersion:n==null?void 0:n.cfg.sdkVersion}},{mode:"StableOnlyLive"})}function ts(r,e,t){if(t===void 0)return j.Computable.make(i=>ts(r,e,i),{key:`inputs#${f.resourceIdToString(r.rid)}#${e}`});const s=t.accessor(r).node(),o=Tt(r,e),n=o.uiState(t);return{author:s.getKeyValueAsJson(ht(e)),args:JSON.parse(o.args(t)),ui:n!==void 0?JSON.parse(n):void 0}}function Pn(r,e,t){return j.Computable.make(s=>{const o=s.accessor(r).node(),n=zr(r,e);return Ee(Ye(o,e),({cfg:i,bpId:a})=>{const c={};for(const[u,l]of Object.entries(i.outputs)){const d=ke(t,n,l,i.code,a);c[u]=j.Computable.wrapError(d)}return c})},{key:"outputs#"+f.resourceIdToString(r.rid)+"#"+e}).withStableType()}function Cn(r,e){return j.Computable.make(t=>{const s=t.accessor(r).node(),o=k.notEmpty(s.getKeyValueAsJson(he)),n=[];for(const{id:i}of ae(o)){const a=Ye(s,i);if(a===void 0)continue;const c=Object.entries(a.cfg.outputs).map(([,l])=>l).filter(l=>vn(l)).map(l=>l);if(c.length===0)continue;const u=zr(s.persist(),i);for(const l of c)n.push(j.Computable.wrapError(ke(e,u,l,a.cfg.code,a.bpId)))}return n})}class Rn{constructor(){w(this,"states",new Map)}setState(e,t){const s=this.states.get(e);if(s===void 0){this.states.set(e,{state:t,change:new j.ChangeSource});return}s.state={...t},s.change.markChanged()}readState(e,t){let s=this.states.get(t);return s===void 0&&(s={state:{...B.DefaultNavigationState},change:new j.ChangeSource},this.states.set(t,s)),s.change.attachWatcher(e.watcher),s.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 Qe{constructor(e,t,s){w(this,"rid");w(this,"overview");w(this,"navigationStates",new Rn);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=s,this.overview=yn(s.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Cn(s.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 Ir.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(f.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!f.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,s,o=void 0,n=ce.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=B.extractConfig(a);return await te(this.env.pl,this.rid,o,u=>u.addBlock({id:n,label:e,renderingMode:c.renderingMode},{args:JSON.stringify(c.initialArgs),uiState:JSON.stringify(c.initialUiState),blockPack:i},s)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,s=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await te(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,s?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await te(this.env.pl,this.rid,t,s=>s.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await te(this.env.pl,this.rid,t,s=>{const o=s.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(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};s.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,s){await te(this.env.pl,this.rid,s,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,s){await te(this.env.pl,this.rid,s,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,s,o){await te(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(s))}),await this.projectTree.refreshState()}async setBlockSettings(e,t){await te(this.env.pl,this.rid,void 0,s=>{s.setBlockSettings(e,t)}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async s=>{const o=f.ensureResourceIdNotNull((await s.getField(f.field(this.rid,M(e,"blockPack")))).value),n=f.ensureResourceIdNotNull((await s.getField(f.field(o,f.Pl.HolderRefField))).value),i=await s.getResourceData(n,!1),a=JSON.parse(Buffer.from(k.notEmpty(i.data)).toString("utf-8"));await te(s,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await s.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const s=Pn(this.projectTree.entry(),e,this.env),n={fullState:j.Computable.make(i=>({argsAndUiState:ts(this.projectTree.entry(),e,i),outputs:s,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 s=wn(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,s),s}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 s=await qe.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:En},e.logger);return new Qe(e,t,s)}}function En(r){switch(r.type.name){case"BlockPackCustom":return r.fields.filter(e=>e.name!=="template");case"UserProject":return r.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return r.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(r){return{blobDownloadPath:q.join(r,"download"),downloadBlobToURLPath:q.join(r,"downloadToURL")}}const rs={...Ft,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function ss(r){return{...It(r),frontendDownloadPath:q.join(r,"frontend")}}function kn(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var St={exports:{}};const On="2.0.0",os=256,$n=Number.MAX_SAFE_INTEGER||9007199254740991,Tn=16,Fn=os-6,In=["major","premajor","minor","preminor","patch","prepatch","prerelease"];var Ze={MAX_LENGTH:os,MAX_SAFE_COMPONENT_LENGTH:Tn,MAX_SAFE_BUILD_LENGTH:Fn,MAX_SAFE_INTEGER:$n,RELEASE_TYPES:In,SEMVER_SPEC_VERSION:On,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2};const An=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};var et=An;(function(r,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_LENGTH:o}=Ze,n=et;e=r.exports={};const i=e.re=[],a=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const g="[a-zA-Z0-9-]",h=[["\\s",1],["\\d",o],[g,s]],R=x=>{for(const[L,G]of h)x=x.split(`${L}*`).join(`${L}{0,${G}}`).split(`${L}+`).join(`${L}{1,${G}}`);return x},m=(x,L,G)=>{const F=R(L),_=d++;n(x,_,L),l[x]=_,c[_]=L,u[_]=F,i[_]=new RegExp(L,G?"g":void 0),a[_]=new RegExp(F,G?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${g}*`),m("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${c[l.NUMERICIDENTIFIER]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NUMERICIDENTIFIERLOOSE]}|${c[l.NONNUMERICIDENTIFIER]})`),m("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${g}+`),m("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),m("FULL",`^${c[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),m("LOOSE",`^${c[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),m("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",c[l.COERCE],!0),m("COERCERTLFULL",c[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(St,St.exports);var Fe=St.exports;const Ln=Object.freeze({loose:!0}),Dn=Object.freeze({}),Nn=r=>r?typeof r!="object"?Ln:r:Dn;var At=Nn;const ir=/^[0-9]+$/,ns=(r,e)=>{const t=ir.test(r),s=ir.test(e);return t&&s&&(r=+r,e=+e),r===e?0:t&&!s?-1:s&&!t?1:r<e?-1:1},Bn=(r,e)=>ns(e,r);var is={compareIdentifiers:ns,rcompareIdentifiers:Bn};const je=et,{MAX_LENGTH:ar,MAX_SAFE_INTEGER:xe}=Ze,{safeRe:cr,safeSrc:lr,t:Ve}=Fe,jn=At,{compareIdentifiers:me}=is;let xn=class ne{constructor(e,t){if(t=jn(t),e instanceof ne){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>ar)throw new TypeError(`version is longer than ${ar} characters`);je("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const s=e.trim().match(t.loose?cr[Ve.LOOSE]:cr[Ve.FULL]);if(!s)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+s[1],this.minor=+s[2],this.patch=+s[3],this.major>xe||this.major<0)throw new TypeError("Invalid major version");if(this.minor>xe||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>xe||this.patch<0)throw new TypeError("Invalid patch version");s[4]?this.prerelease=s[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){const n=+o;if(n>=0&&n<xe)return n}return o}):this.prerelease=[],this.build=s[5]?s[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(je("SemVer.compare",this.version,this.options,e),!(e instanceof ne)){if(typeof e=="string"&&e===this.version)return 0;e=new ne(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof ne||(e=new ne(e,this.options)),me(this.major,e.major)||me(this.minor,e.minor)||me(this.patch,e.patch)}comparePre(e){if(e instanceof ne||(e=new ne(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 s=this.prerelease[t],o=e.prerelease[t];if(je("prerelease compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return me(s,o)}while(++t)}compareBuild(e){e instanceof ne||(e=new ne(e,this.options));let t=0;do{const s=this.build[t],o=e.build[t];if(je("build compare",t,s,o),s===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(s===void 0)return-1;if(s===o)continue;return me(s,o)}while(++t)}inc(e,t,s){if(e.startsWith("pre")){if(!t&&s===!1)throw new Error("invalid increment argument: identifier is empty");if(t){const o=new RegExp(`^${this.options.loose?lr[Ve.PRERELEASELOOSE]:lr[Ve.PRERELEASE]}$`),n=`-${t}`.match(o);if(!n||n[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,s);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,s);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,s),this.inc("pre",t,s);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,s),this.inc("pre",t,s);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const o=Number(s)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]=="number"&&(this.prerelease[n]++,n=-2);if(n===-1){if(t===this.prerelease.join(".")&&s===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(t){let n=[t,o];s===!1&&(n=[t]),me(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 W=xn;const ur=W,Vn=(r,e,t=!1)=>{if(r instanceof ur)return r;try{return new ur(r,e)}catch(s){if(!t)return null;throw s}};var Se=Vn;const Un=Se,Gn=(r,e)=>{const t=Un(r,e);return t?t.version:null};var Jn=Gn;const Mn=Se,_n=(r,e)=>{const t=Mn(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};var Kn=_n;const dr=W,Hn=(r,e,t,s,o)=>{typeof t=="string"&&(o=s,s=t,t=void 0);try{return new dr(r instanceof dr?r.version:r,t).inc(e,s,o).version}catch{return null}};var qn=Hn;const pr=Se,Wn=(r,e)=>{const t=pr(r,null,!0),s=pr(e,null,!0),o=t.compare(s);if(o===0)return null;const n=o>0,i=n?t:s,a=n?s:t,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}const l=c?"pre":"";return t.major!==s.major?l+"major":t.minor!==s.minor?l+"minor":t.patch!==s.patch?l+"patch":"prerelease"};var zn=Wn;const Xn=W,Yn=(r,e)=>new Xn(r,e).major;var Qn=Yn;const Zn=W,ei=(r,e)=>new Zn(r,e).minor;var ti=ei;const ri=W,si=(r,e)=>new ri(r,e).patch;var oi=si;const ni=Se,ii=(r,e)=>{const t=ni(r,e);return t&&t.prerelease.length?t.prerelease:null};var ai=ii;const hr=W,ci=(r,e,t)=>new hr(r,t).compare(new hr(e,t));var se=ci;const li=se,ui=(r,e,t)=>li(e,r,t);var di=ui;const pi=se,hi=(r,e)=>pi(r,e,!0);var fi=hi;const fr=W,gi=(r,e,t)=>{const s=new fr(r,t),o=new fr(e,t);return s.compare(o)||s.compareBuild(o)};var Lt=gi;const mi=Lt,vi=(r,e)=>r.sort((t,s)=>mi(t,s,e));var yi=vi;const Si=Lt,bi=(r,e)=>r.sort((t,s)=>Si(s,t,e));var wi=bi;const Pi=se,Ci=(r,e,t)=>Pi(r,e,t)>0;var tt=Ci;const Ri=se,Ei=(r,e,t)=>Ri(r,e,t)<0;var Dt=Ei;const ki=se,Oi=(r,e,t)=>ki(r,e,t)===0;var as=Oi;const $i=se,Ti=(r,e,t)=>$i(r,e,t)!==0;var cs=Ti;const Fi=se,Ii=(r,e,t)=>Fi(r,e,t)>=0;var Nt=Ii;const Ai=se,Li=(r,e,t)=>Ai(r,e,t)<=0;var Bt=Li;const Di=as,Ni=cs,Bi=tt,ji=Nt,xi=Dt,Vi=Bt,Ui=(r,e,t,s)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Di(r,t,s);case"!=":return Ni(r,t,s);case">":return Bi(r,t,s);case">=":return ji(r,t,s);case"<":return xi(r,t,s);case"<=":return Vi(r,t,s);default:throw new TypeError(`Invalid operator: ${e}`)}};var ls=Ui;const Gi=W,Ji=Se,{safeRe:Ue,t:Ge}=Fe,Mi=(r,e)=>{if(r instanceof Gi)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Ue[Ge.COERCEFULL]:Ue[Ge.COERCE]);else{const c=e.includePrerelease?Ue[Ge.COERCERTLFULL]:Ue[Ge.COERCERTL];let u;for(;(u=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||u.index+u[0].length!==t.index+t[0].length)&&(t=u),c.lastIndex=u.index+u[1].length+u[2].length;c.lastIndex=-1}if(t===null)return null;const s=t[2],o=t[3]||"0",n=t[4]||"0",i=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Ji(`${s}.${o}.${n}${i}${a}`,e)};var _i=Mi;class Ki{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 Hi=Ki,at,gr;function oe(){if(gr)return at;gr=1;const r=/\s+/g;class e{constructor(p,v){if(v=o(v),p instanceof e)return p.loose===!!v.loose&&p.includePrerelease===!!v.includePrerelease?p:new e(p.raw,v);if(p instanceof n)return this.raw=p.value,this.set=[[p]],this.formatted=void 0,this;if(this.options=v,this.loose=!!v.loose,this.includePrerelease=!!v.includePrerelease,this.raw=p.trim().replace(r," "),this.set=this.raw.split("||").map(S=>this.parseRange(S.trim())).filter(S=>S.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const S=this.set[0];if(this.set=this.set.filter(P=>!m(P[0])),this.set.length===0)this.set=[S];else if(this.set.length>1){for(const P of this.set)if(P.length===1&&x(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 v=this.set[p];for(let S=0;S<v.length;S++)S>0&&(this.formatted+=" "),this.formatted+=v[S].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(p){const S=((this.options.includePrerelease&&h)|(this.options.loose&&R))+":"+p,P=s.get(S);if(P)return P;const b=this.options.loose,C=b?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];p=p.replace(C,Q(this.options.includePrerelease)),i("hyphen replace",p),p=p.replace(c[u.COMPARATORTRIM],l),i("comparator trim",p),p=p.replace(c[u.TILDETRIM],d),i("tilde trim",p),p=p.replace(c[u.CARETTRIM],g),i("caret trim",p);let T=p.split(" ").map(I=>G(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(c[u.COMPARATORLOOSE])))),i("range list",T);const E=new Map,A=T.map(I=>new n(I,this.options));for(const I of A){if(m(I))return[I];E.set(I.value,I)}E.size>1&&E.has("")&&E.delete("");const V=[...E.values()];return s.set(S,V),V}intersects(p,v){if(!(p instanceof e))throw new TypeError("a Range is required");return this.set.some(S=>L(S,v)&&p.set.some(P=>L(P,v)&&S.every(b=>P.every(C=>b.intersects(C,v)))))}test(p){if(!p)return!1;if(typeof p=="string")try{p=new a(p,this.options)}catch{return!1}for(let v=0;v<this.set.length;v++)if(ge(this.set[v],p,this.options))return!0;return!1}}at=e;const t=Hi,s=new t,o=At,n=rt(),i=et,a=W,{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:g}=Fe,{FLAG_INCLUDE_PRERELEASE:h,FLAG_LOOSE:R}=Ze,m=y=>y.value==="<0.0.0-0",x=y=>y.value==="",L=(y,p)=>{let v=!0;const S=y.slice();let P=S.pop();for(;v&&S.length;)v=S.every(b=>P.intersects(b,p)),P=S.pop();return v},G=(y,p)=>(i("comp",y,p),y=D(y,p),i("caret",y),y=_(y,p),i("tildes",y),y=de(y,p),i("xrange",y),y=K(y,p),i("stars",y),y),F=y=>!y||y.toLowerCase()==="x"||y==="*",_=(y,p)=>y.trim().split(/\s+/).map(v=>fe(v,p)).join(" "),fe=(y,p)=>{const v=p.loose?c[u.TILDELOOSE]:c[u.TILDE];return y.replace(v,(S,P,b,C,T)=>{i("tilde",y,S,P,b,C,T);let E;return F(P)?E="":F(b)?E=`>=${P}.0.0 <${+P+1}.0.0-0`:F(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(v=>Y(v,p)).join(" "),Y=(y,p)=>{i("caret",y,p);const v=p.loose?c[u.CARETLOOSE]:c[u.CARET],S=p.includePrerelease?"-0":"";return y.replace(v,(P,b,C,T,E)=>{i("caret",y,P,b,C,T,E);let A;return F(b)?A="":F(C)?A=`>=${b}.0.0${S} <${+b+1}.0.0-0`:F(T)?b==="0"?A=`>=${b}.${C}.0${S} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.0${S} <${+b+1}.0.0-0`:E?(i("replaceCaret pr",E),b==="0"?C==="0"?A=`>=${b}.${C}.${T}-${E} <${b}.${C}.${+T+1}-0`:A=`>=${b}.${C}.${T}-${E} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.${T}-${E} <${+b+1}.0.0-0`):(i("no pr"),b==="0"?C==="0"?A=`>=${b}.${C}.${T}${S} <${b}.${C}.${+T+1}-0`:A=`>=${b}.${C}.${T}${S} <${b}.${+C+1}.0-0`:A=`>=${b}.${C}.${T} <${+b+1}.0.0-0`),i("caret return",A),A})},de=(y,p)=>(i("replaceXRanges",y,p),y.split(/\s+/).map(v=>z(v,p)).join(" ")),z=(y,p)=>{y=y.trim();const v=p.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return y.replace(v,(S,P,b,C,T,E)=>{i("xRange",y,S,P,b,C,T,E);const A=F(b),V=A||F(C),I=V||F(T),le=I;return P==="="&&le&&(P=""),E=p.includePrerelease?"-0":"",A?P===">"||P==="<"?S="<0.0.0-0":S="*":P&&le?(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"),S=`${P+b}.${C}.${T}${E}`):V?S=`>=${b}.0.0${E} <${+b+1}.0.0-0`:I&&(S=`>=${b}.${C}.0${E} <${b}.${+C+1}.0-0`),i("xRange return",S),S})},K=(y,p)=>(i("replaceStars",y,p),y.trim().replace(c[u.STAR],"")),J=(y,p)=>(i("replaceGTE0",y,p),y.trim().replace(c[p.includePrerelease?u.GTE0PRE:u.GTE0],"")),Q=y=>(p,v,S,P,b,C,T,E,A,V,I,le)=>(F(S)?v="":F(P)?v=`>=${S}.0.0${y?"-0":""}`:F(b)?v=`>=${S}.${P}.0${y?"-0":""}`:C?v=`>=${v}`:v=`>=${v}${y?"-0":""}`,F(A)?E="":F(V)?E=`<${+A+1}.0.0-0`:F(I)?E=`<${A}.${+V+1}.0-0`:le?E=`<=${A}.${V}.${I}-${le}`:y?E=`<${A}.${V}.${+I+1}-0`:E=`<=${E}`,`${v} ${E}`.trim()),ge=(y,p,v)=>{for(let S=0;S<y.length;S++)if(!y[S].test(p))return!1;if(p.prerelease.length&&!v.includePrerelease){for(let S=0;S<y.length;S++)if(i(y[S].semver),y[S].semver!==n.ANY&&y[S].semver.prerelease.length>0){const P=y[S].semver;if(P.major===p.major&&P.minor===p.minor&&P.patch===p.patch)return!0}return!1}return!0};return at}var ct,mr;function rt(){if(mr)return ct;mr=1;const r=Symbol("SemVer ANY");class e{static get ANY(){return r}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===r?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],g=l.match(d);if(!g)throw new TypeError(`Invalid comparator: ${l}`);this.operator=g[1]!==void 0?g[1]:"",this.operator==="="&&(this.operator=""),g[2]?this.semver=new a(g[2],this.options.loose):this.semver=r}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===r||l===r)return!0;if(typeof l=="string")try{l=new a(l,this.options)}catch{return!1}return n(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||n(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||n(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}ct=e;const t=At,{safeRe:s,t:o}=Fe,n=ls,i=et,a=W,c=oe();return ct}const qi=oe(),Wi=(r,e,t)=>{try{e=new qi(e,t)}catch{return!1}return e.test(r)};var st=Wi;const zi=oe(),Xi=(r,e)=>new zi(r,e).set.map(t=>t.map(s=>s.value).join(" ").trim().split(" "));var Yi=Xi;const Qi=W,Zi=oe(),ea=(r,e,t)=>{let s=null,o=null,n=null;try{n=new Zi(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===-1)&&(s=i,o=new Qi(s,t))}),s};var ta=ea;const ra=W,sa=oe(),oa=(r,e,t)=>{let s=null,o=null,n=null;try{n=new sa(e,t)}catch{return null}return r.forEach(i=>{n.test(i)&&(!s||o.compare(i)===1)&&(s=i,o=new ra(s,t))}),s};var na=oa;const lt=W,ia=oe(),vr=tt,aa=(r,e)=>{r=new ia(r,e);let t=new lt("0.0.0");if(r.test(t)||(t=new lt("0.0.0-0"),r.test(t)))return t;t=null;for(let s=0;s<r.set.length;++s){const o=r.set[s];let n=null;o.forEach(i=>{const a=new lt(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!n||vr(a,n))&&(n=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),n&&(!t||vr(t,n))&&(t=n)}return t&&r.test(t)?t:null};var ca=aa;const la=oe(),ua=(r,e)=>{try{return new la(r,e).range||"*"}catch{return null}};var da=ua;const pa=W,us=rt(),{ANY:ha}=us,fa=oe(),ga=st,yr=tt,Sr=Dt,ma=Bt,va=Nt,ya=(r,e,t,s)=>{r=new pa(r,s),e=new fa(e,s);let o,n,i,a,c;switch(t){case">":o=yr,n=ma,i=Sr,a=">",c=">=";break;case"<":o=Sr,n=va,i=yr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ga(r,e,s))return!1;for(let u=0;u<e.set.length;++u){const l=e.set[u];let d=null,g=null;if(l.forEach(h=>{h.semver===ha&&(h=new us(">=0.0.0")),d=d||h,g=g||h,o(h.semver,d.semver,s)?d=h:i(h.semver,g.semver,s)&&(g=h)}),d.operator===a||d.operator===c||(!g.operator||g.operator===a)&&n(r,g.semver))return!1;if(g.operator===c&&i(r,g.semver))return!1}return!0};var jt=ya;const Sa=jt,ba=(r,e,t)=>Sa(r,e,">",t);var wa=ba;const Pa=jt,Ca=(r,e,t)=>Pa(r,e,"<",t);var Ra=Ca;const br=oe(),Ea=(r,e,t)=>(r=new br(r,t),e=new br(e,t),r.intersects(e,t));var ka=Ea;const Oa=st,$a=se;var Ta=(r,e,t)=>{const s=[];let o=null,n=null;const i=r.sort((l,d)=>$a(l,d,t));for(const l of i)Oa(l,e,t)?(n=l,o||(o=l)):(n&&s.push([o,n]),n=null,o=null);o&&s.push([o,null]);const a=[];for(const[l,d]of s)l===d?a.push(l):!d&&l===i[0]?a.push("*"):d?l===i[0]?a.push(`<=${d}`):a.push(`${l} - ${d}`):a.push(`>=${l}`);const c=a.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return c.length<u.length?c:e};const wr=oe(),xt=rt(),{ANY:ut}=xt,be=st,Vt=se,Fa=(r,e,t={})=>{if(r===e)return!0;r=new wr(r,t),e=new wr(e,t);let s=!1;e:for(const o of r.set){for(const n of e.set){const i=Aa(o,n,t);if(s=s||i!==null,i)continue e}if(s)return!1}return!0},Ia=[new xt(">=0.0.0-0")],Pr=[new xt(">=0.0.0")],Aa=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===ut){if(e.length===1&&e[0].semver===ut)return!0;t.includePrerelease?r=Ia:r=Pr}if(e.length===1&&e[0].semver===ut){if(t.includePrerelease)return!0;e=Pr}const s=new Set;let o,n;for(const h of r)h.operator===">"||h.operator===">="?o=Cr(o,h,t):h.operator==="<"||h.operator==="<="?n=Rr(n,h,t):s.add(h.semver);if(s.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 s){if(o&&!be(h,String(o),t)||n&&!be(h,String(n),t))return null;for(const R of e)if(!be(h,String(R),t))return!1;return!0}let a,c,u,l,d=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1,g=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(l=l||h.operator===">"||h.operator===">=",u=u||h.operator==="<"||h.operator==="<=",o){if(g&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===g.major&&h.semver.minor===g.minor&&h.semver.patch===g.patch&&(g=!1),h.operator===">"||h.operator===">="){if(a=Cr(o,h,t),a===h&&a!==o)return!1}else if(o.operator===">="&&!be(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(c=Rr(n,h,t),c===h&&c!==n)return!1}else if(n.operator==="<="&&!be(n.semver,String(h),t))return!1}if(!h.operator&&(n||o)&&i!==0)return!1}return!(o&&u&&!n&&i!==0||n&&l&&!o&&i!==0||g||d)},Cr=(r,e,t)=>{if(!r)return e;const s=Vt(r.semver,e.semver,t);return s>0?r:s<0||e.operator===">"&&r.operator===">="?e:r},Rr=(r,e,t)=>{if(!r)return e;const s=Vt(r.semver,e.semver,t);return s<0?r:s>0||e.operator==="<"&&r.operator==="<="?e:r};var La=Fa;const dt=Fe,Er=Ze,Da=W,kr=is,Na=Se,Ba=Jn,ja=Kn,xa=qn,Va=zn,Ua=Qn,Ga=ti,Ja=oi,Ma=ai,_a=se,Ka=di,Ha=fi,qa=Lt,Wa=yi,za=wi,Xa=tt,Ya=Dt,Qa=as,Za=cs,ec=Nt,tc=Bt,rc=ls,sc=_i,oc=rt(),nc=oe(),ic=st,ac=Yi,cc=ta,lc=na,uc=ca,dc=da,pc=jt,hc=wa,fc=Ra,gc=ka,mc=Ta,vc=La;var yc={parse:Na,valid:Ba,clean:ja,inc:xa,diff:Va,major:Ua,minor:Ga,patch:Ja,prerelease:Ma,compare:_a,rcompare:Ka,compareLoose:Ha,compareBuild:qa,sort:Wa,rsort:za,gt:Xa,lt:Ya,eq:Qa,neq:Za,gte:ec,lte:tc,cmp:rc,coerce:sc,Comparator:oc,Range:nc,satisfies:ic,toComparators:ac,maxSatisfying:cc,minSatisfying:lc,minVersion:uc,validRange:dc,outside:pc,gtr:hc,ltr:fc,intersects:gc,simplifyRange:mc,subset:vc,SemVer:Da,re:dt.re,src:dt.src,tokens:dt.t,SEMVER_SPEC_VERSION:Er.SEMVER_SPEC_VERSION,RELEASE_TYPES:Er.RELEASE_TYPES,compareIdentifiers:kr.compareIdentifiers,rcompareIdentifiers:kr.rcompareIdentifiers};const Sc=kn(yc),bc={minDelay:1500},wc="__no_updates__";class Pc extends j.PollComputablePool{constructor(t,s,o={}){super({...o,...bc},s);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_${re(t)}`;default:return wc}}async readValue(t){var s,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 H.tryLoadPackDescription(n.folder,this.logger);if(i===void 0)return{suggestions:[]};const a=await We(i);return a===n.mtime?{suggestions:[]}:{mainSuggestion:{...n,mtime:a},suggestions:[]}}catch(i){return this.logger.warn(i),{suggestions:[]}}case"from-registry-v2":try{const{versionLock:i,skipVersion:a}=t.settings;if(i==="patch")return{suggestions:[]};const c=this.registryProvider.getRegistry(n.registryUrl);let u=this.preferredUpdateChannel;if(u===void 0)if(n.channel===void 0)if(await c.getLatestOverview(n.id,U.StableChannel))u=U.StableChannel;else{if(await c.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 l=await c.getUpdateSuggestions(n.id,u);if(l===void 0||l.length===0)return{suggestions:[]};l.reverse();let d;switch(i){case void 0:d=l[0].update;break;case"major":d=(s=l.find(R=>R.type!=="major"))==null?void 0:s.update;break;case"minor":d=(o=l.find(R=>R.type==="patch"))==null?void 0:o.update;break}const g=l.map(({type:R,update:m})=>({type:R,update:{...n,id:{...n.id,version:m}}}));if(d===void 0)return{suggestions:g};if(a!==void 0&&Sc.lte(d,a))return{suggestions:g};const h={...n,id:{...n.id,version:d}};return(async()=>{try{await c.getComponents(h.id)}catch(R){this.logger.warn(R)}})(),{suggestions:g,mainSuggestion:h}}catch(i){return this.logger.warn(i),{suggestions:[]}}default:return{suggestions:[]}}}catch(n){return this.logger.warn(n),{suggestions:[]}}}resultsEqual(t,s){return re(t)===re(s)}}class Or{constructor(){w(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");t.refCount===0&&(this.resources.delete(e),(o=>o!=null&&typeof o[Symbol.dispose]=="function")(t.resource)&&t.resource[Symbol.dispose]())}acquire(e){const t=this.calculateParamsKey(e);let s=this.resources.get(t);s===void 0&&(s={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,s)),s.refCount++;let o=!1;return{resource:s.resource,key:t,unref:()=>{o||(s.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 we;function ie(){return we||(we={logPFrameRequests:process.env.MI_LOG_PFRAMES!==void 0,usePFrameRs:process.env.MI_USE_PFRAMES_RS!==void 0},process.env.MI_LOG_TREE_STAT&&(we.logTreeStats=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request"),we)}function Oe(r){return String(r.id)}const Cc=["Int","Long","Float","Double","String","Bytes"];function Pe(r){const e=[],t=[];for(const s of r)s.type==="bySingleColumn"?(e.push(s),t.push({...s,type:"bySingleColumnV2"})):t.push(s);if(e.length>0){const s=JSON.stringify(e);console.warn(`type overriten from 'bySingleColumn' to 'bySingleColumnV2' for filters: ${s}`)}return t}function $r(r){const e=t=>{switch(t.operator){case"Matches":case"StringContainsFuzzy":case"StringIContainsFuzzy":return!1;case"Not":return e(t.operand);case"And":case"Or":return t.operands.every(s=>e(s));default:return!0}};return r.every(t=>e(t.predicate))}const Ce=(r,e)=>typeof e=="bigint"?e.toString():e;class Rc{constructor(e,t,s,o){w(this,"rustPFrame");w(this,"blobIdToResource",new Map);w(this,"blobHandleComputables",new Map);w(this,"createDataPFrame");w(this,"preloadBlob",async e=>{const t=e.map(s=>this.getOrCreateComputableForBlob(s));for(const s of t)await s.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),s=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(s)}catch(t){const s=JSON.stringify(t);throw console.log(`resolveBlobContent catched error: ${s}`),t}});this.blobDriver=e,this.logger=t,this.blobContentCache=s;const n=(a,c)=>{switch(a){default:case"info":return this.logger.info(c);case"warn":return this.logger.warn(c);case"error":return this.logger.error(c)}};for(const a of o)for(const c of Po(a.data))this.blobIdToResource.set(Oe(c),c);const i=[...new Map(o.map(a=>({...a,data:Co(a.data,Oe)})).map(a=>[re(a),a])).values()];this.rustPFrame=(()=>{try{const a=new bs.PFrame(ie().logPFrameRequests?n:void 0);a.setDataSource(this);for(const c of i)a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data);return a}catch(a){throw new Error(`Rust PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}})(),this.createDataPFrame=()=>{try{const a=ie().logPFrameRequests?new _t.PFrame(n):new _t.PFrame;a.setDataSource(this);for(const c of i)try{a.addColumnSpec(c.id,c.spec),a.setColumnData(c.id,c.data)}catch(u){throw new Error(`Adding column ${c.id} to PFrame failed: ${u}; Spec: ${JSON.stringify(c.spec)}, DataInfo: ${JSON.stringify(c.data)}.`)}return a}catch(a){throw new Error(`Data PFrame creation failed, columns: ${JSON.stringify(i)}, error: ${a}`)}}}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 s=this.blobIdToResource.get(e);if(s===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(s).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.rustPFrame.dispose()}}class Ec{constructor(e){this.table=e}[Symbol.dispose](){this.table.then(e=>e.dispose())}}class kc{constructor(e,t){w(this,"pFrames");w(this,"pTables");w(this,"blobContentCache");w(this,"concurrencyLimiter");this.blobDriver=e,this.logger=t;const s=new ws.LRUCache({maxSize:1e9,fetchMethod:async n=>await Ar.readFile(n),sizeCalculation:n=>n.length});this.blobContentCache=s;const o=new k.ConcurrencyLimitingExecutor(1);this.concurrencyLimiter=o,this.pFrames=new class extends Or{constructor(n,i){super(),this.blobDriver=n,this.logger=i}createNewResource(n){return ie().logPFrameRequests&&t.info(`PFrame creation (pFrameHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Ce)}`),new Rc(this.blobDriver,this.logger,s,n)}calculateParamsKey(n){return $c(n)}}(this.blobDriver,this.logger),this.pTables=new class extends Or{constructor(n){super(),this.pFrames=n}createNewResource(n){const i=n.pFrameHandle,a=o.run(async()=>{if(ie().logPFrameRequests&&t.info(`PTable creation (pTableHandle = ${this.calculateParamsKey(n)}): ${JSON.stringify(n,Ce)}`),ie().usePFrameRs&&$r(n.def.filters))return await this.pFrames.getByKey(i).rustPFrame.createTable({src:pe(n.def.src),filters:Pe(n.def.filters)},n.signal);var c=[];try{const g=Ie(c,this.pFrames.getByKey(i).disposableDataPFrame);return await g.dataPFrame.createTable({src:pe(n.def.src),filters:Pe(n.def.filters)},n.signal)}catch(u){var l=u,d=!0}finally{Ae(c,l,d)}}).then(async c=>n.def.sorting.length!==0?await c.sort(n.def.sorting,n.signal):c);return new Ec(a)}calculateParamsKey(n){return Oc(n)}}(this.pFrames)}createPFrame(e,t){const s=e.filter(n=>Cc.find(i=>i===n.spec.valueType)).map(n=>B.mapPObjectData(n,i=>qe.isPlTreeNodeAccessor(i)?To(i):Fo(n.spec,i))),o=this.pFrames.acquire(s);return t.addOnDestroy(o.unref),o.key}createPTable(e,t,s){const o=this.createPFrame(B.extractAllColumns(e.src),t),n=B.mapPTableDef(e,a=>a.id),i=this.pTables.acquire({def:n,pFrameHandle:o,signal:s});return ie().logPFrameRequests&&this.logger.info(`Create PTable call (pFrameHandle = ${o}; pTableHandle = ${JSON.stringify(i)}): ${JSON.stringify(B.mapPTableDef(e,a=>a.spec),Ce)}`),t.addOnDestroy(i.unref),i.key}async findColumns(e,t){const s={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:[...new Map(t.compatibleWith.map(n=>[re(n),n])).values()],qualifications:[]}]:[]};return{hits:(await this.pFrames.getByKey(e).rustPFrame.findColumns(s)).hits.filter(n=>n.mappingVariants.length===0||n.mappingVariants.some(i=>i.qualifications.forHit.length===0&&i.qualifications.forQueries.every(a=>a.length===0))).map(n=>n.hit)}}async getColumnSpec(e,t){return await this.pFrames.getByKey(e).rustPFrame.getColumnSpec(t)}async listColumns(e){return await this.pFrames.getByKey(e).rustPFrame.listColumns()}async calculateTableData(e,t,s){let o=await this.concurrencyLimiter.run(async()=>{if(ie().logPFrameRequests&&this.logger.info(`Call calculateTableData, handle = ${e}, request = ${JSON.stringify(t,Ce)}`),ie().usePFrameRs&&$r(t.filters))return await this.pFrames.getByKey(e).rustPFrame.createTable({src:pe(t.src),filters:Pe(t.filters)},s);var a=[];try{const d=Ie(a,this.pFrames.getByKey(e).disposableDataPFrame);return await d.dataPFrame.createTable({src:pe(t.src),filters:Pe(t.filters)},s)}catch(c){var u=c,l=!0}finally{Ae(a,u,l)}});if(t.sorting.length>0){const a=await this.concurrencyLimiter.run(async()=>await o.sort(t.sorting,s));o.dispose(),o=a}const n=o.getSpec(),i=await this.concurrencyLimiter.run(async()=>await o.getData([...n.keys()]));return o.dispose(),n.map((a,c)=>({spec:a,data:i[c]}))}async getUniqueValues(e,t,s){return await this.concurrencyLimiter.run(async()=>{var n=[];try{ie().logPFrameRequests&&this.logger.info(`Call getUniqueValues, handle = ${e}, request = ${JSON.stringify(t,Ce)}`);const o=Ie(n,this.pFrames.getByKey(e).disposableDataPFrame);return await o.dataPFrame.getUniqueValues({...t,filters:Pe(t.filters)},s)}catch(i){var a=i,c=!0}finally{Ae(n,a,c)}})}async getShape(e){return(await this.pTables.getByKey(e).table).getShape()}async getSpec(e){return(await this.pTables.getByKey(e).table).getSpec()}async getData(e,t,s){const o=await this.pTables.getByKey(e).table;return await this.concurrencyLimiter.run(async()=>await o.getData(t,s))}}function pe(r){switch(r.type){case"column":return{type:"column",columnId:r.column,qualifications:[]};case"inner":case"full":return{type:r.type,entries:r.entries.map(e=>pe(e))};case"outer":return{type:"outer",primary:pe(r.primary),secondary:r.secondary.map(e=>pe(e))};default:k.assertNever(r)}}function Oc(r){const e=ce.createHash("sha256");return e.update(re(r)),e.digest().toString("hex")}function $c(r){const e=[...r].map(s=>B.mapPObjectData(s,o=>{let n;const i=o.type;switch(i){case"Json":n={type:o.type,keyLength:o.keyLength,payload:Object.entries(o.data).map(([a,c])=>({key:a,value:c}))};break;case"JsonPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:Oe(c)}))};break;case"BinaryPartitioned":n={type:o.type,keyLength:o.partitionKeyLength,payload:Object.entries(o.parts).map(([a,c])=>({key:a,value:[Oe(c.index),Oe(c.values)]}))};break;default:throw Error(`unsupported resource type: ${JSON.stringify(i)}`)}return n.payload.sort((a,c)=>a.key.localeCompare(c.key)),n}));e.sort((s,o)=>s.id.localeCompare(o.id));const t=ce.createHash("sha256");return t.update(re(e)),t.digest().toString("hex")}async function ds(r,e,t){const s={...Ft,...It(e),...t},o=new k.HmacSha256Signer(s.localSecret),n=ee.createDownloadClient(s.logger,r,s.localProjections),i=ee.createLogsClient(r,s.logger),a=ee.createUploadBlobClient(r,s.logger),c=ee.createUploadProgressClient(r,s.logger),u=new ee.DownloadDriver(s.logger,n,i,s.blobDownloadPath,o,s.blobDriverOps),l=new ee.DownloadBlobToURLDriver(s.logger,o,n,s.downloadBlobToURLPath,s.downloadBlobToURLDriverOps),d=new ee.UploadDriver(s.logger,o,a,c,s.uploadDriverOps),g=new ee.LogsStreamDriver(s.logger,i,s.logStreamDriverOps),h=new ee.LogsDriver(s.logger,g,u),R=await ee.LsDriver.init(s.logger,r,o,s.localProjections,s.openFileDialogCallback,s.virtualLocalStoragesOverride),m=new kc(u,s.logger);return{blobDriver:u,blobToURLDriver:l,logDriver:h,lsDriver:R,signer:o,uploadDriver:d,pFrameDriver:m}}class Ut{constructor(e,t,s,o,n,i,a,c){w(this,"pl");w(this,"projectList");w(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=s,this.projectListResourceId=o,this.openedProjectsList=n,this.projectListTree=i,this.blockRegistryProvider=a,this.projectList=c,this.pl=this.env.pl}get internalDriverKit(){return this.env.driverKit}async createProject(e,t=ce.randomUUID()){const s=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await wo(o,e);return o.createField(f.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await f.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),s}async setProjectMeta(e,t,s){await te(this.pl,e,s,o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(f.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 s=(await t.getField(f.field(this.projectListResourceId,e))).value;if(f.isNullResourceId(s))throw new Error("Unexpected project list structure.");return s})}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 Qe.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,s){const o={...rs,...ss(t),...s};o.defaultTreeOptions.logStat=ie().logTreeStats;const n=await e.withWriteTx("MLInitialization",async m=>{const x=f.field(m.clientRoot,Hs);m.createField(x,"Dynamic");const L=await m.getField(x);if(f.isNullResourceId(L.value)){const G=m.createEphemeral(jr);return m.lock(G),m.setField(x,G),await m.commit(),await G.globalId}else return L.value}),i=o.logger,a=await ds(e,t,o),c=new ue.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new Dr(c),l=new fo(u,a.signer,c),d=new ee.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),g={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:l,frontendDownloadDriver:d,driverKit:a,blockUpdateWatcher:new Pc(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c,preferredUpdateChannel:o.preferredUpdateChannel}),quickJs:await Me.getQuickJS()},h=new j.WatchableValue([]),R=await Ws(e,n,h,g);return new Ut(g,a,a.signer,n,h,R.tree,u,R.computable)}}const Tc=["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 Fc(r,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},s=[];Tc.forEach(c=>{Ps.channel(c).subscribe(l=>{var g;const d=new Date().toISOString();(g=l==null?void 0:l.response)!=null&&g.headers&&(l.response.headers=l.response.headers.map(h=>h.toString())),s.push(JSON.stringify({timestamp:d,event:c,data:l}))})});const o={plPings:[],blockRegistryOverviewChecks:[],blockGARegistryOverviewChecks:[],blockRegistryUiChecks:[],blockGARegistryUiChecks:[],autoUpdateCdnChecks:[]},n=f.plAddressToConfig(r,{defaultRequestTimeout:t.pingTimeoutMs});o.plPings=await ve(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const u=await new f.UnauthenticatedPlClient(n).ping();return JSON.stringify(u).slice(0,t.bodyLimit)+"..."});const a=new f.UnauthenticatedPlClient(n).ll.httpDispatcher;return o.blockRegistryOverviewChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockRegistryUrl),t,a)),o.blockGARegistryOverviewChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockOverviewPath,t.blockGARegistryUrl),t,a)),o.blockRegistryUiChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockRegistryUrl),t,a)),o.blockGARegistryUiChecks=await ve(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>await Re(new URL(t.blockUiPath,t.blockGARegistryUrl),t,a)),o.autoUpdateCdnChecks=await ve(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>await Re(t.autoUpdateCdnUrl,t,a)),Ic(o,r,t,s)}async function ve(r,e,t){const s=bt(),o=[];for(;Tr(s)<r;){const n=bt();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=Tr(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await Ir.setTimeout(c)}return o}async function Re(r,e,t){const{body:s,statusCode:o}=await ue.request(r,{dispatcher:t,headersTimeout:e.httpTimeoutMs,bodyTimeout:e.httpTimeoutMs}),n=await s.text();return{statusCode:o,beginningOfBody:n.slice(0,e.bodyLimit)+"..."}}function Ic(r,e,t,s){const o=r.plPings.filter(a=>a.response.ok),n=r.plPings.filter(a=>!a.response.ok),i=[...new Set(o.map(a=>JSON.stringify(a.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
|
${s.join(`
|
|
41
41
|
`)}
|
|
42
|
-
`}function ye(r){const e=r.filter(o=>o.response.ok),{mean:t,median:s}=
|
|
42
|
+
`}function ye(r){const e=r.filter(o=>o.response.ok),{mean:t,median:s}=Ac(r);return`
|
|
43
43
|
total: ${r.length};
|
|
44
44
|
successes: ${e.length};
|
|
45
45
|
errors: ${r.length-e.length};
|
|
46
46
|
mean in ms: ${t};
|
|
47
47
|
median in ms: ${s};
|
|
48
|
-
`}function
|
|
48
|
+
`}function Ac(r){const e=r.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let s;if(e.length>0){const o=Math.floor(e.length/2);s=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:s}}function bt(){return Date.now()}function Tr(r){return bt()-r}exports.BlockPackRegistry=Is;exports.CentralBlockRegistry=As;exports.DefaultDriverKitOpsPaths=It;exports.DefaultDriverKitOpsSettings=Ft;exports.DefaultMiddleLayerOpsPaths=ss;exports.DefaultMiddleLayerOpsSettings=rs;exports.FrontendFromFolderResourceType=Ot;exports.FrontendFromUrlResourceType=kt;exports.MiddleLayer=Ut;exports.Project=Qe;exports.TengoTemplateGet=Vr;exports.TengoTemplateGetRegistry=Ur;exports.TengoTemplateGetTemplate=Jr;exports.TengoTemplateGetTemplateURI=Gr;exports.TengoTemplatePack=io;exports.TengoTemplatePackConvert=ao;exports.TengoTemplatePackConvertTemplate=lo;exports.TengoTemplatePackConvertTemplatePack=co;exports.V1CentralDevSnapshotRegistry=Ds;exports.V1CentralRegistry=Ls;exports.V2RegistryProvider=Dr;exports.checkNetwork=Fc;exports.createRenderTemplate=Et;exports.getDevV1PacketMtime=Ct;exports.getDevV2PacketMtime=We;exports.initDriverKit=ds;exports.loadTemplate=ze;exports.prepareTemplateSpec=Mr;Object.keys(B).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>B[r]})});Object.keys(U).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>U[r]})});Object.keys(Mt).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>Mt[r]})});Object.keys(f).forEach(r=>{r!=="default"&&!Object.prototype.hasOwnProperty.call(exports,r)&&Object.defineProperty(exports,r,{enumerable:!0,get:()=>f[r]})});
|
|
49
49
|
//# sourceMappingURL=index.js.map
|