@syntropika/tembra-sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -17
- package/dist/authoring/types.d.ts +64 -3
- package/dist/authoring/wit.d.ts +6 -0
- package/dist/bridge/commands.d.ts +1190 -0
- package/dist/bridge/identifiers.d.ts +2 -0
- package/dist/bridge/kernel.d.ts +18 -107
- package/dist/bridge/protocol.d.ts +3 -138
- package/dist/browser.d.ts +14 -1
- package/dist/browser.js +141 -3298
- package/dist/chunks/browser-b8jamxw2.js +3399 -0
- package/dist/chunks/execution-nsqc6nrt.js +1419 -0
- package/dist/chunks/index-01zk0xqx.js +160 -0
- package/dist/chunks/index-3fjdfdfd.js +152 -0
- package/dist/chunks/index-aaymjn7v.js +787 -0
- package/dist/chunks/index-c1w7z9hx.js +356 -0
- package/dist/chunks/index-h8t0n42q.js +738 -0
- package/dist/chunks/index-hfds9mzp.js +308 -0
- package/dist/chunks/index-kr4x67wt.js +177 -0
- package/dist/chunks/index-kr6bnh34.js +117 -0
- package/dist/chunks/index-kyt9dj0a.js +1421 -0
- package/dist/chunks/index-n1wxzc9w.js +830 -0
- package/dist/chunks/index-pvac426d.js +74 -0
- package/dist/chunks/index-smyds5ce.js +3234 -0
- package/dist/chunks/index-sse8aapb.js +121 -0
- package/dist/chunks/index-v6heph77.js +643 -0
- package/dist/chunks/index-xrdvnv37.js +3448 -0
- package/dist/chunks/index-za4mg94e.js +26 -0
- package/dist/chunks/index-zkqmnjj8.js +167 -0
- package/dist/coordinator.js +9 -500
- package/dist/error.d.ts +2 -0
- package/dist/errors.d.ts +3 -0
- package/dist/guest.d.ts +173 -0
- package/dist/guest.js +26 -0
- package/dist/host.d.ts +36 -30
- package/dist/host.js +37 -3276
- package/dist/http/bytes.d.ts +8 -0
- package/dist/http/events.d.ts +7 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.js +291 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +49 -862
- package/dist/infrastructure/rpc/client.d.ts +2 -1
- package/dist/infrastructure/rpc/resources.d.ts +28 -0
- package/dist/interpreter/abi.d.ts +54 -0
- package/dist/interpreter/acquire.d.ts +18 -0
- package/dist/interpreter/browser-network.d.ts +52 -0
- package/dist/interpreter/browser-port.d.ts +55 -0
- package/dist/interpreter/browser.d.ts +79 -0
- package/dist/interpreter/cli.d.ts +5 -0
- package/dist/interpreter/codec.d.ts +42 -0
- package/dist/interpreter/component/execution.d.ts +42 -0
- package/dist/interpreter/component/host.d.ts +69 -0
- package/dist/interpreter/component/instance.d.ts +40 -0
- package/dist/interpreter/component/kernel.d.ts +120 -0
- package/dist/interpreter/component/names.d.ts +5 -0
- package/dist/interpreter/component/port.d.ts +85 -0
- package/dist/interpreter/component/prepared.d.ts +97 -0
- package/dist/interpreter/component/resources.d.ts +45 -0
- package/dist/interpreter/component/revision.d.ts +87 -0
- package/dist/interpreter/component/scope.d.ts +116 -0
- package/dist/interpreter/component/streams.d.ts +28 -0
- package/dist/interpreter/component/values.d.ts +79 -0
- package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
- package/dist/interpreter/component/wasi-host.d.ts +64 -0
- package/dist/interpreter/component/wasi-http.d.ts +33 -0
- package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
- package/dist/interpreter/component/wasi.d.ts +41 -0
- package/dist/interpreter/core.d.ts +64 -0
- package/dist/interpreter/fetch-http-provider.d.ts +17 -0
- package/dist/interpreter/filesystem/contract.d.ts +85 -0
- package/dist/interpreter/filesystem/memory.d.ts +3 -0
- package/dist/interpreter/filesystem/opfs.d.ts +3 -0
- package/dist/interpreter/filesystem/scope.d.ts +35 -0
- package/dist/interpreter/filesystem.d.ts +8 -0
- package/dist/interpreter/gate.d.ts +6 -0
- package/dist/interpreter/host-protocol.d.ts +100 -0
- package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
- package/dist/interpreter/http-ingress.d.ts +96 -0
- package/dist/interpreter/http-provider.d.ts +85 -0
- package/dist/interpreter/io.d.ts +20 -0
- package/dist/interpreter/mobile.d.ts +149 -0
- package/dist/interpreter/native-ingress.d.ts +95 -0
- package/dist/interpreter/node-port.d.ts +25 -0
- package/dist/interpreter/node.d.ts +36 -0
- package/dist/interpreter/revision.d.ts +64 -0
- package/dist/interpreter/scope.d.ts +89 -0
- package/dist/interpreter/socket-addresses.d.ts +50 -0
- package/dist/interpreter/socket-provider.d.ts +110 -0
- package/dist/interpreter/standard-cli.d.ts +34 -0
- package/dist/interpreter/standard-codec.d.ts +96 -0
- package/dist/interpreter/standard-filesystem.d.ts +47 -0
- package/dist/interpreter/standard-host.d.ts +71 -0
- package/dist/interpreter/standard-http-values.d.ts +159 -0
- package/dist/interpreter/standard-http.d.ts +9 -0
- package/dist/interpreter/standard-ingress.d.ts +63 -0
- package/dist/interpreter/standard-sockets.d.ts +177 -0
- package/dist/interpreter/standard-streams.d.ts +218 -0
- package/dist/interpreter/standard-system.d.ts +35 -0
- package/dist/interpreter/standard-utf8.d.ts +4 -0
- package/dist/interpreter/standard.d.ts +18 -0
- package/dist/interpreter/types.d.ts +152 -0
- package/dist/interpreter/wit-shape.d.ts +92 -0
- package/dist/manager.js +5 -332
- package/dist/msgpack.js +9 -615
- package/dist/node.d.ts +8 -1
- package/dist/node.js +248 -3287
- package/dist/rpc.js +196 -699
- package/dist/runtime/adapters.d.ts +120 -0
- package/dist/runtime/adapters.js +38 -0
- package/dist/runtime/calls.d.ts +9 -3
- package/dist/runtime/lifecycle.d.ts +3 -1
- package/dist/runtime/orbs.d.ts +5 -4
- package/dist/runtime/references.d.ts +27 -1
- package/dist/runtime/reload.d.ts +5 -3
- package/dist/runtime/scopes.d.ts +1 -1
- package/dist/runtime/signals.d.ts +4 -0
- package/dist/runtime/wit-client.d.ts +38 -0
- package/dist/telemetry.js +4 -25
- package/dist/tooling/build.d.ts +2 -2
- package/dist/tooling/client-resources.d.ts +23 -0
- package/dist/tooling/client.d.ts +10 -0
- package/dist/tooling/component-glue.d.ts +17 -0
- package/dist/tooling/component.d.ts +11 -0
- package/dist/tooling/index.d.ts +3 -1
- package/dist/tooling/index.js +1155 -102
- package/dist/tooling/resolver.d.ts +4 -4
- package/dist/tooling/typecheck.d.ts +2 -1
- package/dist/tooling/types.d.ts +27 -12
- package/dist/tooling/wit.d.ts +9 -0
- package/dist/wasi/wasi-clocks-types.d.ts +2 -0
- package/dist/wasi/wasi-http-client.d.ts +5 -0
- package/dist/wasi/wasi-http-types.d.ts +285 -0
- package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
- package/dist/wasi/wasi-sockets-types.d.ts +146 -0
- package/package.json +62 -35
- package/src/authoring/declaration.ts +1 -1
- package/src/authoring/types.ts +53 -3
- package/src/authoring/wit.ts +15 -0
- package/src/bridge/commands.ts +1105 -0
- package/src/bridge/identifiers.ts +2 -0
- package/src/bridge/kernel.ts +56 -98
- package/src/bridge/protocol.ts +3 -142
- package/src/browser.ts +90 -6
- package/src/context-key.ts +4 -7
- package/src/error.ts +1 -1
- package/src/errors.ts +7 -0
- package/src/guest.ts +327 -0
- package/src/host.ts +128 -23
- package/src/http/bytes.ts +87 -0
- package/src/http/events.ts +34 -0
- package/src/http.ts +272 -0
- package/src/index.ts +3 -0
- package/src/infrastructure/rpc/client.ts +136 -17
- package/src/infrastructure/rpc/resources.ts +123 -0
- package/src/interpreter/abi.ts +69 -0
- package/src/interpreter/acquire.ts +58 -0
- package/src/interpreter/browser-network.ts +170 -0
- package/src/interpreter/browser-port.ts +425 -0
- package/src/interpreter/browser.ts +340 -0
- package/src/interpreter/cli.ts +30 -0
- package/src/interpreter/codec.ts +298 -0
- package/src/interpreter/component/execution.ts +264 -0
- package/src/interpreter/component/host.ts +409 -0
- package/src/interpreter/component/instance.ts +138 -0
- package/src/interpreter/component/kernel.ts +611 -0
- package/src/interpreter/component/names.ts +13 -0
- package/src/interpreter/component/port.ts +598 -0
- package/src/interpreter/component/prepared.ts +194 -0
- package/src/interpreter/component/resources.ts +345 -0
- package/src/interpreter/component/revision.ts +702 -0
- package/src/interpreter/component/scope.ts +447 -0
- package/src/interpreter/component/streams.ts +180 -0
- package/src/interpreter/component/values.ts +254 -0
- package/src/interpreter/component/wasi-filesystem.ts +472 -0
- package/src/interpreter/component/wasi-host.ts +197 -0
- package/src/interpreter/component/wasi-http.ts +939 -0
- package/src/interpreter/component/wasi-sockets.ts +958 -0
- package/src/interpreter/component/wasi.ts +238 -0
- package/src/interpreter/core.ts +386 -0
- package/src/interpreter/fetch-http-provider.ts +98 -0
- package/src/interpreter/filesystem/contract.ts +138 -0
- package/src/interpreter/filesystem/memory.ts +180 -0
- package/src/interpreter/filesystem/opfs.ts +294 -0
- package/src/interpreter/filesystem/scope.ts +390 -0
- package/src/interpreter/filesystem.ts +20 -0
- package/src/interpreter/gate.ts +55 -0
- package/src/interpreter/host-protocol.ts +242 -0
- package/src/interpreter/http-ingress-fetch.ts +133 -0
- package/src/interpreter/http-ingress.ts +203 -0
- package/src/interpreter/http-provider.ts +105 -0
- package/src/interpreter/io.ts +66 -0
- package/src/interpreter/mobile.ts +385 -0
- package/src/interpreter/native-ingress.ts +550 -0
- package/src/interpreter/node-port.ts +218 -0
- package/src/interpreter/node.ts +114 -0
- package/src/interpreter/revision.ts +450 -0
- package/src/interpreter/scope.ts +453 -0
- package/src/interpreter/socket-addresses.ts +246 -0
- package/src/interpreter/socket-provider.ts +126 -0
- package/src/interpreter/standard-cli.ts +184 -0
- package/src/interpreter/standard-codec.ts +403 -0
- package/src/interpreter/standard-filesystem.ts +545 -0
- package/src/interpreter/standard-host.ts +840 -0
- package/src/interpreter/standard-http-values.ts +624 -0
- package/src/interpreter/standard-http.ts +622 -0
- package/src/interpreter/standard-ingress.ts +344 -0
- package/src/interpreter/standard-sockets.ts +847 -0
- package/src/interpreter/standard-streams.ts +710 -0
- package/src/interpreter/standard-system.ts +182 -0
- package/src/interpreter/standard-utf8.ts +72 -0
- package/src/interpreter/standard.ts +283 -0
- package/src/interpreter/types.ts +163 -0
- package/src/interpreter/wit-shape.ts +175 -0
- package/src/node.ts +43 -14
- package/src/runtime/activities.ts +6 -6
- package/src/runtime/adapters.ts +314 -0
- package/src/runtime/calls.ts +218 -56
- package/src/runtime/context.ts +7 -7
- package/src/runtime/lifecycle.ts +36 -17
- package/src/runtime/orbs.ts +81 -39
- package/src/runtime/programs.ts +16 -8
- package/src/runtime/references.ts +128 -11
- package/src/runtime/reload.ts +71 -30
- package/src/runtime/resources.ts +2 -2
- package/src/runtime/scopes.ts +17 -17
- package/src/runtime/session.ts +3 -1
- package/src/runtime/signals.ts +31 -0
- package/src/runtime/wit-client.ts +228 -0
- package/src/tooling/build.ts +152 -54
- package/src/tooling/client-resources.ts +74 -0
- package/src/tooling/client.ts +531 -0
- package/src/tooling/component-glue.ts +288 -0
- package/src/tooling/component.ts +225 -0
- package/src/tooling/index.ts +3 -7
- package/src/tooling/resolver.ts +42 -25
- package/src/tooling/typecheck.ts +59 -4
- package/src/tooling/types.ts +27 -12
- package/src/tooling/wit.ts +188 -0
- package/dist/embedded.d.ts +0 -1
- package/dist/embedded.js +0 -1
- package/src/embedded.ts +0 -293
package/src/tooling/typecheck.ts
CHANGED
|
@@ -1,13 +1,24 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
2
4
|
|
|
3
5
|
/** Check orb source types before bundling an artifact. */
|
|
4
|
-
export function typecheck(
|
|
6
|
+
export function typecheck(
|
|
7
|
+
entry: string,
|
|
8
|
+
root: string,
|
|
9
|
+
virtual: ReadonlyMap<string, string> = new Map(),
|
|
10
|
+
conditions: readonly string[] = [],
|
|
11
|
+
): ts.Program {
|
|
5
12
|
const configFile = ts.findConfigFile(root, ts.sys.fileExists);
|
|
6
13
|
const loaded = configFile ? ts.readConfigFile(configFile, ts.sys.readFile) : { config: {} };
|
|
7
14
|
if (loaded.error)
|
|
8
15
|
throw new Error(ts.flattenDiagnosticMessageText(loaded.error.messageText, "\n"));
|
|
9
|
-
const parsed = ts.parseJsonConfigFileContent(
|
|
10
|
-
|
|
16
|
+
const parsed = ts.parseJsonConfigFileContent(
|
|
17
|
+
loaded.config,
|
|
18
|
+
ts.sys,
|
|
19
|
+
configFile ? path.dirname(configFile) : root,
|
|
20
|
+
);
|
|
21
|
+
const options: ts.CompilerOptions = {
|
|
11
22
|
...parsed.options,
|
|
12
23
|
target: ts.ScriptTarget.ES2023,
|
|
13
24
|
module: ts.ModuleKind.ESNext,
|
|
@@ -16,7 +27,50 @@ export function typecheck(entry: string, root: string): void {
|
|
|
16
27
|
noEmit: true,
|
|
17
28
|
strict: true,
|
|
18
29
|
skipLibCheck: true,
|
|
19
|
-
|
|
30
|
+
lib: ["lib.es2023.d.ts", "lib.esnext.disposable.d.ts"],
|
|
31
|
+
types: [],
|
|
32
|
+
allowArbitraryExtensions: true,
|
|
33
|
+
customConditions: [...conditions, "source"],
|
|
34
|
+
};
|
|
35
|
+
const host = ts.createCompilerHost(options);
|
|
36
|
+
const readFile = host.readFile;
|
|
37
|
+
const fileExists = host.fileExists;
|
|
38
|
+
const getSourceFile = host.getSourceFile;
|
|
39
|
+
const directoryExists = host.directoryExists;
|
|
40
|
+
const directories = new Set<string>();
|
|
41
|
+
for (const file of virtual.keys()) {
|
|
42
|
+
let directory = path.dirname(file);
|
|
43
|
+
while (!directories.has(directory)) {
|
|
44
|
+
directories.add(directory);
|
|
45
|
+
const parent = path.dirname(directory);
|
|
46
|
+
if (parent === directory) break;
|
|
47
|
+
directory = parent;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
host.directoryExists = (directory) =>
|
|
51
|
+
directories.has(directory) || directoryExists?.(directory) === true;
|
|
52
|
+
host.readFile = (file) => virtual.get(file) ?? readFile(file);
|
|
53
|
+
host.fileExists = (file) => virtual.has(file) || fileExists(file);
|
|
54
|
+
host.getSourceFile = (file, language, onError, create) => {
|
|
55
|
+
const source = virtual.get(file);
|
|
56
|
+
return source === undefined
|
|
57
|
+
? getSourceFile(file, language, onError, create)
|
|
58
|
+
: ts.createSourceFile(
|
|
59
|
+
file,
|
|
60
|
+
source,
|
|
61
|
+
typeof language === "object" ? language.languageVersion : language,
|
|
62
|
+
true,
|
|
63
|
+
);
|
|
64
|
+
};
|
|
65
|
+
// The package entry locates its canonical guest declarations in source or installed output.
|
|
66
|
+
const packageEntry = new URL(import.meta.resolve("@syntropika/tembra-sdk"));
|
|
67
|
+
const environment = fileURLToPath(
|
|
68
|
+
new URL(packageEntry.pathname.endsWith(".ts") ? "guest.ts" : "guest.d.ts", packageEntry),
|
|
69
|
+
);
|
|
70
|
+
// Include selected ambient declarations without typechecking unrelated build entrypoints.
|
|
71
|
+
const ambient = parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file));
|
|
72
|
+
const aliases = [...virtual.keys()].filter((file) => file.endsWith(".d.wit.ts"));
|
|
73
|
+
const program = ts.createProgram([entry, environment, ...ambient, ...aliases], options, host);
|
|
20
74
|
const diagnostics = ts.getPreEmitDiagnostics(program);
|
|
21
75
|
if (diagnostics.length)
|
|
22
76
|
throw new Error(
|
|
@@ -29,4 +83,5 @@ export function typecheck(entry: string, root: string): void {
|
|
|
29
83
|
getNewLine: () => "\n",
|
|
30
84
|
}),
|
|
31
85
|
);
|
|
86
|
+
return program;
|
|
32
87
|
}
|
package/src/tooling/types.ts
CHANGED
|
@@ -1,16 +1,29 @@
|
|
|
1
|
-
export const Platform = Object.freeze({
|
|
2
|
-
Browser: "browser",
|
|
3
|
-
Worker: "worker",
|
|
4
|
-
Node: "node",
|
|
5
|
-
Embedded: "embedded",
|
|
6
|
-
} as const);
|
|
7
|
-
export type Platform = (typeof Platform)[keyof typeof Platform];
|
|
8
1
|
export interface BuildTarget {
|
|
9
2
|
entry: string;
|
|
10
|
-
|
|
3
|
+
wit: string;
|
|
4
|
+
world?: string;
|
|
5
|
+
/** Compiled components receive their identity from this target's name and API version. */
|
|
6
|
+
apiVersion?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Compiled callback interfaces contributing to their selected Orb's hook, with execution
|
|
9
|
+
* priority, next to those a component built with `#[orb]` carries; a hook named by both must
|
|
10
|
+
* have the same priority.
|
|
11
|
+
*/
|
|
12
|
+
contributes?: Readonly<Record<string, number>>;
|
|
13
|
+
/**
|
|
14
|
+
* Compiled reference-view imports, by import binding, mapped to the provider interface identity
|
|
15
|
+
* each view addresses, next to those a component built with `#[orb]` carries; a view named by
|
|
16
|
+
* both must address the same interface. The contract checks every view's shape before
|
|
17
|
+
* packaging.
|
|
18
|
+
*/
|
|
19
|
+
references?: Readonly<Record<string, string>>;
|
|
20
|
+
/**
|
|
21
|
+
* Compiled Orbs only: also emit `browser/index.js`, an application-owned module that lets
|
|
22
|
+
* browser hosts run exactly this artifact (register it with `createHost({ isolated: {
|
|
23
|
+
* components } })`). Source Orbs run in browsers without preparation.
|
|
24
|
+
*/
|
|
25
|
+
browser?: boolean;
|
|
11
26
|
minify?: boolean;
|
|
12
|
-
typecheck?: boolean;
|
|
13
|
-
nativeExternals?: readonly string[];
|
|
14
27
|
define?: Readonly<Record<string, string>>;
|
|
15
28
|
}
|
|
16
29
|
export interface BuildConfig {
|
|
@@ -19,14 +32,16 @@ export interface BuildConfig {
|
|
|
19
32
|
builds: Readonly<Record<string, BuildTarget>>;
|
|
20
33
|
}
|
|
21
34
|
export interface Artifact {
|
|
35
|
+
/** Build target key; the source Orb's installation identity belongs to its literal declaration. */
|
|
22
36
|
name: string;
|
|
23
|
-
platform: Platform;
|
|
24
37
|
path: string;
|
|
25
38
|
sha256: string;
|
|
26
39
|
bytes: number;
|
|
40
|
+
/** The prepared browser module of a compiled Orb built with `browser: true`. */
|
|
41
|
+
browser?: string;
|
|
27
42
|
}
|
|
28
43
|
|
|
29
|
-
/** Preserve build
|
|
44
|
+
/** Preserve literal build configuration types. */
|
|
30
45
|
export function defineConfig<const C extends BuildConfig>(config: C): C {
|
|
31
46
|
return config;
|
|
32
47
|
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import type { NodeContract } from "@syntropika/tembra-engine-node";
|
|
5
|
+
import { query } from "../interpreter/types.ts";
|
|
6
|
+
|
|
7
|
+
export interface WitTypes {
|
|
8
|
+
readonly files: ReadonlyMap<string, string>;
|
|
9
|
+
readonly sha256: string;
|
|
10
|
+
readonly contract: NodeContract;
|
|
11
|
+
readonly imports: ReadonlyMap<string, string>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Generate official WIT declarations in memory and expose a type-only .wit module. */
|
|
15
|
+
export async function witTypes(
|
|
16
|
+
file: string,
|
|
17
|
+
world?: string,
|
|
18
|
+
root = path.dirname(path.resolve(file)),
|
|
19
|
+
): Promise<WitTypes> {
|
|
20
|
+
const { NodeContract } = await import("@syntropika/tembra-engine-node");
|
|
21
|
+
const { $init, generateTypes } = await import("@bytecodealliance/jco-transpile/component");
|
|
22
|
+
const absolute = path.resolve(file);
|
|
23
|
+
if (!absolute.endsWith(".wit")) throw new Error("Direct WIT imports require a .wit entry file");
|
|
24
|
+
const contract = new NodeContract(path.dirname(absolute), world);
|
|
25
|
+
await $init;
|
|
26
|
+
const generated = generateTypes("contract", {
|
|
27
|
+
wit: { tag: "binary", val: contract.wit() },
|
|
28
|
+
...(world ? { world } : {}),
|
|
29
|
+
});
|
|
30
|
+
const entries = [...generated]
|
|
31
|
+
.map(([name, bytes]): [string, Uint8Array] => {
|
|
32
|
+
if (!name.endsWith(".d.ts")) return [name, bytes];
|
|
33
|
+
const text = new TextDecoder().decode(bytes);
|
|
34
|
+
const source = ts.createSourceFile(name, text, ts.ScriptTarget.ESNext, true);
|
|
35
|
+
// WIT resources always have a canonical drop. The pinned jco declarations omit it;
|
|
36
|
+
// declaration merging exposes the runtime's Symbol.dispose without copying WIT types.
|
|
37
|
+
const resources = source.statements.filter(
|
|
38
|
+
(statement): statement is ts.ClassDeclaration =>
|
|
39
|
+
ts.isClassDeclaration(statement) &&
|
|
40
|
+
statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ===
|
|
41
|
+
true,
|
|
42
|
+
);
|
|
43
|
+
const disposable = resources.map(
|
|
44
|
+
(resource) => `export interface ${resource.name!.text} extends Disposable {}`,
|
|
45
|
+
);
|
|
46
|
+
return [
|
|
47
|
+
name,
|
|
48
|
+
disposable.length
|
|
49
|
+
? new TextEncoder().encode(
|
|
50
|
+
'/// <reference lib="esnext.disposable" />\n' +
|
|
51
|
+
text +
|
|
52
|
+
"\n" +
|
|
53
|
+
disposable.join("\n") +
|
|
54
|
+
"\n",
|
|
55
|
+
)
|
|
56
|
+
: bytes,
|
|
57
|
+
];
|
|
58
|
+
})
|
|
59
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
60
|
+
const digest = createHash("sha256");
|
|
61
|
+
for (const [name, bytes] of entries)
|
|
62
|
+
digest.update(JSON.stringify([name, bytes.length])).update(bytes);
|
|
63
|
+
const sha256 = digest.digest("hex");
|
|
64
|
+
const directory = path.join(path.dirname(absolute), ".tembra", "types", sha256);
|
|
65
|
+
const files = new Map(
|
|
66
|
+
entries.map(([name, bytes]) => [path.join(directory, name), new TextDecoder().decode(bytes)]),
|
|
67
|
+
);
|
|
68
|
+
const alias = absolute.slice(0, -4) + ".d.wit.ts";
|
|
69
|
+
const target =
|
|
70
|
+
"./" +
|
|
71
|
+
path
|
|
72
|
+
.relative(path.dirname(alias), path.join(directory, "contract.js"))
|
|
73
|
+
.split(path.sep)
|
|
74
|
+
.join("/");
|
|
75
|
+
// Share one physical ambient module across contracts in the same editor project.
|
|
76
|
+
const references: string[] = [];
|
|
77
|
+
const imports = new Map<string, string>();
|
|
78
|
+
const generatedFiles = new Map(
|
|
79
|
+
entries.map(([name, bytes]) => [name, new TextDecoder().decode(bytes)]),
|
|
80
|
+
);
|
|
81
|
+
const description = query<{ imports: { contract?: string }[] }>(contract, { kind: "describe" });
|
|
82
|
+
for (const imported of description.imports) {
|
|
83
|
+
if (!imported.contract) continue;
|
|
84
|
+
const identity = /^([^:]+):([^/]+)\/([^@]+)(?:@[^@]+)?$/.exec(imported.contract);
|
|
85
|
+
if (!identity) continue;
|
|
86
|
+
const [, namespace, name, interfaceName] = identity;
|
|
87
|
+
const declaration = `interfaces/${namespace}-${name}-${interfaceName}.d.ts`;
|
|
88
|
+
const contents = generatedFiles.get(declaration);
|
|
89
|
+
if (!contents) continue;
|
|
90
|
+
// The pinned generator can collapse two imported versions onto one file. Never alias
|
|
91
|
+
// that file to the other identity: that would silently change its binary signature.
|
|
92
|
+
const declared = /@module Interface ([^\s*]+)/.exec(contents)?.[1];
|
|
93
|
+
if (declared !== imported.contract)
|
|
94
|
+
throw new Error(
|
|
95
|
+
`Ambiguous generated WIT interface: ${imported.contract} resolves to ${declared}`,
|
|
96
|
+
);
|
|
97
|
+
const closure = declarationClosure(declaration, generatedFiles);
|
|
98
|
+
const fingerprint = createHash("sha256").update(imported.contract);
|
|
99
|
+
for (const [name, contents] of [...closure].sort(([a], [b]) => a.localeCompare(b)))
|
|
100
|
+
fingerprint.update(JSON.stringify([name, contents]));
|
|
101
|
+
const digest = fingerprint.digest("hex");
|
|
102
|
+
imports.set(imported.contract, digest);
|
|
103
|
+
const shared = path.join(root, ".tembra", "imports", digest);
|
|
104
|
+
for (const [name, contents] of closure) files.set(path.join(shared, name), contents);
|
|
105
|
+
const module = "./" + declaration.replace(/\.d\.ts$/, ".js");
|
|
106
|
+
const ambient = path.join(shared, "index.d.ts");
|
|
107
|
+
files.set(ambient, canonicalModule(imported.contract, module, contents));
|
|
108
|
+
const reference = "./" + path.relative(path.dirname(alias), ambient).split(path.sep).join("/");
|
|
109
|
+
references.push(`/// <reference path=${JSON.stringify(reference)} />`);
|
|
110
|
+
}
|
|
111
|
+
files.set(alias, [...references, `export * from ${JSON.stringify(target)};`, ""].join("\n"));
|
|
112
|
+
return { files, sha256, contract, imports };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Keep the imported interface's complete official type graph, excluding unrelated world exports. */
|
|
116
|
+
function declarationClosure(
|
|
117
|
+
entry: string,
|
|
118
|
+
generated: ReadonlyMap<string, string>,
|
|
119
|
+
): Map<string, string> {
|
|
120
|
+
const files = new Map<string, string>();
|
|
121
|
+
function include(file: string): void {
|
|
122
|
+
if (files.has(file)) return;
|
|
123
|
+
const contents = generated.get(file);
|
|
124
|
+
if (contents === undefined) throw new Error(`Missing generated WIT declaration: ${file}`);
|
|
125
|
+
files.set(file, contents);
|
|
126
|
+
const source = ts.createSourceFile(file, contents, ts.ScriptTarget.ESNext, true);
|
|
127
|
+
function visit(node: ts.Node): void {
|
|
128
|
+
const specifier =
|
|
129
|
+
ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)
|
|
130
|
+
? node.argument.literal
|
|
131
|
+
: ts.isImportDeclaration(node) || ts.isExportDeclaration(node)
|
|
132
|
+
? node.moduleSpecifier
|
|
133
|
+
: undefined;
|
|
134
|
+
if (specifier && ts.isStringLiteral(specifier) && specifier.text.startsWith("."))
|
|
135
|
+
include(
|
|
136
|
+
path.posix
|
|
137
|
+
.normalize(path.posix.join(path.posix.dirname(file), specifier.text))
|
|
138
|
+
.replace(/\.js$/, ".d.ts"),
|
|
139
|
+
);
|
|
140
|
+
ts.forEachChild(node, visit);
|
|
141
|
+
}
|
|
142
|
+
visit(source);
|
|
143
|
+
}
|
|
144
|
+
include(entry);
|
|
145
|
+
return files;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Alias official declarations without copying their signatures or defining another WIT schema. */
|
|
149
|
+
function canonicalModule(identity: string, module: string, contents: string): string {
|
|
150
|
+
const source = ts.createSourceFile(module, contents, ts.ScriptTarget.ESNext, true);
|
|
151
|
+
const types = new Map<string, readonly ts.TypeParameterDeclaration[]>();
|
|
152
|
+
const values = new Set<string>();
|
|
153
|
+
for (const statement of source.statements) {
|
|
154
|
+
if (
|
|
155
|
+
!ts.canHaveModifiers(statement) ||
|
|
156
|
+
!ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
|
|
157
|
+
)
|
|
158
|
+
continue;
|
|
159
|
+
if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement))
|
|
160
|
+
types.set(statement.name.text, statement.typeParameters ?? []);
|
|
161
|
+
else if (ts.isFunctionDeclaration(statement) && statement.name) values.add(statement.name.text);
|
|
162
|
+
else if (
|
|
163
|
+
(ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) &&
|
|
164
|
+
statement.name
|
|
165
|
+
) {
|
|
166
|
+
types.set(
|
|
167
|
+
statement.name.text,
|
|
168
|
+
ts.isClassDeclaration(statement) ? (statement.typeParameters ?? []) : [],
|
|
169
|
+
);
|
|
170
|
+
values.add(statement.name.text);
|
|
171
|
+
} else throw new Error(`Unsupported generated WIT declaration in ${identity}`);
|
|
172
|
+
}
|
|
173
|
+
const from = `import(${JSON.stringify(module)})`;
|
|
174
|
+
return [
|
|
175
|
+
`declare module ${JSON.stringify(identity)} {`,
|
|
176
|
+
...[...types].map(([name, parameters]) => {
|
|
177
|
+
const declaration = parameters.length
|
|
178
|
+
? `<${parameters.map((parameter) => parameter.getText(source)).join(", ")}>`
|
|
179
|
+
: "";
|
|
180
|
+
const arguments_ = parameters.length
|
|
181
|
+
? `<${parameters.map((parameter) => parameter.name.text).join(", ")}>`
|
|
182
|
+
: "";
|
|
183
|
+
return ` export type ${name}${declaration} = ${from}.${name}${arguments_};`;
|
|
184
|
+
}),
|
|
185
|
+
...[...values].map((name) => ` export const ${name}: typeof ${from}.${name};`),
|
|
186
|
+
"}",
|
|
187
|
+
].join("\n");
|
|
188
|
+
}
|
package/dist/embedded.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/embedded.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
(()=>{var l=Object.freeze({Invalid:"invalid",Unavailable:"unavailable",Released:"released",Gone:"gone",Expired:"expired",Cancelled:"cancelled",Forbidden:"forbidden",Conflict:"conflict",Unsupported:"unsupported",Closed:"closed",Exhausted:"exhausted"}),u=Object.freeze({ActivationBusy:"activation_busy",Address:"address",AlreadyCommitted:"already_committed",AmbiguousScope:"ambiguous_scope",ApiVersion:"api_version",Arguments:"arguments",AsyncFactory:"async_factory",AsyncState:"async_state",Bigint:"bigint",ByteResult:"byte_result",Call:"call",Callback:"callback",CleanupBusy:"cleanup_busy",Clock:"clock",Codec:"codec",Connection:"connection",Context:"context",Contribution:"contribution",CoordinationLimits:"coordination_limits",Deadline:"deadline",Dependency:"dependency",DependencyCycle:"dependency_cycle",DependencyService:"dependency_service",Disposing:"disposing",Driver:"driver",Duplicate:"duplicate",DuplicateContribution:"duplicate_contribution",DuplicateListener:"duplicate_listener",DuplicateResource:"duplicate_resource",DuplicateService:"duplicate_service",EffectResults:"effect_results",EffectsRunning:"effects_running",EngineEffect:"engine_effect",EventSource:"event_source",ExclusiveDependent:"exclusive_dependent",Executor:"executor",Orb:"orb",OrbGone:"orb_gone",OrbInstalled:"orb_installed",OrbScope:"orb_scope",Factory:"factory",FactoryExpired:"factory_expired",FrameSize:"frame_size",GateBusy:"gate_busy",GateOrb:"gate_orb",GateObject:"gate_object",Hook:"hook",HookDependency:"hook_dependency",Hooks:"hooks",HooksDisabled:"hooks_disabled",Host:"host",HostAddress:"host_address",HostResource:"host_resource",HostResourceReload:"host_resource_reload",Identities:"identities",Implementation:"implementation",Invocation:"invocation",Javascript:"javascript",JsonAccessor:"json_accessor",JsonCycle:"json_cycle",JsonNumber:"json_number",JsonSymbol:"json_symbol",JsonTag:"json_tag",JsonType:"json_type",JsonValue:"json_value",Lifetime:"lifetime",Linger:"linger",ListenerCallback:"listener_callback",LiveConsumer:"live_consumer",LiveReference:"live_reference",LocalValue:"local_value",Memory:"memory",Metadata:"metadata",MetadataSize:"metadata_size",Method:"method",MigrationGate:"migration_gate",MigrationRequired:"migration_required",MigrationValue:"migration_value",MissingHook:"missing_hook",MissingMethod:"missing_method",NativeEffect:"native_effect",NativeMethod:"native_method",NativeObject:"native_object",NativeService:"native_service",Next:"next",NextUsed:"next_used",NotReady:"not_ready",Object:"object",ObjectState:"object_state",ObservationSource:"observation_source",ObservationAdmitted:"observation_admitted",Opaque:"opaque",Operation:"operation",OperationOwner:"operation_owner",Owner:"owner",Payload:"payload",PendingRequests:"pending_requests",PrepareDeadline:"prepare_deadline",Priority:"priority",Program:"program",ProgramPhase:"program_phase",ProgramRunning:"program_running",Reference:"reference",ReloadAborted:"reload_aborted",ReloadDeadline:"reload_deadline",ReloadPreparing:"reload_preparing",ReloadRunning:"reload_running",ReloadTicket:"reload_ticket",RemoteOpaque:"remote_opaque",RemoteReferences:"remote_references",Request:"request",RequestIds:"request_ids",Requires:"requires",Resource:"resource",ResourceDependencies:"resource_dependencies",ResourceDependency:"resource_dependency",ResourceHost:"resource_host",ResourceInFactory:"resource_in_factory",ResourceState:"resource_state",ResourceVersion:"resource_version",Result:"result",RetainedVersions:"retained_versions",RevisionExhausted:"revision_exhausted",Root:"root",Route:"route",RpcFrame:"rpc_frame",RpcOperation:"rpc_operation",RpcRequest:"rpc_request",RustType:"rust_type",Scope:"scope",ScopeClosed:"scope_closed",ScopeOrb:"scope_orb",ScopeOwner:"scope_owner",ScopeResource:"scope_resource",Serialization:"serialization",Service:"service",ServiceGone:"service_gone",State:"state",StateCycle:"state_cycle",StateInitialized:"state_initialized",StateOwner:"state_owner",StateRevision:"state_revision",StateValidation:"state_validation",StateValue:"state_value",StateVersion:"state_version",Subscription:"subscription",SubscriptionBusy:"subscription_busy",SubscriptionIdle:"subscription_idle",SubscriptionQueue:"subscription_queue",SubscriptionSize:"subscription_size",SubscriptionsDisabled:"subscriptions_disabled",Superseded:"superseded",Task:"task",Telemetry:"telemetry",UndeclaredDependency:"undeclared_dependency",UndeclaredService:"undeclared_service",UnknownService:"unknown_service",UpgradeConflict:"upgrade_conflict",Utf8:"utf8",Value:"value",ValueGone:"value_gone",ValuesExhausted:"values_exhausted",Views:"views"}),G=Object.freeze({Referenced:"referenced",Host:"host"}),_=Object.freeze({Loading:"loading",Live:"live",Released:"released",Gone:"gone"}),D=Object.freeze({Prepared:"prepared",Committed:"committed",Aborted:"aborted"}),ie=Object.freeze({Observe:"observe",Transform:"transform",Decide:"decide"});var d=Object.freeze({ContextDerive:"context-derive",ContextValue:"context-value",ContextStats:"context-stats",Allocate:"allocate",ScopeRegister:"scope-register",ScopeExists:"scope-exists",ScopesForOwner:"scopes-for-owner",ScopesForOrb:"scopes-for-orb",ScopeAddResource:"scope-add-resource",ScopeActivate:"scope-activate",ScopesCleanup:"scopes-cleanup",ScopesReloadRegistered:"scopes-reload-registered",ScopesReload:"scopes-reload",ProgramRun:"program-run",ProgramNext:"program-next",ProgramCompleteStep:"program-complete-step",ProgramCommit:"program-commit",ProgramAbort:"program-abort",ProgramForget:"program-forget",Features:"features",Prepare:"prepare",Gate:"gate",GateOrbs:"gate-orbs",Commit:"commit",Abort:"abort",Orbs:"orbs",Orb:"orb",OrbNamed:"orb-named",NextDeadline:"next-deadline",Address:"address",Acquire:"acquire",Ready:"ready",Dependency:"dependency",Undepend:"undepend",Fail:"fail",Status:"status",Release:"release",Forget:"forget",Root:"root",CleanupRoot:"cleanup-root",RootPrincipal:"root-principal",CheckContext:"check-context",CheckRoot:"check-root",EndRoot:"end-root",CancelRoot:"cancel-root",BeginCall:"begin-call",BeginOperation:"begin-operation",BeginHookObservation:"begin-hook-observation",FinishCall:"finish-call",Invocation:"invocation",StateInit:"state-init",Snapshot:"snapshot",StateAdopt:"state-adopt",Task:"task",TaskRoot:"task-root",StopTask:"stop-task",FinishTask:"finish-task",Resource:"resource",ResourceOpened:"resource-opened",ResourceValue:"resource-value",CloseResource:"close-resource",ResourceClosed:"resource-closed",Disposed:"disposed",Tick:"tick",NextWake:"next-wake",NextIdle:"next-idle",Close:"close",FinishClose:"finish-close",Diagnostics:"diagnostics",Drain:"drain",Restrict:"restrict",Contribute:"contribute",ContributionOrdinal:"contribution-ordinal",HookPlan:"hook-plan",Listen:"listen",Subscribe:"subscribe",Enqueue:"enqueue",NextDelivery:"next-delivery",FinishDelivery:"finish-delivery",Unsubscribe:"unsubscribe"}),C=Object.freeze({Execute:"execute",CancelEffects:"cancel-effects",ProgramPrepared:"program-prepared",ProgramComplete:"program-complete",Dispose:"dispose",CloseResource:"close-resource",DropValue:"drop-value",CancelRoot:"cancel-root",CancelTask:"cancel-task",RetireOrb:"retire-orb",State:"state",SubscriptionFailed:"subscription-failed",DetachSubscription:"detach-subscription",Deliver:"deliver"}),j=Object.freeze({Stop:"stop",Open:"open",Close:"close",Restore:"restore",Prepare:"prepare",Validate:"validate",Initialize:"initialize",Migrate:"migrate",Adopt:"adopt",Start:"start",Drop:"drop"}),Ge=Object.freeze({Execute:"execute",Wait:"wait",Prepared:"prepared",Complete:"complete",Failed:"failed"}),Be=Object.freeze({Activate:"activate",Dispose:"dispose",CancelEffect:"cancel-effect",Effect:"effect",Invoke:"invoke",Contribute:"contribute"}),We=Object.freeze({Describe:"describe",Get:"get",Release:"release",Call:"call",Cancel:"cancel"}),$e=Object.freeze({State:"state"}),I=Object.freeze({Host:"host",Orb:"orb",Object:"object"}),S=Object.freeze({Declaring:"declaring",Prepared:"prepared",Live:"live",Closed:"closed"}),Qe=Object.freeze({Preparing:"preparing",Commit:"commit",Abort:"abort"}),ae=Object.freeze({Ok:"ok",Error:"error"}),K=Object.freeze({Bigint:"bigint",Bytes:"bytes",Object:"object"}),je=Object.freeze({Json:"tembra-json/1",MessagePack:"tembra-msgpack/1"});function f(e,t,n){return Object.freeze({code:e,reason:t,message:n})}var c=Object.freeze({Cancelled:Object.freeze({EngineEffect:f(l.Cancelled,u.EngineEffect,"The engine effect was cancelled"),Request:f(l.Cancelled,u.Request,"The request was cancelled"),Resource:f(l.Cancelled,u.Resource,"Resource opening was cancelled"),Root:f(l.Cancelled,u.Root,"The operation was cancelled"),Task:f(l.Cancelled,u.Task,"The task was cancelled")}),Closed:Object.freeze({Host:f(l.Closed,u.Host,"The host is closing")}),Conflict:Object.freeze({AlreadyCommitted:f(l.Conflict,u.AlreadyCommitted,"The replacement is already committed"),Codec:f(l.Conflict,u.Codec,"The Rust and JS host codecs must agree"),PrepareDeadline:f(l.Conflict,u.PrepareDeadline,"The preparation deadline expired"),ReloadRunning:f(l.Conflict,u.ReloadRunning,"A replacement is already running"),ReloadTicket:f(l.Conflict,u.ReloadTicket,"The replacement is no longer prepared")}),Exhausted:Object.freeze({FrameSize:f(l.Exhausted,u.FrameSize,"The frame exceeds the configured size limit"),PendingRequests:f(l.Exhausted,u.PendingRequests,"The pending request limit was reached"),RemoteReferences:f(l.Exhausted,u.RemoteReferences,"The remote reference limit was reached"),RequestIds:f(l.Exhausted,u.RequestIds,"Request identities are exhausted"),SubscriptionQueue:f(l.Exhausted,u.SubscriptionQueue,"The subscription queue is full")}),Expired:Object.freeze({Next:f(l.Expired,u.Next,"Continuation scope has ended")}),Forbidden:Object.freeze({Context:f(l.Forbidden,u.Context,"An issued context from this host is required"),HostResource:f(l.Forbidden,u.HostResource,"The host resource was not declared"),Method:f(l.Forbidden,u.Method,"The method is not allowed by this reference"),ObservationSource:f(l.Forbidden,u.ObservationSource,"Hook observation requires the original physical invocation"),Opaque:f(l.Forbidden,u.Opaque,"The resource is not available as an opaque local value"),Service:f(l.Forbidden,u.Service,"Access to this service is forbidden"),StateOwner:f(l.Forbidden,u.StateOwner,"Only the owning orb may change this state"),UndeclaredDependency:f(l.Forbidden,u.UndeclaredDependency,"The dependency was not declared"),UndeclaredService:f(l.Forbidden,u.UndeclaredService,"The service was not declared as a dependency")}),Gone:Object.freeze({Connection:f(l.Gone,u.Connection,"The connection is closed"),Contribution:f(l.Gone,u.Contribution,"The contribution is no longer available"),Implementation:f(l.Gone,u.Implementation,"The implementation is no longer available"),ListenerCallback:f(l.Gone,u.ListenerCallback,"The listener callback is no longer available"),Reference:f(l.Gone,u.Reference,"The reference is no longer available"),Resource:f(l.Gone,u.Resource,"The resource is no longer available"),Scope:f(l.Gone,u.Scope,"The declaration scope is no longer available"),State:f(l.Gone,u.State,"State owner is gone")}),Invalid:Object.freeze({Address:f(l.Invalid,u.Address,"Invalid address"),AsyncFactory:f(l.Invalid,u.AsyncFactory,"Factories must be synchronous"),AsyncState:f(l.Invalid,u.AsyncState,"State updates and migrations must be synchronous"),CoordinationLimits:f(l.Invalid,u.CoordinationLimits,"Invalid coordination limits"),DependencyCycle:f(l.Invalid,u.DependencyCycle,"Orb factories cannot acquire their own services"),DependencyService:f(l.Invalid,u.DependencyService,"Invalid dependency service"),DuplicateListener:f(l.Invalid,u.DuplicateListener,"Invalid duplicate listener"),DuplicateResource:f(l.Invalid,u.DuplicateResource,"Invalid duplicate resource"),EventSource:f(l.Invalid,u.EventSource,"Invalid event source"),Orb:f(l.Invalid,u.Orb,"An orb needs a name and positive API version"),OrbGone:f(l.Invalid,u.OrbGone,"Invalid orb gone"),OrbInstalled:f(l.Invalid,u.OrbInstalled,"Use reload to replace an installed orb"),Factory:f(l.Invalid,u.Factory,"Invalid factory"),FactoryExpired:f(l.Invalid,u.FactoryExpired,"Declarations must be synchronous"),Hook:f(l.Invalid,u.Hook,"Hooks need a run function"),HookDependency:f(l.Invalid,u.HookDependency,"Invalid hook dependency"),HooksDisabled:f(l.Invalid,u.HooksDisabled,"Invalid hooks disabled"),JsonAccessor:f(l.Invalid,u.JsonAccessor,"Invalid json accessor"),JsonCycle:f(l.Invalid,u.JsonCycle,"Invalid json cycle"),JsonNumber:f(l.Invalid,u.JsonNumber,"Use BigInt for integers outside the safe Number range"),JsonSymbol:f(l.Invalid,u.JsonSymbol,"Invalid json symbol"),JsonTag:f(l.Invalid,u.JsonTag,"Unknown or malformed portable type tag"),JsonType:f(l.Invalid,u.JsonType,"Supply a codec for custom object types"),JsonValue:f(l.Invalid,u.JsonValue,"This JSON codec requires explicit portable values"),Method:f(l.Invalid,u.Method,"Methods must be functions"),NextUsed:f(l.Invalid,u.NextUsed,"Invalid next used"),Priority:f(l.Invalid,u.Priority,"Invalid priority"),Reference:f(l.Invalid,u.Reference,"An issued local reference is required"),Resource:f(l.Invalid,u.Resource,"Invalid resource"),ResourceHost:f(l.Invalid,u.ResourceHost,"Resource dependencies must belong to the same host"),ResourceInFactory:f(l.Invalid,u.ResourceInFactory,"Resources open after declaration"),RpcFrame:f(l.Invalid,u.RpcFrame,"Invalid rpc frame"),RpcOperation:f(l.Invalid,u.RpcOperation,"Invalid rpc operation"),RpcRequest:f(l.Invalid,u.RpcRequest,"Invalid rpc request"),Service:f(l.Invalid,u.Service,"Invalid service"),ServiceGone:f(l.Invalid,u.ServiceGone,"Invalid service gone"),State:f(l.Invalid,u.State,"Service does not expose state"),StateCycle:f(l.Invalid,u.StateCycle,"State cannot contain cycles"),StateValidation:f(l.Invalid,u.StateValidation,"The orb rejected the state candidate"),StateValue:f(l.Invalid,u.StateValue,"State cannot contain accessors"),StateVersion:f(l.Invalid,u.StateVersion,"Invalid state version"),SubscriptionsDisabled:f(l.Invalid,u.SubscriptionsDisabled,"Invalid subscriptions disabled"),SubscriptionSize:f(l.Invalid,u.SubscriptionSize,"A local byte budget requires an explicit sizeOf function"),Task:f(l.Invalid,u.Task,"Invalid task"),Utf8:f(l.Invalid,u.Utf8,"Invalid utf8"),ValueGone:f(l.Invalid,u.ValueGone,"Invalid value gone"),ValuesExhausted:f(l.Invalid,u.ValuesExhausted,"Invalid values exhausted")}),Released:Object.freeze({Reference:f(l.Released,u.Reference,"The reference has been released")}),Unavailable:Object.freeze({Callback:f(l.Unavailable,u.Callback,"A callback failed"),OrbScope:f(l.Unavailable,u.OrbScope,"The orb scope is unavailable"),NotReady:f(l.Unavailable,u.NotReady,"The object is not ready"),Route:f(l.Unavailable,u.Route,"The route is unavailable")}),Unsupported:Object.freeze({EngineEffect:f(l.Unsupported,u.EngineEffect,"The engine effect is not supported by this adapter"),RemoteOpaque:f(l.Unsupported,u.RemoteOpaque,"Opaque resources are local to their language environment"),Telemetry:f(l.Unsupported,u.Telemetry,"Telemetry is disabled in this kernel"),Views:f(l.Unsupported,u.Views,"Reference views are disabled in this kernel")})});var He=new Set(Object.values(l));function Me(e){return typeof e==="object"&&e!==null&&"code"in e&&He.has(e.code)&&"reason"in e&&typeof e.reason==="string"&&"message"in e&&typeof e.message==="string"}class b extends Error{code;reason;constructor(e,t=e.message,n){super(t,n);this.name="TembraError",this.code=e.code,this.reason=e.reason}}function z(e){let t=c.Unavailable.Callback.message;try{if(e instanceof b)return e;if(Me(e))return new b(e,e.message,{cause:e});t=String(e instanceof Error?e.message:e)}catch{}return new b(c.Unavailable.Callback,t,{cause:e})}function h(e,t=e.message){throw new b(e,t)}var B="$tembra";function ce(e,t){if(typeof e==="bigint")return{[B]:[K.Bigint,e.toString()]};if(e instanceof Uint8Array)return{[B]:[K.Bytes,[...e]]};if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber,"Use BigInt for integers outside the safe Number range");return e}if(typeof e!=="object")h(c.Invalid.JsonValue,"This JSON codec requires explicit portable values");if(t.has(e))h(c.Invalid.JsonCycle);let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)h(c.Invalid.JsonType,"Supply a codec for custom object types");t.add(e);try{if(Array.isArray(e))return Array.from(e,(r)=>ce(r,t));let o=Reflect.ownKeys(e).map((r)=>{if(typeof r!=="string")h(c.Invalid.JsonSymbol);let s=Object.getOwnPropertyDescriptor(e,r);if(!Object.hasOwn(s,"value"))h(c.Invalid.JsonAccessor);return[r,ce(s.value,t)]});return Object.hasOwn(e,B)?{[B]:[K.Object,o]}:Object.fromEntries(o)}finally{t.delete(e)}}function ne(e){if(e===null||typeof e!=="object"){if(typeof e==="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber);return e}if(Array.isArray(e))return e.map(ne);if(Object.hasOwn(e,B)){let t=e[B];if(Object.keys(e).length!==1||!Array.isArray(t)||t.length!==2)h(c.Invalid.JsonTag);let[n,o]=t;if(n===K.Bigint&&typeof o==="string"&&/^-?(0|[1-9]\d*)$/.test(o))return BigInt(o);if(n===K.Bytes&&Array.isArray(o)&&o.every((r)=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(o);if(n===K.Object&&Array.isArray(o)){if(!o.every((r)=>Array.isArray(r)&&r.length===2&&typeof r[0]==="string"))h(c.Invalid.JsonTag);return Object.fromEntries(o.map(([r,s])=>[r,ne(s)]))}h(c.Invalid.JsonTag,"Unknown or malformed portable type tag")}return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ne(n)]))}function Ke(e){let t=[];for(let n of e){let o=n.codePointAt(0);if(o>=55296&&o<=57343)o=65533;if(o<128)t.push(o);else if(o<2048)t.push(192|o>>6,128|o&63);else if(o<65536)t.push(224|o>>12,128|o>>6&63,128|o&63);else t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return Uint8Array.from(t)}function Ue(e){let t=[];for(let n=0;n<e.length;){let o=e[n++];if(o<128){t.push(String.fromCharCode(o));continue}let r=o>=194&&o<=223?1:o>=224&&o<=239?2:o>=240&&o<=244?3:-1;if(r<0||n+r>e.length)h(c.Invalid.Utf8);let s=o&127>>r+1;for(let a=0;a<r;a++){let i=e[n++];if((i&192)!==128)h(c.Invalid.Utf8);s=s<<6|i&63}if(s<[0,128,2048,65536][r]||s>1114111||s>=55296&&s<=57343)h(c.Invalid.Utf8);t.push(String.fromCodePoint(s))}return t.join("")}var W=Object.freeze({id:je.Json,serialize:(e)=>Ke(JSON.stringify(ce(e,new WeakSet))),deserialize:(e)=>ne(JSON.parse(Ue(e)))});var P=Object.freeze({Text:"text",Integer:"integer",Boolean:"boolean",Opaque:"opaque"});class U{name;version;kind;constructor(e,t,n){this.name=e;this.version=t;this.kind=n;Object.freeze(this)}static text(e,t=1){return new U(e,t,P.Text)}static integer(e,t=1){return new U(e,t,P.Integer)}static boolean(e,t=1){return new U(e,t,P.Boolean)}static opaque(e,t=1){return new U(e,t,P.Opaque)}source(e,t){if(this.kind!==P.Opaque)return;let n=typeof e==="object"&&e!==null?t.session.contextTokens.get(e):void 0;if(!n||n.root!==t.root)throw TypeError("An owner-issued opaque reference from this host and root is required");return n.source}}function de(e,t,n){let o=e.session.kernel.command(d.ContextValue,{root:e.root,context:n,call:e.invocation?.id,key:t});if(!o)return;if(o.kind!==P.Opaque)return o.value;let r=Object.freeze({opaque:!0});return e.session.contextTokens.set(r,{root:e.root,source:o.source}),r}function Ee(e,t,n){let o=de(e,t,n);if(!o)throw TypeError("The owner did not issue a reference");return o}var Ie=Symbol.for("@syntropika/tembra-sdk/service-identities"),Q=Object.getOwnPropertyDescriptor(globalThis,Ie)?.value;if(Q!==void 0&&!(Q instanceof WeakMap))throw TypeError("The SDK service identity slot must contain a WeakMap");var X=Q instanceof WeakMap?Q:new WeakMap;if(Q===void 0)Object.defineProperty(globalThis,Ie,{value:X});function De(e,t,n){let o=new Map;for(let[r,s,a]of n){let i={orb:e,name:r,apiVersion:t};for(let p of[s,a]){let m=o.get(p)??X.get(p);if(m&&(m.orb!==e||m.name!==r||m.apiVersion!==t))h(c.Invalid.Service,"A service definition must have one orb, name and API version");o.set(p,i)}}for(let[r,s]of o)X.set(r,s)}function Y(e,t={}){if(typeof e==="string")return{name:e,options:t};let n=X.get(e);if(!n)h(c.Invalid.Service,"Declare this service in an orb before acquiring it");if(t.apiVersion!==void 0&&t.apiVersion!==n.apiVersion)h(c.Invalid.Service,"The acquisition API version must match the service declaration");return{name:n.name,options:{...t,apiVersion:n.apiVersion}}}function le(e){if(!e.name||!Number.isInteger(e.apiVersion)||e.apiVersion<=0)h(c.Invalid.Orb,"An orb needs a name and positive API version");let t=Object.fromEntries(Object.entries(e.services??{}).map(([a,i])=>{if(!a||!i.methods||typeof i.methods!=="object")h(c.Invalid.Service);if(i.create&&typeof i.create!=="function")h(c.Invalid.Factory);for(let m of Object.values(i.methods))if(typeof m!=="function")h(c.Invalid.Method,"Methods must be functions");let p={...i,methods:Object.freeze({...i.methods})};return[a,Object.freeze(p)]})),n=Object.fromEntries(Object.entries(e.requires??{}).map(([a,i])=>[a,Object.freeze({...i,...i.methods?{methods:Object.freeze([...i.methods])}:{},...i.hooks?{hooks:Object.freeze([...i.hooks])}:{},...i.services?{services:Object.freeze(Object.fromEntries(Object.entries(i.services).map(([p,m])=>[p,Object.freeze([...m])])))}:{}})])),o=Object.fromEntries(Object.entries(e.hooks??{}).map(([a,i])=>{if(typeof i.run!=="function")h(c.Invalid.Hook,"Hooks need a run function");return[a,Object.freeze({...i,capabilities:Object.freeze([...i.capabilities??[]])})]})),r=Object.fromEntries(Object.entries(e.contributes??{}).map(([a,i])=>[a,Object.freeze(Object.fromEntries(Object.entries(i).map(([p,m])=>[p,typeof m==="function"?m:Object.freeze({...m})])))])),s=Object.freeze({...e,services:Object.freeze(t),requires:Object.freeze(n),hooks:Object.freeze(o),contributes:Object.freeze(r)});return De(e.name,e.apiVersion,Object.entries(e.services??{}).map(([a,i])=>[a,i,t[a]])),s}class pe{allocate;#e=1;#t=new Map;constructor(e){this.allocate=e}put(e){if(this.#e>4294967295)h(c.Invalid.ValuesExhausted);let t=this.allocate?this.allocate():this.#e++;return this.#t.set(t,e),t}get(e){if(!this.#t.has(e))h(c.Invalid.ValueGone);return this.#t.get(e)}drop(e){this.#t.delete(e)}has(e){return this.#t.has(e)}set(e,t){this.#t.set(e,t)}clear(){this.#t.clear()}get size(){return this.#t.size}}var Pe=new WeakSet;function Z(e){let t=new WeakSet;function n(o){if(o===null||typeof o!=="object"){if(["function","symbol"].includes(typeof o))h(c.Invalid.StateValue,"State must contain plain data");return}if(Pe.has(o))return;if(t.has(o))h(c.Invalid.StateCycle,"State cannot contain cycles");let r=Object.getPrototypeOf(o);if(!Array.isArray(o)&&r!==Object.prototype&&r!==null)h(c.Invalid.StateValue,"State requires plain objects and arrays");t.add(o);for(let s of Reflect.ownKeys(o)){if(typeof s!=="string")h(c.Invalid.StateValue,"State cannot contain symbol properties");let a=Object.getOwnPropertyDescriptor(o,s);if(!Object.hasOwn(a,"value"))h(c.Invalid.StateValue,"State cannot contain accessors");n(a.value)}t.delete(o),Object.freeze(o),Pe.add(o)}return n(e),e}class oe{compute;report;check;#e;#t=new Set;#n=new Set;#o=!0;#r;#s;#i;constructor(e,t,n,o){this.compute=e;this.report=n;this.check=o;this.#e=Z(e(t))}get value(){return this.check(),this.#e}track(e,t){this.#r=e,this.#i=t;let n=new WeakRef(this);this.#s=()=>n.deref()?.detach(),e?.add(this.#s)}detach(){if(!this.#o)return;if(this.#o=!1,this.#s)this.#r?.delete(this.#s);this.#i?.(),this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}prepare(e){if(!this.#o)return;try{this.check()}catch{this.detach();return}let t;try{t=Z(this.compute(e))}catch(o){this.detach(),this.report(o);return}if(!this.#o)return;let n=[];if(!Object.is(t,this.#e))for(let o of this.#n){let s=o.deref()?.prepare(t);if(s)n.push(s);else this.#n.delete(o)}return{adopt:()=>{if(!this.#o||Object.is(t,this.#e))return()=>{};this.#e=t;let o=n.map((s)=>s.adopt()),r=[...this.#t];return()=>{if(!this.#o)return;for(let s of o)s();for(let s of r)try{s(t)}catch(a){this.report(a)}}}}}select(e){this.check();let t=new oe(e,this.#e,this.report,this.check);this.check();let n=new WeakRef(t);return this.#n.add(n),t.track(this.#r,()=>this.#n.delete(n)),t}subscribe(e){this.check(),this.#t.add(e);try{e(this.#e)}catch(t){this.report(t)}return()=>{this.#t.delete(e)}}}class L{backend;object;closed=!1;#e;#t=new Set;#n=new Set;constructor(e,t,n){this.backend=e;this.object=t;this.#e=arguments.length>=3?n:e.value(e.snapshot(t).value)}check(){if(this.closed)throw new b(c.Gone.State,"State owner is gone")}get value(){return this.check(),this.#e}view(e,t=()=>this.check()){let n=this;return{get value(){return t(),n.value},update(o,r){t(),n.backend.check(o,n.object);let s=n.backend.snapshot(n.object),a=n.backend.value(s.value),i=r(a);if(F(i,e),n.backend.check(o,n.object),Object.is(i,a))return a;let p=n.prepare(i);n.backend.adopt(n.object,o,s.revision,i);let m=n.adopt(p,i);return n.backend.publish(m),i},select:(o)=>(t(),n.select(o,t)),subscribe:(o)=>(t(),n.subscribe(o))}}select(e,t=()=>this.check(),n){t();let o=new oe(e,this.value,(s)=>this.backend.report(s),t);t();let r=new WeakRef(o);return this.#n.add(r),o.track(n,()=>this.#n.delete(r)),o}subscribe(e){this.check(),this.#t.add(e);try{e(this.value)}catch(t){this.backend.report(t)}return()=>{this.#t.delete(e)}}prepare(e){let t=[];for(let n of this.#n){let r=n.deref()?.prepare(e);if(r)t.push(r);else this.#n.delete(n)}return t}adopt(e,t){this.#e=t;let n=e.map((r)=>r.adopt()),o=[...this.#t];return()=>{for(let r of n)r();for(let r of o)try{r(t)}catch(s){this.backend.report(s)}}}close(){this.closed=!0,this.#e=void 0,this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}}function F(e,t){if(e&&typeof e.then==="function")h(c.Invalid.AsyncState,"State updates and migrations must be synchronous");let n=Z(e),o=t.validate?.(n);if(o!==void 0&&o!==!0)h(c.Invalid.StateValidation,"Orb rejected the candidate state");return n}class H{session;environment;constructor(e,t){this.session=e;this.environment=t}check(){if(this.environment.phase!==S.Declaring)h(c.Invalid.FactoryExpired,"Declarations must be synchronous")}get principal(){return this.session.principalFor(this.environment.object?.id??0)}get orb(){return this.environment.orb.scope?.value}get key(){return this.environment.object?.address.key??["main"]}state(e,t={}){this.check();let n=this.environment,o=n.object;if(!o||n.state)h(c.Invalid.State,"An object declares exactly one state");let r=t.version??1;if(!Number.isInteger(r)||r<=0)h(c.Invalid.StateVersion);let s=o.binding;if(!s&&o.live)s=new L(this.session,o.id,F(e,t));if(!s){let i=F(e,t),p=this.session.values.put(i);try{this.session.kernel.command(d.StateInit,{object:o.id,value:p,version:r})}catch(m){throw this.session.values.drop(p),m}o.binding=s=new L(this.session,o.id)}let a=s.view(t);return n.state={initial:e,options:t,binding:s},a}get(e,t,n={}){this.check();let o=Y(e,n),r=this.session.scopes.requirement(this.environment,o.name),s=r.service;if(typeof e!=="string"&&s!==o.name)h(c.Invalid.Service,"A typed dependency must resolve its declared service name");if(!this.environment.object&&this.environment.orb.definition.services?.[s])h(c.Invalid.DependencyCycle);let a=Y(e,{...n,...r.apiVersion?{apiVersion:r.apiVersion}:{},...r.methods?{methods:r.methods}:{},principal:n.principal??this.principal}),i=JSON.stringify([s,t,n.principal??this.principal]),p=this.environment.dependencies.get(i);if(p)return p;let m=this.session.handles.hold(s,t,a.options);if(this.environment.object)try{this.session.kernel.command(d.Dependency,{object:this.environment.object.id,reference:this.session.handles.reference(m).id})}catch(y){throw m.release(),y}return this.environment.dependencies.set(i,m),m}resource(e,t){if(this.check(),!t)return this.session.scopes.hostResource(e);if(this.environment.resources.has(e))h(c.Invalid.DuplicateResource,e);let n=this.session.resources.declare(this.environment,e,t);return this.environment.resources.set(e,n),n.handle}task(e){if(this.check(),typeof e!=="function")h(c.Invalid.Task);this.environment.tasks.push({start:e})}on(e,t,n,o={}){if(this.check(),!this.session.kernel.features.subscriptions)h(c.Invalid.SubscriptionsDisabled);if(o.maxBytes!==void 0&&!o.sizeOf)h(c.Invalid.SubscriptionSize,"A local byte budget requires an explicit sizeOf function");if(!e||this.environment.listeners.some((r)=>r.name===e))h(c.Invalid.DuplicateListener,e);this.environment.listeners.push({name:e,source:t,handle:n,options:o})}hook(e){if(this.check(),!this.session.kernel.features.hooks)h(c.Invalid.HooksDisabled);if(!this.environment.orb.definition.hooks?.[e])h(c.Invalid.Hook,e);let t=this.session.kernel.command(d.Allocate);return{run:(n,o)=>this.session.orbs.runHook(this.environment,e,n,o),observe:(n,o)=>this.session.orbs.observe(this.environment,e,t,n,o)}}}function Ae(e,t,n){return{get value(){return t(),e.value},select(o){return t(),e.select(o,t,n)},subscribe(o){t();let r=e.subscribe((i)=>{try{t()}catch{return}o(i)}),s=!0,a=()=>{if(!s)return;s=!1,n.delete(a),r()};n.add(a);try{t()}catch{a()}return a}}}class ue{port;features;constructor(e){this.port=e;this.features=this.command(d.Features)}command(e,t={}){let n=JSON.parse(this.port.request(JSON.stringify({...t,op:e})));if(n.error)throw new b(n.error);return n.ok}}class fe{capacity;sampleEvery;#e=[];#t=0;constructor(e=256,t=1){this.capacity=e;this.sampleEvery=t;if(!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<=0)throw RangeError("Invalid telemetry limits")}sample(){return this.#t++%this.sampleEvery===0}record(e){if(this.#e.length===this.capacity)this.#e.shift();this.#e.push(e)}drain(){return this.#e.splice(0)}}class me{session;tasks=new Map;listeners=new Map;#e=new WeakMap;constructor(e){this.session=e}prepare(e,t){for(let n of e.listeners){let o=typeof n.source==="function"?n.source():n.source;if(!o||typeof o.subscribe!=="function")h(c.Invalid.EventSource);let r=this.session.kernel.command(d.Listen,{scope:e.id,previous:t?.id,name:n.name,source:this.identity(o),sizing:n.options.sizeOf?this.identity(n.options.sizeOf):0,operation:this.session.kernel.command(d.Allocate),maxPending:n.options.maxPending??64,...n.options.maxBytes?{maxBytes:n.options.maxBytes}:{},coalesce:"select"in o}),s=this.listeners.get(r);if(s){n.running=s;continue}let a={id:r,definition:n,environment:e,stopped:!1,detach(){}};n.running=a,this.listeners.set(r,a);try{if(a.detach=o.subscribe((i)=>{if(a.stopped)return;let p=this.session.values.put(i);try{let m=n.options.sizeOf?.(i)??0;if(!Number.isSafeInteger(m)||m<0||m>4294967295)throw new b(c.Invalid.SubscriptionSize);this.session.kernel.command(d.Enqueue,{subscription:r,payload:p,bytes:m})}catch(m){this.session.values.drop(p),this.session.report(m),this.failed(r)}this.session.lifecycle.flush()}),a.stopped)a.detach()}catch(i){throw this.stopListener(a),i}}}start(e){e.phase=S.Live;for(let t of e.listeners){let n=t.running;n.environment=e,n.definition=t}for(let t of e.tasks)this.startTask(e,t)}startTask(e,t){if(t.running||e.phase!==S.Live||this.session.closing)return;let n=this.session.kernel.command(d.Task,{owner:e.owner}),o=new AbortController,r=this.session.kernel.command(d.Allocate),s={id:n,controller:o,done:Promise.resolve()};t.running=s,this.tasks.set(n,s),s.done=this.session.track(Promise.resolve().then(async()=>{try{await t.start({signal:o.signal,root:(a)=>{let i=this.session.kernel.command(d.TaskRoot,{task:n,principal:this.session.principalFor(e.object?.id??0)});return this.session.calls.root(()=>this.session.calls.owned(e,r,a,i),!1,i)}})}catch(a){if(!o.signal.aborted)this.session.report(a)}finally{this.session.kernel.command(d.Tick,{now:this.session.now()}),this.session.kernel.command(d.FinishTask,{task:n}),this.tasks.delete(n),delete t.running,this.session.lifecycle.flush()}}))}identity(e){let t=this.#e.get(e);if(t===void 0)t=this.session.kernel.command(d.Allocate),this.#e.set(e,t);return t}deliver(e,t,n){let o=this.listeners.get(e),r=Promise.resolve().then(async()=>{try{if(!o)throw new b(c.Gone.ListenerCallback);await this.session.calls.owned(o.environment,n,(s)=>o.definition.handle(s,this.session.values.get(t)))}catch(s){this.session.report(s)}finally{this.session.kernel.command(d.FinishDelivery,{subscription:e}),this.session.lifecycle.flush()}});if(o)o.done=r;this.session.track(r)}detach(e){let t=this.listeners.get(e);if(t)this.stopListener(t)}cancel(e){this.tasks.get(e)?.controller.abort(new b(c.Cancelled.Task))}failed(e){let t=this.listeners.get(e);if(!t)return;this.session.report(new b(c.Exhausted.SubscriptionQueue)),this.stopListener(t)}stopListener(e){if(e.stopped)return;e.stopped=!0;try{e.detach()}catch(t){this.session.report(t)}this.session.kernel.command(d.Unsubscribe,{subscription:e.id}),this.listeners.delete(e.id),this.session.lifecycle.flush()}async stop(e){for(let t of e.tasks)if(t.running)this.session.kernel.command(d.StopTask,{task:t.running.id});this.session.lifecycle.flush(),await Promise.all(e.tasks.map((t)=>t.running?.done)),await Promise.all(e.listeners.map((t)=>t.running?.done))}}var re=new WeakMap;class A{session;root;invocation;frame;constructor(e,t,n,o=0){this.session=e;this.root=t;this.invocation=n;this.frame=o;re.set(this,this)}with(e,t){let n=e.source(t,this),o=this.session.kernel.command(d.ContextDerive,{root:this.root,context:this.frame,call:this.invocation?.id,key:e,...e.kind===P.Opaque?{source:n}:{value:t}});return new A(this.session,this.root,this.invocation,o)}value(e){return de(this,e,this.frame)}exportValues(e){let t={};for(let n of e){if(n.kind===P.Opaque)throw TypeError("Local opaque references cannot be exported");let o=this.value(n);if(o!==void 0)t[`${n.name}@${n.version}`]=o}return t}get principal(){return this.session.kernel.command(d.RootPrincipal,{root:this.root})}get signal(){return this.session.calls.signal(this.root)}check(){this.session.kernel.command(d.CheckContext,{root:this.root,call:this.invocation?.id})}cancel(){this.session.kernel.command(d.CancelRoot,{root:this.root}),this.session.lifecycle.flush()}get(e,t,n={}){return this.check(),this.session.handles.get(e,t,n,this)}resource(e){return this.check(),this.session.scopes.hostResource(e)}}function he(e,t){if(typeof e!=="object"||e===null||re.get(e)?.session!==t)throw new b(c.Forbidden.Context,"An issued context from this host is required");return re.get(e)}function V(e,t){let n=he(e,t);return n.check(),n}function _e(e){return typeof e==="object"&&e!==null&&re.has(e)}class be{session;constructor(e){this.session=e}signal(e){let t=this.session,n=t.controllers.get(e);if(!n){n=new AbortController;try{t.kernel.command(d.CheckRoot,{root:e})}catch(o){if(!(o instanceof b)||o.code!==l.Cancelled)throw o;n.abort(o)}t.controllers.set(e,n)}return n.signal}releaseRoot(e){for(let t of this.session.rootReferences.get(e)??[])this.session.handles.release(t);this.session.rootReferences.delete(e),this.session.controllers.delete(e)}async root(e,t=!1,n,o=this.session.principal){let r=this.session,s=n??r.kernel.command(t?d.CleanupRoot:d.Root,{principal:o}),a=new A(r,s);try{return await e(a)}finally{if(this.releaseRoot(s),r.options.native?.rootEnded?.(s),!r.lifecycle.closedDiagnostics)r.kernel.command(d.EndRoot,{root:s});r.controllers.delete(s),r.lifecycle.flush()}}async invoke(e,t,n,o){let r=this.session;if(V(o,r),e.released)throw new b(c.Released.Reference);await e.ready;let s=r.options.native?.admit?.(e.id,t,o),a;if(s)a=s.call;else o.check(),a=r.kernel.command(d.BeginCall,{reference:e.id,root:o.root,context:o.frame||void 0,method:t});let i=new A(r,o.root,a,o.frame),p=r.track((async()=>{let m=r.telemetry?.sample(),y=m?r.now():0,v=ae.Ok;try{let g=r.options.native;if(g&&(s?.native??g.hasOrb(a.orb)))return await g.invoke(a,n,i);let R=r.objects.get(a.object)?.versions.get(a.orb),x=R?.orb.definition.services?.[e.address.service]?.methods[t];if(!R||!x)throw new b(c.Gone.Implementation);return await x(R.value,i,...n)}catch(g){throw v=ae.Error,g}finally{if(m)r.telemetry.record({service:e.address.service,method:t,root:a.root,codeVersion:a.codeVersion,duration:r.now()-y,outcome:v});r.lifecycle.finishCall(a.id)}})());return this.observe(p,o.signal)}async owned(e,t,n,o){let r=this.session,s=async(a)=>{let i=r.kernel.command(d.BeginOperation,{orb:e.orb.info.id,root:a.root,context:a.frame||void 0,operation:t,...e.object?{object:e.object.id}:{}});try{return await n(new A(r,a.root,i,a.frame))}finally{r.kernel.command(d.FinishCall,{call:i.id}),r.lifecycle.flush()}};return o===void 0?this.root(s,!1,void 0,r.principalFor(e.object?.id??0)):s(typeof o==="number"?new A(r,o):o)}async observe(e,t){if(t.aborted)throw t.reason;let n,o=new Promise((r,s)=>{n=()=>s(t.reason??new b(c.Cancelled.Root)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,o])}finally{t.removeEventListener("abort",n)}}}class ve{session;records=new Map;operations=new Map;#e=new Map;#t=new Map;constructor(e){this.session=e}declarations(e){let t=e.map((s)=>le(s)),n=this.session.kernel.command(d.Orbs),o=(s)=>t.find((a)=>a.name===s),r=t.map((s)=>{if(!this.session.kernel.features.views&&Object.values(s.services??{}).some((i)=>i.access))throw new b(c.Unsupported.Views);let a=Object.entries(s.requires??{}).map(([i,p])=>{let m=p.orb??i,y=o(m),v=n.find((R)=>R.name===m),g=y?Object.keys(y.services??{}):v?.services.map((R)=>R.name)??[],k=g.includes(i)?i:g.length===1?g[0]:void 0;if(p.methods&&!k)h(c.Invalid.DependencyService,`Use explicit services for ${m}`);return{orb:m,apiVersion:p.apiVersion,services:p.services??(p.methods?{[k]:p.methods}:{}),hooks:p.hooks??[]}});for(let[i,p]of Object.entries(s.contributes??{})){let m=s.requires?.[i];if(!m)h(c.Invalid.HookDependency,i);for(let[y,v]of Object.entries(p)){if(!m.hooks?.includes(y))h(c.Invalid.HookDependency,y);let g=typeof v==="function"?0:v.priority??0;if(!Number.isInteger(g)||g<-2147483648||g>2147483647)h(c.Invalid.Priority)}}return{name:s.name,apiVersion:s.apiVersion,requires:a,hooks:Object.keys(s.hooks??{}),services:Object.entries(s.services??{}).map(([i,p])=>({name:i,methods:Object.keys(p.methods),lifetime:p.lifetime??G.Referenced,linger:p.linger??0}))}});return{definitions:t,metadata:r}}async install(e){let t=this.session.kernel.command(d.Orbs);if(e.some((s)=>t.some((a)=>a.name===s.name)))h(c.Invalid.OrbInstalled,"Use reload to replace an installed orb");let n=this.declarations(e),o=this.session.kernel.command(d.Prepare,{orbs:n.metadata});this.session.kernel.command(d.Commit,{ticket:o.id});let r=o.orbs.map((s)=>({info:s,definition:n.definitions.find((a)=>a.name===s.name)}));for(let s of r)this.records.set(s.info.id,s);for(let s of r)this.registerContributions(s);await Promise.all(r.map((s)=>this.ready(s)));for(let s of r)for(let a of s.info.services.filter((i)=>i.lifetime===G.Host))(await this.session.handles.get(a.name,"main",{principal:"host"})).release();this.session.lifecycle.flush()}scope(e){if(e.scope)return e.scope;let t=this.session.scopes.environment({kind:I.Orb,id:e.info.owner},e);e.scope=t;try{let n=e.definition.create?.(new H(this.session,t))??{};if(n&&typeof n.then==="function")h(c.Invalid.AsyncFactory);t.value=n}finally{t.phase=S.Prepared,this.session.programs.register(t)}return t}ready(e){if(e.scope?.phase===S.Live)return Promise.resolve();let t=this.#e.get(e.info.id);if(!t){t=(async()=>{try{if(await this.session.scopes.readyHostScope(),e.scope?.phase===S.Closed)delete e.scope;let o=this.scope(e);await this.session.programs.activate(o.id)}catch(o){if(e.scope)await this.session.programs.cleanup([e.scope]),delete e.scope;throw o}})(),this.#e.set(e.info.id,t);let n=()=>{if(this.#e.get(e.info.id)===t)this.#e.delete(e.info.id)};t.then(n,n)}return t}registerContributions(e){for(let[t,n]of Object.entries(e.definition.contributes??{})){let r=e.definition.requires[t].orb??t;for(let[s,a]of Object.entries(n)){let i=this.session.kernel.command(d.Allocate),p=JSON.stringify([e.info.name,r,s]);if(!this.#t.has(p))this.#t.set(p,this.session.kernel.command(d.ContributionOrdinal));this.operations.set(i,{orb:e,handler:typeof a==="function"?a:a.handle}),this.session.kernel.command(d.Contribute,{orb:e.info.id,target:r,hook:s,operation:i,priority:typeof a==="function"?0:a.priority??0,ordinal:this.#t.get(p)})}}}async runHook(e,t,n,o){n=V(n,this.session);let r=e.orb.definition.hooks?.[t];if(!r)h(c.Invalid.Hook,t);let a=this.session.kernel.command(d.HookPlan,{root:n.root,target:e.orb.info.name,hook:t}).map((i)=>async(p,m,y)=>this.runContribution(i,p,m,y));return r.run(n,o,a)}async observe(e,t,n,o,r){o=he(o,this.session);let s=e.orb.definition.hooks?.[t];if(!s)h(c.Invalid.Hook,t);if(!o.invocation)throw new b(c.Forbidden.ObservationSource);let a=this.session.kernel.command(d.BeginHookObservation,{source:o.invocation.id,orb:e.orb.info.id,operation:n,...e.object?{object:e.object.id}:{},hook:t});await this.session.track(this.session.calls.root(async()=>{try{let i=new A(this.session,a.invocation.root,a.invocation),p=a.plan.map((m)=>async(y,v,g)=>this.runContribution(m,y,v,g));await s.run(i,r,p)}finally{this.session.lifecycle.finishCall(a.invocation.id)}},!1,a.invocation.root))}async runContribution(e,t,n,o){t=V(t,this.session);let r=this.operations.get(e);if(!r){let a=this.session.options.native;if(a?.hasContribution?.(e)&&a.contribute)return a.contribute(e,t,n);throw new b(c.Gone.Contribution)}let s=r.orb.scope;if(!s)throw new b(c.Unavailable.OrbScope);return this.session.calls.owned(s,e,(a)=>r.handler(a,n,o),t)}retire(e){let t=this.session.kernel.command(d.ScopesForOrb,{orb:e}),n=this.session.programs.cleanupScopes(t);this.session.track(n.then(()=>{for(let[o,r]of this.operations)if(r.orb.info.id===e)this.operations.delete(o);this.records.delete(e),this.#e.delete(e)}),!0)}}class ye{session;constructor(e){this.session=e}get closedDiagnostics(){return this.#r}#e;#t=!1;#n;#o;#r;flush(e){if(this.#t)return;this.#t=!0;try{for(;;){let t=e??this.session.kernel.command(d.Drain);if(e=void 0,!t.length)break;for(let n of t)try{this.action(n)}catch(o){this.session.report(o)}}}finally{this.#t=!1,this.scheduleLinger()}}finishCall(e){let t=this.session;if(!this.#t&&t.options.native?.finish){let n=t.options.native.finish(e,t.now());if(!n.actions.length){this.scheduleLinger(n.deadline);return}this.flush(n.actions);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.FinishCall,{call:e}),this.flush()}action(e){let t=this.session;if(t.options.native?.notify?.(e)&&!(e.type===C.ProgramComplete&&t.programs.pending(e.id)))return;switch(e.type){case C.Execute:case C.CancelEffects:case C.ProgramPrepared:case C.ProgramComplete:t.programs.dispatch(e);break;case C.DropValue:t.values.drop(e.id),t.options.native?.dropValue?.(e.id);break;case C.CancelRoot:t.controllers.get(e.id)?.abort(new b(c.Cancelled.Root));break;case C.CancelTask:t.activities.cancel(e.id);break;case C.Deliver:t.activities.deliver(e.id,e.payload,e.operation);break;case C.DetachSubscription:t.activities.detach(e.id);break;case C.SubscriptionFailed:t.activities.failed(e.id);break;case C.Dispose:t.track(this.dispose(e.id),!0);break;case C.CloseResource:break;case C.RetireOrb:t.handles.retire(e.id),t.orbs.retire(e.id);break;case C.State:{let o=t.objects.get(e.id);if(!o?.binding)break;let r=t.snapshot(e.id);if(!t.values.has(r.value)){let s=t.value(r.value);t.publish(o.binding.adopt(o.binding.prepare(s),s))}break}}}async dispose(e){let t=this.session,n=t.objects.get(e);if(!n){await t.options.native?.dispose(e),t.kernel.command(d.Disposed,{object:e}),this.flush();return}return n.disposing??=(async()=>{let o=[];await n.activation.catch(()=>{});let r=t.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e}});try{await t.programs.cleanupScopes(r)}catch(s){o.push(s)}try{if(t.options.native?.hasOrb(n.orb))await t.options.native.dispose(e)}catch(s){o.push(s)}if(n.binding?.close(),t.kernel.command(d.Disposed,{object:e}),t.objects.delete(e),this.flush(),o.length)throw AggregateError(o,"Object cleanup failed")})(),n.disposing}scheduleLinger(e){let t=this.session;if(t.closing)return;let n=(e===void 0?t.kernel.command(d.NextDeadline):e)??void 0;if(n===this.#o)return;if(this.#n!==void 0)clearTimeout(this.#n);if(this.#n=void 0,this.#o=n,n===void 0)return;this.#n=setTimeout(()=>{if(this.#o!==n)return;this.#n=void 0,this.#o=void 0,t.kernel.command(d.Tick,{now:t.now()}),this.flush()},Math.max(0,n-t.now())),this.#n.unref?.()}diagnostics(){let e=this.session;if(this.#r)return this.#r;return{...e.kernel.command(d.Diagnostics),values:e.values.size,pendingJobs:e.jobs.size}}close(){let e=this.session;return this.#e??=(async()=>{e.closing=!0,clearTimeout(this.#n),this.#n=void 0,this.#o=void 0,e.kernel.command(d.Close),await e.replacements.cancel(),this.flush();for(;;){await e.options.native?.settled?.(),this.flush();let t=[...e.jobs];if(!t.length)break;await Promise.allSettled(t),this.flush()}if(e.kernel.command(d.FinishClose),e.values.clear(),e.handles.clear(),e.orbs.records.clear(),e.scopes.clear(),this.#r=this.diagnostics(),e.kernel.port.free?.(),e.cleanupErrors.length)throw AggregateError(e.cleanupErrors,"Host cleanup failed")})(),this.#e}}function ee(){let e,t,n=new Promise((o,r)=>{e=o,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function Ve(e,t){return e.slice(0,t).replace(/[\uD800-\uDFFF]/gu,"�")}class ge{session;scopes=new Map;#e=new Map;constructor(e){this.session=e}register(e){let t=e.owner.kind===I.Host?void 0:e.object?e.orb.scope:this.session.hostScope;this.session.kernel.command(d.ScopeRegister,{scope:e.id,owner:e.owner,orb:e.orb.info.id,parents:t?[t.id]:[],dependencies:[...e.dependencies.values()].map((n)=>this.session.handles.reference(n).id),resources:[...e.resources.values()].map((n)=>n.id),stateVersion:e.state?.options.version??(e.state?1:void 0),migrate:Boolean(e.state?.options.migrate)})}activate(e){return this.run(this.session.kernel.command(d.ScopeActivate,{scope:e}))}cleanup(e){let t=e.map((n)=>n.id).filter((n)=>this.session.kernel.command(d.ScopeExists,{scope:n}));return this.cleanupScopes(t)}cleanupScopes(e){return e.length?this.run(this.session.kernel.command(d.ScopesCleanup,{scopes:e})):Promise.resolve()}pending(e){return this.#e.has(e)}run(e){let t=this.#e.get(e);if(t)return t.promise;let n=ee();this.#e.set(e,n);try{this.session.kernel.command(d.ProgramRun,{program:e}),this.session.lifecycle.flush()}catch(o){this.#e.delete(e),n.reject(o)}return n.promise}dispatch(e){if(e.type===C.Execute)this.session.track(Promise.allSettled(e.effects.map((t)=>this.execute(t))).then((t)=>{let n=Math.max(0,Math.min(2048,Math.floor((1048448-t.length*96)/(12*t.length)))),o=t.map((r)=>{if(r.status==="fulfilled")return{value:r.value??null};try{let{code:s,reason:a,message:i}=z(r.reason);if(!Object.values(l).includes(s)||typeof a!=="string"||typeof i!=="string")return{error:c.Unavailable.Callback};return{error:{code:s,reason:Ve(a,n),message:Ve(i,n)}}}catch{return{error:c.Unavailable.Callback}}});this.session.kernel.command(d.ProgramCompleteStep,{program:e.id,results:o}),this.session.lifecycle.flush()}));else if(e.type===C.CancelEffects)for(let t of e.effects){if(t.type!==j.Open&&t.type!==j.Restore)continue;let n=this.session.resources.find(t.resource);if(n)n.controller.abort(new b(c.Cancelled.EngineEffect));else if(this.session.options.native?.cancelEffect){let o=this.session.options.native.cancelEffect.bind(this.session.options.native);this.session.track(Promise.resolve().then(()=>o(t))).catch((r)=>this.session.report(r))}}else{let t=this.#e.get(e.id);if(this.#e.delete(e.id),e.error){let n=new b(e.error);if(t)t.reject(n);else this.session.cleanupErrors.push(n),this.session.report(n)}else t?.resolve()}}resource(e){let t=this.session.resources.find(e);if(t)return t;throw new b(c.Gone.Resource)}async execute(e){let t=e.scope===void 0?void 0:this.scopes.get(e.scope);if(e.scope!==void 0&&!t&&this.session.options.native)return this.session.options.native.effect(e);if((e.type===j.Close||e.type===j.Open)&&!this.session.resources.find(e.resource)&&this.session.options.native)return this.session.options.native.effect(e);switch(e.type){case j.Open:await this.resource(e.resource).start();break;case j.Close:await this.session.resources.close(this.resource(e.resource));break;case j.Restore:await this.session.resources.reopen(this.resource(e.previous),e.resource);break;case j.Stop:if(t)await this.session.activities.stop(t);break;case j.Prepare:{if(!t)throw new b(c.Gone.Scope);this.session.activities.prepare(t,e.previous?this.scopes.get(e.previous):void 0);break}case j.Validate:F(this.session.value(e.value),t.state.options);break;case j.Initialize:return this.candidate(t,t.state.initial);case j.Migrate:{let n=t.state;return this.candidate(t,n.options.migrate(this.session.value(e.value),e.version))}case j.Adopt:{let n=new Map;for(let o of e.replacements){if(!o.next)continue;let r=this.scopes.get(o.next);for(let[s,a]of r.resourceDeclarations??[])s.options=a;if(delete r.resourceDeclarations,n.set(r.orb.info.id,r.orb),r.object){if(r.state)r.object.binding=r.state.binding;r.object.orb=r.orb.info.id,r.object.versions.set(r.orb.info.id,r)}}for(let o of n.values())this.session.orbs.records.set(o.info.id,o),this.session.orbs.registerContributions(o);for(let o of e.replacements){let r=o.next?this.scopes.get(o.next):void 0;if(r?.object)this.session.handles.refreshReferences(r.object,r.orb)}for(let o of e.replacements)if(o.next)this.scopes.get(o.next)?.state?.publish?.();break}case j.Start:if(t){if(this.session.activities.start(t),t.object)t.object.live=!0}break;case j.Drop:{if(!t)break;for(let n of t.dependencies.values())this.session.handles.revoke(this.session.handles.reference(n).id);t.dependencies.clear();for(let n of t.resources.values())this.session.resources.closedRecords.delete(n.id);if(t.phase=S.Closed,t.object)t.object.versions.delete(t.orb.info.id);this.scopes.delete(t.id);break}default:throw new b(c.Unsupported.EngineEffect,e.type)}}candidate(e,t){let n=e.state,o=F(t,n.options),r=this.session.values.put(o);return n.publish=()=>this.session.publish(n.binding.adopt(n.binding.prepare(o),o)),r}}var qe=new WeakMap,ke=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry((e)=>e.session.deref()?.handles.release(e.id));class we{session;constructor(e){this.session=e}#e=new Map;#t=new Map;activateAcquired(e,t,n=[]){let o=this.session,r=o.objects.get(e.object);if(!r){let y=ee();r={id:e.object,address:t,orb:e.orb,versions:new Map,activation:y.promise},o.objects.set(r.id,r);let v=r;o.track(o.scopes.activate(v,e).then(y.resolve,(g)=>{v.error=g;try{o.kernel.command(d.Fail,{object:v.id})}catch{}y.reject(g),o.lifecycle.flush()}))}if(!this.claimExists(e.reference))return r.activation;let a=this.orbMetadata(r.orb).services.find((y)=>y.name===t.service)?.methods??[],i={id:e.reference,object:e.object,address:t,methods:new Set(a),requiredMethods:new Set(n),stateCleanups:new Set,ready:r.activation,released:!1,nativeOwned:!0},p=o.orbs.records.get(r.orb)?.definition.services?.[t.service]?.access;try{this.referenceMethods(i,a,p)}catch(y){if(o.kernel.features.views&&this.claimExists(i.id))o.kernel.command(d.Restrict,{reference:i.id,methods:[]});throw y}o.references.set(i.id,i);let m=this.#t.get(i.object);if(!m)this.#t.set(i.object,m=new Set);return m.add(i),r.activation}hold(e,t,n={},o){let r;if(typeof e==="string")r=e;else{let w=Y(e,n);r=w.name,n=w.options}let s=this.session;if(o)V(o,s);s.kernel.command(d.Tick,{now:s.now()});let a={service:r,key:typeof t==="string"?[t]:[...t],principal:n.principal??o?.principal??s.principal},i=s.kernel.command(d.Acquire,{...a,apiVersion:n.apiVersion??0,methods:n.methods??[]}),p=s.objects.get(i.object);if(!p){let w=ee();p={id:i.object,address:a,orb:i.orb,versions:new Map,activation:w.promise},s.objects.set(p.id,p);let T=p;queueMicrotask(()=>{s.track(s.scopes.activate(T,i).then(w.resolve,(M)=>{T.error=M;try{s.kernel.command(d.Fail,{object:T.id})}catch{}w.reject(M),s.lifecycle.flush()}))})}let m=this.orbMetadata(i.orb),y=new Set(m.services.find((w)=>w.name===r)?.methods??[]),v={id:i.reference,object:i.object,address:a,methods:y,requiredMethods:new Set(n.methods??[]),stateCleanups:new Set,ready:p.activation,released:!1,...o?{context:o}:{}},g=s.options.native?.access?.(i.orb,r,a.principal),k=g?()=>({methods:g}):s.orbs.records.get(i.orb)?.definition.services?.[r]?.access;try{this.referenceMethods(v,y,k)}catch(w){throw s.kernel.command(d.Release,{reference:v.id}),s.kernel.command(d.Forget,{reference:v.id}),s.lifecycle.flush(),w}s.references.set(v.id,v);let R=this.#t.get(v.object);if(!R)R=new Set,this.#t.set(v.object,R);if(R.add(v),o){let w=s.rootReferences.get(o.root);if(!w)w=new Set,s.rootReferences.set(o.root,w);w.add(v.id)}let x=()=>{if(v.released)throw new b(c.Released.Reference);if(s.closing)throw new b(c.Gone.Reference);let w=s.objects.get(v.object);if(!w||w.disposing||w.error)throw new b(c.Gone.Reference);if(!w.live)throw new b(c.Unavailable.NotReady)},E={get ready(){return v.ready},get status(){return v.released?_.Released:q.closing?_.Gone:q.kernel.command(d.Status,{reference:v.id})},get state(){x();let w=q.objects.get(v.object)?.binding;if(!w)h(c.Invalid.State,"Service does not expose state");return Ae(w,x,v.stateCleanups)},release:()=>this.release(v.id),opaque:(w)=>{x();let T=s.objects.get(v.object),M=T.versions.get(T.orb)?.resources.get(w);if(!M?.options.opaque)throw new b(c.Forbidden.Opaque,w);return M.handle.value}},q=s,J=new Proxy(E,{get:(w,T,M)=>{if(T==="then")return;if(Object.hasOwn(w,T))return Reflect.get(w,T,M);if(typeof T!=="string")return;if(!v.methods.has(T))return;return(...te)=>{let se=v.context;if(_e(te.at(-1)))se=te.pop();return se?s.calls.invoke(v,T,te,V(se,s)):s.calls.root((Fe)=>s.calls.invoke(v,T,te,Fe),!1,void 0,v.address.principal)}}});return qe.set(J,{session:s,record:v}),ke?.register(J,{session:new WeakRef(s),id:v.id},v),J}async get(e,t,n={},o){let r=this.hold(e,t,n,o);try{return await r.ready,r}catch(s){throw r.release(),s}}reference(e){let t=typeof e==="object"&&e!==null?qe.get(e):void 0;if(!t||t.session!==this.session)h(c.Invalid.Reference,"An issued local reference is required");return t.record}orbMetadata(e){let t=this.session.orbs.records.get(e)?.info;if(t)return t;let n=this.#e.get(e);if(!n)n=this.session.kernel.command(d.Orb,{id:e}),this.#e.set(e,n);return n}referenceMethods(e,t,n,o=!1){let r=this.session;if(n&&!r.kernel.features.views)throw new b(c.Unsupported.Views);let s=n?new Set(n(e.address.principal).methods):void 0,a=new Set([...t].filter((i)=>(!e.requiredMethods.size||e.requiredMethods.has(i))&&(!s||s.has(i))));if(n||o&&r.kernel.features.views)r.kernel.command(d.Restrict,{reference:e.id,methods:[...a]});e.methods=a}refreshReferences(e,t){let n=this.session,o=t.definition.services?.[e.address.service];if(!o)return;let r=Object.keys(o.methods);for(let s of this.#t.get(e.id)??[]){if(s.released)continue;if(s.nativeOwned&&!this.claimExists(s.id)){this.revoke(s.id);continue}try{this.referenceMethods(s,r,o.access,!0)}catch(a){if(s.methods.clear(),!s.released&&n.kernel.features.views)n.kernel.command(d.Restrict,{reference:s.id,methods:[]});n.report(a)}}}claimExists(e){try{let t=this.session.kernel.command(d.Status,{reference:e});return t!==_.Released&&t!==_.Gone}catch(t){if(t instanceof b&&(t.code===l.Gone||t.code===l.Released))return!1;throw t}}forget(e){for(let n of e.stateCleanups)n();e.stateCleanups.clear(),this.session.references.delete(e.id);let t=this.#t.get(e.object);if(t?.delete(e),!t?.size)this.#t.delete(e.object)}release(e){let t=this.session,n=t.references.get(e);if(!n||n.released)return;if(n.released=!0,ke?.unregister(n),t.lifecycle.closedDiagnostics){this.forget(n);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.Release,{reference:e}),t.kernel.command(d.Forget,{reference:e}),this.forget(n),t.lifecycle.flush()}revoke(e){let t=this.session.references.get(e);if(!t)return;t.released=!0,ke?.unregister(t),this.forget(t)}retire(e){this.#e.delete(e)}clear(){for(let e of this.session.references.values())this.forget(e);this.session.references.clear(),this.#t.clear(),this.#e.clear()}}class Re{session;#e;#t;#n;constructor(e){this.session=e}async replace(e,t={},n=[]){return(await this.prepare(e,t,n)).commit()}prepare(e,t={},n=[]){if(this.session.closing)return Promise.reject(new b(c.Closed.Host));if(this.#e)return Promise.reject(new b(c.Conflict.ReloadRunning));let o=this.capture(e,t,n);return this.#e=o,o.catch(()=>{if(this.#e===o)this.#e=void 0}),o}async cancel(){if(this.#n?.status===D.Prepared)return this.#n.abort();if(this.#t!==void 0){this.session.kernel.command(d.ProgramAbort,{program:this.#t});let e=this.session.programs.run(this.#t);this.session.lifecycle.flush(),await e.catch(()=>{})}await this.#e?.catch(()=>{return})}async capture(e,t,n){let o=this.session,r=o.orbs.declarations(e),s=o.kernel.command(d.Prepare,{orbs:r.metadata,remove:n}),a=new Map(r.definitions.map((k)=>[k.name,k])),i=s.orbs.map((k)=>({info:k,definition:a.get(k.name),ticket:s.id})),p=new Map(i.map((k)=>[k.info.id,k])),m;try{for(let k of i)o.orbs.scope(k);for(let k of s.objects){let R=o.objects.get(k);if(!R)continue;let x=s.providers[R.address.service],E=x===void 0?void 0:p.get(x);if(E)o.scopes.createEnvironment(R,E)}for(let k of i)k.ticket=void 0;if(m=o.kernel.command(d.ScopesReloadRegistered,{ticket:s.id,deadline:t.deadline??5000,now:o.now()}),this.#t=m,await o.programs.run(m),o.closing)await o.programs.run(m)}catch(k){if(this.#t=void 0,m===void 0){o.kernel.command(d.Abort,{ticket:s.id});let R=s.orbs.flatMap((x)=>o.kernel.command(d.ScopesForOrb,{orb:x.id}));await o.programs.cleanupScopes(R)}throw k}this.#t=void 0;let y=m,v={codeVersion:s.codeVersion,orbs:i.map((k)=>k.info.name)},g=D.Prepared;return this.#n={report:v,get status(){return g},commit:async()=>{if(g!==D.Prepared)throw new b(c.Conflict.ReloadTicket);this.#n=void 0;try{o.kernel.command(d.ProgramCommit,{program:y})}catch(k){throw o.kernel.command(d.ProgramAbort,{program:y}),await o.programs.run(y).catch(()=>{}),g=D.Aborted,this.#e=void 0,k}return g=D.Committed,this.#e=void 0,await o.programs.run(y),v},abort:async()=>{if(g===D.Aborted)return;if(g!==D.Prepared)throw new b(c.Conflict.AlreadyCommitted);g=D.Aborted,this.#n=void 0,this.#e=void 0,o.kernel.command(d.ProgramAbort,{program:y});try{await o.programs.run(y)}catch(k){if(!(k instanceof b)||k.reason!==u.ReloadAborted)throw k}}}}}var ze=new WeakMap;class Oe{session;records=new Map;closedRecords=new Map;constructor(e){this.session=e}find(e){return this.records.get(e)??this.closedRecords.get(e)}dependencyIds(e){let t=[];for(let n of e.deps??[]){let o=typeof n==="object"&&n!==null?ze.get(n):void 0;if(o){if(o.session!==this.session)h(c.Invalid.ResourceHost,"Resource dependencies must belong to the same host");t.push(o.id)}else this.session.handles.reference(n)}return t}register(e,t,n){return this.session.kernel.command(d.Resource,{owner:e.owner,name:t,version:n.version??1,exclusive:n.exclusive??!1,dependencies:this.dependencyIds(n)}).id}redeclare(e,t){for(let n of t.resources.values())this.records.delete(n.id),this.closedRecords.delete(n.id),n.reset(this.register(e,n.name,n.options)),n.dependencies=this.dependencyIds(n.options),this.records.set(n.id,n),e.resources.set(n.name,n)}declare(e,t,n){if(!t||typeof n.open!=="function")h(c.Invalid.Resource);let o=this.register(e,t,n),r=this.records.get(o);if(r)return(e.resourceDeclarations??=new Map).set(r,n),r;let s=new AbortController,a=Object.freeze({get value(){if(e.phase===S.Declaring)h(c.Invalid.ResourceInFactory,"Resources open after declaration");let p=i.session.kernel.command(d.ResourceValue,{resource:i.id});return i.session.value(p)},version:n.version??1}),i={id:o,name:t,options:n,handle:a,dependencies:this.dependencyIds(n),controller:s,session:this.session,reset:(p)=>{i.id=p,i.controller=new AbortController,delete i.value,delete i.closed,delete i.started},start:()=>(i.started??=(async()=>{let p=i.options,m=await p.open(i.controller.signal),y=this.session.values.put(m);try{this.session.kernel.command(d.ResourceOpened,{resource:i.id,value:y})}catch(v){if(this.session.values.drop(y),p.close)await this.session.calls.root((g)=>p.close(m,g),!0);throw v}i.value=y})(),i.started.catch(()=>{}),i.started)};return ze.set(a,i),this.records.set(o,i),i}async close(e){return e.closed??=(async()=>{e.controller.abort(new b(c.Cancelled.Resource)),await e.started?.catch(()=>{});try{if(e.value!==void 0&&e.options.close){let t=this.session.value(e.value);await this.session.calls.root((n)=>e.options.close(t,n),!0)}}finally{this.session.kernel.command(d.ResourceClosed,{resource:e.id}),this.records.delete(e.id),this.closedRecords.set(e.id,e),this.session.lifecycle.flush()}})(),e.closed}async reopen(e,t){this.closedRecords.delete(e.id),e.reset(t),this.records.set(t,e),await e.start()}}class Se{session;constructor(e){this.session=e}#e=new Map;#t=new Set;#n;environment(e,t,n){let o={id:this.session.kernel.command(d.Allocate),owner:e,orb:t,...n?{object:n}:{},phase:S.Declaring,value:{},dependencies:new Map,resources:new Map,tasks:[],listeners:[]};return this.session.programs.scopes.set(o.id,o),o}async activate(e,t){let n=this.session;if(n.options.native?.hasOrb(t.orb)){await n.options.native.activate(e.id,t.orb,e.address.service,e.address.key,e.address.principal);let o=n.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e.id}});await Promise.all(o.map((r)=>n.programs.activate(r)));try{n.snapshot(e.id),e.binding=new L(n,e.id)}catch{}}else{let o=n.orbs.records.get(t.orb);if(!o)h(c.Invalid.OrbGone);await n.orbs.ready(o);let r=this.createEnvironment(e,o);e.versions.set(o.info.id,r),await this.session.programs.activate(r.id)}if(n.kernel.command(d.Status,{reference:t.reference})===_.Loading)n.kernel.command(d.Ready,{object:e.id});e.live=!0,n.lifecycle.flush()}createEnvironment(e,t){let n=t.definition.services?.[e.address.service];if(!n)h(c.Invalid.ServiceGone);let o=this.environment({kind:I.Object,id:e.id},t,e);try{let r=n.create?.(new H(this.session,o))??{};if(r&&typeof r.then==="function")h(c.Invalid.AsyncFactory,"Factories must be synchronous");return o.value=r,o}finally{o.phase=S.Prepared,this.session.programs.register(o)}}readyHostScope(){let e=this.session;if(e.closing)return Promise.reject(new b(c.Closed.Host));if(this.#n)return this.#n;let t=(async()=>{if(e.hostScope.phase===S.Closed)e.hostScope=await this.redeclareHostScope(e.hostScope);await this.session.programs.activate(e.hostScope.id);while(this.#t.size){let o=this.#t.values().next().value;if(o.phase===S.Closed||[...o.resources.values()].some((r)=>e.resources.dependencyIds(r.options).some((s,a)=>s!==r.dependencies[a]))){let r=o;o=await this.redeclareHostScope(r),this.#t.delete(r),this.#t.add(o)}await this.session.programs.activate(o.id),this.#t.delete(o)}})();this.#n=t;let n=()=>{if(this.#n===t)this.#n=void 0};return t.then(n,n),t}async redeclareHostScope(e){let t=this.session;await t.programs.cleanup([e]);let n=this.environment({kind:I.Host},e.orb);return t.resources.redeclare(n,e),n.phase=S.Prepared,t.programs.register(n),n}requirement(e,t){if(e.orb.definition.services?.[t])return{service:t,apiVersion:e.orb.info.apiVersion};for(let[o,r]of Object.entries(e.orb.definition.requires??{})){let s;try{s=this.session.kernel.command(d.OrbNamed,{name:r.orb??o,ticket:e.orb.ticket})}catch(p){if(p instanceof b&&p.code===l.Gone&&p.reason===u.Orb)continue;throw p}let a=o===t?s.services.find((p)=>p.name===o)??(s.services.length===1?s.services[0]:void 0):s.services.find((p)=>p.name===t);if(!a)continue;let i=r.services?.[a.name]??r.methods;if(!i)throw new b(c.Forbidden.UndeclaredService,t);return{service:a.name,apiVersion:r.apiVersion,methods:i}}throw new b(c.Forbidden.UndeclaredDependency,t)}hostResource(e){let t=this.#e.get(e);if(!t)throw new b(c.Forbidden.HostResource,e);return t.handle}resource(e,t){let n=this.session;if(n.closing)throw new b(c.Closed.Host);if(this.#e.has(e))h(c.Invalid.DuplicateResource);let o=this.environment({kind:I.Host},n.hostScope.orb);try{let r=new H(n,o).resource(e,t);return this.#e.set(e,o.resources.get(e)),o.phase=S.Prepared,n.programs.register(o),this.#t.add(o),n.track(this.readyHostScope()).catch((s)=>n.report(s)),r}catch(r){throw n.programs.scopes.delete(o.id),r}}registerHost(e){for(let[t,n]of e.resources)this.#e.set(t,n)}clear(){this.#e.clear(),this.#t.clear()}}class xe{options;contextTokens=new WeakMap;calls=new be(this);handles=new we(this);scopes=new Se(this);lifecycle=new ye(this);kernel;values;resources=new Oe(this);activities=new me(this);orbs=new ve(this);replacements=new Re(this);programs=new ge(this);objects=new Map;references=new Map;rootReferences=new Map;controllers=new Map;jobs=new Set;cleanupErrors=[];hostScope;codec;name;principal;errors=[];now;telemetry;closing=!1;#e=!1;#t=[];constructor(e){this.options=e;if(this.kernel=new ue(e.kernel),e.telemetry&&!this.kernel.features.telemetry)throw new b(c.Unsupported.Telemetry);this.telemetry=e.telemetry?new fe(e.telemetry.capacity,e.telemetry.sampleEvery):void 0,this.values=new pe(()=>this.kernel.command(d.Allocate)),this.codec=e.serialization??W,this.name=e.name??"host",this.principal=e.principal??"host";let t=e.now??(()=>performance.now()),n=e.clockOrigin??t();this.now=()=>Math.floor(t()-n);let o={info:{id:0,owner:0,name:"$host",apiVersion:1,codeVersion:1,services:[],hooks:[],requires:[]},definition:{name:"$host",apiVersion:1}};this.hostScope=this.scopes.environment({kind:I.Host},o);for(let[r,s]of Object.entries(e.resources??{}))new H(this,this.hostScope).resource(r,s);this.scopes.registerHost(this.hostScope),this.hostScope.phase=S.Prepared,this.programs.register(this.hostScope)}principalFor(e){return this.objects.get(e)?.address.principal??this.principal}snapshot(e){return this.kernel.command(d.Snapshot,{object:e})}value(e){if(this.values.has(e))return this.values.get(e);if(!this.options.native)h(c.Invalid.ValueGone);let t=this.options.native.value(e);return this.values.set(e,t),t}check(e,t){let n=V(e,this);if(!n.invocation||n.invocation.object!==t)throw new b(c.Forbidden.StateOwner);return n.invocation}adopt(e,t,n,o){let r=this.check(t,e),s=this.values.put(o);try{return this.kernel.command(d.StateAdopt,{call:r.id,object:e,revision:n,value:s})}catch(a){throw this.values.drop(s),a}finally{this.lifecycle.flush()}}publish(e){if(this.#t.push(e),this.#e)return;this.#e=!0;try{while(this.#t.length)this.#t.shift()()}finally{this.#e=!1}}report(e){let t=z(e);if(this.errors.length===64)this.errors.shift();this.errors.push(t);try{this.options.onError?.(t)}catch{}}track(e,t=!1){return this.jobs.add(e),e.then(()=>{this.jobs.delete(e)},(n)=>{if(this.jobs.delete(e),t)this.cleanupErrors.push(n),this.report(n)}),e}}class Ce{session;constructor(e){this.session=new xe(e)}get name(){return this.session.name}get features(){return this.session.kernel.features}install(e){return this.session.orbs.install(Array.isArray(e)?e:[e])}async load(e){if(!this.session.options.load)throw Error("This host has no module loader");await this.install(await this.session.options.load(e))}reload(e,t){return this.session.replacements.replace(e,t)}prepare(e,t){return this.session.replacements.prepare(e,t)}remove(e,t){return this.session.replacements.replace([],t,e)}hold(e,t,n){return this.session.handles.hold(e,t,n)}get(e,t,n){return this.session.handles.get(e,t,n)}root(e,t={}){return this.session.calls.root(e,!1,void 0,t.principal)}resource(e,t){return this.session.scopes.resource(e,t)}diagnostics(){return this.session.lifecycle.diagnostics()}errors(){return this.session.errors.splice(0)}traces(){return this.session.telemetry?.drain()??[]}installedOrbs(){return this.session.kernel.command(d.Orbs).map((e)=>{let t=this.session.orbs.records.get(e.id)?.definition,n=Object.freeze({...e,hookCapabilities:Object.fromEntries(e.hooks.map((o)=>[o,t?.hooks?.[o]?.capabilities??[]]))});return Object.freeze({...e,describe:()=>n})})}close(){return this.session.lifecycle.close()}}var O=Deno.core.ops,N=globalThis;N.queueMicrotask??=(e)=>Promise.resolve().then(e);N.performance??={now:()=>O.op_tembra_now()};N.AbortController??=class{signal={aborted:!1,reason:void 0,listeners:new Set,addEventListener(e,t){this.listeners.add(t)},removeEventListener(e,t){this.listeners.delete(t)},throwIfAborted(){if(this.aborted)throw this.reason}};abort(e=Error("Aborted")){if(this.signal.aborted)return;this.signal.aborted=!0,this.signal.reason=e;for(let t of[...this.signal.listeners])t();this.signal.listeners.clear()}};var Le=0,Te=new Set;N.setTimeout??=(e,t=0,...n)=>{let o=++Le;return Te.add(o),O.op_tembra_sleep(o,Math.max(0,Math.min(2147483647,t))).then(()=>{if(Te.delete(o))e(...n)}),o};N.clearTimeout??=(e)=>{if(Te.delete(e))O.op_tembra_clear_timer(e)};function Ne(e={}){let t=e.serialization??W;if(t.id!==O.op_tembra_codec())throw new b(c.Conflict.Codec,"The Rust and JS host codecs must agree");function n(i){let p=t.deserialize(i);if(p.error)throw new b(p.error);return p.ok}let o=O.op_tembra_driver_enabled?.()??!1,r=new Map;N.__tembraDeliver=(i)=>{for(let[p,m,y]of i){let v=r.get(p);if(!v)throw Error("unknown native completion");r.delete(p);try{if(!y)throw Error(m);v.resolve(n(m))}catch(g){v.reject(g)}}};function s(i,p){let m=O.op_tembra_submit(i,p);return new Promise((y,v)=>r.set(m,{resolve:y,reject:v}))}let a=new Ce({...e,clockOrigin:0,kernel:{request:(i)=>O.op_tembra_kernel(i)},native:{...o?{admit:(i,p,m)=>{let y=JSON.parse(O.op_tembra_admit(JSON.stringify({reference:i,method:p,root:m.root,context:m.frame,parent:m.invocation?.id})));if(y.error)throw new b(y.error);return y.ok},finish:(i,p)=>{let m=JSON.parse(O.op_tembra_finish(i,String(p)));if(m.error)throw new b(m.error);return m.ok}}:{},rootEnded:(i)=>O.op_tembra_end_context(i),access:(i,p,m)=>JSON.parse(O.op_tembra_access(i,p,m))??void 0,settled:()=>O.op_tembra_settled(),notify:(i)=>O.op_tembra_notify(JSON.stringify(i)),hasContribution:(i)=>O.op_tembra_has_contribution?.(i)??!1,contribute:async(i,p,m)=>n(await O.op_tembra_native("contribute",t.serialize({operation:i,root:p.root,frame:p.frame,...m===void 0?{}:{input:m}}))).value,hasOrb:(i)=>O.op_tembra_has_orb(i),activate:async(i,p,m)=>{n(await O.op_tembra_native("activate",t.serialize({object:i,orb:p,service:m})))},invoke:async(i,p)=>o?s("invoke",t.serialize({invocation:i,arguments:p})):n(await O.op_tembra_native("invoke",t.serialize({invocation:i,arguments:p}))),dispose:async(i)=>{n(await O.op_tembra_native("dispose",t.serialize({object:i})))},effect:async(i)=>n(await O.op_tembra_native("effect",t.serialize(i))),cancelEffect:async(i)=>{n(await O.op_tembra_native("cancel-effect",t.serialize(i)))},value:(i)=>n(O.op_tembra_value(i)),dropValue:(i)=>O.op_tembra_drop_value(i)}});if(O.op_tembra_callback_next)(async()=>{for(;;){let i=O.op_tembra_callback_next();Deno.core.unrefOpPromise(i);let p=await i;if(!p.length)return;let m=new DataView(p.buffer,p.byteOffset,9),y=m.getUint8(0),v=m.getUint32(1,!0)+m.getUint32(5,!0)*4294967296;if(y!==0){if(y===2)a.session.calls.releaseRoot(v);if(y===3)a.session.handles.revoke(v);a.session.lifecycle.flush();continue}let g;try{g=t.deserialize(p.subarray(9))}catch(k){let{code:R,reason:x,message:E}=z(k);O.op_tembra_callback_error(v,JSON.stringify({code:R,reason:x,message:E}),!0);continue}a.session.track((async()=>{let k;try{let R;if(g.kind==="activate")await a.session.handles.activateAcquired(g.acquired,g.address,g.methods),R=null;else{let x=g.call,E=a.session.kernel.command(d.Invocation,{call:x}),q=new A(a.session,E.root,E,g.frame);if(g.kind==="invoke"){let J=a.session.objects.get(E.object),w=J?.versions.get(E.orb),T=w?.orb.definition.services?.[J.address.service]?.methods[E.method];if(!T||!w)throw new b(c.Gone.Implementation);R=await T(w.value,q,...g.input)}else R=await a.session.orbs.runContribution(g.operation,q,g.input)}k=R===void 0?{}:{value:R}}catch(R){let x=z(R);k={error:{code:x.code,reason:x.reason,message:x.message}}}try{O.op_tembra_callback_complete(v,t.serialize(k))}catch(R){let{code:x,reason:E,message:q}=z(R);O.op_tembra_callback_error(v,JSON.stringify({code:x,reason:E,message:q}),!1)}})(),!0)}})();return a}N.Tembra=Object.freeze({ContextKey:U,ContextKind:P,opaqueFrom:Ee,createHost:Ne,jsonCodec:W,Code:l,Reason:u,Lifetime:G,Status:_,ReloadStatus:D,HookCapability:ie,Errors:c});})();
|