@milaboratories/pl-middle-layer 1.14.32 → 1.15.0
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/block_registry/registry.d.ts.map +1 -1
- package/dist/cfg_render/executor.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +898 -825
- package/dist/index.mjs.map +1 -1
- package/dist/js_render/context.d.ts +3 -0
- package/dist/js_render/context.d.ts.map +1 -1
- package/dist/js_render/index.d.ts +2 -2
- package/dist/js_render/index.d.ts.map +1 -1
- package/dist/middle_layer/active_cfg.d.ts.map +1 -1
- package/dist/middle_layer/project.d.ts +0 -2
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project_overview.d.ts.map +1 -1
- package/dist/middle_layer/render.d.ts +3 -2
- package/dist/middle_layer/render.d.ts.map +1 -1
- package/dist/middle_layer/util.d.ts +3 -2
- package/dist/middle_layer/util.d.ts.map +1 -1
- package/dist/model/block_pack.d.ts +2 -2
- package/dist/model/block_pack_spec.d.ts +2 -2
- package/dist/model/block_pack_spec.d.ts.map +1 -1
- package/dist/model/project_model.d.ts +4 -1
- package/dist/model/project_model.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.d.ts +2 -2
- package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
- package/dist/mutator/project.d.ts +1 -1
- package/dist/mutator/project.d.ts.map +1 -1
- package/dist/pool/result_pool.d.ts +3 -1
- package/dist/pool/result_pool.d.ts.map +1 -1
- package/package.json +11 -11
- package/src/block_registry/registry.ts +12 -2
- package/src/cfg_render/executor.ts +2 -1
- package/src/js_render/context.ts +46 -0
- package/src/js_render/index.ts +12 -4
- package/src/middle_layer/active_cfg.ts +6 -9
- package/src/middle_layer/middle_layer.test.ts +9 -9
- package/src/middle_layer/project.ts +13 -13
- package/src/middle_layer/project_overview.ts +17 -6
- package/src/middle_layer/render.ts +9 -3
- package/src/middle_layer/util.ts +5 -3
- package/src/model/block_pack.ts +2 -2
- package/src/model/block_pack_spec.ts +2 -2
- package/src/model/project_model.ts +4 -1
- package/src/mutator/block-pack/block_pack.test.ts +1 -1
- package/src/mutator/block-pack/block_pack.ts +10 -10
- package/src/mutator/project.test.ts +7 -0
- package/src/mutator/project.ts +20 -13
- package/src/pool/result_pool.ts +45 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/block_registry/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAW,MAAM,QAAQ,CAAC;AAE7C,OAAO,EACL,4BAA4B,EAG7B,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EACL,gBAAgB,EAEhB,aAAa,EAEd,MAAM,uCAAuC,CAAC;AAwB/C,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1E;AAED,wBAAsB,mBAAmB,CACvC,WAAW,EAAE,4BAA4B,GACxC,OAAO,CAAC,MAAM,CAAC,CAOjB;AAED,qBAAa,iBAAiB;IAE1B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAFL,UAAU,EAAE,kBAAkB,EAC9B,UAAU,EAAE,aAAa,EAAE,EAC3B,IAAI,CAAC,EAAE,UAAU,YAAA;YAGtB,kBAAkB;
|
|
1
|
+
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/block_registry/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAW,MAAM,QAAQ,CAAC;AAE7C,OAAO,EACL,4BAA4B,EAG7B,MAAM,4BAA4B,CAAC;AAOpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EACL,gBAAgB,EAEhB,aAAa,EAEd,MAAM,uCAAuC,CAAC;AAwB/C,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1E;AAED,wBAAsB,mBAAmB,CACvC,WAAW,EAAE,4BAA4B,GACxC,OAAO,CAAC,MAAM,CAAC,CAOjB;AAED,qBAAa,iBAAiB;IAE1B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,UAAU;IAC3B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAFL,UAAU,EAAE,kBAAkB,EAC9B,UAAU,EAAE,aAAa,EAAE,EAC3B,IAAI,CAAC,EAAE,UAAU,YAAA;YAGtB,kBAAkB;IAuHnB,cAAc,IAAI,OAAO,CAAC,gBAAgB,CAAC;CASzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/cfg_render/executor.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAiB,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG3C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/cfg_render/executor.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAiB,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAG3C,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AA6KlE,2CAA2C;AAC3C,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,oBAAoB,EAC7B,IAAI,EAAE,eAAe,EACrB,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAErB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,GAAG,EAAE,GAAG,EACR,GAAG,GAAE,OAAO,CAAC,sBAAsB,CAAM,GACxC,UAAU,CAAC,OAAO,CAAC,CAmDrB"}
|
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var Ht=Object.defineProperty;var _t=(s,e,t)=>e in s?Ht(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var p=(s,e,t)=>_t(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),M=require("undici"),D=require("@platforma-sdk/block-tools"),A=require("node:fs"),x=require("node:path"),qt=require("yaml"),h=require("@milaboratories/ts-helpers"),zt=require("node:fs/promises"),Wt=require("@milaboratories/resolve-helper"),l=require("@milaboratories/pl-client"),Ee=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),K=require("node:crypto"),dt=require("denque"),Yt=require("@platforma-sdk/workflow-tengo"),xe=require("canonicalize"),Qt=require("node:assert"),ie=require("quickjs-emscripten"),pt=require("node:timers/promises"),J=require("@milaboratories/pl-drivers"),Zt=require("@milaboratories/pframes-node"),Xt=require("lru-cache");function er(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const gt=er(zt);async function Ye(s){try{return await gt.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const tr=[D.RegistryV1.PlPackageYamlConfigFile],rr=[D.RegistryV1.PlPackageJsonConfigFile],je=["backend","dist","tengo","tpl","main.plj.gz"],Ae=["config","dist","config.json"],ht=["frontend","dist"],Qe="block-model/dist/config.json",sr="block-ui/package.json",or=[je,Ae,tr,rr,ht];async function nr(s){return await Ye(x.join(s,...Ae))!==void 0||await Ye(x.join(s,...je))!==void 0}function me(s,e){const t=Wt.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Ze(s,e){if(x.isAbsolute(s)||(s=x.resolve(s)),await nr(s))return{workflow:x.join(s,...je),config:x.join(s,...Ae),ui:x.join(s,...ht)};{const t=me(s,Qe),r=me(s,Qe),o=me(s,sr);return{workflow:t,config:r,ui:x.resolve(o,"..","dist")}}}async function ir(s){try{return await A.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function ar(s){try{return await A.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ie(s){let e=0n;for(const t of or){const r=x.join(s,...t),o=await ar(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function de(s){const e=await A.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await A.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class cr{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await M.request(`${r.url}/${D.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:d,latestVersion:g}=a,f={organization:c,name:u,version:g};t.push({registryId:e.id,id:f,meta:{title:d.title??"No title",description:d.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:f,registryUrl:r.url},otherVersions:a.allVersions})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(a=>({...a,registryId:e.id}));case"local-dev":for(const a of await A.promises.readdir(r.path,{withFileTypes:!0})){if(!a.isDirectory())continue;const c=x.join(r.path,a.name),u=await ir(x.join(c,D.RegistryV1.PlPackageYamlConfigFile));if(u!==void 0){const d=D.RegistryV1.PlPackageConfigData.parse(qt.parse(u)),g=await Ie(c),f={organization:d.organization,name:d.package,version:"DEV"};t.push({registryId:e.id,id:f,meta:{title:d.meta.title??"No title",description:d.meta.description??"No Description",organization:{name:d.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:c,mtime:g},otherVersions:[]})}else{const d=await D.tryLoadPackDescription(c);if(d!==void 0){const g=await de(d);t.push({registryId:e.id,id:d.id,meta:await D.BlockPackMetaEmbedAbsoluteBytes.parseAsync(d.meta),spec:{type:"dev-v2",folder:c,mtime:g},otherVersions:[]})}}}return t;default:return h.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}}class ft{constructor(e){p(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new D.RegistryV2Reader(D.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const ur={type:"remote-v2",url:"https://blocks.pl-open.science/"},lr={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},dr={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},pr={groups:[{id:"default",label:"Default",blocks:[]}]},gr={stagingRefreshTimestamp:0,blocksInLimbo:[]},hr={label:"New Project"},fr={name:"UserProject",version:"2"},mt="SchemaVersion",vt="1",Ne="ProjectCreated",X="ProjectLastModified",ee="ProjectMeta",q="ProjectStructure",ae="BlockRenderingState",mr="BlockFrontendState/",vr=/^BlockFrontendState\/(?<blockid>.*)$/;function ke(s){return`${mr}${s}`}const yr="BlockArgsAuthor/";function Ce(s){return`${yr}${s}`}const Pe="ProjectStructureAuthor";function br(s){const e=s.match(vr);if(e!==null)return e.groups.blockid}const wr="__serviceTemplate_";function Re(s){return`${wr}${s}`}function P(s,e){return`${s}-${e}`}const Sr=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function kr(s){const e=s.match(Sr);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Cr="projects",yt={name:"Projects",version:"1"},Pr=s=>l.resourceTypesEqual(s.type,yt)?s.fields:[];async function Rr(s,e,t,r){const o=await Ee.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Pr},r.logger);return{computable:S.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const d of a.listDynamicFields()){const g=a.traverse(d);if(g===void 0)continue;const f=h.notEmpty(g.getKeyValueAsJson(ee)),v=h.notEmpty(g.getKeyValueAsJson(Ne)),w=h.notEmpty(g.getKeyValueAsJson(X));u.push({id:d,rid:g.id,created:new Date(v),lastModified:new Date(w),opened:c.indexOf(g.id)>=0,meta:f})}return u.sort(d=>-d.lastModified.valueOf()),u}).withStableType(),tree:o}}const Fr={name:"EphRenderTemplate",version:"1"},Or={name:"RenderTemplate",version:"1"};function Ve(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Fr):s.createStruct(Or),i=l.field(n,"template"),a=l.field(n,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",l.Pl.createPlMap(s,r,t)),s.lockInputs(n),l.Pl.futureRecord(s,n,o,"Output","outputs/")}const Br={name:"BContextEnd",version:"1"},Dr={name:"BContext",version:"1"},Tr="id",Er="parent/",xr=["context","result"];function Xe(s,e,t){return Ve(s,e,!0,t,xr)}function jr(s){const e=s.createEphemeral(Br);return s.lock(e),e}function Ar(s,e){if(e.length===0)return jr(s);if(e.length===1)return e[0];const t=s.createEphemeral(Dr);s.createField(l.field(t,Tr),"Input",l.Pl.createPlString(s,K.randomUUID()));for(let r=0;r<e.length;r++)s.createField(l.field(t,`${Er}${r}`),"Input",e[r]);return s.lock(t),t}const bt={name:"TengoTemplateGet",version:"1"},wt="registry",St="templateURI",kt="template",Ct={name:"TengoTemplatePack",version:"1"},Pt={name:"TengoTemplatePackConvert",version:"1"},Rt="templatePack",Ft="template";async function Ot(s){switch(s.type){case"from-file":return{type:"explicit",content:await A.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return h.assertNever(s)}}function Ir(s,e){const t=s.createStruct(bt),r=l.field(t,wt),o=l.field(t,St),n=l.field(t,kt);return s.setField(r,s.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Nr(s,e){const t=s.createValue(Ct,e.content),r=s.createStruct(Pt),o=l.field(r,Rt),n=l.field(r,Ft);return s.setField(o,t),n}function pe(s,e){switch(e.type){case"from-registry":return Ir(s,e);case"explicit":return Nr(s,e);default:return h.assertNever(e)}}const Le={name:"Frontend/FromUrl",version:"1"},Je={name:"Frontend/FromFolder",version:"1"};function Vr(s,e){switch(e.type){case"url":return s.createValue(Le,JSON.stringify({url:e.url}));case"local":return s.createValue(Je,JSON.stringify({path:e.path,signature:e.signature}));default:return h.assertNever(e)}}const Lr={name:"BlockPackCustom",version:"1"},Bt="template",Dt="frontend";function et(s){return s.endsWith("/")?s:`${s}/`}class Jr{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfig(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Ze(e.folder),r=await A.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=await A.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${et(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await M.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await M.request(o.model.url,t)).body.json()}default:return h.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Ze(e.folder),r=await A.promises.readFile(t.workflow),o=JSON.parse(await A.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=JSON.parse(await A.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await A.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await de(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${et(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await M.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 M.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:c,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await M.request(o.model.url,t)).body.json(),i=async()=>await(await M.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 h.assertNever(e)}}}function Mr(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Lr,JSON.stringify(t));return s.createField(l.field(r,Bt),"Input",pe(s,e.template)),s.createField(l.field(r,Dt),"Input",Vr(s,e.frontend)),s.lock(r),r}function tt(s,e){switch(e.type){case"explicit":return Mr(s,e);default:return h.assertNever(e.type)}}function se(s,e){return{__isRef:!0,blockId:s,name:e}}function Ur(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Fe(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if(Ur(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)Fe(s,o,t);else for(const[,o]of Object.entries(e))Fe(s,o,t);return;default:h.assertNever(r)}}function Kr(s,e){const t={upstreams:new Set,missingReferences:!1};return Fe(t,s,e),t}function V(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Tt{constructor(e){p(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){let i=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function Oe(s){const e=new Map;let t;for(const{id:r}of V(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Tt(e)}function oe(s,e){const t=new Map,r=new Set;for(const{id:o}of V(s)){const n=e(o);if(n===void 0)continue;const i=Kr(n,r),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)),r.add(o)}return new Tt(t)}function $r(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Be(s,e){if(s.size>e.size)return Be(e,s);for(const t of s)if(e.has(t))return!0;return!1}function rt(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!$r(n.upstream,i.upstream)||Be(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?Be(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let ve;async function Et(){if(ve===void 0){const s=await Ot(Yt.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=K.createHash("sha256").update(s.content).digest("hex");ve={spec:s,hash:e}}return ve}function Gr(s,e,t){return Ve(s,e,!0,{pf:t},["result"]).result}function ye(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class st{constructor(e,t){p(this,"currentInputsC",ye(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));p(this,"actualProductionInputsC",ye(()=>{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())}));p(this,"productionStaleC",ye(()=>{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 productionStale(){return this.productionRendered&&this.productionStaleC()}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(l.Pl.unwrapHolder(e,this.fields.blockPack.ref),Bt,"Input")}}const Hr=s=>{throw new Error(`No new block info for ${s}`)};class ce{constructor(e,t,r,o,n,i,a,c,u,d,g,f){p(this,"globalModCount",0);p(this,"fieldsChanged",!1);p(this,"lastModifiedChanged",!1);p(this,"structureChanged",!1);p(this,"metaChanged",!1);p(this,"renderingStateChanged",!1);p(this,"changedBlockFrontendStates",new Set);p(this,"blocksWithChangedInputs",new Set);p(this,"stagingGraph");p(this,"pendingProductionGraph");p(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=d,this.blockFrontendStates=g,this.ctxExportTplHolder=f}fixProblems(){this.blockInfos.forEach(e=>{(e.fields.prodArgs===void 0||e.fields.prodOutput===void 0||e.fields.prodCtx===void 0)&&this.deleteBlockFields(e.id,"prodArgs","prodOutput","prodCtx")})}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=Oe(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=oe(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return h.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of V(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=l.field(this.rid,P(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(l.field(this.rid,P(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(l.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}setBlockLabel(e,t){const r=this.structure;let o=!1;for(const n of V(r))if(n.id===e){n.label=t,o=!0;break}if(!o)throw new Error(`block ${e} not found`);this.updateStructure(r),this.updateLastModified()}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(l.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Ar(this.tx,r)}exportCtx(e){return Gr(this.tx,l.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=Xe(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",l.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=Xe(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",l.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=Hr){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=Oe(e),i=oe(e,u=>{var d;return(d=this.blockInfos.get(u))==null?void 0:d.actualProductionInputs}),a=rt(r,n),c=rt(o,i);for(const u of a.onlyInA){const{fields:d}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(d)),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 d=new st(u,{});this.blockInfos.set(u,d);const g=t(u),f=tt(this.tx,g.blockPack);this.setBlockField(u,"blockPack",l.Pl.wrapInHolder(this.tx,f),"NotReady");const v=Buffer.from(g.args),w=this.tx.createValue(l.Pl.JsonObject,v);this.setBlockField(u,"currentArgs",w,"Ready",v),d.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,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",l.Pl.wrapInHolder(this.tx,tt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const a=o.nodes.get(i);if(a===void 0)throw new Error(`Can't find block with id: ${i}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of V(this.structure)){if(!r.has(i.id))continue;let a=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!a){for(const c of o.nodes.get(i.id).upstream)if(n.has(c)){a=!0;break}}a&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new dt(e),o=new Set(e),n=[];for(;!r.isEmpty();){const c=r.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 d of t.traverseIdsExcludingRoots("downstream",c))o.has(d)||(r.push(d),o.add(d))}}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,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,Ce(t)):this.tx.setKValue(this.rid,Ce(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,Pe):this.tx.setKValue(this.rid,Pe,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,X,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,q,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ae,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,ee,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,ke(e)):this.tx.setKValue(this.rid,ke(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,mt),i=e.getKValueJson(t,X),a=e.getKValueJson(t,ee),c=e.getKValueJson(t,q),u=e.getKValueJson(t,ae),d=e.listKeyValuesString(t),[g,f,v,w,C,{stagingRefreshTimestamp:I,blocksInLimbo:H},$]=await Promise.all([o,n,i,a,c,u,d]);if(f!==vt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${f}`);const _=new Map;for(const b of g.fields){const B=kr(b.name);if(B===void 0)continue;let R=_.get(B.blockId);R===void 0&&(R={id:B.blockId,fields:{}},_.set(B.blockId,R)),R.fields[B.fieldName]=l.isNullResourceId(b.value)?{modCount:0}:{modCount:0,ref:b.value}}const z=await Et(),te=Re(z.hash),k=g.fields.find(b=>b.name===te);let U;k!==void 0?U=l.ensureResourceIdNotNull(k.value):(U=l.Pl.wrapInHolder(e,pe(e,z.spec)),e.createField(l.field(t,Re(z.hash)),"Dynamic",U));const W={stagingRefreshTimestamp:I},j=new Set(H),T=new Map;for(const b of $){const B=br(b.key);B!==void 0&&T.set(B,b.value)}const O=[];_.forEach(({id:b,fields:B})=>{for(const[,R]of Object.entries(B))if(R.ref!==void 0){if(!l.isResource(R.ref)||l.isResourceRef(R.ref))throw new Error("unexpected behaviour");O.push([R,e.getResourceData(R.ref,!1)])}});for(const[b,B]of O){const R=await B;b.value=R.data,l.isNotNullResourceId(R.error)?b.status="Error":R.resourceReady||l.isNotNullResourceId(R.originalResourceId)?b.status="Ready":b.status="NotReady"}const G=new Map;_.forEach(({id:b,fields:B})=>G.set(b,new st(b,B)));const L=new Set;for(const b of V(C)){if(!G.has(b.id))throw new Error(`Inconsistent project structure: no inputs for ${b.id}`);L.add(b.id)}G.forEach(b=>{if(!L.has(b.id))throw new Error(`Inconsistent project structure: no structure entry for ${b.id}`);b.check()});const re=new ce(t,e,r,f,v,w,C,W,j,G,T,U);return re.fixProblems(),re}}async function _r(s,e=hr){const t=s.createEphemeral(fr);s.lock(t);const r=String(Date.now());s.setKValue(t,mt,JSON.stringify(vt)),s.setKValue(t,Ne,r),s.setKValue(t,X,r),s.setKValue(t,ee,JSON.stringify(e)),s.setKValue(t,q,JSON.stringify(pr)),s.setKValue(t,ae,JSON.stringify(gr));const o=await Et();return s.createField(l.field(t,Re(o.hash)),"Dynamic",l.Pl.wrapInHolder(s,pe(s,o.spec))),t}async function be(s,e,t){return N(s,e,void 0,t)}async function N(s,e,t,r){if(s instanceof l.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await ce.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await ce.load(s,e,t),n=await r(o);return o.save(),n}}function*qr(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:h.assertNever(s)}}function ot(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function zr(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:ot(s.parts,e)};case"BinaryPartitioned":return{...s,parts:ot(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:h.assertNever(s)}}const Wr=l.resourceType("PColumnData/JsonPartitioned","1"),Yr=l.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Qr=l.resourceType("PColumnData/BinaryPartitioned","1"),Zr=l.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),Xr=l.resourceType("PColumnData/Json","1");function es(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(l.resourceTypesEqual(s.resourceType,Xr)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(l.resourceTypesEqual(s.resourceType,Wr)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,Yr)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,Qr)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,Zr)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const 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 d=r[u];d===void 0&&(d={},r[u]=d),r[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 d=r[u];d===void 0&&(d={},r[u]=d),r[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:r}}throw new Error(`unsupported resource type: ${l.resourceTypeToString(s.resourceType)}`)}function xt(s,e){const t=K.createHash("sha256");return t.update(xe(s)),t.update(String(l.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function jt(s,e=!0,t=!1,r=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const d of s.listInputFields()){const g=d.match(o);if(!g){if(e)throw new Error(`unexpected field name ${d}`);continue}let f=h.notEmpty((a=g.groups)==null?void 0:a.name);if(!f.startsWith(r)){if(e)throw new Error(`unexpected field name ${d}`);continue}f=f.slice(r.length);const v=h.notEmpty((c=g.groups)==null?void 0:c.type);let w=n.get(f);switch(w===void 0&&(w={},n.set(f,w)),v){case"spec":w.spec=(u=s.traverse({field:d,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":w.hasData=!0,w.data=()=>s.traverseOrError({field:d,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,d]of n)d.data===void 0&&(d.hasData=!1);return{locked:i,results:n}}function ts(s,e=!0,t=""){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const r=jt(s,e,!1,t);Qt(r.locked);const o={};for(const[n,i]of r.results){if(i.spec===void 0)throw new Error(`no spec for key ${n}`);if(i.hasData!==!0||i.data===void 0)throw new Error(`no data for key ${n}`);const a=i.data();if(a===void 0)throw new Error(`no data for key ${n}`);if(!a.ok)throw new Ee.PlError(a.error);o[n]={id:xt(i.spec,a.value),spec:i.spec,data:a.value}}return o}class Me{constructor(e,t){p(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getBlockLabel(e){var t,r;return h.notEmpty((r=(t=this.blocks.get(e))==null?void 0:t.info)==null?void 0:r.label,`block "${e}" not found`)}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:se(i,a),obj:{id:u.ok?xt(c.spec,u.value):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,d]of a.prod.results)c.add(u),n(i,u,d)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,d]of a.staging.results)c.has(u)||n(i,u,d)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const 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:se(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:se(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),F.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:se(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=h.notEmpty(o.getKeyValueAsJson(q)),a=Oe(n).traverseIds("upstream",r),c=new Map;for(const u of V(n)){if(!a.has(u.id))continue;const d=nt(o.traverse({field:P(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:P(u.id,"prodUiCtx"),stableIfNotFound:!0})),g=nt(o.traverse({field:P(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:P(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:d,staging:g})}return new Me(e,c)}}function nt(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return jt(e.value,!1,!0)}function Ue(s,e){const t=s.persist(),r=h.notEmpty(s.traverse({field:P(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),o=s.getKeyValueAsString(ke(e));return{blockId:e,args:r,uiState:o,blockMeta:n=>{const i=n.accessor(t).node(),a=h.notEmpty(i.getKeyValueAsJson(q)),c=new Map;for(const u of V(a))c.set(u.id,u);return c}}}function At(s,e){const t=s.persist();return{...Ue(s,e),prod:r=>{var o;return(o=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:o.persist()},staging:r=>{var n;const o=(n=r.accessor(t).node({ignoreError:!0}).traverse({field:P(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return o===void 0&&r.markUnstable("staging_not_rendered"),o},getResultsPool:r=>Me.create(r,t,e)}}function*E(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*E(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*E(t);return;case"MakeArray":for(const t of s.template)yield*E(t);return;case"GetJsonField":case"GetResourceField":yield*E(s.source),yield*E(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*E(s.source),yield*E(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*E(s.source);return;case"IsEmpty":yield*E(s.arg);return;case"Not":yield*E(s.operand);return;case"And":case"Or":yield*E(s.operand1),yield*E(s.operand2);return;default:h.assertNever(s)}}function rs(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function ue(s,e){return s===void 0?void 0:e(s)}function ss(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function os(s){for(const e of E(s))if(ss(e))return!0;return!1}function ge(s){return{type:"ReturnResult",result:s}}function m(s){return()=>ge(s)}const ns=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return m(e)},is=s=>{const e=s.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},as=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var o;return ge((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function It(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function cs(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Nt(r.length),args:It(r,o=>y({...s,[e.itVar]:o},e.mapping))})}}function Nt(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return m(t)}}function us(s,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const o={};for(const[n,i]of Object.entries(r)){const a={...s,[e.itVar]:i};o[n]=y(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:ls,args:o})}}const ls=s=>m(s),ds=s=>{const e=s.arg;return m(e===void 0?void 0:e.length===0)},ps=s=>{const e=s.operand;return m(e===void 0?void 0:!e)},gs=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},hs=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e||t)},fs=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return ge((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},ms=s=>{const e=s.source,t=s.field;return m(e===void 0||t===void 0?void 0:e[t])};function vs(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=m(void 0);else{const u={...s,[e.itVar]:c.persist()};i[a]=y(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:ys,args:i}}}}const ys=s=>m(s),bs=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},ws=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Ss=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},ks=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Cs=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Ps=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Rs=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Fs=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},Os=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function y(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>ge(t(r.cCtx)):(t===void 0&&console.log("asdasd"),m(t));case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Mt(r,s,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:ms,args:{source:y(s,e.source),field:y(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:cs(s,e),args:{source:y(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:us(s,e),args:{source:y(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:ns,args:rs(e.template,r=>y(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Nt(e.template.length),args:It(e.template,r=>y(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:is,args:{source:y(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ds,args:{arg:y(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:ps,args:{operand:y(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:gs,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:hs,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:vs(s,e),args:{source:y(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:as,args:{source:y(s,e.source),field:y(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:fs,args:{source:y(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:bs,args:{source:y(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:ws,args:{source:y(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Ss,args:{source:y(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:ks,args:{source:y(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Cs,args:{source:y(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Ps,args:{source:y(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Rs(e.lines),args:{source:y(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Fs(e.patternToSearch),args:{source:y(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:Os,args:{source:y(s,e.source)}});default:return h.assertNever(e)}}const Bs=["$prod","$staging"];function Ds(s){return{$blockId:s.blockId,$args:JSON.parse(s.args),$ui:s.uiState!==void 0?JSON.parse(s.uiState):void 0,$prod:s.prod,$staging:s.staging}}const Vt=Symbol(),Lt="return",Ts={op:Vt,arg:Lt};function Es(s){return s.op==Vt&&s.arg==Lt}function xs(){return{pendingSubroutines:new Map}}function it(s,e,t,r){const o=new dt(t),n=(a,c)=>{if(Es(a))return e.result=c,!1;const u=h.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(s);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":const u=Symbol(),d=Object.entries(c.args),g=d.length;if(g===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[f,v]of d)o.push({destination:{op:u,arg:f},operation:v});e.pendingSubroutines.set(u,{argCounter:g,args:{},subroutine:c.subroutine,destination:a.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:h.assertNever(c)}}return i}function Jt(s,e,t,r={}){return Mt(s,Ds(e),t,r)}function Mt(s,e,t,r={}){const o=xe({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>Bs.indexOf(n)===-1)),cfg:t});return S.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},a=xs();return{ir:it(i,a,[{destination:Ts,operation:y(e,t)}],!0),async postprocessValue(u,d){const g=[];for(const C of u)g.push({destination:C.destination,operation:m(C.computable)});const f={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},v=new Map;for(const[C,I]of a.pendingSubroutines)v.set(C,{...I,args:{...I.args}});const w={result:a.result,pendingSubroutines:v};if(it(f,w,g,!1),!("result"in w))throw new Error("illegal cfg rendering stack state, no result");return w.result}}},{...r,key:o})}function js(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function at(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class le{constructor(e,t,r,o,n){p(this,"callbackRegistry");p(this,"fnJSONStringify");p(this,"fnJSONParse");p(this,"computablesToResolve",{});p(this,"computableCtx");p(this,"accessors",new Map);p(this,"meta");p(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw le.cleanErrorContext(t),t}}runCallback(e,...t){try{return ie.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw le.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return at(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return at(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const n=ts(o,t,r),i={};for(const[a,c]of Object.entries(n))i[a]=F.mapPObjectData(c,u=>this.wrapAccessor(u));return i}registerComputable(e,t){const r=`${e}_${K.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=h.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:F.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:F.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}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=>F.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(F.mapPTableDef(e,t=>F.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}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=K.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(js(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ie.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"args",e.manage(this.vm.newString(this.blockCtx.args))),this.blockCtx.uiState!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(this.blockCtx.uiState))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry);const r=(o,n)=>{this.vm.newFunction(o,n).consume(i=>this.vm.setProp(t,o,i))};r("getAccessorHandleByName",o=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(o)),void 0)),r("resolveWithCommon",(o,n,...i)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(o),this.importObjectViaJson(n),...i.map(a=>this.importObjectViaJson(a))),void 0)),r("getResourceType",o=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(o)),void 0)),r("getInputsLocked",o=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(o)),void 0)),r("getOutputsLocked",o=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(o)),void 0)),r("getIsReadyOrError",o=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(o)),void 0)),r("getIsFinal",o=>this.exportSingleValue(this.getIsFinal(this.vm.getString(o)),void 0)),r("getError",o=>this.exportSingleValue(this.getError(this.vm.getString(o)),void 0)),r("listInputFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("listOutputFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("listDynamicFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("getKeyValueBase64",(o,n)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getKeyValueAsString",(o,n)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getDataBase64",o=>this.exportSingleValue(this.getDataBase64(this.vm.getString(o)),void 0)),r("getDataAsString",o=>this.exportSingleValue(this.getDataAsString(this.vm.getString(o)),void 0)),r("parsePObjectCollection",(o,n,i)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(o),this.vm.dump(n),this.vm.getString(i)),void 0)),r("getBlobContentAsBase64",o=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(o)),void 0)),r("getBlobContentAsString",o=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(o)),void 0)),r("getDownloadedBlobContentHandle",o=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(o)),void 0)),r("getOnDemandBlobContentHandle",o=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(o)),void 0)),r("getImportProgress",o=>this.exportSingleValue(this.getImportProgress(this.vm.getString(o)),void 0)),r("getLastLogs",(o,n)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(o),this.vm.getNumber(n)),void 0)),r("getProgressLog",(o,n)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getLogHandle",o=>this.exportSingleValue(this.getLogHandle(this.vm.getString(o)),void 0)),r("getBlockLabel",o=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(o)),void 0)),r("getDataFromResultPool",o=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),r("getDataWithErrorsFromResultPool",o=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),r("getSpecsFromResultPool",o=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),r("calculateOptions",o=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(o)),void 0)),r("createPFrame",o=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(o)),void 0)),r("createPTable",o=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(o)),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function As(s,e,t,r,o={}){return S.Computable.makeRaw(n=>{const i=new ie.Scope;n.addOnDestroy(()=>i.dispose());const a=i.manage(s.quickJs.newRuntime());a.setMemoryLimit(1024*640),a.setMaxStackSize(1024*320);const c=i.manage(a.newContext()),u=new le(i,c,e,s,n);u.evaluateBundle(r.content);const d=u.runCallback(t);return u.resetComputableCtx(),{ir:u.computablesToResolve,postprocessValue:async g=>{for(const[f,v]of Object.entries(g))u.runCallback(f,v);return u.importObjectUniversal(d)}}},o)}function De(s,e,t,r,o={}){if(F.isFunctionHandle(t)){if(r===void 0)throw new Error("No code bundle.");return As(s,e,t,r,o)}else return Jt(s.driverKit,e,t,o)}function Is(s,e,t){return S.Computable.make(r=>{var w,C,I,H,$,_,z,te;const o=r.accessor(s).node(),n=h.notEmpty(o.getKeyValueAsJson(Ne)),i=h.notEmpty(o.getKeyValueAsJson(X)),a=h.notEmpty(o.getKeyValueAsJson(ee)),c=h.notEmpty(o.getKeyValueAsJson(q)),u=h.notEmpty(o.getKeyValueAsJson(ae)),d=new Map;for(const{id:k}of V(c)){const U=o.traverse({field:P(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let W;const j=o.traverse({field:P(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(j!==void 0){const T=o.getField({field:P(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),O=o.getField({field:P(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});W={arguments:j.getDataAsJson(),stale:U.id!==j.id,outputError:T.error!==void 0||O.error!==void 0||((w=T.value)==null?void 0:w.getError())!==void 0||((C=O.value)==null?void 0:C.getError())!==void 0,outputsError:((I=T.error)==null?void 0:I.getDataAsString())??(($=(H=T.value)==null?void 0:H.getError())==null?void 0:$.getDataAsString()),exportsError:((_=O.error)==null?void 0:_.getDataAsString())??((te=(z=O.value)==null?void 0:z.getError())==null?void 0:te.getDataAsString()),finished:(T.value!==void 0&&T.value.getIsReadyOrError()||T.error!==void 0&&T.error.getIsReadyOrError())&&(O.value!==void 0&&O.value.getIsReadyOrError()||O.error!==void 0&&O.error.getIsReadyOrError())}}d.set(k,{currentArguments:U.getDataAsJson(),prod:W})}const g=oe(c,k=>d.get(k).currentArguments),f=new Set(u.blocksInLimbo),v=[...V(c)].map(({id:k,label:U,renderingMode:W})=>{var He,_e,qe,ze;const j=h.notEmpty(d.get(k)),T=h.notEmpty(g.nodes.get(k));let O="NotCalculated";j.prod!==void 0&&(f.has(k)?O="Limbo":O=j.prod.finished?"Done":"Running");const G=o.traverse({field:P(k,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),L=G==null?void 0:G.getDataAsJson(),{sections:re,inputsValid:b,sdkVersion:B}=ue(L==null?void 0:L.config,fe=>{const Y=F.normalizeBlockConfig(fe),We=Ue(o,k);return{sections:De(t,We,Y.sections,Y.code),inputsValid:De(t,We,Y.inputsValid,Y.code),sdkVersion:Y.sdkVersion}})||{},R=ue(L,fe=>t.blockUpdateWatcher.get(fe.source));return{id:k,label:U,renderingMode:W,stale:((He=j.prod)==null?void 0:He.stale)!==!1||O==="Limbo",missingReference:T.missingReferences,upstreams:[...g.traverseIdsExcludingRoots("upstream",k)],downstreams:[...g.traverseIdsExcludingRoots("downstream",k)],calculationStatus:O,outputErrors:((_e=j.prod)==null?void 0:_e.outputError)===!0,outputsError:(qe=j.prod)==null?void 0:qe.outputsError,exportsError:(ze=j.prod)==null?void 0:ze.exportsError,sections:re,inputsValid:b,currentBlockPack:L==null?void 0:L.source,updatedBlockPack:R,sdkVersion:B,navigationState:e.getState(k)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(Pe),blocks:v}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(u=>n.has(u))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(u=>o.has(u))===-1;return{...i,canRun:c,stale:a}})}}}).withStableType()}function Ut(s,e){var t,r;return ue((r=(t=s.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}))==null?void 0:t.getDataAsJson())==null?void 0:r.config,o=>F.normalizeBlockConfig(o))}function Ns(s,e){const t=s.node();if(l.resourceTypesEqual(t.resourceType,Le)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(l.resourceTypesEqual(t.resourceType,Je)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Vs(s,e){if(s!==void 0)return S.Computable.make(t=>Ns(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function Ls(s,e,t){return S.Computable.make(r=>{var a;const o=r.accessor(s).node(),n=Ut(o,e),i=(a=o.traverse({field:P(e,"blockPack"),assertFieldType:"Dynamic"},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:Dt,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Vs(i,t),sdkVersion:n==null?void 0:n.sdkVersion}},{mode:"StableOnlyLive"})}function Js(s,e,t){return S.Computable.make(r=>{const o=r.accessor(s).node(),n=Ue(o,e);return{author:o.getKeyValueAsJson(Ce(e)),args:JSON.parse(n.args),ui:n.uiState!==void 0?JSON.parse(n.uiState):void 0}},{key:"inputs#"+l.resourceIdToString(s.rid)+e})}function Ms(s,e,t){return S.Computable.make(r=>{const o=r.accessor(s).node(),n=At(o,e),i=Ut(o,e);return ue(i,a=>{const c={};for(const[u,d]of Object.entries(a.outputs))c[u]=S.Computable.wrapError(De(t,n,d,a.code));return c})},{key:"outputs#"+l.resourceIdToString(s.rid)+e}).withStableType()}function Us(s,e){return S.Computable.make(t=>{const r=t.accessor(s).node(),o=h.notEmpty(r.getKeyValueAsJson(q)),n=[];for(const{id:i,renderingMode:a}of V(o)){const c=r.traverse({field:P(i,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),u=c==null?void 0:c.getDataAsJson();if((u==null?void 0:u.config)===void 0)continue;const d=F.normalizeBlockConfig(u.config),g=Object.entries(d.outputs).map(([,v])=>v).filter(v=>!F.isFunctionHandle(v)&&os(v)).map(v=>v);if(g.length===0)continue;const f=At(r,i);for(const v of g)n.push(S.Computable.wrapError(Jt(e.driverKit,f,v)))}return n})}class Ks{constructor(){p(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...F.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.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 he{constructor(e,t,r){p(this,"rid");p(this,"overview");p(this,"navigationStates",new Ks);p(this,"blockComputables",new Map);p(this,"blockFrontends",new Map);p(this,"activeConfigs");p(this,"refreshLoopResult");p(this,"abortController",new AbortController);p(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Is(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Us(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await be(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await pt.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(l.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!l.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=K.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfig(t);return await N(this.env.pl,this.rid,o,c=>c.addBlock({id:n,label:e,renderingMode:a.renderingMode},{args:JSON.stringify(a.initialArgs),blockPack:i},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfig(t);await N(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await N(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await N(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await be(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await be(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockLabel(e,t,r){await N(this.env.pl,this.rid,r,o=>{o.setBlockLabel(e,t)}),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await N(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await N(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await N(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=l.ensureResourceIdNotNull((await r.getField(l.field(this.rid,P(e,"blockPack")))).value),n=l.ensureResourceIdNotNull((await r.getField(l.field(o,l.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(h.notEmpty(i.data)).toString("utf-8"));await N(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=Ms(this.projectTree.entry(),e,this.env),n={fullState:S.Computable.make(i=>({argsAndUiState:Js(this.projectTree.entry(),e),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,navigationState:i.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=Ls(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){const r=await Ee.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:$s},e.logger);return new he(e,t,r)}}function $s(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}const Ke={logger:new h.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function $e(s){return{blobDownloadPath:x.join(s,"download")}}const Kt={...Ke,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function $t(s){return{...$e(s),frontendDownloadPath:x.join(s,"frontend")}}const Gs={minDelay:1500},Hs="__no_updates__";class _s extends S.PollComputablePool{constructor(t,r,o={}){super({...o,...Gs},r);p(this,"http");this.registryProvider=t,this.http=o.http}getKey(t){switch(t.type){case"dev-v1":return`dev_1_${t.folder}_${t.mtime}`;case"dev-v2":return`dev_2_${t.folder}_${t.mtime}`;case"from-registry-v2":return`from_registry_v2_${t.registryUrl}_${t.id.organization}_${t.id.name}_${t.id.version}`;default:return Hs}}async readValue(t){var r;try{switch(t.type){case"dev-v1":try{const o=await Ie(t.folder);return o===t.mtime?void 0:{...t,mtime:o}}catch(o){this.logger.warn(o);return}case"dev-v2":try{const o=await D.tryLoadPackDescription(t.folder,this.logger);if(o===void 0)return;const n=await de(o);return n===t.mtime?void 0:{...t,mtime:n}}catch(o){this.logger.warn(o);return}case"from-registry-v2":try{const o=this.registryProvider.getRegistry(t.registryUrl),n=(r=await o.getOverviewForSpec(t.id))==null?void 0:r.spec;if((n==null?void 0:n.type)!=="from-registry-v2")throw new Error("Unexpected");return Q.blockPackIdEquals(n.id,t.id)?void 0:((async()=>{try{await o.getComponents(n.id)}catch(i){this.logger.warn(i)}})(),n)}catch(o){this.logger.warn(o);return}default:return}}catch(o){this.logger.warn(o);return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0||t.type!==r.type)return!1;switch(t.type){case"from-registry-v1":return r.type!=="from-registry-v1"?!1:t.registryUrl===r.registryUrl&&Q.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&Q.blockPackIdEquals(t.id,r.id);case"dev-v1":return r.type!=="dev-v1"?!1:t.folder===r.folder&&t.mtime===r.mtime;case"dev-v2":return r.type!=="dev-v2"?!1:t.folder===r.folder&&t.mtime===r.mtime;default:h.assertNever(t)}}}class ct{constructor(){p(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function ut(s){return String(s.id)}class qs{constructor(e,t,r){p(this,"pFrame",new Zt.PFrame);p(this,"blobIdToResource",new Map);p(this,"blobHandleComputables",new Map);p(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});p(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});p(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)});this.blobDriver=e,this.blobContentCache=t,this.columns=r,this.pFrame.setDataSource(this);for(const o of r){for(const i of qr(o.data))this.blobIdToResource.set(ut(i),i);const n=zr(o.data,ut);try{this.pFrame.addColumnSpec(o.id,o.spec),this.pFrame.setColumnData(o.id,n)}catch(i){throw new Error(`Adding column ${o.id} to PFrame failed: ${i}; Spec: ${o.spec}, DataInfo: ${n}.`)}}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class zs{constructor(e){p(this,"pFrames");p(this,"pTables");p(this,"blobContentCache");p(this,"concurrencyLimiter");this.blobDriver=e;const t=new Xt.LRUCache({maxSize:1e9,fetchMethod:async o=>await gt.readFile(o),sizeCalculation:o=>o.length}),r=new h.ConcurrencyLimitingExecutor(1);this.blobContentCache=t,this.concurrencyLimiter=r,this.pFrames=new class extends ct{constructor(o){super(),this.blobDriver=o}createNewResource(o){return new qs(this.blobDriver,t,o)}calculateParamsKey(o){return Ys(o)}}(this.blobDriver),this.pTables=new class extends ct{constructor(o){super(),this.pFrames=o}async createNewResource(o){const n=this.pFrames.getByKey(o.pFrameHandle),i=await r.run(async()=>await n.pFrame.createTable({src:Z(o.def.src),filters:o.def.filters}));return o.def.sorting.length!==0?i.sort(o.def.sorting):i}calculateParamsKey(o){return Ws(o)}}(this.pFrames)}createPFrame(e,t){const r=e.map(n=>F.mapPObjectData(n,i=>es(i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(Qs(e.src),t),o=F.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:t.compatibleWith,qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.findColumns(r))).hits.map(o=>o.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.createTable({src:Z(t.src),filters:t.filters}));if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,a)=>({spec:i,data:n[a]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues(t))}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function Z(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>Z(e))};case"outer":return{type:"outer",primary:Z(s.primary),secondary:s.secondary.map(e=>Z(e))};default:h.assertNever(s)}}function Ws(s){const e=K.createHash("sha256");return e.update(s.pFrameHandle),e.update(xe(s.def)),e.digest().toString("hex")}function Ys(s){const e=s.map(o=>o.id).sort(),t=K.createHash("sha256");let r="";for(const o of e)r!==o&&(t.update(o),r=o);return t.digest().toString("hex")}function Qs(s){const e=new Map;return ne(s,e),[...e.values()]}function ne(s,e){switch(s.type){case"column":e.set(s.column.id,s.column);return;case"full":case"inner":for(const t of s.entries)ne(t,e);return;case"outer":ne(s.primary,e);for(const t of s.secondary)ne(t,e);return;default:h.assertNever(s)}}async function Gt(s,e,t){const r={...Ke,...$e(e),...t},o=new h.HmacSha256Signer(r.localSecret),n=J.createDownloadClient(r.logger,s,r.localProjections),i=J.createLogsClient(s,r.logger),a=J.createUploadBlobClient(s,r.logger),c=J.createUploadProgressClient(s,r.logger),u=new J.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),d=new J.UploadDriver(r.logger,o,a,c,r.uploadDriverOps),g=new J.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),f=new J.LogsDriver(r.logger,g,u),v=await J.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),w=new zs(u);return{blobDriver:u,logDriver:f,lsDriver:v,signer:o,uploadDriver:d,pFrameDriver:w}}class Ge{constructor(e,t,r,o,n,i,a,c){p(this,"pl");p(this,"projectList");p(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,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=K.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await _r(o,e);return o.createField(l.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await l.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await N(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(l.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(l.field(this.projectListResourceId,e))).value;if(l.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await he.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 h.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...Kt,...$t(t),...r};process.env.MI_LOG_TREE_STAT&&(o.defaultTreeOptions.logStat=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request");const n=await e.withWriteTx("MLInitialization",async C=>{const I=l.field(C.clientRoot,Cr);C.createField(I,"Dynamic");const H=await C.getField(I);if(l.isNullResourceId(H.value)){const $=C.createEphemeral(yt);return C.lock($),C.setField(I,$),await C.commit(),await $.globalId}else return H.value}),i=o.logger,a=await Gt(e,t,o),c=new M.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new ft(c),d=new Jr(u,a.signer,c),g=new J.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),f={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:d,frontendDownloadDriver:g,driverKit:a,blockUpdateWatcher:new _s(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c}),quickJs:await ie.getQuickJS()},v=new S.WatchableValue([]),w=await Rr(e,n,v,f);return new Ge(f,a,a.signer,n,v,w.tree,u,w.computable)}}async function Zs(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:5e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science/v2/overview.json",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",...e},r={plPings:[],blockRegistryChecks:[],autoUpdateCdnChecks:[]},o=l.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});r.plPings=await we(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const c=await new l.UnauthenticatedPlClient(o).ping();return JSON.stringify(c).slice(0,100)+"..."});const i=new l.UnauthenticatedPlClient(o).ll.httpDispatcher;return r.blockRegistryChecks=await we(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>{const{body:a,statusCode:c}=await M.request(t.blockRegistryUrl,{dispatcher:i,headersTimeout:t.httpTimeoutMs,bodyTimeout:t.httpTimeoutMs}),u=await a.text();return{statusCode:c,beginningOfBody:u.slice(0,100)+"..."}}),r.autoUpdateCdnChecks=await we(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>{const{body:a,statusCode:c}=await M.request(t.autoUpdateCdnUrl,{dispatcher:i,headersTimeout:t.httpTimeoutMs,bodyTimeout:t.httpTimeoutMs}),u=await a.text();return{statusCode:c,beginningOfBody:u.slice(0,100)+"..."}}),Xs(r,s,t)}async function we(s,e,t){const r=Te(),o=[];for(;lt(r)<s;){const n=Te();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=lt(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await pt.setTimeout(c)}return o}function Xs(s,e,t){const r=s.plPings.filter(i=>i.response.ok),o=s.plPings.filter(i=>!i.response.ok),n=[...new Set(r.map(i=>JSON.stringify(i.response.value)))];return`
|
|
1
|
+
"use strict";var qt=Object.defineProperty;var Wt=(s,e,t)=>e in s?qt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var g=(s,e,t)=>Wt(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@platforma-sdk/model"),Q=require("@milaboratories/pl-model-middle-layer"),J=require("undici"),D=require("@platforma-sdk/block-tools"),A=require("node:fs"),T=require("node:path"),zt=require("yaml"),f=require("@milaboratories/ts-helpers"),Yt=require("node:fs/promises"),Qt=require("@milaboratories/resolve-helper"),l=require("@milaboratories/pl-client"),je=require("@milaboratories/pl-tree"),S=require("@milaboratories/computable"),U=require("node:crypto"),gt=require("denque"),Zt=require("@platforma-sdk/workflow-tengo"),Ae=require("canonicalize"),Xt=require("node:assert"),ce=require("quickjs-emscripten"),ht=require("node:timers/promises"),V=require("@milaboratories/pl-drivers"),er=require("@milaboratories/pframes-node"),tr=require("lru-cache");function rr(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const ft=rr(Yt);async function Qe(s){try{return await ft.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}const or=[D.RegistryV1.PlPackageYamlConfigFile],sr=[D.RegistryV1.PlPackageJsonConfigFile],Ie=["backend","dist","tengo","tpl","main.plj.gz"],Ne=["config","dist","config.json"],mt=["frontend","dist"],Ze="block-model/dist/config.json",nr="block-ui/package.json",ir=[Ie,Ne,or,sr,mt];async function ar(s){return await Qe(T.join(s,...Ne))!==void 0||await Qe(T.join(s,...Ie))!==void 0}function ye(s,e){const t=Qt.tryResolve(s,e);if(t===void 0)throw new Error(`Can't resolve ${e} against ${s}`);return t}async function Xe(s,e){if(T.isAbsolute(s)||(s=T.resolve(s)),await ar(s))return{workflow:T.join(s,...Ie),config:T.join(s,...Ne),ui:T.join(s,...mt)};{const t=ye(s,Ze),r=ye(s,Ze),o=ye(s,nr);return{workflow:t,config:r,ui:T.resolve(o,"..","dist")}}}async function cr(s){try{return await A.promises.readFile(s,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}async function ur(s){try{return await A.promises.stat(s,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}}async function Ve(s){let e=0n;for(const t of ir){const r=T.join(s,...t),o=await ur(r);o!==void 0&&e<o.mtimeNs&&(e=o.mtimeNs)}return e.toString()}async function pe(s){const e=await A.promises.stat(s.components.workflow.main.file,{bigint:!0}),t=await A.promises.stat(s.components.model.file,{bigint:!0});return(e.mtimeNs>t.mtimeNs?e.mtimeNs:t.mtimeNs).toString()}class lr{constructor(e,t,r){this.v2Provider=e,this.registries=t,this.http=r}async getPackagesForRoot(e){const t=[],r=e.spec;switch(r.type){case"remote-v1":const o=this.http!==void 0?{dispatcher:this.http}:{},i=await(await J.request(`${r.url}/${D.RegistryV1.GlobalOverviewPath}`,o)).body.json();for(const a of i){const{organization:c,package:u,latestMeta:d,latestVersion:p}=a,h={organization:c,name:u,version:p};t.push({registryId:e.id,id:h,meta:{title:d.title??"No title",description:d.description??"No Description",organization:{name:c,url:"https://unknown.com"}},spec:{type:"from-registry-v1",id:h,registryUrl:r.url},otherVersions:a.allVersions})}return t;case"remote-v2":return(await this.v2Provider.getRegistry(r.url).listBlockPacks()).map(a=>({...a,registryId:e.id}));case"local-dev":for(const a of await A.promises.readdir(r.path,{withFileTypes:!0})){if(!a.isDirectory())continue;const c=T.join(r.path,a.name),u=await cr(T.join(c,D.RegistryV1.PlPackageYamlConfigFile));if(u!==void 0){const d=D.RegistryV1.PlPackageConfigData.parse(zt.parse(u)),p=await Ve(c),h={organization:d.organization,name:d.package,version:"DEV"};t.push({registryId:e.id,id:h,meta:{title:d.meta.title??"No title",description:d.meta.description??"No Description",organization:{name:d.organization,url:"https://unknown.com"}},spec:{type:"dev-v2",folder:c,mtime:p},otherVersions:[]})}else{let d=c,p=await D.tryLoadPackDescription(d);if(p===void 0){for(const h of["block","meta"])if(d=T.join(c,h),p=await D.tryLoadPackDescription(d),p!==void 0)break}if(p!==void 0){const h=await pe(p);t.push({registryId:e.id,id:p.id,meta:await D.BlockPackMetaEmbedAbsoluteBytes.parseAsync(p.meta),spec:{type:"dev-v2",folder:d,mtime:h},otherVersions:[]})}}}return t;default:return f.assertNever(r)}}async listBlockPacks(){const e=[],t=[];for(const r of this.registries)t.push({...r,status:"online"}),e.push(...await this.getPackagesForRoot(r));return{registries:t,blockPacks:e}}}class vt{constructor(e){g(this,"registries",new Map);this.http=e}getRegistry(e){const t=this.registries.get(e);if(t)return t;const r=new D.RegistryV2Reader(D.folderReaderByUrl(e,this.http));return this.registries.set(e,r),r}}const dr={type:"remote-v2",url:"https://blocks.pl-open.science/"},pr={type:"remote-v1",url:"https://block.registry.platforma.bio/releases"},gr={type:"remote-v1",url:"https://block.registry.platforma.bio/dev"},hr={groups:[{id:"default",label:"Default",blocks:[]}]},fr={stagingRefreshTimestamp:0,blocksInLimbo:[]},mr={label:"New Project"},vr={name:"UserProject",version:"2"},yt="SchemaVersion",bt="1",Le="ProjectCreated",te="ProjectLastModified",re="ProjectMeta",W="ProjectStructure",ue="BlockRenderingState",yr="BlockFrontendState/",br=/^BlockFrontendState\/(?<blockid>.*)$/;function Pe(s){return`${yr}${s}`}const wr="BlockArgsAuthor/";function Re(s){return`${wr}${s}`}const Fe="ProjectStructureAuthor";function Sr(s){const e=s.match(br);if(e!==null)return e.groups.blockid}const kr="__serviceTemplate_";function Oe(s){return`${kr}${s}`}function R(s,e){return`${s}-${e}`}const Cr=/^(?<blockId>.*)-(?<fieldName>blockPack|prodArgs|currentArgs|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious)$/;function Pr(s){const e=s.match(Cr);if(e===null)return;const{blockId:t,fieldName:r}=e.groups;return{blockId:t,fieldName:r}}const Rr="projects",wt={name:"Projects",version:"1"},Fr=s=>l.resourceTypesEqual(s.type,wt)?s.fields:[];async function Or(s,e,t,r){const o=await je.SynchronizedTreeState.init(s,e,{...r.ops.defaultTreeOptions,pruning:Fr},r.logger);return{computable:S.Computable.make(i=>{const a=i.accessor(o.entry()).node(),c=t.getValue(i);if(a===void 0)return;const u=[];for(const d of a.listDynamicFields()){const p=a.traverse(d);if(p===void 0)continue;const h=f.notEmpty(p.getKeyValueAsJson(re)),v=f.notEmpty(p.getKeyValueAsJson(Le)),w=f.notEmpty(p.getKeyValueAsJson(te));u.push({id:d,rid:p.id,created:new Date(v),lastModified:new Date(w),opened:c.indexOf(p.id)>=0,meta:h})}return u.sort(d=>-d.lastModified.valueOf()),u}).withStableType(),tree:o}}const Br={name:"EphRenderTemplate",version:"1"},Dr={name:"RenderTemplate",version:"1"};function Je(s,e,t,r,o){if(o.length===0)throw new Error("Zero output names provided");const n=t?s.createEphemeral(Br):s.createStruct(Dr),i=l.field(n,"template"),a=l.field(n,"inputs");return s.createField(i,"Input",e),s.createField(a,"Input",l.Pl.createPlMap(s,r,t)),s.lockInputs(n),l.Pl.futureRecord(s,n,o,"Output","outputs/")}const Tr={name:"BContextEnd",version:"1"},xr={name:"BContext",version:"1"},Er="id",jr="parent/",Ar=["context","result"];function et(s,e,t){return Je(s,e,!0,t,Ar)}function Ir(s){const e=s.createEphemeral(Tr);return s.lock(e),e}function Nr(s,e){if(e.length===0)return Ir(s);if(e.length===1)return e[0];const t=s.createEphemeral(xr);s.createField(l.field(t,Er),"Input",l.Pl.createPlString(s,U.randomUUID()));for(let r=0;r<e.length;r++)s.createField(l.field(t,`${jr}${r}`),"Input",e[r]);return s.lock(t),t}const St={name:"TengoTemplateGet",version:"1"},kt="registry",Ct="templateURI",Pt="template",Rt={name:"TengoTemplatePack",version:"1"},Ft={name:"TengoTemplatePackConvert",version:"1"},Ot="templatePack",Bt="template";async function Dt(s){switch(s.type){case"from-file":return{type:"explicit",content:await A.promises.readFile(s.path)};case"from-registry":case"explicit":return s;default:return f.assertNever(s)}}function Vr(s,e){const t=s.createStruct(St),r=l.field(t,kt),o=l.field(t,Ct),n=l.field(t,Pt);return s.setField(r,s.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.registry)))),s.setField(o,s.createValue(l.Pl.JsonString,Buffer.from(JSON.stringify(e.path)))),n}function Lr(s,e){const t=s.createValue(Rt,e.content),r=s.createStruct(Ft),o=l.field(r,Ot),n=l.field(r,Bt);return s.setField(o,t),n}function ge(s,e){switch(e.type){case"from-registry":return Vr(s,e);case"explicit":return Lr(s,e);default:return f.assertNever(e)}}const Me={name:"Frontend/FromUrl",version:"1"},Ue={name:"Frontend/FromFolder",version:"1"};function Jr(s,e){switch(e.type){case"url":return s.createValue(Me,JSON.stringify({url:e.url}));case"local":return s.createValue(Ue,JSON.stringify({path:e.path,signature:e.signature}));default:return f.assertNever(e)}}const Mr={name:"BlockPackCustom",version:"1"},Tt="template",xt="frontend";function tt(s){return s.endsWith("/")?s:`${s}/`}class Ur{constructor(e,t,r){this.v2RegistryProvider=e,this.signer=t,this.http=r}async getBlockConfigContainer(e){switch(e.type){case"explicit":return e.config;case"dev-v1":{const t=await Xe(e.folder),r=await A.promises.readFile(t.config,{encoding:"utf-8"});return JSON.parse(r)}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=await A.promises.readFile(t.components.model.file,{encoding:"utf-8"});return JSON.parse(r)}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${tt(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`;return await(await J.request(`${r}/config.json`,t)).body.json()}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id);return await(await J.request(o.model.url,t)).body.json()}default:return f.assertNever(e)}}async prepare(e){switch(e.type){case"explicit":return e;case"dev-v1":{const t=await Xe(e.folder),r=await A.promises.readFile(t.workflow),o=JSON.parse(await A.promises.readFile(t.config,"utf-8")),n=t.ui;return{type:"explicit",template:{type:"explicit",content:r},config:o,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:e}}case"dev-v2":{const t=await D.loadPackDescription(e.folder),r=JSON.parse(await A.promises.readFile(t.components.model.file,{encoding:"utf-8"})),o=await A.promises.readFile(t.components.workflow.main.file),n=t.components.ui.folder,i={...e};return e.mtime===void 0&&(i.mtime=await pe(t)),{type:"explicit",template:{type:"explicit",content:o},config:r,frontend:{type:"local",path:n,signature:this.signer.sign(n)},source:i}}case"from-registry-v1":{const t=this.http!==void 0?{dispatcher:this.http}:{},r=`${tt(e.registryUrl)}${D.RegistryV1.packageContentPrefix({organization:e.id.organization,package:e.id.name,version:e.id.version})}`,o=`${r}/template.plj.gz`,n=await J.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 J.request(`${r}/config.json`,t)).body.json();return{type:"explicit",template:{type:"explicit",content:i},config:c,frontend:{type:"url",url:`${r}/frontend.tgz`},source:e}}case"from-registry-v2":{const t=this.http!==void 0?{dispatcher:this.http}:{},o=await this.v2RegistryProvider.getRegistry(e.registryUrl).getComponents(e.id),n=async()=>await(await J.request(o.model.url,t)).body.json(),i=async()=>await(await J.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 f.assertNever(e)}}}function Kr(s,e){const t={config:e.config,source:e.source},r=s.createStruct(Mr,JSON.stringify(t));return s.createField(l.field(r,Tt),"Input",ge(s,e.template)),s.createField(l.field(r,xt),"Input",Jr(s,e.frontend)),s.lock(r),r}function rt(s,e){switch(e.type){case"explicit":return Kr(s,e);default:return f.assertNever(e.type)}}function ne(s,e){return{__isRef:!0,blockId:s,name:e}}function $r(s){return typeof s=="object"&&s!==null&&s.__isRef===!0&&"blockId"in s&&"name"in s}function Be(s,e,t){const r=typeof e;switch(r){case"function":case"bigint":case"number":case"string":case"boolean":case"symbol":case"undefined":return;case"object":if(e===null)return;if($r(e))t===void 0||t.has(e.blockId)?s.upstreams.add(e.blockId):s.missingReferences=!0;else if(Array.isArray(e))for(const o of e)Be(s,o,t);else for(const[,o]of Object.entries(e))Be(s,o,t);return;default:f.assertNever(r)}}function Gr(s,e){const t={upstreams:new Set,missingReferences:!1};return Be(t,s,e),t}function M(s){return{*[Symbol.iterator](){for(const e of s.groups)for(const t of e.blocks)yield t}}}class Et{constructor(e){g(this,"nodes");this.nodes=e}traverseIds(e,...t){const r=new Set;return this.traverse(e,t,o=>r.add(o.id)),r}traverseIdsExcludingRoots(e,...t){const r=this.traverseIds(e,...t);for(const o of t)r.delete(o);return r}traverse(e,t,r){let o=[...t];const n=new Set(o);for(;o.length>0;){let i=[];for(const a of o){const c=this.nodes.get(a);r(c),c[e].forEach(u=>{n.has(u)||(n.add(u),i.push(u))})}o=i}}}function De(s){const e=new Map;let t;for(const{id:r}of M(s)){const o={id:r,missingReferences:!1};e.set(r,o),t===void 0?o.upstream=new Set:(o.upstream=new Set([t.id]),t.downstream=new Set([o.id])),t=o}return t!==void 0&&(t.downstream=new Set),new Et(e)}function ie(s,e){const t=new Map,r=new Set;for(const{id:o}of M(s)){const n=e(o);if(n===void 0)continue;const i=Gr(n,r),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)),r.add(o)}return new Et(t)}function _r(s,e){if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;return!0}function Te(s,e){if(s.size>e.size)return Te(e,s);for(const t of s)if(e.has(t))return!0;return!1}function ot(s,e){const t=new Set,r=new Set,o=new Set;return s.nodes.forEach(n=>{const i=e.nodes.get(n.id);i===void 0?t.add(n.id):(!_r(n.upstream,i.upstream)||Te(n.upstream,o))&&o.add(n.id)}),e.nodes.forEach(n=>{s.nodes.has(n.id)?Te(n.upstream,o)&&o.add(n.id):r.add(n.id)}),{onlyInA:t,onlyInB:r,different:o}}let be;async function jt(){if(be===void 0){const s=await Dt(Zt.Templates["pframes.export-pframe"]);if(s.type!=="explicit")throw new Error("Unexpected prepared template type.");const e=U.createHash("sha256").update(s.content).digest("hex");be={spec:s,hash:e}}return be}function Hr(s,e,t){return Je(s,e,!0,{pf:t},["result"]).result}function we(s,e){let t=!1,r,o;return()=>{if(!t)return t=!0,r=s(),o=e(),o;const n=s();return r!==n&&(r=n,o=e()),e()}}class st{constructor(e,t){g(this,"currentInputsC",we(()=>this.fields.currentArgs.modCount,()=>JSON.parse(Buffer.from(this.fields.currentArgs.value).toString())));g(this,"actualProductionInputsC",we(()=>{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())}));g(this,"productionStaleC",we(()=>{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 productionStale(){return this.productionRendered&&this.productionStaleC()}get requireProductionRendering(){return!this.productionRendered||this.productionStaleC()}get actualProductionInputs(){return this.actualProductionInputsC()}getTemplate(e){return e.getFutureFieldValue(l.Pl.unwrapHolder(e,this.fields.blockPack.ref),Tt,"Input")}}const qr=s=>{throw new Error(`No new block info for ${s}`)};class le{constructor(e,t,r,o,n,i,a,c,u,d,p,h){g(this,"globalModCount",0);g(this,"fieldsChanged",!1);g(this,"lastModifiedChanged",!1);g(this,"structureChanged",!1);g(this,"metaChanged",!1);g(this,"renderingStateChanged",!1);g(this,"changedBlockFrontendStates",new Set);g(this,"blocksWithChangedInputs",new Set);g(this,"stagingGraph");g(this,"pendingProductionGraph");g(this,"actualProductionGraph");this.rid=e,this.tx=t,this.author=r,this.schema=o,this.lastModified=n,this.meta=i,this.struct=a,this.renderingState=c,this.blocksInLimbo=u,this.blockInfos=d,this.blockFrontendStates=p,this.ctxExportTplHolder=h}fixProblems(){this.blockInfos.forEach(e=>{(e.fields.prodArgs===void 0||e.fields.prodOutput===void 0||e.fields.prodCtx===void 0)&&this.deleteBlockFields(e.id,"prodArgs","prodOutput","prodCtx")})}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=De(this.struct)),this.stagingGraph}getPendingProductionGraph(){return this.pendingProductionGraph===void 0&&(this.pendingProductionGraph=ie(this.struct,e=>this.getBlockInfo(e).currentInputs)),this.pendingProductionGraph}getActualProductionGraph(){return this.actualProductionGraph===void 0&&(this.actualProductionGraph=ie(this.struct,e=>this.getBlockInfo(e).actualProductionInputs)),this.actualProductionGraph}getBlockInfo(e){return f.notEmpty(this.blockInfos.get(e))}getBlock(e){for(const t of M(this.struct))if(t.id===e)return t;throw new Error("block not found")}setBlockFieldObj(e,t,r){const o=l.field(this.rid,R(e,t));if(r.ref===void 0)throw new Error("Can't set value with empty ref");this.getBlockInfo(e).fields[t]===void 0?this.tx.createField(o,"Dynamic",r.ref):this.tx.setField(o,r.ref),this.getBlockInfo(e).fields[t]={modCount:this.globalModCount++,...r},this.fieldsChanged=!0}setBlockField(e,t,r,o,n){this.setBlockFieldObj(e,t,{ref:r,status:o,value:n})}deleteBlockFields(e,...t){let r=!1;const o=this.getBlockInfo(e);for(const n of t){const i=o.fields;n in i&&(this.tx.removeField(l.field(this.rid,R(e,n))),delete i[n],this.fieldsChanged=!0,r=!0)}return r}updateLastModified(){this.lastModified=Date.now(),this.lastModifiedChanged=!0}resetStagingRefreshTimestamp(){this.renderingState.stagingRefreshTimestamp=Date.now(),this.renderingStateChanged=!0}resetStaging(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.stagingOutput)==null?void 0:r.status)==="Ready"&&((o=t.stagingCtx)==null?void 0:o.status)==="Ready"&&((n=t.stagingUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"stagingOutputPrevious",t.stagingOutput),this.setBlockFieldObj(e,"stagingCtxPrevious",t.stagingCtx),this.setBlockFieldObj(e,"stagingUiCtxPrevious",t.stagingUiCtx)),this.deleteBlockFields(e,"stagingOutput","stagingCtx","stagingUiCtx")&&this.resetStagingRefreshTimestamp()}resetProduction(e){var r,o,n;const t=this.getBlockInfo(e).fields;((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"&&((n=t.prodUiCtx)==null?void 0:n.status)==="Ready"&&(this.setBlockFieldObj(e,"prodOutputPrevious",t.prodOutput),this.setBlockFieldObj(e,"prodCtxPrevious",t.prodCtx),this.setBlockFieldObj(e,"prodUiCtxPrevious",t.prodUiCtx)),this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}resetOrLimboProduction(e){var r,o;const t=this.getBlockInfo(e).fields;return((r=t.prodOutput)==null?void 0:r.status)==="Ready"&&((o=t.prodCtx)==null?void 0:o.status)==="Ready"?this.blocksInLimbo.has(e)?!1:(this.blocksInLimbo.add(e),this.renderingStateChanged=!0,this.deleteBlockFields(e,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),!0):this.deleteBlockFields(e,"prodOutput","prodCtx","prodUiCtx","prodArgs")}setArgs(e){const t=[];for(const{blockId:r,args:o}of e){const n=this.getBlockInfo(r);JSON.parse(o);const i=Buffer.from(o);if(Buffer.compare(n.fields.currentArgs.value,i)===0)continue;const a=this.tx.createValue(l.Pl.JsonObject,i);this.setBlockField(r,"currentArgs",a,"Ready",i),this.blocksWithChangedInputs.add(r),t.push(r)}this.getStagingGraph().traverse("downstream",t,({id:r})=>this.resetStaging(r)),t.length>0&&this.updateLastModified()}setUiState(e,t){if(this.blockInfos.get(e)===void 0)throw new Error("no such block");this.blockFrontendStates.get(e)!==t&&(t===void 0?this.blockFrontendStates.delete(e):this.blockFrontendStates.set(e,t),this.changedBlockFrontendStates.add(e),this.blocksWithChangedInputs.add(e),this.updateLastModified())}createCtx(e,t){const r=[];return e.forEach(o=>{const n=this.getBlockInfo(o);if(n.fields[t]===void 0||n.fields[t].ref===void 0)throw new Error("One of the upstreams staging is not rendered.");r.push(l.Pl.unwrapHolder(this.tx,n.fields[t].ref))}),Nr(this.tx,r)}exportCtx(e){return Hr(this.tx,l.Pl.unwrapHolder(this.tx,this.ctxExportTplHolder),e)}renderStagingFor(e){this.resetStaging(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getStagingGraph().nodes.get(e).upstream,"stagingCtx");if(this.getBlock(e).renderingMode!=="Heavy")throw new Error("not supported yet");const o=t.getTemplate(this.tx),n=et(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!1)),context:r});this.setBlockField(e,"stagingCtx",l.Pl.wrapInEphHolder(this.tx,n.context),"NotReady"),this.setBlockField(e,"stagingUiCtx",this.exportCtx(n.context),"NotReady"),this.setBlockField(e,"stagingOutput",n.result,"NotReady")}renderProductionFor(e){this.resetProduction(e);const t=this.getBlockInfo(e),r=this.createCtx(this.getPendingProductionGraph().nodes.get(e).upstream,"prodCtx");if(this.getBlock(e).renderingMode==="Light")throw new Error("Can't render production for light block.");const o=t.getTemplate(this.tx),n=et(this.tx,o,{args:t.fields.currentArgs.ref,blockId:this.tx.createValue(l.Pl.JsonString,JSON.stringify(e)),isProduction:this.tx.createValue(l.Pl.JsonBool,JSON.stringify(!0)),context:r});this.setBlockField(e,"prodCtx",l.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=qr){const r=this.getStagingGraph(),o=this.getActualProductionGraph(),n=De(e),i=ie(e,u=>{var d;return(d=this.blockInfos.get(u))==null?void 0:d.actualProductionInputs}),a=ot(r,n),c=ot(o,i);for(const u of a.onlyInA){const{fields:d}=this.getBlockInfo(u);this.deleteBlockFields(u,...Object.keys(d)),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 d=new st(u,{});this.blockInfos.set(u,d);const p=t(u),h=rt(this.tx,p.blockPack);this.setBlockField(u,"blockPack",l.Pl.wrapInHolder(this.tx,h),"NotReady");const v=Buffer.from(p.args),w=this.tx.createValue(l.Pl.JsonObject,v);this.setBlockField(u,"currentArgs",w,"Ready",v),p.uiState&&(this.blockFrontendStates.set(u,p.uiState),this.changedBlockFrontendStates.add(u)),d.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,r){const o=this.structure;if(r===void 0)o.groups[o.groups.length-1].blocks.push(e);else{let n=!1;for(const i of o.groups){const a=i.blocks.findIndex(c=>c.id===r);if(!(a<0)){i.blocks.splice(a,0,e),n=!0;break}}if(!n)throw new Error(`Can't find element with id: ${r}`)}this.updateStructure(o,n=>{if(n!==e.id)throw new Error("Unexpected");return t})}deleteBlock(e){const t=this.structure;let r=!1;for(const o of t.groups){const n=o.blocks.findIndex(i=>i.id===e);if(!(n<0)){o.blocks.splice(n,1),r=!0;break}}if(!r)throw new Error(`Can't find element with id: ${e}`);this.updateStructure(t)}migrateBlockPack(e,t,r){const o=this.getBlockInfo(e);this.setBlockField(e,"blockPack",l.Pl.wrapInHolder(this.tx,rt(this.tx,t)),"NotReady"),r!==void 0?(this.setArgs([{blockId:e,args:r}]),this.setUiState(e,void 0)):this.getStagingGraph().traverse("downstream",[e],({id:n})=>this.resetStaging(n)),o.productionRendered&&this.getActualProductionGraph().traverse("downstream",[e],({id:n})=>this.resetOrLimboProduction(n)),this.updateLastModified()}renderProduction(e,t=!1){const r=new Set(e),o=this.getPendingProductionGraph();if(t)o.traverse("upstream",e,i=>{r.add(i.id)});else for(const i of r){const a=o.nodes.get(i);if(a===void 0)throw new Error(`Can't find block with id: ${i}`);for(const c of a.upstream)if(!r.has(c))throw new Error("Can't render blocks not including all upstreams.")}const n=new Set;for(const i of M(this.structure)){if(!r.has(i.id))continue;let a=this.getBlockInfo(i.id).requireProductionRendering||this.blocksInLimbo.has(i.id);if(!a){for(const c of o.nodes.get(i.id).upstream)if(n.has(c)){a=!0;break}}a&&(this.renderProductionFor(i.id),n.add(i.id))}return o.traverse("downstream",[...n],i=>{n.has(i.id)||this.resetOrLimboProduction(i.id)}),n.size>0&&this.updateLastModified(),n}stopProduction(...e){var i,a;const t=this.getActualProductionGraph(),r=new gt(e),o=new Set(e),n=[];for(;!r.isEmpty();){const c=r.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 d of t.traverseIdsExcludingRoots("downstream",c))o.has(d)||(r.push(d),o.add(d))}}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,r=e===void 0?void 0:1+Math.max(0,t*e/1e3);let o=0;this.traverseWithStagingLag((n,i)=>{i!==0&&(r===void 0||i<=r)&&(this.renderStagingFor(n),o++)}),o>0&&this.resetStagingRefreshTimestamp()}setMeta(e){this.meta=e,this.metaChanged=!0,this.updateLastModified()}doRefresh(e){this.refreshStagings(e),this.blockInfos.forEach(t=>{var r,o,n,i;((r=t.fields.prodCtx)==null?void 0:r.status)==="Ready"&&((o=t.fields.prodOutput)==null?void 0:o.status)==="Ready"&&this.deleteBlockFields(t.id,"prodOutputPrevious","prodCtxPrevious","prodUiCtxPrevious"),((n=t.fields.stagingCtx)==null?void 0:n.status)==="Ready"&&((i=t.fields.stagingOutput)==null?void 0:i.status)==="Ready"&&this.deleteBlockFields(t.id,"stagingOutputPrevious","stagingCtxPrevious","stagingUiCtxPrevious")})}assignAuthorMarkers(){const e=this.author?JSON.stringify(this.author):void 0;for(const t of this.blocksWithChangedInputs)e===void 0?this.tx.deleteKValue(this.rid,Re(t)):this.tx.setKValue(this.rid,Re(t),e);(this.metaChanged||this.structureChanged)&&(e===void 0?this.tx.deleteKValue(this.rid,Fe):this.tx.setKValue(this.rid,Fe,e))}save(){if(this.wasModified){this.lastModifiedChanged&&this.tx.setKValue(this.rid,te,JSON.stringify(this.lastModified)),this.structureChanged&&this.tx.setKValue(this.rid,W,JSON.stringify(this.struct)),this.renderingStateChanged&&this.tx.setKValue(this.rid,ue,JSON.stringify({...this.renderingState,blocksInLimbo:[...this.blocksInLimbo]})),this.metaChanged&&this.tx.setKValue(this.rid,re,JSON.stringify(this.meta));for(const e of this.changedBlockFrontendStates){const t=this.blockFrontendStates.get(e);t===void 0?this.tx.deleteKValue(this.rid,Pe(e)):this.tx.setKValue(this.rid,Pe(e),t)}this.assignAuthorMarkers()}}static async load(e,t,r){const o=e.getResourceData(t,!0),n=e.getKValueJson(t,yt),i=e.getKValueJson(t,te),a=e.getKValueJson(t,re),c=e.getKValueJson(t,W),u=e.getKValueJson(t,ue),d=e.listKeyValuesString(t),[p,h,v,w,P,{stagingRefreshTimestamp:K,blocksInLimbo:_},$]=await Promise.all([o,n,i,a,c,u,d]);if(h!==bt)throw new Error(`Can't act on this project resource because it has a wrong schema version: ${h}`);const H=new Map;for(const b of p.fields){const B=Pr(b.name);if(B===void 0)continue;let F=H.get(B.blockId);F===void 0&&(F={id:B.blockId,fields:{}},H.set(B.blockId,F)),F.fields[B.fieldName]=l.isNullResourceId(b.value)?{modCount:0}:{modCount:0,ref:b.value}}const z=await jt(),oe=Oe(z.hash),k=p.fields.find(b=>b.name===oe);let I;k!==void 0?I=l.ensureResourceIdNotNull(k.value):(I=l.Pl.wrapInHolder(e,ge(e,z.spec)),e.createField(l.field(t,Oe(z.hash)),"Dynamic",I));const Y={stagingRefreshTimestamp:K},j=new Set(_),x=new Map;for(const b of $){const B=Sr(b.key);B!==void 0&&x.set(B,b.value)}const O=[];H.forEach(({id:b,fields:B})=>{for(const[,F]of Object.entries(B))if(F.ref!==void 0){if(!l.isResource(F.ref)||l.isResourceRef(F.ref))throw new Error("unexpected behaviour");O.push([F,e.getResourceData(F.ref,!1)])}});for(const[b,B]of O){const F=await B;b.value=F.data,l.isNotNullResourceId(F.error)?b.status="Error":F.resourceReady||l.isNotNullResourceId(F.originalResourceId)?b.status="Ready":b.status="NotReady"}const G=new Map;H.forEach(({id:b,fields:B})=>G.set(b,new st(b,B)));const N=new Set;for(const b of M(P)){if(!G.has(b.id))throw new Error(`Inconsistent project structure: no inputs for ${b.id}`);N.add(b.id)}G.forEach(b=>{if(!N.has(b.id))throw new Error(`Inconsistent project structure: no structure entry for ${b.id}`);b.check()});const se=new le(t,e,r,h,v,w,P,Y,j,G,x,I);return se.fixProblems(),se}}async function Wr(s,e=mr){const t=s.createEphemeral(vr);s.lock(t);const r=String(Date.now());s.setKValue(t,yt,JSON.stringify(bt)),s.setKValue(t,Le,r),s.setKValue(t,te,r),s.setKValue(t,re,JSON.stringify(e)),s.setKValue(t,W,JSON.stringify(hr)),s.setKValue(t,ue,JSON.stringify(fr));const o=await jt();return s.createField(l.field(t,Oe(o.hash)),"Dynamic",l.Pl.wrapInHolder(s,ge(s,o.spec))),t}async function Se(s,e,t){return L(s,e,void 0,t)}async function L(s,e,t,r){if(s instanceof l.PlClient)return await s.withWriteTx("ProjectAction",async o=>{const n=await le.load(o,e,t),i=await r(n);return n.wasModified&&(n.save(),await o.commit()),i});{const o=await le.load(s,e,t),n=await r(o);return o.save(),n}}function*zr(s){switch(s.type){case"Json":return;case"JsonPartitioned":for(const[,e]of Object.entries(s.parts))yield e;return;case"BinaryPartitioned":for(const[,{index:e,values:t}]of Object.entries(s.parts))yield e,yield t;return;default:f.assertNever(s)}}function nt(s,e){return Object.fromEntries(Object.entries(s).map(([t,r])=>[t,e(r,t)]))}function Yr(s,e){switch(s.type){case"Json":return{...s};case"JsonPartitioned":return{...s,parts:nt(s.parts,e)};case"BinaryPartitioned":return{...s,parts:nt(s.parts,t=>({index:e(t.index),values:e(t.values)}))};default:f.assertNever(s)}}const Qr=l.resourceType("PColumnData/JsonPartitioned","1"),Zr=l.resourceType("PColumnData/Partitioned/JsonPartitioned","1"),Xr=l.resourceType("PColumnData/BinaryPartitioned","1"),eo=l.resourceType("PColumnData/Partitioned/BinaryPartitioned","1"),to=l.resourceType("PColumnData/Json","1");function ro(s){if(!s.getIsReadyOrError())throw new Error("Data not ready.");const e=s.getDataAsJson();if(e===void 0)throw new Error("unexpected data info structure, no resource data");if(l.resourceTypesEqual(s.resourceType,to)){const t=e;return{type:"Json",keyLength:t.keyLength,data:t.data}}else if(l.resourceTypesEqual(s.resourceType,Qr)){const t=e,r=Object.fromEntries(s.listInputFields().map(o=>[o,s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo]));return{type:"JsonPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,Zr)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const a of i){const c=JSON.stringify([...JSON.parse(o),...JSON.parse(a)]);r[c]=n.traverse({field:a,errorIfFieldNotSet:!0}).resourceInfo}}return{type:"JsonPartitioned",partitionKeyLength:t.superPartitionKeyLength+t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,Xr)){const t=e,r={};for(const o of s.listInputFields())if(o.endsWith(".index")){const n=o.slice(0,o.length-6);let i=r[n];i===void 0&&(i={},r[n]=i),i.index=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else if(o.endsWith(".values")){const n=o.slice(0,o.length-7);let i=r[n];i===void 0&&(i={},r[n]=i),i.values=s.traverse({field:o,errorIfFieldNotSet:!0}).resourceInfo}else throw new Error(`unrecognized part field name: ${o}`);for(const[o,n]of Object.entries(r)){if(n.index===void 0)throw new Error(`no index for part ${o}`);if(n.values===void 0)throw new Error(`no values for part ${o}`)}return{type:"BinaryPartitioned",partitionKeyLength:t.partitionKeyLength,parts:r}}else if(l.resourceTypesEqual(s.resourceType,eo)){const t=e,r={};for(const o of s.listInputFields()){const n=s.traverse({field:o,errorIfFieldNotSet:!0}),i=n.listInputFields();if(i===void 0)throw new Error(`no partition keys for super key ${o}`);for(const 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 d=r[u];d===void 0&&(d={},r[u]=d),r[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 d=r[u];d===void 0&&(d={},r[u]=d),r[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:r}}throw new Error(`unsupported resource type: ${l.resourceTypeToString(s.resourceType)}`)}function xe(s,e){const t=U.createHash("sha256");return t.update(Ae(s)),t.update(String(l.isNullResourceId(e.originalId)?e.id:e.originalId)),t.digest().toString("hex")}function At(s,e=!0,t=!1,r=""){var a,c,u;const o=/^(?<name>.*)\.(?<type>spec|data)$/,n=new Map;for(const d of s.listInputFields()){const p=d.match(o);if(!p){if(e)throw new Error(`unexpected field name ${d}`);continue}let h=f.notEmpty((a=p.groups)==null?void 0:a.name);if(!h.startsWith(r)){if(e)throw new Error(`unexpected field name ${d}`);continue}h=h.slice(r.length);const v=f.notEmpty((c=p.groups)==null?void 0:c.type);let w=n.get(h);switch(w===void 0&&(w={},n.set(h,w)),v){case"spec":w.spec=(u=s.traverse({field:d,ignoreError:t,pureFieldErrorToUndefined:t}))==null?void 0:u.getDataAsJson();break;case"data":w.hasData=!0,w.data=()=>s.traverseOrError({field:d,ignoreError:t});default:continue}}const i=s.getInputsLocked();if(i)for(const[,d]of n)d.data===void 0&&(d.hasData=!1);return{locked:i,results:n}}function oo(s,e=!0,t=""){if(!s.getIsReadyOrError())throw new Error("resource is not ready");const r=At(s,e,!1,t);Xt(r.locked);const o={};for(const[n,i]of r.results){if(i.spec===void 0)throw new Error(`no spec for key ${n}`);if(i.hasData!==!0||i.data===void 0)throw new Error(`no data for key ${n}`);const a=i.data();if(a===void 0)throw new Error(`no data for key ${n}`);if(!a.ok)throw new je.PlError(a.error);o[n]={id:xe(i.spec,a.value),spec:i.spec,data:a.value}}return o}class Ke{constructor(e,t){g(this,"allSpecsAvailable");this.ctx=e,this.blocks=t;let r=!0;e:for(const o of t.values())for(const n of[o.prod,o.staging])if(n!==void 0){if(!n.locked){r=!1;break e}for(const i of n.results.values())if(i.spec===void 0){r=!1;break e}}this.allSpecsAvailable=r}getSpecByRef(e,t){var n,i,a,c,u,d;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(i=(n=r.prod)==null?void 0:n.results)==null?void 0:i.get(t))==null?void 0:a.spec;if(o!==void 0||(o=(d=(u=(c=r.staging)==null?void 0:c.results)==null?void 0:u.get(t))==null?void 0:d.spec,o!==void 0))return o;r.staging===void 0?this.ctx.markUnstable(`staging_not_rendered:${e}`):r.staging.locked?r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`):this.ctx.markUnstable(`staging_not_locked:${e}`)}getDataOrErrorByRef(e,t){var i,a,c;const r=this.blocks.get(e);if(r===void 0)return;let o=(a=(i=r.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 C.mapValueInVOE(n,u=>({id:xe(o.spec,u),spec:o.spec,data:u}));o!==void 0&&this.ctx.markUnstable(`no_data:${e}:${t}`),r.prod!==void 0&&!r.prod.locked&&this.ctx.markUnstable(`prod_not_locked:${e}`)}getDataByRef(e,t){const r=this.getDataOrErrorByRef(e,t);if(!(r===void 0||!r.ok))return r.value}getData(){const e=this.getDataWithErrors(),t=[];for(const r of e.entries)r.obj.id!==void 0&&r.obj.data.ok&&t.push({ref:r.ref,obj:{id:r.obj.id,spec:r.obj.spec,data:r.obj.data.value}});return{entries:t,isComplete:e.isComplete,instabilityMarker:e.instabilityMarker}}getDataWithErrors(){const e=[];let t=!0,r;const o=i=>{r===void 0&&(r=i),t=!1},n=(i,a,c)=>{if(c.spec!==void 0&&c.hasData===!0&&c.data!==void 0){const u=c.data();u!==void 0?e.push({ref:ne(i,a),obj:{id:u.ok?xe(c.spec,u.value):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,d]of a.prod.results)c.add(u),n(i,u,d)}if(a.staging!==void 0){a.staging.locked||o(`staging_not_locked:${i}`);for(const[u,d]of a.staging.results)c.has(u)||n(i,u,d)}}return{entries:e,isComplete:t,instabilityMarker:r}}getSpecs(){const e=[];let t=!0,r;const o=n=>{r===void 0&&(r=n),t=!1};for(const[n,i]of this.blocks){const 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:ne(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:ne(n,c),obj:u.spec})}}return{entries:e,isComplete:t,instabilityMarker:r}}calculateOptions(e){const t=[];for(const r of this.blocks.values()){const o=new Set,n=i=>{for(const[a,c]of i.results)o.has(a)||c.spec===void 0||(o.add(a),C.executePSpecPredicate(e,c.spec)&&t.push({label:r.info.label+" / "+a,ref:ne(r.info.id,a),spec:c.spec}))};r.staging!==void 0&&n(r.staging),r.prod!==void 0&&n(r.prod)}return t}static create(e,t,r){const o=e.accessor(t).node(),n=f.notEmpty(o.getKeyValueAsJson(W)),a=De(n).traverseIds("upstream",r),c=new Map;for(const u of M(n)){if(!a.has(u.id))continue;const d=it(o.traverse({field:R(u.id,"prodCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0,stableIfNotFound:!0})!==void 0,o.traverseOrError({field:R(u.id,"prodUiCtx"),stableIfNotFound:!0})),p=it(o.traverse({field:R(u.id,"stagingCtx"),ignoreError:!0,pureFieldErrorToUndefined:!0})!==void 0,o.traverseOrError({field:R(u.id,"stagingUiCtx")}));c.set(u.id,{info:u,prod:d,staging:p})}return new Ke(e,c)}}function it(s,e){if(e===void 0)return s?{locked:!1,results:new Map}:void 0;if(e.ok)return At(e.value,!1,!0)}function $e(s,e){const t=s.persist(),r=f.notEmpty(s.traverse({field:R(e,"currentArgs"),errorIfFieldNotSet:!0}).getDataAsString()),o=s.getKeyValueAsString(Pe(e));return{blockId:e,args:r,uiState:o,blockMeta:n=>{const i=n.accessor(t).node(),a=f.notEmpty(i.getKeyValueAsJson(W)),c=new Map;for(const u of M(a))c.set(u.id,u);return c}}}function It(s,e){const t=s.persist();return{...$e(s,e),prod:r=>{var o;return(o=r.accessor(t).node({ignoreError:!0}).traverse({field:R(e,"prodOutput"),stableIfNotFound:!0,ignoreError:!0}))==null?void 0:o.persist()},staging:r=>{var n;const o=(n=r.accessor(t).node({ignoreError:!0}).traverse({field:R(e,"stagingOutput"),ignoreError:!0}))==null?void 0:n.persist();return o===void 0&&r.markUnstable("staging_not_rendered"),o},getResultsPool:r=>Ke.create(r,t,e)}}function*E(s,e){switch(yield s,s.type){case"GetFromCtx":case"Immediate":return;case"Isolate":yield*E(s.cfg);return;case"MakeObject":for(const[,t]of Object.entries(s.template))yield*E(t);return;case"MakeArray":for(const t of s.template)yield*E(t);return;case"GetJsonField":case"GetResourceField":yield*E(s.source),yield*E(s.field);return;case"MapRecordValues":case"MapArrayValues":case"MapResourceFields":yield*E(s.source),yield*E(s.mapping);return;case"Flatten":case"GetResourceValueAsJson":case"GetBlobContent":case"GetBlobContentAsString":case"GetBlobContentAsJson":case"GetDownloadedBlobContent":case"GetOnDemandBlobContent":case"GetImportProgress":case"GetLastLogs":case"GetProgressLog":case"GetLogHandle":yield*E(s.source);return;case"IsEmpty":yield*E(s.arg);return;case"Not":yield*E(s.operand);return;case"And":case"Or":yield*E(s.operand1),yield*E(s.operand2);return;default:f.assertNever(s)}}function so(s,e){const t={};for(const[r,o]of Object.entries(s))t[r]=e(o);return t}function Z(s,e){return s===void 0?void 0:e(s)}function no(s){switch(s.type){case"GetImportProgress":return!0;default:return!1}}function io(s){for(const e of E(s))if(no(e))return!0;return!1}function he(s){return{type:"ReturnResult",result:s}}function m(s){return()=>he(s)}const ao=s=>{const e={};for(const[t,r]of Object.entries(s))e[t]=r;return m(e)},co=s=>{const e=s.source;if(e===void 0)return m(void 0);const t=[];for(const r of e)r instanceof Array?t.push(...r):t.push(r);return m(t)},uo=s=>{const e=s.source,t=s.field;return e===void 0||t===void 0?m(void 0):({cCtx:r})=>{var o;return he((o=r.accessor(e).node().traverse(t))==null?void 0:o.persist())}};function Nt(s,e){const t={},r=s.length;for(let o=0;o<r;o++)t[String(o)]=e(s[o]);return t}function lo(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):()=>({type:"ScheduleSubroutine",subroutine:Vt(r.length),args:Nt(r,o=>y({...s,[e.itVar]:o},e.mapping))})}}function Vt(s){return e=>{const t=[];for(let r=0;r<s;r++)t.push(e[String(r)]);return m(t)}}function po(s,e){return t=>{const r=t.source;if(r===void 0)return m(void 0);const o={};for(const[n,i]of Object.entries(r)){const a={...s,[e.itVar]:i};o[n]=y(a,e.mapping)}return()=>({type:"ScheduleSubroutine",subroutine:go,args:o})}}const go=s=>m(s),ho=s=>{const e=s.arg;return m(e===void 0?void 0:e.length===0)},fo=s=>{const e=s.operand;return m(e===void 0?void 0:!e)},mo=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e&&t)},vo=s=>{const e=s.operand1,t=s.operand2;return m(e===void 0||t===void 0?void 0:e||t)},yo=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t})=>{var r;return he((r=t.accessor(e).node())==null?void 0:r.getDataAsJson())}},bo=s=>{const e=s.source,t=s.field;return m(e===void 0||t===void 0?void 0:e[t])};function wo(s,e){return t=>{const r=t.source;return r===void 0?m(void 0):({cCtx:o})=>{const n=o.accessor(r).node(),i={};for(const a of n.listInputFields()){const c=n.traverse(a);if(c===void 0)i[a]=m(void 0);else{const u={...s,[e.itVar]:c.persist()};i[a]=y(u,e.mapping)}}return{type:"ScheduleSubroutine",subroutine:So,args:i}}}}const So=s=>m(s),ko=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r!==void 0)return await t.blobDriver.getContent(r.handle)}})})},Co=s=>{const e=s.source;return e===void 0?m(void 0):({cCtx:t,drivers:r})=>{const o=t.accessor(e).node().resourceInfo;return{type:"ScheduleComputable",computable:S.Computable.make(()=>r.blobDriver.getDownloadedBlob(o),{postprocessValue:async n=>n===void 0?void 0:(await r.blobDriver.getContent(n.handle)).toString()})}}},Po=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:S.Computable.make(r=>t.blobDriver.getDownloadedBlob(r.accessor(e).node().resourceInfo),{postprocessValue:async r=>{if(r==null)return;const o=await t.blobDriver.getContent(r.handle);if(o!=null)return JSON.parse(Buffer.from(o).toString())}})})},Ro=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getDownloadedBlob(e)})},Fo=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.blobDriver.getOnDemandBlob(e)})},Oo=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.uploadDriver.getProgressId(e)})},Bo=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getLastLogs(t,s)})},Do=s=>e=>{const t=e.source;return t===void 0?m(void 0):({drivers:r})=>({type:"ScheduleComputable",computable:r.logDriver.getProgressLog(t,s)})},To=s=>{const e=s.source;return e===void 0?m(void 0):({drivers:t})=>({type:"ScheduleComputable",computable:t.logDriver.getLogHandle(e)})};function y(s,e){switch(e.type){case"GetFromCtx":const t=s[e.variable];return typeof t=="function"?r=>he(t(r.cCtx)):(t===void 0&&console.log("asdasd"),m(t));case"Isolate":return({drivers:r})=>({type:"ScheduleComputable",computable:Mt(r,s,e.cfg)});case"Immediate":return m(e.value);case"GetJsonField":return()=>({type:"ScheduleSubroutine",subroutine:bo,args:{source:y(s,e.source),field:y(s,e.field)}});case"MapArrayValues":return()=>({type:"ScheduleSubroutine",subroutine:lo(s,e),args:{source:y(s,e.source)}});case"MapRecordValues":return()=>({type:"ScheduleSubroutine",subroutine:po(s,e),args:{source:y(s,e.source)}});case"MakeObject":return()=>({type:"ScheduleSubroutine",subroutine:ao,args:so(e.template,r=>y(s,r))});case"MakeArray":return()=>({type:"ScheduleSubroutine",subroutine:Vt(e.template.length),args:Nt(e.template,r=>y(s,r))});case"Flatten":return()=>({type:"ScheduleSubroutine",subroutine:co,args:{source:y(s,e.source)}});case"IsEmpty":return()=>({type:"ScheduleSubroutine",subroutine:ho,args:{arg:y(s,e.arg)}});case"Not":return()=>({type:"ScheduleSubroutine",subroutine:fo,args:{operand:y(s,e.operand)}});case"And":return()=>({type:"ScheduleSubroutine",subroutine:mo,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"Or":return()=>({type:"ScheduleSubroutine",subroutine:vo,args:{operand1:y(s,e.operand1),operand2:y(s,e.operand2)}});case"MapResourceFields":return()=>({type:"ScheduleSubroutine",subroutine:wo(s,e),args:{source:y(s,e.source)}});case"GetResourceField":return()=>({type:"ScheduleSubroutine",subroutine:uo,args:{source:y(s,e.source),field:y(s,e.field)}});case"GetResourceValueAsJson":return()=>({type:"ScheduleSubroutine",subroutine:yo,args:{source:y(s,e.source)}});case"GetBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:ko,args:{source:y(s,e.source)}});case"GetBlobContentAsString":return()=>({type:"ScheduleSubroutine",subroutine:Co,args:{source:y(s,e.source)}});case"GetBlobContentAsJson":return()=>({type:"ScheduleSubroutine",subroutine:Po,args:{source:y(s,e.source)}});case"GetDownloadedBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Ro,args:{source:y(s,e.source)}});case"GetOnDemandBlobContent":return()=>({type:"ScheduleSubroutine",subroutine:Fo,args:{source:y(s,e.source)}});case"GetImportProgress":return()=>({type:"ScheduleSubroutine",subroutine:Oo,args:{source:y(s,e.source)}});case"GetLastLogs":return()=>({type:"ScheduleSubroutine",subroutine:Bo(e.lines),args:{source:y(s,e.source)}});case"GetProgressLog":return()=>({type:"ScheduleSubroutine",subroutine:Do(e.patternToSearch),args:{source:y(s,e.source)}});case"GetLogHandle":return()=>({type:"ScheduleSubroutine",subroutine:To,args:{source:y(s,e.source)}});default:return f.assertNever(e)}}const xo=["$prod","$staging"];function Eo(s){return{$blockId:s.blockId,$args:JSON.parse(s.args),$ui:s.uiState!==void 0?JSON.parse(s.uiState):void 0,$prod:s.prod,$staging:s.staging}}const Lt=Symbol(),Jt="return",jo={op:Lt,arg:Jt};function Ao(s){return s.op==Lt&&s.arg==Jt}function Io(){return{pendingSubroutines:new Map}}function at(s,e,t,r){const o=new gt(t),n=(a,c)=>{if(Ao(a))return e.result=c,!1;const u=f.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(s);switch(c.type){case"ReturnResult":if(!n(a.destination,c.result))break e;break;case"ScheduleSubroutine":const u=Symbol(),d=Object.entries(c.args),p=d.length;if(p===0)o.push({destination:a.destination,operation:c.subroutine({})});else{for(const[h,v]of d)o.push({destination:{op:u,arg:h},operation:v});e.pendingSubroutines.set(u,{argCounter:p,args:{},subroutine:c.subroutine,destination:a.destination})}break;case"ScheduleComputable":if(!r)throw new Error("asynchronous operations are forbidden in this context");i.push({destination:a.destination,computable:c.computable});break;default:f.assertNever(c)}}return i}function No(s,e,t,r={}){return Mt(s,Eo(e),t,r)}function Mt(s,e,t,r={}){const o=Ae({ctx:Object.fromEntries(Object.entries(e).filter(([n])=>xo.indexOf(n)===-1)),cfg:t});return S.Computable.makeRaw(n=>{const i={drivers:s,cCtx:n},a=Io();return{ir:at(i,a,[{destination:jo,operation:y(e,t)}],!0),async postprocessValue(u){const d=[];for(const w of u)d.push({destination:w.destination,operation:m(w.computable)});const p={drivers:s,get cCtx(){throw new Error("asynchronous operations are forbidden in this context")}},h=new Map;for(const[w,P]of a.pendingSubroutines)h.set(w,{...P,args:{...P.args}});const v={result:a.result,pendingSubroutines:h};if(at(p,v,d,!1),!("result"in v))throw new Error("illegal cfg rendering stack state, no result");return v.result}}},{...r,key:o})}function Vo(s){return s instanceof ArrayBuffer||ArrayBuffer.isView(s)}function ct(s){return s!==void 0?Buffer.from(s).toString("base64"):void 0}class de{constructor(e,t,r,o,n){g(this,"callbackRegistry");g(this,"fnJSONStringify");g(this,"fnJSONParse");g(this,"computablesToResolve",{});g(this,"computableCtx");g(this,"accessors",new Map);g(this,"meta");g(this,"_resultPool");if(this.scope=e,this.vm=t,this.blockCtx=r,this.env=o,this.computableCtx=n,this.callbackRegistry=this.scope.manage(this.vm.newObject()),this.fnJSONStringify=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"stringify"))),t.typeof(this.fnJSONStringify)!=="function")throw new Error("JSON.stringify() not found.");if(this.fnJSONParse=e.manage(t.getProp(t.global,"JSON").consume(i=>t.getProp(i,"parse"))),t.typeof(this.fnJSONParse)!=="function")throw new Error("JSON.parse() not found.");this.meta=r.blockMeta(n),this.injectCtx()}resetComputableCtx(){this.computableCtx=void 0,this.accessors.clear()}static cleanErrorContext(e){typeof e=="object"&&e!==null&&"context"in e&&delete e.context}evaluateBundle(e){try{this.vm.unwrapResult(this.vm.evalCode(e,"bundle.js",{type:"global"})).dispose()}catch(t){throw de.cleanErrorContext(t),t}}runCallback(e,...t){try{return ce.Scope.withScope(r=>{const o=r.manage(this.vm.getProp(this.callbackRegistry,e));if(this.vm.typeof(o)!=="function")throw new Error(`No such callback: ${e}`);return this.scope.manage(this.vm.unwrapResult(this.vm.callFunction(o,this.vm.undefined,...t.map(n=>this.exportObjectUniversal(n,r)))))})}catch(r){throw de.cleanErrorContext(r),r}}getAccessorHandleByName(e){if(this.computableCtx===void 0)throw new Error("Accessors can't be used in this context");const t=(r,o)=>{if(!this.accessors.has(r)){const n=this.blockCtx[o];if(n===void 0)throw new Error("Staging context not available");const i=n(this.computableCtx);i?this.accessors.set(r,this.computableCtx.accessor(i).node({ignoreError:!0})):this.accessors.set(r,void 0)}return this.accessors.get(r)?r:void 0};if(e==="staging")return t("staging","staging");if(e==="main")return t("main","prod")}resolveWithCommon(e,t,...r){return this.wrapAccessor(this.getAccessor(e).traverseWithCommon(t,...r))}getResourceType(e){return this.getAccessor(e).resourceType}getInputsLocked(e){return this.getAccessor(e).getInputsLocked()}getOutputsLocked(e){return this.getAccessor(e).getOutputsLocked()}getIsReadyOrError(e){return this.getAccessor(e).getIsReadyOrError()}getIsFinal(e){return this.getAccessor(e).getIsFinal()}getError(e){return this.wrapAccessor(this.getAccessor(e).getError())}listInputFields(e){return this.getAccessor(e).listInputFields()}listOutputFields(e){return this.getAccessor(e).listOutputFields()}listDynamicFields(e){return this.getAccessor(e).listDynamicFields()}getKeyValueBase64(e,t){return ct(this.getAccessor(e).getKeyValue(t))}getKeyValueAsString(e,t){return this.getAccessor(e).getKeyValueAsString(t)}getDataBase64(e){return ct(this.getAccessor(e).getData())}getDataAsString(e){return this.getAccessor(e).getDataAsString()}parsePObjectCollection(e,t,r){const o=this.getAccessor(e);if(!o.getIsReadyOrError())return;const n=oo(o,t,r),i={};for(const[a,c]of Object.entries(n))i[a]=C.mapPObjectData(c,u=>this.wrapAccessor(u));return i}registerComputable(e,t){const r=`${e}_${U.randomUUID()}`;return this.computablesToResolve[r]=t,r}getBlobContentAsString(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsString",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("utf-8")}}))}getBlobContentAsBase64(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getBlobContentAsBase64",S.Computable.make(r=>this.env.driverKit.blobDriver.getDownloadedBlob(t,r),{postprocessValue:async r=>{if(r!==void 0)return Buffer.from(await this.env.driverKit.blobDriver.getContent(r.handle)).toString("base64")}}))}getDownloadedBlobContentHandle(e){const t=this.getAccessor(e).resourceInfo;return this.registerComputable("getDownloadedBlobContentHandle",this.env.driverKit.blobDriver.getDownloadedBlob(t))}getOnDemandBlobContentHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getOnDemandBlobContentHandle",this.env.driverKit.blobDriver.getOnDemandBlob(t))}getImportProgress(e){const t=this.getAccessor(e).persist();return this.registerComputable("getImportProgress",this.env.driverKit.uploadDriver.getProgressId(t))}getLastLogs(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getLastLogs",this.env.driverKit.logDriver.getLastLogs(r,t))}getProgressLog(e,t){const r=this.getAccessor(e).persist();return this.registerComputable("getProgressLog",this.env.driverKit.logDriver.getProgressLog(r,t))}getLogHandle(e){const t=this.getAccessor(e).persist();return this.registerComputable("getLogHandle",this.env.driverKit.logDriver.getLogHandle(t))}getBlockLabel(e){const t=this.meta.get(e);if(t===void 0)throw new Error(`Block ${e} not found.`);return t.label}get resultPool(){if(this._resultPool===void 0){if(this.computableCtx===void 0)throw new Error("can't use result pool in this context (most porbably called from the future mapper)");this._resultPool=f.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:C.mapPObjectData(t.obj,r=>this.wrapAccessor(r))}))}}getDataWithErrorsFromResultPool(){const e=this.resultPool.getDataWithErrors();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`incomplete_result_pool:${e.instabilityMarker}`),{isComplete:e.isComplete,entries:e.entries.map(t=>({ref:t.ref,obj:{id:t.obj.id,spec:t.obj.spec,data:C.mapValueInVOE(t.obj.data,r=>this.wrapAccessor(r))}}))}}getSpecsFromResultPool(){const e=this.resultPool.getSpecs();return e.instabilityMarker!==void 0&&this.computableCtx.markUnstable(`specs_from_pool_incomplete:${e.instabilityMarker}`),e}getSpecFromResultPoolByRef(e,t){return this.resultPool.getSpecByRef(e,t)}getDataFromResultPoolByRef(e,t){return C.mapPObjectData(this.resultPool.getDataByRef(e,t),r=>this.wrapAccessor(r))}createPFrame(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PFrames from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPFrame(e.map(t=>C.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}createPTable(e){if(this.computableCtx===void 0)throw new Error("can't instantiate PTable from this context (most porbably called from the future mapper)");return this.env.driverKit.pFrameDriver.createPTable(C.mapPTableDef(e,t=>C.mapPObjectData(t,r=>this.getAccessor(r))),this.computableCtx)}getCurrentUnstableMarker(){var e;return(e=this.computableCtx)==null?void 0:e.unstableMarker}getAccessor(e){const t=this.accessors.get(e);if(t===void 0)throw new Error("No such accessor");return t}wrapAccessor(e){if(e!==void 0){const t=U.randomUUID();return this.accessors.set(t,e),t}}exportSingleValue(e,t){const r=this.tryExportSingleValue(e,t);if(r===void 0)throw new Error(`Can't export value: ${e}`);return r}tryExportSingleValue(e,t){let r,o=!1;switch(typeof e){case"string":r=this.vm.newString(e),o=!0;break;case"number":r=this.vm.newNumber(e),o=!0;break;case"undefined":r=this.vm.undefined;break;case"boolean":r=e?this.vm.true:this.vm.false;break;default:if(e===null){r=this.vm.null;break}if(Vo(e)){r=this.vm.newArrayBuffer(e),o=!0;break}return}return o&&t!=null?t.manage(r):r}exportObjectUniversal(e,t){const r=this.tryExportSingleValue(e,t);return r!==void 0?r:this.exportObjectViaJson(e,t)}exportObjectViaJson(e,t){const r=this.vm.newString(JSON.stringify(e)).consume(o=>this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse,this.vm.undefined,o)));return t!==void 0?t.manage(r):r}importObjectUniversal(e){switch(this.vm.typeof(e)){case"undefined":return;case"boolean":case"number":case"string":return this.vm.dump(e);default:return this.importObjectViaJson(e)}}importObjectViaJson(e){const t=this.vm.unwrapResult(this.vm.callFunction(this.fnJSONStringify,this.vm.undefined,e)).consume(r=>this.vm.getString(r));if(t!=="undefined")return JSON.parse(t)}injectCtx(){ce.Scope.withScope(e=>{const t=e.manage(this.vm.newObject());this.vm.setProp(t,"args",e.manage(this.vm.newString(this.blockCtx.args))),this.blockCtx.uiState!==void 0&&this.vm.setProp(t,"uiState",e.manage(this.vm.newString(this.blockCtx.uiState))),this.vm.setProp(t,"callbackRegistry",this.callbackRegistry);const r=(o,n)=>{this.vm.newFunction(o,n).consume(i=>this.vm.setProp(t,o,i))};r("getAccessorHandleByName",o=>this.exportSingleValue(this.getAccessorHandleByName(this.vm.getString(o)),void 0)),r("resolveWithCommon",(o,n,...i)=>this.exportSingleValue(this.resolveWithCommon(this.vm.getString(o),this.importObjectViaJson(n),...i.map(a=>this.importObjectViaJson(a))),void 0)),r("getResourceType",o=>this.exportObjectViaJson(this.getResourceType(this.vm.getString(o)),void 0)),r("getInputsLocked",o=>this.exportSingleValue(this.getInputsLocked(this.vm.getString(o)),void 0)),r("getOutputsLocked",o=>this.exportSingleValue(this.getOutputsLocked(this.vm.getString(o)),void 0)),r("getIsReadyOrError",o=>this.exportSingleValue(this.getIsReadyOrError(this.vm.getString(o)),void 0)),r("getIsFinal",o=>this.exportSingleValue(this.getIsFinal(this.vm.getString(o)),void 0)),r("getError",o=>this.exportSingleValue(this.getError(this.vm.getString(o)),void 0)),r("listInputFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("listOutputFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("listDynamicFields",o=>this.exportObjectViaJson(this.listInputFields(this.vm.getString(o)),void 0)),r("getKeyValueBase64",(o,n)=>this.exportSingleValue(this.getKeyValueBase64(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getKeyValueAsString",(o,n)=>this.exportSingleValue(this.getKeyValueAsString(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getDataBase64",o=>this.exportSingleValue(this.getDataBase64(this.vm.getString(o)),void 0)),r("getDataAsString",o=>this.exportSingleValue(this.getDataAsString(this.vm.getString(o)),void 0)),r("parsePObjectCollection",(o,n,i)=>this.exportObjectUniversal(this.parsePObjectCollection(this.vm.getString(o),this.vm.dump(n),this.vm.getString(i)),void 0)),r("getBlobContentAsBase64",o=>this.exportSingleValue(this.getBlobContentAsBase64(this.vm.getString(o)),void 0)),r("getBlobContentAsString",o=>this.exportSingleValue(this.getBlobContentAsString(this.vm.getString(o)),void 0)),r("getDownloadedBlobContentHandle",o=>this.exportSingleValue(this.getDownloadedBlobContentHandle(this.vm.getString(o)),void 0)),r("getOnDemandBlobContentHandle",o=>this.exportSingleValue(this.getOnDemandBlobContentHandle(this.vm.getString(o)),void 0)),r("getImportProgress",o=>this.exportSingleValue(this.getImportProgress(this.vm.getString(o)),void 0)),r("getLastLogs",(o,n)=>this.exportSingleValue(this.getLastLogs(this.vm.getString(o),this.vm.getNumber(n)),void 0)),r("getProgressLog",(o,n)=>this.exportSingleValue(this.getProgressLog(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getLogHandle",o=>this.exportSingleValue(this.getLogHandle(this.vm.getString(o)),void 0)),r("getBlockLabel",o=>this.exportSingleValue(this.getBlockLabel(this.vm.getString(o)),void 0)),r("getDataFromResultPool",o=>this.exportObjectUniversal(this.getDataFromResultPool(),void 0)),r("getDataWithErrorsFromResultPool",o=>this.exportObjectUniversal(this.getDataWithErrorsFromResultPool(),void 0)),r("getSpecsFromResultPool",o=>this.exportObjectUniversal(this.getSpecsFromResultPool(),void 0)),r("calculateOptions",o=>this.exportObjectUniversal(this.calculateOptions(this.importObjectViaJson(o)),void 0)),r("getSpecFromResultPoolByRef",(o,n)=>this.exportObjectUniversal(this.getSpecFromResultPoolByRef(this.vm.getString(o),this.vm.getString(n)),void 0)),r("getDataFromResultPoolByRef",(o,n)=>this.exportObjectUniversal(this.getDataFromResultPoolByRef(this.vm.getString(o),this.vm.getString(n)),void 0)),r("createPFrame",o=>this.exportSingleValue(this.createPFrame(this.importObjectViaJson(o)),void 0)),r("createPTable",o=>this.exportSingleValue(this.createPTable(this.importObjectViaJson(o)),void 0)),r("getCurrentUnstableMarker",()=>this.exportSingleValue(this.getCurrentUnstableMarker(),void 0)),this.vm.setProp(this.vm.global,"cfgRenderCtx",t)})}}function Ut(s,e){var t,r;return Z((r=(t=s.traverse({field:R(e,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}))==null?void 0:t.getDataAsJson())==null?void 0:r.config,o=>C.extractConfig(o))}const ut=process.env.MI_LOG_OUTPUT_STATUS;function Lo(s,e,t,r,o={}){return o={...o},o.mode===void 0&&t.retentive===!0&&(o.mode="StableOnlyRetentive"),S.Computable.makeRaw(n=>{const i=new ce.Scope;n.addOnDestroy(()=>i.dispose());const a=i.manage(s.quickJs.newRuntime());a.setMemoryLimit(1024*640),a.setMaxStackSize(1024*320);const c=i.manage(a.newContext()),u=new de(i,c,e,s,n);u.evaluateBundle(r.content);const d=u.runCallback(t.handle);return u.resetComputableCtx(),{ir:u.computablesToResolve,postprocessValue:async(p,{unstableMarker:h,stable:v})=>{ut&&(ut!=="unstable-only"||!v)&&console.log(v?`Stable output ${t.handle} calculated.`:`Unstable output ${t.handle}; marker = ${h}`);for(const[w,P]of Object.entries(p))u.runCallback(w,P);return u.importObjectUniversal(d)}}},o)}function Jo(s){return C.isConfigLambda(s)?s.isActive===!0:io(s)}function X(s,e,t,r,o={}){if(C.isConfigLambda(t)){if(r===void 0)throw new Error("No code bundle.");return Lo(s,e,t,r,o)}else return No(s.driverKit,e,t,o)}function Mo(s,e,t){return S.Computable.make(r=>{var w,P,K,_,$,H,z,oe;const o=r.accessor(s).node(),n=f.notEmpty(o.getKeyValueAsJson(Le)),i=f.notEmpty(o.getKeyValueAsJson(te)),a=f.notEmpty(o.getKeyValueAsJson(re)),c=f.notEmpty(o.getKeyValueAsJson(W)),u=f.notEmpty(o.getKeyValueAsJson(ue)),d=new Map;for(const{id:k}of M(c)){const I=o.traverse({field:R(k,"currentArgs"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0});let Y;const j=o.traverse({field:R(k,"prodArgs"),assertFieldType:"Dynamic",stableIfNotFound:!0});if(j!==void 0){const x=o.getField({field:R(k,"prodOutput"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0}),O=o.getField({field:R(k,"prodUiCtx"),assertFieldType:"Dynamic",errorIfFieldNotFound:!0});Y={arguments:j.getDataAsJson(),stale:I.id!==j.id,outputError:x.error!==void 0||O.error!==void 0||((w=x.value)==null?void 0:w.getError())!==void 0||((P=O.value)==null?void 0:P.getError())!==void 0,outputsError:((K=x.error)==null?void 0:K.getDataAsString())??(($=(_=x.value)==null?void 0:_.getError())==null?void 0:$.getDataAsString()),exportsError:((H=O.error)==null?void 0:H.getDataAsString())??((oe=(z=O.value)==null?void 0:z.getError())==null?void 0:oe.getDataAsString()),finished:(x.value!==void 0&&x.value.getIsReadyOrError()||x.error!==void 0&&x.error.getIsReadyOrError())&&(O.value!==void 0&&O.value.getIsReadyOrError()||O.error!==void 0&&O.error.getIsReadyOrError())}}d.set(k,{currentArguments:I.getDataAsJson(),prod:Y})}const p=ie(c,k=>d.get(k).currentArguments),h=new Set(u.blocksInLimbo),v=[...M(c)].map(({id:k,label:I,renderingMode:Y})=>{var qe,We,ze,Ye;const j=f.notEmpty(d.get(k)),x=f.notEmpty(p.nodes.get(k));let O="NotCalculated";j.prod!==void 0&&(h.has(k)?O="Limbo":O=j.prod.finished?"Done":"Running");const G=o.traverse({field:R(k,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),N=G==null?void 0:G.getDataAsJson(),{sections:se,title:b,inputsValid:B,sdkVersion:F}=Z(N==null?void 0:N.config,me=>{const q=C.extractConfig(me),ve=$e(o,k);return{sections:X(t,ve,q.sections,q.code),title:Z(q.title,Ht=>X(t,ve,Ht,q.code)),inputsValid:X(t,ve,q.inputsValid,q.code),sdkVersion:q.sdkVersion}})||{},_t=Z(N,me=>t.blockUpdateWatcher.get(me.source));return{id:k,label:b??I,title:b??I,renderingMode:Y,stale:((qe=j.prod)==null?void 0:qe.stale)!==!1||O==="Limbo",missingReference:x.missingReferences,upstreams:[...p.traverseIdsExcludingRoots("upstream",k)],downstreams:[...p.traverseIdsExcludingRoots("downstream",k)],calculationStatus:O,outputErrors:((We=j.prod)==null?void 0:We.outputError)===!0,outputsError:(ze=j.prod)==null?void 0:ze.outputsError,exportsError:(Ye=j.prod)==null?void 0:Ye.exportsError,sections:se,inputsValid:B,currentBlockPack:N==null?void 0:N.source,updatedBlockPack:_t,sdkVersion:F,navigationState:e.getState(k)}});return{meta:a,created:new Date(n),lastModified:new Date(i),authorMarker:o.getKeyValueAsJson(Fe),blocks:v}},{postprocessValue:r=>{const o=new Set,n=new Set;return{...r,blocks:r.blocks.map(i=>{i.inputsValid||o.add(i.id),i.stale&&n.add(i.id);const a=i.stale||i.upstreams.findIndex(u=>n.has(u))!==-1,c=(a||i.outputErrors)&&!!i.inputsValid&&!i.missingReference&&i.upstreams.findIndex(u=>o.has(u))===-1;return{...i,canRun:c,stale:a}})}}}).withStableType()}function Uo(s,e){const t=s.node();if(l.resourceTypesEqual(t.resourceType,Me)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.frontendDownloadDriver.getPath(new URL(r.url)).withStableType()}else if(l.resourceTypesEqual(t.resourceType,Ue)){const r=t.getDataAsJson();if(r===void 0)throw new Error("No resource data.");return e.signer.verify(r.path,r.signature,`Frontend path signature mismatch for: ${r.path}`),r.path}else throw new Error(`Unsupported resource type: ${JSON.stringify(t.resourceType)}`)}function Ko(s,e){if(s!==void 0)return S.Computable.make(t=>Uo(t.accessor(s),e),{postprocessValue:t=>{if(t!==void 0){if(typeof t=="string")return t;if(t.error!==void 0)throw new Error(t.error);return t.path}}}).withStableType()}function $o(s,e,t){return S.Computable.make(r=>{var a;const o=r.accessor(s).node(),n=Ut(o,e),i=(a=o.traverse({field:R(e,"blockPack"),assertFieldType:"Dynamic"},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0},{field:xt,assertFieldType:"Input"}))==null?void 0:a.persist();return{path:Ko(i,t),sdkVersion:n==null?void 0:n.sdkVersion}},{mode:"StableOnlyLive"})}function Go(s,e,t){return S.Computable.make(r=>{const o=r.accessor(s).node(),n=$e(o,e);return{author:o.getKeyValueAsJson(Re(e)),args:JSON.parse(n.args),ui:n.uiState!==void 0?JSON.parse(n.uiState):void 0}},{key:"inputs#"+l.resourceIdToString(s.rid)+e})}function _o(s,e,t){return S.Computable.make(r=>{const o=r.accessor(s).node(),n=It(o,e),i=Ut(o,e);return Z(i,a=>{const c={};for(const[u,d]of Object.entries(a.outputs))c[u]=S.Computable.wrapError(X(t,n,d,a.code));return c})},{key:"outputs#"+l.resourceIdToString(s.rid)+e}).withStableType()}function Ho(s,e){return S.Computable.make(t=>{const r=t.accessor(s).node(),o=f.notEmpty(r.getKeyValueAsJson(W)),n=[];for(const{id:i,renderingMode:a}of M(o)){const c=r.traverse({field:R(i,"blockPack"),assertFieldType:"Dynamic",errorIfFieldNotSet:!0},{field:l.Pl.HolderRefField,assertFieldType:"Input",errorIfFieldNotFound:!0}),u=c==null?void 0:c.getDataAsJson();if((u==null?void 0:u.config)===void 0)continue;const d=C.extractConfig(u.config),p=Object.entries(d.outputs).map(([,v])=>v).filter(v=>Jo(v)).map(v=>v);if(p.length===0)continue;const h=It(r,i);for(const v of p)n.push(S.Computable.wrapError(X(e,h,v,d.code)))}return n})}class qo{constructor(){g(this,"states",new Map)}setState(e,t){const r=this.states.get(e);if(r===void 0){this.states.set(e,{state:t,change:new S.ChangeSource});return}r.state={...t},r.change.markChanged()}readState(e,t){let r=this.states.get(t);return r===void 0&&(r={state:{...C.DefaultNavigationState},change:new S.ChangeSource},this.states.set(t,r)),r.change.attachWatcher(e.watcher),r.state}getState(e){return S.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 fe{constructor(e,t,r){g(this,"rid");g(this,"overview");g(this,"navigationStates",new qo);g(this,"blockComputables",new Map);g(this,"blockFrontends",new Map);g(this,"activeConfigs");g(this,"refreshLoopResult");g(this,"abortController",new AbortController);g(this,"destroyed",!1);this.env=e,this.projectTree=r,this.overview=Mo(r.entry(),this.navigationStates,e).withPreCalculatedValueTree(),this.rid=t,this.refreshLoopResult=this.refreshLoop(),this.activeConfigs=Ho(r.entry(),e)}async refreshLoop(){for(;!this.destroyed;)try{await Se(this.env.pl,this.rid,e=>{e.doRefresh(this.env.ops.stagingRenderingRate)}),await this.activeConfigs.getValue(),await ht.setTimeout(this.env.ops.projectRefreshInterval,this.abortController.signal)}catch(e){if(l.isNotFoundError(e)){console.warn("project refresh routine terminated, because project was externally deleted");break}else if(!l.isTimeoutOrCancelError(e))throw new Error("Unexpected exception",{cause:e})}}async addBlock(e,t,r,o=void 0,n=U.randomUUID()){const i=await this.env.bpPreparer.prepare(t),a=await this.env.bpPreparer.getBlockConfigContainer(t),c=C.extractConfig(a);return await L(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},r)),await this.projectTree.refreshState(),n}async updateBlockPack(e,t,r=!1,o){const n=await this.env.bpPreparer.prepare(t),i=await this.env.bpPreparer.getBlockConfigContainer(t);await L(this.env.pl,this.rid,o,a=>a.migrateBlockPack(e,n,r?JSON.stringify(i.initialArgs):void 0)),await this.projectTree.refreshState()}async deleteBlock(e,t){await L(this.env.pl,this.rid,t,r=>r.deleteBlock(e)),this.navigationStates.deleteBlock(e),await this.projectTree.refreshState()}async reorderBlocks(e,t){await L(this.env.pl,this.rid,t,r=>{const o=r.structure;if(o.groups.length!==1)throw new Error("Unexpected project structure, non-sinular block group");const n=o.groups[0];if(n.blocks.length!==e.length)throw new Error(`Lengh mismatch: ${n.blocks.length} !== ${e.length}`);if(new Set(e).size!==e.length)throw new Error("Repeated block ids");const i={groups:[{id:n.id,label:n.label,blocks:e.map(a=>{const c=n.blocks.find(u=>u.id===a);if(c===void 0)throw new Error(`Can't find block: ${a}`);return c})}]};r.updateStructure(i)}),await this.projectTree.refreshState()}async runBlock(e){await Se(this.env.pl,this.rid,t=>t.renderProduction([e],!0)),await this.projectTree.refreshState()}async stopBlock(e){await Se(this.env.pl,this.rid,t=>t.stopProduction(e)),await this.projectTree.refreshState()}async setBlockArgs(e,t,r){await L(this.env.pl,this.rid,r,o=>o.setArgs([{blockId:e,args:JSON.stringify(t)}])),await this.projectTree.refreshState()}async setUiState(e,t,r){await L(this.env.pl,this.rid,r,o=>o.setUiState(e,t===void 0?void 0:JSON.stringify(t))),await this.projectTree.refreshState()}async setNavigationState(e,t){this.navigationStates.setState(e,t)}async setBlockArgsAndUiState(e,t,r,o){await L(this.env.pl,this.rid,o,n=>{n.setArgs([{blockId:e,args:JSON.stringify(t)}]),n.setUiState(e,JSON.stringify(r))}),await this.projectTree.refreshState()}async resetBlockArgsAndUiState(e,t){await this.env.pl.withWriteTx("BlockInputsReset",async r=>{const o=l.ensureResourceIdNotNull((await r.getField(l.field(this.rid,R(e,"blockPack")))).value),n=l.ensureResourceIdNotNull((await r.getField(l.field(o,l.Pl.HolderRefField))).value),i=await r.getResourceData(n,!1),a=JSON.parse(Buffer.from(f.notEmpty(i.data)).toString("utf-8"));await L(r,this.rid,t,c=>{c.setArgs([{blockId:e,args:JSON.stringify(a.config.initialArgs)}]),c.setUiState(e,void 0)}),await r.commit()}),await this.projectTree.refreshState()}getBlockComputables(e){const t=this.blockComputables.get(e);if(t===void 0){const r=_o(this.projectTree.entry(),e,this.env),n={fullState:S.Computable.make(i=>({argsAndUiState:Go(this.projectTree.entry(),e),outputs:r,navigationState:this.navigationStates.getState(e)}),{postprocessValue:i=>({...i.argsAndUiState,outputs:i.outputs,navigationState:i.navigationState})}).withPreCalculatedValueTree()};return this.blockComputables.set(e,n),n}return t}getBlockState(e){return this.getBlockComputables(e).fullState}getBlockFrontend(e){const t=this.blockFrontends.get(e);if(t===void 0){const r=$o(this.projectTree.entry(),e,this.env).withPreCalculatedValueTree();return this.blockFrontends.set(e,r),r}return t}async destroy(){this.destroyed=!0,this.abortController.abort(),await this.refreshLoopResult,await this.projectTree.terminate(),this.overview.resetState(),this.blockFrontends.forEach(e=>e.resetState()),this.blockComputables.forEach(e=>{e.fullState.resetState()}),this.activeConfigs.resetState()}async destroyAndAwaitTermination(){await this.destroy()}static async init(e,t){const r=await je.SynchronizedTreeState.init(e.pl,t,{...e.ops.defaultTreeOptions,pruning:Wo},e.logger);return new fe(e,t,r)}}function Wo(s){switch(s.type.name){case"BlockPackCustom":return s.fields.filter(e=>e.name!=="template");case"UserProject":return s.fields.filter(e=>!e.name.startsWith("__serviceTemplate"));case"Blob":return[];default:return s.fields}}const Ge={logger:new f.ConsoleLoggerAdapter,blobDriverOps:{cacheSoftSizeBytes:100*1024*1024,nConcurrentDownloads:10},uploadDriverOps:{nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3},logStreamDriverOps:{nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}};function _e(s){return{blobDownloadPath:T.join(s,"download")}}const Kt={...Ge,defaultTreeOptions:{pollingInterval:350,stopPollingDelay:2500},devBlockUpdateRecheckInterval:1e3,projectRefreshInterval:700,stagingRenderingRate:5};function $t(s){return{..._e(s),frontendDownloadPath:T.join(s,"frontend")}}const zo={minDelay:1500},Yo="__no_updates__";class Qo extends S.PollComputablePool{constructor(t,r,o={}){super({...o,...zo},r);g(this,"http");this.registryProvider=t,this.http=o.http}getKey(t){switch(t.type){case"dev-v1":return`dev_1_${t.folder}_${t.mtime}`;case"dev-v2":return`dev_2_${t.folder}_${t.mtime}`;case"from-registry-v2":return`from_registry_v2_${t.registryUrl}_${t.id.organization}_${t.id.name}_${t.id.version}`;default:return Yo}}async readValue(t){var r;try{switch(t.type){case"dev-v1":try{const o=await Ve(t.folder);return o===t.mtime?void 0:{...t,mtime:o}}catch(o){this.logger.warn(o);return}case"dev-v2":try{const o=await D.tryLoadPackDescription(t.folder,this.logger);if(o===void 0)return;const n=await pe(o);return n===t.mtime?void 0:{...t,mtime:n}}catch(o){this.logger.warn(o);return}case"from-registry-v2":try{const o=this.registryProvider.getRegistry(t.registryUrl),n=(r=await o.getOverviewForSpec(t.id))==null?void 0:r.spec;if((n==null?void 0:n.type)!=="from-registry-v2")throw new Error("Unexpected");return Q.blockPackIdEquals(n.id,t.id)?void 0:((async()=>{try{await o.getComponents(n.id)}catch(i){this.logger.warn(i)}})(),n)}catch(o){this.logger.warn(o);return}default:return}}catch(o){this.logger.warn(o);return}}resultsEqual(t,r){if(t===void 0&&r===void 0)return!0;if(t===void 0||r===void 0||t.type!==r.type)return!1;switch(t.type){case"from-registry-v1":return r.type!=="from-registry-v1"?!1:t.registryUrl===r.registryUrl&&Q.blockPackIdEquals(t.id,r.id);case"from-registry-v2":return r.type!=="from-registry-v2"?!1:t.registryUrl===r.registryUrl&&Q.blockPackIdEquals(t.id,r.id);case"dev-v1":return r.type!=="dev-v1"?!1:t.folder===r.folder&&t.mtime===r.mtime;case"dev-v2":return r.type!=="dev-v2"?!1:t.folder===r.folder&&t.mtime===r.mtime;default:f.assertNever(t)}}}class lt{constructor(){g(this,"resources",new Map)}check(e){const t=this.resources.get(e);if(t===void 0)throw new Error("Unexpected state.");if(t.refCount===0){this.resources.delete(e);const r=t.resource;r!=null&&typeof r[Symbol.dispose]=="function"&&r[Symbol.dispose]()}}acquire(e){const t=this.calculateParamsKey(e);let r=this.resources.get(t);r===void 0&&(r={refCount:0,resource:this.createNewResource(e)},this.resources.set(t,r)),r.refCount++;let o=!1;return{resource:r.resource,key:t,unref:()=>{o||(r.refCount--,o=!0,this.check(t))}}}getByKey(e){if(!this.resources.has(e))throw new Error(`resource not found, key = ${e}`);return this.resources.get(e).resource}tryGetByKey(e){var t;return(t=this.resources.get(e))==null?void 0:t.resource}}function dt(s){return String(s.id)}class Zo{constructor(e,t,r){g(this,"pFrame",new er.PFrame);g(this,"blobIdToResource",new Map);g(this,"blobHandleComputables",new Map);g(this,"preloadBlob",async e=>{const t=e.map(r=>this.getOrCreateComputableForBlob(r));for(const r of t)await r.awaitStableFullValue()});g(this,"resolveBlob",async e=>{const t=this.getOrCreateComputableForBlob(e);return this.blobDriver.getLocalPath((await t.awaitStableValue()).handle)});g(this,"resolveBlobContent",async e=>{const t=this.getOrCreateComputableForBlob(e),r=this.blobDriver.getLocalPath((await t.awaitStableValue()).handle);return await this.blobContentCache.forceFetch(r)});this.blobDriver=e,this.blobContentCache=t,this.columns=r,this.pFrame.setDataSource(this);for(const o of r){for(const i of zr(o.data))this.blobIdToResource.set(dt(i),i);const n=Yr(o.data,dt);try{this.pFrame.addColumnSpec(o.id,o.spec),this.pFrame.setColumnData(o.id,n)}catch(i){throw new Error(`Adding column ${o.id} to PFrame failed: ${i}; Spec: ${o.spec}, DataInfo: ${n}.`)}}}getOrCreateComputableForBlob(e){let t=this.blobHandleComputables.get(e);if(t!==void 0)return t;const r=this.blobIdToResource.get(e);if(r===void 0)throw new Error(`Blob with id ${e} not found.`);return t=this.blobDriver.getDownloadedBlob(r).withPreCalculatedValueTree(),this.blobHandleComputables.set(e,t),t}[Symbol.dispose](){for(const e of this.blobHandleComputables.values())e.resetState();this.pFrame.dispose()}}class Xo{constructor(e){g(this,"pFrames");g(this,"pTables");g(this,"blobContentCache");g(this,"concurrencyLimiter");this.blobDriver=e;const t=new tr.LRUCache({maxSize:1e9,fetchMethod:async o=>await ft.readFile(o),sizeCalculation:o=>o.length}),r=new f.ConcurrencyLimitingExecutor(1);this.blobContentCache=t,this.concurrencyLimiter=r,this.pFrames=new class extends lt{constructor(o){super(),this.blobDriver=o}createNewResource(o){return new Zo(this.blobDriver,t,o)}calculateParamsKey(o){return ts(o)}}(this.blobDriver),this.pTables=new class extends lt{constructor(o){super(),this.pFrames=o}async createNewResource(o){const n=this.pFrames.getByKey(o.pFrameHandle),i=await r.run(async()=>await n.pFrame.createTable({src:ee(o.def.src),filters:o.def.filters}));return o.def.sorting.length!==0?i.sort(o.def.sorting):i}calculateParamsKey(o){return es(o)}}(this.pFrames)}createPFrame(e,t){const r=e.map(n=>C.mapPObjectData(n,i=>ro(i))),o=this.pFrames.acquire(r);return t.addOnDestroy(o.unref),o.key}createPTable(e,t){const r=this.createPFrame(rs(e.src),t),o=C.mapPTableDef(e,i=>i.id),n=this.pTables.acquire({def:o,pFrameHandle:r});return t.addOnDestroy(n.unref),n.key}async findColumns(e,t){const r={...t,compatibleWith:t.compatibleWith.length!==0?[{axesSpec:t.compatibleWith,qualifications:[]}]:[]};return{hits:(await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.findColumns(r))).hits.map(o=>o.hit)}}async getColumnSpec(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getColumnSpec(t))}async listColumns(e){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.listColumns())}async calculateTableData(e,t){let r=await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.createTable({src:ee(t.src),filters:t.filters}));if(t.sorting.length>0){const i=await this.concurrencyLimiter.run(async()=>await r.sort(t.sorting));r.dispose(),r=i}const o=r.getSpec(),n=await this.concurrencyLimiter.run(async()=>await r.getData([...o.keys()]));return r.dispose(),o.map((i,a)=>({spec:i,data:n[a]}))}async getUniqueValues(e,t){return await this.concurrencyLimiter.run(async()=>await this.pFrames.getByKey(e).pFrame.getUniqueValues(t))}async getShape(e){return(await this.pTables.getByKey(e)).getShape()}async getSpec(e){return(await this.pTables.getByKey(e)).getSpec()}async getData(e,t,r){const o=await this.pTables.getByKey(e);return await this.concurrencyLimiter.run(async()=>await o.getData(t,r))}}function ee(s){switch(s.type){case"column":return{type:"column",columnId:s.column,qualifications:[]};case"inner":case"full":return{type:s.type,entries:s.entries.map(e=>ee(e))};case"outer":return{type:"outer",primary:ee(s.primary),secondary:s.secondary.map(e=>ee(e))};default:f.assertNever(s)}}function es(s){const e=U.createHash("sha256");return e.update(s.pFrameHandle),e.update(Ae(s.def)),e.digest().toString("hex")}function ts(s){const e=s.map(o=>o.id).sort(),t=U.createHash("sha256");let r="";for(const o of e)r!==o&&(t.update(o),r=o);return t.digest().toString("hex")}function rs(s){const e=new Map;return ae(s,e),[...e.values()]}function ae(s,e){switch(s.type){case"column":e.set(s.column.id,s.column);return;case"full":case"inner":for(const t of s.entries)ae(t,e);return;case"outer":ae(s.primary,e);for(const t of s.secondary)ae(t,e);return;default:f.assertNever(s)}}async function Gt(s,e,t){const r={...Ge,..._e(e),...t},o=new f.HmacSha256Signer(r.localSecret),n=V.createDownloadClient(r.logger,s,r.localProjections),i=V.createLogsClient(s,r.logger),a=V.createUploadBlobClient(s,r.logger),c=V.createUploadProgressClient(s,r.logger),u=new V.DownloadDriver(r.logger,n,i,r.blobDownloadPath,o,r.blobDriverOps),d=new V.UploadDriver(r.logger,o,a,c,r.uploadDriverOps),p=new V.LogsStreamDriver(r.logger,i,r.logStreamDriverOps),h=new V.LogsDriver(r.logger,p,u),v=await V.LsDriver.init(r.logger,s,o,r.localProjections,r.openFileDialogCallback,r.virtualLocalStoragesOverride),w=new Xo(u);return{blobDriver:u,logDriver:h,lsDriver:v,signer:o,uploadDriver:d,pFrameDriver:w}}class He{constructor(e,t,r,o,n,i,a,c){g(this,"pl");g(this,"projectList");g(this,"openedProjectsByRid",new Map);this.env=e,this.driverKit=t,this.signer=r,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=U.randomUUID()){const r=await this.pl.withWriteTx("MLCreateProject",async o=>{const n=await Wr(o,e);return o.createField(l.field(this.projectListResourceId,t),"Dynamic",n),await o.commit(),await l.toGlobalResourceId(n)});return await this.projectListTree.refreshState(),r}async setProjectMeta(e,t,r){await L(this.pl,e,r,async o=>{o.setMeta(t)}),await this.projectListTree.refreshState()}async deleteProject(e){await this.pl.withWriteTx("MLRemoveProject",async t=>{t.removeField(l.field(this.projectListResourceId,e)),await t.commit()}),await this.projectListTree.refreshState()}async projectIdToResourceId(e){return await this.pl.withReadTx("Project id to resource id",async t=>{const r=(await t.getField(l.field(this.projectListResourceId,e))).value;if(l.isNullResourceId(r))throw new Error("Unexpected project list structure.");return r})}async ensureProjectRid(e){return typeof e=="string"?await this.projectIdToResourceId(e):e}async openProject(e){const t=await this.ensureProjectRid(e);if(this.openedProjectsByRid.has(t))throw new Error(`Project ${t} already opened`);this.openedProjectsByRid.set(t,await fe.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 f.HmacSha256Signer.generateSecret()}static async init(e,t,r){const o={...Kt,...$t(t),...r};process.env.MI_LOG_TREE_STAT&&(o.defaultTreeOptions.logStat=process.env.MI_LOG_TREE_STAT==="cumulative"?"cumulative":"per-request");const n=await e.withWriteTx("MLInitialization",async P=>{const K=l.field(P.clientRoot,Rr);P.createField(K,"Dynamic");const _=await P.getField(K);if(l.isNullResourceId(_.value)){const $=P.createEphemeral(wt);return P.lock($),P.setField(K,$),await P.commit(),await $.globalId}else return _.value}),i=o.logger,a=await Gt(e,t,o),c=new J.RetryAgent(e.httpDispatcher,{minTimeout:250,maxRetries:4}),u=new vt(c),d=new Ur(u,a.signer,c),p=new V.DownloadUrlDriver(i,e.httpDispatcher,o.frontendDownloadPath),h={pl:e,signer:a.signer,logger:i,httpDispatcher:e.httpDispatcher,retryHttpDispatcher:c,ops:o,bpPreparer:d,frontendDownloadDriver:p,driverKit:a,blockUpdateWatcher:new Qo(u,i,{minDelay:o.devBlockUpdateRecheckInterval,http:c}),quickJs:await ce.getQuickJS()},v=new S.WatchableValue([]),w=await Or(e,n,v,h);return new He(h,a,a.signer,n,v,w.tree,u,w.computable)}}async function os(s,e={}){const t={pingCheckDurationMs:1e4,pingTimeoutMs:3e3,maxPingsPerSecond:50,httpTimeoutMs:3e3,blockRegistryDurationMs:5e3,maxRegistryChecksPerSecond:1,blockRegistryUrl:"https://blocks.pl-open.science/v2/overview.json",autoUpdateCdnDurationMs:5e3,maxAutoUpdateCdnChecksPerSecond:1,autoUpdateCdnUrl:"https://cdn.platforma.bio/software/platforma-desktop-v2/windows/amd64/latest.yml",...e},r={plPings:[],blockRegistryChecks:[],autoUpdateCdnChecks:[]},o=l.plAddressToConfig(s,{defaultRequestTimeout:t.pingTimeoutMs});r.plPings=await ke(t.pingCheckDurationMs,t.maxPingsPerSecond,async()=>{const c=await new l.UnauthenticatedPlClient(o).ping();return JSON.stringify(c).slice(0,100)+"..."});const i=new l.UnauthenticatedPlClient(o).ll.httpDispatcher;return r.blockRegistryChecks=await ke(t.blockRegistryDurationMs,t.maxRegistryChecksPerSecond,async()=>{const{body:a,statusCode:c}=await J.request(t.blockRegistryUrl,{dispatcher:i,headersTimeout:t.httpTimeoutMs,bodyTimeout:t.httpTimeoutMs}),u=await a.text();return{statusCode:c,beginningOfBody:u.slice(0,100)+"..."}}),r.autoUpdateCdnChecks=await ke(t.autoUpdateCdnDurationMs,t.maxAutoUpdateCdnChecksPerSecond,async()=>{const{body:a,statusCode:c}=await J.request(t.autoUpdateCdnUrl,{dispatcher:i,headersTimeout:t.httpTimeoutMs,bodyTimeout:t.httpTimeoutMs}),u=await a.text();return{statusCode:c,beginningOfBody:u.slice(0,100)+"..."}}),ss(r,s,t)}async function ke(s,e,t){const r=Ee(),o=[];for(;pt(r)<s;){const n=Ee();let i;try{i={ok:!0,value:await t()}}catch(u){i={ok:!1,error:u}}const a=pt(n);o.push({elapsedMs:a,response:i});const c=1e3/e-a;c>0&&await ht.setTimeout(c)}return o}function ss(s,e,t){const r=s.plPings.filter(i=>i.response.ok),o=s.plPings.filter(i=>!i.response.ok),n=[...new Set(r.map(i=>JSON.stringify(i.response.value)))];return`
|
|
2
2
|
Network report:
|
|
3
3
|
pl endpoint: ${e};
|
|
4
4
|
options: ${JSON.stringify(t,null,2)}.
|
|
5
5
|
|
|
6
|
-
Platforma pings: ${
|
|
6
|
+
Platforma pings: ${Ce(s.plPings)}
|
|
7
7
|
|
|
8
|
-
Block registry responses: ${
|
|
8
|
+
Block registry responses: ${Ce(s.blockRegistryChecks)}
|
|
9
9
|
|
|
10
|
-
Auto-update CDN responses: ${
|
|
10
|
+
Auto-update CDN responses: ${Ce(s.autoUpdateCdnChecks)}
|
|
11
11
|
|
|
12
12
|
Block registry dumps:
|
|
13
13
|
${JSON.stringify(s.blockRegistryChecks,null,2)}
|
|
@@ -20,11 +20,11 @@ ${JSON.stringify(o,null,2)}
|
|
|
20
20
|
|
|
21
21
|
Platforma pings success dump examples:
|
|
22
22
|
${JSON.stringify(n,null,2)}
|
|
23
|
-
`}function
|
|
23
|
+
`}function Ce(s){const e=s.filter(o=>o.response.ok),{mean:t,median:r}=ns(s);return`
|
|
24
24
|
total: ${s.length};
|
|
25
25
|
successes: ${e.length};
|
|
26
26
|
errors: ${s.length-e.length};
|
|
27
27
|
mean in ms: ${t};
|
|
28
28
|
median in ms: ${r};
|
|
29
|
-
`}function
|
|
29
|
+
`}function ns(s){const e=s.map(o=>o.elapsedMs),t=e.reduce((o,n)=>o+n)/e.length;let r;if(e.length>0){const o=Math.floor(e.length/2);r=e.length%2?e[o]:(e[o-1]+e[o])/2}return{mean:t,median:r}}function Ee(){return Date.now()}function pt(s){return Ee()-s}exports.BlockPackRegistry=lr;exports.CentralBlockRegistry=dr;exports.DefaultDriverKitOpsPaths=_e;exports.DefaultDriverKitOpsSettings=Ge;exports.DefaultMiddleLayerOpsPaths=$t;exports.DefaultMiddleLayerOpsSettings=Kt;exports.FrontendFromFolderResourceType=Ue;exports.FrontendFromUrlResourceType=Me;exports.MiddleLayer=He;exports.Project=fe;exports.TengoTemplateGet=St;exports.TengoTemplateGetRegistry=kt;exports.TengoTemplateGetTemplate=Pt;exports.TengoTemplateGetTemplateURI=Ct;exports.TengoTemplatePack=Rt;exports.TengoTemplatePackConvert=Ft;exports.TengoTemplatePackConvertTemplate=Bt;exports.TengoTemplatePackConvertTemplatePack=Ot;exports.V1CentralDevSnapshotRegistry=gr;exports.V1CentralRegistry=pr;exports.V2RegistryProvider=vt;exports.checkNetwork=os;exports.createRenderTemplate=Je;exports.getDevV1PacketMtime=Ve;exports.getDevV2PacketMtime=pe;exports.initDriverKit=Gt;exports.loadTemplate=ge;exports.prepareTemplateSpec=Dt;Object.keys(C).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>C[s]})});Object.keys(Q).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>Q[s]})});Object.keys(l).forEach(s=>{s!=="default"&&!Object.prototype.hasOwnProperty.call(exports,s)&&Object.defineProperty(exports,s,{enumerable:!0,get:()=>l[s]})});
|
|
30
30
|
//# sourceMappingURL=index.js.map
|