@pritzlaff/nano-core 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -88,8 +88,88 @@ function fits(source, action) {
88
88
  return false;
89
89
  return source.output.hash === action.input.hash || canonicalSchema(action.input.schema) === "{}";
90
90
  }
91
+ // packages/nano/src/coord.ts
92
+ var NS = /^[a-zA-Z][a-zA-Z0-9-]*([./][a-zA-Z0-9-]+)*$/;
93
+ var NAME = /^[a-zA-Z0-9-]+$/;
94
+ var ID = /^[^/@\s#\x00-\x1f\x7f]{1,64}$/;
95
+ var POD = /^[^/@.\s#\x00-\x1f\x7f]{1,64}$/;
96
+ var check = (ok, what, v) => {
97
+ if (!ok)
98
+ throw new Error(`bad ${what} ${JSON.stringify(v)}`);
99
+ };
100
+ var value = (v, text) => Object.freeze(Object.assign(v, { toString: () => text, toJSON: () => text }));
101
+ function namespace(name) {
102
+ check(NS.test(name), "namespace", name);
103
+ const ns = value({
104
+ kind: "namespace",
105
+ name,
106
+ interfaceId: (n) => {
107
+ check(NAME.test(n), "name", n);
108
+ return value({ kind: "interface", ns, name: n }, `${name}.${n}`);
109
+ },
110
+ implementationId: (n) => {
111
+ check(NAME.test(n), "name", n);
112
+ return value({ kind: "implementation", ns, name: n }, `${name}/${n}`);
113
+ }
114
+ }, name);
115
+ return ns;
116
+ }
117
+ function port(i, op) {
118
+ check(NAME.test(op), "op name", op);
119
+ return value({ kind: "port", interface: i, op }, `${i}/${op}`);
120
+ }
121
+ function runtime(id) {
122
+ check(ID.test(id), "runtime", id);
123
+ return value({ kind: "runtime", id }, id);
124
+ }
125
+ function pod(implementation, runtime2, name) {
126
+ check(POD.test(name), "pod", name);
127
+ return value({ kind: "pod", implementation, runtime: runtime2, pod: name }, `${implementation}@${runtime2}/${name}`);
128
+ }
129
+ var cut = (s, sep) => {
130
+ const at = s.lastIndexOf(sep);
131
+ return at > 0 ? [s.slice(0, at), s.slice(at + 1)] : undefined;
132
+ };
133
+ function read(kind, s) {
134
+ const bad = () => {
135
+ throw new Error(`bad ${kind} coordinate ${JSON.stringify(s)}`);
136
+ };
137
+ const attempt = (f) => {
138
+ try {
139
+ return f();
140
+ } catch {
141
+ return bad();
142
+ }
143
+ };
144
+ switch (kind) {
145
+ case "namespace":
146
+ return attempt(() => namespace(s));
147
+ case "interface": {
148
+ const [ns, n] = cut(s, ".") ?? bad();
149
+ return attempt(() => namespace(ns).interfaceId(n));
150
+ }
151
+ case "implementation": {
152
+ const [ns, n] = cut(s, "/") ?? bad();
153
+ return attempt(() => namespace(ns).implementationId(n));
154
+ }
155
+ case "port": {
156
+ const [i, op] = cut(s, "/") ?? bad();
157
+ return attempt(() => port(read("interface", i), op));
158
+ }
159
+ case "runtime":
160
+ return attempt(() => runtime(s));
161
+ default: {
162
+ const at = s.indexOf("@"), slash = s.indexOf("/", at);
163
+ if (at < 0 || slash < 0)
164
+ bad();
165
+ return attempt(() => pod(read("implementation", s.slice(0, at)), runtime(s.slice(at + 1, slash)), s.slice(slash + 1)));
166
+ }
167
+ }
168
+ }
169
+ var Coord = { namespace, port, runtime, pod, parse: read };
170
+
91
171
  // packages/nano/src/result.ts
92
- var success = (value) => ({ ok: true, value });
172
+ var success = (value2) => ({ ok: true, value: value2 });
93
173
  var failure = (type, reason, coord) => ({
94
174
  ok: false,
95
175
  fail: coord === undefined ? { type, reason } : { type, reason, coord }
@@ -110,9 +190,9 @@ function handlers(i, obj) {
110
190
  for (const o of Object.values(i.ops)) {
111
191
  if (o.kind !== "action" || typeof methods[o.name] !== "function")
112
192
  continue;
113
- out[o.name] = async (input) => {
193
+ out[o.name] = async (input, ctx) => {
114
194
  try {
115
- return success(await methods[o.name].call(obj, input) ?? null);
195
+ return success(await methods[o.name].call(obj, input, ctx) ?? null);
116
196
  } catch (e) {
117
197
  const fail = e?.fail;
118
198
  return fail ? { ok: false, fail } : failure("threw", e instanceof Error ? e.message : String(e));
@@ -156,7 +236,7 @@ function lift(i, obj) {
156
236
  for (const o of Object.values(i.ops)) {
157
237
  const m = methods[o.name];
158
238
  if (o.kind === "event" && typeof m === "function")
159
- sources.set(port(i, o), { op: o, run: () => m.call(obj) });
239
+ sources.set(port2(i, o), { op: o, run: () => m.call(obj) });
160
240
  }
161
241
  return { ...provide(i, handlers(i, obj)), sources };
162
242
  }
@@ -166,17 +246,17 @@ var isInterface = (s) => ("byCoord" in s);
166
246
  function selectorData(s) {
167
247
  if (!isInterface(s))
168
248
  return s;
169
- const { tags, implementation, provider, runtime } = s;
249
+ const { tags, implementation, provider, runtime: runtime2 } = s;
170
250
  return {
171
- implements: s.coord,
251
+ implements: Coord.parse("interface", s.coord),
172
252
  ...tags && { tags },
173
253
  ...implementation !== undefined && { implementation },
174
254
  ...provider !== undefined && { provider },
175
- ...runtime !== undefined && { runtime }
255
+ ...runtime2 !== undefined && { runtime: runtime2 }
176
256
  };
177
257
  }
178
- var of = (i, s = {}) => ({ ...i, ...s, implements: i.coord });
179
- var matches = (s, t) => (s.implements === undefined || t.provides.has(s.implements)) && (s.tags ?? []).every((tag) => t.tags.has(tag)) && (s.implementation === undefined || s.implementation === t.implementation) && (s.provider === undefined || s.provider === t.provider) && (s.runtime === undefined || s.runtime === t.runtime);
258
+ var of = (i, s = {}) => ({ ...i, ...s, implements: Coord.parse("interface", i.coord) });
259
+ var matches = (s, t) => (s.implements === undefined || t.provides.has(String(s.implements))) && (s.tags ?? []).every((tag) => t.tags.has(tag)) && (s.implementation === undefined || String(s.implementation) === t.implementation) && (s.provider === undefined || String(s.provider) === t.provider) && (s.runtime === undefined || String(s.runtime) === t.runtime);
180
260
  var Selector = { of };
181
261
 
182
262
  // packages/nano/src/implementation.ts
@@ -187,7 +267,7 @@ function provide(i, handlers2) {
187
267
  for (const o of Object.values(i.ops)) {
188
268
  const h = o.kind === "event" ? undefined : byName[o.name];
189
269
  if (h)
190
- out.set(port(i, o), h);
270
+ out.set(port2(i, o), h);
191
271
  }
192
272
  return { iface: i, handlers: out };
193
273
  }
@@ -196,16 +276,33 @@ function define2(at, spec) {
196
276
  const slash = coord.lastIndexOf("/");
197
277
  if (!COORD.test(coord) || slash < 0)
198
278
  throw new Error(`bad implementation coordinate ${coord}`);
279
+ const calls = {};
280
+ for (const [op, byRole] of Object.entries(spec.calls ?? {})) {
281
+ if (!spec.provides.some((i) => (op in i.ops)))
282
+ throw new Error(`${coord}: ${op} is not an op this implementation provides`);
283
+ calls[op] = Object.entries(byRole).flatMap(([role, ops]) => {
284
+ const dep = spec.dependencies?.[role];
285
+ if (!dep)
286
+ throw new Error(`${coord}: ${role} is not a dependency`);
287
+ const iface = isInterface2(dep);
288
+ return ops.map((o) => {
289
+ if (iface && !iface.byCoord.has(o.coord))
290
+ throw new Error(`${coord}: ${iface.coord} has no op ${o.name}`);
291
+ return `${role}.${o.name}`;
292
+ });
293
+ });
294
+ }
199
295
  return {
200
296
  coord,
297
+ calls,
201
298
  provider: coord.slice(0, slash),
202
299
  provides: spec.provides,
203
300
  dependencies: Object.fromEntries(Object.entries(spec.dependencies ?? {}).map(([role, s]) => [role, selectorData(s)])),
204
301
  ...spec.config && { config: spec.config },
205
302
  ...spec.description !== undefined && { description: spec.description },
206
303
  async make(base, config) {
207
- const deps = Object.fromEntries(Object.keys(spec.dependencies ?? {}).map((role) => [role, plain(isInterface2(spec.dependencies[role]), () => base.one(selectorData(spec.dependencies[role])))]));
208
- const ctx = Object.assign(Object.create(base), { deps });
304
+ const withDeps = (c) => Object.assign(Object.create(c), { deps: Object.fromEntries(Object.keys(spec.dependencies ?? {}).map((role) => [role, plain(isInterface2(spec.dependencies[role]), () => c.one(selectorData(spec.dependencies[role])))])) });
305
+ const ctx = withDeps(base);
209
306
  const made = await spec.make(ctx, config);
210
307
  if (!Array.isArray(made) && spec.provides.length !== 1)
211
308
  throw new Error(`${coord}: a plain object provides exactly one interface`);
@@ -221,14 +318,14 @@ function define2(at, spec) {
221
318
  throw new Error(`${coord}: ${ic} is provided twice`);
222
319
  given.add(ic);
223
320
  for (const [p, h] of part.handlers)
224
- out.set(p, h);
321
+ out.set(p, (input, inv) => h(input, withDeps(inv)));
225
322
  for (const [p, src] of part.sources ?? [])
226
323
  sources.set(p, src);
227
324
  }
228
325
  for (const i of spec.provides)
229
326
  for (const o of Object.values(i.ops))
230
- if (o.kind !== "event" && !out.has(port(i, o)))
231
- throw new Error(`${coord}: missing ${port(i, o)}`);
327
+ if (o.kind !== "event" && !out.has(port2(i, o)))
328
+ throw new Error(`${coord}: missing ${port2(i, o)}`);
232
329
  return { handlers: out, sources };
233
330
  }
234
331
  };
@@ -266,91 +363,19 @@ function builder(api, at, steps = { deps: {} }) {
266
363
  };
267
364
  }
268
365
  var COORD = /^[a-zA-Z][a-zA-Z0-9-]*([./][a-zA-Z0-9-]+)+$/;
269
- var port = (i, o) => `${i.coord}/${o.name}`;
366
+ var port2 = (i, o) => `${i.coord}/${o.name}`;
270
367
  function define3(at, unnamed) {
271
368
  const coord = String(at);
272
- if (!COORD.test(coord))
369
+ try {
370
+ Coord.parse("interface", coord);
371
+ } catch {
273
372
  throw new Error(`bad interface coordinate ${coord}`);
373
+ }
274
374
  const ops = Object.fromEntries(Object.entries(unnamed).map(([name, o]) => [name, { ...o, name, coord: hashOf(canonical({ name, input: o.input?.hash ?? null, output: o.output.hash })) }]));
275
375
  const api = { coord, ops, byCoord: new Map(Object.values(ops).map((o) => [o.coord, o])), impl: (at2) => builder(api, at2) };
276
376
  return api;
277
377
  }
278
378
  var Interface = { define: define3 };
279
- // packages/nano/src/coord.ts
280
- var NS = /^[a-zA-Z][a-zA-Z0-9-]*([./][a-zA-Z0-9-]+)*$/;
281
- var NAME = /^[a-zA-Z0-9-]+$/;
282
- var ID = /^[^/@\s#\x00-\x1f\x7f]{1,64}$/;
283
- var POD = /^[^/@.\s#\x00-\x1f\x7f]{1,64}$/;
284
- var check = (ok, what, v) => {
285
- if (!ok)
286
- throw new Error(`bad ${what} ${JSON.stringify(v)}`);
287
- };
288
- var value = (v, text) => Object.freeze(Object.assign(v, { toString: () => text }));
289
- function namespace(name) {
290
- check(NS.test(name), "namespace", name);
291
- const ns = value({
292
- kind: "namespace",
293
- name,
294
- interfaceId: (n) => {
295
- check(NAME.test(n), "name", n);
296
- return value({ kind: "interface", ns, name: n }, `${name}.${n}`);
297
- },
298
- implementationId: (n) => {
299
- check(NAME.test(n), "name", n);
300
- return value({ kind: "implementation", ns, name: n }, `${name}/${n}`);
301
- }
302
- }, name);
303
- return ns;
304
- }
305
- function port2(i, op) {
306
- check(NAME.test(op), "op name", op);
307
- return value({ kind: "port", interface: i, op }, `${i}/${op}`);
308
- }
309
- function pod(implementation, runtime, name) {
310
- check(ID.test(runtime), "runtime", runtime);
311
- check(POD.test(name), "pod", name);
312
- return value({ kind: "pod", implementation, runtime, pod: name }, `${implementation}@${runtime}/${name}`);
313
- }
314
- var cut = (s, sep) => {
315
- const at = s.lastIndexOf(sep);
316
- return at > 0 ? [s.slice(0, at), s.slice(at + 1)] : undefined;
317
- };
318
- function read(kind, s) {
319
- const bad = () => {
320
- throw new Error(`bad ${kind} coordinate ${JSON.stringify(s)}`);
321
- };
322
- const attempt = (f) => {
323
- try {
324
- return f();
325
- } catch {
326
- return bad();
327
- }
328
- };
329
- switch (kind) {
330
- case "namespace":
331
- return attempt(() => namespace(s));
332
- case "interface": {
333
- const [ns, n] = cut(s, ".") ?? bad();
334
- return attempt(() => namespace(ns).interfaceId(n));
335
- }
336
- case "implementation": {
337
- const [ns, n] = cut(s, "/") ?? bad();
338
- return attempt(() => namespace(ns).implementationId(n));
339
- }
340
- case "port": {
341
- const [i, op] = cut(s, "/") ?? bad();
342
- return attempt(() => port2(read("interface", i), op));
343
- }
344
- default: {
345
- const at = s.indexOf("@"), slash = s.indexOf("/", at);
346
- if (at < 0 || slash < 0)
347
- bad();
348
- return attempt(() => pod(read("implementation", s.slice(0, at)), s.slice(at + 1, slash), s.slice(slash + 1)));
349
- }
350
- }
351
- }
352
- var Coord = { namespace, port: port2, pod, parse: read };
353
-
354
379
  // packages/nano/src/provider.ts
355
380
  function define4(at, implementations, meta = {}) {
356
381
  const coord = String(at);
@@ -418,7 +443,7 @@ function create() {
418
443
  implementations: [...impls.values()].sort(byCoord).map((i) => ({
419
444
  coord: i.coord,
420
445
  provides: i.provides.map((x) => x.coord).sort(),
421
- dependencies: structuredClone(i.dependencies)
446
+ dependencies: JSON.parse(JSON.stringify(i.dependencies))
422
447
  })),
423
448
  interfaces: [...ifaces.values()].sort(byCoord).map((i) => ({
424
449
  coord: i.coord,
@@ -438,14 +463,33 @@ function create() {
438
463
  op: (c) => ops.get(c)
439
464
  };
440
465
  }
441
- var Registry = { create };
466
+ async function load(modules, base) {
467
+ const registry = create();
468
+ const exports = {};
469
+ for (const [ns, path] of Object.entries(modules)) {
470
+ let mod;
471
+ try {
472
+ mod = await import(new URL(path, base).href);
473
+ } catch (e) {
474
+ return failure("not-found", `${ns} (${path}): ${e instanceof Error ? e.message : String(e)}`);
475
+ }
476
+ const p = mod.default;
477
+ const q = p;
478
+ const added = q && typeof q.coord === "string" && q.implementations instanceof Map ? registry.add(q) : failure("invalid-input", `${path} has no default Provider`);
479
+ if (!added.ok)
480
+ return added;
481
+ exports[ns] = mod;
482
+ }
483
+ return success({ registry, exports });
484
+ }
485
+ var Registry = { create, load };
442
486
  // packages/nano/src/policy.ts
443
487
  import { Type } from "typebox";
444
488
  var ALLOW_ALL = Object.freeze({ isAllowed: () => ({ approved: true }) });
445
489
  var Policies = {
446
490
  allowAll: () => ALLOW_ALL
447
491
  };
448
- var Kind = Type.Union([Type.Literal("call"), Type.Literal("pipe"), Type.Literal("on"), Type.Literal("subscribe"), Type.Literal("unsubscribe"), Type.Literal("lifecycle"), Type.Literal("*")]);
492
+ var Kind = Type.Union([Type.Literal("call"), Type.Literal("pipe"), Type.Literal("on"), Type.Literal("subscribe"), Type.Literal("unsubscribe"), Type.Literal("lifecycle"), Type.Literal("start"), Type.Literal("*")]);
449
493
  var Kinds = Type.Union([Kind, Type.Array(Kind)]);
450
494
  var Match = {
451
495
  from: Type.Optional(Type.String()),
@@ -488,6 +532,11 @@ function PolicyRules(rules) {
488
532
  return hit.allow ? { approved: true } : { approved: false, reason: `rules[${hit.i}]` };
489
533
  } };
490
534
  }
535
+ // packages/nano/src/deployment-policy.ts
536
+ var ALLOW_ALL2 = Object.freeze({ isAllowed: () => ({ approved: true }) });
537
+ var DeploymentPolicies = {
538
+ allowAll: () => ALLOW_ALL2
539
+ };
491
540
  // packages/nano/src/pod.ts
492
541
  var describe = (eager) => (impl, opts = {}) => ({
493
542
  implementation: impl.coord,
@@ -506,7 +555,7 @@ var Shape = Type2.Record(PodName, Type2.Object({
506
555
  implementation: Type2.String(),
507
556
  config: Type2.Optional(Type2.Unknown()),
508
557
  eager: Type2.Boolean(),
509
- isolation: Type2.Optional(Type2.Union([Type2.Literal("host"), Type2.Literal("sandbox"), Type2.Literal("isolated-sandbox")]))
558
+ isolation: Type2.Optional(Type2.Union([Type2.Literal("host"), Type2.Literal("sandbox"), Type2.Literal("isolated-sandbox"), Type2.Literal("home-origin")]))
510
559
  }, strict), { ...strict, maxProperties: 5000 });
511
560
  var Tags = Type2.Record(Id, Type2.Array(Type2.String()), strict);
512
561
  function shapeError(schema, d, what) {
@@ -568,7 +617,12 @@ var strict2 = { additionalProperties: false };
568
617
  var Shape2 = Type3.Object({
569
618
  pods: Type3.Array(Type3.String()),
570
619
  subscriptions: Type3.Array(Type3.Union([
571
- Type3.Object({ kind: Type3.Literal("call"), from: Type3.String(), to: Type3.String() }, strict2),
620
+ Type3.Object({
621
+ kind: Type3.Literal("call"),
622
+ from: Type3.String(),
623
+ to: Type3.String(),
624
+ ops: Type3.Optional(Type3.Array(Type3.Object({ source: Type3.String(), target: Type3.String() }, strict2), { maxItems: 2000 }))
625
+ }, strict2),
572
626
  Type3.Object({ kind: Type3.Literal("pipe"), from: Type3.String(), source: Type3.String(), to: Type3.String(), target: Type3.String() }, strict2)
573
627
  ]), { maxItems: 2000 }),
574
628
  policy: Type3.Optional(Type3.Union([
@@ -584,16 +638,27 @@ var opAt = (impl, p) => {
584
638
  m = new Map;
585
639
  for (const i of impl.provides)
586
640
  for (const o of Object.values(i.ops))
587
- if (!m.has(port(i, o)))
588
- m.set(port(i, o), o);
641
+ if (!m.has(port2(i, o)))
642
+ m.set(port2(i, o), o);
589
643
  ports.set(impl, m);
590
644
  }
591
645
  return m.get(p);
592
646
  };
593
647
  function unfit(s, from, to) {
594
648
  if (s.kind === "call") {
595
- const deps = Object.values(from.dependencies).flatMap((d) => d.implements === undefined ? [] : [d.implements]);
596
- return deps.length && !to.provides.some((i) => deps.includes(i.coord)) ? `${s.to} provides none of ${s.from}'s dependencies` : undefined;
649
+ const deps = Object.values(from.dependencies).flatMap((d) => d.implements === undefined ? [] : [String(d.implements)]);
650
+ if (deps.length && !to.provides.some((i) => deps.includes(i.coord)))
651
+ return `${s.to} provides none of ${s.from}'s dependencies`;
652
+ const pairs = new Set;
653
+ for (const o of s.ops ?? []) {
654
+ if (!opAt(from, o.source))
655
+ return `${o.source} is not an op of ${s.from}`;
656
+ if (opAt(to, o.target)?.kind !== "action")
657
+ return `${o.target} is not an action of ${s.to}`;
658
+ if (pairs.size === pairs.add(JSON.stringify([o.source, o.target])).size)
659
+ return `${o.source} to ${o.target} is there twice`;
660
+ }
661
+ return;
597
662
  }
598
663
  const source = opAt(from, s.source), target = opAt(to, s.target);
599
664
  if (!source)
@@ -637,9 +702,9 @@ function create3(id, d, pods) {
637
702
  const why = shapeError(Shape2, copy, `runtime ${id}`) ?? check2(id, copy, pods);
638
703
  if (why)
639
704
  return failure("invalid-input", why);
640
- const runtime = Object.freeze({ id, pods, deployment: () => structuredClone(copy) });
641
- made.add(runtime);
642
- return success(runtime);
705
+ const runtime2 = Object.freeze({ id, pods, deployment: () => structuredClone(copy) });
706
+ made.add(runtime2);
707
+ return success(runtime2);
643
708
  } catch (e) {
644
709
  return failure("invalid-input", `unreadable runtime ${id}: ${e instanceof Error ? e.message : String(e)}`);
645
710
  }
@@ -651,7 +716,7 @@ import { Type as Type4 } from "typebox";
651
716
  // packages/nano/src/deployment-edit.ts
652
717
  function edit(base, registry) {
653
718
  const d = structuredClone(base);
654
- const runtime = (id) => d.runtimes[id] ??= { pods: [], subscriptions: [] };
719
+ const runtime2 = (id) => d.runtimes[id] ??= { pods: [], subscriptions: [] };
655
720
  const fail = (type, reason) => {
656
721
  throw thrown({ type, reason });
657
722
  };
@@ -659,12 +724,12 @@ function edit(base, registry) {
659
724
  if (Object.hasOwn(d.pods, w.pod))
660
725
  fail("invalid-input", `pod ${w.pod} is already in the deployment`);
661
726
  d.pods[w.pod] = { implementation: impl.coord, eager: w.eager ?? false };
662
- runtime(w.in).pods.push(w.pod);
727
+ runtime2(w.in).pods.push(w.pod);
663
728
  }
664
729
  function handle(at, pod2, api) {
665
730
  return { runtime: at, pod: pod2, implementation: d.pods[pod2].implementation, create(impl, w) {
666
731
  place(impl, w);
667
- const r = runtime(at);
732
+ const r = runtime2(at);
668
733
  r.subscriptions.push({ kind: "call", from: w.pod, to: pod2 });
669
734
  if (r.policy?.kind === "rules")
670
735
  r.policy.rules.unshift({ allow: ["call", "subscribe"], from: w.pod, outside: !r.pods.includes(w.pod), toInterface: api.coord });
@@ -680,7 +745,25 @@ function edit(base, registry) {
680
745
  return fail("not-unique", `${found.length} pods provide ${api.coord} in ${at}`);
681
746
  return handle(at, found[0], api);
682
747
  }
683
- return { place, resolve, deployment: () => structuredClone(d) };
748
+ const same = (a, s) => s.kind === "pipe" && s.from === a.from && s.source === a.source && s.to === a.to && s.target === a.target;
749
+ function pipe(at, p) {
750
+ const r = d.runtimes[at];
751
+ if (!r)
752
+ return fail("not-found", `no runtime ${at}`);
753
+ for (const pod2 of [p.from, p.to])
754
+ if (!r.pods.includes(pod2))
755
+ fail("not-found", `${pod2} is not placed in ${at}`);
756
+ if (r.subscriptions.some((s) => same(p, s)))
757
+ fail("invalid-input", `${p.from} ${p.source} is already piped to ${p.to} ${p.target} in ${at}`);
758
+ r.subscriptions.push({ kind: "pipe", ...p });
759
+ }
760
+ function unpipe(at, p) {
761
+ const r = d.runtimes[at], i = r ? r.subscriptions.findIndex((s) => same(p, s)) : -1;
762
+ if (!r || i < 0)
763
+ return fail("not-found", `no such pipe in ${at}`);
764
+ r.subscriptions.splice(i, 1);
765
+ }
766
+ return { place, resolve, pipe, unpipe, deployment: () => structuredClone(d) };
684
767
  }
685
768
 
686
769
  // packages/nano/src/deployment.ts
@@ -692,6 +775,7 @@ var Shape3 = Type4.Object({
692
775
  tags: Type4.Optional(Type4.Record(Id, Type4.Array(Type4.String()), strict3)),
693
776
  modules: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
694
777
  views: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
778
+ frames: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
695
779
  layout: Type4.Optional(Type4.Record(Type4.String(), Type4.Unknown()))
696
780
  }, strict3);
697
781
  function assemble(d, registry) {
@@ -710,10 +794,10 @@ function assemble(d, registry) {
710
794
  const scope = pods.value.select(Array.isArray(r?.pods) ? [...new Set([...r.pods.filter((n) => typeof n === "string"), ...froms])] : []);
711
795
  if (!scope.ok)
712
796
  return failure("invalid-input", `runtime ${id}: ${scope.fail.reason}`);
713
- const runtime = Runtime.create(id, r, scope.value);
714
- if (!runtime.ok)
715
- return runtime;
716
- out[id] = runtime.value;
797
+ const runtime2 = Runtime.create(id, r, scope.value);
798
+ if (!runtime2.ok)
799
+ return runtime2;
800
+ out[id] = runtime2.value;
717
801
  }
718
802
  return success(out);
719
803
  } catch (e) {
@@ -753,18 +837,10 @@ async function loaded(url) {
753
837
  const top = AppDeployment.assemble({ ...host, pods: {}, runtimes: {} }, Registry.create());
754
838
  if (!top.ok)
755
839
  return failure("invalid-input", `${url}: ${top.fail.reason}`);
756
- const registry = Registry.create();
757
- for (const [ns, path] of Object.entries(deployment?.modules ?? {})) {
758
- let provider;
759
- try {
760
- provider = (await import(new URL(path, url).href)).default;
761
- } catch (e) {
762
- return failure("not-found", `${ns} (${path}): ${why(e)}`);
763
- }
764
- const added = provider && typeof provider === "object" ? registry.add(provider) : failure("invalid-input", `${path} has no default Provider`);
765
- if (!added.ok)
766
- return added;
767
- }
840
+ const loadedModules = await Registry.load(deployment.modules ?? {}, url);
841
+ if (!loadedModules.ok)
842
+ return loadedModules;
843
+ const { registry } = loadedModules.value;
768
844
  return success({ deployment, registry });
769
845
  }
770
846
 
@@ -890,7 +966,7 @@ function refusal(live, ask, d = live.now()) {
890
966
  return `policy threw: ${msg(e)}`;
891
967
  }
892
968
  }
893
- async function deliver(live, to, p, input) {
969
+ async function deliver(live, to, p, input, m) {
894
970
  const asked = action(impl(live, to), p);
895
971
  if (!asked)
896
972
  return failure("unknown-op", `${to} has no action ${p}`);
@@ -904,7 +980,7 @@ async function deliver(live, to, p, input) {
904
980
  return failure("unknown-op", `${to} has no action ${p}`);
905
981
  if (o.input && !o.input.check(input))
906
982
  return failure("invalid-input", `${p}: input does not fit ${o.input.label ?? "its schema"}`);
907
- const ran = await attempt(live, to, `${to} ${p}`, () => h(input));
983
+ const ran = await attempt(live, to, `${to} ${p}`, () => h(input, contextFor(live, to, made2.value.onClose, { ...m, port: p })));
908
984
  if (!ran.ok)
909
985
  return ran;
910
986
  const r = ran.value;
@@ -914,16 +990,16 @@ async function deliver(live, to, p, input) {
914
990
  return failure("invalid-output", `${p}: output does not fit ${o.output.label ?? "its schema"}`);
915
991
  return r;
916
992
  }
917
- async function send(live, runtime, from, to, p, input, how = { kind: "call" }) {
993
+ async function send(live, runtime2, from, to, p, input, how = { kind: "call" }) {
918
994
  const { trace } = live, { kind, id = trace.id(), cause, work } = how, correlation = how.correlation ?? id;
919
- trace.emit({ type: "sent", id, runtime, kind, from, to, port: p, correlation, ...cause !== undefined && { cause } });
920
- const reason = refusal(live, { runtime, kind, from, to, port: p, data: input });
995
+ trace.emit({ type: "sent", id, runtime: runtime2, kind, from, to, port: p, correlation, ...cause !== undefined && { cause }, ...input !== undefined && { input } });
996
+ const reason = refusal(live, { runtime: runtime2, kind, from, to, port: p, data: input });
921
997
  if (reason !== undefined) {
922
998
  trace.emit({ type: "denied", id, reason });
923
999
  return failure("denied", reason);
924
1000
  }
925
1001
  const t0 = performance.now();
926
- const r = await (work ? work() : deliver(live, to, p, input)).catch((e) => failure("invalid-input", `${p}: unreadable input: ${msg(e)}`));
1002
+ const r = await (work ? work() : deliver(live, to, p, input, { id, correlation })).catch((e) => failure("invalid-input", `${p}: unreadable input: ${msg(e)}`));
927
1003
  trace.emit({ type: "delivered", id, result: r, ms: performance.now() - t0 });
928
1004
  return r;
929
1005
  }
@@ -937,11 +1013,11 @@ var fly = (live, p) => {
937
1013
  p.then(done, done);
938
1014
  return p;
939
1015
  };
940
- async function act(live, runtime, from, to, p, input, kind, chain = {}) {
1016
+ async function act(live, runtime2, from, to, p, input, kind, chain = {}) {
941
1017
  const id = chain.id ?? live.trace.id(), correlation = chain.correlation ?? id;
942
- const r = await send(live, runtime, from, to, p, input, { ...chain, kind, id, correlation });
1018
+ const r = await send(live, runtime2, from, to, p, input, { ...chain, kind, id, correlation });
943
1019
  if (r.ok)
944
- emit(live, to, p, { input, output: r.value }, { correlation, cause: id }, runtime);
1020
+ emit(live, to, p, { input, output: r.value }, { correlation, cause: id }, runtime2);
945
1021
  return r;
946
1022
  }
947
1023
  function emit(live, from, port3, e, chain, travelled) {
@@ -961,18 +1037,18 @@ function emit(live, from, port3, e, chain, travelled) {
961
1037
  }
962
1038
  return Promise.all(pipes);
963
1039
  }
964
- function client(live, runtime, from, to, gone) {
1040
+ function client(live, runtime2, from, to, gone, chain) {
965
1041
  const call = async (name, input) => {
966
1042
  const why2 = gone();
967
1043
  if (why2)
968
1044
  return why2;
969
1045
  const provides = (impl(live, to)?.provides ?? []).filter((i) => Object.values(i.ops).some((o) => o.kind === "action" && o.name === name));
970
- const ports2 = provides.map((i) => port(i, i.ops[name]));
1046
+ const ports2 = provides.map((i) => port2(i, i.ops[name]));
971
1047
  if (ports2.length === 0)
972
1048
  return failure("unknown-op", `${to} has no action ${name}`);
973
1049
  if (ports2.length > 1)
974
1050
  return failure("not-unique", `${to}: ${name} is an action of more than one interface`);
975
- return act(live, runtime, from, to, ports2[0], input, "call");
1051
+ return act(live, runtime2, from, to, ports2[0], input, "call", chain);
976
1052
  };
977
1053
  return new Proxy({}, { get: (_, name) => typeof name === "string" && name !== "then" ? (input) => call(name, input) : undefined });
978
1054
  }
@@ -1055,7 +1131,7 @@ function iterate(listen, ended) {
1055
1131
  // packages/nano/src/application/context.ts
1056
1132
  var portOf = (live, pod2, o) => {
1057
1133
  const i = impl(live, pod2)?.provides.find((i2) => i2.byCoord.has(o?.coord));
1058
- return i && port(i, o);
1134
+ return i && port2(i, o);
1059
1135
  };
1060
1136
  var dataOf = (s) => typeof s === "object" && s ? selectorData(s) : undefined;
1061
1137
  var fitsData = (o, data) => {
@@ -1065,34 +1141,42 @@ var fitsData = (o, data) => {
1065
1141
  return false;
1066
1142
  }
1067
1143
  };
1068
- function contextFor(live, name, onClose) {
1069
- let mine = new Set;
1070
- const heard = new Set;
1144
+ var builds = new WeakMap;
1145
+ function buildOf(live, onClose) {
1146
+ const known = builds.get(onClose);
1147
+ if (known)
1148
+ return known;
1149
+ const b = { mine: new Set, heard: new Set };
1150
+ builds.set(onClose, b);
1071
1151
  onClose(() => {
1072
- for (const o of [...mine])
1152
+ for (const o of [...b.mine])
1073
1153
  o.end();
1074
- mine = undefined;
1075
- for (const h of heard)
1154
+ b.mine = undefined;
1155
+ for (const h of b.heard)
1076
1156
  live.listeners.podChanges.delete(h);
1077
1157
  });
1078
- const selection = (runtime, to) => {
1079
- const gone = () => lookup(live.now()).calls.has(`${runtime} ${name} ${to}`) ? undefined : failure("not-found", `${name}->${to} is no longer in ${runtime}`);
1080
- return { pod: to, runtime, call: client(live, runtime, name, to, gone), on(o, fn) {
1158
+ return b;
1159
+ }
1160
+ function contextFor(live, name, onClose, invoked) {
1161
+ const b = buildOf(live, onClose), chain = invoked && { correlation: invoked.correlation, cause: invoked.id };
1162
+ const selection = (runtime2, to) => {
1163
+ const gone = () => lookup(live.now()).calls.has(`${runtime2} ${name} ${to}`) ? undefined : failure("not-found", `${name}->${to} is no longer in ${runtime2}`);
1164
+ return { pod: to, runtime: runtime2, call: client(live, runtime2, name, to, gone, chain), on(o, fn) {
1081
1165
  let stop;
1082
1166
  const connect2 = (fn2) => {
1083
1167
  const p = portOf(live, to, o);
1084
1168
  if (!p)
1085
1169
  throw thrown({ type: "unknown-op", reason: `${name}: ${o?.name} is not an op of ${to}` });
1086
- const why2 = !mine ? failure("not-found", `${name}: this build is closed`) : gone();
1170
+ const why2 = !b.mine ? failure("not-found", `${name}: this build is closed`) : gone();
1087
1171
  if (why2 && !why2.ok)
1088
1172
  throw thrown(why2.fail);
1089
- const c = connect(live, { runtime, from: to, port: p, to: name, gone, fn: fn2 }, (f) => stop?.(f));
1173
+ const c = connect(live, { runtime: runtime2, from: to, port: p, to: name, gone, fn: fn2 }, (f) => stop?.(f));
1090
1174
  if (!c.ok)
1091
1175
  throw thrown(c.fail);
1092
1176
  const sub = c.value;
1093
- mine.add(sub);
1177
+ b.mine.add(sub);
1094
1178
  return () => {
1095
- mine?.delete(sub);
1179
+ b.mine?.delete(sub);
1096
1180
  sub.end();
1097
1181
  };
1098
1182
  };
@@ -1105,22 +1189,23 @@ function contextFor(live, name, onClose) {
1105
1189
  const want = dataOf(s), d = live.now();
1106
1190
  if (!want)
1107
1191
  return [];
1108
- return (lookup(d).callsFrom.get(name) ?? []).flatMap(({ runtime, to }) => {
1192
+ return (lookup(d).callsFrom.get(name) ?? []).flatMap(({ runtime: runtime2, to }) => {
1109
1193
  const sub = { to };
1110
1194
  const i = impl(live, sub.to);
1111
1195
  const target = {
1112
1196
  name: sub.to,
1113
- runtime,
1197
+ runtime: runtime2,
1114
1198
  implementation: i.coord,
1115
1199
  provider: i.provider,
1116
1200
  provides: new Set(i.provides.map((i2) => i2.coord)),
1117
1201
  tags: new Set(d.tags?.[sub.to] ?? [])
1118
1202
  };
1119
- return matches(want, target) ? [selection(runtime, sub.to)] : [];
1203
+ return matches(want, target) ? [selection(runtime2, sub.to)] : [];
1120
1204
  });
1121
1205
  };
1122
1206
  const ctx = {
1123
1207
  self: name,
1208
+ ...invoked && { callingOp: invoked.port },
1124
1209
  get runtimes() {
1125
1210
  return placedIn(live, name).map(([id]) => id);
1126
1211
  },
@@ -1139,13 +1224,13 @@ function contextFor(live, name, onClose) {
1139
1224
  return live.trace.emit({ type: "warning", reason: `${name}: ${o?.name} is not one of its events` });
1140
1225
  if (!fitsData(o, data))
1141
1226
  return live.trace.emit({ type: "failure", pod: name, reason: `${name}: ${o.name} data does not fit ${o.output?.label ?? "its schema"}` });
1142
- await emit(live, name, p, { output: data });
1227
+ await emit(live, name, p, { output: data }, chain);
1143
1228
  },
1144
1229
  addOnPodChangeListener(fn) {
1145
- if (!mine)
1230
+ if (!b.mine)
1146
1231
  return;
1147
1232
  const h = { pod: name, fn };
1148
- heard.add(h);
1233
+ b.heard.add(h);
1149
1234
  live.listeners.podChanges.add(h);
1150
1235
  },
1151
1236
  addOnCloseListener: onClose
@@ -1208,6 +1293,7 @@ async function implementationOf(live, name, pod2) {
1208
1293
  function instances(live) {
1209
1294
  const made2 = new Map;
1210
1295
  const closing = new Map;
1296
+ const outcome = new Map;
1211
1297
  let closed = false;
1212
1298
  async function build(name, c) {
1213
1299
  await closing.get(name);
@@ -1233,10 +1319,11 @@ function instances(live) {
1233
1319
  if (!r.ok)
1234
1320
  return r;
1235
1321
  start(live, name, ctx, r.value.sources, c.add);
1236
- return success({ implementation: impl2, handlers: r.value.handlers });
1322
+ return success({ implementation: impl2, handlers: r.value.handlers, onClose: c.add });
1237
1323
  }
1238
1324
  async function forget(name, why2) {
1239
1325
  const e = made2.get(name);
1326
+ outcome.delete(name);
1240
1327
  if (!e)
1241
1328
  return;
1242
1329
  made2.delete(name);
@@ -1255,17 +1342,21 @@ function instances(live) {
1255
1342
  const c = closer(live, name), mine = { build: build(name, c), close: c.close };
1256
1343
  made2.set(name, e = mine);
1257
1344
  mine.build.then((r) => {
1258
- if (!r.ok && made2.get(name) === mine)
1345
+ if (made2.get(name) !== mine)
1346
+ return;
1347
+ outcome.set(name, r.ok ? "running" : "failed");
1348
+ if (!r.ok)
1259
1349
  made2.delete(name);
1260
1350
  });
1261
1351
  }
1262
1352
  return e.build;
1263
1353
  },
1264
1354
  forget,
1355
+ status: (name) => closed ? "stopped" : outcome.get(name) ?? "not started",
1265
1356
  async close() {
1266
1357
  closed = true;
1267
- const builds = [...made2.values()].map((e) => e.build);
1268
- await Promise.all([...[...made2.keys()].map((n) => forget(n, "closed")), ...builds]);
1358
+ const builds2 = [...made2.values()].map((e) => e.build);
1359
+ await Promise.all([...[...made2.keys()].map((n) => forget(n, "closed")), ...builds2]);
1269
1360
  }
1270
1361
  };
1271
1362
  }
@@ -1306,18 +1397,18 @@ async function notifyPodChanges(live, before) {
1306
1397
  }
1307
1398
 
1308
1399
  // packages/nano/src/application/listen.ts
1309
- function listen(live, runtime, fn) {
1400
+ function listen(live, runtime2, fn) {
1310
1401
  const mine = new Set;
1311
1402
  const seen = new Set;
1312
1403
  const refresh = () => {
1313
- for (const p of live.now().runtimes[runtime]?.pods ?? [])
1404
+ for (const p of live.now().runtimes[runtime2]?.pods ?? [])
1314
1405
  seen.add(p);
1315
1406
  };
1316
1407
  refresh();
1317
1408
  return live.trace.listen((e) => {
1318
1409
  refresh();
1319
1410
  if (e.type === "sent") {
1320
- if (e.runtime === runtime) {
1411
+ if (e.runtime === runtime2) {
1321
1412
  mine.add(e.id);
1322
1413
  fn(e);
1323
1414
  }
@@ -1328,8 +1419,8 @@ function listen(live, runtime, fn) {
1328
1419
  const keep = (l) => l.filter((p) => seen.has(p));
1329
1420
  const n = { added: keep(e.added), removed: keep(e.removed), changed: keep(e.changed), rewired: keep(e.rewired) };
1330
1421
  if (Object.values(n).some((l) => l.length))
1331
- fn({ type: "applied", ...n });
1332
- const here = live.now().runtimes[runtime]?.pods ?? [];
1422
+ fn({ type: "applied", caller: e.caller, ...n });
1423
+ const here = live.now().runtimes[runtime2]?.pods ?? [];
1333
1424
  for (const p of seen)
1334
1425
  if (!here.includes(p))
1335
1426
  seen.delete(p);
@@ -1338,17 +1429,73 @@ function listen(live, runtime, fn) {
1338
1429
  });
1339
1430
  }
1340
1431
 
1432
+ // packages/nano/src/application/start.ts
1433
+ var pending = new WeakMap;
1434
+ function starter(live, at, status, call) {
1435
+ const under = pending.get(live) ?? new Map;
1436
+ pending.set(live, under);
1437
+ async function send2(runtime2, pod2) {
1438
+ const id = live.trace.id();
1439
+ live.trace.emit({ type: "sent", id, runtime: runtime2, kind: "start", from: "host", to: pod2, correlation: id });
1440
+ const reason = refusal(live, { runtime: runtime2, kind: "start", from: "host", to: pod2 });
1441
+ if (reason !== undefined) {
1442
+ live.trace.emit({ type: "denied", id, reason });
1443
+ return failure("denied", reason);
1444
+ }
1445
+ const t0 = performance.now();
1446
+ const made2 = await live.instance(pod2);
1447
+ const r = made2.ok ? success(undefined) : made2;
1448
+ live.trace.emit({ type: "delivered", id, result: r, ms: performance.now() - t0 });
1449
+ return r;
1450
+ }
1451
+ async function begin(pod2) {
1452
+ const r = at();
1453
+ if (!r.ok)
1454
+ return r;
1455
+ if (live.closed())
1456
+ return failure("not-found", "application is closed");
1457
+ if (!lookup(live.now()).placed.get(r.value)?.has(pod2))
1458
+ return failure("not-found", `${pod2} is not placed in ${r.value}`);
1459
+ const key = `${r.value}|${pod2}`, other = under.get(key);
1460
+ if (other) {
1461
+ const o = await other;
1462
+ return o.ok ? success({ started: false }) : o;
1463
+ }
1464
+ if (status(pod2) === "running")
1465
+ return success({ started: false });
1466
+ const mine = send2(r.value, pod2);
1467
+ under.set(key, mine);
1468
+ try {
1469
+ const m = await mine;
1470
+ return m.ok ? success({ started: true }) : m;
1471
+ } finally {
1472
+ if (under.get(key) === mine)
1473
+ under.delete(key);
1474
+ }
1475
+ }
1476
+ return {
1477
+ async start(pod2) {
1478
+ const r = await begin(pod2);
1479
+ return !r.ok ? r : r.value.started ? success(undefined) : failure("invalid-input", `${pod2} is already running`);
1480
+ },
1481
+ async getOrCreate(pod2) {
1482
+ const r = await begin(pod2);
1483
+ return r.ok ? success({ started: r.value.started, pod: call(pod2) }) : r;
1484
+ }
1485
+ };
1486
+ }
1487
+
1341
1488
  // packages/nano/src/application/resolve.ts
1342
1489
  var miss = (type, reason) => ({ ok: false, fail: { type, reason } });
1343
- function placement(live, runtime, api, where) {
1490
+ function placement(live, runtime2, api, where) {
1344
1491
  const found = [];
1345
- const named = where.pod !== undefined && lookup(live.now()).placed.get(runtime)?.has(where.pod) ? [where.pod] : undefined;
1346
- for (const pod2 of named ?? (where.pod !== undefined ? [] : live.now().runtimes[runtime]?.pods ?? [])) {
1492
+ const named = where.pod !== undefined && lookup(live.now()).placed.get(runtime2)?.has(where.pod) ? [where.pod] : undefined;
1493
+ for (const pod2 of named ?? (where.pod !== undefined ? [] : live.now().runtimes[runtime2]?.pods ?? [])) {
1347
1494
  const i = impl(live, pod2);
1348
1495
  if ((where.pod ?? pod2) === pod2 && i?.provides.some((x) => x.coord === api.coord))
1349
- found.push({ pod: pod2, runtime, implementation: i.coord });
1496
+ found.push({ pod: pod2, runtime: runtime2, implementation: i.coord });
1350
1497
  }
1351
- const what = `${api.coord} in ${runtime}${where.pod ? ` at ${where.pod}` : ""}`;
1498
+ const what = `${api.coord} in ${runtime2}${where.pod ? ` at ${where.pod}` : ""}`;
1352
1499
  if (!found.length)
1353
1500
  return miss("not-found", `no pod provides ${what}`);
1354
1501
  return found.length === 1 ? { ok: true, value: found[0] } : miss("not-unique", `${found.length} pods provide ${what}`);
@@ -1356,7 +1503,7 @@ function placement(live, runtime, api, where) {
1356
1503
  var throws = (fail) => () => {
1357
1504
  throw thrown(fail);
1358
1505
  };
1359
- function runtimeView(live, id) {
1506
+ function runtimeView(live, status, id) {
1360
1507
  const at = () => id === undefined ? only(live) : named(live, id);
1361
1508
  const call = (pod2) => {
1362
1509
  const r = at(), id2 = r.ok ? r.value : "";
@@ -1372,7 +1519,7 @@ function runtimeView(live, id) {
1372
1519
  const p = placement(live, r.value, api, where);
1373
1520
  if (!p.ok)
1374
1521
  return p;
1375
- const reachable = Object.values(api.ops).some((o) => refusal(live, { runtime: r.value, kind: o.kind === "event" ? "subscribe" : "call", from: "host", to: p.value.pod, port: port(api, o) }) === undefined);
1522
+ const reachable = Object.values(api.ops).some((o) => refusal(live, { runtime: r.value, kind: o.kind === "event" ? "subscribe" : "call", from: "host", to: p.value.pod, port: port2(api, o) }) === undefined);
1376
1523
  return reachable ? p : miss("denied", `${r.value}'s policy lets the host reach no op of ${api.coord}`);
1377
1524
  };
1378
1525
  const resolve = (api, where = {}) => {
@@ -1391,16 +1538,16 @@ function runtimeView(live, id) {
1391
1538
  const r = at();
1392
1539
  if (!r.ok)
1393
1540
  return throws(r.fail)();
1394
- const runtime = r.value;
1395
- const api = (live.now().runtimes[runtime]?.pods ?? []).flatMap((p2) => impl(live, p2)?.provides ?? []).find((i) => i.byCoord.has(op.coord));
1541
+ const runtime2 = r.value;
1542
+ const api = (live.now().runtimes[runtime2]?.pods ?? []).flatMap((p2) => impl(live, p2)?.provides ?? []).find((i) => i.byCoord.has(op.coord));
1396
1543
  if (!api)
1397
- return throws(miss("not-found", `no pod provides ${op.coord} in ${runtime}`).fail)();
1398
- const p = placement(live, runtime, api, where);
1544
+ return throws(miss("not-found", `no pod provides ${op.coord} in ${runtime2}`).fail)();
1545
+ const p = placement(live, runtime2, api, where);
1399
1546
  if (!p.ok)
1400
1547
  return throws(p.fail)();
1401
1548
  const from = p.value.pod;
1402
- const gone = () => !lookup(live.now()).placed.get(runtime)?.has(from);
1403
- const c = connect(live, { runtime, from, port: port(api, op), to: "host", gone, fn: fn2 }, (f) => stop?.(f));
1549
+ const gone = () => !lookup(live.now()).placed.get(runtime2)?.has(from);
1550
+ const c = connect(live, { runtime: runtime2, from, port: port2(api, op), to: "host", gone, fn: fn2 }, (f) => stop?.(f));
1404
1551
  if (!c.ok)
1405
1552
  throw thrown(c.fail);
1406
1553
  return () => c.value.end();
@@ -1414,7 +1561,11 @@ function runtimeView(live, id) {
1414
1561
  const r = at();
1415
1562
  return r.ok ? listen(live, r.value, fn) : throws(r.fail)();
1416
1563
  };
1417
- return { resolve, get: (api, where) => resolve(api, where).getOrThrow(), call, subscribe, listen: watch };
1564
+ const statusOf = (pod2) => {
1565
+ const r = at();
1566
+ return !r.ok ? r : lookup(live.now()).placed.get(r.value)?.has(pod2) ? success(status(pod2)) : failure("not-found", `${pod2} is not placed in ${r.value}`);
1567
+ };
1568
+ return { resolve, get: (api, where) => resolve(api, where).getOrThrow(), call, subscribe, listen: watch, status: statusOf, ...starter(live, at, status, call) };
1418
1569
  }
1419
1570
  var named = (live, id) => Object.hasOwn(live.now().runtimes, id) ? { ok: true, value: id } : miss("not-found", `no runtime ${id}`);
1420
1571
  var only = (live) => {
@@ -1482,10 +1633,13 @@ async function create4(runtimes, opts = {}) {
1482
1633
  });
1483
1634
  return done;
1484
1635
  }
1485
- async function reconcile(d) {
1636
+ async function reconcile(d, caller) {
1486
1637
  const checked = adopt(d);
1487
1638
  if (!checked.ok)
1488
1639
  return checked;
1640
+ const verdict = await Promise.resolve().then(() => (opts.deploymentPolicy ?? DeploymentPolicies.allowAll()).isAllowed({ caller, deployment: d })).catch((e) => ({ approved: false, reason: `policy threw: ${e instanceof Error ? e.message : String(e)}` }));
1641
+ if (verdict?.approved !== true)
1642
+ return failure("denied", verdict?.approved === false && typeof verdict.reason === "string" ? verdict.reason : "policy gave no verdict");
1489
1643
  const changes = diff(current, checked.value), before = current;
1490
1644
  current = checked.value;
1491
1645
  for (const o of [...live.listeners.ons]) {
@@ -1500,17 +1654,17 @@ async function create4(runtimes, opts = {}) {
1500
1654
  await Promise.all([...changes.removed.map((n) => pods.forget(n, "removed")), ...changes.changed.map((n) => pods.forget(n, "changed"))]);
1501
1655
  await buildEager([...changes.added, ...changes.changed]);
1502
1656
  await notifyPodChanges(live, before);
1503
- trace.emit({ type: "applied", ...changes });
1657
+ trace.emit({ type: "applied", caller, ...changes });
1504
1658
  return success(undefined);
1505
1659
  }
1506
- const one = runtimeView(live);
1660
+ const one = runtimeView(live, pods.status);
1507
1661
  const app = {
1508
- runtime: (id) => runtimeView(live, id),
1662
+ runtime: (id) => runtimeView(live, pods.status, id),
1509
1663
  resolve: (api, where) => one.resolve(api, where),
1510
1664
  get: (api, where) => one.get(api, where),
1511
1665
  subscribe: one.subscribe,
1512
1666
  call: (...at) => at.length === 1 ? one.call(at[0]) : app.runtime(at[0]).call(at[1]),
1513
- apply: (next) => closing ? Promise.resolve(shut()) : queued(() => reconcile(next)),
1667
+ apply: (next, o) => closing ? Promise.resolve(shut()) : queued(() => reconcile(next, o?.caller ?? "host")),
1514
1668
  restart: (pod2) => closing ? Promise.resolve(shut()) : queued(async () => {
1515
1669
  if (!current.pods[pod2])
1516
1670
  return failure("not-found", `no pod ${pod2}`);
@@ -1532,7 +1686,7 @@ async function create4(runtimes, opts = {}) {
1532
1686
  };
1533
1687
  return success(app);
1534
1688
  }
1535
- async function load(url, opts = {}) {
1689
+ async function load2(url, opts = {}) {
1536
1690
  const l = await loaded(url);
1537
1691
  const r = l.ok ? AppDeployment.assemble(l.value.deployment, l.value.registry) : l;
1538
1692
  const app = r.ok ? await create4(r.value, opts) : r;
@@ -1540,13 +1694,14 @@ async function load(url, opts = {}) {
1540
1694
  throw Object.assign(new Error(`${app.fail.type}: ${app.fail.reason}`), { fail: app.fail });
1541
1695
  return app.value;
1542
1696
  }
1543
- var Application = { create: create4, load };
1697
+ var Application = { create: create4, load: load2 };
1544
1698
  export {
1545
1699
  success,
1546
1700
  selectorData,
1547
1701
  provide,
1548
- port,
1702
+ port2 as port,
1549
1703
  matches,
1704
+ lookup,
1550
1705
  isNanoResult,
1551
1706
  isJson,
1552
1707
  hashOf,
@@ -1567,11 +1722,12 @@ export {
1567
1722
  Op,
1568
1723
  Interface,
1569
1724
  Implementation,
1725
+ DeploymentPolicies,
1570
1726
  Coord2 as Coord,
1571
1727
  COORD,
1572
1728
  Application,
1573
1729
  AppDeployment
1574
1730
  };
1575
1731
 
1576
- //# debugId=8907FB92CC372A3264756E2164756E21
1732
+ //# debugId=78F269783047682B64756E2164756E21
1577
1733
  //# sourceMappingURL=index.js.map