@tinkered/entry 0.0.0-stage → 0.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # @tinkered/entry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The backend of a Tinker app. Code only: how to
4
+ use it is in the skills.
5
+
6
+ An app gets this code by version. It is not
7
+ copied into the app.
8
+
9
+ ## Entries
10
+
11
+ Each entry is named by the kind of program that
12
+ imports it:
13
+
14
+ - `@tinkered/entry/cmd`: a command, a program
15
+ with no port.
16
+ - `@tinkered/entry/server`: a server, a program
17
+ that listens on a port.
18
+
19
+ Later, one entry per runtime:
20
+
21
+ - `@tinkered/entry/bun`: Bun, from
22
+ `@tinkered/bun`.
23
+ - `@tinkered/entry/node`: Node.
24
+
25
+ ## A page cannot import an entry
26
+
27
+ Each entry is backend code.
28
+ A page bundler reads the `browser` export
29
+ condition first.
30
+ For `cmd` and `server` it gets an empty file.
31
+
32
+ - A page that imports a value fails its build:
33
+ `"routes" is not exported by not-in-page.mjs`.
34
+ - A page that loads it anyway stops with
35
+ `BackendInPage`.
36
+ - `import type` still works.
37
+ - Bun and Node get the real code.
38
+
39
+ The model is Next.js `server-only`.
40
+
41
+ ## What each entry holds
42
+
43
+ `@tinkered/entry/cmd`:
44
+
45
+ - `defineMain`: types a command's main.
46
+ It runs nothing.
47
+ - `createMainHost`, `runMain`: the host.
48
+ It owns the signals and the exit code.
49
+ A main that answers with no `closed`
50
+ exits 1 with `MainClosedMissing`.
51
+ - `observeServerPanics`: an unhandled
52
+ rejection closes the root, then exits 1.
53
+ - The types `MainClosed`, `MainContext`,
54
+ `MainStarted`, from `@tinkered/bun`, so a
55
+ command has one place to import from.
56
+
57
+ `@tinkered/entry/server`:
58
+
59
+ - `routes`: the route table, one session per
60
+ request.
61
+ - `requestStop`: aborts when the request
62
+ ends.
63
+ - `backendStop`: aborts when the server
64
+ stops.
65
+ - `requestBody`: the request's body reader.
66
+ - `http`, `httpRequest`, `httpBackend`:
67
+ outbound HTTP.
68
+ - `health`, `baseVersion`: the health route
69
+ and this package's version.
70
+ - `Errors`, `isError`: the kinds this
71
+ package raises, `HttpRequestFailed`,
72
+ `MainClosedMissing`, `BackendInPage`, and
73
+ their payloads.
74
+ - `abortReasons`: the shared abort reason
75
+ `closed`.
76
+
77
+ `zod` is a peer: the server entry needs it.
78
+
79
+ ## A server command
80
+
81
+ ```ts
82
+ import { serve } from "@tinkered/bun";
83
+ import { createScope } from "@tinkered/core";
84
+ import {
85
+ defineMain,
86
+ observeServerPanics,
87
+ } from "@tinkered/entry/cmd";
88
+ import {
89
+ health,
90
+ routes,
91
+ } from "@tinkered/entry/server";
92
+
93
+ export default defineMain(
94
+ async ({ env, signal, stderr, exit }) => {
95
+ const table = routes({
96
+ stop: signal,
97
+ table: { "GET /api/health": health },
98
+ });
99
+ const app = createScope({
100
+ signal,
101
+ capsules: [
102
+ serve({
103
+ port: Number(env.PORT ?? 4318),
104
+ pages: {},
105
+ handlers: [table],
106
+ }),
107
+ table,
108
+ ],
109
+ });
110
+
111
+ const live = await app.ready;
112
+ live.onClose(
113
+ observeServerPanics(
114
+ exit.bind(null, 1),
115
+ app.closed,
116
+ stderr,
117
+ ),
118
+ );
119
+ return app;
120
+ },
121
+ );
122
+ ```
123
+
124
+ `run` from `@tinkered/bun`, or `runMain`,
125
+ starts it.
126
+
127
+ ## State
128
+
129
+ The code moved in from the template
130
+ `lagz0ne/tinker-app` at d13daed. The names
131
+ and behavior are the template's.
package/dist/cmd.d.mts ADDED
@@ -0,0 +1,73 @@
1
+ import { MainClosed, MainContext, MainStarted } from "@tinkered/bun";
2
+ //#region src/cmd/main.d.ts
3
+ /**
4
+ * Type-only entry marker, with no startup, state, or hidden error policy. Plain, not an
5
+ * operation: it gives a command's main its input type and runs nothing.
6
+ */
7
+ export declare const defineMain: <R extends MainStarted>(main: (ctx: MainContext) => R | Promise<R>) => (ctx: MainContext) => R | Promise<R>;
8
+ //#endregion
9
+ //#region src/cmd/main-host.d.ts
10
+ type Output = MainContext["stdout"] & {
11
+ writable?: boolean;
12
+ destroyed?: boolean;
13
+ isTTY?: boolean;
14
+ write(chunk: string, done?: (error?: Error | null) => void): unknown;
15
+ on?(event: "error", listener: (error: unknown) => void): unknown;
16
+ off?(event: "error", listener: (error: unknown) => void): unknown;
17
+ };
18
+ /** A command's main, as `defineMain` gives it: it may answer at once or later. */
19
+ type Main<R> = (ctx: MainContext) => R | Promise<R>;
20
+ declare namespace MainHost {
21
+ type Options = {
22
+ env: MainContext["env"];
23
+ args?: readonly string[];
24
+ /** The folder the command runs in; the process folder when left out. */
25
+ cwd?: string;
26
+ stdout: Output;
27
+ stderr: Output;
28
+ /** How long a stopped command may take to close before the hard stop. */
29
+ graceMs?: number;
30
+ hardStop?: () => void;
31
+ /** Runs once the command returned, unless it already stopped. */
32
+ onStart?: (app: {
33
+ closed: MainClosed;
34
+ }, signal: AbortSignal) => unknown;
35
+ };
36
+ }
37
+ /**
38
+ * The command host, for a command with no port: a one-shot command such as `cmds/import.ts`, and
39
+ * the tests that run a command in process. Plain, not an operation: it runs before any scope
40
+ * exists. Only the command receives `exit`; a host stop aborts
41
+ * its signal. The first stop's code wins. A startup throw exits 78 for a config error (a missing
42
+ * tag or config key, a value that failed its schema, or a bad URL), else 1; a failed root exits 1.
43
+ * A failure prints one line: `command failed (exit <code>): <kind>: <payload>`, or the error's
44
+ * stack.
45
+ */
46
+ export declare function createMainHost<R extends {
47
+ closed: MainClosed;
48
+ }>(main: Main<R>, options: MainHost.Options): {
49
+ started: Promise<R>;
50
+ closed: Promise<number>;
51
+ signal: AbortSignal;
52
+ /** Only native host stops own these abort reasons; a command's exit does not. */
53
+ stop(next: number, reason?: unknown): void;
54
+ };
55
+ /**
56
+ * Run a command as a process: OS signals stop it (a closed terminal, SIGHUP, like Ctrl-C), and
57
+ * its code becomes the process exit code. Output whose reader is gone does not change that code.
58
+ * Plain, not an operation: it owns OS signals and the exit code.
59
+ */
60
+ export declare function runMain<R extends {
61
+ closed: MainClosed;
62
+ }>(main: Main<R>, options?: Partial<MainHost.Options>): Promise<number>;
63
+ //#endregion
64
+ //#region src/cmd/panics.d.ts
65
+ /**
66
+ * Report unhandled work, close through the caller, then leave with failure. Plain, not an
67
+ * operation: the process panic hook must report even when the root's own close fails.
68
+ */
69
+ export declare function observeServerPanics(abort: (error: unknown) => void, closed: Promise<unknown>, stderr: {
70
+ write(chunk: string): unknown;
71
+ }): () => void;
72
+ //#endregion
73
+ export type { MainClosed, MainContext, MainHost, MainStarted };
package/dist/cmd.mjs ADDED
@@ -0,0 +1,204 @@
1
+ import { r as raise } from "./errors-Ch7N6rzT.mjs";
2
+ import { inspect } from "node:util";
3
+ //#region src/cmd/main.ts
4
+ /**
5
+ * Type-only entry marker, with no startup, state, or hidden error policy. Plain, not an
6
+ * operation: it gives a command's main its input type and runs nothing.
7
+ */
8
+ const defineMain = (main) => main;
9
+ //#endregion
10
+ //#region src/cmd/main-host.ts
11
+ /** POSIX exit codes for a stop by signal: 128 plus the signal's number. */
12
+ const signalCodes = {
13
+ SIGHUP: 129,
14
+ SIGINT: 130,
15
+ SIGTERM: 143
16
+ };
17
+ /**
18
+ * The command host, for a command with no port: a one-shot command such as `cmds/import.ts`, and
19
+ * the tests that run a command in process. Plain, not an operation: it runs before any scope
20
+ * exists. Only the command receives `exit`; a host stop aborts
21
+ * its signal. The first stop's code wins. A startup throw exits 78 for a config error (a missing
22
+ * tag or config key, a value that failed its schema, or a bad URL), else 1; a failed root exits 1.
23
+ * A failure prints one line: `command failed (exit <code>): <kind>: <payload>`, or the error's
24
+ * stack.
25
+ */
26
+ function createMainHost(main, options) {
27
+ const { env, args = [], cwd = process.cwd(), stdout, stderr, graceMs = 1e4 } = options;
28
+ const hardStop = options.hardStop ?? (() => process.kill(process.pid, "SIGKILL"));
29
+ const controller = new AbortController();
30
+ const printed = /* @__PURE__ */ new Set();
31
+ const hostReasons = /* @__PURE__ */ new WeakSet();
32
+ /** The first stop's code; `stopped` says there was one. */
33
+ let code = 0;
34
+ let stopped = false;
35
+ let savedReason;
36
+ let timer;
37
+ let finished = false;
38
+ /** The first stop starts the grace timer: a command still open when it ends gets the hard stop. */
39
+ const startGrace = () => {
40
+ timer = setTimeout(hardStop, graceMs);
41
+ timer.unref?.();
42
+ };
43
+ controller.signal.addEventListener("abort", startGrace);
44
+ /**
45
+ * The first stop sets the code and prints a failing reason; a later one prints a new reason as
46
+ * late. Each reason prints once, and a host stop's own reason never. The code is set before the
47
+ * print, so a stop from inside the print (a getter, a `toJSON`) is late. A broken output stream
48
+ * must not block abort or the grace deadline, so a failed write is left as is.
49
+ */
50
+ const stop = (next, reason) => {
51
+ if (reason === void 0) {
52
+ const own = new DOMException("Command stopped", "AbortError");
53
+ hostReasons.add(own);
54
+ reason = own;
55
+ }
56
+ const late = stopped || finished;
57
+ if (late && reason === savedReason) return;
58
+ const prefix = late ? `after exit ${code}` : `command failed (exit ${next})`;
59
+ if (!late) {
60
+ stopped = true;
61
+ code = next;
62
+ savedReason = reason;
63
+ }
64
+ [reason].filter((given) => (late || next !== 0) && given != null && !printed.has(given) && !hostReasons.has(Object(given))).forEach((given) => {
65
+ printed.add(given);
66
+ const value = Object(given);
67
+ const { kind, payload, stack } = value;
68
+ /**
69
+ * Error text is best effort; a bad payload must never interrupt a stop. The stack (or the
70
+ * reason's text) is the fallback when the payload cannot print, and a fixed line when
71
+ * neither can.
72
+ */
73
+ let detail = "Unprintable command failure";
74
+ try {
75
+ detail = stack ?? String(value);
76
+ } catch {}
77
+ try {
78
+ if (next !== 1 && kind && payload) detail = `${kind}: ${JSON.stringify(payload)}`;
79
+ } catch {}
80
+ try {
81
+ stderr.write(`${prefix}: ${detail}\n`);
82
+ } catch {}
83
+ });
84
+ if (late) return;
85
+ controller.abort(reason);
86
+ };
87
+ const started = Promise.resolve().then(() => main({
88
+ env,
89
+ args,
90
+ cwd,
91
+ signal: controller.signal,
92
+ stdout,
93
+ stderr,
94
+ exit: stop
95
+ }));
96
+ return {
97
+ started,
98
+ closed: started.then(async (app) => {
99
+ return Promise.resolve().then(async () => {
100
+ if (!(app?.closed instanceof Promise)) raise("MainClosedMissing", {});
101
+ if (!controller.signal.aborted) await options.onStart?.(app, controller.signal);
102
+ const failure = [await app.closed ?? []].flat().flatMap((end) => end.status === "failed" ? [end.error] : end.teardownErrors ?? []).at(0);
103
+ if (failure === void 0) return false;
104
+ stop(1, failure);
105
+ return true;
106
+ }).catch(async (error) => {
107
+ /** A stop's own reason is no failure; a close error that is not this error prints late. */
108
+ let failed = !controller.signal.aborted || error !== controller.signal.reason;
109
+ if (failed) stop(1, error);
110
+ if (!(app?.closed instanceof Promise)) return failed;
111
+ await app.closed.catch((cleanup) => {
112
+ if (cleanup === error) return;
113
+ failed = true;
114
+ stop(1, cleanup);
115
+ });
116
+ return failed;
117
+ });
118
+ }, (error) => {
119
+ /** A startup throw: 78 for a config error, else 1. A stop's own reason is no failure. */
120
+ const failed = !controller.signal.aborted || error !== controller.signal.reason;
121
+ const config = [
122
+ "MissingTag",
123
+ "MissingConfig",
124
+ "DataValidationFailed"
125
+ ].includes(Object(error).kind);
126
+ if (failed) stop(config || Object(error).code === "ERR_INVALID_URL" ? 78 : 1, error);
127
+ return failed;
128
+ }).then(async (failed) => {
129
+ for (const stream of [stdout, stderr]) await new Promise((resolve, reject) => {
130
+ if (typeof stream.writable !== "boolean" || stream.destroyed) return resolve();
131
+ stream.write("", (error) => error ? reject(error) : resolve());
132
+ }).catch((error) => {
133
+ /**
134
+ * A gone reader is no failure: a closed pipe (EPIPE), or a closed terminal (EIO on a
135
+ * terminal). On a file or a pipe, EIO is a real write failure.
136
+ */
137
+ const { code: why } = Object(error);
138
+ if (why !== "EPIPE" && !(why === "EIO" && stream.isTTY === true)) failed = true;
139
+ });
140
+ finished = true;
141
+ clearTimeout(timer);
142
+ if (stopped) return code;
143
+ return failed ? 1 : 0;
144
+ }),
145
+ signal: controller.signal,
146
+ /** Only native host stops own these abort reasons; a command's exit does not. */
147
+ stop(next, reason) {
148
+ if (reason instanceof DOMException && reason.name === "AbortError") hostReasons.add(reason);
149
+ stop(next, reason);
150
+ }
151
+ };
152
+ }
153
+ /**
154
+ * Run a command as a process: OS signals stop it (a closed terminal, SIGHUP, like Ctrl-C), and
155
+ * its code becomes the process exit code. Output whose reader is gone does not change that code.
156
+ * Plain, not an operation: it owns OS signals and the exit code.
157
+ */
158
+ async function runMain(main, options = {}) {
159
+ const inputs = {
160
+ env: process.env,
161
+ args: process.argv.slice(2),
162
+ cwd: process.cwd(),
163
+ stdout: process.stdout,
164
+ stderr: process.stderr,
165
+ ...options
166
+ };
167
+ const host = createMainHost(main, inputs);
168
+ const stops = Object.entries(signalCodes).map(([name, exitCode]) => [name, () => host.stop(exitCode, new DOMException(name, "AbortError"))]);
169
+ for (const [name, handler] of stops) process.on(name, handler);
170
+ const quiet = (error) => {
171
+ const { code } = Object(error);
172
+ if (code !== "EPIPE" && !(code === "EIO" && inputs.stdout.isTTY === true)) throw error;
173
+ };
174
+ inputs.stdout.on?.("error", quiet);
175
+ inputs.stderr.on?.("error", quiet);
176
+ try {
177
+ process.exitCode = await host.closed;
178
+ return process.exitCode;
179
+ } finally {
180
+ for (const [name, handler] of stops) process.off(name, handler);
181
+ inputs.stdout.off?.("error", quiet);
182
+ inputs.stderr.off?.("error", quiet);
183
+ }
184
+ }
185
+ //#endregion
186
+ //#region src/cmd/panics.ts
187
+ /**
188
+ * Report unhandled work, close through the caller, then leave with failure. Plain, not an
189
+ * operation: the process panic hook must report even when the root's own close fails.
190
+ */
191
+ function observeServerPanics(abort, closed, stderr) {
192
+ const fail = async (error) => {
193
+ try {
194
+ abort(error);
195
+ await closed;
196
+ } catch (cleanup) {
197
+ stderr.write(`server close failed: ${inspect(cleanup)}\n`);
198
+ }
199
+ };
200
+ process.on("unhandledRejection", fail);
201
+ return process.off.bind(process, "unhandledRejection", fail);
202
+ }
203
+ //#endregion
204
+ export { createMainHost, defineMain, observeServerPanics, runMain };
@@ -0,0 +1,16 @@
1
+ //#region src/errors.ts
2
+ /** The only place this package throws a registry error itself; an operation uses `ctx.raise`. */
3
+ function raise(kind, payload) {
4
+ throw Object.assign(new Error(kind), {
5
+ kind,
6
+ payload
7
+ });
8
+ }
9
+ /** Narrow an unknown error to one registry entry; callers rethrow on mismatch. */
10
+ function isError(value, kind) {
11
+ return value instanceof Error && "kind" in value && value.kind === kind;
12
+ }
13
+ /** Abort consumers keep the native AbortError name and code without a per-call stack. */
14
+ const abortReasons = { closed: new DOMException("The owner closed", "AbortError") };
15
+ //#endregion
16
+ export { isError as n, raise as r, abortReasons as t };
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,11 @@
1
+ import { r as raise } from "./errors-Ch7N6rzT.mjs";
2
+ //#region src/not-in-page.ts
3
+ /**
4
+ * What a page bundler gets for `@tinkered/entry/cmd` and `/server`: the `browser` export
5
+ * condition points here. It exports nothing, so a page build that names a backend export
6
+ * fails; a page that loads it anyway stops at the first line. Precedent: Next.js
7
+ * `server-only`.
8
+ */
9
+ raise("BackendInPage", {});
10
+ //#endregion
11
+ export {};
@@ -0,0 +1,134 @@
1
+ import { Ns, Operation as Operation$1, Scope } from "@tinkered/core";
2
+ import { z } from "zod";
3
+ //#region src/errors.d.ts
4
+ /** The registry: this package raises no error of its own outside it. */
5
+ type Payloads = {
6
+ /** Sending an HTTP request, or reading its reply, failed; an HTTP status is a result. */
7
+ HttpRequestFailed: {
8
+ method: string;
9
+ path: string;
10
+ cause?: {
11
+ name?: string;
12
+ code?: string | number;
13
+ };
14
+ };
15
+ /** A command's main answered with no `closed` promise, so the host cannot wait for its root. */
16
+ MainClosedMissing: Record<string, never>;
17
+ /** A page loaded a backend entry; only a program on Bun or Node may import it. */
18
+ BackendInPage: Record<string, never>;
19
+ };
20
+ declare namespace Errors {
21
+ type Name = keyof Payloads;
22
+ type Payload<N extends Name> = Payloads[N];
23
+ type Of<N extends Name = Name> = Error & {
24
+ kind: N;
25
+ payload: Payloads[N];
26
+ };
27
+ /** Core's `ctx.raise`, typed to this registry: the kind picks the payload. */
28
+ type Raise = <N extends Name>(kind: N, payload: Payloads[N]) => never;
29
+ }
30
+ /** Narrow an unknown error to one registry entry; callers rethrow on mismatch. */
31
+ export declare function isError<N extends Errors.Name>(value: unknown, kind: N): value is Errors.Of<N>;
32
+ /** Abort consumers keep the native AbortError name and code without a per-call stack. */
33
+ export declare const abortReasons: {
34
+ closed: DOMException;
35
+ };
36
+ //#endregion
37
+ //#region src/server/health.d.ts
38
+ /** This package's version, read from its package.json when it is built. */
39
+ export declare const baseVersion: string;
40
+ export declare const health: import("@tinkered/core").Operation.Handle<{
41
+ ok: boolean;
42
+ base: string;
43
+ }, void>;
44
+ //#endregion
45
+ //#region src/server/backend.d.ts
46
+ /**
47
+ * The one way out for HTTP components send themselves; tests bind a fake (ADR 0102). Its default is
48
+ * the real `fetch`: an effect default on the seam, as ADR 0113 allows.
49
+ */
50
+ export declare const httpBackend: import("@tinkered/core").Tag.Defaulted<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>;
51
+ //#endregion
52
+ //#region src/server/http.d.ts
53
+ /** Closing this session or an ancestor ends HTTP waits before graceful work drains.
54
+ * Stop tags also end waits without closing a layer; caller cancellation keeps Core's result. */
55
+ export declare const http: import("@tinkered/core").Resource.Handle<{
56
+ send(url: string, init: RequestInit & {
57
+ signal: AbortSignal;
58
+ }): Promise<{
59
+ status: number;
60
+ headers: {
61
+ [k: string]: string[];
62
+ };
63
+ body: string;
64
+ }>;
65
+ }>;
66
+ /** HTTP statuses are results; only sending or reading failures raise HttpRequestFailed. */
67
+ export declare const httpRequest: import("@tinkered/core").Operation.Handle<Promise<{
68
+ status: number;
69
+ headers: {
70
+ [k: string]: string[];
71
+ };
72
+ body: string;
73
+ }>, {
74
+ url: string;
75
+ method: string;
76
+ headers?: Record<string, string> | undefined;
77
+ body?: string | undefined;
78
+ } & z.$brand<"HttpRequest">>;
79
+ //#endregion
80
+ //#region src/server/lifetime.d.ts
81
+ /** The main supplies its host signal before graceful drain joins held requests. */
82
+ export declare const backendStop: import("@tinkered/core").Tag.Handle<AbortSignal>;
83
+ /** Aborts when the request ends: Core's own tag, so every rpc transport binds the same one. */
84
+ export declare const requestStop: import("@tinkered/core").Tag.Handle<AbortSignal>;
85
+ //#endregion
86
+ //#region src/server/request-body.d.ts
87
+ /** The request owns the reader; its route borrows it until all body checks finish. */
88
+ export declare const requestBody: import("@tinkered/core").Resource.Handle<{
89
+ signal: AbortSignal;
90
+ open(body: ReadableStream<Uint8Array<ArrayBuffer>>): ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>;
91
+ release: () => Promise<void>;
92
+ }>;
93
+ //#endregion
94
+ //#region src/server/routes.d.ts
95
+ /** One row of the route table: `METHOD /path/{param}` names the operation that answers it. */
96
+ type Routes = Readonly<Record<`${string} /${string}`, Operation$1.Handle<any, any>>>;
97
+ /**
98
+ * The cmd's one route table, compiled once at start. A row with no param is one Map read by
99
+ * `METHOD /path`, as a static route in Hono's router; a row with a param keeps its URLPattern,
100
+ * matched once. The first row that fits wins, by table order, in both. A route's
101
+ * raw input is its query plus its path params. Its reply: a Response as is, nothing as 204, a
102
+ * value as JSON. Bad input is 400, a cancel 503, anything else 500. No row: undefined. A route
103
+ * that sent its reply early has answered: how its operation ends later changes no reply.
104
+ * Each request runs in its own session of `scope`: a valid `traceparent` makes the route's span
105
+ * its child; no header, or a bad one, starts a fresh trace. An early reply leaves that session
106
+ * open until the run ends. A row whose op has a `routes.ns` binding opens it in that namespace.
107
+ * A subflow the route op does not await is cut off when the run ends: Core aborts its signal.
108
+ * To keep work running past the reply, reply with `reply` and await that work in the op.
109
+ * Only the first reply counts. Every later reply, and a Response the op returns after an early
110
+ * `reply`, is dropped and its body cancelled. The root waits for those cancels when it closes; a
111
+ * cancel that fails is a warning in the root's log, with its error. An op that replies with a stream must
112
+ * close or error it in a `finally`: if the op throws first, the client waits for the 60 s idle
113
+ * timeout.
114
+ */
115
+ export declare const routes: import("@tinkered/core").Capsule.Handle<{
116
+ readonly table: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<Readonly<Record<`${string} /${string}`, Operation$1.Handle<any, any>>>>>;
117
+ readonly stop: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<AbortSignal>>;
118
+ readonly ns: import("@tinkered/core").Edge<"all", import("@tinkered/core").Tag.Handle<{
119
+ readonly op: Routes[keyof Routes];
120
+ readonly ns: Ns;
121
+ }>>;
122
+ }, {
123
+ readonly request: import("@tinkered/core").Tag.Handle<Request>;
124
+ readonly reply: import("@tinkered/core").Tag.Handle<(response: Response) => void>;
125
+ readonly ns: import("@tinkered/core").Tag.Handle<{
126
+ readonly op: Routes[keyof Routes];
127
+ readonly ns: Ns;
128
+ }>;
129
+ readonly stop: import("@tinkered/core").Tag.Handle<AbortSignal>;
130
+ }, {
131
+ fetch: (incoming: Request, scope: Scope.Handle) => Promise<Response | undefined>;
132
+ }>;
133
+ //#endregion
134
+ export type { Errors, Routes };
@@ -0,0 +1,326 @@
1
+ import { n as isError, t as abortReasons } from "./errors-Ch7N6rzT.mjs";
2
+ import { capsule, operation, resource, tag, transport } from "@tinkered/core";
3
+ import { z } from "zod";
4
+ //#endregion
5
+ //#region src/server/health.ts
6
+ /** This package's version, read from its package.json when it is built. */
7
+ const baseVersion = "0.30.1";
8
+ const health = operation({
9
+ label: "tinker.health",
10
+ run: () => ({
11
+ ok: true,
12
+ base: baseVersion
13
+ })
14
+ });
15
+ //#endregion
16
+ //#region src/server/backend.ts
17
+ /**
18
+ * The one way out for HTTP components send themselves; tests bind a fake (ADR 0102). Its default is
19
+ * the real `fetch`: an effect default on the seam, as ADR 0113 allows.
20
+ */
21
+ const httpBackend = tag({
22
+ label: "http.backend",
23
+ default: (input, init) => fetch(input, init)
24
+ });
25
+ //#endregion
26
+ //#region src/server/lifetime.ts
27
+ /** The main supplies its host signal before graceful drain joins held requests. */
28
+ const backendStop = tag({ label: "lifetime.backendStop" });
29
+ /** Aborts when the request ends: Core's own tag, so every rpc transport binds the same one. */
30
+ const requestStop = transport.requestStop;
31
+ //#endregion
32
+ //#region src/server/http.ts
33
+ const requestShape = z.strictObject({
34
+ url: z.url({ protocol: /^https?$/ }),
35
+ method: z.string().regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/).toUpperCase(),
36
+ headers: z.record(z.string(), z.string()).optional(),
37
+ body: z.string().optional()
38
+ }).brand();
39
+ const nameShape = z.string();
40
+ const codeShape = z.union([z.string(), z.number()]);
41
+ /** Caught native errors are not operation input; each failure field is checked on its own. */
42
+ const failureShape = z.object({
43
+ name: z.unknown().optional(),
44
+ code: z.unknown().optional(),
45
+ cause: z.unknown().optional()
46
+ });
47
+ /** Closing this session or an ancestor ends HTTP waits before graceful work drains.
48
+ * Stop tags also end waits without closing a layer; caller cancellation keeps Core's result. */
49
+ const http = resource({
50
+ label: "http",
51
+ target: "session",
52
+ depends: {
53
+ send: httpBackend,
54
+ backendStop: backendStop.optional,
55
+ requestStop: requestStop.optional
56
+ },
57
+ factory: ({ send, backendStop, requestStop }, { closing, defer }) => {
58
+ const stop = new AbortController();
59
+ defer(() => stop.abort(abortReasons.closed));
60
+ return { async send(url, init) {
61
+ const signal = AbortSignal.any([
62
+ init.signal,
63
+ closing,
64
+ stop.signal,
65
+ ...backendStop.present ? [backendStop.value] : [],
66
+ ...requestStop.present ? [requestStop.value] : []
67
+ ]);
68
+ signal.throwIfAborted();
69
+ const response = await send(url, {
70
+ ...init,
71
+ signal
72
+ });
73
+ return {
74
+ status: response.status,
75
+ headers: Object.fromEntries(Array.from(response.headers, ([name, value]) => [name, name === "set-cookie" ? response.headers.getSetCookie() : [value]])),
76
+ body: await response.text()
77
+ };
78
+ } };
79
+ }
80
+ });
81
+ /** HTTP statuses are results; only sending or reading failures raise HttpRequestFailed. */
82
+ const httpRequest = operation({
83
+ label: "http.request",
84
+ input: requestShape,
85
+ depends: { http },
86
+ run: ({ http }, { input, obs, signal, raise: coreRaise }) => {
87
+ const raise = coreRaise;
88
+ const { url, method, headers, body } = input;
89
+ const path = new URL(url).pathname;
90
+ return obs.child(`http ${method} ${path}`, async (span) => {
91
+ if (span) {
92
+ span.attributes["http.request.method"] = method;
93
+ span.attributes["url.path"] = path;
94
+ }
95
+ try {
96
+ const response = await http.send(url, {
97
+ method,
98
+ headers,
99
+ body,
100
+ signal
101
+ });
102
+ if (span) span.attributes["http.response.status_code"] = response.status;
103
+ return response;
104
+ } catch (cause) {
105
+ signal.throwIfAborted();
106
+ const failure = failureShape.safeParse(cause);
107
+ if (!failure.success) return raise("HttpRequestFailed", {
108
+ method,
109
+ path
110
+ });
111
+ const nested = failureShape.safeParse(failure.data.cause);
112
+ const details = nested.success ? nested.data : failure.data;
113
+ const name = nameShape.optional().catch(void 0);
114
+ const code = codeShape.optional().catch(void 0);
115
+ return raise("HttpRequestFailed", {
116
+ method,
117
+ path,
118
+ cause: {
119
+ name: name.parse(details.name) ?? name.parse(failure.data.name),
120
+ code: code.parse(details.code) ?? code.parse(failure.data.code)
121
+ }
122
+ });
123
+ }
124
+ });
125
+ }
126
+ });
127
+ //#endregion
128
+ //#region src/server/request-body.ts
129
+ /** The request owns the reader; its route borrows it until all body checks finish. */
130
+ const requestBody = resource({
131
+ label: "request.body",
132
+ target: "session",
133
+ depends: {
134
+ backendStop,
135
+ requestStop
136
+ },
137
+ factory: ({ backendStop, requestStop }, ctx) => {
138
+ const signal = AbortSignal.any([
139
+ backendStop,
140
+ requestStop,
141
+ ctx.signal
142
+ ]);
143
+ let reader;
144
+ let cancellation;
145
+ const cancel = () => {
146
+ cancellation ??= reader?.cancel();
147
+ };
148
+ signal.addEventListener("abort", cancel, { once: true });
149
+ const release = async () => {
150
+ signal.removeEventListener("abort", cancel);
151
+ if (signal.aborted) cancel();
152
+ await cancellation;
153
+ reader?.releaseLock();
154
+ reader = void 0;
155
+ };
156
+ ctx.defer(release);
157
+ return {
158
+ signal,
159
+ open(body) {
160
+ reader = body.getReader();
161
+ if (signal.aborted) cancel();
162
+ return reader;
163
+ },
164
+ release
165
+ };
166
+ }
167
+ });
168
+ //#endregion
169
+ //#region src/server/routes.ts
170
+ /**
171
+ * The request a route operation answers; bound per request, read only by HTTP-aware ops. It is
172
+ * Core's own tag, so an op reads it the same under a route and under any rpc transport.
173
+ */
174
+ const request = transport.request;
175
+ /**
176
+ * Sends the reply before the route operation ends. A stream's operation replies with its body,
177
+ * then keeps running, and so keeps its own session, until the stream ends.
178
+ */
179
+ const reply = tag({ label: "routes.reply" });
180
+ /**
181
+ * A row's namespace, bound by the capsule that owns its op: `routes.ns({ op, ns })`. Each
182
+ * request of that row runs in it; in a quiet one it makes no span or log line, failures too.
183
+ */
184
+ const ns = tag({ label: "routes.ns" });
185
+ const table = tag({ label: "routes.table" });
186
+ /** A failure's kind picks its status; any other kind is 500. */
187
+ const failures = {
188
+ DataValidationFailed: 400,
189
+ Cancelled: 503
190
+ };
191
+ /**
192
+ * The cmd's one route table, compiled once at start. A row with no param is one Map read by
193
+ * `METHOD /path`, as a static route in Hono's router; a row with a param keeps its URLPattern,
194
+ * matched once. The first row that fits wins, by table order, in both. A route's
195
+ * raw input is its query plus its path params. Its reply: a Response as is, nothing as 204, a
196
+ * value as JSON. Bad input is 400, a cancel 503, anything else 500. No row: undefined. A route
197
+ * that sent its reply early has answered: how its operation ends later changes no reply.
198
+ * Each request runs in its own session of `scope`: a valid `traceparent` makes the route's span
199
+ * its child; no header, or a bad one, starts a fresh trace. An early reply leaves that session
200
+ * open until the run ends. A row whose op has a `routes.ns` binding opens it in that namespace.
201
+ * A subflow the route op does not await is cut off when the run ends: Core aborts its signal.
202
+ * To keep work running past the reply, reply with `reply` and await that work in the op.
203
+ * Only the first reply counts. Every later reply, and a Response the op returns after an early
204
+ * `reply`, is dropped and its body cancelled. The root waits for those cancels when it closes; a
205
+ * cancel that fails is a warning in the root's log, with its error. An op that replies with a stream must
206
+ * close or error it in a `finally`: if the op throws first, the client waits for the 60 s idle
207
+ * timeout.
208
+ */
209
+ const routes = capsule({
210
+ label: "routes",
211
+ config: {
212
+ table: table.required,
213
+ stop: backendStop.required,
214
+ ns: ns.all
215
+ },
216
+ exports: {
217
+ request,
218
+ reply,
219
+ ns,
220
+ stop: requestStop
221
+ },
222
+ hooks: { async start({ config, next, defer, log }) {
223
+ await next();
224
+ /** Body cancels still running: the root owns them, and waits for them when it closes. */
225
+ const cancels = /* @__PURE__ */ new Set();
226
+ defer(async () => {
227
+ await Promise.all(cancels);
228
+ });
229
+ /** A reply that is not the answer reaches no one: cancel its body, so a stream stops. */
230
+ const discard = async (late, answer) => {
231
+ const dropped = await late;
232
+ if (dropped === await answer) return;
233
+ try {
234
+ await dropped.body?.cancel();
235
+ } catch (error) {
236
+ log.warn("routes: a dropped reply's body did not cancel", { error });
237
+ }
238
+ };
239
+ const own = (cancel) => {
240
+ const owned = cancel.finally(() => cancels.delete(owned));
241
+ cancels.add(owned);
242
+ };
243
+ /** Rows whose path has no param, by their key. */
244
+ const fixed = /* @__PURE__ */ new Map();
245
+ /** Rows with a param, and a fixed row that an earlier one of these also matches. */
246
+ const patterned = [];
247
+ for (const [key, op] of Object.entries(config.table)) {
248
+ const [method, pathname] = key.split(" ");
249
+ const pattern = new URLPattern({ pathname: pathname.replaceAll(/\{(\w+)\}/g, ":$1") });
250
+ const plain = /^[\w\-.~/]*/.exec(pathname)[0];
251
+ const head = plain === pathname ? plain : plain.slice(0, plain.lastIndexOf("/") + 1);
252
+ const row = {
253
+ method,
254
+ pattern,
255
+ op,
256
+ ns: config.ns.find((row) => row.op === op)?.ns,
257
+ head
258
+ };
259
+ const shadowed = patterned.some((r) => r.method === method && r.pattern.test({ pathname }));
260
+ if (plain === pathname && !shadowed) fixed.set(key, row);
261
+ else patterned.push(row);
262
+ }
263
+ /** A `serve` handler (ADR 0132 in tinkered): the table's answer, or undefined. */
264
+ const fetch = async (incoming, scope) => {
265
+ const url = new URL(incoming.url);
266
+ const method = incoming.method;
267
+ let row = fixed.get(`${method} ${url.pathname}`);
268
+ let params = {};
269
+ for (let at = 0; !row && at < patterned.length; at++) {
270
+ const next = patterned[at];
271
+ if (next.method !== method || !url.pathname.startsWith(next.head)) continue;
272
+ const match = next.pattern.exec(url);
273
+ if (match) [row, params] = [next, match.pathname.groups];
274
+ }
275
+ if (!row) return void 0;
276
+ const signal = AbortSignal.any([incoming.signal, config.stop]);
277
+ const trace = transport.traceparentOf(incoming.headers.get("traceparent"));
278
+ const early = Promise.withResolvers();
279
+ /** The request's answer, once the first reply came or the run ended. */
280
+ let answer;
281
+ /** The op's `reply`: the first one answers; any later one is dropped. */
282
+ const send = (response) => {
283
+ if (answer) return own(discard(response, answer));
284
+ answer = early.promise;
285
+ early.resolve(response);
286
+ };
287
+ /** A closing root throws `Disposed` from createSession: answer it as a failed run. */
288
+ let session;
289
+ const settled = Promise.resolve().then(() => (session = scope.createSession({
290
+ trace,
291
+ ns: row.ns
292
+ })).settle(row.op, {
293
+ rawInput: {
294
+ ...Object.fromEntries(url.searchParams),
295
+ ...params
296
+ },
297
+ signal,
298
+ tags: [
299
+ request(incoming),
300
+ requestStop(signal),
301
+ reply(send)
302
+ ]
303
+ })).catch((error) => ({
304
+ status: "failed",
305
+ error,
306
+ kind: "error"
307
+ })).finally(() => session?.close()).then((result) => {
308
+ if (result.status === "success") {
309
+ const value = result.value;
310
+ if (value instanceof Response) return value;
311
+ if (value === void 0) return new Response(null, { status: 204 });
312
+ return Response.json(value, { headers: { "Cache-Control": "no-store" } });
313
+ }
314
+ const kind = result.status === "cancelled" ? "Cancelled" : Object(result.error).kind;
315
+ return new Response(null, { status: failures[kind] ?? 500 });
316
+ });
317
+ const winner = await Promise.race([early.promise, settled]);
318
+ answer ??= settled;
319
+ own(discard(settled, answer));
320
+ return winner;
321
+ };
322
+ return { fetch };
323
+ } }
324
+ });
325
+ //#endregion
326
+ export { abortReasons, backendStop, baseVersion, health, http, httpBackend, httpRequest, isError, requestBody, requestStop, routes };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@tinkered/entry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.30.1",
4
+ "description": "Tinker's backend entries: a command, a server, and the runtime under them.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/lagz0ne/tinkered.git",
9
+ "directory": "packages/entry"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "imports": {
17
+ "#package.json": "./package.json"
18
+ },
19
+ "exports": {
20
+ "./cmd": {
21
+ "browser": "./dist/not-in-page.mjs",
22
+ "default": "./dist/cmd.mjs"
23
+ },
24
+ "./server": {
25
+ "browser": "./dist/not-in-page.mjs",
26
+ "default": "./dist/server.mjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "dependencies": {
34
+ "@tinkered/bun": "^0.30.1",
35
+ "@tinkered/core": "^0.30.1"
36
+ },
37
+ "devDependencies": {
38
+ "@hughescr/stryker-bun-runner": "1.6.0",
39
+ "@stryker-mutator/core": "^10.0.0",
40
+ "@types/bun": "^1.3.0",
41
+ "@types/node": "^26.1.1",
42
+ "vite-plus": "1.0.0",
43
+ "vitest": "5.0.1",
44
+ "zod": "^4.0.0"
45
+ },
46
+ "peerDependencies": {
47
+ "zod": "^4.0.0"
48
+ },
49
+ "engines": {
50
+ "bun": ">=1.4"
51
+ },
52
+ "scripts": {
53
+ "build": "vp pack",
54
+ "dev": "vp pack --watch",
55
+ "test": "bun --bun vp test",
56
+ "mutate": "stryker run && stryker run stryker.run.config.mjs",
57
+ "check": "vp check"
58
+ }
59
+ }