@syntropika/tembra-sdk 0.2.2 → 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 -3332
- 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 -3310
- 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 -3321
- 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 +7 -6
- 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 +213 -90
- 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 -301
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public browser filesystem provider API. The implementation lives in private modules:
|
|
3
|
+
* `filesystem/contract.ts` (types and errors), `filesystem/scope.ts` (rights, lifetime and path
|
|
4
|
+
* confinement), `filesystem/memory.ts` and `filesystem/opfs.ts` (storage backends).
|
|
5
|
+
*/
|
|
6
|
+
export {
|
|
7
|
+
type Descriptor,
|
|
8
|
+
type DirectoryDescriptor,
|
|
9
|
+
type DirectoryEntry,
|
|
10
|
+
type EntryType,
|
|
11
|
+
type FileDescriptor,
|
|
12
|
+
type FileStat,
|
|
13
|
+
FilesystemError,
|
|
14
|
+
type FilesystemErrorCode,
|
|
15
|
+
type FilesystemProvider,
|
|
16
|
+
type MountedFilesystem,
|
|
17
|
+
type OpenOptions,
|
|
18
|
+
} from "./filesystem/contract.ts";
|
|
19
|
+
export { memoryFilesystem } from "./filesystem/memory.ts";
|
|
20
|
+
export { opfsFilesystem } from "./filesystem/opfs.ts";
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Serialize one VM while allowing independent VMs and host callbacks to make progress. */
|
|
2
|
+
export class Gate {
|
|
3
|
+
#busy = false;
|
|
4
|
+
#queue: (() => void)[] = [];
|
|
5
|
+
|
|
6
|
+
/** Ordinary contention waits for ownership; only factories need a bounded causal admission wait. */
|
|
7
|
+
enter(milliseconds?: number, signal?: AbortSignal): Promise<() => void> {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
10
|
+
const detach = () => {
|
|
11
|
+
clearTimeout(timer);
|
|
12
|
+
signal?.removeEventListener("abort", cancel);
|
|
13
|
+
};
|
|
14
|
+
const remove = (error: unknown) => {
|
|
15
|
+
const index = this.#queue.indexOf(acquire);
|
|
16
|
+
if (index < 0) return;
|
|
17
|
+
this.#queue.splice(index, 1);
|
|
18
|
+
detach();
|
|
19
|
+
reject(error);
|
|
20
|
+
};
|
|
21
|
+
const cancel = () => remove(new Error("Operation cancelled before interpreter admission"));
|
|
22
|
+
const acquire = () => {
|
|
23
|
+
detach();
|
|
24
|
+
this.#busy = true;
|
|
25
|
+
let released = false;
|
|
26
|
+
resolve(() => {
|
|
27
|
+
if (released) return;
|
|
28
|
+
released = true;
|
|
29
|
+
const next = this.#queue.shift();
|
|
30
|
+
if (next) next();
|
|
31
|
+
else this.#busy = false;
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
if (signal?.aborted) {
|
|
35
|
+
reject(new Error("Operation cancelled before interpreter admission"));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (!this.#busy) acquire();
|
|
39
|
+
else {
|
|
40
|
+
this.#queue.push(acquire);
|
|
41
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
42
|
+
if (milliseconds !== undefined)
|
|
43
|
+
timer = setTimeout(
|
|
44
|
+
() =>
|
|
45
|
+
remove(
|
|
46
|
+
new Error(
|
|
47
|
+
"Interpreter factory admission timed out while another callback held the VM",
|
|
48
|
+
),
|
|
49
|
+
),
|
|
50
|
+
milliseconds,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private host-operation protocol between the interpreter guest and the SDK host.
|
|
3
|
+
* Mirrors `crates/executor-wasm/src/protocol.rs`: unknown operation names are unsupported,
|
|
4
|
+
* while a known operation with missing, mistyped or extra fields is malformed.
|
|
5
|
+
* Payloads (`initial`, `value`, `args`) stay JSON because the WIT contract validates them.
|
|
6
|
+
* Snapshot reads may name the revision the guest already retains (`known`); the host then
|
|
7
|
+
* answers with the current identity and omits a value that has not changed.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Handle issued by one environment table; `scope` selects the table, never an authority. */
|
|
11
|
+
export interface Handle {
|
|
12
|
+
readonly scope?: number;
|
|
13
|
+
readonly id: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A snapshot read optionally names the kernel revision whose value the guest already holds. */
|
|
17
|
+
export interface SnapshotRead extends Handle {
|
|
18
|
+
readonly known?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Longest kernel revision spelling accepted from a guest (a decimal `u64`). */
|
|
22
|
+
const REVISION_LENGTH = 20;
|
|
23
|
+
|
|
24
|
+
export type LogLevel = "log" | "debug" | "info" | "warn" | "error";
|
|
25
|
+
|
|
26
|
+
/** Synchronous host operations. */
|
|
27
|
+
export type HostRequest =
|
|
28
|
+
| { readonly operation: "console"; readonly level: LogLevel; readonly message: string }
|
|
29
|
+
| { readonly operation: "address" }
|
|
30
|
+
| { readonly operation: "orb" }
|
|
31
|
+
| { readonly operation: "signal.cancelled" }
|
|
32
|
+
| { readonly operation: "context.check" }
|
|
33
|
+
| { readonly operation: "context.principal" }
|
|
34
|
+
| { readonly operation: "context.cancel" }
|
|
35
|
+
| {
|
|
36
|
+
readonly operation: "state.declare";
|
|
37
|
+
readonly initial: unknown;
|
|
38
|
+
readonly version: number;
|
|
39
|
+
readonly validate: number | null;
|
|
40
|
+
}
|
|
41
|
+
| ({ readonly operation: "state.read" } & SnapshotRead)
|
|
42
|
+
| ({ readonly operation: "state.update"; readonly value: unknown } & Handle)
|
|
43
|
+
| {
|
|
44
|
+
readonly operation: "reference.declare";
|
|
45
|
+
readonly service: string;
|
|
46
|
+
readonly key: readonly string[];
|
|
47
|
+
}
|
|
48
|
+
| ({ readonly operation: "reference.release" } & Handle)
|
|
49
|
+
| ({ readonly operation: "reference.status" } & Handle)
|
|
50
|
+
| ({ readonly operation: "reference.state" } & SnapshotRead)
|
|
51
|
+
| {
|
|
52
|
+
readonly operation: "resource.declare";
|
|
53
|
+
readonly name: string;
|
|
54
|
+
readonly version: number;
|
|
55
|
+
readonly open: number;
|
|
56
|
+
readonly close: number;
|
|
57
|
+
readonly dependencies: readonly Handle[];
|
|
58
|
+
}
|
|
59
|
+
| ({ readonly operation: "resource.read" } & Handle)
|
|
60
|
+
| { readonly operation: "hook.declare"; readonly name: string };
|
|
61
|
+
|
|
62
|
+
/** Asynchronous host operations, awaited outside the guest heap. */
|
|
63
|
+
export type AsyncHostRequest =
|
|
64
|
+
| ({ readonly operation: "hook.run"; readonly value: unknown } & Handle)
|
|
65
|
+
| ({ readonly operation: "reference.ready" } & Handle)
|
|
66
|
+
/**
|
|
67
|
+
* `Context.get`: the guest names only a selected import binding and key; the host supplies the
|
|
68
|
+
* invocation, principal and requirement. Source handles use their environment's table;
|
|
69
|
+
* checked compiled reference views use their Orb table, shared by the Store's environments.
|
|
70
|
+
*/
|
|
71
|
+
| {
|
|
72
|
+
readonly operation: "reference.acquire";
|
|
73
|
+
readonly service: string;
|
|
74
|
+
readonly key: readonly string[];
|
|
75
|
+
}
|
|
76
|
+
| ({
|
|
77
|
+
readonly operation: "reference.call";
|
|
78
|
+
readonly method: string;
|
|
79
|
+
readonly args: unknown;
|
|
80
|
+
} & Handle)
|
|
81
|
+
| { readonly operation: "wait"; readonly milliseconds: number };
|
|
82
|
+
|
|
83
|
+
/** Longest cooperative timer a callback may request. */
|
|
84
|
+
export const WAIT_LIMIT_MILLISECONDS = 5000;
|
|
85
|
+
|
|
86
|
+
/** Field kinds; a trailing `?` marks a field that may be absent (or null) and takes a default. */
|
|
87
|
+
type Kind =
|
|
88
|
+
| "u32"
|
|
89
|
+
| "string"
|
|
90
|
+
| "keys"
|
|
91
|
+
| "level"
|
|
92
|
+
| "json"
|
|
93
|
+
| "json?"
|
|
94
|
+
| "callback?"
|
|
95
|
+
| "scope?"
|
|
96
|
+
| "revision?"
|
|
97
|
+
| "handles?";
|
|
98
|
+
type Schema = Readonly<Record<string, Kind>>;
|
|
99
|
+
|
|
100
|
+
const HANDLE = { scope: "scope?", id: "u32" } as const satisfies Schema;
|
|
101
|
+
const SNAPSHOT = { ...HANDLE, known: "revision?" } as const satisfies Schema;
|
|
102
|
+
const SYNC = {
|
|
103
|
+
console: { level: "level", message: "string" },
|
|
104
|
+
address: {},
|
|
105
|
+
orb: {},
|
|
106
|
+
"signal.cancelled": {},
|
|
107
|
+
"context.check": {},
|
|
108
|
+
"context.principal": {},
|
|
109
|
+
"context.cancel": {},
|
|
110
|
+
"state.declare": { initial: "json?", version: "u32", validate: "callback?" },
|
|
111
|
+
"state.read": SNAPSHOT,
|
|
112
|
+
"state.update": { ...HANDLE, value: "json?" },
|
|
113
|
+
"reference.declare": { service: "string", key: "keys" },
|
|
114
|
+
"reference.release": HANDLE,
|
|
115
|
+
"reference.status": HANDLE,
|
|
116
|
+
"reference.state": SNAPSHOT,
|
|
117
|
+
"resource.declare": {
|
|
118
|
+
name: "string",
|
|
119
|
+
version: "u32",
|
|
120
|
+
open: "u32",
|
|
121
|
+
close: "u32",
|
|
122
|
+
dependencies: "handles?",
|
|
123
|
+
},
|
|
124
|
+
"resource.read": HANDLE,
|
|
125
|
+
"hook.declare": { name: "string" },
|
|
126
|
+
} as const satisfies Record<HostRequest["operation"], Schema>;
|
|
127
|
+
const ASYNC = {
|
|
128
|
+
"hook.run": { ...HANDLE, value: "json" },
|
|
129
|
+
"reference.ready": HANDLE,
|
|
130
|
+
"reference.acquire": { service: "string", key: "keys" },
|
|
131
|
+
"reference.call": { ...HANDLE, method: "string", args: "json" },
|
|
132
|
+
wait: { milliseconds: "u32" },
|
|
133
|
+
} as const satisfies Record<AsyncHostRequest["operation"], Schema>;
|
|
134
|
+
const LEVELS: readonly string[] = ["log", "debug", "info", "warn", "error"];
|
|
135
|
+
|
|
136
|
+
/** Decode one synchronous packet into a typed request. */
|
|
137
|
+
export function decodeHostRequest(packet: string): HostRequest {
|
|
138
|
+
return decode(packet, SYNC, "host request") as HostRequest;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Decode one asynchronous packet into a typed request. */
|
|
142
|
+
export function decodeAsyncHostRequest(packet: string): AsyncHostRequest {
|
|
143
|
+
return decode(packet, ASYNC, "asynchronous host request") as AsyncHostRequest;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Diagnostics and reads of already issued values stay usable after cancellation. */
|
|
147
|
+
export function survivesCancellation(request: HostRequest): boolean {
|
|
148
|
+
switch (request.operation) {
|
|
149
|
+
case "console":
|
|
150
|
+
case "signal.cancelled":
|
|
151
|
+
case "state.read":
|
|
152
|
+
case "resource.read":
|
|
153
|
+
case "reference.state":
|
|
154
|
+
case "reference.status":
|
|
155
|
+
case "reference.release":
|
|
156
|
+
return true;
|
|
157
|
+
default:
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Validate a packet against the schema for its operation, filling defaults for optional fields. */
|
|
163
|
+
function decode(packet: string, schemas: Readonly<Record<string, Schema>>, label: string): unknown {
|
|
164
|
+
const malformed = (reason: string) => new Error(`Malformed ${label}: ${reason}`);
|
|
165
|
+
let raw: unknown;
|
|
166
|
+
try {
|
|
167
|
+
raw = JSON.parse(packet);
|
|
168
|
+
} catch {
|
|
169
|
+
throw malformed("invalid JSON");
|
|
170
|
+
}
|
|
171
|
+
if (!isRecord(raw)) throw malformed("expected an object");
|
|
172
|
+
const operation = raw.operation;
|
|
173
|
+
if (typeof operation !== "string") throw malformed("expected string operation");
|
|
174
|
+
if (!Object.hasOwn(schemas, operation))
|
|
175
|
+
throw new Error(`Unsupported ${label} operation ${operation}`);
|
|
176
|
+
const schema = schemas[operation]!;
|
|
177
|
+
for (const key of Object.keys(raw))
|
|
178
|
+
if (key !== "operation" && !Object.hasOwn(schema, key)) throw malformed(`unknown field ${key}`);
|
|
179
|
+
const request: Record<string, unknown> = { operation };
|
|
180
|
+
for (const [key, kind] of Object.entries(schema)) {
|
|
181
|
+
const value = field(raw[key], kind, () => malformed(`invalid field ${key}`));
|
|
182
|
+
if (value !== undefined) request[key] = value;
|
|
183
|
+
}
|
|
184
|
+
return request;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Check one field and return its normalized value; `undefined` means omitted. */
|
|
188
|
+
function field(value: unknown, kind: Kind, invalid: () => Error): unknown {
|
|
189
|
+
const absent = value === undefined || value === null;
|
|
190
|
+
switch (kind) {
|
|
191
|
+
case "u32":
|
|
192
|
+
if (!isU32(value)) throw invalid();
|
|
193
|
+
return value;
|
|
194
|
+
case "string":
|
|
195
|
+
if (typeof value !== "string") throw invalid();
|
|
196
|
+
return value;
|
|
197
|
+
case "keys":
|
|
198
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
|
|
199
|
+
throw invalid();
|
|
200
|
+
return value;
|
|
201
|
+
case "level":
|
|
202
|
+
if (typeof value !== "string" || !LEVELS.includes(value)) throw invalid();
|
|
203
|
+
return value;
|
|
204
|
+
case "json":
|
|
205
|
+
if (value === undefined) throw invalid();
|
|
206
|
+
return value;
|
|
207
|
+
case "json?":
|
|
208
|
+
return value ?? null;
|
|
209
|
+
case "callback?":
|
|
210
|
+
if (absent) return null;
|
|
211
|
+
if (!isU32(value)) throw invalid();
|
|
212
|
+
return value;
|
|
213
|
+
case "revision?":
|
|
214
|
+
if (absent) return undefined;
|
|
215
|
+
if (typeof value !== "string" || value.length > REVISION_LENGTH || !/^\d+$/.test(value))
|
|
216
|
+
throw invalid();
|
|
217
|
+
return value;
|
|
218
|
+
case "scope?":
|
|
219
|
+
if (absent) return undefined;
|
|
220
|
+
if (!Number.isSafeInteger(value) || (value as number) < 0) throw invalid();
|
|
221
|
+
return value;
|
|
222
|
+
case "handles?":
|
|
223
|
+
if (absent) return [];
|
|
224
|
+
if (!Array.isArray(value)) throw invalid();
|
|
225
|
+
return value.map((item) => {
|
|
226
|
+
if (!isRecord(item) || Object.keys(item).some((key) => key !== "scope" && key !== "id"))
|
|
227
|
+
throw invalid();
|
|
228
|
+
const scope = field(item.scope, "scope?", invalid);
|
|
229
|
+
return scope === undefined
|
|
230
|
+
? { id: field(item.id, "u32", invalid) }
|
|
231
|
+
: { scope, id: field(item.id, "u32", invalid) };
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
237
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function isU32(value: unknown): value is number {
|
|
241
|
+
return Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 0xffff_ffff;
|
|
242
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WHATWG `Request`/`Response` convenience form of `Host.handleHttp`, for hosts that have
|
|
3
|
+
* those globals. It refuses what WHATWG cannot represent instead of dropping it:
|
|
4
|
+
* - a 1xx status (the `Response` constructor accepts only 200..=599);
|
|
5
|
+
* - a field the platform's `Response` would hide (browsers drop `set-cookie`);
|
|
6
|
+
* - non-empty response trailers: the body errors at its end, after every byte was delivered.
|
|
7
|
+
* Known WHATWG normalizations stay documented, not refused: duplicate fields are joined with
|
|
8
|
+
* ", " (except `set-cookie`), values lose surrounding whitespace, the request URL is normalized
|
|
9
|
+
* and a `Request` has no trailers. Use `IncomingHttpRequest` for the lossless raw form.
|
|
10
|
+
*/
|
|
11
|
+
import { byteString, bytesOf } from "./http-provider.ts";
|
|
12
|
+
import type { HttpHandlerResponse, IncomingHttpRequest } from "./http-ingress.ts";
|
|
13
|
+
|
|
14
|
+
/** Statuses whose `Response` carries no body. */
|
|
15
|
+
const NULL_BODY = new Set([101, 103, 204, 205, 304]);
|
|
16
|
+
|
|
17
|
+
/** Whether `value` is a WHATWG `Request` of this realm. */
|
|
18
|
+
export function isFetchRequest(value: unknown): value is Request {
|
|
19
|
+
return typeof Request === "function" && value instanceof Request;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Read a WHATWG stream through an iterator whose `return()` cancels it. */
|
|
23
|
+
function iterate(stream: ReadableStream<Uint8Array>): AsyncIterable<Uint8Array> {
|
|
24
|
+
return {
|
|
25
|
+
[Symbol.asyncIterator]() {
|
|
26
|
+
const reader = stream.getReader();
|
|
27
|
+
return {
|
|
28
|
+
async next() {
|
|
29
|
+
const next = await reader.read();
|
|
30
|
+
return next.done ? { done: true, value: undefined } : { done: false, value: next.value };
|
|
31
|
+
},
|
|
32
|
+
async return() {
|
|
33
|
+
await reader.cancel();
|
|
34
|
+
return { done: true, value: undefined };
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The raw request a WHATWG `Request` describes. */
|
|
42
|
+
export function fromFetchRequest(request: Request): IncomingHttpRequest {
|
|
43
|
+
if (typeof ReadableStream !== "function")
|
|
44
|
+
throw new TypeError(
|
|
45
|
+
"WHATWG ReadableStream is unavailable on this host; pass an IncomingHttpRequest to receive raw parts",
|
|
46
|
+
);
|
|
47
|
+
// Some hosts install a buffered fetch polyfill whose Request has no public body stream.
|
|
48
|
+
const body = (request as Partial<Request>).body;
|
|
49
|
+
if (body === undefined)
|
|
50
|
+
throw new TypeError(
|
|
51
|
+
"WHATWG Request has no body stream on this host; pass an IncomingHttpRequest to receive raw parts",
|
|
52
|
+
);
|
|
53
|
+
const url = new URL(request.url);
|
|
54
|
+
return {
|
|
55
|
+
method: request.method,
|
|
56
|
+
scheme: url.protocol.slice(0, -1),
|
|
57
|
+
authority: url.host,
|
|
58
|
+
pathWithQuery: url.pathname + url.search,
|
|
59
|
+
fields: [...request.headers].map(([name, value]) => [name, bytesOf(value)] as const),
|
|
60
|
+
body: body ? iterate(body) : null,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** End a response the application will never receive. */
|
|
65
|
+
function discard(response: HttpHandlerResponse): void {
|
|
66
|
+
void response.body[Symbol.asyncIterator]().return?.();
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The WHATWG `Response` for a handler response, or a refusal. */
|
|
70
|
+
export function toFetchResponse(response: HttpHandlerResponse): Response {
|
|
71
|
+
const refuse = (message: string) => {
|
|
72
|
+
discard(response);
|
|
73
|
+
return new TypeError(`${message}; pass an IncomingHttpRequest to receive raw parts`);
|
|
74
|
+
};
|
|
75
|
+
if (typeof Response !== "function" || typeof Headers !== "function")
|
|
76
|
+
throw refuse("WHATWG Response is unavailable on this host");
|
|
77
|
+
if (response.status < 200) throw refuse(`HTTP status ${response.status} has no WHATWG Response`);
|
|
78
|
+
const headers = new Headers();
|
|
79
|
+
try {
|
|
80
|
+
for (const [name, value] of response.fields) headers.append(name, byteString(value));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw refuse(error instanceof Error ? error.message : String(error));
|
|
83
|
+
}
|
|
84
|
+
const empty = NULL_BODY.has(response.status);
|
|
85
|
+
if (!empty && typeof ReadableStream !== "function")
|
|
86
|
+
throw refuse("WHATWG ReadableStream is unavailable on this host");
|
|
87
|
+
const iterator = response.body[Symbol.asyncIterator]();
|
|
88
|
+
const body = empty
|
|
89
|
+
? null
|
|
90
|
+
: new ReadableStream<Uint8Array>(
|
|
91
|
+
{
|
|
92
|
+
async pull(controller) {
|
|
93
|
+
const next = await iterator.next();
|
|
94
|
+
if (!next.done) return controller.enqueue(next.value);
|
|
95
|
+
if ((await response.trailers)?.length)
|
|
96
|
+
return controller.error(
|
|
97
|
+
new TypeError("response trailers have no WHATWG representation"),
|
|
98
|
+
);
|
|
99
|
+
controller.close();
|
|
100
|
+
},
|
|
101
|
+
async cancel() {
|
|
102
|
+
await iterator.return?.();
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
{ highWaterMark: 0 },
|
|
106
|
+
);
|
|
107
|
+
const result = new Response(body as ReadableStream<Uint8Array<ArrayBuffer>> | null, {
|
|
108
|
+
status: response.status,
|
|
109
|
+
headers,
|
|
110
|
+
});
|
|
111
|
+
for (const [name] of response.fields)
|
|
112
|
+
if (!result.headers.has(name)) {
|
|
113
|
+
void iterator.return?.();
|
|
114
|
+
throw new TypeError(
|
|
115
|
+
`the platform Response drops the ${name} field; pass an IncomingHttpRequest to receive raw parts`,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
if (empty) void drainEmpty(iterator);
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A null-body status still completes its delivery: an empty body ends normally, while content
|
|
124
|
+
* that has no place in such a response is refused to the handler as a disconnect.
|
|
125
|
+
*/
|
|
126
|
+
async function drainEmpty(iterator: AsyncIterator<Uint8Array>): Promise<void> {
|
|
127
|
+
try {
|
|
128
|
+
const next = await iterator.next();
|
|
129
|
+
if (!next.done) await iterator.return?.();
|
|
130
|
+
} catch {
|
|
131
|
+
// The handler's failure ends its own delivery.
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Incoming HTTP for `Host.handleHttp`: the raw request and response shapes, the handler's error
|
|
3
|
+
* and the private exchange that carries one request into an Orb's `wasi:http/handler` export.
|
|
4
|
+
*
|
|
5
|
+
* The raw shapes are lossless: field values are bytes, order and duplicates are kept, the
|
|
6
|
+
* request target is passed verbatim, and both sides carry trailers. Bodies are
|
|
7
|
+
* `AsyncIterable<Uint8Array>`, so nothing here needs WHATWG streams; `return()` on the response
|
|
8
|
+
* body's iterator is the client disconnect. Nothing in this module performs I/O.
|
|
9
|
+
*/
|
|
10
|
+
import type { ErrorCode } from "wasi:http/types@0.3.0";
|
|
11
|
+
import { Errors } from "../errors.ts";
|
|
12
|
+
import { TembraError } from "../error.ts";
|
|
13
|
+
import type { HttpField } from "./http-provider.ts";
|
|
14
|
+
|
|
15
|
+
/** The exact standard export an Orb serves incoming HTTP through. */
|
|
16
|
+
export const HTTP_HANDLER = "wasi:http/handler@0.3.0";
|
|
17
|
+
|
|
18
|
+
/** One request as the host received it; the application owns listening, routing and auth. */
|
|
19
|
+
export interface IncomingHttpRequest {
|
|
20
|
+
/** `GET`, `POST`, … or an extension token, verbatim. */
|
|
21
|
+
readonly method: string;
|
|
22
|
+
/** `http`, `https` or another scheme; absent when the request has none. */
|
|
23
|
+
readonly scheme?: string | undefined;
|
|
24
|
+
readonly authority?: string | undefined;
|
|
25
|
+
/** The origin-form path and query exactly as received. */
|
|
26
|
+
readonly pathWithQuery?: string | undefined;
|
|
27
|
+
/** Lowercase names and raw value bytes, in order, duplicates kept. */
|
|
28
|
+
readonly fields: readonly HttpField[];
|
|
29
|
+
/**
|
|
30
|
+
* The request contents, pulled as the handler reads, or `null` for none. The host calls its
|
|
31
|
+
* iterator's `return()` once, without awaiting it, when the handler drops the body early, the
|
|
32
|
+
* client disconnects, the call ends, or the call fails before the handler received it.
|
|
33
|
+
*/
|
|
34
|
+
readonly body: AsyncIterable<Uint8Array> | null;
|
|
35
|
+
/** Trailers, read after the body ended; absent means none. */
|
|
36
|
+
readonly trailers?: PromiseLike<readonly HttpField[] | undefined> | undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The handler's response; the head arrives before the body is produced. */
|
|
40
|
+
export interface HttpHandlerResponse {
|
|
41
|
+
/** 100..=599. */
|
|
42
|
+
readonly status: number;
|
|
43
|
+
readonly fields: readonly HttpField[];
|
|
44
|
+
/**
|
|
45
|
+
* The contents, produced while they are read; read once. Reading to the end and then the
|
|
46
|
+
* trailers completes the transmission. Calling `return()` on its iterator (or abandoning a
|
|
47
|
+
* `for await` loop) is the client disconnect: the handler sees `connection-terminated`, its
|
|
48
|
+
* request body is closed and its next write fails.
|
|
49
|
+
*/
|
|
50
|
+
readonly body: AsyncIterable<Uint8Array>;
|
|
51
|
+
/**
|
|
52
|
+
* Settles after the body ended: `undefined` for none. Rejects with an `HttpHandlerError` when
|
|
53
|
+
* the handler failed its body or trailers, or when the delivery ended early.
|
|
54
|
+
*/
|
|
55
|
+
readonly trailers: Promise<readonly HttpField[] | undefined>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface HandleHttpOptions {
|
|
59
|
+
/** Cancels the call, as cancelling its root does; the response body then ends. */
|
|
60
|
+
readonly signal?: AbortSignal | undefined;
|
|
61
|
+
/** The principal of the root this request runs in; defaults to the host's. */
|
|
62
|
+
readonly principal?: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The handler (or the delivery of its response) ended with a standard `error-code`. */
|
|
66
|
+
export class HttpHandlerError extends Error {
|
|
67
|
+
constructor(
|
|
68
|
+
readonly code: ErrorCode,
|
|
69
|
+
message = `HTTP handler failed: ${code.tag}`,
|
|
70
|
+
) {
|
|
71
|
+
super(message);
|
|
72
|
+
this.name = "HttpHandlerError";
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The transmission result the handler sees when its client disconnected. */
|
|
77
|
+
export const CONNECTION_TERMINATED: ErrorCode = { tag: "connection-terminated" };
|
|
78
|
+
|
|
79
|
+
/** Exchanges created by `Host.handleHttp`; nothing else can enter the handler method. */
|
|
80
|
+
const issued = new WeakSet<object>();
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* One request travelling into one handler call. The head resolves as soon as the handler
|
|
84
|
+
* published its response; a failure before that is reported only once the call physically
|
|
85
|
+
* settled.
|
|
86
|
+
*/
|
|
87
|
+
export class IngressExchange {
|
|
88
|
+
readonly head: Promise<HttpHandlerResponse>;
|
|
89
|
+
#resolve!: (response: HttpHandlerResponse) => void;
|
|
90
|
+
#reject!: (error: unknown) => void;
|
|
91
|
+
#claimed = false;
|
|
92
|
+
/** A port took the request body; from then on only that port closes it. */
|
|
93
|
+
#owned = false;
|
|
94
|
+
#published = false;
|
|
95
|
+
#refusal: unknown;
|
|
96
|
+
|
|
97
|
+
constructor(readonly request: IncomingHttpRequest) {
|
|
98
|
+
this.head = new Promise((resolve, reject) => {
|
|
99
|
+
this.#resolve = resolve;
|
|
100
|
+
this.#reject = reject;
|
|
101
|
+
});
|
|
102
|
+
issued.add(this);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Whether the handler's result (a response or its error) was published. */
|
|
106
|
+
get published(): boolean {
|
|
107
|
+
return this.#published;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The handler returned a response: release the head now. */
|
|
111
|
+
respond(response: HttpHandlerResponse): void {
|
|
112
|
+
if (this.#published) throw new Error("the response head was already published");
|
|
113
|
+
this.#published = true;
|
|
114
|
+
this.#resolve(response);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The handler returned its `error-code`: reported once the call settled. */
|
|
118
|
+
refuse(code: ErrorCode): void {
|
|
119
|
+
if (this.#published) throw new Error("the response head was already published");
|
|
120
|
+
this.#published = true;
|
|
121
|
+
this.#refusal = new HttpHandlerError(code);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* A port takes the request: from now on it alone pulls and closes the body. Called exactly
|
|
126
|
+
* where a port's own end-of-call cleanup starts to cover the body.
|
|
127
|
+
*/
|
|
128
|
+
own(): IncomingHttpRequest {
|
|
129
|
+
this.#owned = true;
|
|
130
|
+
return this.request;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The call physically settled; without a published response, report why. A body no port
|
|
135
|
+
* ever took (the call failed before any port saw it) is closed here, once; its `return()` is
|
|
136
|
+
* not awaited and an application failure there cannot affect the report.
|
|
137
|
+
*/
|
|
138
|
+
settle(failure?: unknown): void {
|
|
139
|
+
if (!this.#owned) {
|
|
140
|
+
this.#owned = true;
|
|
141
|
+
try {
|
|
142
|
+
const done = this.request.body?.[Symbol.asyncIterator]().return?.();
|
|
143
|
+
if (typeof (done as PromiseLike<unknown> | undefined)?.then === "function")
|
|
144
|
+
Promise.resolve(done).catch(() => {});
|
|
145
|
+
} catch {
|
|
146
|
+
// A body that cannot be opened or closed (a locked stream) stays the application's.
|
|
147
|
+
}
|
|
148
|
+
if (typeof this.request.trailers?.then === "function")
|
|
149
|
+
Promise.resolve(this.request.trailers).catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
if (this.#refusal !== undefined) return this.#reject(this.#refusal);
|
|
152
|
+
if (this.#published && this.#refusal === undefined) return;
|
|
153
|
+
this.#reject(failure ?? new Error("the HTTP handler ended without a response"));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Take the exchange for the handler call; a host-local value enters exactly one call. */
|
|
157
|
+
static claim(value: unknown): IngressExchange {
|
|
158
|
+
if (typeof value !== "object" || value === null || !issued.has(value))
|
|
159
|
+
throw new TembraError(
|
|
160
|
+
Errors.Invalid.LocalValue,
|
|
161
|
+
`${HTTP_HANDLER} is served only through Host.handleHttp`,
|
|
162
|
+
);
|
|
163
|
+
const exchange = value as IngressExchange;
|
|
164
|
+
if (exchange.#claimed) throw new Error("the HTTP request was already handled");
|
|
165
|
+
exchange.#claimed = true;
|
|
166
|
+
return exchange;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Check the raw request's shape before any work starts; semantics are checked by the host. */
|
|
171
|
+
export function checkedRequest(request: IncomingHttpRequest): IncomingHttpRequest {
|
|
172
|
+
if (typeof request !== "object" || request === null)
|
|
173
|
+
throw new TypeError("handleHttp requires a request");
|
|
174
|
+
const { method, scheme, authority, pathWithQuery, fields, body, trailers } = request;
|
|
175
|
+
if (typeof method !== "string") throw new TypeError("request method must be a string");
|
|
176
|
+
for (const [name, value] of [
|
|
177
|
+
["scheme", scheme],
|
|
178
|
+
["authority", authority],
|
|
179
|
+
["pathWithQuery", pathWithQuery],
|
|
180
|
+
] as const)
|
|
181
|
+
if (value !== undefined && typeof value !== "string")
|
|
182
|
+
throw new TypeError(`request ${name} must be a string`);
|
|
183
|
+
if (!Array.isArray(fields)) throw new TypeError("request fields must be an array");
|
|
184
|
+
const copied = fields.map((field) => {
|
|
185
|
+
const [name, value] = Array.isArray(field) ? field : [];
|
|
186
|
+
if (typeof name !== "string" || !(value instanceof Uint8Array))
|
|
187
|
+
throw new TypeError("request fields are [name, Uint8Array] pairs");
|
|
188
|
+
return Object.freeze([name, value.slice()] as const);
|
|
189
|
+
});
|
|
190
|
+
if (body !== null && typeof body?.[Symbol.asyncIterator] !== "function")
|
|
191
|
+
throw new TypeError("request body must be an AsyncIterable<Uint8Array> or null");
|
|
192
|
+
if (trailers !== undefined && typeof trailers?.then !== "function")
|
|
193
|
+
throw new TypeError("request trailers must be a promise");
|
|
194
|
+
return Object.freeze({
|
|
195
|
+
method,
|
|
196
|
+
scheme,
|
|
197
|
+
authority,
|
|
198
|
+
pathWithQuery,
|
|
199
|
+
fields: Object.freeze(copied),
|
|
200
|
+
body,
|
|
201
|
+
trailers,
|
|
202
|
+
});
|
|
203
|
+
}
|