\n * ```\n */\n get template() {\n return null;\n }\n /**\n * shouldUpdate returns a boolean that indicates if runtime should update\n * when inputs or state change.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if updates should be allowed.\n */\n shouldUpdate(inputs, state) {\n return true;\n }\n /**\n * Update is called anytime an input to the particle changes.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * Inputs are the stores the particle is bound to.\n * State is an object that can be changed and passed to sub-functions.\n * Tools allow the particle to perform supervised activities -\n * for example services are a tool.\n *\n * The update function can return an object containing the new desired\n * value(s) for the stores. For example, if we wanted to update the\n * `Person` and `Address` stores we would return:\n *\n * ```\n * return {\n * Person: 'Jane Smith',\n * Address: '123 Main Street'\n * };\n * ```\n *\n * @param inputs\n * @param state\n * @param tools\n *\n * @returns [OPTIONAL] object containing store to value mappings\n */\n async update(inputs, state, tools) {\n return null;\n }\n /**\n * shouldRender returns a boolean that indicates if runtime should\n * render the template.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if the template should be re-rendered.\n */\n shouldRender(inputs, state) {\n return true;\n }\n /**\n * Render returns an object that contains the key: value pairings\n * that will be interpolated into the {@link template | template}.\n * For example, if the template contained keys `class`,\n * `hideDiv`, and `displayTxt` we could return:\n * ```\n * {\n * class: 'title`,\n * hideDiv: false,\n * displayTxt: \"My Page's Title\"\n * }\n * ```\n *\n * This functions can be overwritten to return the desired\n * values.\n *\n * @param inputs\n * @param state\n */\n render(inputs, state) {\n return null;\n }\n}\nconst privateProperty = initialValue => {\n let value = initialValue;\n return { get: () => value, set: v => value = v };\n};\nexport class Particle {\n pipe;\n impl;\n internal;\n constructor(proto, pipe, beStateful) {\n this.pipe = pipe;\n this.impl = create(proto);\n defineProperty(this, 'internal', privateProperty(nob()));\n this.internal.$busy = 0;\n //if (beStateful) {\n this.internal.beStateful = true;\n this.internal.state = nob();\n //}\n }\n get log() {\n return this.pipe?.log || log;\n }\n get template() {\n return this.impl?.template;\n }\n get config() {\n return {\n template: this.template\n };\n }\n // set-trap for inputs, so we can do work when inputs change\n set inputs(inputs) {\n //this.log(inputs);\n this.internal.inputs = inputs;\n this.invalidateInputs();\n }\n get inputs() {\n return this.internal.inputs;\n }\n get state() {\n return this.internal.state;\n }\n async service(request) {\n return this.pipe?.service?.(request);\n }\n invalidateInputs() {\n this.invalidate();\n }\n // validate after the next microtask\n invalidate() {\n if (!this.internal.validator) {\n //this.internal.validator = this.async(this.validate);\n this.internal.validator = timeout(this.validate.bind(this), 1);\n }\n }\n // call fn after a microtask boundary\n async(fn) {\n return Promise.resolve().then(fn.bind(this));\n }\n // activate particle lifecycle\n async validate() {\n //this.log('validate');\n if (this.internal.validator) {\n // try..finally to ensure we nullify `validator`\n try {\n this.internal.$validateAfterBusy = this.internal.$busy;\n if (!this.internal.$busy) {\n // if we're not stateful\n if (!this.internal.beStateful) {\n // then it's a fresh state every validation\n this.internal.state = nob();\n }\n // inputs are immutable (changes to them are ignored)\n this.internal.inputs = this.validateInputs();\n // let the impl decide what to do\n await this.maybeUpdate();\n }\n }\n catch (e) {\n log.error(e);\n }\n // nullify validator _after_ methods so state changes don't reschedule validation\n this.internal.validator = null;\n }\n }\n validateInputs() {\n // shallow-clone our input dictionary\n const inputs = assign(nob(), this.inputs);\n // for each input, try to provide prototypical helpers\n entries(inputs).forEach(([key, value]) => {\n if (value && (typeof value === 'object')) {\n if (!Array.isArray(value)) {\n value = setPrototypeOf({ ...value }, storePrototype);\n }\n inputs[key] = value;\n }\n });\n //return harden(inputs);\n return inputs;\n }\n implements(methodName) {\n return typeof this.impl?.[methodName] === 'function';\n }\n async maybeUpdate() {\n if (await this.checkInit()) {\n if (!this.canUpdate()) {\n // we might want to render even if we don't update,\n // if we `outputData` the system will add render models\n this.outputData(null);\n }\n if (await this.shouldUpdate(this.inputs, this.state)) {\n this.update();\n }\n }\n }\n async checkInit() {\n if (!this.internal.initialized) {\n this.internal.initialized = true;\n if (this.implements('initialize')) {\n await this.asyncMethod(this.impl.initialize);\n }\n }\n return true;\n }\n canUpdate() {\n return this.implements('update');\n }\n async shouldUpdate(inputs, state) {\n //return true;\n // not implementing `shouldUpdate`, means the value should always be true\n // TODO(sjmiles): this violates our 'false by default' convention, but the\n // naming is awkward: `shouldNotUpdate`? `preventUpdate`?\n return !this.impl?.shouldUpdate || (await this.impl.shouldUpdate(inputs, state) !== false);\n }\n update() {\n this.asyncMethod(this.impl?.update);\n }\n outputData(data) {\n this.pipe?.output?.(data, this.maybeRender());\n }\n maybeRender() {\n //this.log('maybeRender');\n if (this.template) {\n const { inputs, state } = this.internal;\n if (this.impl?.shouldRender?.(inputs, state) !== false) {\n //this.log('render');\n if (this.implements('render')) {\n return this.impl.render(inputs, state);\n }\n else {\n return { ...inputs, ...state };\n }\n }\n }\n }\n async handleEvent({ handler, data }) {\n const onhandler = this.impl?.[handler];\n if (onhandler) {\n this.internal.inputs.eventlet = data;\n await this.asyncMethod(onhandler.bind(this.impl), { eventlet: data });\n this.internal.inputs.eventlet = null;\n }\n else {\n //console.log(`[${this.id}] event handler [${handler}] not found`);\n }\n }\n async asyncMethod(asyncMethod, injections) {\n if (asyncMethod) {\n const { inputs, state } = this.internal;\n const stdlib = {\n service: async (request) => this.service(request),\n invalidate: () => this.invalidate(),\n output: async (data) => this.outputData(data)\n };\n const task = asyncMethod.bind(this.impl, inputs, state, { ...stdlib, ...injections });\n this.outputData(await this.try(task));\n if (!this.internal.$busy && this.internal.$validateAfterBusy) {\n this.invalidate();\n }\n }\n }\n async try(asyncFunc) {\n this.internal.$busy++;\n try {\n return await asyncFunc();\n }\n catch (e) {\n log.error(e);\n }\n finally {\n this.internal.$busy--;\n }\n }\n}\nscope.harden(globalThis);\nscope.harden(Particle);\n// log('Any leaked values? Must pass three tests:');\n// try { globalThis['sneaky'] = 42; } catch(x) { log('sneaky test: pass'); }\n// try { Particle['foo'] = 42; } catch(x) { log('Particle.foo test: pass'); }\n// try { log['foo'] = 42; } catch(x) { log('log.foo test: pass'); };\nParticle;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport class EventEmitter {\n // map of event name to listener array\n listeners = {};\n getEventListeners(eventName) {\n return this.listeners[eventName] || (this.listeners[eventName] = []);\n }\n fire(eventName, ...args) {\n const listeners = this.getEventListeners(eventName);\n if (listeners?.forEach) {\n listeners.forEach(listener => listener(...args));\n }\n }\n listen(eventName, listener, listenerName) {\n const listeners = this.getEventListeners(eventName);\n listeners.push(listener);\n listener._name = listenerName || '(unnamed listener)';\n return listener;\n }\n unlisten(eventName, listener) {\n const list = this.getEventListeners(eventName);\n const index = (typeof listener === 'string') ? list.findIndex(l => l._name === listener) : list.indexOf(listener);\n if (index >= 0) {\n list.splice(index, 1);\n }\n else {\n console.warn('failed to unlisten from', eventName);\n }\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const logKinds = ['log', 'group', 'groupCollapsed', 'groupEnd', 'dir'];\nexport const errKinds = ['warn', 'error'];\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logKinds, errKinds } from './types.js';\nconst { fromEntries } = Object;\nconst _logFactory = (enable, preamble, bg, color, kind = 'log') => {\n if (!enable) {\n return () => { };\n }\n if (kind === 'dir') {\n return console.dir.bind(console);\n }\n const style = `background: ${bg || 'gray'}; color: ${color || 'white'}; padding: 1px 6px 2px 7px; border-radius: 6px 0 0 6px;`;\n return console[kind].bind(console, `%c${preamble}`, style);\n};\nexport const logFactory = (enable, preamble, bg = '', color = '') => {\n const debugLoggers = fromEntries(logKinds.map(kind => [kind, _logFactory(enable, preamble, bg, color, kind)]));\n const errorLoggers = fromEntries(errKinds.map(kind => [kind, _logFactory(true, preamble, bg, color, kind)]));\n const loggers = { ...debugLoggers, ...errorLoggers };\n // Inject `log` as default, keeping all loggers available to be invoked by name.\n const log = loggers.log;\n Object.assign(log, loggers);\n return log;\n};\nlogFactory.flags = globalThis.config?.logFlags || {};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nimport { logFactory } from '../utils/log.js';\nconst customLogFactory = (id) => logFactory(logFactory.flags.arc, `Arc (${id})`, 'slateblue');\nconst { assign, keys, entries, create } = Object;\nconst values = (o) => Object.values(o);\nconst nob = () => create(null);\nexport class Arc extends EventEmitter {\n log;\n id;\n meta;\n stores;\n hosts;\n surface;\n composer;\n hostService;\n constructor(id, meta, surface) {\n super();\n this.id = id;\n this.meta = meta;\n this.surface = surface;\n this.hosts = nob();\n this.stores = nob();\n this.log = customLogFactory(id);\n }\n async addHost(host, surface) {\n // to support hosts we need a composer\n await this.ensureComposer();\n // bookkeep\n this.hosts[host.id] = host;\n host.arc = this;\n // TODO(sjmiles): support per host surfacing?\n //await host.bindToSurface(surface ?? this.surface);\n // begin work\n this.updateHost(host);\n return host;\n }\n async ensureComposer() {\n if (!this.composer && this.surface) {\n // create composer\n this.composer = await this.surface.createComposer('root');\n // pipeline for events from composer to this.onevent\n // TODO(sjmiles): use 'bind' to avoid a closure and improve the stack trace\n this.composer.onevent = this.onevent.bind(this);\n }\n }\n rerender() {\n values(this.hosts).forEach(h => h.rerender());\n }\n removeHost(id) {\n this.hosts[id]?.detach();\n delete this.hosts[id];\n }\n addStore(storeId, store) {\n if (store && !this.stores[storeId]) {\n this.stores[storeId] = store;\n store.listen('change', () => this.storeChanged(storeId, store), this.id);\n }\n }\n removeStore(storeId) {\n const store = this.stores[storeId];\n if (store) {\n store.unlisten('change', this.id);\n }\n delete this.stores[storeId];\n }\n // TODO(sjmiles): 2nd param is used in overrides, make explicit\n storeChanged(storeId, store) {\n this.log(`storeChanged: \"${storeId}\"`);\n const isBound = inputs => inputs && inputs.some(input => values(input)[0] == storeId || keys(input)[0] == storeId);\n values(this.hosts).forEach(host => {\n const inputs = host.meta?.inputs;\n if (inputs === '*' || isBound(inputs)) {\n this.log(`host \"${host.id}\" has interest in \"${storeId}\"`);\n // TODO(sjmiles): we only have to update inputs for storeId, we lose efficiency here\n this.updateHost(host);\n }\n });\n this.fire('store-changed', storeId);\n }\n updateParticleMeta(hostId, meta) {\n const host = this.hosts[hostId];\n host.meta = meta;\n this.updateHost(host);\n }\n updateHost(host) {\n host.inputs = this.computeInputs(host);\n }\n // TODO(sjmiles): debounce? (update is sync-debounced already)\n // complement to `assignOutputs`\n computeInputs(host) {\n const inputs = nob();\n const inputBindings = host.meta?.inputs;\n if (inputBindings === '*') {\n // TODO(sjmiles): we could make the contract that the bindAll inputs are\n // names (or names + meta) only. The Particle could look up values via\n // service (to reduce throughput requirements)\n entries(this.stores).forEach(([name, store]) => inputs[name] = store.pojo);\n }\n else {\n const staticInputs = host.meta?.staticInputs;\n assign(inputs, staticInputs);\n if (inputBindings) {\n inputBindings.forEach(input => this.computeInput(entries(input)[0], inputs));\n this.log(`computeInputs(${host.id}) =`, inputs);\n }\n }\n return inputs;\n }\n computeInput([name, binding], inputs) {\n const storeName = binding || name;\n const store = this.stores[storeName];\n if (store) {\n inputs[name] = store.pojo;\n }\n else {\n this.log.warn(`computeInput: \"${storeName}\" (bound to \"${name}\") not found`);\n }\n }\n // complement to `computeInputs`\n assignOutputs({ id, meta }, outputs) {\n const names = keys(outputs);\n if (meta?.outputs && names.length) {\n names.forEach(name => this.assignOutput(name, outputs[name], meta.outputs));\n this.log(`[end][${id}] assignOutputs:`, outputs);\n }\n }\n assignOutput(name, output, outputs) {\n if (output !== undefined) {\n const binding = this.findOutputByName(outputs, name) || name;\n const store = this.stores[binding];\n if (!store) {\n if (outputs?.[name]) {\n this.log.warn(`assignOutputs: no \"${binding}\" store for output \"${name}\"`);\n }\n }\n else {\n // Note: users can mess up output data in any way they see fit, so we should\n // probably invent `outputCleansing`.\n this.log(`assignOutputs: \"${name}\" is dirty, updating Store \"${binding}\"`, output);\n store.data = output;\n }\n }\n }\n findOutputByName(outputs, name) {\n const output = outputs?.find(output => keys(output)[0] === name);\n if (output) {\n return values(output)[0];\n }\n }\n async render(packet) {\n if (this.composer) {\n this.composer.render(packet);\n }\n else {\n //this.log.low('render called, but composer is null', packet);\n }\n }\n onevent(pid, eventlet) {\n const host = this.hosts[pid];\n if (host) {\n host.handleEvent(eventlet);\n }\n }\n async service(host, request) {\n let result = await this.surface?.service(request);\n if (result === undefined) {\n result = this.hostService?.(host, request);\n }\n return result;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/*\n * update the fields of `obj` with the fields of `data`,\n * perturbing `obj` as little as possible (since it might be a magic proxy thing\n * like an Automerge document)\n */\nexport const shallowUpdate = (obj, data) => {\n let result = data;\n if (!data) {\n //\n }\n else if (Array.isArray(data)) {\n if (!Array.isArray(obj)) {\n // TODO(sjmiles): eek, very perturbing to obj\n obj = [];\n }\n for (let i = 0; i < data.length; i++) {\n const value = data[i];\n if (obj[i] !== value) {\n obj[i] = value;\n }\n }\n const overage = obj.length - data.length;\n if (overage > 0) {\n obj.splice(data.length, overage);\n }\n }\n else if (typeof data === 'object') {\n result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n const seen = {};\n // for each key in input data ...\n Object.keys(data).forEach(key => {\n // copy that data into output\n result[key] = data[key];\n // remember the key\n seen[key] = true;\n });\n // for each key in the output data...\n Object.keys(result).forEach(key => {\n // if this key was not in the input, remove it\n if (!seen[key]) {\n delete result[key];\n }\n });\n }\n return result;\n};\nexport const shallowMerge = (obj, data) => {\n if (data == null) {\n return null;\n }\n if (typeof data === 'object') {\n const result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n Object.keys(data).forEach(key => result[key] = data[key]);\n return result;\n }\n return data;\n};\nexport function deepCopy(datum) {\n if (!datum) {\n return datum;\n }\n else if (Array.isArray(datum)) {\n // This is trivially type safe but tsc needs help\n return datum.map(element => deepCopy(element));\n }\n else if (typeof datum === 'object') {\n const clone = Object.create(null);\n Object.entries(datum).forEach(([key, value]) => {\n clone[key] = deepCopy(value);\n });\n return clone;\n }\n else {\n return datum;\n }\n}\nexport const deepEqual = (a, b) => {\n const type = typeof a;\n // must be same type to be equal\n if (type !== typeof b) {\n return false;\n }\n // we are `deep` because we recursively study object types\n if (type === 'object' && a && b) {\n const aProps = Object.getOwnPropertyNames(a);\n const bProps = Object.getOwnPropertyNames(b);\n // equal if same # of props, and no prop is not deepEqual\n return (aProps.length == bProps.length) && !aProps.some(name => !deepEqual(a[name], b[name]));\n }\n // finally, perform simple comparison\n return (a === b);\n};\nexport const deepUndefinedToNull = (obj) => {\n if (obj === undefined) {\n return null;\n }\n if (obj && (typeof obj === 'object')) {\n // we are `deep` because we recursively study object types\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(name => {\n const prop = obj[name];\n if (prop === undefined) {\n delete obj[name];\n //obj[name] = null;\n }\n else {\n deepUndefinedToNull(prop);\n }\n });\n }\n return obj;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nconst { floor, pow, random } = Math;\n// random n-digit number\nexport const key = (digits) => floor((1 + random() * 9) * pow(10, digits - 1));\n// random integer from [0..range)\nexport const irand = (range) => floor(random() * range);\n// random element from array\nexport const arand = (array) => array[irand(array.length)];\n// test if event has occured, where `probability` is between [0..1]\nexport const prob = (probability) => Boolean(random() < probability);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepCopy } from '../utils/object.js';\nconst log = logFactory(logFactory.flags.decorator, 'Decorator', 'plum');\nconst { values, entries } = Object;\nconst opaqueData = {};\nexport const Decorator = {\n setOpaqueData(name, data) {\n opaqueData[name] = data; //deepCopy(data);\n return name;\n },\n getOpaqueData(name) {\n return opaqueData[name];\n },\n processOutputModel({ privateData }) {\n if (privateData) {\n const key = privateData.__privateKey;\n if (key) {\n const data = Object.values(opaqueData).pop();\n const { _privateKey, ...privy } = privateData;\n data['privateData'] = privy;\n }\n //log.warn(privateData);\n }\n },\n maybeDecorateModel(model, particle) {\n if (model && !Array.isArray(model)) {\n // for each item in model, regardless of key\n values(model).forEach((item) => {\n // is an object?\n if (item && (typeof item === 'object')) {\n // are there sub-models\n if (item['models']) {\n // the decorate this item\n log('applying decorator(s) to list:', item);\n this.maybeDecorateItem(item, particle);\n }\n else {\n // otherwise, check if there are sub-items to decorate\n if (model?.filter || model?.decorator || model?.collateBy) {\n log('scanning for lists in sub-model:', item);\n this.maybeDecorateModel(item, particle);\n }\n }\n }\n });\n }\n // possibly decorated model\n return model;\n },\n maybeDecorateItem(item, particle) {\n let models = (typeof item.models === 'string') ? this.getOpaqueData(item.models) : item.models;\n if (models) {\n // do a decorator\n models = maybeDecorate(models, item.decorator, particle);\n // do a filter\n models = maybeFilter(models, item.filter, particle.impl);\n // do a collator\n models = maybeCollateBy(models, item);\n // mutate items\n item.models = models;\n //console.log(JSON.stringify(models, null, ' '));\n }\n },\n};\nconst maybeDecorate = (models, decorator, particle) => {\n decorator = particle.impl[decorator] ?? decorator;\n const { inputs, state } = particle.internal;\n if (decorator) {\n // TODO(cromwellian): Could be expensive to do everything, store responsibility?\n const immutableInputs = Object.freeze(deepCopy(inputs));\n // we don't want the decorator to have access to mutable globals\n const immutableState = Object.freeze(deepCopy(state));\n // models become decorous\n models = models.map((model, i) => {\n // use previously mutated data or initialize\n // TODO(cromwellian): I'd like to do Object.freeze() here, also somehow not mutate the models inplace\n // Possibly have setOpaqueData wrap the data so the privateData lives on the wrapper + internal immutable data\n model.privateData = model.privateData || {};\n // TODO(cromwellian): also could be done once during setOpaqueData() if we can track privateData differently\n const immutableModel = Object.freeze(deepCopy(model));\n const decorated = decorator(immutableModel, immutableInputs, immutableState);\n // set new privateData from returned\n model.privateData = { ...decorated.privateData, __privateKey: i };\n return { ...decorated, ...model, };\n });\n // sort (possible that all values undefined)\n models.sort(sortByLc('sortKey'));\n log('decoration was performed');\n }\n //models.forEach(model => delete model.privateData);\n return models;\n};\nconst maybeFilter = (models, filter, impl) => {\n filter = impl[filter] ?? filter;\n if (filter && models) {\n // models become filtrated\n models = models.filter(filter);\n }\n return models;\n};\nconst maybeCollateBy = (models, item) => {\n // construct requested sub-lists\n entries(item).forEach(([name, collator]) => {\n // generate named collations for items of the form `[name]: {collateBy}`\n if (collator?.['collateBy']) {\n // group the models into buckets based on the model-field named by `collateBy`\n const collation = collate(models, collator['collateBy']);\n models = collationToRenderModels(collation, name, collator['$template']);\n }\n });\n return models;\n};\nconst sortByLc = key => (a, b) => sort(String(a[key]).toLowerCase(), String(b[key]).toLowerCase());\n//const sortBy = key => (a, b) => sort(a[key], b[key]);\nconst sort = (a, b) => a < b ? -1 : a > b ? 1 : 0;\nconst collate = (models, collateBy) => {\n const collation = {};\n models.forEach(model => {\n const keyValue = model[collateBy];\n if (keyValue) {\n const category = collation[keyValue] || (collation[keyValue] = []);\n category.push(model);\n }\n });\n return collation;\n};\nconst collationToRenderModels = (collation, name, $template) => {\n return entries(collation).map(([key, models]) => ({\n key,\n [name]: { models, $template },\n single: !(models['length'] !== 1),\n ...models?.[0]\n }));\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { arand } from '../utils/rand.js';\nimport { EventEmitter } from './EventEmitter.js';\nimport { Decorator } from './Decorator.js';\nconst { entries, keys } = Object;\nconst customLogFactory = (id) => logFactory(logFactory.flags.host, `Host (${id})`, arand(['#5a189a', '#51168b', '#48137b', '#6b2fa4', '#7b46ae', '#3f116c']));\n/**\n * Host owns metadata (e.g. `id`, `container`) that its Particle is not allowed to access.\n * Host knows how to talk, asynchronously, to its Particle (potentially using a bus).\n**/\n/* TODO(sjmiles):\nUpdate Cycle Documented Briefly\n1. when a Store changes it invokes it's listeners\n2. when an Arc hears a Store change, it updates Hosts bound to the Store\n3. Arc updates Host by creating an `inputs` object from Stores and metadata\n - ignores fact inputs are accumulated\n - ignores information about which Store has updated\n4. `inputs` object is assigned to `hosts.inputs` \uD83D\uDE43\n5. Host does an expensive `deepEqual` equality check. Turning on `host` logging should reveal `this.log('inputs are not interesting, skipping update');` if data is caught in this trap\n - we can use reference testing here if we are more careful\n about using immutable data\n6. the particle.inputs are assigned (but is really a *merge*)\n*/\nexport class Host extends EventEmitter {\n arc;\n id;\n lastOutput;\n lastPacket;\n lastRenderModel;\n log;\n meta;\n particle;\n constructor(id) {\n super();\n this.log = customLogFactory(id);\n this.id = id;\n }\n onevent(eventlet) {\n this.arc?.onevent(eventlet);\n }\n // Particle and ParticleMeta are separate, host specifically integrates these on behalf of Particle\n installParticle(particle, meta) {\n if (this.particle) {\n this.detachParticle();\n }\n if (particle) {\n this.particle = particle;\n this.meta = meta || this.meta;\n }\n }\n get container() {\n return this.meta?.container || 'root';\n }\n detach() {\n this.detachParticle();\n this.arc = null;\n }\n detachParticle() {\n if (this.particle) {\n this.render({ $clear: true });\n this.particle = null;\n this.meta = null;\n }\n }\n async service(request) {\n if (request?.decorate) {\n return Decorator.maybeDecorateModel(request.model, this.particle);\n }\n return this.arc?.service(this, request);\n }\n output(outputModel, renderModel) {\n if (outputModel) {\n Decorator.processOutputModel(outputModel);\n this.lastOutput = outputModel;\n this.arc?.assignOutputs(this, outputModel);\n }\n if (this.template) {\n Decorator.maybeDecorateModel(renderModel, this.particle);\n this.log(renderModel);\n this.lastRenderModel = renderModel;\n this.render(renderModel);\n }\n }\n rerender() {\n if (this.lastRenderModel) {\n this.render(this.lastRenderModel);\n }\n // if (this.lastPacket) {\n // this.arc?.render(this.lastPacket);\n // }\n }\n render(model) {\n const { id, container, template } = this;\n const content = { model, template };\n const packet = { id, container, content };\n this.arc?.render(packet);\n this.lastPacket = packet;\n }\n set inputs(inputs) {\n if (this.particle && inputs) {\n const lastInputs = this.particle.internal.inputs;\n if (this.dirtyCheck(inputs, lastInputs, this.lastOutput)) {\n this.particle.inputs = { ...this.meta?.staticInputs, ...inputs };\n this.fire('inputs-changed');\n }\n else {\n this.log('inputs are uninteresting, skipping update');\n }\n }\n }\n dirtyCheck(inputs, lastInputs, lastOutput) {\n const dirtyBits = ([n, v]) => (lastOutput?.[n] && !deepEqual(lastOutput[n], v))\n || !deepEqual(lastInputs?.[n], v);\n return !lastInputs\n || entries(inputs).length !== this.lastInputsLength(lastInputs)\n || entries(inputs).some(dirtyBits);\n }\n lastInputsLength(lastInputs) {\n return keys(lastInputs).filter(key => !this.meta?.staticInputs?.[key] && key !== 'eventlet').length;\n }\n get config() {\n return this.particle?.config;\n }\n get template() {\n return this.config?.template;\n }\n invalidate() {\n this.particle?.invalidate();\n }\n handleEvent(eventlet) {\n return this.particle?.handleEvent(eventlet);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nconst { create, keys } = Object;\nconst { stringify, parse } = JSON;\nexport class DataStore extends EventEmitter {\n privateData;\n constructor() {\n super();\n }\n setPrivateData(data) {\n this.privateData = data;\n }\n set data(data) {\n this.setPrivateData(data);\n }\n get data() {\n return this.privateData;\n }\n toString() {\n return this.pretty;\n }\n get isObject() {\n return this.data && typeof this.data === 'object';\n }\n get pojo() {\n return this.data;\n }\n get json() {\n return stringify(this.data);\n }\n set json(json) {\n let value = null;\n try {\n value = parse(json);\n }\n catch (x) {\n //\n }\n this.data = value;\n }\n get pretty() {\n const sorted = {};\n const pojo = this.pojo;\n keys(pojo).sort().forEach(key => sorted[key] = pojo[key]);\n return stringify(sorted, null, ' ');\n }\n}\nclass ObservableStore extends DataStore {\n change(mutator) {\n mutator(this);\n this.doChange();\n }\n doChange() {\n this.fire('change', this);\n this.onChange(this);\n }\n onChange(store) {\n // override\n }\n set data(data) {\n this.change(self => self.setPrivateData(data));\n }\n // TODO(sjmiles): one of the compile/build/bundle tools\n // evacipates the inherited getter, so we clone it\n get data() {\n return this['privateData'];\n }\n set(key, value) {\n if (!this.data) {\n this.setPrivateData(create(null));\n }\n if (value !== undefined) {\n this.change(self => self.data[key] = value);\n }\n else {\n this.delete(key);\n }\n }\n delete(key) {\n this.change(doc => delete doc.data[key]);\n }\n}\nclass PersistableStore extends ObservableStore {\n meta;\n constructor(meta) {\n super();\n this.meta = { ...meta };\n }\n toString() {\n return `${JSON.stringify(this.meta, null, ' ')}, ${this.pretty}`;\n }\n get tags() {\n return this.meta.tags ?? (this.meta.tags = []);\n }\n is(...tags) {\n // true if every member of `tags` is also in `this.tags`\n return tags.every(tag => this.tags.includes(tag));\n }\n isCollection() {\n return this.meta.type?.[0] === '[';\n }\n shouldPersist() {\n return this.is('persisted') && !this.is('volatile');\n }\n async doChange() {\n // do not await\n this.persist();\n return super.doChange();\n }\n // TODO(sjmiles): as of now the persist/restore methods\n // are bound in Runtime:addStore\n async persist() {\n }\n async restore( /*value: any*/) {\n }\n // delete() {\n // this.persistor?.remove(this);\n // }\n save() {\n return this.json;\n }\n load(serial, defaultValue) {\n let value = defaultValue;\n try {\n if (serial) {\n value = parse(serial);\n }\n }\n catch (x) {\n //\n }\n if (value !== undefined) {\n this.data = value;\n }\n }\n}\nexport class Store extends PersistableStore {\n}\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { irand } from \"./rand.js\";\nexport const makeId = (pairs, digits, delim) => {\n pairs = pairs || 2;\n digits = digits || 2;\n delim = delim || '-';\n const min = Math.pow(10, digits - 1);\n const range = Math.pow(10, digits) - min;\n const result = [];\n for (let i = 0; i < pairs; i++) {\n result.push(`${irand(range - min) + min}`);\n }\n return result.join(delim);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Arc } from './core/Arc.js';\nimport { Host } from './core/Host.js';\nimport { Store } from './core/Store.js';\nimport { EventEmitter } from './core/EventEmitter.js';\nimport { logFactory } from './utils/log.js';\nimport { makeId } from './utils/id.js';\nconst log = logFactory(logFactory.flags.runtime, 'runtime', '#873600');\nconst particleFactoryCache = {};\nconst storeFactories = {};\nconst { keys } = Object;\nexport class Runtime extends EventEmitter {\n log;\n uid; // user id\n nid; // network id\n arcs;\n stores;\n peers;\n shares;\n endpoint;\n network;\n surfaces;\n persistor;\n prettyUid;\n static securityLockdown;\n static particleIndustry;\n static particleOptions;\n constructor(uid) {\n uid = uid || 'user';\n super();\n this.arcs = {};\n this.surfaces = {};\n this.stores = {};\n this.peers = new Set();\n this.shares = new Set();\n this.setUid(uid);\n this.log = logFactory(logFactory.flags.runtime, `runtime:[${this.prettyUid}]`, '#873600');\n //Runtime.securityLockdown?.(Runtime.particleOptions);\n }\n setUid(uid) {\n this.uid = uid;\n this.nid = `${uid}:${makeId(1, 2)}`;\n this.prettyUid = uid.substring(0, uid.indexOf('@') + 1) || uid;\n }\n async bootstrapArc(name, meta, surface, service) {\n // make an arc on `surface`\n const arc = new Arc(name, meta, surface);\n // install service handler\n arc.hostService = this.serviceFactory(service);\n // add `arc` to runtime\n await this.addArc(arc);\n // fin\n return arc;\n }\n serviceFactory(service) {\n return async (host, request) => service.handle(this, host, request);\n }\n async bootstrapParticle(arc, id, meta) {\n // make a host\n const host = new Host(id);\n // make a particle\n await this.marshalParticle(host, meta);\n // add `host` to `arc`\n const promise = arc.addHost(host);\n // report\n log('bootstrapped particle', id);\n //log(host);\n // we'll call you when it's ready\n return promise;\n }\n // no-op surface mapping\n addSurface(id, surface) {\n this.surfaces[id] = surface;\n }\n getSurface(id) {\n return this.surfaces[id];\n }\n // map arcs by arc.id\n addArc(arc) {\n const { id } = arc;\n if (id && !this.arcs[id]) {\n return this.arcs[id] = arc;\n }\n throw `arc has no id, or id \"${id}\" is already in use`;\n }\n removeArc(arc) {\n const { id } = arc;\n if (!id || !this.arcs[id]) {\n throw !id ? `arc has no id` : `id \"${id}\" is not in use`;\n }\n delete this.arcs[id];\n }\n // create a particle inside of host\n async marshalParticle(host, particleMeta) {\n const particle = await this.createParticle(host, particleMeta.kind);\n host.installParticle(particle, particleMeta);\n }\n // create a host, install a particle, add host to arc\n async installParticle(arc, particleMeta, name) {\n this.log('installParticle', name, particleMeta, arc.id);\n // provide a default name\n name = name || makeId();\n // deduplicate name\n if (arc.hosts[name]) {\n let n = 1;\n for (; (arc.hosts[`${name}-${n}`]); n++)\n ;\n name = `${name}-${n}`;\n }\n // build the structure\n const host = new Host(name);\n await this.marshalParticle(host, particleMeta);\n arc.addHost(host);\n return host;\n }\n // map a store by a Runtime-specific storeId\n // Stores have no intrinsic id\n addStore(storeId, store) {\n // if the store needs to discuss things with Runtime\n // TODO(sjmiles): this is likely unsafe for re-entry\n if (store.marshal) {\n store.marshal(this);\n }\n // bind to persist/restore functions\n store.persist = async () => this.persistStore(storeId, store);\n store.restore = async () => this.restoreStore(storeId, store);\n // override the Store's own persistor to use the runtime persistor\n // TODO(sjmiles): why?\n // if (store.persistor) {\n // store.persistor.persist = store => this.persistor?.persist(storeId, store);\n // }\n // bind this.storeChanged to store.change (and name the binding)\n const name = `${this.nid}:${storeId}-changed`;\n const onChange = this.storeChanged.bind(this, storeId);\n store.listen('change', onChange, name);\n // map the store\n this.stores[storeId] = store;\n // evaluate for sharing\n this.maybeShareStore(storeId);\n // notify listeners that a thing happened\n // TODO(sjmiles): makes no sense without id\n //this.fire('store-added', store);\n }\n async persistStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`persistStore \"${storeId}\"`);\n return this.persistor.persist?.(storeId, store);\n }\n }\n async restoreStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`restoreStore \"${storeId}\"`);\n return this.persistor.restore?.(storeId);\n }\n }\n storeChanged(storeId, store) {\n this.log('storeChanged', storeId);\n this.network?.invalidatePeers(storeId);\n this.onStoreChange(storeId, store);\n this.fire('store-changed', { storeId, store });\n }\n // TODO(sjmiles): evacipate this method\n onStoreChange(storeId, store) {\n // override for bespoke response\n }\n do(storeId, task) {\n task(this.stores[storeId]);\n }\n removeStore(storeId) {\n this.do(storeId, store => {\n store?.unlisten('change', `${this.nid}:${storeId}-changed`);\n });\n delete this.stores[storeId];\n }\n maybeShareStore(storeId) {\n this.do(storeId, store => {\n if (store?.is('shared')) {\n this.shareStore(storeId);\n }\n });\n }\n addPeer(peerId) {\n this.peers.add(peerId);\n [...this.shares].forEach(storeId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n shareStore(storeId) {\n this.shares.add(storeId);\n [...this.peers].forEach(peerId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n maybeShareStoreWithPeer(storeId, peerId) {\n this.do(storeId, store => {\n const nid = this.uid.replace(/\\./g, '_');\n if (!store.is('private') || (peerId.startsWith(nid))) {\n this.shareStoreWithPeer(storeId, peerId);\n }\n });\n }\n shareStoreWithPeer(storeId, peerId) {\n this.network?.shareStore(storeId, peerId);\n }\n async createParticle(host, kind) {\n try {\n const factory = await this.marshalParticleFactory(kind);\n return factory(host);\n }\n catch (x) {\n log.error(`createParticle(${kind}):`, x);\n }\n }\n async marshalParticleFactory(kind) {\n return particleFactoryCache[kind] ?? this.lateBindParticle(kind);\n }\n lateBindParticle(kind) {\n return Runtime.registerParticleFactory(kind, Runtime?.particleIndustry(kind, Runtime.particleOptions));\n }\n static registerParticleFactory(kind, factoryPromise) {\n return particleFactoryCache[kind] = factoryPromise;\n }\n requireStore(meta) {\n let store = this.stores[meta.name];\n if (!store) {\n store = this.createStore(meta);\n this.addStore(meta.name, store);\n }\n return store;\n }\n createStore(meta) {\n const key = keys(storeFactories).find(tag => meta.tags?.includes?.(tag));\n const storeClass = storeFactories[String(key)] || Store;\n return new storeClass(meta);\n }\n static registerStoreClass(tag, storeClass) {\n storeFactories[tag] = storeClass;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'flan', 'violet');\nconst { entries, create } = Object;\nexport class Parser {\n stores;\n particles;\n slots;\n meta;\n constructor(recipe) {\n this.stores = [];\n this.particles = [];\n this.slots = [];\n this.meta = create(null);\n if (recipe) {\n this.parse(recipe);\n }\n }\n parse(recipe) {\n // `normalize` converts shorthand to longhand before parsing\n const normalized = this.normalize(recipe);\n this.parseSlotSpec(normalized, 'root', '');\n return this;\n }\n normalize(recipe) {\n if (typeof recipe !== 'object') {\n throw Error('recipe must be an Object');\n }\n // TODO(sjmiles): would be great if `normalize` normalized all the things\n return recipe;\n }\n parseSlotSpec(spec, slotName, parentName) {\n // process entries\n for (const key in spec) {\n switch (key) {\n case '$meta':\n // value is a dictionary\n this.meta = { ...this.meta, ...spec.$meta };\n break;\n case '$stores':\n // value is a StoreSpec\n this.parseStoresNode(spec.$stores);\n break;\n default: {\n // value is a ParticleSpec\n const container = parentName ? `${parentName}#${slotName}` : slotName;\n this.parseParticleSpec(container, key, spec[key]);\n break;\n }\n }\n }\n }\n parseStoresNode(stores) {\n for (const key in stores) {\n this.parseStoreSpec(key, stores[key]);\n }\n }\n parseStoreSpec(name, spec) {\n if (this.stores.find(s => s.name === name)) {\n log('duplicate store name');\n return;\n }\n const meta = {\n name,\n type: spec.$type,\n tags: spec.$tags,\n value: spec.$value\n };\n this.stores.push(meta);\n }\n parseParticleSpec(container, id, spec) {\n if (!spec.$kind) {\n log.warn(`parseParticleSpec: malformed spec has no \"kind\":`, spec);\n throw Error();\n }\n if (this.particles.find(s => s.id === id)) {\n log('duplicate particle name');\n return;\n }\n this.particles.push({ id, container, spec });\n if (spec.$slots) {\n this.parseSlotsNode(spec.$slots, id);\n }\n }\n parseSlotsNode(slots, parent) {\n entries(slots).forEach(([key, spec]) => this.parseSlotSpec(spec, key, parent));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport function matches(candidateMeta, targetMeta) {\n for (const property in targetMeta) {\n if (candidateMeta[property] !== targetMeta[property]) {\n return false;\n }\n }\n return true;\n}\n;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { matches } from '../utils/matching.js';\nconst log = logFactory(logFactory.flags.recipe, 'StoreCook', '#99bb15');\nconst { values } = Object;\nconst findStores = (runtime, criteria) => {\n return values(runtime.stores).filter(store => matches(store?.meta, criteria));\n};\nconst mapStore = (runtime, { name, type }) => {\n // TODO(b/244191110): Type matching API to be wired here.\n return findStores(runtime, { name, type })?.[0];\n};\nexport class StoreCook {\n static async execute(runtime, arc, stores) {\n return this.forEachStore(this.realizeStore, runtime, arc, stores);\n }\n static async evacipate(runtime, arc, stores) {\n return this.forEachStore(this.derealizeStore, runtime, arc, stores);\n }\n static async forEachStore(task, runtime, arc, stores) {\n return Promise.all(stores.map(store => task.call(this, runtime, arc, store)));\n }\n static async realizeStore(runtime, arc, rawMeta) {\n const meta = this.constructMeta(runtime, arc, rawMeta);\n let value = meta?.value;\n let store = mapStore(runtime, meta);\n if (store) {\n log(`realizeStore: mapped \"${rawMeta.name}\" to \"${store.meta.name}\"`);\n }\n else {\n store = runtime.createStore(meta);\n log(`realizeStore: created \"${meta.name}\"`);\n // TODO(sjmiles): Stores no longer know their own id, so there is a wrinkle here as we\n // re-route persistence through runtime (so we can bind in the id)\n // Also: the 'id' is known as 'meta.name' here, this is also a problem\n // store && (store.persistor = {\n // restore: store => runtime.persistor?.restore(meta.name, store),\n // persist: () => {}\n // });\n // runtime.addStore(meta.name, store);\n //await store?.restore(meta?.value)\n runtime.addStore(meta.name, store);\n if (store.shouldPersist()) {\n const cached = await store.restore();\n value = cached === undefined ? value : cached;\n }\n }\n if (value !== undefined) {\n log(`setting data to:`, value);\n store.data = value;\n }\n arc.addStore(meta.name, store);\n }\n static async derealizeStore(runtime, arc, spec) {\n runtime.removeStore(spec.$name);\n arc.removeStore(spec.$name);\n }\n static constructMeta(runtime, arc, rawMeta) {\n const meta = {\n ...rawMeta,\n arcid: arc.id,\n uid: runtime.uid,\n };\n return {\n ...meta,\n owner: meta.uid,\n shareid: `${meta.name}:${meta.arcid}:${meta.uid}`\n };\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'ParticleCook', '#5fa530');\nexport class ParticleCook {\n static async execute(runtime, arc, particles) {\n // serial\n for (const particle of particles) {\n await this.realizeParticle(runtime, arc, particle);\n }\n // parallel\n //return Promise.all(particles.map(particle => this.realizeParticle(runtime, arc, particle)));\n }\n static async realizeParticle(runtime, arc, node) {\n log('realizedParticle:', node.id);\n // convert spec to metadata\n const meta = this.specToMeta(node.spec);\n meta.container ||= node.container;\n // make a (hosted) particle\n return runtime.bootstrapParticle(arc, node.id, meta);\n }\n static specToMeta(spec) {\n if (spec.$bindings) {\n console.warn(`Particle '${spec.$kind}' spec contains deprecated $bindings property (${JSON.stringify(spec.$bindings)})`);\n }\n // TODO(sjmiles): impedance mismatch here is likely to cause problems\n const { $kind: kind, $container: container, $staticInputs: staticInputs } = spec;\n const inputs = this.formatBindings(spec.$inputs);\n const outputs = this.formatBindings(spec.$outputs);\n return { kind, staticInputs, inputs, outputs, container };\n }\n static formatBindings(bindings) {\n return bindings?.map?.(binding => typeof binding === 'string' ? { [binding]: binding } : binding);\n }\n static async evacipate(runtime, arc, particles) {\n return Promise.all(particles.map(particle => this.derealizeParticle(runtime, arc, particle)));\n }\n static async derealizeParticle(runtime, arc, node) {\n arc.removeHost(node.id);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { Parser } from './RecipeParser.js';\nimport { StoreCook } from './StoreCook.js';\nimport { ParticleCook } from './ParticleCook.js';\nconst log = logFactory(logFactory.flags.recipe, 'Chef', '#087f23');\nexport class Chef {\n static async execute(recipe, runtime, arc) {\n if (arc instanceof Promise) {\n log.error('`arc` must be an Arc, not a Promise. Make sure `boostrapArc` is awaited.');\n return;\n }\n //log.groupCollapsed('executing recipe...', recipe.$meta);\n log('|-->...| executing recipe: ', recipe.$meta ?? '');\n const plan = new Parser(recipe);\n // `store` preparation\n await StoreCook.execute(runtime, arc, plan.stores);\n // `particle` preparation\n await ParticleCook.execute(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): what do we use this for?\n arc.meta = { ...arc.meta, ...plan.meta };\n log('|...-->| recipe complete: ', recipe.$meta ?? '');\n //log.groupEnd();\n }\n static async evacipate(recipe, runtime, arc) {\n //log.groupCollapsed('evacipating recipe...', recipe.$meta);\n log('|-->...| evacipating recipe: ', recipe.$meta);\n // TODO(sjmiles): this is work we already did\n const plan = new Parser(recipe);\n // `store` work\n // TODO(sjmiles): not sure what stores are unique to this plan\n //await StoreCook.evacipate(runtime, arc, plan);\n // `particle` work\n await ParticleCook.evacipate(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): doh\n //arc.meta = {...arc.meta, ...plan.meta};\n log('|...-->| recipe evacipated: ', recipe.$meta);\n //log.groupEnd();\n }\n static async executeAll(recipes, runtime, arc) {\n for (const recipe of recipes) {\n await this.execute(recipe, runtime, arc);\n }\n //return Promise.all(recipes?.map(recipe => this.execute(recipe, runtime, arc)));\n }\n static async evacipateAll(recipes, runtime, arc) {\n return Promise.all(recipes?.map(recipe => this.evacipate(recipe, runtime, arc)));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const PathMapper = class {\n map;\n constructor(root) {\n this.map = {};\n this.setRoot(root);\n }\n add(mappings) {\n Object.assign(this.map, mappings || {});\n }\n resolve(path) {\n const bits = path.split('/');\n const top = bits.shift();\n const prefix = this.map[top] || top;\n return [prefix, ...bits].join('/');\n }\n setRoot(root) {\n if (root.length && root[root.length - 1] === '/') {\n root = root.slice(0, -1);\n }\n this.add({\n '$root': root,\n '$arcs': root\n });\n }\n getAbsoluteHereUrl(meta, depth) {\n // you are here\n const localRelative = meta.url.split('/').slice(0, -(depth ?? 1)).join('/');\n if (!globalThis?.document) {\n return localRelative;\n }\n else {\n // document root is here\n let base = document.URL;\n // if document URL has a filename, remove it\n if (base[base.length - 1] !== '/') {\n base = `${base.split('/').slice(0, -1).join('/')}/`;\n }\n // create absoute path to here (aka 'local')\n let localAbsolute = new URL(localRelative, base).href;\n // no trailing slash!\n if (localAbsolute[localAbsolute.length - 1] === '/') {\n localAbsolute = localAbsolute.slice(0, -1);\n }\n return localAbsolute;\n }\n }\n};\nconst root = import.meta.url.split('/').slice(0, -3).join('/');\nexport const Paths = globalThis['Paths'] = new PathMapper(root);\nPaths.add(globalThis.config?.paths);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.code, 'code', 'gold');\nconst defaultParticleBasePath = '$arcs/js/core/Particle.js';\nexport const requireParticleBaseCode = async (sourcePath) => {\n if (!requireParticleBaseCode.source) {\n const path = Paths.resolve(sourcePath || defaultParticleBasePath);\n log('particle base code path: ', path);\n const response = await fetch(path);\n const moduleText = await response.text() + \"\\n//# sourceURL=\" + path + \"\\n\";\n requireParticleBaseCode.source = moduleText.replace(/export /g, '');\n }\n return requireParticleBaseCode.source;\n};\nrequireParticleBaseCode.source = null;\nexport const requireParticleImplCode = async (kind, options) => {\n const code = options?.code || await fetchParticleCode(kind);\n // TODO(sjmiles): brittle content processing, needs to be documented\n return code.slice(code.indexOf('({'));\n};\nexport const fetchParticleCode = async (kind) => {\n if (kind) {\n return await maybeFetchParticleCode(kind);\n }\n log.error(`fetchParticleCode: empty 'kind'`);\n};\nexport const maybeFetchParticleCode = async (kind) => {\n const path = pathForKind(kind);\n try {\n const response = await fetch(path);\n //if (response.ok) {\n return await response.text();\n //}\n }\n catch (x) {\n log.error(`could not locate implementation for particle \"${kind}\" [${path}]`);\n }\n};\nexport const pathForKind = (kind) => {\n if (kind) {\n if (!'$./'.includes(kind[0]) && !kind.includes('://')) {\n kind = `$library/${kind}`;\n }\n if (!kind?.split('/').pop().includes('.')) {\n kind = `${kind}.js`;\n }\n return Paths.resolve(kind);\n }\n return '404';\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { Runtime } from '../Runtime.js';\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { requireParticleImplCode, pathForKind } from './code.js';\nconst log = logFactory(logFactory.flags.isolation, 'vanilla', 'goldenrod');\nconst harden = object => object;\nglobalThis.harden = harden;\nglobalThis.scope = {\n harden\n};\nconst makeKey = () => `i${Math.floor((1 + Math.random() * 9) * 1e14)}`;\nconst timeout = async (func, delayMs) => new Promise(resolve => setTimeout(() => resolve(func()), delayMs));\nexport const initVanilla = (options) => {\n // requiredLog.groupCollapsed('LOCKDOWN');\n try {\n log(deepEqual);\n const utils = { log, resolve, html, makeKey, deepEqual, timeout };\n const scope = {\n // default injections\n ...utils,\n // app injections\n ...options?.injections,\n };\n Object.assign(globalThis.scope, scope);\n Object.assign(globalThis, scope);\n }\n finally {\n /**/\n }\n};\nconst resolve = Paths.resolve.bind(Paths);\nconst html = (strings, ...values) => `${strings[0]}${values.map((v, i) => `${v}${strings[i + 1]}`).join('')}`.trim();\nconst createParticleFactory = async (kind, options) => {\n // ensure our canonical Particle class exists in the isolation chamber\n const { Particle } = await import('../core/Particle.js');\n //const Particle = await requireParticle();\n // // evaluate custom code in isolation chamber\n const implFactory = await requireImplFactory(kind, options);\n // injections\n const log = createLogger(kind);\n const injections = { log, resolve, html, ...options?.injections };\n // construct 3P prototype\n const proto = implFactory(injections);\n // // construct particleFactory\n const particleFactory = (host) => {\n const pipe = {\n log,\n output: host.output.bind(host),\n service: host.service.bind(host)\n };\n return new Particle(proto, pipe, true);\n };\n return particleFactory;\n};\nconst requireImplFactory = async (kind, options) => {\n // snatch up the custom particle code\n const implCode = await requireParticleImplCode(kind, options);\n let factory = (0, eval)(implCode);\n // if it's an object\n if (typeof factory === 'object') {\n // repackage the code to eliminate closures\n factory = repackageImplFactory(factory, kind);\n log('repackaged factory:\\n', factory);\n }\n return globalThis.harden(factory);\n};\nconst repackageImplFactory = (factory, kind) => {\n const { constNames, rewriteConsts, funcNames, rewriteFuncs } = collectDecls(factory);\n const proto = `{${[...constNames, ...funcNames]}}`;\n const moduleRewrite = `\n({log, ...utils}) => {\n// protect utils\nglobalThis.harden(utils);\n// these are just handy\nconst {assign, keys, entries, values, create} = Object;\n// declarations\n${[...rewriteConsts, ...rewriteFuncs].join('\\n\\n')}\n// hardened Object (map) of declarations,\n// suitable to be a prototype\nreturn globalThis.harden(${proto});\n// name the file for debuggers\n//# sourceURL=sandbox/${pathForKind(kind).split('/').pop()}\n};\n `;\n log('rewritten:\\n\\n', moduleRewrite);\n return (0, eval)(moduleRewrite);\n};\nconst collectDecls = factory => {\n // dictionary to 2-tuples\n const props = Object.entries(factory);\n // filter by typeof\n const isFunc = ([n, p]) => typeof p === 'function';\n // filter out forbidden names\n const isForbidden = ([n, p]) => n == 'harden' || n == 'globalThis';\n // get props that are functions\n const funcs = props.filter(item => isFunc(item) && !isForbidden(item));\n // rewrite object declarations as module declarations\n const rewriteFuncs = funcs.map(([n, f]) => {\n const code = f?.toString?.() ?? '';\n const async = code.includes('async');\n const body = code.replace('async ', '').replace('function ', '');\n return `${async ? 'async' : ''} function ${body};`;\n });\n // array up the function names\n const funcNames = funcs.map(([n]) => n);\n // if it's not a Function, it's a const\n const consts = props.filter(item => !isFunc(item) && !isForbidden(item));\n // build const decls\n const rewriteConsts = consts.map(([n, p]) => {\n return `const ${n} = \\`${p}\\`;`;\n });\n // array up the const names\n const constNames = consts.map(([n]) => n);\n return {\n constNames,\n rewriteConsts,\n funcNames,\n rewriteFuncs\n };\n};\nconst createLogger = kind => {\n const _log = logFactory(logFactory.flags.particles, kind, '#002266');\n return (msg, ...args) => {\n const stack = msg?.stack?.split('\\n')?.slice(1, 2) || (new Error()).stack?.split('\\n').slice(2, 3);\n const where = stack\n .map(entry => entry\n .replace(/\\([^()]*?\\)/, '')\n .replace(/ \\([^()]*?\\)/, '')\n .replace('
, ', '')\n .replace('Object.', '')\n .replace('eval at :', '')\n .replace(/\\(|\\)/g, '')\n .replace(/\\[[^\\]]*?\\] /, '')\n .replace(/at (.*) (\\d)/, 'at \"$1\" $2'))\n .reverse()\n .join('\\n')\n .trim();\n if (msg?.message) {\n _log.error(msg.message, ...args, `(${where})`);\n }\n else {\n _log(msg, ...args, `(${where})`);\n }\n };\n};\n// give the runtime a safe way to instantiate Particles\nRuntime.particleIndustry = createParticleFactory;\nRuntime.securityLockdown = initVanilla;\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport * from './date.js';\nexport * from './id.js';\nexport * from './log.js';\nexport * from './matching.js';\nexport * from './object.js';\nexport * from './paths.js';\nexport * from './rand.js';\nexport * from './task.js';\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const computeAgeString = (date, now) => {\n let deltaTime = Math.round((now - date) / 1000);\n if (isNaN(deltaTime)) {\n return `\u2022`;\n }\n let plural = '';\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} second${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} minute${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 24) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} hour${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 24);\n if (deltaTime < 30) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} day${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 30);\n if (deltaTime < 12) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} month${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 12);\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} year${plural} ago`;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/**\n * Perform `action` if `delay` ms have elapsed since last debounce call for `key`.\n *\n * ```\n * // invoke 'task' one second after last time this line executed\n * this.debounceTask = debounce(this.debounceTask, task, 1000);\n * ```\n */\nexport const debounce = (key, action, delay) => {\n if (key) {\n clearTimeout(key);\n }\n if (action && delay) {\n return setTimeout(action, delay);\n }\n};\nexport const async = task => {\n return async (...args) => {\n await Promise.resolve();\n task(...args);\n };\n};\nexport const asyncTask = (task, delayMs) => {\n setTimeout(task, delayMs ?? 0);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n\nexport * from '../js/Runtime.js';\nexport * from '../js/core/EventEmitter.js';\nexport * from '../js/core/Store.js';\nexport * from '../js/core/Arc.js';\nexport * from '../js/core/Host.js';\nexport * from '../js/core/Decorator.js';\nexport * from '../js/recipe/Chef.js';\nexport * from '../js/recipe/ParticleCook.js';\nexport * from '../js/recipe/StoreCook.js';\nexport * from '../js/recipe/RecipeParser.js';\nexport * from '../js/isolation/code.js';\nexport * from '../js/isolation/vanilla.js';\n\nimport * as utils from '../js/utils/utils.js';\nconst {logFactory, Paths} = utils;\nexport {logFactory, Paths, utils};\n\nconst root = import.meta.url.split('/').slice(0, -1).join('/');\nPaths.setRoot(root);\n"],
+ "mappings": ";;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAYQA,SAAQC,SAAQC,OAAMC,SAAQC,UAAS,gBAAgB,gBACzD,OACEC,MAAK,SACPC,MAEA,gBAiFO,aA6GP,iBAIO;AAnNb;AAAA;AAYA,KAAM,EAAE,QAAAN,SAAQ,QAAAC,SAAQ,MAAAC,OAAM,QAAAC,SAAQ,SAAAC,UAAS,gBAAgB,mBAAmB;AAClF,IAAM,QAAQ,WAAW,YAAY,CAAC;AACtC,KAAM,EAAE,KAAAC,MAAK,YAAY;AACzB,IAAMC,OAAM,MAAMN,QAAO,IAAI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;AAAA,EACnC;AACJ;AACO,IAAM,QAAQ,UAAQ;AACzB,SAAO,UAAU,SAAS;AACtB,UAAM,QAAQ,QAAQ;AACtB,SAAK,GAAG,IAAI;AAAA,EAChB;AACJ;AACO,IAAM,YAAY,CAAC,MAAM,YAAY;AACxC,aAAW,MAAM,WAAW,CAAC;AACjC;;;ACRA,IAAM,EAAC,YAAAC,aAAY,OAAAC,OAAK,IAAI;AAG5B,IAAMC,QAAO,YAAY,IAAI,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG;AAC7DC,OAAM,QAAQD,KAAI;",
"names": ["create", "assign", "keys", "values", "entries", "log", "nob", "key", "log", "output", "key", "values", "entries", "key", "entries", "keys", "customLogFactory", "key", "create", "keys", "key", "log", "keys", "key", "log", "entries", "create", "key", "log", "values", "log", "log", "root", "log", "log", "timeout", "resolve", "scope", "values", "Particle", "async", "key", "logFactory", "Paths", "root", "Paths"]
}
diff --git a/pkg/Library/Core/arcs.min.js b/pkg/Library/Core/arcs.min.js
index 5f003a0d..d1b9f60d 100644
--- a/pkg/Library/Core/arcs.min.js
+++ b/pkg/Library/Core/arcs.min.js
@@ -1,6 +1,6 @@
-var et=Object.defineProperty;var kt=(s,t,e)=>t in s?et(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var Dt=(s,t)=>()=>(s&&(t=s(s=0)),t);var st=(s,t)=>{for(var e in t)et(s,e,{get:t[e],enumerable:!0})};var w=(s,t,e)=>(kt(s,typeof t!="symbol"?t+"":t,e),e);var wt={};st(wt,{Particle:()=>B,ParticleApi:()=>Y});var xt,St,vt,le,X,he,pe,T,Q,ue,D,fe,Y,de,B,Pt=Dt(()=>{({create:xt,assign:St,keys:vt,values:le,entries:X,defineProperty:he,setPrototypeOf:pe}=Object),T=globalThis.scope??{},{log:Q,timeout:ue}=T,D=()=>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 X(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[T.makeKey()]=t)}push(...s){this.add(...s)}remove(s){X(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}},Y=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}},B=class{pipe;impl;internal;constructor(t,e,r){this.pipe=e,this.impl=xt(t),he(this,"internal",de(D())),this.internal.$busy=0,this.internal.beStateful=!0,this.internal.state=D()}get log(){return this.pipe?.log||Q}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=D()),this.internal.inputs=this.validateInputs(),await this.maybeUpdate())}catch(t){Q.error(t)}this.internal.validator=null}}validateInputs(){let t=St(D(),this.inputs);return X(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){Q.error(e)}finally{this.internal.$busy--}}};T.harden(globalThis);T.harden(B)});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 rt=["log","group","groupCollapsed","groupEnd","dir"],it=["warn","error"];var{fromEntries:at}=Object,ot=(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=at(rt.map(h=>[h,ot(s,t,e,r,h)])),a=at(it.map(h=>[h,ot(!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:M,entries:nt,create:At}=Object,P=s=>Object.values(s),z=()=>At(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=z(),this.stores=z(),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||M(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=z(),r=t.meta?.inputs;if(r==="*")nt(this.stores).forEach(([i,a])=>e[i]=a.pojo);else{let i=t.meta?.staticInputs;Tt(e,i),r&&(r.forEach(a=>this.computeInput(nt(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=M(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=>M(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 Mt=(s,t)=>{let e=t;if(t){if(Array.isArray(t)){Array.isArray(s)||(s=[]);for(let i=0;i0&&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},ct=s=>s===void 0?null:(s&&typeof s=="object"&&Object.getOwnPropertyNames(s).forEach(e=>{let r=s[e];r===void 0?delete s[e]:ct(r)}),s);var{floor:lt,pow:Ut,random:U}=Math,Lt=s=>lt((1+U()*9)*Ut(10,s-1)),j=s=>lt(U()*s),L=s=>s[j(s.length)],Nt=s=>Boolean(U(){e&&typeof e=="object"&&(e.models?(N("applying decorator(s) to list:",e),this.maybeDecorateItem(e,t)):(s?.filter||s?.decorator||s?.collateBy)&&(N("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=It(e,s.decorator,t),e=Ht(e,s.filter,t.impl),e=Kt(e,s),s.models=e)}},It=(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=>{c.privateData=c.privateData||{};let h=Object.freeze(m(c)),y=t(h,a,n);return c.privateData=y.privateData,{...y,...c}}),s.sort(qt("sortKey")),N("decoration was performed")}return s},Ht=(s,t,e)=>(t=e[t]??t,t&&s&&(s=s.filter(t)),s),Kt=(s,t)=>(pt(t).forEach(([e,r])=>{if(r?.collateBy){let i=Jt(s,r.collateBy);s=Vt(i,e,r.$template)}}),s),qt=s=>(t,e)=>Wt(String(t[s]).toLowerCase(),String(e[s]).toLowerCase()),Wt=(s,t)=>st?1:0,Jt=(s,t)=>{let e={};return s.forEach(r=>{let i=r[t];i&&(e[i]||(e[i]=[])).push(r)}),e},Vt=(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:_t}=Object,Gt=s=>o(o.flags.host,`Host (${s})`,L(["#5a189a","#51168b","#48137b","#6b2fa4","#7b46ae","#3f116c"])),$=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?R.maybeDecorateModel(t.model,this.particle):this.arc?.service(this,t)}output(t,e){t&&(this.lastOutput=t,this.arc?.assignOutputs(this,t)),this.template&&(R.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 _t(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])}},K=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)}},E=class extends K{};var C=(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;nt.handle(this,e,r)}async bootstrapParticle(t,e,r){let i=new $(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||C(),t.hosts[r]){let a=1;for(;t.hosts[`${r}-${a}`];a++);r=`${r}-${a}`}let i=new $(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 b.registerParticleFactory(t,b?.particleIndustry(t,b.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(q).find(i=>t.tags?.includes?.(i)),r=q[String(e)]||E;return new r(t)}static registerStoreClass(t,e){q[t]=e}},f=b;w(f,"securityLockdown"),w(f,"particleIndustry"),w(f,"particleOptions");var W=o(o.flags.recipe,"flan","violet"),{entries:Zt,create:te}=Object,v=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],F=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"),x=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 S=o(o.flags.recipe,"Chef","#087f23"),yt=class{static async execute(t,e,r){if(r instanceof Promise){S.error("`arc` must be an Arc, not a Promise. Make sure `boostrapArc` is awaited.");return}S("|-->...| executing recipe: ",t.$meta??"");let i=new v(t);await F.execute(e,r,i.stores),await x.execute(e,r,i.particles),r.meta={...r.meta,...i.meta},S("|...-->| recipe complete: ",t.$meta??"")}static async evacipate(t,e,r){S("|-->...| evacipating recipe: ",t.$meta);let i=new v(t);await x.evacipate(e,r,i.particles),S("|...-->| 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 _=o(o.flags.code,"code","gold"),oe="$arcs/js/core/Particle.js",k=async s=>{if(!k.source){let t=d.resolve(s||oe);_("particle base code path: ",t);let r=await(await fetch(t)).text()+`
+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;i0&&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(){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)=>st?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;nt.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+`
-`;k.source=r.replace(/export /g,"")}return k.source};k.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);_.error("fetchParticleCode: empty 'kind'")},ce=async s=>{let t=G(s);try{return await(await fetch(t)).text()}catch{_.error(`could not locate implementation for particle "${s}" [${t}]`)}},G=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 y={log:i,output:h.output.bind(h),service:h.service.bind(h)};return new e(n,y,!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:
+`;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
@@ -15,14 +15,14 @@ ${[...r,...a].join(`
// suitable to be a prototype
return globalThis.harden(${n});
// name the file for debuggers
-//# sourceURL=sandbox/${G(t).split("/").pop()}
+//# 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 tt=g?.toString?.()??"",Ct=tt.includes("async"),Ft=tt.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(`
+`,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(", ","").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 Z={};st(Z,{PathMapper:()=>$t,Paths:()=>d,arand:()=>L,async:()=>Oe,asyncTask:()=>je,computeAgeString:()=>we,debounce:()=>Pe,deepCopy:()=>m,deepEqual:()=>u,deepUndefinedToNull:()=>ct,irand:()=>j,key:()=>Lt,logFactory:()=>o,makeId:()=>C,matches:()=>J,prob:()=>Nt,shallowMerge:()=>zt,shallowUpdate:()=>Mt});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}=Z;var Ce=import.meta.url.split("/").slice(0,-1).join("/");Ee.setRoot(Ce);export{O as Arc,yt as Chef,I as DataStore,R as Decorator,p as EventEmitter,$ as Host,v as Parser,x as ParticleCook,Ee as Paths,f as Runtime,E as Store,F as StoreCook,ne as fetchParticleCode,ye as initVanilla,Rs as logFactory,ce as maybeFetchParticleCode,G as pathForKind,k as requireParticleBaseCode,bt as requireParticleImplCode,Z as utils};
+`).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
diff --git a/pkg/Library/Core/arcs.min.js.map b/pkg/Library/Core/arcs.min.js.map
index 9840f56b..578cc953 100644
--- a/pkg/Library/Core/arcs.min.js.map
+++ b/pkg/Library/Core/arcs.min.js.map
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": ["../../../core/js/core/Particle.js", "../../../core/js/core/EventEmitter.js", "../../../core/js/utils/types.js", "../../../core/js/utils/log.js", "../../../core/js/core/Arc.js", "../../../core/js/utils/object.js", "../../../core/js/utils/rand.js", "../../../core/js/core/Decorator.js", "../../../core/js/core/Host.js", "../../../core/js/core/Store.js", "../../../core/js/utils/id.js", "../../../core/js/Runtime.js", "../../../core/js/recipe/RecipeParser.js", "../../../core/js/utils/matching.js", "../../../core/js/recipe/StoreCook.js", "../../../core/js/recipe/ParticleCook.js", "../../../core/js/recipe/Chef.js", "../../../core/js/utils/paths.js", "../../../core/js/isolation/code.js", "../../../core/js/isolation/vanilla.js", "../../../core/js/utils/utils.js", "../../../core/js/utils/date.js", "../../../core/js/utils/task.js", "../../../core/src/arcs.ts"],
- "sourcesContent": ["/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/*\n * PSA: code in this file is subject to isolation restrictions, including runtime processing.\n * Particle module interfaces with 3p code, and is often loaded into isolation contexts.\n**/\nconst { create, assign, keys, values, entries, defineProperty, setPrototypeOf } = Object;\nconst scope = globalThis['scope'] ?? {};\nconst { log, timeout } = scope;\nconst nob = () => create(null);\n// yay lambda, he gets a semi-colon ... named classes not so much\nconst storePrototype = new class {\n get empty() {\n return this.length === 0;\n }\n get data() {\n return this;\n }\n get pojo() {\n return this.data;\n }\n get json() {\n return JSON.stringify(this.pojo);\n }\n get pretty() {\n return JSON.stringify(this.pojo, null, ' ');\n }\n get keys() {\n return keys(this.data);\n }\n get length() {\n return keys(this.data).length;\n }\n get values() {\n return values(this.data);\n }\n get entries() {\n return entries(this.data);\n }\n set(key, value) {\n this.data[key] = value;\n }\n setByIndex(index, value) {\n this.data[this.keys[index]] = value;\n }\n add(...values) {\n values.forEach(value => this.data[scope.makeKey()] = value);\n }\n push(...values) {\n this.add(...values);\n }\n remove(value) {\n entries(this.data).find(([key, entry]) => {\n if (entry === value) {\n delete this.data[key];\n return true;\n }\n });\n }\n has(key) {\n return this.data[key] !== undefined;\n }\n get(key) {\n return this.getByKey(key);\n }\n getByKey(key) {\n return this.data[key];\n }\n getByIndex(index) {\n return this.data[this.keys[index]];\n }\n delete(key) {\n delete this.data[key];\n }\n deleteByIndex(index) {\n delete this.data[this.keys[index]];\n }\n assign(dictionary) {\n assign(this.data, dictionary);\n }\n map(mapFunc) {\n return this.values.map(mapFunc);\n }\n toString() {\n return this.pretty;\n }\n};\n/**\n * ParticleAPI functions are called at various points in the particle's lifecycle.\n * Developers should override these functions as needed to give a particle\n * functionality.\n */\nexport class ParticleApi {\n /**\n * Particles that render on a surface should provide a template. The template\n * can include double curly bracketed keys that will be interpolated at\n * runtime.\n *\n * To dynamically change the template, we double curly braced keys must be\n * the only thing inside a div or span:\n * ```\n * {{key}}.\n * {{key}}
\n * ```\n *\n * The value for each key is returned from the {@link render | render method}.\n *\n * Double curly bracketed keys can also be placed inside div definitions to\n * change attributes. In this instance we place them inside quotation marks.\n * For example:\n * ```\n * \n * ```\n */\n get template() {\n return null;\n }\n /**\n * shouldUpdate returns a boolean that indicates if runtime should update\n * when inputs or state change.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if updates should be allowed.\n */\n shouldUpdate(inputs, state) {\n return true;\n }\n /**\n * Update is called anytime an input to the particle changes.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * Inputs are the stores the particle is bound to.\n * State is an object that can be changed and passed to sub-functions.\n * Tools allow the particle to perform supervised activities -\n * for example services are a tool.\n *\n * The update function can return an object containing the new desired\n * value(s) for the stores. For example, if we wanted to update the\n * `Person` and `Address` stores we would return:\n *\n * ```\n * return {\n * Person: 'Jane Smith',\n * Address: '123 Main Street'\n * };\n * ```\n *\n * @param inputs\n * @param state\n * @param tools\n *\n * @returns [OPTIONAL] object containing store to value mappings\n */\n async update(inputs, state, tools) {\n return null;\n }\n /**\n * shouldRender returns a boolean that indicates if runtime should\n * render the template.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if the template should be re-rendered.\n */\n shouldRender(inputs, state) {\n return true;\n }\n /**\n * Render returns an object that contains the key: value pairings\n * that will be interpolated into the {@link template | template}.\n * For example, if the template contained keys `class`,\n * `hideDiv`, and `displayTxt` we could return:\n * ```\n * {\n * class: 'title`,\n * hideDiv: false,\n * displayTxt: \"My Page's Title\"\n * }\n * ```\n *\n * This functions can be overwritten to return the desired\n * values.\n *\n * @param inputs\n * @param state\n */\n render(inputs, state) {\n return null;\n }\n}\nconst privateProperty = initialValue => {\n let value = initialValue;\n return { get: () => value, set: v => value = v };\n};\nexport class Particle {\n pipe;\n impl;\n internal;\n constructor(proto, pipe, beStateful) {\n this.pipe = pipe;\n this.impl = create(proto);\n defineProperty(this, 'internal', privateProperty(nob()));\n this.internal.$busy = 0;\n //if (beStateful) {\n this.internal.beStateful = true;\n this.internal.state = nob();\n //}\n }\n get log() {\n return this.pipe?.log || log;\n }\n get template() {\n return this.impl?.template;\n }\n get config() {\n return {\n template: this.template\n };\n }\n // set-trap for inputs, so we can do work when inputs change\n set inputs(inputs) {\n //this.log(inputs);\n this.internal.inputs = inputs;\n this.invalidateInputs();\n }\n get inputs() {\n return this.internal.inputs;\n }\n get state() {\n return this.internal.state;\n }\n async service(request) {\n return this.pipe?.service?.(request);\n }\n invalidateInputs() {\n this.invalidate();\n }\n // validate after the next microtask\n invalidate() {\n if (!this.internal.validator) {\n //this.internal.validator = this.async(this.validate);\n this.internal.validator = timeout(this.validate.bind(this), 1);\n }\n }\n // call fn after a microtask boundary\n async(fn) {\n return Promise.resolve().then(fn.bind(this));\n }\n // activate particle lifecycle\n async validate() {\n //this.log('validate');\n if (this.internal.validator) {\n // try..finally to ensure we nullify `validator`\n try {\n this.internal.$validateAfterBusy = this.internal.$busy;\n if (!this.internal.$busy) {\n // if we're not stateful\n if (!this.internal.beStateful) {\n // then it's a fresh state every validation\n this.internal.state = nob();\n }\n // inputs are immutable (changes to them are ignored)\n this.internal.inputs = this.validateInputs();\n // let the impl decide what to do\n await this.maybeUpdate();\n }\n }\n catch (e) {\n log.error(e);\n }\n // nullify validator _after_ methods so state changes don't reschedule validation\n this.internal.validator = null;\n }\n }\n validateInputs() {\n // shallow-clone our input dictionary\n const inputs = assign(nob(), this.inputs);\n // for each input, try to provide prototypical helpers\n entries(inputs).forEach(([key, value]) => {\n if (value && (typeof value === 'object')) {\n if (!Array.isArray(value)) {\n value = setPrototypeOf({ ...value }, storePrototype);\n }\n inputs[key] = value;\n }\n });\n //return harden(inputs);\n return inputs;\n }\n implements(methodName) {\n return typeof this.impl?.[methodName] === 'function';\n }\n async maybeUpdate() {\n if (await this.checkInit()) {\n if (!this.canUpdate()) {\n // we might want to render even if we don't update,\n // if we `outputData` the system will add render models\n this.outputData(null);\n }\n if (await this.shouldUpdate(this.inputs, this.state)) {\n this.update();\n }\n }\n }\n async checkInit() {\n if (!this.internal.initialized) {\n this.internal.initialized = true;\n if (this.implements('initialize')) {\n await this.asyncMethod(this.impl.initialize);\n }\n }\n return true;\n }\n canUpdate() {\n return this.implements('update');\n }\n async shouldUpdate(inputs, state) {\n //return true;\n // not implementing `shouldUpdate`, means the value should always be true\n // TODO(sjmiles): this violates our 'false by default' convention, but the\n // naming is awkward: `shouldNotUpdate`? `preventUpdate`?\n return !this.impl?.shouldUpdate || (await this.impl.shouldUpdate(inputs, state) !== false);\n }\n update() {\n this.asyncMethod(this.impl?.update);\n }\n outputData(data) {\n this.pipe?.output?.(data, this.maybeRender());\n }\n maybeRender() {\n //this.log('maybeRender');\n if (this.template) {\n const { inputs, state } = this.internal;\n if (this.impl?.shouldRender?.(inputs, state) !== false) {\n //this.log('render');\n if (this.implements('render')) {\n return this.impl.render(inputs, state);\n }\n else {\n return { ...inputs, ...state };\n }\n }\n }\n }\n async handleEvent({ handler, data }) {\n const onhandler = this.impl?.[handler];\n if (onhandler) {\n this.internal.inputs.eventlet = data;\n await this.asyncMethod(onhandler.bind(this.impl), { eventlet: data });\n this.internal.inputs.eventlet = null;\n }\n else {\n //console.log(`[${this.id}] event handler [${handler}] not found`);\n }\n }\n async asyncMethod(asyncMethod, injections) {\n if (asyncMethod) {\n const { inputs, state } = this.internal;\n const stdlib = {\n service: async (request) => this.service(request),\n invalidate: () => this.invalidate(),\n output: async (data) => this.outputData(data)\n };\n const task = asyncMethod.bind(this.impl, inputs, state, { ...stdlib, ...injections });\n this.outputData(await this.try(task));\n if (!this.internal.$busy && this.internal.$validateAfterBusy) {\n this.invalidate();\n }\n }\n }\n async try(asyncFunc) {\n this.internal.$busy++;\n try {\n return await asyncFunc();\n }\n catch (e) {\n log.error(e);\n }\n finally {\n this.internal.$busy--;\n }\n }\n}\nscope.harden(globalThis);\nscope.harden(Particle);\n// log('Any leaked values? Must pass three tests:');\n// try { globalThis['sneaky'] = 42; } catch(x) { log('sneaky test: pass'); }\n// try { Particle['foo'] = 42; } catch(x) { log('Particle.foo test: pass'); }\n// try { log['foo'] = 42; } catch(x) { log('log.foo test: pass'); };\nParticle;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport class EventEmitter {\n // map of event name to listener array\n listeners = {};\n getEventListeners(eventName) {\n return this.listeners[eventName] || (this.listeners[eventName] = []);\n }\n fire(eventName, ...args) {\n const listeners = this.getEventListeners(eventName);\n if (listeners?.forEach) {\n listeners.forEach(listener => listener(...args));\n }\n }\n listen(eventName, listener, listenerName) {\n const listeners = this.getEventListeners(eventName);\n listeners.push(listener);\n listener._name = listenerName || '(unnamed listener)';\n return listener;\n }\n unlisten(eventName, listener) {\n const list = this.getEventListeners(eventName);\n const index = (typeof listener === 'string') ? list.findIndex(l => l._name === listener) : list.indexOf(listener);\n if (index >= 0) {\n list.splice(index, 1);\n }\n else {\n console.warn('failed to unlisten from', eventName);\n }\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const logKinds = ['log', 'group', 'groupCollapsed', 'groupEnd', 'dir'];\nexport const errKinds = ['warn', 'error'];\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logKinds, errKinds } from './types.js';\nconst { fromEntries } = Object;\nconst _logFactory = (enable, preamble, bg, color, kind = 'log') => {\n if (!enable) {\n return () => { };\n }\n if (kind === 'dir') {\n return console.dir.bind(console);\n }\n const style = `background: ${bg || 'gray'}; color: ${color || 'white'}; padding: 1px 6px 2px 7px; border-radius: 6px 0 0 6px;`;\n return console[kind].bind(console, `%c${preamble}`, style);\n};\nexport const logFactory = (enable, preamble, bg = '', color = '') => {\n const debugLoggers = fromEntries(logKinds.map(kind => [kind, _logFactory(enable, preamble, bg, color, kind)]));\n const errorLoggers = fromEntries(errKinds.map(kind => [kind, _logFactory(true, preamble, bg, color, kind)]));\n const loggers = { ...debugLoggers, ...errorLoggers };\n // Inject `log` as default, keeping all loggers available to be invoked by name.\n const log = loggers.log;\n Object.assign(log, loggers);\n return log;\n};\nlogFactory.flags = globalThis.config?.logFlags || {};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nimport { logFactory } from '../utils/log.js';\nconst customLogFactory = (id) => logFactory(logFactory.flags.arc, `Arc (${id})`, 'slateblue');\nconst { assign, keys, entries, create } = Object;\nconst values = (o) => Object.values(o);\nconst nob = () => create(null);\nexport class Arc extends EventEmitter {\n log;\n id;\n meta;\n stores;\n hosts;\n surface;\n composer;\n hostService;\n constructor(id, meta, surface) {\n super();\n this.id = id;\n this.meta = meta;\n this.surface = surface;\n this.hosts = nob();\n this.stores = nob();\n this.log = customLogFactory(id);\n }\n async addHost(host, surface) {\n // to support hosts we need a composer\n await this.ensureComposer();\n // bookkeep\n this.hosts[host.id] = host;\n host.arc = this;\n // TODO(sjmiles): support per host surfacing?\n //await host.bindToSurface(surface ?? this.surface);\n // begin work\n this.updateHost(host);\n return host;\n }\n async ensureComposer() {\n if (!this.composer && this.surface) {\n // create composer\n this.composer = await this.surface.createComposer('root');\n // pipeline for events from composer to this.onevent\n // TODO(sjmiles): use 'bind' to avoid a closure and improve the stack trace\n this.composer.onevent = this.onevent.bind(this);\n }\n }\n rerender() {\n values(this.hosts).forEach(h => h.rerender());\n }\n removeHost(id) {\n this.hosts[id]?.detach();\n delete this.hosts[id];\n }\n addStore(storeId, store) {\n if (store && !this.stores[storeId]) {\n this.stores[storeId] = store;\n store.listen('change', () => this.storeChanged(storeId, store), this.id);\n }\n }\n removeStore(storeId) {\n const store = this.stores[storeId];\n if (store) {\n store.unlisten('change', this.id);\n }\n delete this.stores[storeId];\n }\n // TODO(sjmiles): 2nd param is used in overrides, make explicit\n storeChanged(storeId, store) {\n this.log(`storeChanged: \"${storeId}\"`);\n const isBound = inputs => inputs && inputs.some(input => values(input)[0] == storeId || keys(input)[0] == storeId);\n values(this.hosts).forEach(host => {\n const inputs = host.meta?.inputs;\n if (inputs === '*' || isBound(inputs)) {\n this.log(`host \"${host.id}\" has interest in \"${storeId}\"`);\n // TODO(sjmiles): we only have to update inputs for storeId, we lose efficiency here\n this.updateHost(host);\n }\n });\n this.fire('store-changed', storeId);\n }\n updateParticleMeta(hostId, meta) {\n const host = this.hosts[hostId];\n host.meta = meta;\n this.updateHost(host);\n }\n updateHost(host) {\n host.inputs = this.computeInputs(host);\n }\n // TODO(sjmiles): debounce? (update is sync-debounced already)\n // complement to `assignOutputs`\n computeInputs(host) {\n const inputs = nob();\n const inputBindings = host.meta?.inputs;\n if (inputBindings === '*') {\n // TODO(sjmiles): we could make the contract that the bindAll inputs are\n // names (or names + meta) only. The Particle could look up values via\n // service (to reduce throughput requirements)\n entries(this.stores).forEach(([name, store]) => inputs[name] = store.pojo);\n }\n else {\n const staticInputs = host.meta?.staticInputs;\n assign(inputs, staticInputs);\n if (inputBindings) {\n inputBindings.forEach(input => this.computeInput(entries(input)[0], inputs));\n this.log(`computeInputs(${host.id}) =`, inputs);\n }\n }\n return inputs;\n }\n computeInput([name, binding], inputs) {\n const storeName = binding || name;\n const store = this.stores[storeName];\n if (store) {\n inputs[name] = store.pojo;\n }\n else {\n this.log.warn(`computeInput: \"${storeName}\" (bound to \"${name}\") not found`);\n }\n }\n // complement to `computeInputs`\n assignOutputs({ id, meta }, outputs) {\n const names = keys(outputs);\n if (meta?.outputs && names.length) {\n names.forEach(name => this.assignOutput(name, outputs[name], meta.outputs));\n this.log(`[end][${id}] assignOutputs:`, outputs);\n }\n }\n assignOutput(name, output, outputs) {\n if (output !== undefined) {\n const binding = this.findOutputByName(outputs, name) || name;\n const store = this.stores[binding];\n if (!store) {\n if (outputs?.[name]) {\n this.log.warn(`assignOutputs: no \"${binding}\" store for output \"${name}\"`);\n }\n }\n else {\n // Note: users can mess up output data in any way they see fit, so we should\n // probably invent `outputCleansing`.\n this.log(`assignOutputs: \"${name}\" is dirty, updating Store \"${binding}\"`, output);\n store.data = output;\n }\n }\n }\n findOutputByName(outputs, name) {\n const output = outputs?.find(output => keys(output)[0] === name);\n if (output) {\n return values(output)[0];\n }\n }\n async render(packet) {\n if (this.composer) {\n this.composer.render(packet);\n }\n else {\n //this.log.low('render called, but composer is null', packet);\n }\n }\n onevent(pid, eventlet) {\n const host = this.hosts[pid];\n if (host) {\n host.handleEvent(eventlet);\n }\n }\n async service(host, request) {\n let result = await this.surface?.service(request);\n if (result === undefined) {\n result = this.hostService?.(host, request);\n }\n return result;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/*\n * update the fields of `obj` with the fields of `data`,\n * perturbing `obj` as little as possible (since it might be a magic proxy thing\n * like an Automerge document)\n */\nexport const shallowUpdate = (obj, data) => {\n let result = data;\n if (!data) {\n //\n }\n else if (Array.isArray(data)) {\n if (!Array.isArray(obj)) {\n // TODO(sjmiles): eek, very perturbing to obj\n obj = [];\n }\n for (let i = 0; i < data.length; i++) {\n const value = data[i];\n if (obj[i] !== value) {\n obj[i] = value;\n }\n }\n const overage = obj.length - data.length;\n if (overage > 0) {\n obj.splice(data.length, overage);\n }\n }\n else if (typeof data === 'object') {\n result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n const seen = {};\n // for each key in input data ...\n Object.keys(data).forEach(key => {\n // copy that data into output\n result[key] = data[key];\n // remember the key\n seen[key] = true;\n });\n // for each key in the output data...\n Object.keys(result).forEach(key => {\n // if this key was not in the input, remove it\n if (!seen[key]) {\n delete result[key];\n }\n });\n }\n return result;\n};\nexport const shallowMerge = (obj, data) => {\n if (data == null) {\n return null;\n }\n if (typeof data === 'object') {\n const result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n Object.keys(data).forEach(key => result[key] = data[key]);\n return result;\n }\n return data;\n};\nexport function deepCopy(datum) {\n if (!datum) {\n return datum;\n }\n else if (Array.isArray(datum)) {\n // This is trivially type safe but tsc needs help\n return datum.map(element => deepCopy(element));\n }\n else if (typeof datum === 'object') {\n const clone = Object.create(null);\n Object.entries(datum).forEach(([key, value]) => {\n clone[key] = deepCopy(value);\n });\n return clone;\n }\n else {\n return datum;\n }\n}\nexport const deepEqual = (a, b) => {\n const type = typeof a;\n // must be same type to be equal\n if (type !== typeof b) {\n return false;\n }\n // we are `deep` because we recursively study object types\n if (type === 'object' && a && b) {\n const aProps = Object.getOwnPropertyNames(a);\n const bProps = Object.getOwnPropertyNames(b);\n // equal if same # of props, and no prop is not deepEqual\n return (aProps.length == bProps.length) && !aProps.some(name => !deepEqual(a[name], b[name]));\n }\n // finally, perform simple comparison\n return (a === b);\n};\nexport const deepUndefinedToNull = (obj) => {\n if (obj === undefined) {\n return null;\n }\n if (obj && (typeof obj === 'object')) {\n // we are `deep` because we recursively study object types\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(name => {\n const prop = obj[name];\n if (prop === undefined) {\n delete obj[name];\n //obj[name] = null;\n }\n else {\n deepUndefinedToNull(prop);\n }\n });\n }\n return obj;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nconst { floor, pow, random } = Math;\n// random n-digit number\nexport const key = (digits) => floor((1 + random() * 9) * pow(10, digits - 1));\n// random integer from [0..range)\nexport const irand = (range) => floor(random() * range);\n// random element from array\nexport const arand = (array) => array[irand(array.length)];\n// test if event has occured, where `probability` is between [0..1]\nexport const prob = (probability) => Boolean(random() < probability);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepCopy } from '../utils/object.js';\nconst log = logFactory(logFactory.flags.decorator, 'Decorator', 'plum');\nconst { values, entries } = Object;\nconst opaqueData = {};\nexport const Decorator = {\n setOpaqueData(name, data) {\n opaqueData[name] = data; //deepCopy(data);\n return name;\n },\n getOpaqueData(name) {\n return opaqueData[name];\n },\n maybeDecorateModel(model, particle) {\n if (model && !Array.isArray(model)) {\n // for each item in model, regardless of key\n values(model).forEach((item) => {\n // is an object?\n if (item && (typeof item === 'object')) {\n // are there sub-models\n if (item['models']) {\n // the decorate this item\n log('applying decorator(s) to list:', item);\n this.maybeDecorateItem(item, particle);\n }\n else {\n // otherwise, check if there are sub-items to decorate\n if (model?.filter || model?.decorator || model?.collateBy) {\n log('scanning for lists in sub-model:', item);\n this.maybeDecorateModel(item, particle);\n }\n }\n }\n });\n }\n // possibly decorated model\n return model;\n },\n maybeDecorateItem(item, particle) {\n let models = (typeof item.models === 'string') ? this.getOpaqueData(item.models) : item.models;\n if (models) {\n // do a decorator\n models = maybeDecorate(models, item.decorator, particle);\n // do a filter\n models = maybeFilter(models, item.filter, particle.impl);\n // do a collator\n models = maybeCollateBy(models, item);\n // mutate items\n item.models = models;\n //console.log(JSON.stringify(models, null, ' '));\n }\n },\n};\nconst maybeDecorate = (models, decorator, particle) => {\n decorator = particle.impl[decorator] ?? decorator;\n const { inputs, state } = particle.internal;\n if (decorator) {\n // TODO(cromwellian): Could be expensive to do everything, store responsibility?\n const immutableInputs = Object.freeze(deepCopy(inputs));\n // we don't want the decorator to have access to mutable globals\n const immutableState = Object.freeze(deepCopy(state));\n // models become decorous\n models = models.map(model => {\n // use previously mutated data or initialize\n // TODO(cromwellian): I'd like to do Object.freeze() here, also somehow not mutate the models inplace\n // Possibly have setOpaqueData wrap the data so the privateData lives on the wrapper + internal immutable data\n model.privateData = model.privateData || {};\n // TODO(cromwellian): also could be done once during setOpaqueData() if we can track privateData differently\n const immutableModel = Object.freeze(deepCopy(model));\n const decorated = decorator(immutableModel, immutableInputs, immutableState);\n // set new privateData from returned\n model.privateData = decorated.privateData;\n return { ...decorated, ...model, };\n });\n // sort (possible that all values undefined)\n models.sort(sortByLc('sortKey'));\n log('decoration was performed');\n }\n //models.forEach(model => delete model.privateData);\n return models;\n};\nconst maybeFilter = (models, filter, impl) => {\n filter = impl[filter] ?? filter;\n if (filter && models) {\n // models become filtrated\n models = models.filter(filter);\n }\n return models;\n};\nconst maybeCollateBy = (models, item) => {\n // construct requested sub-lists\n entries(item).forEach(([name, collator]) => {\n // generate named collations for items of the form `[name]: {collateBy}`\n if (collator?.['collateBy']) {\n // group the models into buckets based on the model-field named by `collateBy`\n const collation = collate(models, collator['collateBy']);\n models = collationToRenderModels(collation, name, collator['$template']);\n }\n });\n return models;\n};\nconst sortByLc = key => (a, b) => sort(String(a[key]).toLowerCase(), String(b[key]).toLowerCase());\n//const sortBy = key => (a, b) => sort(a[key], b[key]);\nconst sort = (a, b) => a < b ? -1 : a > b ? 1 : 0;\nconst collate = (models, collateBy) => {\n const collation = {};\n models.forEach(model => {\n const keyValue = model[collateBy];\n if (keyValue) {\n const category = collation[keyValue] || (collation[keyValue] = []);\n category.push(model);\n }\n });\n return collation;\n};\nconst collationToRenderModels = (collation, name, $template) => {\n return entries(collation).map(([key, models]) => ({\n key,\n [name]: { models, $template },\n single: !(models['length'] !== 1),\n ...models?.[0]\n }));\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { arand } from '../utils/rand.js';\nimport { EventEmitter } from './EventEmitter.js';\nimport { Decorator } from './Decorator.js';\nconst { entries, keys } = Object;\nconst customLogFactory = (id) => logFactory(logFactory.flags.host, `Host (${id})`, arand(['#5a189a', '#51168b', '#48137b', '#6b2fa4', '#7b46ae', '#3f116c']));\n/**\n * Host owns metadata (e.g. `id`, `container`) that its Particle is not allowed to access.\n * Host knows how to talk, asynchronously, to its Particle (potentially using a bus).\n**/\n/* TODO(sjmiles):\nUpdate Cycle Documented Briefly\n1. when a Store changes it invokes it's listeners\n2. when an Arc hears a Store change, it updates Hosts bound to the Store\n3. Arc updates Host by creating an `inputs` object from Stores and metadata\n - ignores fact inputs are accumulated\n - ignores information about which Store has updated\n4. `inputs` object is assigned to `hosts.inputs` \uD83D\uDE43\n5. Host does an expensive `deepEqual` equality check. Turning on `host` logging should reveal `this.log('inputs are not interesting, skipping update');` if data is caught in this trap\n - we can use reference testing here if we are more careful\n about using immutable data\n6. the particle.inputs are assigned (but is really a *merge*)\n*/\nexport class Host extends EventEmitter {\n arc;\n id;\n lastOutput;\n lastPacket;\n lastRenderModel;\n log;\n meta;\n particle;\n constructor(id) {\n super();\n this.log = customLogFactory(id);\n this.id = id;\n }\n onevent(eventlet) {\n this.arc?.onevent(eventlet);\n }\n // Particle and ParticleMeta are separate, host specifically integrates these on behalf of Particle\n installParticle(particle, meta) {\n if (this.particle) {\n this.detachParticle();\n }\n if (particle) {\n this.particle = particle;\n this.meta = meta || this.meta;\n }\n }\n get container() {\n return this.meta?.container || 'root';\n }\n detach() {\n this.detachParticle();\n this.arc = null;\n }\n detachParticle() {\n if (this.particle) {\n this.render({ $clear: true });\n this.particle = null;\n this.meta = null;\n }\n }\n async service(request) {\n if (request?.decorate) {\n return Decorator.maybeDecorateModel(request.model, this.particle);\n }\n return this.arc?.service(this, request);\n }\n output(outputModel, renderModel) {\n if (outputModel) {\n this.lastOutput = outputModel;\n this.arc?.assignOutputs(this, outputModel);\n }\n if (this.template) {\n Decorator.maybeDecorateModel(renderModel, this.particle);\n this.log(renderModel);\n this.lastRenderModel = renderModel;\n this.render(renderModel);\n }\n }\n rerender() {\n if (this.lastRenderModel) {\n this.render(this.lastRenderModel);\n }\n // if (this.lastPacket) {\n // this.arc?.render(this.lastPacket);\n // }\n }\n render(model) {\n const { id, container, template } = this;\n const content = { model, template };\n const packet = { id, container, content };\n this.arc?.render(packet);\n this.lastPacket = packet;\n }\n set inputs(inputs) {\n if (this.particle && inputs) {\n const lastInputs = this.particle.internal.inputs;\n if (this.dirtyCheck(inputs, lastInputs, this.lastOutput)) {\n this.particle.inputs = { ...this.meta?.staticInputs, ...inputs };\n this.fire('inputs-changed');\n }\n else {\n this.log('inputs are uninteresting, skipping update');\n }\n }\n }\n dirtyCheck(inputs, lastInputs, lastOutput) {\n const dirtyBits = ([n, v]) => (lastOutput?.[n] && !deepEqual(lastOutput[n], v))\n || !deepEqual(lastInputs?.[n], v);\n return !lastInputs\n || entries(inputs).length !== this.lastInputsLength(lastInputs)\n || entries(inputs).some(dirtyBits);\n }\n lastInputsLength(lastInputs) {\n return keys(lastInputs).filter(key => !this.meta?.staticInputs?.[key] && key !== 'eventlet').length;\n }\n get config() {\n return this.particle?.config;\n }\n get template() {\n return this.config?.template;\n }\n invalidate() {\n this.particle?.invalidate();\n }\n handleEvent(eventlet) {\n return this.particle?.handleEvent(eventlet);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nconst { create, keys } = Object;\nconst { stringify, parse } = JSON;\nexport class DataStore extends EventEmitter {\n privateData;\n constructor() {\n super();\n }\n setPrivateData(data) {\n this.privateData = data;\n }\n set data(data) {\n this.setPrivateData(data);\n }\n get data() {\n return this.privateData;\n }\n toString() {\n return this.pretty;\n }\n get isObject() {\n return this.data && typeof this.data === 'object';\n }\n get pojo() {\n return this.data;\n }\n get json() {\n return stringify(this.data);\n }\n set json(json) {\n let value = null;\n try {\n value = parse(json);\n }\n catch (x) {\n //\n }\n this.data = value;\n }\n get pretty() {\n const sorted = {};\n const pojo = this.pojo;\n keys(pojo).sort().forEach(key => sorted[key] = pojo[key]);\n return stringify(sorted, null, ' ');\n }\n}\nclass ObservableStore extends DataStore {\n change(mutator) {\n mutator(this);\n this.doChange();\n }\n doChange() {\n this.fire('change', this);\n this.onChange(this);\n }\n onChange(store) {\n // override\n }\n set data(data) {\n this.change(self => self.setPrivateData(data));\n }\n // TODO(sjmiles): one of the compile/build/bundle tools\n // evacipates the inherited getter, so we clone it\n get data() {\n return this['privateData'];\n }\n set(key, value) {\n if (!this.data) {\n this.setPrivateData(create(null));\n }\n if (value !== undefined) {\n this.change(self => self.data[key] = value);\n }\n else {\n this.delete(key);\n }\n }\n delete(key) {\n this.change(doc => delete doc.data[key]);\n }\n}\nclass PersistableStore extends ObservableStore {\n meta;\n constructor(meta) {\n super();\n this.meta = { ...meta };\n }\n toString() {\n return `${JSON.stringify(this.meta, null, ' ')}, ${this.pretty}`;\n }\n get tags() {\n return this.meta.tags ?? (this.meta.tags = []);\n }\n is(...tags) {\n // true if every member of `tags` is also in `this.tags`\n return tags.every(tag => this.tags.includes(tag));\n }\n isCollection() {\n return this.meta.type?.[0] === '[';\n }\n shouldPersist() {\n return this.is('persisted') && !this.is('volatile');\n }\n async doChange() {\n // do not await\n this.persist();\n return super.doChange();\n }\n // TODO(sjmiles): as of now the persist/restore methods\n // are bound in Runtime:addStore\n async persist() {\n }\n async restore( /*value: any*/) {\n }\n // delete() {\n // this.persistor?.remove(this);\n // }\n save() {\n return this.json;\n }\n load(serial, defaultValue) {\n let value = defaultValue;\n try {\n if (serial) {\n value = parse(serial);\n }\n }\n catch (x) {\n //\n }\n if (value !== undefined) {\n this.data = value;\n }\n }\n}\nexport class Store extends PersistableStore {\n}\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { irand } from \"./rand.js\";\nexport const makeId = (pairs, digits, delim) => {\n pairs = pairs || 2;\n digits = digits || 2;\n delim = delim || '-';\n const min = Math.pow(10, digits - 1);\n const range = Math.pow(10, digits) - min;\n const result = [];\n for (let i = 0; i < pairs; i++) {\n result.push(`${irand(range - min) + min}`);\n }\n return result.join(delim);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Arc } from './core/Arc.js';\nimport { Host } from './core/Host.js';\nimport { Store } from './core/Store.js';\nimport { EventEmitter } from './core/EventEmitter.js';\nimport { logFactory } from './utils/log.js';\nimport { makeId } from './utils/id.js';\nconst log = logFactory(logFactory.flags.runtime, 'runtime', '#873600');\nconst particleFactoryCache = {};\nconst storeFactories = {};\nconst { keys } = Object;\nexport class Runtime extends EventEmitter {\n log;\n uid; // user id\n nid; // network id\n arcs;\n stores;\n peers;\n shares;\n endpoint;\n network;\n surfaces;\n persistor;\n prettyUid;\n static securityLockdown;\n static particleIndustry;\n static particleOptions;\n constructor(uid) {\n uid = uid || 'user';\n super();\n this.arcs = {};\n this.surfaces = {};\n this.stores = {};\n this.peers = new Set();\n this.shares = new Set();\n this.setUid(uid);\n this.log = logFactory(logFactory.flags.runtime, `runtime:[${this.prettyUid}]`, '#873600');\n //Runtime.securityLockdown?.(Runtime.particleOptions);\n }\n setUid(uid) {\n this.uid = uid;\n this.nid = `${uid}:${makeId(1, 2)}`;\n this.prettyUid = uid.substring(0, uid.indexOf('@') + 1) || uid;\n }\n async bootstrapArc(name, meta, surface, service) {\n // make an arc on `surface`\n const arc = new Arc(name, meta, surface);\n // install service handler\n arc.hostService = this.serviceFactory(service);\n // add `arc` to runtime\n await this.addArc(arc);\n // fin\n return arc;\n }\n serviceFactory(service) {\n return async (host, request) => service.handle(this, host, request);\n }\n async bootstrapParticle(arc, id, meta) {\n // make a host\n const host = new Host(id);\n // make a particle\n await this.marshalParticle(host, meta);\n // add `host` to `arc`\n const promise = arc.addHost(host);\n // report\n log('bootstrapped particle', id);\n //log(host);\n // we'll call you when it's ready\n return promise;\n }\n // no-op surface mapping\n addSurface(id, surface) {\n this.surfaces[id] = surface;\n }\n getSurface(id) {\n return this.surfaces[id];\n }\n // map arcs by arc.id\n addArc(arc) {\n const { id } = arc;\n if (id && !this.arcs[id]) {\n return this.arcs[id] = arc;\n }\n throw `arc has no id, or id \"${id}\" is already in use`;\n }\n removeArc(arc) {\n const { id } = arc;\n if (!id || !this.arcs[id]) {\n throw !id ? `arc has no id` : `id \"${id}\" is not in use`;\n }\n delete this.arcs[id];\n }\n // create a particle inside of host\n async marshalParticle(host, particleMeta) {\n const particle = await this.createParticle(host, particleMeta.kind);\n host.installParticle(particle, particleMeta);\n }\n // create a host, install a particle, add host to arc\n async installParticle(arc, particleMeta, name) {\n this.log('installParticle', name, particleMeta, arc.id);\n // provide a default name\n name = name || makeId();\n // deduplicate name\n if (arc.hosts[name]) {\n let n = 1;\n for (; (arc.hosts[`${name}-${n}`]); n++)\n ;\n name = `${name}-${n}`;\n }\n // build the structure\n const host = new Host(name);\n await this.marshalParticle(host, particleMeta);\n arc.addHost(host);\n return host;\n }\n // map a store by a Runtime-specific storeId\n // Stores have no intrinsic id\n addStore(storeId, store) {\n // if the store needs to discuss things with Runtime\n // TODO(sjmiles): this is likely unsafe for re-entry\n if (store.marshal) {\n store.marshal(this);\n }\n // bind to persist/restore functions\n store.persist = async () => this.persistStore(storeId, store);\n store.restore = async () => this.restoreStore(storeId, store);\n // override the Store's own persistor to use the runtime persistor\n // TODO(sjmiles): why?\n // if (store.persistor) {\n // store.persistor.persist = store => this.persistor?.persist(storeId, store);\n // }\n // bind this.storeChanged to store.change (and name the binding)\n const name = `${this.nid}:${storeId}-changed`;\n const onChange = this.storeChanged.bind(this, storeId);\n store.listen('change', onChange, name);\n // map the store\n this.stores[storeId] = store;\n // evaluate for sharing\n this.maybeShareStore(storeId);\n // notify listeners that a thing happened\n // TODO(sjmiles): makes no sense without id\n //this.fire('store-added', store);\n }\n async persistStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`persistStore \"${storeId}\"`);\n return this.persistor.persist?.(storeId, store);\n }\n }\n async restoreStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`restoreStore \"${storeId}\"`);\n return this.persistor.restore?.(storeId);\n }\n }\n storeChanged(storeId, store) {\n this.log('storeChanged', storeId);\n this.network?.invalidatePeers(storeId);\n this.onStoreChange(storeId, store);\n this.fire('store-changed', { storeId, store });\n }\n // TODO(sjmiles): evacipate this method\n onStoreChange(storeId, store) {\n // override for bespoke response\n }\n do(storeId, task) {\n task(this.stores[storeId]);\n }\n removeStore(storeId) {\n this.do(storeId, store => {\n store?.unlisten('change', `${this.nid}:${storeId}-changed`);\n });\n delete this.stores[storeId];\n }\n maybeShareStore(storeId) {\n this.do(storeId, store => {\n if (store?.is('shared')) {\n this.shareStore(storeId);\n }\n });\n }\n addPeer(peerId) {\n this.peers.add(peerId);\n [...this.shares].forEach(storeId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n shareStore(storeId) {\n this.shares.add(storeId);\n [...this.peers].forEach(peerId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n maybeShareStoreWithPeer(storeId, peerId) {\n this.do(storeId, store => {\n const nid = this.uid.replace(/\\./g, '_');\n if (!store.is('private') || (peerId.startsWith(nid))) {\n this.shareStoreWithPeer(storeId, peerId);\n }\n });\n }\n shareStoreWithPeer(storeId, peerId) {\n this.network?.shareStore(storeId, peerId);\n }\n async createParticle(host, kind) {\n try {\n const factory = await this.marshalParticleFactory(kind);\n return factory(host);\n }\n catch (x) {\n log.error(`createParticle(${kind}):`, x);\n }\n }\n async marshalParticleFactory(kind) {\n return particleFactoryCache[kind] ?? this.lateBindParticle(kind);\n }\n lateBindParticle(kind) {\n return Runtime.registerParticleFactory(kind, Runtime?.particleIndustry(kind, Runtime.particleOptions));\n }\n static registerParticleFactory(kind, factoryPromise) {\n return particleFactoryCache[kind] = factoryPromise;\n }\n requireStore(meta) {\n let store = this.stores[meta.name];\n if (!store) {\n store = this.createStore(meta);\n this.addStore(meta.name, store);\n }\n return store;\n }\n createStore(meta) {\n const key = keys(storeFactories).find(tag => meta.tags?.includes?.(tag));\n const storeClass = storeFactories[String(key)] || Store;\n return new storeClass(meta);\n }\n static registerStoreClass(tag, storeClass) {\n storeFactories[tag] = storeClass;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'flan', 'violet');\nconst { entries, create } = Object;\nexport class Parser {\n stores;\n particles;\n slots;\n meta;\n constructor(recipe) {\n this.stores = [];\n this.particles = [];\n this.slots = [];\n this.meta = create(null);\n if (recipe) {\n this.parse(recipe);\n }\n }\n parse(recipe) {\n // `normalize` converts shorthand to longhand before parsing\n const normalized = this.normalize(recipe);\n this.parseSlotSpec(normalized, 'root', '');\n return this;\n }\n normalize(recipe) {\n if (typeof recipe !== 'object') {\n throw Error('recipe must be an Object');\n }\n // TODO(sjmiles): would be great if `normalize` normalized all the things\n return recipe;\n }\n parseSlotSpec(spec, slotName, parentName) {\n // process entries\n for (const key in spec) {\n switch (key) {\n case '$meta':\n // value is a dictionary\n this.meta = { ...this.meta, ...spec.$meta };\n break;\n case '$stores':\n // value is a StoreSpec\n this.parseStoresNode(spec.$stores);\n break;\n default: {\n // value is a ParticleSpec\n const container = parentName ? `${parentName}#${slotName}` : slotName;\n this.parseParticleSpec(container, key, spec[key]);\n break;\n }\n }\n }\n }\n parseStoresNode(stores) {\n for (const key in stores) {\n this.parseStoreSpec(key, stores[key]);\n }\n }\n parseStoreSpec(name, spec) {\n if (this.stores.find(s => s.name === name)) {\n log('duplicate store name');\n return;\n }\n const meta = {\n name,\n type: spec.$type,\n tags: spec.$tags,\n value: spec.$value\n };\n this.stores.push(meta);\n }\n parseParticleSpec(container, id, spec) {\n if (!spec.$kind) {\n log.warn(`parseParticleSpec: malformed spec has no \"kind\":`, spec);\n throw Error();\n }\n if (this.particles.find(s => s.id === id)) {\n log('duplicate particle name');\n return;\n }\n this.particles.push({ id, container, spec });\n if (spec.$slots) {\n this.parseSlotsNode(spec.$slots, id);\n }\n }\n parseSlotsNode(slots, parent) {\n entries(slots).forEach(([key, spec]) => this.parseSlotSpec(spec, key, parent));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport function matches(candidateMeta, targetMeta) {\n for (const property in targetMeta) {\n if (candidateMeta[property] !== targetMeta[property]) {\n return false;\n }\n }\n return true;\n}\n;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { matches } from '../utils/matching.js';\nconst log = logFactory(logFactory.flags.recipe, 'StoreCook', '#99bb15');\nconst { values } = Object;\nconst findStores = (runtime, criteria) => {\n return values(runtime.stores).filter(store => matches(store?.meta, criteria));\n};\nconst mapStore = (runtime, { name, type }) => {\n // TODO(b/244191110): Type matching API to be wired here.\n return findStores(runtime, { name, type })?.[0];\n};\nexport class StoreCook {\n static async execute(runtime, arc, stores) {\n return this.forEachStore(this.realizeStore, runtime, arc, stores);\n }\n static async evacipate(runtime, arc, stores) {\n return this.forEachStore(this.derealizeStore, runtime, arc, stores);\n }\n static async forEachStore(task, runtime, arc, stores) {\n return Promise.all(stores.map(store => task.call(this, runtime, arc, store)));\n }\n static async realizeStore(runtime, arc, rawMeta) {\n const meta = this.constructMeta(runtime, arc, rawMeta);\n let value = meta?.value;\n let store = mapStore(runtime, meta);\n if (store) {\n log(`realizeStore: mapped \"${rawMeta.name}\" to \"${store.meta.name}\"`);\n }\n else {\n store = runtime.createStore(meta);\n log(`realizeStore: created \"${meta.name}\"`);\n // TODO(sjmiles): Stores no longer know their own id, so there is a wrinkle here as we\n // re-route persistence through runtime (so we can bind in the id)\n // Also: the 'id' is known as 'meta.name' here, this is also a problem\n // store && (store.persistor = {\n // restore: store => runtime.persistor?.restore(meta.name, store),\n // persist: () => {}\n // });\n // runtime.addStore(meta.name, store);\n //await store?.restore(meta?.value)\n runtime.addStore(meta.name, store);\n if (store.shouldPersist()) {\n const cached = await store.restore();\n value = cached === undefined ? value : cached;\n }\n }\n if (value !== undefined) {\n log(`setting data to:`, value);\n store.data = value;\n }\n arc.addStore(meta.name, store);\n }\n static async derealizeStore(runtime, arc, spec) {\n runtime.removeStore(spec.$name);\n arc.removeStore(spec.$name);\n }\n static constructMeta(runtime, arc, rawMeta) {\n const meta = {\n ...rawMeta,\n arcid: arc.id,\n uid: runtime.uid,\n };\n return {\n ...meta,\n owner: meta.uid,\n shareid: `${meta.name}:${meta.arcid}:${meta.uid}`\n };\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'ParticleCook', '#5fa530');\nexport class ParticleCook {\n static async execute(runtime, arc, particles) {\n // serial\n for (const particle of particles) {\n await this.realizeParticle(runtime, arc, particle);\n }\n // parallel\n //return Promise.all(particles.map(particle => this.realizeParticle(runtime, arc, particle)));\n }\n static async realizeParticle(runtime, arc, node) {\n log('realizedParticle:', node.id);\n // convert spec to metadata\n const meta = this.specToMeta(node.spec);\n meta.container ||= node.container;\n // make a (hosted) particle\n return runtime.bootstrapParticle(arc, node.id, meta);\n }\n static specToMeta(spec) {\n if (spec.$bindings) {\n console.warn(`Particle '${spec.$kind}' spec contains deprecated $bindings property (${JSON.stringify(spec.$bindings)})`);\n }\n // TODO(sjmiles): impedance mismatch here is likely to cause problems\n const { $kind: kind, $container: container, $staticInputs: staticInputs } = spec;\n const inputs = this.formatBindings(spec.$inputs);\n const outputs = this.formatBindings(spec.$outputs);\n return { kind, staticInputs, inputs, outputs, container };\n }\n static formatBindings(bindings) {\n return bindings?.map?.(binding => typeof binding === 'string' ? { [binding]: binding } : binding);\n }\n static async evacipate(runtime, arc, particles) {\n return Promise.all(particles.map(particle => this.derealizeParticle(runtime, arc, particle)));\n }\n static async derealizeParticle(runtime, arc, node) {\n arc.removeHost(node.id);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { Parser } from './RecipeParser.js';\nimport { StoreCook } from './StoreCook.js';\nimport { ParticleCook } from './ParticleCook.js';\nconst log = logFactory(logFactory.flags.recipe, 'Chef', '#087f23');\nexport class Chef {\n static async execute(recipe, runtime, arc) {\n if (arc instanceof Promise) {\n log.error('`arc` must be an Arc, not a Promise. Make sure `boostrapArc` is awaited.');\n return;\n }\n //log.groupCollapsed('executing recipe...', recipe.$meta);\n log('|-->...| executing recipe: ', recipe.$meta ?? '');\n const plan = new Parser(recipe);\n // `store` preparation\n await StoreCook.execute(runtime, arc, plan.stores);\n // `particle` preparation\n await ParticleCook.execute(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): what do we use this for?\n arc.meta = { ...arc.meta, ...plan.meta };\n log('|...-->| recipe complete: ', recipe.$meta ?? '');\n //log.groupEnd();\n }\n static async evacipate(recipe, runtime, arc) {\n //log.groupCollapsed('evacipating recipe...', recipe.$meta);\n log('|-->...| evacipating recipe: ', recipe.$meta);\n // TODO(sjmiles): this is work we already did\n const plan = new Parser(recipe);\n // `store` work\n // TODO(sjmiles): not sure what stores are unique to this plan\n //await StoreCook.evacipate(runtime, arc, plan);\n // `particle` work\n await ParticleCook.evacipate(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): doh\n //arc.meta = {...arc.meta, ...plan.meta};\n log('|...-->| recipe evacipated: ', recipe.$meta);\n //log.groupEnd();\n }\n static async executeAll(recipes, runtime, arc) {\n for (const recipe of recipes) {\n await this.execute(recipe, runtime, arc);\n }\n //return Promise.all(recipes?.map(recipe => this.execute(recipe, runtime, arc)));\n }\n static async evacipateAll(recipes, runtime, arc) {\n return Promise.all(recipes?.map(recipe => this.evacipate(recipe, runtime, arc)));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const PathMapper = class {\n map;\n constructor(root) {\n this.map = {};\n this.setRoot(root);\n }\n add(mappings) {\n Object.assign(this.map, mappings || {});\n }\n resolve(path) {\n const bits = path.split('/');\n const top = bits.shift();\n const prefix = this.map[top] || top;\n return [prefix, ...bits].join('/');\n }\n setRoot(root) {\n if (root.length && root[root.length - 1] === '/') {\n root = root.slice(0, -1);\n }\n this.add({\n '$root': root,\n '$arcs': root\n });\n }\n getAbsoluteHereUrl(meta, depth) {\n // you are here\n const localRelative = meta.url.split('/').slice(0, -(depth ?? 1)).join('/');\n if (!globalThis?.document) {\n return localRelative;\n }\n else {\n // document root is here\n let base = document.URL;\n // if document URL has a filename, remove it\n if (base[base.length - 1] !== '/') {\n base = `${base.split('/').slice(0, -1).join('/')}/`;\n }\n // create absoute path to here (aka 'local')\n let localAbsolute = new URL(localRelative, base).href;\n // no trailing slash!\n if (localAbsolute[localAbsolute.length - 1] === '/') {\n localAbsolute = localAbsolute.slice(0, -1);\n }\n return localAbsolute;\n }\n }\n};\nconst root = import.meta.url.split('/').slice(0, -3).join('/');\nexport const Paths = globalThis['Paths'] = new PathMapper(root);\nPaths.add(globalThis.config?.paths);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.code, 'code', 'gold');\nconst defaultParticleBasePath = '$arcs/js/core/Particle.js';\nexport const requireParticleBaseCode = async (sourcePath) => {\n if (!requireParticleBaseCode.source) {\n const path = Paths.resolve(sourcePath || defaultParticleBasePath);\n log('particle base code path: ', path);\n const response = await fetch(path);\n const moduleText = await response.text() + \"\\n//# sourceURL=\" + path + \"\\n\";\n requireParticleBaseCode.source = moduleText.replace(/export /g, '');\n }\n return requireParticleBaseCode.source;\n};\nrequireParticleBaseCode.source = null;\nexport const requireParticleImplCode = async (kind, options) => {\n const code = options?.code || await fetchParticleCode(kind);\n // TODO(sjmiles): brittle content processing, needs to be documented\n return code.slice(code.indexOf('({'));\n};\nexport const fetchParticleCode = async (kind) => {\n if (kind) {\n return await maybeFetchParticleCode(kind);\n }\n log.error(`fetchParticleCode: empty 'kind'`);\n};\nexport const maybeFetchParticleCode = async (kind) => {\n const path = pathForKind(kind);\n try {\n const response = await fetch(path);\n //if (response.ok) {\n return await response.text();\n //}\n }\n catch (x) {\n log.error(`could not locate implementation for particle \"${kind}\" [${path}]`);\n }\n};\nexport const pathForKind = (kind) => {\n if (kind) {\n if (!'$./'.includes(kind[0]) && !kind.includes('://')) {\n kind = `$library/${kind}`;\n }\n if (!kind?.split('/').pop().includes('.')) {\n kind = `${kind}.js`;\n }\n return Paths.resolve(kind);\n }\n return '404';\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { Runtime } from '../Runtime.js';\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { requireParticleImplCode, pathForKind } from './code.js';\nconst log = logFactory(logFactory.flags.isolation, 'vanilla', 'goldenrod');\nconst harden = object => object;\nglobalThis.harden = harden;\nglobalThis.scope = {\n harden\n};\nconst makeKey = () => `i${Math.floor((1 + Math.random() * 9) * 1e14)}`;\nconst timeout = async (func, delayMs) => new Promise(resolve => setTimeout(() => resolve(func()), delayMs));\nexport const initVanilla = (options) => {\n // requiredLog.groupCollapsed('LOCKDOWN');\n try {\n log(deepEqual);\n const utils = { log, resolve, html, makeKey, deepEqual, timeout };\n const scope = {\n // default injections\n ...utils,\n // app injections\n ...options?.injections,\n };\n Object.assign(globalThis.scope, scope);\n Object.assign(globalThis, scope);\n }\n finally {\n /**/\n }\n};\nconst resolve = Paths.resolve.bind(Paths);\nconst html = (strings, ...values) => `${strings[0]}${values.map((v, i) => `${v}${strings[i + 1]}`).join('')}`.trim();\nconst createParticleFactory = async (kind, options) => {\n // ensure our canonical Particle class exists in the isolation chamber\n const { Particle } = await import('../core/Particle.js');\n //const Particle = await requireParticle();\n // // evaluate custom code in isolation chamber\n const implFactory = await requireImplFactory(kind, options);\n // injections\n const log = createLogger(kind);\n const injections = { log, resolve, html, ...options?.injections };\n // construct 3P prototype\n const proto = implFactory(injections);\n // // construct particleFactory\n const particleFactory = (host) => {\n const pipe = {\n log,\n output: host.output.bind(host),\n service: host.service.bind(host)\n };\n return new Particle(proto, pipe, true);\n };\n return particleFactory;\n};\nconst requireImplFactory = async (kind, options) => {\n // snatch up the custom particle code\n const implCode = await requireParticleImplCode(kind, options);\n let factory = (0, eval)(implCode);\n // if it's an object\n if (typeof factory === 'object') {\n // repackage the code to eliminate closures\n factory = repackageImplFactory(factory, kind);\n log('repackaged factory:\\n', factory);\n }\n return globalThis.harden(factory);\n};\nconst repackageImplFactory = (factory, kind) => {\n const { constNames, rewriteConsts, funcNames, rewriteFuncs } = collectDecls(factory);\n const proto = `{${[...constNames, ...funcNames]}}`;\n const moduleRewrite = `\n({log, ...utils}) => {\n// protect utils\nglobalThis.harden(utils);\n// these are just handy\nconst {assign, keys, entries, values, create} = Object;\n// declarations\n${[...rewriteConsts, ...rewriteFuncs].join('\\n\\n')}\n// hardened Object (map) of declarations,\n// suitable to be a prototype\nreturn globalThis.harden(${proto});\n// name the file for debuggers\n//# sourceURL=sandbox/${pathForKind(kind).split('/').pop()}\n};\n `;\n log('rewritten:\\n\\n', moduleRewrite);\n return (0, eval)(moduleRewrite);\n};\nconst collectDecls = factory => {\n // dictionary to 2-tuples\n const props = Object.entries(factory);\n // filter by typeof\n const isFunc = ([n, p]) => typeof p === 'function';\n // filter out forbidden names\n const isForbidden = ([n, p]) => n == 'harden' || n == 'globalThis';\n // get props that are functions\n const funcs = props.filter(item => isFunc(item) && !isForbidden(item));\n // rewrite object declarations as module declarations\n const rewriteFuncs = funcs.map(([n, f]) => {\n const code = f?.toString?.() ?? '';\n const async = code.includes('async');\n const body = code.replace('async ', '').replace('function ', '');\n return `${async ? 'async' : ''} function ${body};`;\n });\n // array up the function names\n const funcNames = funcs.map(([n]) => n);\n // if it's not a Function, it's a const\n const consts = props.filter(item => !isFunc(item) && !isForbidden(item));\n // build const decls\n const rewriteConsts = consts.map(([n, p]) => {\n return `const ${n} = \\`${p}\\`;`;\n });\n // array up the const names\n const constNames = consts.map(([n]) => n);\n return {\n constNames,\n rewriteConsts,\n funcNames,\n rewriteFuncs\n };\n};\nconst createLogger = kind => {\n const _log = logFactory(logFactory.flags.particles, kind, '#002266');\n return (msg, ...args) => {\n const stack = msg?.stack?.split('\\n')?.slice(1, 2) || (new Error()).stack?.split('\\n').slice(2, 3);\n const where = stack\n .map(entry => entry\n .replace(/\\([^()]*?\\)/, '')\n .replace(/ \\([^()]*?\\)/, '')\n .replace('
, ', '')\n .replace('Object.', '')\n .replace('eval at :', '')\n .replace(/\\(|\\)/g, '')\n .replace(/\\[[^\\]]*?\\] /, '')\n .replace(/at (.*) (\\d)/, 'at \"$1\" $2'))\n .reverse()\n .join('\\n')\n .trim();\n if (msg?.message) {\n _log.error(msg.message, ...args, `(${where})`);\n }\n else {\n _log(msg, ...args, `(${where})`);\n }\n };\n};\n// give the runtime a safe way to instantiate Particles\nRuntime.particleIndustry = createParticleFactory;\nRuntime.securityLockdown = initVanilla;\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport * from './date.js';\nexport * from './id.js';\nexport * from './log.js';\nexport * from './matching.js';\nexport * from './object.js';\nexport * from './paths.js';\nexport * from './rand.js';\nexport * from './task.js';\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const computeAgeString = (date, now) => {\n let deltaTime = Math.round((now - date) / 1000);\n if (isNaN(deltaTime)) {\n return `\u2022`;\n }\n let plural = '';\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} second${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} minute${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 24) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} hour${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 24);\n if (deltaTime < 30) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} day${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 30);\n if (deltaTime < 12) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} month${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 12);\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} year${plural} ago`;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/**\n * Perform `action` if `delay` ms have elapsed since last debounce call for `key`.\n *\n * ```\n * // invoke 'task' one second after last time this line executed\n * this.debounceTask = debounce(this.debounceTask, task, 1000);\n * ```\n */\nexport const debounce = (key, action, delay) => {\n if (key) {\n clearTimeout(key);\n }\n if (action && delay) {\n return setTimeout(action, delay);\n }\n};\nexport const async = task => {\n return async (...args) => {\n await Promise.resolve();\n task(...args);\n };\n};\nexport const asyncTask = (task, delayMs) => {\n setTimeout(task, delayMs ?? 0);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n\nexport * from '../js/Runtime.js';\nexport * from '../js/core/EventEmitter.js';\nexport * from '../js/core/Store.js';\nexport * from '../js/core/Arc.js';\nexport * from '../js/core/Host.js';\nexport * from '../js/core/Decorator.js';\nexport * from '../js/recipe/Chef.js';\nexport * from '../js/recipe/ParticleCook.js';\nexport * from '../js/recipe/StoreCook.js';\nexport * from '../js/recipe/RecipeParser.js';\nexport * from '../js/isolation/code.js';\nexport * from '../js/isolation/vanilla.js';\n\nimport * as utils from '../js/utils/utils.js';\nconst {logFactory, Paths} = utils;\nexport {logFactory, Paths, utils};\n\nconst root = import.meta.url.split('/').slice(0, -1).join('/');\nPaths.setRoot(root);\n"],
- "mappings": "gRAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,cAAAE,EAAA,gBAAAC,IAAA,IAYQC,GAAQC,GAAQC,GAAMC,GAAQC,EAASC,GAAgBC,GACzDC,EACEC,EAAKC,GACPC,EAEAC,GAiFOZ,EA6GPa,GAIOd,EAnNbe,GAAAC,GAAA,MAYM,CAAE,OAAAd,GAAQ,OAAAC,GAAQ,KAAAC,GAAM,OAAAC,GAAQ,QAAAC,EAAS,eAAAC,GAAgB,eAAAC,IAAmB,QAC5EC,EAAQ,WAAW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AChB,EAESC,GAAY,CAACF,EAAMG,IAAY,CACxC,WAAWH,EAAMG,GAAW,CAAC,CACjC,ECRA,GAAM,CAAC,WAAAC,GAAY,MAAAC,EAAK,EAAIC,EAG5B,IAAMC,GAAO,YAAY,IAAI,MAAM,GAAG,EAAE,MAAM,EAAG,EAAE,EAAE,KAAK,GAAG,EAC7DC,GAAM,QAAQD,EAAI",
- "names": ["Particle_exports", "__export", "Particle", "ParticleApi", "create", "assign", "keys", "values", "entries", "defineProperty", "setPrototypeOf", "scope", "log", "timeout", "nob", "storePrototype", "privateProperty", "init_Particle", "__esmMin", "key", "value", "index", "entry", "dictionary", "mapFunc", "inputs", "state", "tools", "initialValue", "v", "proto", "pipe", "beStateful", "request", "fn", "e", "methodName", "data", "handler", "onhandler", "asyncMethod", "injections", "stdlib", "task", "asyncFunc", "EventEmitter", "eventName", "args", "listeners", "listener", "listenerName", "list", "index", "l", "logKinds", "errKinds", "fromEntries", "_logFactory", "enable", "preamble", "bg", "color", "kind", "style", "logFactory", "debugLoggers", "logKinds", "errorLoggers", "errKinds", "loggers", "log", "customLogFactory", "id", "logFactory", "assign", "keys", "entries", "create", "values", "o", "nob", "Arc", "EventEmitter", "meta", "surface", "host", "h", "storeId", "store", "isBound", "inputs", "input", "hostId", "inputBindings", "name", "staticInputs", "binding", "storeName", "outputs", "names", "output", "packet", "pid", "eventlet", "request", "result", "shallowUpdate", "obj", "data", "result", "value", "overage", "seen", "key", "shallowMerge", "deepCopy", "datum", "element", "clone", "deepEqual", "a", "b", "type", "aProps", "bProps", "name", "deepUndefinedToNull", "prop", "floor", "pow", "random", "key", "digits", "irand", "range", "arand", "array", "prob", "probability", "log", "logFactory", "values", "entries", "opaqueData", "Decorator", "name", "data", "model", "particle", "item", "models", "maybeDecorate", "maybeFilter", "maybeCollateBy", "decorator", "inputs", "state", "immutableInputs", "deepCopy", "immutableState", "immutableModel", "decorated", "sortByLc", "filter", "impl", "collator", "collation", "collate", "collationToRenderModels", "key", "a", "b", "sort", "collateBy", "keyValue", "$template", "entries", "keys", "customLogFactory", "id", "logFactory", "arand", "Host", "EventEmitter", "eventlet", "particle", "meta", "request", "Decorator", "outputModel", "renderModel", "model", "container", "template", "packet", "inputs", "lastInputs", "lastOutput", "dirtyBits", "n", "v", "deepEqual", "key", "create", "keys", "stringify", "parse", "DataStore", "EventEmitter", "data", "json", "value", "sorted", "pojo", "key", "ObservableStore", "mutator", "store", "self", "doc", "PersistableStore", "meta", "tags", "tag", "serial", "defaultValue", "Store", "makeId", "pairs", "digits", "delim", "min", "range", "result", "i", "irand", "log", "logFactory", "particleFactoryCache", "storeFactories", "keys", "_Runtime", "EventEmitter", "uid", "makeId", "name", "meta", "surface", "service", "arc", "Arc", "host", "request", "id", "Host", "promise", "particleMeta", "particle", "n", "storeId", "store", "onChange", "task", "peerId", "nid", "kind", "x", "factoryPromise", "key", "tag", "storeClass", "Store", "Runtime", "__publicField", "log", "logFactory", "entries", "create", "Parser", "recipe", "normalized", "spec", "slotName", "parentName", "key", "container", "stores", "name", "s", "meta", "id", "slots", "parent", "matches", "candidateMeta", "targetMeta", "property", "log", "logFactory", "values", "findStores", "runtime", "criteria", "store", "matches", "mapStore", "name", "type", "StoreCook", "arc", "stores", "task", "rawMeta", "meta", "value", "cached", "spec", "log", "logFactory", "ParticleCook", "runtime", "arc", "particles", "particle", "node", "meta", "spec", "kind", "container", "staticInputs", "inputs", "outputs", "bindings", "binding", "log", "logFactory", "Chef", "recipe", "runtime", "arc", "plan", "Parser", "StoreCook", "ParticleCook", "recipes", "PathMapper", "root", "mappings", "path", "bits", "top", "meta", "depth", "localRelative", "base", "localAbsolute", "Paths", "log", "logFactory", "defaultParticleBasePath", "requireParticleBaseCode", "sourcePath", "path", "Paths", "moduleText", "requireParticleImplCode", "kind", "options", "code", "fetchParticleCode", "maybeFetchParticleCode", "pathForKind", "log", "logFactory", "harden", "object", "makeKey", "timeout", "func", "delayMs", "resolve", "initVanilla", "options", "deepEqual", "scope", "html", "Paths", "strings", "values", "v", "i", "createParticleFactory", "kind", "Particle", "implFactory", "requireImplFactory", "createLogger", "injections", "proto", "host", "pipe", "implCode", "requireParticleImplCode", "factory", "repackageImplFactory", "constNames", "rewriteConsts", "funcNames", "rewriteFuncs", "collectDecls", "moduleRewrite", "pathForKind", "props", "isFunc", "n", "p", "isForbidden", "funcs", "item", "f", "code", "async", "body", "consts", "_log", "msg", "args", "where", "entry", "Runtime", "utils_exports", "__export", "PathMapper", "Paths", "arand", "async", "asyncTask", "computeAgeString", "debounce", "deepCopy", "deepEqual", "deepUndefinedToNull", "irand", "key", "logFactory", "makeId", "matches", "prob", "shallowMerge", "shallowUpdate", "computeAgeString", "date", "now", "deltaTime", "plural", "debounce", "key", "action", "delay", "async", "task", "args", "asyncTask", "delayMs", "logFactory", "Paths", "utils_exports", "root", "Paths"]
+ "sourcesContent": ["/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/*\n * PSA: code in this file is subject to isolation restrictions, including runtime processing.\n * Particle module interfaces with 3p code, and is often loaded into isolation contexts.\n**/\nconst { create, assign, keys, values, entries, defineProperty, setPrototypeOf } = Object;\nconst scope = globalThis['scope'] ?? {};\nconst { log, timeout } = scope;\nconst nob = () => create(null);\n// yay lambda, he gets a semi-colon ... named classes not so much\nconst storePrototype = new class {\n get empty() {\n return this.length === 0;\n }\n get data() {\n return this;\n }\n get pojo() {\n return this.data;\n }\n get json() {\n return JSON.stringify(this.pojo);\n }\n get pretty() {\n return JSON.stringify(this.pojo, null, ' ');\n }\n get keys() {\n return keys(this.data);\n }\n get length() {\n return keys(this.data).length;\n }\n get values() {\n return values(this.data);\n }\n get entries() {\n return entries(this.data);\n }\n set(key, value) {\n this.data[key] = value;\n }\n setByIndex(index, value) {\n this.data[this.keys[index]] = value;\n }\n add(...values) {\n values.forEach(value => this.data[scope.makeKey()] = value);\n }\n push(...values) {\n this.add(...values);\n }\n remove(value) {\n entries(this.data).find(([key, entry]) => {\n if (entry === value) {\n delete this.data[key];\n return true;\n }\n });\n }\n has(key) {\n return this.data[key] !== undefined;\n }\n get(key) {\n return this.getByKey(key);\n }\n getByKey(key) {\n return this.data[key];\n }\n getByIndex(index) {\n return this.data[this.keys[index]];\n }\n delete(key) {\n delete this.data[key];\n }\n deleteByIndex(index) {\n delete this.data[this.keys[index]];\n }\n assign(dictionary) {\n assign(this.data, dictionary);\n }\n map(mapFunc) {\n return this.values.map(mapFunc);\n }\n toString() {\n return this.pretty;\n }\n};\n/**\n * ParticleAPI functions are called at various points in the particle's lifecycle.\n * Developers should override these functions as needed to give a particle\n * functionality.\n */\nexport class ParticleApi {\n /**\n * Particles that render on a surface should provide a template. The template\n * can include double curly bracketed keys that will be interpolated at\n * runtime.\n *\n * To dynamically change the template, we double curly braced keys must be\n * the only thing inside a div or span:\n * ```\n * {{key}}.\n * {{key}}
\n * ```\n *\n * The value for each key is returned from the {@link render | render method}.\n *\n * Double curly bracketed keys can also be placed inside div definitions to\n * change attributes. In this instance we place them inside quotation marks.\n * For example:\n * ```\n * \n * ```\n */\n get template() {\n return null;\n }\n /**\n * shouldUpdate returns a boolean that indicates if runtime should update\n * when inputs or state change.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if updates should be allowed.\n */\n shouldUpdate(inputs, state) {\n return true;\n }\n /**\n * Update is called anytime an input to the particle changes.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * Inputs are the stores the particle is bound to.\n * State is an object that can be changed and passed to sub-functions.\n * Tools allow the particle to perform supervised activities -\n * for example services are a tool.\n *\n * The update function can return an object containing the new desired\n * value(s) for the stores. For example, if we wanted to update the\n * `Person` and `Address` stores we would return:\n *\n * ```\n * return {\n * Person: 'Jane Smith',\n * Address: '123 Main Street'\n * };\n * ```\n *\n * @param inputs\n * @param state\n * @param tools\n *\n * @returns [OPTIONAL] object containing store to value mappings\n */\n async update(inputs, state, tools) {\n return null;\n }\n /**\n * shouldRender returns a boolean that indicates if runtime should\n * render the template.\n *\n * This function can be overwritten to implement the desired\n * behaviour.\n *\n * @param inputs\n * @param state\n *\n * @returns a boolean to indicate if the template should be re-rendered.\n */\n shouldRender(inputs, state) {\n return true;\n }\n /**\n * Render returns an object that contains the key: value pairings\n * that will be interpolated into the {@link template | template}.\n * For example, if the template contained keys `class`,\n * `hideDiv`, and `displayTxt` we could return:\n * ```\n * {\n * class: 'title`,\n * hideDiv: false,\n * displayTxt: \"My Page's Title\"\n * }\n * ```\n *\n * This functions can be overwritten to return the desired\n * values.\n *\n * @param inputs\n * @param state\n */\n render(inputs, state) {\n return null;\n }\n}\nconst privateProperty = initialValue => {\n let value = initialValue;\n return { get: () => value, set: v => value = v };\n};\nexport class Particle {\n pipe;\n impl;\n internal;\n constructor(proto, pipe, beStateful) {\n this.pipe = pipe;\n this.impl = create(proto);\n defineProperty(this, 'internal', privateProperty(nob()));\n this.internal.$busy = 0;\n //if (beStateful) {\n this.internal.beStateful = true;\n this.internal.state = nob();\n //}\n }\n get log() {\n return this.pipe?.log || log;\n }\n get template() {\n return this.impl?.template;\n }\n get config() {\n return {\n template: this.template\n };\n }\n // set-trap for inputs, so we can do work when inputs change\n set inputs(inputs) {\n //this.log(inputs);\n this.internal.inputs = inputs;\n this.invalidateInputs();\n }\n get inputs() {\n return this.internal.inputs;\n }\n get state() {\n return this.internal.state;\n }\n async service(request) {\n return this.pipe?.service?.(request);\n }\n invalidateInputs() {\n this.invalidate();\n }\n // validate after the next microtask\n invalidate() {\n if (!this.internal.validator) {\n //this.internal.validator = this.async(this.validate);\n this.internal.validator = timeout(this.validate.bind(this), 1);\n }\n }\n // call fn after a microtask boundary\n async(fn) {\n return Promise.resolve().then(fn.bind(this));\n }\n // activate particle lifecycle\n async validate() {\n //this.log('validate');\n if (this.internal.validator) {\n // try..finally to ensure we nullify `validator`\n try {\n this.internal.$validateAfterBusy = this.internal.$busy;\n if (!this.internal.$busy) {\n // if we're not stateful\n if (!this.internal.beStateful) {\n // then it's a fresh state every validation\n this.internal.state = nob();\n }\n // inputs are immutable (changes to them are ignored)\n this.internal.inputs = this.validateInputs();\n // let the impl decide what to do\n await this.maybeUpdate();\n }\n }\n catch (e) {\n log.error(e);\n }\n // nullify validator _after_ methods so state changes don't reschedule validation\n this.internal.validator = null;\n }\n }\n validateInputs() {\n // shallow-clone our input dictionary\n const inputs = assign(nob(), this.inputs);\n // for each input, try to provide prototypical helpers\n entries(inputs).forEach(([key, value]) => {\n if (value && (typeof value === 'object')) {\n if (!Array.isArray(value)) {\n value = setPrototypeOf({ ...value }, storePrototype);\n }\n inputs[key] = value;\n }\n });\n //return harden(inputs);\n return inputs;\n }\n implements(methodName) {\n return typeof this.impl?.[methodName] === 'function';\n }\n async maybeUpdate() {\n if (await this.checkInit()) {\n if (!this.canUpdate()) {\n // we might want to render even if we don't update,\n // if we `outputData` the system will add render models\n this.outputData(null);\n }\n if (await this.shouldUpdate(this.inputs, this.state)) {\n this.update();\n }\n }\n }\n async checkInit() {\n if (!this.internal.initialized) {\n this.internal.initialized = true;\n if (this.implements('initialize')) {\n await this.asyncMethod(this.impl.initialize);\n }\n }\n return true;\n }\n canUpdate() {\n return this.implements('update');\n }\n async shouldUpdate(inputs, state) {\n //return true;\n // not implementing `shouldUpdate`, means the value should always be true\n // TODO(sjmiles): this violates our 'false by default' convention, but the\n // naming is awkward: `shouldNotUpdate`? `preventUpdate`?\n return !this.impl?.shouldUpdate || (await this.impl.shouldUpdate(inputs, state) !== false);\n }\n update() {\n this.asyncMethod(this.impl?.update);\n }\n outputData(data) {\n this.pipe?.output?.(data, this.maybeRender());\n }\n maybeRender() {\n //this.log('maybeRender');\n if (this.template) {\n const { inputs, state } = this.internal;\n if (this.impl?.shouldRender?.(inputs, state) !== false) {\n //this.log('render');\n if (this.implements('render')) {\n return this.impl.render(inputs, state);\n }\n else {\n return { ...inputs, ...state };\n }\n }\n }\n }\n async handleEvent({ handler, data }) {\n const onhandler = this.impl?.[handler];\n if (onhandler) {\n this.internal.inputs.eventlet = data;\n await this.asyncMethod(onhandler.bind(this.impl), { eventlet: data });\n this.internal.inputs.eventlet = null;\n }\n else {\n //console.log(`[${this.id}] event handler [${handler}] not found`);\n }\n }\n async asyncMethod(asyncMethod, injections) {\n if (asyncMethod) {\n const { inputs, state } = this.internal;\n const stdlib = {\n service: async (request) => this.service(request),\n invalidate: () => this.invalidate(),\n output: async (data) => this.outputData(data)\n };\n const task = asyncMethod.bind(this.impl, inputs, state, { ...stdlib, ...injections });\n this.outputData(await this.try(task));\n if (!this.internal.$busy && this.internal.$validateAfterBusy) {\n this.invalidate();\n }\n }\n }\n async try(asyncFunc) {\n this.internal.$busy++;\n try {\n return await asyncFunc();\n }\n catch (e) {\n log.error(e);\n }\n finally {\n this.internal.$busy--;\n }\n }\n}\nscope.harden(globalThis);\nscope.harden(Particle);\n// log('Any leaked values? Must pass three tests:');\n// try { globalThis['sneaky'] = 42; } catch(x) { log('sneaky test: pass'); }\n// try { Particle['foo'] = 42; } catch(x) { log('Particle.foo test: pass'); }\n// try { log['foo'] = 42; } catch(x) { log('log.foo test: pass'); };\nParticle;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport class EventEmitter {\n // map of event name to listener array\n listeners = {};\n getEventListeners(eventName) {\n return this.listeners[eventName] || (this.listeners[eventName] = []);\n }\n fire(eventName, ...args) {\n const listeners = this.getEventListeners(eventName);\n if (listeners?.forEach) {\n listeners.forEach(listener => listener(...args));\n }\n }\n listen(eventName, listener, listenerName) {\n const listeners = this.getEventListeners(eventName);\n listeners.push(listener);\n listener._name = listenerName || '(unnamed listener)';\n return listener;\n }\n unlisten(eventName, listener) {\n const list = this.getEventListeners(eventName);\n const index = (typeof listener === 'string') ? list.findIndex(l => l._name === listener) : list.indexOf(listener);\n if (index >= 0) {\n list.splice(index, 1);\n }\n else {\n console.warn('failed to unlisten from', eventName);\n }\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const logKinds = ['log', 'group', 'groupCollapsed', 'groupEnd', 'dir'];\nexport const errKinds = ['warn', 'error'];\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logKinds, errKinds } from './types.js';\nconst { fromEntries } = Object;\nconst _logFactory = (enable, preamble, bg, color, kind = 'log') => {\n if (!enable) {\n return () => { };\n }\n if (kind === 'dir') {\n return console.dir.bind(console);\n }\n const style = `background: ${bg || 'gray'}; color: ${color || 'white'}; padding: 1px 6px 2px 7px; border-radius: 6px 0 0 6px;`;\n return console[kind].bind(console, `%c${preamble}`, style);\n};\nexport const logFactory = (enable, preamble, bg = '', color = '') => {\n const debugLoggers = fromEntries(logKinds.map(kind => [kind, _logFactory(enable, preamble, bg, color, kind)]));\n const errorLoggers = fromEntries(errKinds.map(kind => [kind, _logFactory(true, preamble, bg, color, kind)]));\n const loggers = { ...debugLoggers, ...errorLoggers };\n // Inject `log` as default, keeping all loggers available to be invoked by name.\n const log = loggers.log;\n Object.assign(log, loggers);\n return log;\n};\nlogFactory.flags = globalThis.config?.logFlags || {};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nimport { logFactory } from '../utils/log.js';\nconst customLogFactory = (id) => logFactory(logFactory.flags.arc, `Arc (${id})`, 'slateblue');\nconst { assign, keys, entries, create } = Object;\nconst values = (o) => Object.values(o);\nconst nob = () => create(null);\nexport class Arc extends EventEmitter {\n log;\n id;\n meta;\n stores;\n hosts;\n surface;\n composer;\n hostService;\n constructor(id, meta, surface) {\n super();\n this.id = id;\n this.meta = meta;\n this.surface = surface;\n this.hosts = nob();\n this.stores = nob();\n this.log = customLogFactory(id);\n }\n async addHost(host, surface) {\n // to support hosts we need a composer\n await this.ensureComposer();\n // bookkeep\n this.hosts[host.id] = host;\n host.arc = this;\n // TODO(sjmiles): support per host surfacing?\n //await host.bindToSurface(surface ?? this.surface);\n // begin work\n this.updateHost(host);\n return host;\n }\n async ensureComposer() {\n if (!this.composer && this.surface) {\n // create composer\n this.composer = await this.surface.createComposer('root');\n // pipeline for events from composer to this.onevent\n // TODO(sjmiles): use 'bind' to avoid a closure and improve the stack trace\n this.composer.onevent = this.onevent.bind(this);\n }\n }\n rerender() {\n values(this.hosts).forEach(h => h.rerender());\n }\n removeHost(id) {\n this.hosts[id]?.detach();\n delete this.hosts[id];\n }\n addStore(storeId, store) {\n if (store && !this.stores[storeId]) {\n this.stores[storeId] = store;\n store.listen('change', () => this.storeChanged(storeId, store), this.id);\n }\n }\n removeStore(storeId) {\n const store = this.stores[storeId];\n if (store) {\n store.unlisten('change', this.id);\n }\n delete this.stores[storeId];\n }\n // TODO(sjmiles): 2nd param is used in overrides, make explicit\n storeChanged(storeId, store) {\n this.log(`storeChanged: \"${storeId}\"`);\n const isBound = inputs => inputs && inputs.some(input => values(input)[0] == storeId || keys(input)[0] == storeId);\n values(this.hosts).forEach(host => {\n const inputs = host.meta?.inputs;\n if (inputs === '*' || isBound(inputs)) {\n this.log(`host \"${host.id}\" has interest in \"${storeId}\"`);\n // TODO(sjmiles): we only have to update inputs for storeId, we lose efficiency here\n this.updateHost(host);\n }\n });\n this.fire('store-changed', storeId);\n }\n updateParticleMeta(hostId, meta) {\n const host = this.hosts[hostId];\n host.meta = meta;\n this.updateHost(host);\n }\n updateHost(host) {\n host.inputs = this.computeInputs(host);\n }\n // TODO(sjmiles): debounce? (update is sync-debounced already)\n // complement to `assignOutputs`\n computeInputs(host) {\n const inputs = nob();\n const inputBindings = host.meta?.inputs;\n if (inputBindings === '*') {\n // TODO(sjmiles): we could make the contract that the bindAll inputs are\n // names (or names + meta) only. The Particle could look up values via\n // service (to reduce throughput requirements)\n entries(this.stores).forEach(([name, store]) => inputs[name] = store.pojo);\n }\n else {\n const staticInputs = host.meta?.staticInputs;\n assign(inputs, staticInputs);\n if (inputBindings) {\n inputBindings.forEach(input => this.computeInput(entries(input)[0], inputs));\n this.log(`computeInputs(${host.id}) =`, inputs);\n }\n }\n return inputs;\n }\n computeInput([name, binding], inputs) {\n const storeName = binding || name;\n const store = this.stores[storeName];\n if (store) {\n inputs[name] = store.pojo;\n }\n else {\n this.log.warn(`computeInput: \"${storeName}\" (bound to \"${name}\") not found`);\n }\n }\n // complement to `computeInputs`\n assignOutputs({ id, meta }, outputs) {\n const names = keys(outputs);\n if (meta?.outputs && names.length) {\n names.forEach(name => this.assignOutput(name, outputs[name], meta.outputs));\n this.log(`[end][${id}] assignOutputs:`, outputs);\n }\n }\n assignOutput(name, output, outputs) {\n if (output !== undefined) {\n const binding = this.findOutputByName(outputs, name) || name;\n const store = this.stores[binding];\n if (!store) {\n if (outputs?.[name]) {\n this.log.warn(`assignOutputs: no \"${binding}\" store for output \"${name}\"`);\n }\n }\n else {\n // Note: users can mess up output data in any way they see fit, so we should\n // probably invent `outputCleansing`.\n this.log(`assignOutputs: \"${name}\" is dirty, updating Store \"${binding}\"`, output);\n store.data = output;\n }\n }\n }\n findOutputByName(outputs, name) {\n const output = outputs?.find(output => keys(output)[0] === name);\n if (output) {\n return values(output)[0];\n }\n }\n async render(packet) {\n if (this.composer) {\n this.composer.render(packet);\n }\n else {\n //this.log.low('render called, but composer is null', packet);\n }\n }\n onevent(pid, eventlet) {\n const host = this.hosts[pid];\n if (host) {\n host.handleEvent(eventlet);\n }\n }\n async service(host, request) {\n let result = await this.surface?.service(request);\n if (result === undefined) {\n result = this.hostService?.(host, request);\n }\n return result;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/*\n * update the fields of `obj` with the fields of `data`,\n * perturbing `obj` as little as possible (since it might be a magic proxy thing\n * like an Automerge document)\n */\nexport const shallowUpdate = (obj, data) => {\n let result = data;\n if (!data) {\n //\n }\n else if (Array.isArray(data)) {\n if (!Array.isArray(obj)) {\n // TODO(sjmiles): eek, very perturbing to obj\n obj = [];\n }\n for (let i = 0; i < data.length; i++) {\n const value = data[i];\n if (obj[i] !== value) {\n obj[i] = value;\n }\n }\n const overage = obj.length - data.length;\n if (overage > 0) {\n obj.splice(data.length, overage);\n }\n }\n else if (typeof data === 'object') {\n result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n const seen = {};\n // for each key in input data ...\n Object.keys(data).forEach(key => {\n // copy that data into output\n result[key] = data[key];\n // remember the key\n seen[key] = true;\n });\n // for each key in the output data...\n Object.keys(result).forEach(key => {\n // if this key was not in the input, remove it\n if (!seen[key]) {\n delete result[key];\n }\n });\n }\n return result;\n};\nexport const shallowMerge = (obj, data) => {\n if (data == null) {\n return null;\n }\n if (typeof data === 'object') {\n const result = (obj && typeof obj === 'object') ? obj : Object.create(null);\n Object.keys(data).forEach(key => result[key] = data[key]);\n return result;\n }\n return data;\n};\nexport function deepCopy(datum) {\n if (!datum) {\n return datum;\n }\n else if (Array.isArray(datum)) {\n // This is trivially type safe but tsc needs help\n return datum.map(element => deepCopy(element));\n }\n else if (typeof datum === 'object') {\n const clone = Object.create(null);\n Object.entries(datum).forEach(([key, value]) => {\n clone[key] = deepCopy(value);\n });\n return clone;\n }\n else {\n return datum;\n }\n}\nexport const deepEqual = (a, b) => {\n const type = typeof a;\n // must be same type to be equal\n if (type !== typeof b) {\n return false;\n }\n // we are `deep` because we recursively study object types\n if (type === 'object' && a && b) {\n const aProps = Object.getOwnPropertyNames(a);\n const bProps = Object.getOwnPropertyNames(b);\n // equal if same # of props, and no prop is not deepEqual\n return (aProps.length == bProps.length) && !aProps.some(name => !deepEqual(a[name], b[name]));\n }\n // finally, perform simple comparison\n return (a === b);\n};\nexport const deepUndefinedToNull = (obj) => {\n if (obj === undefined) {\n return null;\n }\n if (obj && (typeof obj === 'object')) {\n // we are `deep` because we recursively study object types\n const props = Object.getOwnPropertyNames(obj);\n props.forEach(name => {\n const prop = obj[name];\n if (prop === undefined) {\n delete obj[name];\n //obj[name] = null;\n }\n else {\n deepUndefinedToNull(prop);\n }\n });\n }\n return obj;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nconst { floor, pow, random } = Math;\n// random n-digit number\nexport const key = (digits) => floor((1 + random() * 9) * pow(10, digits - 1));\n// random integer from [0..range)\nexport const irand = (range) => floor(random() * range);\n// random element from array\nexport const arand = (array) => array[irand(array.length)];\n// test if event has occured, where `probability` is between [0..1]\nexport const prob = (probability) => Boolean(random() < probability);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepCopy } from '../utils/object.js';\nconst log = logFactory(logFactory.flags.decorator, 'Decorator', 'plum');\nconst { values, entries } = Object;\nconst opaqueData = {};\nexport const Decorator = {\n setOpaqueData(name, data) {\n opaqueData[name] = data; //deepCopy(data);\n return name;\n },\n getOpaqueData(name) {\n return opaqueData[name];\n },\n processOutputModel({ privateData }) {\n if (privateData) {\n const key = privateData.__privateKey;\n if (key) {\n const data = Object.values(opaqueData).pop();\n const { _privateKey, ...privy } = privateData;\n data['privateData'] = privy;\n }\n //log.warn(privateData);\n }\n },\n maybeDecorateModel(model, particle) {\n if (model && !Array.isArray(model)) {\n // for each item in model, regardless of key\n values(model).forEach((item) => {\n // is an object?\n if (item && (typeof item === 'object')) {\n // are there sub-models\n if (item['models']) {\n // the decorate this item\n log('applying decorator(s) to list:', item);\n this.maybeDecorateItem(item, particle);\n }\n else {\n // otherwise, check if there are sub-items to decorate\n if (model?.filter || model?.decorator || model?.collateBy) {\n log('scanning for lists in sub-model:', item);\n this.maybeDecorateModel(item, particle);\n }\n }\n }\n });\n }\n // possibly decorated model\n return model;\n },\n maybeDecorateItem(item, particle) {\n let models = (typeof item.models === 'string') ? this.getOpaqueData(item.models) : item.models;\n if (models) {\n // do a decorator\n models = maybeDecorate(models, item.decorator, particle);\n // do a filter\n models = maybeFilter(models, item.filter, particle.impl);\n // do a collator\n models = maybeCollateBy(models, item);\n // mutate items\n item.models = models;\n //console.log(JSON.stringify(models, null, ' '));\n }\n },\n};\nconst maybeDecorate = (models, decorator, particle) => {\n decorator = particle.impl[decorator] ?? decorator;\n const { inputs, state } = particle.internal;\n if (decorator) {\n // TODO(cromwellian): Could be expensive to do everything, store responsibility?\n const immutableInputs = Object.freeze(deepCopy(inputs));\n // we don't want the decorator to have access to mutable globals\n const immutableState = Object.freeze(deepCopy(state));\n // models become decorous\n models = models.map((model, i) => {\n // use previously mutated data or initialize\n // TODO(cromwellian): I'd like to do Object.freeze() here, also somehow not mutate the models inplace\n // Possibly have setOpaqueData wrap the data so the privateData lives on the wrapper + internal immutable data\n model.privateData = model.privateData || {};\n // TODO(cromwellian): also could be done once during setOpaqueData() if we can track privateData differently\n const immutableModel = Object.freeze(deepCopy(model));\n const decorated = decorator(immutableModel, immutableInputs, immutableState);\n // set new privateData from returned\n model.privateData = { ...decorated.privateData, __privateKey: i };\n return { ...decorated, ...model, };\n });\n // sort (possible that all values undefined)\n models.sort(sortByLc('sortKey'));\n log('decoration was performed');\n }\n //models.forEach(model => delete model.privateData);\n return models;\n};\nconst maybeFilter = (models, filter, impl) => {\n filter = impl[filter] ?? filter;\n if (filter && models) {\n // models become filtrated\n models = models.filter(filter);\n }\n return models;\n};\nconst maybeCollateBy = (models, item) => {\n // construct requested sub-lists\n entries(item).forEach(([name, collator]) => {\n // generate named collations for items of the form `[name]: {collateBy}`\n if (collator?.['collateBy']) {\n // group the models into buckets based on the model-field named by `collateBy`\n const collation = collate(models, collator['collateBy']);\n models = collationToRenderModels(collation, name, collator['$template']);\n }\n });\n return models;\n};\nconst sortByLc = key => (a, b) => sort(String(a[key]).toLowerCase(), String(b[key]).toLowerCase());\n//const sortBy = key => (a, b) => sort(a[key], b[key]);\nconst sort = (a, b) => a < b ? -1 : a > b ? 1 : 0;\nconst collate = (models, collateBy) => {\n const collation = {};\n models.forEach(model => {\n const keyValue = model[collateBy];\n if (keyValue) {\n const category = collation[keyValue] || (collation[keyValue] = []);\n category.push(model);\n }\n });\n return collation;\n};\nconst collationToRenderModels = (collation, name, $template) => {\n return entries(collation).map(([key, models]) => ({\n key,\n [name]: { models, $template },\n single: !(models['length'] !== 1),\n ...models?.[0]\n }));\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { arand } from '../utils/rand.js';\nimport { EventEmitter } from './EventEmitter.js';\nimport { Decorator } from './Decorator.js';\nconst { entries, keys } = Object;\nconst customLogFactory = (id) => logFactory(logFactory.flags.host, `Host (${id})`, arand(['#5a189a', '#51168b', '#48137b', '#6b2fa4', '#7b46ae', '#3f116c']));\n/**\n * Host owns metadata (e.g. `id`, `container`) that its Particle is not allowed to access.\n * Host knows how to talk, asynchronously, to its Particle (potentially using a bus).\n**/\n/* TODO(sjmiles):\nUpdate Cycle Documented Briefly\n1. when a Store changes it invokes it's listeners\n2. when an Arc hears a Store change, it updates Hosts bound to the Store\n3. Arc updates Host by creating an `inputs` object from Stores and metadata\n - ignores fact inputs are accumulated\n - ignores information about which Store has updated\n4. `inputs` object is assigned to `hosts.inputs` \uD83D\uDE43\n5. Host does an expensive `deepEqual` equality check. Turning on `host` logging should reveal `this.log('inputs are not interesting, skipping update');` if data is caught in this trap\n - we can use reference testing here if we are more careful\n about using immutable data\n6. the particle.inputs are assigned (but is really a *merge*)\n*/\nexport class Host extends EventEmitter {\n arc;\n id;\n lastOutput;\n lastPacket;\n lastRenderModel;\n log;\n meta;\n particle;\n constructor(id) {\n super();\n this.log = customLogFactory(id);\n this.id = id;\n }\n onevent(eventlet) {\n this.arc?.onevent(eventlet);\n }\n // Particle and ParticleMeta are separate, host specifically integrates these on behalf of Particle\n installParticle(particle, meta) {\n if (this.particle) {\n this.detachParticle();\n }\n if (particle) {\n this.particle = particle;\n this.meta = meta || this.meta;\n }\n }\n get container() {\n return this.meta?.container || 'root';\n }\n detach() {\n this.detachParticle();\n this.arc = null;\n }\n detachParticle() {\n if (this.particle) {\n this.render({ $clear: true });\n this.particle = null;\n this.meta = null;\n }\n }\n async service(request) {\n if (request?.decorate) {\n return Decorator.maybeDecorateModel(request.model, this.particle);\n }\n return this.arc?.service(this, request);\n }\n output(outputModel, renderModel) {\n if (outputModel) {\n Decorator.processOutputModel(outputModel);\n this.lastOutput = outputModel;\n this.arc?.assignOutputs(this, outputModel);\n }\n if (this.template) {\n Decorator.maybeDecorateModel(renderModel, this.particle);\n this.log(renderModel);\n this.lastRenderModel = renderModel;\n this.render(renderModel);\n }\n }\n rerender() {\n if (this.lastRenderModel) {\n this.render(this.lastRenderModel);\n }\n // if (this.lastPacket) {\n // this.arc?.render(this.lastPacket);\n // }\n }\n render(model) {\n const { id, container, template } = this;\n const content = { model, template };\n const packet = { id, container, content };\n this.arc?.render(packet);\n this.lastPacket = packet;\n }\n set inputs(inputs) {\n if (this.particle && inputs) {\n const lastInputs = this.particle.internal.inputs;\n if (this.dirtyCheck(inputs, lastInputs, this.lastOutput)) {\n this.particle.inputs = { ...this.meta?.staticInputs, ...inputs };\n this.fire('inputs-changed');\n }\n else {\n this.log('inputs are uninteresting, skipping update');\n }\n }\n }\n dirtyCheck(inputs, lastInputs, lastOutput) {\n const dirtyBits = ([n, v]) => (lastOutput?.[n] && !deepEqual(lastOutput[n], v))\n || !deepEqual(lastInputs?.[n], v);\n return !lastInputs\n || entries(inputs).length !== this.lastInputsLength(lastInputs)\n || entries(inputs).some(dirtyBits);\n }\n lastInputsLength(lastInputs) {\n return keys(lastInputs).filter(key => !this.meta?.staticInputs?.[key] && key !== 'eventlet').length;\n }\n get config() {\n return this.particle?.config;\n }\n get template() {\n return this.config?.template;\n }\n invalidate() {\n this.particle?.invalidate();\n }\n handleEvent(eventlet) {\n return this.particle?.handleEvent(eventlet);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { EventEmitter } from './EventEmitter.js';\nconst { create, keys } = Object;\nconst { stringify, parse } = JSON;\nexport class DataStore extends EventEmitter {\n privateData;\n constructor() {\n super();\n }\n setPrivateData(data) {\n this.privateData = data;\n }\n set data(data) {\n this.setPrivateData(data);\n }\n get data() {\n return this.privateData;\n }\n toString() {\n return this.pretty;\n }\n get isObject() {\n return this.data && typeof this.data === 'object';\n }\n get pojo() {\n return this.data;\n }\n get json() {\n return stringify(this.data);\n }\n set json(json) {\n let value = null;\n try {\n value = parse(json);\n }\n catch (x) {\n //\n }\n this.data = value;\n }\n get pretty() {\n const sorted = {};\n const pojo = this.pojo;\n keys(pojo).sort().forEach(key => sorted[key] = pojo[key]);\n return stringify(sorted, null, ' ');\n }\n}\nclass ObservableStore extends DataStore {\n change(mutator) {\n mutator(this);\n this.doChange();\n }\n doChange() {\n this.fire('change', this);\n this.onChange(this);\n }\n onChange(store) {\n // override\n }\n set data(data) {\n this.change(self => self.setPrivateData(data));\n }\n // TODO(sjmiles): one of the compile/build/bundle tools\n // evacipates the inherited getter, so we clone it\n get data() {\n return this['privateData'];\n }\n set(key, value) {\n if (!this.data) {\n this.setPrivateData(create(null));\n }\n if (value !== undefined) {\n this.change(self => self.data[key] = value);\n }\n else {\n this.delete(key);\n }\n }\n delete(key) {\n this.change(doc => delete doc.data[key]);\n }\n}\nclass PersistableStore extends ObservableStore {\n meta;\n constructor(meta) {\n super();\n this.meta = { ...meta };\n }\n toString() {\n return `${JSON.stringify(this.meta, null, ' ')}, ${this.pretty}`;\n }\n get tags() {\n return this.meta.tags ?? (this.meta.tags = []);\n }\n is(...tags) {\n // true if every member of `tags` is also in `this.tags`\n return tags.every(tag => this.tags.includes(tag));\n }\n isCollection() {\n return this.meta.type?.[0] === '[';\n }\n shouldPersist() {\n return this.is('persisted') && !this.is('volatile');\n }\n async doChange() {\n // do not await\n this.persist();\n return super.doChange();\n }\n // TODO(sjmiles): as of now the persist/restore methods\n // are bound in Runtime:addStore\n async persist() {\n }\n async restore( /*value: any*/) {\n }\n // delete() {\n // this.persistor?.remove(this);\n // }\n save() {\n return this.json;\n }\n load(serial, defaultValue) {\n let value = defaultValue;\n try {\n if (serial) {\n value = parse(serial);\n }\n }\n catch (x) {\n //\n }\n if (value !== undefined) {\n this.data = value;\n }\n }\n}\nexport class Store extends PersistableStore {\n}\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { irand } from \"./rand.js\";\nexport const makeId = (pairs, digits, delim) => {\n pairs = pairs || 2;\n digits = digits || 2;\n delim = delim || '-';\n const min = Math.pow(10, digits - 1);\n const range = Math.pow(10, digits) - min;\n const result = [];\n for (let i = 0; i < pairs; i++) {\n result.push(`${irand(range - min) + min}`);\n }\n return result.join(delim);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Arc } from './core/Arc.js';\nimport { Host } from './core/Host.js';\nimport { Store } from './core/Store.js';\nimport { EventEmitter } from './core/EventEmitter.js';\nimport { logFactory } from './utils/log.js';\nimport { makeId } from './utils/id.js';\nconst log = logFactory(logFactory.flags.runtime, 'runtime', '#873600');\nconst particleFactoryCache = {};\nconst storeFactories = {};\nconst { keys } = Object;\nexport class Runtime extends EventEmitter {\n log;\n uid; // user id\n nid; // network id\n arcs;\n stores;\n peers;\n shares;\n endpoint;\n network;\n surfaces;\n persistor;\n prettyUid;\n static securityLockdown;\n static particleIndustry;\n static particleOptions;\n constructor(uid) {\n uid = uid || 'user';\n super();\n this.arcs = {};\n this.surfaces = {};\n this.stores = {};\n this.peers = new Set();\n this.shares = new Set();\n this.setUid(uid);\n this.log = logFactory(logFactory.flags.runtime, `runtime:[${this.prettyUid}]`, '#873600');\n //Runtime.securityLockdown?.(Runtime.particleOptions);\n }\n setUid(uid) {\n this.uid = uid;\n this.nid = `${uid}:${makeId(1, 2)}`;\n this.prettyUid = uid.substring(0, uid.indexOf('@') + 1) || uid;\n }\n async bootstrapArc(name, meta, surface, service) {\n // make an arc on `surface`\n const arc = new Arc(name, meta, surface);\n // install service handler\n arc.hostService = this.serviceFactory(service);\n // add `arc` to runtime\n await this.addArc(arc);\n // fin\n return arc;\n }\n serviceFactory(service) {\n return async (host, request) => service.handle(this, host, request);\n }\n async bootstrapParticle(arc, id, meta) {\n // make a host\n const host = new Host(id);\n // make a particle\n await this.marshalParticle(host, meta);\n // add `host` to `arc`\n const promise = arc.addHost(host);\n // report\n log('bootstrapped particle', id);\n //log(host);\n // we'll call you when it's ready\n return promise;\n }\n // no-op surface mapping\n addSurface(id, surface) {\n this.surfaces[id] = surface;\n }\n getSurface(id) {\n return this.surfaces[id];\n }\n // map arcs by arc.id\n addArc(arc) {\n const { id } = arc;\n if (id && !this.arcs[id]) {\n return this.arcs[id] = arc;\n }\n throw `arc has no id, or id \"${id}\" is already in use`;\n }\n removeArc(arc) {\n const { id } = arc;\n if (!id || !this.arcs[id]) {\n throw !id ? `arc has no id` : `id \"${id}\" is not in use`;\n }\n delete this.arcs[id];\n }\n // create a particle inside of host\n async marshalParticle(host, particleMeta) {\n const particle = await this.createParticle(host, particleMeta.kind);\n host.installParticle(particle, particleMeta);\n }\n // create a host, install a particle, add host to arc\n async installParticle(arc, particleMeta, name) {\n this.log('installParticle', name, particleMeta, arc.id);\n // provide a default name\n name = name || makeId();\n // deduplicate name\n if (arc.hosts[name]) {\n let n = 1;\n for (; (arc.hosts[`${name}-${n}`]); n++)\n ;\n name = `${name}-${n}`;\n }\n // build the structure\n const host = new Host(name);\n await this.marshalParticle(host, particleMeta);\n arc.addHost(host);\n return host;\n }\n // map a store by a Runtime-specific storeId\n // Stores have no intrinsic id\n addStore(storeId, store) {\n // if the store needs to discuss things with Runtime\n // TODO(sjmiles): this is likely unsafe for re-entry\n if (store.marshal) {\n store.marshal(this);\n }\n // bind to persist/restore functions\n store.persist = async () => this.persistStore(storeId, store);\n store.restore = async () => this.restoreStore(storeId, store);\n // override the Store's own persistor to use the runtime persistor\n // TODO(sjmiles): why?\n // if (store.persistor) {\n // store.persistor.persist = store => this.persistor?.persist(storeId, store);\n // }\n // bind this.storeChanged to store.change (and name the binding)\n const name = `${this.nid}:${storeId}-changed`;\n const onChange = this.storeChanged.bind(this, storeId);\n store.listen('change', onChange, name);\n // map the store\n this.stores[storeId] = store;\n // evaluate for sharing\n this.maybeShareStore(storeId);\n // notify listeners that a thing happened\n // TODO(sjmiles): makes no sense without id\n //this.fire('store-added', store);\n }\n async persistStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`persistStore \"${storeId}\"`);\n return this.persistor.persist?.(storeId, store);\n }\n }\n async restoreStore(storeId, store) {\n if (store.shouldPersist()) {\n this.log(`restoreStore \"${storeId}\"`);\n return this.persistor.restore?.(storeId);\n }\n }\n storeChanged(storeId, store) {\n this.log('storeChanged', storeId);\n this.network?.invalidatePeers(storeId);\n this.onStoreChange(storeId, store);\n this.fire('store-changed', { storeId, store });\n }\n // TODO(sjmiles): evacipate this method\n onStoreChange(storeId, store) {\n // override for bespoke response\n }\n do(storeId, task) {\n task(this.stores[storeId]);\n }\n removeStore(storeId) {\n this.do(storeId, store => {\n store?.unlisten('change', `${this.nid}:${storeId}-changed`);\n });\n delete this.stores[storeId];\n }\n maybeShareStore(storeId) {\n this.do(storeId, store => {\n if (store?.is('shared')) {\n this.shareStore(storeId);\n }\n });\n }\n addPeer(peerId) {\n this.peers.add(peerId);\n [...this.shares].forEach(storeId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n shareStore(storeId) {\n this.shares.add(storeId);\n [...this.peers].forEach(peerId => this.maybeShareStoreWithPeer(storeId, peerId));\n }\n maybeShareStoreWithPeer(storeId, peerId) {\n this.do(storeId, store => {\n const nid = this.uid.replace(/\\./g, '_');\n if (!store.is('private') || (peerId.startsWith(nid))) {\n this.shareStoreWithPeer(storeId, peerId);\n }\n });\n }\n shareStoreWithPeer(storeId, peerId) {\n this.network?.shareStore(storeId, peerId);\n }\n async createParticle(host, kind) {\n try {\n const factory = await this.marshalParticleFactory(kind);\n return factory(host);\n }\n catch (x) {\n log.error(`createParticle(${kind}):`, x);\n }\n }\n async marshalParticleFactory(kind) {\n return particleFactoryCache[kind] ?? this.lateBindParticle(kind);\n }\n lateBindParticle(kind) {\n return Runtime.registerParticleFactory(kind, Runtime?.particleIndustry(kind, Runtime.particleOptions));\n }\n static registerParticleFactory(kind, factoryPromise) {\n return particleFactoryCache[kind] = factoryPromise;\n }\n requireStore(meta) {\n let store = this.stores[meta.name];\n if (!store) {\n store = this.createStore(meta);\n this.addStore(meta.name, store);\n }\n return store;\n }\n createStore(meta) {\n const key = keys(storeFactories).find(tag => meta.tags?.includes?.(tag));\n const storeClass = storeFactories[String(key)] || Store;\n return new storeClass(meta);\n }\n static registerStoreClass(tag, storeClass) {\n storeFactories[tag] = storeClass;\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'flan', 'violet');\nconst { entries, create } = Object;\nexport class Parser {\n stores;\n particles;\n slots;\n meta;\n constructor(recipe) {\n this.stores = [];\n this.particles = [];\n this.slots = [];\n this.meta = create(null);\n if (recipe) {\n this.parse(recipe);\n }\n }\n parse(recipe) {\n // `normalize` converts shorthand to longhand before parsing\n const normalized = this.normalize(recipe);\n this.parseSlotSpec(normalized, 'root', '');\n return this;\n }\n normalize(recipe) {\n if (typeof recipe !== 'object') {\n throw Error('recipe must be an Object');\n }\n // TODO(sjmiles): would be great if `normalize` normalized all the things\n return recipe;\n }\n parseSlotSpec(spec, slotName, parentName) {\n // process entries\n for (const key in spec) {\n switch (key) {\n case '$meta':\n // value is a dictionary\n this.meta = { ...this.meta, ...spec.$meta };\n break;\n case '$stores':\n // value is a StoreSpec\n this.parseStoresNode(spec.$stores);\n break;\n default: {\n // value is a ParticleSpec\n const container = parentName ? `${parentName}#${slotName}` : slotName;\n this.parseParticleSpec(container, key, spec[key]);\n break;\n }\n }\n }\n }\n parseStoresNode(stores) {\n for (const key in stores) {\n this.parseStoreSpec(key, stores[key]);\n }\n }\n parseStoreSpec(name, spec) {\n if (this.stores.find(s => s.name === name)) {\n log('duplicate store name');\n return;\n }\n const meta = {\n name,\n type: spec.$type,\n tags: spec.$tags,\n value: spec.$value\n };\n this.stores.push(meta);\n }\n parseParticleSpec(container, id, spec) {\n if (!spec.$kind) {\n log.warn(`parseParticleSpec: malformed spec has no \"kind\":`, spec);\n throw Error();\n }\n if (this.particles.find(s => s.id === id)) {\n log('duplicate particle name');\n return;\n }\n this.particles.push({ id, container, spec });\n if (spec.$slots) {\n this.parseSlotsNode(spec.$slots, id);\n }\n }\n parseSlotsNode(slots, parent) {\n entries(slots).forEach(([key, spec]) => this.parseSlotSpec(spec, key, parent));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport function matches(candidateMeta, targetMeta) {\n for (const property in targetMeta) {\n if (candidateMeta[property] !== targetMeta[property]) {\n return false;\n }\n }\n return true;\n}\n;\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { matches } from '../utils/matching.js';\nconst log = logFactory(logFactory.flags.recipe, 'StoreCook', '#99bb15');\nconst { values } = Object;\nconst findStores = (runtime, criteria) => {\n return values(runtime.stores).filter(store => matches(store?.meta, criteria));\n};\nconst mapStore = (runtime, { name, type }) => {\n // TODO(b/244191110): Type matching API to be wired here.\n return findStores(runtime, { name, type })?.[0];\n};\nexport class StoreCook {\n static async execute(runtime, arc, stores) {\n return this.forEachStore(this.realizeStore, runtime, arc, stores);\n }\n static async evacipate(runtime, arc, stores) {\n return this.forEachStore(this.derealizeStore, runtime, arc, stores);\n }\n static async forEachStore(task, runtime, arc, stores) {\n return Promise.all(stores.map(store => task.call(this, runtime, arc, store)));\n }\n static async realizeStore(runtime, arc, rawMeta) {\n const meta = this.constructMeta(runtime, arc, rawMeta);\n let value = meta?.value;\n let store = mapStore(runtime, meta);\n if (store) {\n log(`realizeStore: mapped \"${rawMeta.name}\" to \"${store.meta.name}\"`);\n }\n else {\n store = runtime.createStore(meta);\n log(`realizeStore: created \"${meta.name}\"`);\n // TODO(sjmiles): Stores no longer know their own id, so there is a wrinkle here as we\n // re-route persistence through runtime (so we can bind in the id)\n // Also: the 'id' is known as 'meta.name' here, this is also a problem\n // store && (store.persistor = {\n // restore: store => runtime.persistor?.restore(meta.name, store),\n // persist: () => {}\n // });\n // runtime.addStore(meta.name, store);\n //await store?.restore(meta?.value)\n runtime.addStore(meta.name, store);\n if (store.shouldPersist()) {\n const cached = await store.restore();\n value = cached === undefined ? value : cached;\n }\n }\n if (value !== undefined) {\n log(`setting data to:`, value);\n store.data = value;\n }\n arc.addStore(meta.name, store);\n }\n static async derealizeStore(runtime, arc, spec) {\n runtime.removeStore(spec.$name);\n arc.removeStore(spec.$name);\n }\n static constructMeta(runtime, arc, rawMeta) {\n const meta = {\n ...rawMeta,\n arcid: arc.id,\n uid: runtime.uid,\n };\n return {\n ...meta,\n owner: meta.uid,\n shareid: `${meta.name}:${meta.arcid}:${meta.uid}`\n };\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.recipe, 'ParticleCook', '#5fa530');\nexport class ParticleCook {\n static async execute(runtime, arc, particles) {\n // serial\n for (const particle of particles) {\n await this.realizeParticle(runtime, arc, particle);\n }\n // parallel\n //return Promise.all(particles.map(particle => this.realizeParticle(runtime, arc, particle)));\n }\n static async realizeParticle(runtime, arc, node) {\n log('realizedParticle:', node.id);\n // convert spec to metadata\n const meta = this.specToMeta(node.spec);\n meta.container ||= node.container;\n // make a (hosted) particle\n return runtime.bootstrapParticle(arc, node.id, meta);\n }\n static specToMeta(spec) {\n if (spec.$bindings) {\n console.warn(`Particle '${spec.$kind}' spec contains deprecated $bindings property (${JSON.stringify(spec.$bindings)})`);\n }\n // TODO(sjmiles): impedance mismatch here is likely to cause problems\n const { $kind: kind, $container: container, $staticInputs: staticInputs } = spec;\n const inputs = this.formatBindings(spec.$inputs);\n const outputs = this.formatBindings(spec.$outputs);\n return { kind, staticInputs, inputs, outputs, container };\n }\n static formatBindings(bindings) {\n return bindings?.map?.(binding => typeof binding === 'string' ? { [binding]: binding } : binding);\n }\n static async evacipate(runtime, arc, particles) {\n return Promise.all(particles.map(particle => this.derealizeParticle(runtime, arc, particle)));\n }\n static async derealizeParticle(runtime, arc, node) {\n arc.removeHost(node.id);\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { logFactory } from '../utils/log.js';\nimport { Parser } from './RecipeParser.js';\nimport { StoreCook } from './StoreCook.js';\nimport { ParticleCook } from './ParticleCook.js';\nconst log = logFactory(logFactory.flags.recipe, 'Chef', '#087f23');\nexport class Chef {\n static async execute(recipe, runtime, arc) {\n if (arc instanceof Promise) {\n log.error('`arc` must be an Arc, not a Promise. Make sure `boostrapArc` is awaited.');\n return;\n }\n //log.groupCollapsed('executing recipe...', recipe.$meta);\n log('|-->...| executing recipe: ', recipe.$meta ?? '');\n const plan = new Parser(recipe);\n // `store` preparation\n await StoreCook.execute(runtime, arc, plan.stores);\n // `particle` preparation\n await ParticleCook.execute(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): what do we use this for?\n arc.meta = { ...arc.meta, ...plan.meta };\n log('|...-->| recipe complete: ', recipe.$meta ?? '');\n //log.groupEnd();\n }\n static async evacipate(recipe, runtime, arc) {\n //log.groupCollapsed('evacipating recipe...', recipe.$meta);\n log('|-->...| evacipating recipe: ', recipe.$meta);\n // TODO(sjmiles): this is work we already did\n const plan = new Parser(recipe);\n // `store` work\n // TODO(sjmiles): not sure what stores are unique to this plan\n //await StoreCook.evacipate(runtime, arc, plan);\n // `particle` work\n await ParticleCook.evacipate(runtime, arc, plan.particles);\n // seasoning\n // TODO(sjmiles): doh\n //arc.meta = {...arc.meta, ...plan.meta};\n log('|...-->| recipe evacipated: ', recipe.$meta);\n //log.groupEnd();\n }\n static async executeAll(recipes, runtime, arc) {\n for (const recipe of recipes) {\n await this.execute(recipe, runtime, arc);\n }\n //return Promise.all(recipes?.map(recipe => this.execute(recipe, runtime, arc)));\n }\n static async evacipateAll(recipes, runtime, arc) {\n return Promise.all(recipes?.map(recipe => this.evacipate(recipe, runtime, arc)));\n }\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const PathMapper = class {\n map;\n constructor(root) {\n this.map = {};\n this.setRoot(root);\n }\n add(mappings) {\n Object.assign(this.map, mappings || {});\n }\n resolve(path) {\n const bits = path.split('/');\n const top = bits.shift();\n const prefix = this.map[top] || top;\n return [prefix, ...bits].join('/');\n }\n setRoot(root) {\n if (root.length && root[root.length - 1] === '/') {\n root = root.slice(0, -1);\n }\n this.add({\n '$root': root,\n '$arcs': root\n });\n }\n getAbsoluteHereUrl(meta, depth) {\n // you are here\n const localRelative = meta.url.split('/').slice(0, -(depth ?? 1)).join('/');\n if (!globalThis?.document) {\n return localRelative;\n }\n else {\n // document root is here\n let base = document.URL;\n // if document URL has a filename, remove it\n if (base[base.length - 1] !== '/') {\n base = `${base.split('/').slice(0, -1).join('/')}/`;\n }\n // create absoute path to here (aka 'local')\n let localAbsolute = new URL(localRelative, base).href;\n // no trailing slash!\n if (localAbsolute[localAbsolute.length - 1] === '/') {\n localAbsolute = localAbsolute.slice(0, -1);\n }\n return localAbsolute;\n }\n }\n};\nconst root = import.meta.url.split('/').slice(0, -3).join('/');\nexport const Paths = globalThis['Paths'] = new PathMapper(root);\nPaths.add(globalThis.config?.paths);\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { logFactory } from '../utils/log.js';\nconst log = logFactory(logFactory.flags.code, 'code', 'gold');\nconst defaultParticleBasePath = '$arcs/js/core/Particle.js';\nexport const requireParticleBaseCode = async (sourcePath) => {\n if (!requireParticleBaseCode.source) {\n const path = Paths.resolve(sourcePath || defaultParticleBasePath);\n log('particle base code path: ', path);\n const response = await fetch(path);\n const moduleText = await response.text() + \"\\n//# sourceURL=\" + path + \"\\n\";\n requireParticleBaseCode.source = moduleText.replace(/export /g, '');\n }\n return requireParticleBaseCode.source;\n};\nrequireParticleBaseCode.source = null;\nexport const requireParticleImplCode = async (kind, options) => {\n const code = options?.code || await fetchParticleCode(kind);\n // TODO(sjmiles): brittle content processing, needs to be documented\n return code.slice(code.indexOf('({'));\n};\nexport const fetchParticleCode = async (kind) => {\n if (kind) {\n return await maybeFetchParticleCode(kind);\n }\n log.error(`fetchParticleCode: empty 'kind'`);\n};\nexport const maybeFetchParticleCode = async (kind) => {\n const path = pathForKind(kind);\n try {\n const response = await fetch(path);\n //if (response.ok) {\n return await response.text();\n //}\n }\n catch (x) {\n log.error(`could not locate implementation for particle \"${kind}\" [${path}]`);\n }\n};\nexport const pathForKind = (kind) => {\n if (kind) {\n if (!'$./'.includes(kind[0]) && !kind.includes('://')) {\n kind = `$library/${kind}`;\n }\n if (!kind?.split('/').pop().includes('.')) {\n kind = `${kind}.js`;\n }\n return Paths.resolve(kind);\n }\n return '404';\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nimport { Paths } from '../utils/paths.js';\nimport { Runtime } from '../Runtime.js';\nimport { logFactory } from '../utils/log.js';\nimport { deepEqual } from '../utils/object.js';\nimport { requireParticleImplCode, pathForKind } from './code.js';\nconst log = logFactory(logFactory.flags.isolation, 'vanilla', 'goldenrod');\nconst harden = object => object;\nglobalThis.harden = harden;\nglobalThis.scope = {\n harden\n};\nconst makeKey = () => `i${Math.floor((1 + Math.random() * 9) * 1e14)}`;\nconst timeout = async (func, delayMs) => new Promise(resolve => setTimeout(() => resolve(func()), delayMs));\nexport const initVanilla = (options) => {\n // requiredLog.groupCollapsed('LOCKDOWN');\n try {\n log(deepEqual);\n const utils = { log, resolve, html, makeKey, deepEqual, timeout };\n const scope = {\n // default injections\n ...utils,\n // app injections\n ...options?.injections,\n };\n Object.assign(globalThis.scope, scope);\n Object.assign(globalThis, scope);\n }\n finally {\n /**/\n }\n};\nconst resolve = Paths.resolve.bind(Paths);\nconst html = (strings, ...values) => `${strings[0]}${values.map((v, i) => `${v}${strings[i + 1]}`).join('')}`.trim();\nconst createParticleFactory = async (kind, options) => {\n // ensure our canonical Particle class exists in the isolation chamber\n const { Particle } = await import('../core/Particle.js');\n //const Particle = await requireParticle();\n // // evaluate custom code in isolation chamber\n const implFactory = await requireImplFactory(kind, options);\n // injections\n const log = createLogger(kind);\n const injections = { log, resolve, html, ...options?.injections };\n // construct 3P prototype\n const proto = implFactory(injections);\n // // construct particleFactory\n const particleFactory = (host) => {\n const pipe = {\n log,\n output: host.output.bind(host),\n service: host.service.bind(host)\n };\n return new Particle(proto, pipe, true);\n };\n return particleFactory;\n};\nconst requireImplFactory = async (kind, options) => {\n // snatch up the custom particle code\n const implCode = await requireParticleImplCode(kind, options);\n let factory = (0, eval)(implCode);\n // if it's an object\n if (typeof factory === 'object') {\n // repackage the code to eliminate closures\n factory = repackageImplFactory(factory, kind);\n log('repackaged factory:\\n', factory);\n }\n return globalThis.harden(factory);\n};\nconst repackageImplFactory = (factory, kind) => {\n const { constNames, rewriteConsts, funcNames, rewriteFuncs } = collectDecls(factory);\n const proto = `{${[...constNames, ...funcNames]}}`;\n const moduleRewrite = `\n({log, ...utils}) => {\n// protect utils\nglobalThis.harden(utils);\n// these are just handy\nconst {assign, keys, entries, values, create} = Object;\n// declarations\n${[...rewriteConsts, ...rewriteFuncs].join('\\n\\n')}\n// hardened Object (map) of declarations,\n// suitable to be a prototype\nreturn globalThis.harden(${proto});\n// name the file for debuggers\n//# sourceURL=sandbox/${pathForKind(kind).split('/').pop()}\n};\n `;\n log('rewritten:\\n\\n', moduleRewrite);\n return (0, eval)(moduleRewrite);\n};\nconst collectDecls = factory => {\n // dictionary to 2-tuples\n const props = Object.entries(factory);\n // filter by typeof\n const isFunc = ([n, p]) => typeof p === 'function';\n // filter out forbidden names\n const isForbidden = ([n, p]) => n == 'harden' || n == 'globalThis';\n // get props that are functions\n const funcs = props.filter(item => isFunc(item) && !isForbidden(item));\n // rewrite object declarations as module declarations\n const rewriteFuncs = funcs.map(([n, f]) => {\n const code = f?.toString?.() ?? '';\n const async = code.includes('async');\n const body = code.replace('async ', '').replace('function ', '');\n return `${async ? 'async' : ''} function ${body};`;\n });\n // array up the function names\n const funcNames = funcs.map(([n]) => n);\n // if it's not a Function, it's a const\n const consts = props.filter(item => !isFunc(item) && !isForbidden(item));\n // build const decls\n const rewriteConsts = consts.map(([n, p]) => {\n return `const ${n} = \\`${p}\\`;`;\n });\n // array up the const names\n const constNames = consts.map(([n]) => n);\n return {\n constNames,\n rewriteConsts,\n funcNames,\n rewriteFuncs\n };\n};\nconst createLogger = kind => {\n const _log = logFactory(logFactory.flags.particles, kind, '#002266');\n return (msg, ...args) => {\n const stack = msg?.stack?.split('\\n')?.slice(1, 2) || (new Error()).stack?.split('\\n').slice(2, 3);\n const where = stack\n .map(entry => entry\n .replace(/\\([^()]*?\\)/, '')\n .replace(/ \\([^()]*?\\)/, '')\n .replace('
, ', '')\n .replace('Object.', '')\n .replace('eval at :', '')\n .replace(/\\(|\\)/g, '')\n .replace(/\\[[^\\]]*?\\] /, '')\n .replace(/at (.*) (\\d)/, 'at \"$1\" $2'))\n .reverse()\n .join('\\n')\n .trim();\n if (msg?.message) {\n _log.error(msg.message, ...args, `(${where})`);\n }\n else {\n _log(msg, ...args, `(${where})`);\n }\n };\n};\n// give the runtime a safe way to instantiate Particles\nRuntime.particleIndustry = createParticleFactory;\nRuntime.securityLockdown = initVanilla;\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport * from './date.js';\nexport * from './id.js';\nexport * from './log.js';\nexport * from './matching.js';\nexport * from './object.js';\nexport * from './paths.js';\nexport * from './rand.js';\nexport * from './task.js';\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\nexport const computeAgeString = (date, now) => {\n let deltaTime = Math.round((now - date) / 1000);\n if (isNaN(deltaTime)) {\n return `\u2022`;\n }\n let plural = '';\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} second${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 60) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} minute${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 60);\n if (deltaTime < 24) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} hour${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 24);\n if (deltaTime < 30) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} day${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 30);\n if (deltaTime < 12) {\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} month${plural} ago`;\n }\n deltaTime = Math.round(deltaTime / 12);\n if (deltaTime > 1)\n plural = 's';\n return `${deltaTime} year${plural} ago`;\n};\n", "/**\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n/**\n * Perform `action` if `delay` ms have elapsed since last debounce call for `key`.\n *\n * ```\n * // invoke 'task' one second after last time this line executed\n * this.debounceTask = debounce(this.debounceTask, task, 1000);\n * ```\n */\nexport const debounce = (key, action, delay) => {\n if (key) {\n clearTimeout(key);\n }\n if (action && delay) {\n return setTimeout(action, delay);\n }\n};\nexport const async = task => {\n return async (...args) => {\n await Promise.resolve();\n task(...args);\n };\n};\nexport const asyncTask = (task, delayMs) => {\n setTimeout(task, delayMs ?? 0);\n};\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Use of this source code is governed by a BSD-style\n * license that can be found in the LICENSE file or at\n * https://developers.google.com/open-source/licenses/bsd\n */\n\nexport * from '../js/Runtime.js';\nexport * from '../js/core/EventEmitter.js';\nexport * from '../js/core/Store.js';\nexport * from '../js/core/Arc.js';\nexport * from '../js/core/Host.js';\nexport * from '../js/core/Decorator.js';\nexport * from '../js/recipe/Chef.js';\nexport * from '../js/recipe/ParticleCook.js';\nexport * from '../js/recipe/StoreCook.js';\nexport * from '../js/recipe/RecipeParser.js';\nexport * from '../js/isolation/code.js';\nexport * from '../js/isolation/vanilla.js';\n\nimport * as utils from '../js/utils/utils.js';\nconst {logFactory, Paths} = utils;\nexport {logFactory, Paths, utils};\n\nconst root = import.meta.url.split('/').slice(0, -1).join('/');\nPaths.setRoot(root);\n"],
+ "mappings": "gRAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,cAAAE,EAAA,gBAAAC,IAAA,IAYQC,GAAQC,GAAQC,GAAMC,GAAQC,EAASC,GAAgBC,GACzDC,EACEC,EAAKC,GACPC,EAEAC,GAiFOZ,EA6GPa,GAIOd,EAnNbe,GAAAC,GAAA,MAYM,CAAE,OAAAd,GAAQ,OAAAC,GAAQ,KAAAC,GAAM,OAAAC,GAAQ,QAAAC,EAAS,eAAAC,GAAgB,eAAAC,IAAmB,QAC5EC,EAAQ,WAAW,OAAY,CAAC,EAChC,CAAE,IAAAC,EAAK,QAAAC,IAAYF,EACnBG,EAAM,IAAMV,GAAO,IAAI,EAEvBW,GAAiB,IAAI,KAAM,CAC7B,IAAI,OAAQ,CACR,OAAO,KAAK,SAAW,CAC3B,CACA,IAAI,MAAO,CACP,OAAO,IACX,CACA,IAAI,MAAO,CACP,OAAO,KAAK,IAChB,CACA,IAAI,MAAO,CACP,OAAO,KAAK,UAAU,KAAK,IAAI,CACnC,CACA,IAAI,QAAS,CACT,OAAO,KAAK,UAAU,KAAK,KAAM,KAAM,IAAI,CAC/C,CACA,IAAI,MAAO,CACP,OAAOT,GAAK,KAAK,IAAI,CACzB,CACA,IAAI,QAAS,CACT,OAAOA,GAAK,KAAK,IAAI,EAAE,MAC3B,CACA,IAAI,QAAS,CACT,OAAOC,GAAO,KAAK,IAAI,CAC3B,CACA,IAAI,SAAU,CACV,OAAOC,EAAQ,KAAK,IAAI,CAC5B,CACA,IAAIW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,IAAMC,GAAmB,CAACC,EAAMC,IAAQ,CAC3C,IAAIC,EAAY,KAAK,OAAOD,EAAMD,GAAQ,GAAI,EAC9C,GAAI,MAAME,CAAS,EACf,MAAO,SAEX,IAAIC,EAAS,GACb,OAAID,EAAY,IACRA,EAAY,IACZC,EAAS,KACN,GAAGD,WAAmBC,UAEjCD,EAAY,KAAK,MAAMA,EAAY,EAAE,EACjCA,EAAY,IACRA,EAAY,IACZC,EAAS,KACN,GAAGD,WAAmBC,UAEjCD,EAAY,KAAK,MAAMA,EAAY,EAAE,EACjCA,EAAY,IACRA,EAAY,IACZC,EAAS,KACN,GAAGD,SAAiBC,UAE/BD,EAAY,KAAK,MAAMA,EAAY,EAAE,EACjCA,EAAY,IACRA,EAAY,IACZC,EAAS,KACN,GAAGD,QAAgBC,UAE9BD,EAAY,KAAK,MAAMA,EAAY,EAAE,EACjCA,EAAY,IACRA,EAAY,IACZC,EAAS,KACN,GAAGD,UAAkBC,UAEhCD,EAAY,KAAK,MAAMA,EAAY,EAAE,EACjCA,EAAY,IACZC,EAAS,KACN,GAAGD,SAAiBC,YAC/B,EC/BO,IAAMC,GAAW,CAACC,EAAKC,EAAQC,IAAU,CAI5C,GAHIF,GACA,aAAaA,CAAG,EAEhBC,GAAUC,EACV,OAAO,WAAWD,EAAQC,CAAK,CAEvC,EACaC,GAAQC,GACV,SAAUC,IAAS,CACtB,MAAM,QAAQ,QAAQ,EACtBD,EAAK,GAAGC,CAAI,CAChB,EAESC,GAAY,CAACF,EAAMG,IAAY,CACxC,WAAWH,EAAMG,GAAW,CAAC,CACjC,ECRA,GAAM,CAAC,WAAAC,GAAY,MAAAC,EAAK,EAAIC,GAG5B,IAAMC,GAAO,YAAY,IAAI,MAAM,GAAG,EAAE,MAAM,EAAG,EAAE,EAAE,KAAK,GAAG,EAC7DC,GAAM,QAAQD,EAAI",
+ "names": ["Particle_exports", "__export", "Particle", "ParticleApi", "create", "assign", "keys", "values", "entries", "defineProperty", "setPrototypeOf", "scope", "log", "timeout", "nob", "storePrototype", "privateProperty", "init_Particle", "__esmMin", "key", "value", "index", "entry", "dictionary", "mapFunc", "inputs", "state", "tools", "initialValue", "v", "proto", "pipe", "beStateful", "request", "fn", "e", "methodName", "data", "handler", "onhandler", "asyncMethod", "injections", "stdlib", "task", "asyncFunc", "EventEmitter", "eventName", "args", "listeners", "listener", "listenerName", "list", "index", "l", "logKinds", "errKinds", "fromEntries", "_logFactory", "enable", "preamble", "bg", "color", "kind", "style", "logFactory", "debugLoggers", "logKinds", "errorLoggers", "errKinds", "loggers", "log", "customLogFactory", "id", "logFactory", "assign", "keys", "entries", "create", "values", "o", "nob", "Arc", "EventEmitter", "meta", "surface", "host", "h", "storeId", "store", "isBound", "inputs", "input", "hostId", "inputBindings", "name", "staticInputs", "binding", "storeName", "outputs", "names", "output", "packet", "pid", "eventlet", "request", "result", "shallowUpdate", "obj", "data", "result", "value", "overage", "seen", "key", "shallowMerge", "deepCopy", "datum", "element", "clone", "deepEqual", "a", "b", "type", "aProps", "bProps", "name", "deepUndefinedToNull", "prop", "floor", "pow", "random", "key", "digits", "irand", "range", "arand", "array", "prob", "probability", "log", "logFactory", "values", "entries", "opaqueData", "Decorator", "name", "data", "privateData", "_privateKey", "privy", "model", "particle", "item", "models", "maybeDecorate", "maybeFilter", "maybeCollateBy", "decorator", "inputs", "state", "immutableInputs", "deepCopy", "immutableState", "i", "immutableModel", "decorated", "sortByLc", "filter", "impl", "collator", "collation", "collate", "collationToRenderModels", "key", "a", "b", "sort", "collateBy", "keyValue", "$template", "entries", "keys", "customLogFactory", "id", "logFactory", "arand", "Host", "EventEmitter", "eventlet", "particle", "meta", "request", "Decorator", "outputModel", "renderModel", "model", "container", "template", "packet", "inputs", "lastInputs", "lastOutput", "dirtyBits", "n", "v", "deepEqual", "key", "create", "keys", "stringify", "parse", "DataStore", "EventEmitter", "data", "json", "value", "sorted", "pojo", "key", "ObservableStore", "mutator", "store", "self", "doc", "PersistableStore", "meta", "tags", "tag", "serial", "defaultValue", "Store", "makeId", "pairs", "digits", "delim", "min", "range", "result", "i", "irand", "log", "logFactory", "particleFactoryCache", "storeFactories", "keys", "_Runtime", "EventEmitter", "uid", "makeId", "name", "meta", "surface", "service", "arc", "Arc", "host", "request", "id", "Host", "promise", "particleMeta", "particle", "n", "storeId", "store", "onChange", "task", "peerId", "nid", "kind", "x", "factoryPromise", "key", "tag", "storeClass", "Store", "Runtime", "__publicField", "log", "logFactory", "entries", "create", "Parser", "recipe", "normalized", "spec", "slotName", "parentName", "key", "container", "stores", "name", "s", "meta", "id", "slots", "parent", "matches", "candidateMeta", "targetMeta", "property", "log", "logFactory", "values", "findStores", "runtime", "criteria", "store", "matches", "mapStore", "name", "type", "StoreCook", "arc", "stores", "task", "rawMeta", "meta", "value", "cached", "spec", "log", "logFactory", "ParticleCook", "runtime", "arc", "particles", "particle", "node", "meta", "spec", "kind", "container", "staticInputs", "inputs", "outputs", "bindings", "binding", "log", "logFactory", "Chef", "recipe", "runtime", "arc", "plan", "Parser", "StoreCook", "ParticleCook", "recipes", "PathMapper", "root", "mappings", "path", "bits", "top", "meta", "depth", "localRelative", "base", "localAbsolute", "Paths", "log", "logFactory", "defaultParticleBasePath", "requireParticleBaseCode", "sourcePath", "path", "Paths", "moduleText", "requireParticleImplCode", "kind", "options", "code", "fetchParticleCode", "maybeFetchParticleCode", "pathForKind", "log", "logFactory", "harden", "object", "makeKey", "timeout", "func", "delayMs", "resolve", "initVanilla", "options", "deepEqual", "scope", "html", "Paths", "strings", "values", "v", "i", "createParticleFactory", "kind", "Particle", "implFactory", "requireImplFactory", "createLogger", "injections", "proto", "host", "pipe", "implCode", "requireParticleImplCode", "factory", "repackageImplFactory", "constNames", "rewriteConsts", "funcNames", "rewriteFuncs", "collectDecls", "moduleRewrite", "pathForKind", "props", "isFunc", "n", "p", "isForbidden", "funcs", "item", "f", "code", "async", "body", "consts", "_log", "msg", "args", "where", "entry", "Runtime", "utils_exports", "__export", "PathMapper", "Paths", "arand", "async", "asyncTask", "computeAgeString", "debounce", "deepCopy", "deepEqual", "deepUndefinedToNull", "irand", "key", "logFactory", "makeId", "matches", "prob", "shallowMerge", "shallowUpdate", "computeAgeString", "date", "now", "deltaTime", "plural", "debounce", "key", "action", "delay", "async", "task", "args", "asyncTask", "delayMs", "logFactory", "Paths", "utils_exports", "root", "Paths"]
}