Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions typescript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ The symbol's runtime value and canonical declaration are shared across the ESM a
CommonJS builds, so validators remain type-compatible and schema preflight also runs
when a validator and translator come from different module formats.

An isolated, private [browser/WASM validator prototype](./experimental/browser/README.md)
tracks [#536](https://github.com/microsoft/TypeChat/issues/536). It requires a separate
install and explicit opt-in; it is not a published or supported browser release.
The normal package and `typechat/ts` continue to use the native Node.js backend.

To see TypeChat in action, we recommend exploring the [TypeChat example projects](https://github.com/microsoft/TypeChat/tree/main/typescript/examples). You can try them on your local machine or in a GitHub Codespace.

To learn more about TypeChat, visit the [documentation](https://microsoft.github.io/TypeChat) which includes more information on TypeChat and how to get started.
Expand Down
446 changes: 446 additions & 0 deletions typescript/experimental/browser/README.md

Large diffs are not rendered by default.

39 changes: 39 additions & 0 deletions typescript/experimental/browser/examples/worker/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { compilerVersion, wasmSha256 } from "../../dist/experimental/browser/src/versions.js";

export const wasmAssetPath = `/typescript-${compilerVersion}-${wasmSha256}.wasm`;

export async function buildWorkerExample() {
const html = await readFile(new URL("./index.html", import.meta.url), "utf8");
if (html.split("__TYPECHAT_WASM_ASSET__").length !== 2) {
throw new Error("The worker example must contain exactly one WASM asset placeholder.");
}
const assets = new Map([
["/worker", ["text/html; charset=utf-8", html.replace("__TYPECHAT_WASM_ASSET__", wasmAssetPath)]],
["/worker.css", ["text/css; charset=utf-8", await readFile(new URL("./style.css", import.meta.url))]]
]);
for (const [source, route] of [
["main.mjs", "/worker-main.js"],
["client.ts", "/worker-client.js"],
["validator.worker.ts", "/validator.worker.js"]
]) {
const result = await build({
entryPoints: [fileURLToPath(new URL(source, import.meta.url))],
platform: "browser",
format: "esm",
target: "es2021",
bundle: true,
minify: true,
write: false,
metafile: true,
logLevel: "silent"
});
if (Object.values(result.metafile.outputs).some(output => output.imports.length !== 0)) {
throw new Error("Worker example bundles must be self-contained.");
}
assets.set(route, ["text/javascript", result.outputFiles[0].contents]);
}
return assets;
}
100 changes: 100 additions & 0 deletions typescript/experimental/browser/examples/worker/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { Result } from "@typechat/experimental-browser";

export interface ValidationJob {
wasmUrl: string;
schema: string;
typeName: string;
values: object[];
}

export interface ValidationReport {
results: Result<object>[];
loadCompileMs: number;
initializationMs: number;
validationMs: number;
maxLinearMemoryBytes: number;
closedLinearMemoryBytes: number;
}

export type WorkerPhase = "loading" | "validating";
export type WorkerReply =
| { kind: "phase"; phase: WorkerPhase }
| { kind: "result"; report: ValidationReport }
| { kind: "error"; name: string; message: string };

/**
* Application-owned, one-job-per-worker example. Aborting destroys that job's
* compiler, including synchronous validation; it does not interrupt a shared worker.
*/
export function validateInWorker(
workerUrl: string | URL,
job: ValidationJob,
options: { signal: AbortSignal; onPhase?: (phase: WorkerPhase) => void }
): Promise<ValidationReport> {
return new Promise((resolve, reject) => {
options.signal.throwIfAborted();
const worker = new Worker(workerUrl, { type: "module" });
let settled = false;
const cleanup = () => {
if (settled) {
return false;
}
settled = true;
options.signal.removeEventListener("abort", abort);
worker.removeEventListener("message", message);
worker.removeEventListener("error", failure);
worker.removeEventListener("messageerror", invalidMessage);
worker.terminate();
return true;
};
const fail = (cause: unknown) => {
if (cleanup()) {
reject(cause);
}
};
const abort = () => fail(options.signal.reason);
const failure = (event: ErrorEvent) => {
event.preventDefault();
fail(new Error(event.message || "The validation worker failed without error details."));
};
const invalidMessage = () => fail(new Error("Unable to deserialize a validation worker reply."));
const message = (event: MessageEvent<WorkerReply>) => {
try {
const reply = event.data;
switch (reply?.kind) {
case "phase":
options.onPhase?.(reply.phase);
return;
case "result":
if (cleanup()) {
resolve(reply.report);
}
return;
case "error": {
const error = new Error(reply.message);
error.name = reply.name;
fail(error);
return;
}
default:
fail(new Error("Unexpected validation worker reply."));
}
} catch (cause) {
fail(cause);
}
};
worker.addEventListener("message", message);
worker.addEventListener("error", failure);
worker.addEventListener("messageerror", invalidMessage);
options.signal.addEventListener("abort", abort, { once: true });
if (options.signal.aborted) {
abort();
return;
}
try {
worker.postMessage(job);
} catch (cause) {
fail(cause);
}
});
}
101 changes: 101 additions & 0 deletions typescript/experimental/browser/examples/worker/host.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { gzipSync } from "node:zlib";
import { buildWorkerExample, wasmAssetPath } from "./build.mjs";
import { wasmByteLength, wasmSha256 } from "../../dist/experimental/browser/src/versions.js";

export { wasmAssetPath } from "./build.mjs";
export const contentSecurityPolicy = [
"default-src 'none'",
"script-src 'self' 'wasm-unsafe-eval'",
"worker-src 'self'",
"connect-src 'self'",
"style-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'"
].join("; ");

function chooseEncoding(header) {
if (!header?.trim()) {
return "identity";
}
const qualities = new Map();
for (const entry of header.split(",")) {
const match = /^\s*([a-z0-9!#$%&'*+.^_`|~-]+)\s*(?:;\s*q\s*=\s*(0(?:\.\d{0,3})?|1(?:\.0{0,3})?))?\s*$/i.exec(entry);
if (!match) {
return { status: 400, message: "Invalid Accept-Encoding header." };
}
const name = match[1].toLowerCase();
qualities.set(name, Math.max(qualities.get(name) ?? 0, Number(match[2] ?? 1)));
}
const gzip = qualities.get("gzip") ?? qualities.get("*") ?? 0;
// Identity remains acceptable unless explicitly excluded, including by "*;q=0".
const identity = qualities.get("identity") ?? (qualities.get("*") === 0 ? 0 : 1);
if (gzip > 0 && gzip >= identity) {
return "gzip";
}
return identity > 0 ? "identity" : { status: 406, message: "No acceptable content encoding." };
}

export async function createWorkerExampleHandler() {
const assets = await buildWorkerExample();
const wasm = await readFile(new URL("../../node_modules/@typescript/typescript-wasip1-wasm/lib/tsc.wasm", import.meta.url));
if (wasm.length !== wasmByteLength || createHash("sha256").update(wasm).digest("hex") !== wasmSha256) {
throw new Error("The hosted WASM artifact does not match the pinned compiler.");
}
assets.set(wasmAssetPath, ["application/wasm", wasm]);
const representations = new Map();
for (const [route, [type, source]] of assets) {
const identity = Buffer.from(source);
const gzip = gzipSync(identity);
const etag = bytes => `"${createHash("sha256").update(bytes).digest("hex")}"`;
representations.set(route, { type, identity, gzip, identityTag: etag(identity), gzipTag: etag(gzip) });
}

return (request, response) => {
const asset = representations.get(request.url);
if (!asset) {
return false;
}
const headers = {
"Content-Security-Policy": contentSecurityPolicy,
"X-Content-Type-Options": "nosniff",
"Cache-Control": "no-store"
};
const fail = (status, message, extra = {}) => {
response.writeHead(status, { ...headers, "Content-Type": "text/plain; charset=utf-8", ...extra });
response.end(request.method === "HEAD" ? undefined : message);
return true;
};
if (request.method !== "GET" && request.method !== "HEAD") {
return fail(405, "Only GET and HEAD are supported.", { Allow: "GET, HEAD" });
}
const encoding = chooseEncoding(request.headers["accept-encoding"]);
if (typeof encoding !== "string") {
return fail(encoding.status, encoding.message);
}
const body = asset[encoding];
const tag = encoding === "gzip" ? asset.gzipTag : asset.identityTag;
headers["Content-Type"] = asset.type;
headers.Vary = "Accept-Encoding";
if (encoding === "gzip") {
headers["Content-Encoding"] = "gzip";
}
if (request.url === wasmAssetPath) {
headers["Cache-Control"] = "public, max-age=31536000, immutable";
headers.ETag = tag;
const matches = request.headers["if-none-match"]?.split(",")
.some(value => ["*", tag, `W/${tag}`].includes(value.trim()));
if (matches) {
response.writeHead(304, headers);
response.end();
return true;
}
}
headers["Content-Length"] = body.length;
response.writeHead(200, headers);
response.end(request.method === "HEAD" ? undefined : body);
return true;
};
}
25 changes: 25 additions & 0 deletions typescript/experimental/browser/examples/worker/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Experimental TypeChat worker validation</title>
<link rel="stylesheet" href="/worker.css">
<script type="module" src="/worker-main.js"></script>
</head>
<body data-wasm-url="__TYPECHAT_WASM_ASSET__">
<h1>Experimental TypeChat worker validation</h1>
<p>Offline example: no model calls or credentials. Each run owns a worker and a
compiler. Cancellation terminates that worker. The experimental WASM download is
about 53 MB before compression.</p>
<pre>enum Status { Active = "active", Paused = "paused" }
interface Request { status: Status; value: number; }</pre>
<label for="values">JSON objects to validate</label>
<textarea id="values">[{"status":"active","value":1},{"status":"unknown","value":"invalid"}]</textarea>
<button id="run">Validate in worker</button>
<button id="cancel" disabled>Cancel</button>
<p id="status" role="status">Ready</p>
<p>Main-thread timer ticks: <span id="ticks">0</span></p>
<pre id="result"></pre>
</body>
</html>
47 changes: 47 additions & 0 deletions typescript/experimental/browser/examples/worker/main.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { validateInWorker } from "./client.js";

const run = document.getElementById("run");
const cancel = document.getElementById("cancel");
const status = document.getElementById("status");
const result = document.getElementById("result");
const wasmPath = document.body.dataset.wasmUrl;
if (!wasmPath) {
status.textContent = "The example has no configured WASM asset URL.";
throw new Error(status.textContent);
}

let controller;
let ticks = 0;
const timer = setInterval(() => document.getElementById("ticks").textContent = String(++ticks), 50);
cancel.onclick = () => controller?.abort();
run.onclick = async () => {
controller = new AbortController();
run.disabled = true;
cancel.disabled = false;
status.textContent = "Starting worker";
result.textContent = "";
try {
const values = JSON.parse(document.getElementById("values").value);
const report = await validateInWorker("/validator.worker.js", {
wasmUrl: new URL(wasmPath, location.href).href,
schema: 'export enum Status { Active = "active", Paused = "paused" } export interface Request { status: Status; value: number; }',
typeName: "Request",
values
}, {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(60_000)]),
onPhase: phase => status.textContent = phase
});
result.textContent = JSON.stringify(report, null, 2);
status.textContent = "Completed; worker disposed";
} catch (error) {
status.textContent = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
} finally {
run.disabled = false;
cancel.disabled = true;
controller = undefined;
}
};
addEventListener("pagehide", () => {
clearInterval(timer);
controller?.abort();
}, { once: true });
22 changes: 22 additions & 0 deletions typescript/experimental/browser/examples/worker/serve.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { createServer } from "node:http";
import { createWorkerExampleHandler } from "./host.mjs";

const handleExample = await createWorkerExampleHandler();
const server = createServer((request, response) => {
if (!handleExample(request, response)) {
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
response.end("Not found");
}
});
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Unable to determine the worker example address.");
}
console.log(`Worker example: http://127.0.0.1:${address.port}/worker`);
console.log("Press Ctrl+C to stop the local example.");
});
process.once("SIGINT", () => {
server.closeAllConnections();
server.close();
});
4 changes: 4 additions & 0 deletions typescript/experimental/browser/examples/worker/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
body { font: 1rem system-ui; max-width: 55rem; margin: 2rem auto; padding: 0 1rem; }
textarea { display: block; width: 100%; min-height: 7rem; margin: 1rem 0; }
button { padding: .5rem 1rem; margin-right: .5rem; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; }
9 changes: 9 additions & 0 deletions typescript/experimental/browser/examples/worker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"lib": ["es2021", "webworker"],
"types": [],
"noEmit": true
},
"include": ["client.ts", "validator.worker.ts"]
}
Loading