This repository was archived by the owner on Mar 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy patharcs.min.js
More file actions
34 lines (32 loc) · 25.2 KB
/
Copy patharcs.min.js
File metadata and controls
34 lines (32 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var st=Object.defineProperty;var kt=(s,t,e)=>t in s?st(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Dt=(s,t)=>()=>(s&&(t=s(s=0)),t);var rt=(s,t)=>{for(var e in t)st(s,e,{get:t[e],enumerable:!0})};var w=(s,t,e)=>(kt(s,typeof t!="symbol"?t+"":t,e),e);var wt={};rt(wt,{Particle:()=>T,ParticleApi:()=>Z});var xt,St,vt,le,Y,he,pe,M,X,ue,B,fe,Z,de,T,Pt=Dt(()=>{({create:xt,assign:St,keys:vt,values:le,entries:Y,defineProperty:he,setPrototypeOf:pe}=Object),M=globalThis.scope??{},{log:X,timeout:ue}=M,B=()=>xt(null),fe=new class{get empty(){return this.length===0}get data(){return this}get pojo(){return this.data}get json(){return JSON.stringify(this.pojo)}get pretty(){return JSON.stringify(this.pojo,null," ")}get keys(){return vt(this.data)}get length(){return vt(this.data).length}get values(){return le(this.data)}get entries(){return Y(this.data)}set(s,t){this.data[s]=t}setByIndex(s,t){this.data[this.keys[s]]=t}add(...s){s.forEach(t=>this.data[M.makeKey()]=t)}push(...s){this.add(...s)}remove(s){Y(this.data).find(([t,e])=>{if(e===s)return delete this.data[t],!0})}has(s){return this.data[s]!==void 0}get(s){return this.getByKey(s)}getByKey(s){return this.data[s]}getByIndex(s){return this.data[this.keys[s]]}delete(s){delete this.data[s]}deleteByIndex(s){delete this.data[this.keys[s]]}assign(s){St(this.data,s)}map(s){return this.values.map(s)}toString(){return this.pretty}},Z=class{get template(){return null}shouldUpdate(t,e){return!0}async update(t,e,r){return null}shouldRender(t,e){return!0}render(t,e){return null}},de=s=>{let t=s;return{get:()=>t,set:e=>t=e}},T=class{pipe;impl;internal;constructor(t,e,r){this.pipe=e,this.impl=xt(t),he(this,"internal",de(B())),this.internal.$busy=0,this.internal.beStateful=!0,this.internal.state=B()}get log(){return this.pipe?.log||X}get template(){return this.impl?.template}get config(){return{template:this.template}}set inputs(t){this.internal.inputs=t,this.invalidateInputs()}get inputs(){return this.internal.inputs}get state(){return this.internal.state}async service(t){return this.pipe?.service?.(t)}invalidateInputs(){this.invalidate()}invalidate(){this.internal.validator||(this.internal.validator=ue(this.validate.bind(this),1))}async(t){return Promise.resolve().then(t.bind(this))}async validate(){if(this.internal.validator){try{this.internal.$validateAfterBusy=this.internal.$busy,this.internal.$busy||(this.internal.beStateful||(this.internal.state=B()),this.internal.inputs=this.validateInputs(),await this.maybeUpdate())}catch(t){X.error(t)}this.internal.validator=null}}validateInputs(){let t=St(B(),this.inputs);return Y(t).forEach(([e,r])=>{r&&typeof r=="object"&&(Array.isArray(r)||(r=pe({...r},fe)),t[e]=r)}),t}implements(t){return typeof this.impl?.[t]=="function"}async maybeUpdate(){await this.checkInit()&&(this.canUpdate()||this.outputData(null),await this.shouldUpdate(this.inputs,this.state)&&this.update())}async checkInit(){return this.internal.initialized||(this.internal.initialized=!0,this.implements("initialize")&&await this.asyncMethod(this.impl.initialize)),!0}canUpdate(){return this.implements("update")}async shouldUpdate(t,e){return!this.impl?.shouldUpdate||await this.impl.shouldUpdate(t,e)!==!1}update(){this.asyncMethod(this.impl?.update)}outputData(t){this.pipe?.output?.(t,this.maybeRender())}maybeRender(){if(this.template){let{inputs:t,state:e}=this.internal;if(this.impl?.shouldRender?.(t,e)!==!1)return this.implements("render")?this.impl.render(t,e):{...t,...e}}}async handleEvent({handler:t,data:e}){let r=this.impl?.[t];r&&(this.internal.inputs.eventlet=e,await this.asyncMethod(r.bind(this.impl),{eventlet:e}),this.internal.inputs.eventlet=null)}async asyncMethod(t,e){if(t){let{inputs:r,state:i}=this.internal,a={service:async c=>this.service(c),invalidate:()=>this.invalidate(),output:async c=>this.outputData(c)},n=t.bind(this.impl,r,i,{...a,...e});this.outputData(await this.try(n)),!this.internal.$busy&&this.internal.$validateAfterBusy&&this.invalidate()}}async try(t){this.internal.$busy++;try{return await t()}catch(e){X.error(e)}finally{this.internal.$busy--}}};M.harden(globalThis);M.harden(T)});var p=class{listeners={};getEventListeners(t){return this.listeners[t]||(this.listeners[t]=[])}fire(t,...e){let r=this.getEventListeners(t);r?.forEach&&r.forEach(i=>i(...e))}listen(t,e,r){return this.getEventListeners(t).push(e),e._name=r||"(unnamed listener)",e}unlisten(t,e){let r=this.getEventListeners(t),i=typeof e=="string"?r.findIndex(a=>a._name===e):r.indexOf(e);i>=0?r.splice(i,1):console.warn("failed to unlisten from",t)}};var it=["log","group","groupCollapsed","groupEnd","dir"],at=["warn","error"];var{fromEntries:ot}=Object,nt=(s,t,e,r,i="log")=>{if(!s)return()=>{};if(i==="dir")return console.dir.bind(console);let a=`background: ${e||"gray"}; color: ${r||"white"}; padding: 1px 6px 2px 7px; border-radius: 6px 0 0 6px;`;return console[i].bind(console,`%c${t}`,a)},o=(s,t,e="",r="")=>{let i=ot(it.map(h=>[h,nt(s,t,e,r,h)])),a=ot(at.map(h=>[h,nt(!0,t,e,r,h)])),n={...i,...a},c=n.log;return Object.assign(c,n),c};o.flags=globalThis.config?.logFlags||{};var Bt=s=>o(o.flags.arc,`Arc (${s})`,"slateblue"),{assign:Tt,keys:z,entries:ct,create:Mt}=Object,P=s=>Object.values(s),U=()=>Mt(null),O=class extends p{log;id;meta;stores;hosts;surface;composer;hostService;constructor(t,e,r){super(),this.id=t,this.meta=e,this.surface=r,this.hosts=U(),this.stores=U(),this.log=Bt(t)}async addHost(t,e){return await this.ensureComposer(),this.hosts[t.id]=t,t.arc=this,this.updateHost(t),t}async ensureComposer(){!this.composer&&this.surface&&(this.composer=await this.surface.createComposer("root"),this.composer.onevent=this.onevent.bind(this))}rerender(){P(this.hosts).forEach(t=>t.rerender())}removeHost(t){this.hosts[t]?.detach(),delete this.hosts[t]}addStore(t,e){e&&!this.stores[t]&&(this.stores[t]=e,e.listen("change",()=>this.storeChanged(t,e),this.id))}removeStore(t){let e=this.stores[t];e&&e.unlisten("change",this.id),delete this.stores[t]}storeChanged(t,e){this.log(`storeChanged: "${t}"`);let r=i=>i&&i.some(a=>P(a)[0]==t||z(a)[0]==t);P(this.hosts).forEach(i=>{let a=i.meta?.inputs;(a==="*"||r(a))&&(this.log(`host "${i.id}" has interest in "${t}"`),this.updateHost(i))}),this.fire("store-changed",t)}updateParticleMeta(t,e){let r=this.hosts[t];r.meta=e,this.updateHost(r)}updateHost(t){t.inputs=this.computeInputs(t)}computeInputs(t){let e=U(),r=t.meta?.inputs;if(r==="*")ct(this.stores).forEach(([i,a])=>e[i]=a.pojo);else{let i=t.meta?.staticInputs;Tt(e,i),r&&(r.forEach(a=>this.computeInput(ct(a)[0],e)),this.log(`computeInputs(${t.id}) =`,e))}return e}computeInput([t,e],r){let i=e||t,a=this.stores[i];a?r[t]=a.pojo:this.log.warn(`computeInput: "${i}" (bound to "${t}") not found`)}assignOutputs({id:t,meta:e},r){let i=z(r);e?.outputs&&i.length&&(i.forEach(a=>this.assignOutput(a,r[a],e.outputs)),this.log(`[end][${t}] assignOutputs:`,r))}assignOutput(t,e,r){if(e!==void 0){let i=this.findOutputByName(r,t)||t,a=this.stores[i];a?(this.log(`assignOutputs: "${t}" is dirty, updating Store "${i}"`,e),a.data=e):r?.[t]&&this.log.warn(`assignOutputs: no "${i}" store for output "${t}"`)}}findOutputByName(t,e){let r=t?.find(i=>z(i)[0]===e);if(r)return P(r)[0]}async render(t){this.composer&&this.composer.render(t)}onevent(t,e){let r=this.hosts[t];r&&r.handleEvent(e)}async service(t,e){let r=await this.surface?.service(e);return r===void 0&&(r=this.hostService?.(t,e)),r}};var At=(s,t)=>{let e=t;if(t){if(Array.isArray(t)){Array.isArray(s)||(s=[]);for(let i=0;i<t.length;i++){let a=t[i];s[i]!==a&&(s[i]=a)}let r=s.length-t.length;r>0&&s.splice(t.length,r)}else if(typeof t=="object"){e=s&&typeof s=="object"?s:Object.create(null);let r={};Object.keys(t).forEach(i=>{e[i]=t[i],r[i]=!0}),Object.keys(e).forEach(i=>{r[i]||delete e[i]})}}return e},zt=(s,t)=>{if(t==null)return null;if(typeof t=="object"){let e=s&&typeof s=="object"?s:Object.create(null);return Object.keys(t).forEach(r=>e[r]=t[r]),e}return t};function m(s){if(s){if(Array.isArray(s))return s.map(t=>m(t));if(typeof s=="object"){let t=Object.create(null);return Object.entries(s).forEach(([e,r])=>{t[e]=m(r)}),t}else return s}else return s}var u=(s,t)=>{let e=typeof s;if(e!==typeof t)return!1;if(e==="object"&&s&&t){let r=Object.getOwnPropertyNames(s),i=Object.getOwnPropertyNames(t);return r.length==i.length&&!r.some(a=>!u(s[a],t[a]))}return s===t},lt=s=>s===void 0?null:(s&&typeof s=="object"&&Object.getOwnPropertyNames(s).forEach(e=>{let r=s[e];r===void 0?delete s[e]:lt(r)}),s);var{floor:ht,pow:Ut,random:L}=Math,Lt=s=>ht((1+L()*9)*Ut(10,s-1)),j=s=>ht(L()*s),N=s=>s[j(s.length)],Nt=s=>Boolean(L()<s);var K=o(o.flags.decorator,"Decorator","plum"),{values:Rt,entries:pt}=Object,R={},E={setOpaqueData(s,t){return R[s]=t,s},getOpaqueData(s){return R[s]},processOutputModel({privateData:s}){if(s&&s.__privateKey){let e=Object.values(R).pop(),{_privateKey:r,...i}=s;e.privateData=i}},maybeDecorateModel(s,t){return s&&!Array.isArray(s)&&Rt(s).forEach(e=>{e&&typeof e=="object"&&(e.models?(K("applying decorator(s) to list:",e),this.maybeDecorateItem(e,t)):(s?.filter||s?.decorator||s?.collateBy)&&(K("scanning for lists in sub-model:",e),this.maybeDecorateModel(e,t)))}),s},maybeDecorateItem(s,t){let e=typeof s.models=="string"?this.getOpaqueData(s.models):s.models;e&&(e=Kt(e,s.decorator,t),e=It(e,s.filter,t.impl),e=Ht(e,s),s.models=e)}},Kt=(s,t,e)=>{t=e.impl[t]??t;let{inputs:r,state:i}=e.internal;if(t){let a=Object.freeze(m(r)),n=Object.freeze(m(i));s=s.map((c,h)=>{c.privateData=c.privateData||{};let S=Object.freeze(m(c)),l=t(S,a,n);return c.privateData={...l.privateData,__privateKey:h},{...l,...c}}),s.sort(qt("sortKey")),K("decoration was performed")}return s},It=(s,t,e)=>(t=e[t]??t,t&&s&&(s=s.filter(t)),s),Ht=(s,t)=>(pt(t).forEach(([e,r])=>{if(r?.collateBy){let i=Wt(s,r.collateBy);s=Jt(i,e,r.$template)}}),s),qt=s=>(t,e)=>_t(String(t[s]).toLowerCase(),String(e[s]).toLowerCase()),_t=(s,t)=>s<t?-1:s>t?1:0,Wt=(s,t)=>{let e={};return s.forEach(r=>{let i=r[t];i&&(e[i]||(e[i]=[])).push(r)}),e},Jt=(s,t,e)=>pt(s).map(([r,i])=>({key:r,[t]:{models:i,$template:e},single:i.length===1,...i?.[0]}));var{entries:ut,keys:Vt}=Object,Gt=s=>o(o.flags.host,`Host (${s})`,N(["#5a189a","#51168b","#48137b","#6b2fa4","#7b46ae","#3f116c"])),y=class extends p{arc;id;lastOutput;lastPacket;lastRenderModel;log;meta;particle;constructor(t){super(),this.log=Gt(t),this.id=t}onevent(t){this.arc?.onevent(t)}installParticle(t,e){this.particle&&this.detachParticle(),t&&(this.particle=t,this.meta=e||this.meta)}get container(){return this.meta?.container||"root"}detach(){this.detachParticle(),this.arc=null}detachParticle(){this.particle&&(this.render({$clear:!0}),this.particle=null,this.meta=null)}async service(t){return t?.decorate?E.maybeDecorateModel(t.model,this.particle):this.arc?.service(this,t)}output(t,e){t&&(E.processOutputModel(t),this.lastOutput=t,this.arc?.assignOutputs(this,t)),this.template&&(E.maybeDecorateModel(e,this.particle),this.log(e),this.lastRenderModel=e,this.render(e))}rerender(){this.lastRenderModel&&this.render(this.lastRenderModel)}render(t){let{id:e,container:r,template:i}=this,n={id:e,container:r,content:{model:t,template:i}};this.arc?.render(n),this.lastPacket=n}set inputs(t){if(this.particle&&t){let e=this.particle.internal.inputs;this.dirtyCheck(t,e,this.lastOutput)?(this.particle.inputs={...this.meta?.staticInputs,...t},this.fire("inputs-changed")):this.log("inputs are uninteresting, skipping update")}}dirtyCheck(t,e,r){let i=([a,n])=>r?.[a]&&!u(r[a],n)||!u(e?.[a],n);return!e||ut(t).length!==this.lastInputsLength(e)||ut(t).some(i)}lastInputsLength(t){return Vt(t).filter(e=>!this.meta?.staticInputs?.[e]&&e!=="eventlet").length}get config(){return this.particle?.config}get template(){return this.config?.template}invalidate(){this.particle?.invalidate()}handleEvent(t){return this.particle?.handleEvent(t)}};var{create:Qt,keys:Xt}=Object,{stringify:ft,parse:dt}=JSON,I=class extends p{privateData;constructor(){super()}setPrivateData(t){this.privateData=t}set data(t){this.setPrivateData(t)}get data(){return this.privateData}toString(){return this.pretty}get isObject(){return this.data&&typeof this.data=="object"}get pojo(){return this.data}get json(){return ft(this.data)}set json(t){let e=null;try{e=dt(t)}catch{}this.data=e}get pretty(){let t={},e=this.pojo;return Xt(e).sort().forEach(r=>t[r]=e[r]),ft(t,null," ")}},H=class extends I{change(t){t(this),this.doChange()}doChange(){this.fire("change",this),this.onChange(this)}onChange(t){}set data(t){this.change(e=>e.setPrivateData(t))}get data(){return this.privateData}set(t,e){this.data||this.setPrivateData(Qt(null)),e!==void 0?this.change(r=>r.data[t]=e):this.delete(t)}delete(t){this.change(e=>delete e.data[t])}},q=class extends H{meta;constructor(t){super(),this.meta={...t}}toString(){return`${JSON.stringify(this.meta,null," ")}, ${this.pretty}`}get tags(){return this.meta.tags??(this.meta.tags=[])}is(...t){return t.every(e=>this.tags.includes(e))}isCollection(){return this.meta.type?.[0]==="["}shouldPersist(){return this.is("persisted")&&!this.is("volatile")}async doChange(){return this.persist(),super.doChange()}async persist(){}async restore(){}save(){return this.json}load(t,e){let r=e;try{t&&(r=dt(t))}catch{}r!==void 0&&(this.data=r)}},C=class extends q{};var F=(s,t,e)=>{s=s||2,t=t||2,e=e||"-";let r=Math.pow(10,t-1),i=Math.pow(10,t)-r,a=[];for(let n=0;n<s;n++)a.push(`${j(i-r)+r}`);return a.join(e)};var mt=o(o.flags.runtime,"runtime","#873600"),gt={},_={},{keys:Yt}=Object,$=class extends p{log;uid;nid;arcs;stores;peers;shares;endpoint;network;surfaces;persistor;prettyUid;constructor(t){t=t||"user",super(),this.arcs={},this.surfaces={},this.stores={},this.peers=new Set,this.shares=new Set,this.setUid(t),this.log=o(o.flags.runtime,`runtime:[${this.prettyUid}]`,"#873600")}setUid(t){this.uid=t,this.nid=`${t}:${F(1,2)}`,this.prettyUid=t.substring(0,t.indexOf("@")+1)||t}async bootstrapArc(t,e,r,i){let a=new O(t,e,r);return a.hostService=this.serviceFactory(i),await this.addArc(a),a}serviceFactory(t){return async(e,r)=>t.handle(this,e,r)}async bootstrapParticle(t,e,r){let i=new y(e);await this.marshalParticle(i,r);let a=t.addHost(i);return mt("bootstrapped particle",e),a}addSurface(t,e){this.surfaces[t]=e}getSurface(t){return this.surfaces[t]}addArc(t){let{id:e}=t;if(e&&!this.arcs[e])return this.arcs[e]=t;throw`arc has no id, or id "${e}" is already in use`}removeArc(t){let{id:e}=t;if(!e||!this.arcs[e])throw e?`id "${e}" is not in use`:"arc has no id";delete this.arcs[e]}async marshalParticle(t,e){let r=await this.createParticle(t,e.kind);t.installParticle(r,e)}async installParticle(t,e,r){if(this.log("installParticle",r,e,t.id),r=r||F(),t.hosts[r]){let a=1;for(;t.hosts[`${r}-${a}`];a++);r=`${r}-${a}`}let i=new y(r);return await this.marshalParticle(i,e),t.addHost(i),i}addStore(t,e){e.marshal&&e.marshal(this),e.persist=async()=>this.persistStore(t,e),e.restore=async()=>this.restoreStore(t,e);let r=`${this.nid}:${t}-changed`,i=this.storeChanged.bind(this,t);e.listen("change",i,r),this.stores[t]=e,this.maybeShareStore(t)}async persistStore(t,e){if(e.shouldPersist())return this.log(`persistStore "${t}"`),this.persistor.persist?.(t,e)}async restoreStore(t,e){if(e.shouldPersist())return this.log(`restoreStore "${t}"`),this.persistor.restore?.(t)}storeChanged(t,e){this.log("storeChanged",t),this.network?.invalidatePeers(t),this.onStoreChange(t,e),this.fire("store-changed",{storeId:t,store:e})}onStoreChange(t,e){}do(t,e){e(this.stores[t])}removeStore(t){this.do(t,e=>{e?.unlisten("change",`${this.nid}:${t}-changed`)}),delete this.stores[t]}maybeShareStore(t){this.do(t,e=>{e?.is("shared")&&this.shareStore(t)})}addPeer(t){this.peers.add(t),[...this.shares].forEach(e=>this.maybeShareStoreWithPeer(e,t))}shareStore(t){this.shares.add(t),[...this.peers].forEach(e=>this.maybeShareStoreWithPeer(t,e))}maybeShareStoreWithPeer(t,e){this.do(t,r=>{let i=this.uid.replace(/\./g,"_");(!r.is("private")||e.startsWith(i))&&this.shareStoreWithPeer(t,e)})}shareStoreWithPeer(t,e){this.network?.shareStore(t,e)}async createParticle(t,e){try{return(await this.marshalParticleFactory(e))(t)}catch(r){mt.error(`createParticle(${e}):`,r)}}async marshalParticleFactory(t){return gt[t]??this.lateBindParticle(t)}lateBindParticle(t){return $.registerParticleFactory(t,$?.particleIndustry(t,$.particleOptions))}static registerParticleFactory(t,e){return gt[t]=e}requireStore(t){let e=this.stores[t.name];return e||(e=this.createStore(t),this.addStore(t.name,e)),e}createStore(t){let e=Yt(_).find(i=>t.tags?.includes?.(i)),r=_[String(e)]||C;return new r(t)}static registerStoreClass(t,e){_[t]=e}},f=$;w(f,"securityLockdown"),w(f,"particleIndustry"),w(f,"particleOptions");var W=o(o.flags.recipe,"flan","violet"),{entries:Zt,create:te}=Object,b=class{stores;particles;slots;meta;constructor(t){this.stores=[],this.particles=[],this.slots=[],this.meta=te(null),t&&this.parse(t)}parse(t){let e=this.normalize(t);return this.parseSlotSpec(e,"root",""),this}normalize(t){if(typeof t!="object")throw Error("recipe must be an Object");return t}parseSlotSpec(t,e,r){for(let i in t)switch(i){case"$meta":this.meta={...this.meta,...t.$meta};break;case"$stores":this.parseStoresNode(t.$stores);break;default:{let a=r?`${r}#${e}`:e;this.parseParticleSpec(a,i,t[i]);break}}}parseStoresNode(t){for(let e in t)this.parseStoreSpec(e,t[e])}parseStoreSpec(t,e){if(this.stores.find(i=>i.name===t)){W("duplicate store name");return}let r={name:t,type:e.$type,tags:e.$tags,value:e.$value};this.stores.push(r)}parseParticleSpec(t,e,r){if(!r.$kind)throw W.warn('parseParticleSpec: malformed spec has no "kind":',r),Error();if(this.particles.find(i=>i.id===e)){W("duplicate particle name");return}this.particles.push({id:e,container:t,spec:r}),r.$slots&&this.parseSlotsNode(r.$slots,e)}parseSlotsNode(t,e){Zt(t).forEach(([r,i])=>this.parseSlotSpec(i,r,e))}};function J(s,t){for(let e in t)if(s[e]!==t[e])return!1;return!0}var V=o(o.flags.recipe,"StoreCook","#99bb15"),{values:ee}=Object,se=(s,t)=>ee(s.stores).filter(e=>J(e?.meta,t)),re=(s,{name:t,type:e})=>se(s,{name:t,type:e})?.[0],k=class{static async execute(t,e,r){return this.forEachStore(this.realizeStore,t,e,r)}static async evacipate(t,e,r){return this.forEachStore(this.derealizeStore,t,e,r)}static async forEachStore(t,e,r,i){return Promise.all(i.map(a=>t.call(this,e,r,a)))}static async realizeStore(t,e,r){let i=this.constructMeta(t,e,r),a=i?.value,n=re(t,i);if(n)V(`realizeStore: mapped "${r.name}" to "${n.meta.name}"`);else if(n=t.createStore(i),V(`realizeStore: created "${i.name}"`),t.addStore(i.name,n),n.shouldPersist()){let c=await n.restore();a=c===void 0?a:c}a!==void 0&&(V("setting data to:",a),n.data=a),e.addStore(i.name,n)}static async derealizeStore(t,e,r){t.removeStore(r.$name),e.removeStore(r.$name)}static constructMeta(t,e,r){let i={...r,arcid:e.id,uid:t.uid};return{...i,owner:i.uid,shareid:`${i.name}:${i.arcid}:${i.uid}`}}};var ie=o(o.flags.recipe,"ParticleCook","#5fa530"),v=class{static async execute(t,e,r){for(let i of r)await this.realizeParticle(t,e,i)}static async realizeParticle(t,e,r){ie("realizedParticle:",r.id);let i=this.specToMeta(r.spec);return i.container||=r.container,t.bootstrapParticle(e,r.id,i)}static specToMeta(t){t.$bindings&&console.warn(`Particle '${t.$kind}' spec contains deprecated $bindings property (${JSON.stringify(t.$bindings)})`);let{$kind:e,$container:r,$staticInputs:i}=t,a=this.formatBindings(t.$inputs),n=this.formatBindings(t.$outputs);return{kind:e,staticInputs:i,inputs:a,outputs:n,container:r}}static formatBindings(t){return t?.map?.(e=>typeof e=="string"?{[e]:e}:e)}static async evacipate(t,e,r){return Promise.all(r.map(i=>this.derealizeParticle(t,e,i)))}static async derealizeParticle(t,e,r){e.removeHost(r.id)}};var x=o(o.flags.recipe,"Chef","#087f23"),yt=class{static async execute(t,e,r){if(r instanceof Promise){x.error("`arc` must be an Arc, not a Promise. Make sure `boostrapArc` is awaited.");return}x("|-->...| executing recipe: ",t.$meta??"");let i=new b(t);await k.execute(e,r,i.stores),await v.execute(e,r,i.particles),r.meta={...r.meta,...i.meta},x("|...-->| recipe complete: ",t.$meta??"")}static async evacipate(t,e,r){x("|-->...| evacipating recipe: ",t.$meta);let i=new b(t);await v.evacipate(e,r,i.particles),x("|...-->| recipe evacipated: ",t.$meta)}static async executeAll(t,e,r){for(let i of t)await this.execute(i,e,r)}static async evacipateAll(t,e,r){return Promise.all(t?.map(i=>this.evacipate(i,e,r)))}};var $t=class{map;constructor(s){this.map={},this.setRoot(s)}add(s){Object.assign(this.map,s||{})}resolve(s){let t=s.split("/"),e=t.shift();return[this.map[e]||e,...t].join("/")}setRoot(s){s.length&&s[s.length-1]==="/"&&(s=s.slice(0,-1)),this.add({$root:s,$arcs:s})}getAbsoluteHereUrl(s,t){let e=s.url.split("/").slice(0,-(t??1)).join("/");if(globalThis?.document){let r=document.URL;r[r.length-1]!=="/"&&(r=`${r.split("/").slice(0,-1).join("/")}/`);let i=new URL(e,r).href;return i[i.length-1]==="/"&&(i=i.slice(0,-1)),i}else return e}},ae=import.meta.url.split("/").slice(0,-3).join("/"),d=globalThis.Paths=new $t(ae);d.add(globalThis.config?.paths);var G=o(o.flags.code,"code","gold"),oe="$arcs/js/core/Particle.js",D=async s=>{if(!D.source){let t=d.resolve(s||oe);G("particle base code path: ",t);let r=await(await fetch(t)).text()+`
//# sourceURL=`+t+`
`;D.source=r.replace(/export /g,"")}return D.source};D.source=null;var bt=async(s,t)=>{let e=t?.code||await ne(s);return e.slice(e.indexOf("({"))},ne=async s=>{if(s)return await ce(s);G.error("fetchParticleCode: empty 'kind'")},ce=async s=>{let t=Q(s);try{return await(await fetch(t)).text()}catch{G.error(`could not locate implementation for particle "${s}" [${t}]`)}},Q=s=>s?(!"$./".includes(s[0])&&!s.includes("://")&&(s=`$library/${s}`),s?.split("/").pop().includes(".")||(s=`${s}.js`),d.resolve(s)):"404";var A=o(o.flags.isolation,"vanilla","goldenrod"),Ot=s=>s;globalThis.harden=Ot;globalThis.scope={harden:Ot};var me=()=>`i${Math.floor((1+Math.random()*9)*1e14)}`,ge=async(s,t)=>new Promise(e=>setTimeout(()=>e(s()),t)),ye=s=>{try{A(u);let e={...{log:A,resolve:jt,html:Et,makeKey:me,deepEqual:u,timeout:ge},...s?.injections};Object.assign(globalThis.scope,e),Object.assign(globalThis,e)}finally{}},jt=d.resolve.bind(d),Et=(s,...t)=>`${s[0]}${t.map((e,r)=>`${e}${s[r+1]}`).join("")}`.trim(),$e=async(s,t)=>{let{Particle:e}=await Promise.resolve().then(()=>(Pt(),wt)),r=await be(s,t),i=Se(s),a={log:i,resolve:jt,html:Et,...t?.injections},n=r(a);return h=>{let S={log:i,output:h.output.bind(h),service:h.service.bind(h)};return new e(n,S,!0)}},be=async(s,t)=>{let e=await bt(s,t),r=(0,eval)(e);return typeof r=="object"&&(r=ve(r,s),A(`repackaged factory:
`,r)),globalThis.harden(r)},ve=(s,t)=>{let{constNames:e,rewriteConsts:r,funcNames:i,rewriteFuncs:a}=xe(s),n=`{${[...e,...i]}}`,c=`
({log, ...utils}) => {
// protect utils
globalThis.harden(utils);
// these are just handy
const {assign, keys, entries, values, create} = Object;
// declarations
${[...r,...a].join(`
`)}
// hardened Object (map) of declarations,
// suitable to be a prototype
return globalThis.harden(${n});
// name the file for debuggers
//# sourceURL=sandbox/${Q(t).split("/").pop()}
};
`;return A(`rewritten:
`,c),(0,eval)(c)},xe=s=>{let t=Object.entries(s),e=([l,g])=>typeof g=="function",r=([l,g])=>l=="harden"||l=="globalThis",i=t.filter(l=>e(l)&&!r(l)),a=i.map(([l,g])=>{let et=g?.toString?.()??"",Ct=et.includes("async"),Ft=et.replace("async ","").replace("function ","");return`${Ct?"async":""} function ${Ft};`}),n=i.map(([l])=>l),c=t.filter(l=>!e(l)&&!r(l)),h=c.map(([l,g])=>`const ${l} = \`${g}\`;`);return{constNames:c.map(([l])=>l),rewriteConsts:h,funcNames:n,rewriteFuncs:a}},Se=s=>{let t=o(o.flags.particles,s,"#002266");return(e,...r)=>{let a=(e?.stack?.split(`
`)?.slice(1,2)||new Error().stack?.split(`
`).slice(2,3)).map(n=>n.replace(/\([^()]*?\)/,"").replace(/ \([^()]*?\)/,"").replace("<anonymous>, <anonymous>","").replace("Object.","").replace("eval at :","").replace(/\(|\)/g,"").replace(/\[[^\]]*?\] /,"").replace(/at (.*) (\d)/,'at "$1" $2')).reverse().join(`
`).trim();e?.message?t.error(e.message,...r,`(${a})`):t(e,...r,`(${a})`)}};f.particleIndustry=$e;f.securityLockdown=ye;var tt={};rt(tt,{PathMapper:()=>$t,Paths:()=>d,arand:()=>N,async:()=>Oe,asyncTask:()=>je,computeAgeString:()=>we,debounce:()=>Pe,deepCopy:()=>m,deepEqual:()=>u,deepUndefinedToNull:()=>lt,irand:()=>j,key:()=>Lt,logFactory:()=>o,makeId:()=>F,matches:()=>J,prob:()=>Nt,shallowMerge:()=>zt,shallowUpdate:()=>At});var we=(s,t)=>{let e=Math.round((t-s)/1e3);if(isNaN(e))return"\u2022";let r="";return e<60?(e>1&&(r="s"),`${e} second${r} ago`):(e=Math.round(e/60),e<60?(e>1&&(r="s"),`${e} minute${r} ago`):(e=Math.round(e/60),e<24?(e>1&&(r="s"),`${e} hour${r} ago`):(e=Math.round(e/24),e<30?(e>1&&(r="s"),`${e} day${r} ago`):(e=Math.round(e/30),e<12?(e>1&&(r="s"),`${e} month${r} ago`):(e=Math.round(e/12),e>1&&(r="s"),`${e} year${r} ago`)))))};var Pe=(s,t,e)=>{if(s&&clearTimeout(s),t&&e)return setTimeout(t,e)},Oe=s=>async(...t)=>{await Promise.resolve(),s(...t)},je=(s,t)=>{setTimeout(s,t??0)};var{logFactory:Rs,Paths:Ee}=tt;var Ce=import.meta.url.split("/").slice(0,-1).join("/");Ee.setRoot(Ce);export{O as Arc,yt as Chef,I as DataStore,E as Decorator,p as EventEmitter,y as Host,b as Parser,v as ParticleCook,Ee as Paths,f as Runtime,C as Store,k as StoreCook,ne as fetchParticleCode,ye as initVanilla,Rs as logFactory,ce as maybeFetchParticleCode,Q as pathForKind,D as requireParticleBaseCode,bt as requireParticleImplCode,tt as utils};
/**
* @license
* Copyright 2022 Google LLC
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
//# sourceMappingURL=arcs.min.js.map