@txco/web-abi 0.0.0-stage → 0.2.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 +109 -2
- package/dist/bridge.d.ts +25 -0
- package/dist/bridge.js +103 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +67 -0
- package/dist/envelope.d.ts +57 -0
- package/dist/envelope.js +3 -0
- package/dist/harness.d.ts +32 -0
- package/dist/harness.js +144 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/manifest.d.ts +36 -0
- package/dist/manifest.js +116 -0
- package/dist/producer.d.ts +100 -0
- package/dist/producer.js +204 -0
- package/package.json +55 -4
- package/src/bridge.ts +115 -0
- package/src/cli.ts +71 -0
- package/src/envelope.ts +49 -0
- package/src/harness.ts +149 -0
- package/src/index.ts +4 -0
- package/src/manifest.ts +127 -0
- package/src/producer.ts +269 -0
- package/txco-web.schema.json +44 -0
package/README.md
CHANGED
|
@@ -1,3 +1,110 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @txco/web-abi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The conformance kit for the [Thanks, Computer](https://www.thanks.computer) (TxCo) Web ABI: the contract a framework's build
|
|
4
|
+
produces so `txco` can deploy it.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
<out>/
|
|
8
|
+
txco-web.json the manifest: what the build is, never its routing
|
|
9
|
+
public/ files, installed as the stack's FILES/
|
|
10
|
+
server/ an optional Fetch handler: export default { fetch(request, ctx) }
|
|
11
|
+
ops/ ordinary .txcl, in scope directories (ops/900000/…)
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The kit has four parts:
|
|
15
|
+
|
|
16
|
+
- **The manifest schema** (`txco-web.schema.json`) and a validator. `txco`
|
|
17
|
+
embeds the same schema file, and both validators pass the same test corpus.
|
|
18
|
+
- **The envelope ↔ Fetch bridge**, which every runner uses. It turns the
|
|
19
|
+
chassis's request envelope into a Fetch `Request`, calls the handler, and
|
|
20
|
+
turns the `Response` into the delta the chassis merges.
|
|
21
|
+
- **A harness** that checks a build's `server/` before any runner exists, and
|
|
22
|
+
serves a build locally.
|
|
23
|
+
- **The producer helpers** (`@txco/web-abi/producer`) that a framework adapter,
|
|
24
|
+
preset or plugin writes a build with. They render the ops (a navigation op
|
|
25
|
+
and the catch-all), write and validate the manifest, and guard the output
|
|
26
|
+
directory before a build wipes it. Producers built on them answer requests
|
|
27
|
+
the same way.
|
|
28
|
+
|
|
29
|
+
`txco web check <out>` checks the rest: the files, the ops, and every request
|
|
30
|
+
the build has to answer.
|
|
31
|
+
|
|
32
|
+
## The manifest
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"abi": 1,
|
|
37
|
+
"server": { "entry": "server/index.mjs" },
|
|
38
|
+
"immutable": ["_app/immutable/"]
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Field | Meaning |
|
|
43
|
+
| -------------- | ------------------------------------------------------------------------------------- |
|
|
44
|
+
| `abi` | `1` |
|
|
45
|
+
| `server.entry` | The handler module, under `server/`. Leave it out for a static build. |
|
|
46
|
+
| `immutable` | `public/` prefixes whose file names carry a content hash. They are cached for a year. |
|
|
47
|
+
|
|
48
|
+
Keys starting with `x-` are free for producers. Any other key is an error.
|
|
49
|
+
|
|
50
|
+
## The server contract
|
|
51
|
+
|
|
52
|
+
```js
|
|
53
|
+
export default {
|
|
54
|
+
async fetch(request, ctx) {
|
|
55
|
+
// a Fetch Request; ctx = { client: { ip } }
|
|
56
|
+
return new Response("…");
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- **Buffered both ways.** An answer is capped at about 3 MiB of body.
|
|
62
|
+
- **Cookies.** Each `Set-Cookie` arrives on its own line.
|
|
63
|
+
- **Errors.** A handler that throws, or returns something other than a
|
|
64
|
+
`Response`, answers `500` without revealing why.
|
|
65
|
+
|
|
66
|
+
## Use
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
npx txco-web-abi validate <out> # the manifest
|
|
70
|
+
npx txco-web-abi check-server <out> [--json] # drive server/ through the bridge
|
|
71
|
+
npx txco-web-abi serve <out> [--port 8787] # public/ first, then server/
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
import {
|
|
76
|
+
dispatch,
|
|
77
|
+
envelopeToRequest,
|
|
78
|
+
responseToDelta,
|
|
79
|
+
} from "@txco/web-abi/bridge";
|
|
80
|
+
import { validateManifest } from "@txco/web-abi/manifest";
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Write a producer
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import { checkOutDir, renderOps, writeManifest, writeOps } from "@txco/web-abi/producer";
|
|
87
|
+
|
|
88
|
+
// Before the build: refuse an output dir inside OPS/, one holding foreign
|
|
89
|
+
// files, or one holding the project.
|
|
90
|
+
const problems = checkOutDir({ dir: out, protect: [root, outDir], notInside: [outDir], entries });
|
|
91
|
+
|
|
92
|
+
// After it: public/ is in place. One navigation op (the shell with 200 for
|
|
93
|
+
// an app that routes in the browser, or the 404 page with 404), plus the
|
|
94
|
+
// catch-all at 900900.
|
|
95
|
+
await writeOps(out, renderOps({ mode: "spa", producer: "my-adapter", page: { name: "index.html", html } }));
|
|
96
|
+
await writeManifest(out, { abi: 1, immutable: ["assets/"], "x-producer": { name: "my-adapter" } });
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`@txco/vite-plugin` is built this way.
|
|
100
|
+
|
|
101
|
+
## Develop
|
|
102
|
+
|
|
103
|
+
```sh
|
|
104
|
+
npm install
|
|
105
|
+
npm test # tsc, then node --test (Node 20+)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## License
|
|
109
|
+
|
|
110
|
+
MIT
|
package/dist/bridge.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { FetchHandler, TxcContext, TxcDelta, TxcEnvelope } from "./envelope.js";
|
|
2
|
+
/** An op answer is capped at 4 MiB (--op-payload-max); the body is base64 inside it. */
|
|
3
|
+
export declare const DEFAULT_MAX_ANSWER_BYTES: number;
|
|
4
|
+
export interface RequestOptions {
|
|
5
|
+
/** Refuse a request body larger than this (bytes). Default: no limit. */
|
|
6
|
+
maxBodyBytes?: number;
|
|
7
|
+
}
|
|
8
|
+
/** Builds the Fetch Request an envelope describes. */
|
|
9
|
+
export declare function envelopeToRequest(env: TxcEnvelope, opts?: RequestOptions): Request;
|
|
10
|
+
/** The handler's context: only what the contract defines. */
|
|
11
|
+
export declare function contextFrom(env: TxcEnvelope): TxcContext;
|
|
12
|
+
export interface DeltaOptions {
|
|
13
|
+
/** The request's method: a HEAD answer carries no body. */
|
|
14
|
+
method?: string;
|
|
15
|
+
/** Refuse a body larger than this (bytes). */
|
|
16
|
+
maxAnswerBytes?: number;
|
|
17
|
+
}
|
|
18
|
+
/** Turns a Response into the chassis delta. */
|
|
19
|
+
export declare function responseToDelta(res: Response, opts?: DeltaOptions): Promise<TxcDelta>;
|
|
20
|
+
/**
|
|
21
|
+
* Runs one request through a handler, end to end. A handler that throws, or
|
|
22
|
+
* returns something other than a Response, answers 500; the error is never
|
|
23
|
+
* shown to the client.
|
|
24
|
+
*/
|
|
25
|
+
export declare function dispatch(handler: FetchHandler, env: TxcEnvelope, opts?: RequestOptions & DeltaOptions): Promise<TxcDelta>;
|
package/dist/bridge.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// The envelope ↔ Fetch bridge. A runner hands it the chassis's request
|
|
2
|
+
// envelope; it builds a Fetch Request, calls the server entry, and turns the
|
|
3
|
+
// Response into the delta the chassis merges. Every runner uses this one
|
|
4
|
+
// mapping, so a handler sees the same Request wherever it runs.
|
|
5
|
+
/** An op answer is capped at 4 MiB (--op-payload-max); the body is base64 inside it. */
|
|
6
|
+
export const DEFAULT_MAX_ANSWER_BYTES = 3 * 1024 * 1024;
|
|
7
|
+
// Hop-by-hop headers (RFC 9110 §7.6.1) and those the Request computes.
|
|
8
|
+
const DROPPED_HEADERS = new Set([
|
|
9
|
+
"connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer",
|
|
10
|
+
"upgrade", "content-length", "host",
|
|
11
|
+
]);
|
|
12
|
+
/** Builds the Fetch Request an envelope describes. */
|
|
13
|
+
export function envelopeToRequest(env, opts = {}) {
|
|
14
|
+
const req = env._txc?.web?.req ?? {};
|
|
15
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
16
|
+
let url = req.url?.full;
|
|
17
|
+
if (!url) {
|
|
18
|
+
const host = req.host ?? "localhost";
|
|
19
|
+
const raw = req.url?.query?.raw;
|
|
20
|
+
url = `http://${host}${req.url?.path ?? "/"}${raw ? "?" + raw : ""}`;
|
|
21
|
+
}
|
|
22
|
+
const headers = new Headers();
|
|
23
|
+
for (const [name, value] of Object.entries(req.headers ?? {})) {
|
|
24
|
+
if (DROPPED_HEADERS.has(name.toLowerCase()))
|
|
25
|
+
continue;
|
|
26
|
+
for (const v of Array.isArray(value) ? value : [value])
|
|
27
|
+
headers.append(name, v);
|
|
28
|
+
}
|
|
29
|
+
let body;
|
|
30
|
+
if (req.body && method !== "GET" && method !== "HEAD") {
|
|
31
|
+
const bytes = Buffer.from(req.body, "base64");
|
|
32
|
+
if (opts.maxBodyBytes !== undefined && bytes.byteLength > opts.maxBodyBytes) {
|
|
33
|
+
throw new Error(`request body is ${bytes.byteLength} bytes, over ${opts.maxBodyBytes}`);
|
|
34
|
+
}
|
|
35
|
+
body = new ArrayBuffer(bytes.byteLength);
|
|
36
|
+
new Uint8Array(body).set(bytes);
|
|
37
|
+
}
|
|
38
|
+
return new Request(url, { method, headers, body });
|
|
39
|
+
}
|
|
40
|
+
/** The handler's context: only what the contract defines. */
|
|
41
|
+
export function contextFrom(env) {
|
|
42
|
+
return Object.freeze({ client: Object.freeze({ ip: env._txc?.client?.ip ?? "" }) });
|
|
43
|
+
}
|
|
44
|
+
/** Turns a Response into the chassis delta. */
|
|
45
|
+
export async function responseToDelta(res, opts = {}) {
|
|
46
|
+
const headers = {};
|
|
47
|
+
res.headers.forEach((value, name) => {
|
|
48
|
+
if (name === "set-cookie")
|
|
49
|
+
return; // each cookie on its own line, below
|
|
50
|
+
(headers[name] ??= []).push(value);
|
|
51
|
+
});
|
|
52
|
+
const cookies = res.headers.getSetCookie();
|
|
53
|
+
if (cookies.length > 0)
|
|
54
|
+
headers["set-cookie"] = cookies;
|
|
55
|
+
const delta = { _txc: { web: { res: { status: res.status, headers } }, halt: true } };
|
|
56
|
+
const noBody = (opts.method ?? "GET").toUpperCase() === "HEAD" || res.status === 204 || res.status === 304;
|
|
57
|
+
if (!noBody) {
|
|
58
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
59
|
+
const max = opts.maxAnswerBytes ?? DEFAULT_MAX_ANSWER_BYTES;
|
|
60
|
+
if (bytes.byteLength > max) {
|
|
61
|
+
throw new Error(`response body is ${bytes.byteLength} bytes, over the ${max}-byte answer limit`);
|
|
62
|
+
}
|
|
63
|
+
if (bytes.byteLength > 0)
|
|
64
|
+
delta._txc.web.res.body = bytes.toString("base64");
|
|
65
|
+
}
|
|
66
|
+
return delta;
|
|
67
|
+
}
|
|
68
|
+
function errorDelta(status, message, method) {
|
|
69
|
+
const res = { status, headers: { "content-type": ["text/plain; charset=utf-8"] } };
|
|
70
|
+
if (method.toUpperCase() !== "HEAD")
|
|
71
|
+
res.body = Buffer.from(message + "\n").toString("base64");
|
|
72
|
+
return { _txc: { web: { res }, halt: true } };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Runs one request through a handler, end to end. A handler that throws, or
|
|
76
|
+
* returns something other than a Response, answers 500; the error is never
|
|
77
|
+
* shown to the client.
|
|
78
|
+
*/
|
|
79
|
+
export async function dispatch(handler, env, opts = {}) {
|
|
80
|
+
const method = env._txc?.web?.req?.method ?? "GET";
|
|
81
|
+
let request;
|
|
82
|
+
try {
|
|
83
|
+
request = envelopeToRequest(env, opts);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return errorDelta(413, "request body too large", method);
|
|
87
|
+
}
|
|
88
|
+
let res;
|
|
89
|
+
try {
|
|
90
|
+
res = await handler.fetch(request, contextFrom(env));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return errorDelta(500, "internal error", method);
|
|
94
|
+
}
|
|
95
|
+
if (!(res instanceof Response))
|
|
96
|
+
return errorDelta(500, "internal error", method);
|
|
97
|
+
try {
|
|
98
|
+
return await responseToDelta(res, { ...opts, method: request.method });
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return errorDelta(502, "response too large", method);
|
|
102
|
+
}
|
|
103
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// txco-web-abi: validate a manifest, check a build's server/, or serve a
|
|
3
|
+
// build locally.
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { checkServer, serve } from "./harness.js";
|
|
7
|
+
import { MANIFEST_NAME, validateManifest } from "./manifest.js";
|
|
8
|
+
const USAGE = `Usage: txco-web-abi <command> <abi-dir>
|
|
9
|
+
|
|
10
|
+
Commands:
|
|
11
|
+
validate <abi-dir> check txco-web.json against the Web ABI schema
|
|
12
|
+
check-server <abi-dir> [--json] drive the build's server/ entry through the bridge
|
|
13
|
+
serve <abi-dir> [--port N] serve public/ and server/ locally
|
|
14
|
+
`;
|
|
15
|
+
async function main(argv) {
|
|
16
|
+
const [cmd, dir, ...rest] = argv;
|
|
17
|
+
if (!cmd || !dir) {
|
|
18
|
+
process.stderr.write(USAGE);
|
|
19
|
+
return 2;
|
|
20
|
+
}
|
|
21
|
+
switch (cmd) {
|
|
22
|
+
case "validate": {
|
|
23
|
+
let doc;
|
|
24
|
+
try {
|
|
25
|
+
doc = JSON.parse(await readFile(join(dir, MANIFEST_NAME), "utf8"));
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
process.stderr.write(`${MANIFEST_NAME}: ${e.message}\n`);
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
const r = validateManifest(doc);
|
|
32
|
+
if (r.ok) {
|
|
33
|
+
process.stdout.write(`${MANIFEST_NAME}: ok\n`);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
for (const p of r.errors)
|
|
37
|
+
process.stdout.write(`${p.pointer || "/"}: ${p.message}\n`);
|
|
38
|
+
return 1;
|
|
39
|
+
}
|
|
40
|
+
case "check-server": {
|
|
41
|
+
const results = await checkServer(dir);
|
|
42
|
+
if (rest.includes("--json")) {
|
|
43
|
+
process.stdout.write(JSON.stringify({ ok: results.every((r) => r.ok), results }, null, 2) + "\n");
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
for (const r of results)
|
|
47
|
+
process.stdout.write(`${r.ok ? "✓" : "✗"} ${r.name}${r.detail ? " " + r.detail : ""}\n`);
|
|
48
|
+
}
|
|
49
|
+
return results.every((r) => r.ok) ? 0 : 1;
|
|
50
|
+
}
|
|
51
|
+
case "serve": {
|
|
52
|
+
const i = rest.indexOf("--port");
|
|
53
|
+
const port = i >= 0 ? Number(rest[i + 1]) : 8787;
|
|
54
|
+
const server = await serve(dir, { port });
|
|
55
|
+
const addr = server.address();
|
|
56
|
+
process.stdout.write(`serving ${dir} on http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : port}\n`);
|
|
57
|
+
return await new Promise(() => { }); // until interrupted
|
|
58
|
+
}
|
|
59
|
+
default:
|
|
60
|
+
process.stderr.write(USAGE);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
main(process.argv.slice(2)).then((code) => process.exit(code), (e) => {
|
|
65
|
+
process.stderr.write(`txco-web-abi: ${e.message}\n`);
|
|
66
|
+
process.exit(1);
|
|
67
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** The parts of the chassis's request envelope the bridge reads. */
|
|
2
|
+
export interface TxcEnvelope {
|
|
3
|
+
_txc?: {
|
|
4
|
+
client?: {
|
|
5
|
+
ip?: string;
|
|
6
|
+
};
|
|
7
|
+
web?: {
|
|
8
|
+
req?: {
|
|
9
|
+
method?: string;
|
|
10
|
+
host?: string;
|
|
11
|
+
url?: {
|
|
12
|
+
full?: string;
|
|
13
|
+
path?: string;
|
|
14
|
+
query?: {
|
|
15
|
+
raw?: string;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
/** Header name → values, one per line. */
|
|
19
|
+
headers?: Record<string, string[] | string>;
|
|
20
|
+
/** The body, base64; absent when empty. */
|
|
21
|
+
body?: string;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
[k: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** The response half: what an op writes to answer an HTTP request. */
|
|
28
|
+
export interface TxcWebRes {
|
|
29
|
+
status: number;
|
|
30
|
+
/** Lower-case header name → values. */
|
|
31
|
+
headers: Record<string, string[]>;
|
|
32
|
+
/** The body, base64; absent for HEAD, 204 and 304. */
|
|
33
|
+
body?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The bridge's answer: a delta the chassis merges into the run, never the
|
|
37
|
+
* envelope echoed back (op answers merge by appending arrays, so an echo
|
|
38
|
+
* would duplicate every header).
|
|
39
|
+
*/
|
|
40
|
+
export interface TxcDelta {
|
|
41
|
+
_txc: {
|
|
42
|
+
web: {
|
|
43
|
+
res: TxcWebRes;
|
|
44
|
+
};
|
|
45
|
+
halt: true;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** What a server entry gets beside the Request. Deliberately minimal. */
|
|
49
|
+
export interface TxcContext {
|
|
50
|
+
readonly client: {
|
|
51
|
+
readonly ip: string;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** The server/ entry's default export. */
|
|
55
|
+
export interface FetchHandler {
|
|
56
|
+
fetch(request: Request, ctx: TxcContext): Response | Promise<Response>;
|
|
57
|
+
}
|
package/dist/envelope.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
import type { FetchHandler, TxcEnvelope } from "./envelope.js";
|
|
3
|
+
/** Imports a build's server entry and checks its default export. */
|
|
4
|
+
export declare function loadServer(abiDir: string): Promise<FetchHandler>;
|
|
5
|
+
/** Builds an envelope the way the chassis's web head does, for a request. */
|
|
6
|
+
export declare function envelopeFor(method: string, path: string, init?: {
|
|
7
|
+
headers?: Record<string, string[]>;
|
|
8
|
+
body?: Uint8Array;
|
|
9
|
+
host?: string;
|
|
10
|
+
ip?: string;
|
|
11
|
+
}): TxcEnvelope;
|
|
12
|
+
export interface CheckResult {
|
|
13
|
+
name: string;
|
|
14
|
+
ok: boolean;
|
|
15
|
+
detail?: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Drives a server entry with the requests every handler must answer, through
|
|
19
|
+
* the bridge, and checks each answer is a valid delta: a status in
|
|
20
|
+
* 100–599, headers as arrays, no echo of the request envelope, a body only
|
|
21
|
+
* where one is allowed.
|
|
22
|
+
*/
|
|
23
|
+
export declare function checkServer(abiDir: string): Promise<CheckResult[]>;
|
|
24
|
+
/**
|
|
25
|
+
* Serves a build locally: public/ files first (as the chassis's static
|
|
26
|
+
* serving answers first), everything else through the bridge to server/.
|
|
27
|
+
* For local development; not a chassis.
|
|
28
|
+
*/
|
|
29
|
+
export declare function serve(abiDir: string, opts?: {
|
|
30
|
+
port?: number;
|
|
31
|
+
host?: string;
|
|
32
|
+
}): Promise<Server>;
|
package/dist/harness.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// The harness: load a build's server/ entry and check it honours the
|
|
2
|
+
// contract, before any runner exists; and serve a build locally behind the
|
|
3
|
+
// same bridge a runner will use.
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { readFile, stat } from "node:fs/promises";
|
|
6
|
+
import { extname, join, normalize, sep } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { dispatch } from "./bridge.js";
|
|
9
|
+
import { readManifest } from "./manifest.js";
|
|
10
|
+
/** Imports a build's server entry and checks its default export. */
|
|
11
|
+
export async function loadServer(abiDir) {
|
|
12
|
+
const m = await readManifest(abiDir);
|
|
13
|
+
if (!m.server)
|
|
14
|
+
throw new Error("the manifest names no server.entry: this is a static build");
|
|
15
|
+
const mod = await import(pathToFileURL(join(abiDir, m.server.entry)).href);
|
|
16
|
+
const h = mod.default;
|
|
17
|
+
if (!h || typeof h.fetch !== "function") {
|
|
18
|
+
throw new Error(`${m.server.entry}: the default export must be { fetch(request, ctx) }`);
|
|
19
|
+
}
|
|
20
|
+
return h;
|
|
21
|
+
}
|
|
22
|
+
/** Builds an envelope the way the chassis's web head does, for a request. */
|
|
23
|
+
export function envelopeFor(method, path, init = {}) {
|
|
24
|
+
const host = init.host ?? "localhost";
|
|
25
|
+
const q = path.indexOf("?");
|
|
26
|
+
return {
|
|
27
|
+
_txc: {
|
|
28
|
+
client: { ip: init.ip ?? "127.0.0.1" },
|
|
29
|
+
web: {
|
|
30
|
+
req: {
|
|
31
|
+
method,
|
|
32
|
+
host,
|
|
33
|
+
url: { full: `http://${host}${path}`, path: q < 0 ? path : path.slice(0, q), query: { raw: q < 0 ? "" : path.slice(q + 1) } },
|
|
34
|
+
headers: init.headers ?? {},
|
|
35
|
+
body: init.body && init.body.byteLength > 0 ? Buffer.from(init.body).toString("base64") : undefined,
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Drives a server entry with the requests every handler must answer, through
|
|
43
|
+
* the bridge, and checks each answer is a valid delta: a status in
|
|
44
|
+
* 100–599, headers as arrays, no echo of the request envelope, a body only
|
|
45
|
+
* where one is allowed.
|
|
46
|
+
*/
|
|
47
|
+
export async function checkServer(abiDir) {
|
|
48
|
+
const results = [];
|
|
49
|
+
let handler;
|
|
50
|
+
try {
|
|
51
|
+
handler = await loadServer(abiDir);
|
|
52
|
+
results.push({ name: "load", ok: true });
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
return [{ name: "load", ok: false, detail: e.message }];
|
|
56
|
+
}
|
|
57
|
+
const probes = [
|
|
58
|
+
["GET /", envelopeFor("GET", "/", { headers: { accept: ["text/html"] } }), "GET"],
|
|
59
|
+
["GET unknown page", envelopeFor("GET", "/txco-web-abi-check-unknown", { headers: { accept: ["text/html"] } }), "GET"],
|
|
60
|
+
["POST unknown", envelopeFor("POST", "/txco-web-abi-check-unknown", { headers: { "content-type": ["application/json"] }, body: new TextEncoder().encode("{}") }), "POST"],
|
|
61
|
+
["HEAD /", envelopeFor("HEAD", "/"), "HEAD"],
|
|
62
|
+
];
|
|
63
|
+
for (const [name, env, method] of probes) {
|
|
64
|
+
const delta = await dispatch(handler, env);
|
|
65
|
+
const res = delta?._txc?.web?.res;
|
|
66
|
+
const problems = [];
|
|
67
|
+
if (!res || !Number.isInteger(res.status) || res.status < 100 || res.status > 599)
|
|
68
|
+
problems.push("no valid status");
|
|
69
|
+
if (res && Object.values(res.headers).some((v) => !Array.isArray(v)))
|
|
70
|
+
problems.push("headers must be arrays");
|
|
71
|
+
if (delta._txc.web.req !== undefined)
|
|
72
|
+
problems.push("the answer echoes the request");
|
|
73
|
+
if (method === "HEAD" && res?.body)
|
|
74
|
+
problems.push("a HEAD answer carries a body");
|
|
75
|
+
if (res?.status === 500 && (method === "HEAD" || (res.body && Buffer.from(res.body, "base64").toString() === "internal error\n"))) {
|
|
76
|
+
problems.push("the handler threw or returned no Response (a 500 from the bridge)");
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
JSON.stringify(delta);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
problems.push("the delta isn't serialisable");
|
|
83
|
+
}
|
|
84
|
+
results.push({ name, ok: problems.length === 0, detail: problems.join("; ") || `→ ${res?.status}` });
|
|
85
|
+
}
|
|
86
|
+
return results;
|
|
87
|
+
}
|
|
88
|
+
const TYPES = {
|
|
89
|
+
".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript",
|
|
90
|
+
".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg",
|
|
91
|
+
".webp": "image/webp", ".ico": "image/x-icon", ".txt": "text/plain; charset=utf-8", ".woff2": "font/woff2",
|
|
92
|
+
};
|
|
93
|
+
async function readBody(req) {
|
|
94
|
+
const chunks = [];
|
|
95
|
+
for await (const c of req)
|
|
96
|
+
chunks.push(c);
|
|
97
|
+
return Buffer.concat(chunks);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Serves a build locally: public/ files first (as the chassis's static
|
|
101
|
+
* serving answers first), everything else through the bridge to server/.
|
|
102
|
+
* For local development; not a chassis.
|
|
103
|
+
*/
|
|
104
|
+
export async function serve(abiDir, opts = {}) {
|
|
105
|
+
const handler = await loadServer(abiDir);
|
|
106
|
+
const pub = join(abiDir, "public");
|
|
107
|
+
const server = createServer(async (req, res) => {
|
|
108
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
109
|
+
const path = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
110
|
+
if (method === "GET" || method === "HEAD") {
|
|
111
|
+
const segs = path.split("/").filter(Boolean);
|
|
112
|
+
if (!segs.some((s) => s.startsWith("."))) {
|
|
113
|
+
const file = normalize(join(pub, ...segs, path.endsWith("/") ? "index.html" : ""));
|
|
114
|
+
if (file.startsWith(pub + sep) || file === pub) {
|
|
115
|
+
try {
|
|
116
|
+
if ((await stat(file)).isFile()) {
|
|
117
|
+
const bytes = await readFile(file);
|
|
118
|
+
res.writeHead(200, { "content-type": TYPES[extname(file)] ?? "application/octet-stream" });
|
|
119
|
+
res.end(method === "HEAD" ? undefined : bytes);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// not a file: the server answers
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const headers = {};
|
|
130
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
131
|
+
(headers[req.rawHeaders[i].toLowerCase()] ??= []).push(req.rawHeaders[i + 1]);
|
|
132
|
+
}
|
|
133
|
+
const delta = await dispatch(handler, envelopeFor(method, req.url ?? "/", {
|
|
134
|
+
headers, body: await readBody(req), host: req.headers.host, ip: req.socket.remoteAddress ?? "",
|
|
135
|
+
}));
|
|
136
|
+
const out = delta._txc.web.res;
|
|
137
|
+
for (const [name, values] of Object.entries(out.headers))
|
|
138
|
+
res.setHeader(name, values);
|
|
139
|
+
res.writeHead(out.status);
|
|
140
|
+
res.end(out.body ? Buffer.from(out.body, "base64") : undefined);
|
|
141
|
+
});
|
|
142
|
+
await new Promise((resolve) => server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", resolve));
|
|
143
|
+
return server;
|
|
144
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The manifest's file name at the root of an ABI directory. */
|
|
2
|
+
export declare const MANIFEST_NAME = "txco-web.json";
|
|
3
|
+
/** The manifest's abi value this kit reads. */
|
|
4
|
+
export declare const ABI_VERSION = 1;
|
|
5
|
+
/** Producers' ops live in the band starting here, after every author op. */
|
|
6
|
+
export declare const PRODUCER_SCOPE = 900000;
|
|
7
|
+
export interface Manifest {
|
|
8
|
+
abi: 1;
|
|
9
|
+
server?: {
|
|
10
|
+
entry: string;
|
|
11
|
+
};
|
|
12
|
+
immutable?: string[];
|
|
13
|
+
[extension: `x-${string}`]: unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface Problem {
|
|
16
|
+
/** A JSON pointer into the manifest ("" is the root). */
|
|
17
|
+
pointer: string;
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
export type ValidationResult = {
|
|
21
|
+
ok: true;
|
|
22
|
+
manifest: Manifest;
|
|
23
|
+
} | {
|
|
24
|
+
ok: false;
|
|
25
|
+
errors: Problem[];
|
|
26
|
+
};
|
|
27
|
+
/** Validates a parsed manifest. */
|
|
28
|
+
export declare function validateManifest(doc: unknown): ValidationResult;
|
|
29
|
+
/** Reads and validates <dir>/txco-web.json. Throws on an unreadable or invalid manifest. */
|
|
30
|
+
export declare function readManifest(dir: string): Promise<Manifest>;
|
|
31
|
+
/**
|
|
32
|
+
* The private root of a public/ path: cut at the end of its first "_"
|
|
33
|
+
* segment ("" when it has none). The installer writes one public marker per
|
|
34
|
+
* root, so `_app/x.js` → `_app`, `assets/_Dk3.js` → itself.
|
|
35
|
+
*/
|
|
36
|
+
export declare function publicRoot(rel: string): string;
|