@loozo/angular-launch 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,140 @@
1
+ import { type FrameworkCode } from "../client.js";
2
+ import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
+ /**
4
+ * The application's RPC groups, keyed by generated group ID.
5
+ *
6
+ * @remarks
7
+ * Internal; not exported from a public entry point. Generation writes it as
8
+ * `registry` in `server.generated.ts`.
9
+ */
10
+ export type Registry = Readonly<Record<string, Group<string, Record<string, ProcedureDefinition>>>>;
11
+ declare const scopeMarker: unique symbol;
12
+ /**
13
+ * The application identity and context definition that requests are bound to.
14
+ *
15
+ * @remarks
16
+ * Internal; not exported from a public entry point. Generation writes it as
17
+ * `appBinding` in `server.generated.ts`.
18
+ *
19
+ * @typeParam Definition - The application's context definition.
20
+ */
21
+ export interface ApplicationBinding<Definition extends ContextDefinition<unknown> = ContextDefinition<unknown>> {
22
+ /** The generated application identity. */
23
+ readonly id: string;
24
+ /** The application's context definition. */
25
+ readonly context: Definition;
26
+ }
27
+ /**
28
+ * A live server request bound to the context created for it.
29
+ *
30
+ * @remarks
31
+ * Created by the generated `createContext` in `server.generated.ts`.
32
+ * Render a page by passing `scope.request` together with `scope` as Angular's request
33
+ * context; RPC calls during that render fail with `INTERNAL` if the two don't belong
34
+ * together.
35
+ *
36
+ * @typeParam Value - The context value.
37
+ */
38
+ export interface RequestScope<Value = unknown> {
39
+ /** The identity of the application the scope was created for. */
40
+ readonly appId: string;
41
+ /** A random identifier tying `request` to this scope. */
42
+ readonly binding: string;
43
+ /** A clone of the original request that carries the scope binding. */
44
+ readonly request: Request;
45
+ /** The awaited context value created for `request`. */
46
+ readonly value: Value;
47
+ /** Internal brand of genuine request scopes; not public API. */
48
+ readonly [scopeMarker]: true;
49
+ }
50
+ /**
51
+ * Checks whether a value has the shape of a {@link RequestScope}.
52
+ *
53
+ * @remarks
54
+ * Internal; not exported from a public entry point. It doesn't check which application
55
+ * or request the scope belongs to; Launch checks that separately before dispatching.
56
+ *
57
+ * @param value - The value to check.
58
+ * @returns `true` for values carrying the request scope brand and fields.
59
+ */
60
+ export declare function isRequestScope(value: unknown): value is RequestScope;
61
+ /**
62
+ * Creates the context for a live server request and binds them into a
63
+ * {@link RequestScope}.
64
+ *
65
+ * @remarks
66
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
67
+ * `createContext` in `server.generated.ts`; call that instead.
68
+ * The scope's `request` is a clone of `request` with an added
69
+ * `x-loozo-launch-scope` header, so the original stays usable. The context factory
70
+ * receives that clone.
71
+ *
72
+ * @typeParam Definition - The application's context definition.
73
+ * @param application - The application binding.
74
+ * @param request - The live server request.
75
+ * @returns The request scope.
76
+ * @throws Rejects with whatever the context factory throws or rejects with, or with a
77
+ * `TypeError` when `request`'s body was already read and can't be cloned.
78
+ */
79
+ export declare function createRequestScope<Definition extends ContextDefinition<unknown>>(application: ApplicationBinding<Definition>, request: Request): Promise<RequestScope<ContextOf<Definition>>>;
80
+ export declare function assertBoundScope(scope: unknown, application: ApplicationBinding, request: Request): asserts scope is RequestScope;
81
+ /** The HTTP status and JSON body {@link dispatch} produces for one call. Internal. */
82
+ export interface Reply {
83
+ /** The HTTP status: 200 for a result, otherwise the error's status. */
84
+ readonly status: number;
85
+ /** The result, or an `{ error: { code, message, data } }` frame. */
86
+ readonly body: unknown;
87
+ }
88
+ export declare function failure(code: FrameworkCode): Reply;
89
+ export declare function isJsonMediaType(contentType: string | null): boolean;
90
+ /**
91
+ * Runs one procedure call within a request scope and produces its reply.
92
+ *
93
+ * @remarks
94
+ * The shared pipeline behind {@link handleRpc} and the server-rendering backend of
95
+ * {@link provideLaunchServer}. Internal; not exported from a public entry point. It
96
+ * never rejects: every failure becomes a framework failure reply, and
97
+ * unexpected errors are logged on the server.
98
+ *
99
+ * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
100
+ * path must be `/_rpc/<group ID>/<procedure>` for a registered procedure
101
+ * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
102
+ * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
103
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
104
+ * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
105
+ * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
106
+ * handler's strict JSON result is returned with status 200, and its declared errors
107
+ * with their status.
108
+ *
109
+ * @param registry - The application's RPC groups.
110
+ * @param path - The request path.
111
+ * @param envelope - The parsed request body.
112
+ * @param scope - The request scope whose context the call receives.
113
+ * @param application - The application binding the scope must belong to.
114
+ * @param request - The request the scope must be bound to.
115
+ * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
116
+ * made during server rendering.
117
+ * @returns The reply to send.
118
+ */
119
+ export declare function dispatch(registry: Registry, path: string, envelope: unknown, scope: RequestScope, application: ApplicationBinding, request: Request, mode?: "http" | "rendering"): Promise<Reply>;
120
+ /**
121
+ * Answers an RPC HTTP request, or returns `null` for any other request.
122
+ *
123
+ * @remarks
124
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
125
+ * `handleRequest` in `server.generated.ts`; call that instead.
126
+ * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
127
+ * with an `application/json` content type and no query string, otherwise the reply is
128
+ * `INVALID_INPUT` and no context is created. A fresh context is then created before the
129
+ * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
130
+ * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
131
+ * `Cache-Control: private, no-store` and `Vary: Cookie`.
132
+ *
133
+ * @typeParam Definition - The application's context definition.
134
+ * @param registry - The application's RPC groups.
135
+ * @param application - The application binding.
136
+ * @param request - The incoming server request.
137
+ * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
138
+ */
139
+ export declare function handleRpc<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request): Promise<Response | null>;
140
+ export {};
@@ -0,0 +1,249 @@
1
+ import { frameworkFailures } from "../client.js";
2
+ import { serializeJson } from "../json.js";
3
+ import { declaredFailures } from "./errors.js";
4
+ const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
5
+ const bindingHeader = "x-loozo-launch-scope";
6
+ /**
7
+ * Checks whether a value has the shape of a {@link RequestScope}.
8
+ *
9
+ * @remarks
10
+ * Internal; not exported from a public entry point. It doesn't check which application
11
+ * or request the scope belongs to; Launch checks that separately before dispatching.
12
+ *
13
+ * @param value - The value to check.
14
+ * @returns `true` for values carrying the request scope brand and fields.
15
+ */
16
+ export function isRequestScope(value) {
17
+ return (typeof value === "object" &&
18
+ value !== null &&
19
+ scopeMarker in value &&
20
+ value[scopeMarker] === true &&
21
+ "request" in value &&
22
+ value.request instanceof Request &&
23
+ "appId" in value &&
24
+ typeof value.appId === "string" &&
25
+ "binding" in value &&
26
+ typeof value.binding === "string" &&
27
+ "value" in value);
28
+ }
29
+ /**
30
+ * Creates the context for a live server request and binds them into a
31
+ * {@link RequestScope}.
32
+ *
33
+ * @remarks
34
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
35
+ * `createContext` in `server.generated.ts`; call that instead.
36
+ * The scope's `request` is a clone of `request` with an added
37
+ * `x-loozo-launch-scope` header, so the original stays usable. The context factory
38
+ * receives that clone.
39
+ *
40
+ * @typeParam Definition - The application's context definition.
41
+ * @param application - The application binding.
42
+ * @param request - The live server request.
43
+ * @returns The request scope.
44
+ * @throws Rejects with whatever the context factory throws or rejects with, or with a
45
+ * `TypeError` when `request`'s body was already read and can't be cloned.
46
+ */
47
+ export async function createRequestScope(application, request) {
48
+ const binding = crypto.randomUUID();
49
+ const headers = new Headers(request.headers);
50
+ headers.set(bindingHeader, binding);
51
+ // Keep the caller's body usable and its signal linked via native Request clones.
52
+ const boundRequest = new Request(request.clone(), { headers });
53
+ const value = await application.context.create(boundRequest);
54
+ return {
55
+ appId: application.id,
56
+ binding,
57
+ request: boundRequest,
58
+ value: value,
59
+ [scopeMarker]: true,
60
+ };
61
+ }
62
+ export function assertBoundScope(scope, application, request) {
63
+ if (!isRequestScope(scope) ||
64
+ scope.appId !== application.id ||
65
+ scope.binding.length === 0 ||
66
+ scope.request.headers.get(bindingHeader) !== scope.binding ||
67
+ request.headers.get(bindingHeader) !== scope.binding) {
68
+ throw new Error("Launch request/application scope binding mismatch");
69
+ }
70
+ }
71
+ export function failure(code) {
72
+ const frame = frameworkFailures[code];
73
+ return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
74
+ }
75
+ export function isJsonMediaType(contentType) {
76
+ return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
77
+ }
78
+ /**
79
+ * Runs one procedure call within a request scope and produces its reply.
80
+ *
81
+ * @remarks
82
+ * The shared pipeline behind {@link handleRpc} and the server-rendering backend of
83
+ * {@link provideLaunchServer}. Internal; not exported from a public entry point. It
84
+ * never rejects: every failure becomes a framework failure reply, and
85
+ * unexpected errors are logged on the server.
86
+ *
87
+ * In order: the scope must belong to `application` and `request` (`INTERNAL`); the
88
+ * path must be `/_rpc/<group ID>/<procedure>` for a registered procedure
89
+ * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
90
+ * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
91
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
92
+ * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
93
+ * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
94
+ * handler's strict JSON result is returned with status 200, and its declared errors
95
+ * with their status.
96
+ *
97
+ * @param registry - The application's RPC groups.
98
+ * @param path - The request path.
99
+ * @param envelope - The parsed request body.
100
+ * @param scope - The request scope whose context the call receives.
101
+ * @param application - The application binding the scope must belong to.
102
+ * @param request - The request the scope must be bound to.
103
+ * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
104
+ * made during server rendering.
105
+ * @returns The reply to send.
106
+ */
107
+ export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
108
+ try {
109
+ assertBoundScope(scope, application, request);
110
+ const parts = /^\/_rpc\/([a-f0-9]{24})\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
111
+ if (!parts || !Object.hasOwn(registry, parts[1])) {
112
+ return failure("RPC_NOT_FOUND");
113
+ }
114
+ const group = registry[parts[1]];
115
+ if (!Object.hasOwn(group.procedures, parts[2])) {
116
+ return failure("RPC_NOT_FOUND");
117
+ }
118
+ const procedure = group.procedures[parts[2]];
119
+ if (procedure.kind !== "query" && procedure.kind !== "mutation") {
120
+ throw new Error("Launch registry contains an unsupported procedure");
121
+ }
122
+ // Rendering never performs writes, even for unmarked HttpClient calls or
123
+ // callers/interceptors that relabel a generated method or enable caching.
124
+ if (mode === "rendering" && procedure.kind === "mutation") {
125
+ return failure("FORBIDDEN");
126
+ }
127
+ // Even direct transport crosses the exact same strict JSON boundary.
128
+ const normalized = JSON.parse(serializeJson(envelope));
129
+ if (typeof normalized !== "object" ||
130
+ normalized === null ||
131
+ Array.isArray(normalized) ||
132
+ !("input" in normalized) ||
133
+ Object.keys(normalized).length !== 1) {
134
+ return failure("INVALID_INPUT");
135
+ }
136
+ let input;
137
+ if (procedure.input) {
138
+ const parsed = await procedure.input["~standard"].validate(normalized.input);
139
+ if (parsed.issues) {
140
+ return failure("INVALID_INPUT");
141
+ }
142
+ input = parsed.value;
143
+ }
144
+ else if (normalized.input !== null) {
145
+ return failure("INVALID_INPUT");
146
+ }
147
+ const context = scope.value;
148
+ for (const guard of group.canActivate) {
149
+ if (!(await guard({ context, request }))) {
150
+ return failure("FORBIDDEN");
151
+ }
152
+ }
153
+ for (const guard of procedure.canActivate) {
154
+ if (!(await guard({ context, request, input }))) {
155
+ return failure("FORBIDDEN");
156
+ }
157
+ }
158
+ let output;
159
+ try {
160
+ output = await procedure.handler({ context, input });
161
+ }
162
+ catch (error) {
163
+ let declared;
164
+ if (typeof error === "object" && error !== null) {
165
+ declared = procedure[declaredFailures]?.get(error);
166
+ }
167
+ if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
168
+ throw error;
169
+ }
170
+ const definition = procedure.errors[declared.code];
171
+ if (definition !== declared.definition) {
172
+ throw error;
173
+ }
174
+ const parsed = await definition.data["~standard"].validate(declared.data);
175
+ if (parsed.issues) {
176
+ throw new Error("Declared RPC error data failed validation", { cause: error });
177
+ }
178
+ const data = JSON.parse(serializeJson(parsed.value));
179
+ return {
180
+ status: definition.status,
181
+ body: { error: { code: declared.code, message: definition.message, data } },
182
+ };
183
+ }
184
+ return { status: 200, body: JSON.parse(serializeJson(output)) };
185
+ }
186
+ catch (error) {
187
+ console.error("Launch RPC failed", error);
188
+ return failure("INTERNAL");
189
+ }
190
+ }
191
+ /**
192
+ * Answers an RPC HTTP request, or returns `null` for any other request.
193
+ *
194
+ * @remarks
195
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
196
+ * `handleRequest` in `server.generated.ts`; call that instead.
197
+ * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
198
+ * with an `application/json` content type and no query string, otherwise the reply is
199
+ * `INVALID_INPUT` and no context is created. A fresh context is then created before the
200
+ * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
201
+ * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
202
+ * `Cache-Control: private, no-store` and `Vary: Cookie`.
203
+ *
204
+ * @typeParam Definition - The application's context definition.
205
+ * @param registry - The application's RPC groups.
206
+ * @param application - The application binding.
207
+ * @param request - The incoming server request.
208
+ * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
209
+ */
210
+ export async function handleRpc(registry, application, request) {
211
+ const url = new URL(request.url);
212
+ if (!url.pathname.startsWith("/_rpc/")) {
213
+ return null;
214
+ }
215
+ let reply;
216
+ if (request.method !== "POST" ||
217
+ !isJsonMediaType(request.headers.get("content-type")) ||
218
+ url.search !== "") {
219
+ reply = failure("INVALID_INPUT");
220
+ }
221
+ else {
222
+ try {
223
+ const scope = await createRequestScope(application, request);
224
+ let envelope;
225
+ try {
226
+ envelope = await request.json();
227
+ }
228
+ catch {
229
+ return response(failure("INVALID_INPUT"));
230
+ }
231
+ reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
232
+ }
233
+ catch (error) {
234
+ console.error("Launch context failed", error);
235
+ reply = failure("INTERNAL");
236
+ }
237
+ }
238
+ return response(reply);
239
+ }
240
+ function response(reply) {
241
+ return new Response(serializeJson(reply.body), {
242
+ status: reply.status,
243
+ headers: {
244
+ "content-type": "application/json",
245
+ "cache-control": "private, no-store",
246
+ vary: "Cookie",
247
+ },
248
+ });
249
+ }
@@ -0,0 +1,21 @@
1
+ import type { ErrorDefinition, ErrorDefinitions, ErrorFactories } from "./definitions.js";
2
+ export declare const declaredFailures: unique symbol;
3
+ /**
4
+ * An error a procedure's error factory created, as recorded on the procedure.
5
+ *
6
+ * @remarks
7
+ * The server looks it up when a handler throws, to send the declared error. Application
8
+ * code doesn't create or read it.
9
+ */
10
+ export interface DeclaredFailure {
11
+ /** The declared error code. */
12
+ readonly code: string;
13
+ /** The error's declaration. */
14
+ readonly definition: ErrorDefinition;
15
+ /** The data passed to the factory, before validation. */
16
+ readonly data: unknown;
17
+ }
18
+ export declare function createErrors<Definitions extends ErrorDefinitions>(definitions: Definitions): {
19
+ factories: ErrorFactories<Definitions>;
20
+ failures: WeakMap<object, DeclaredFailure>;
21
+ };
@@ -0,0 +1,32 @@
1
+ import { frameworkFailures } from "../client.js";
2
+ // The map lives on the actual registered procedure, not in module/global state.
3
+ // A native SSR bundle may load this module twice; both copies read that same map.
4
+ export const declaredFailures = Symbol.for("@loozo/angular-launch/private-declared-failures/v1");
5
+ export function createErrors(definitions) {
6
+ const factories = Object.create(null);
7
+ const failures = new WeakMap();
8
+ for (const [code, definition] of Object.entries(definitions)) {
9
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(code) ||
10
+ code === "__proto__" ||
11
+ Object.hasOwn(frameworkFailures, code) ||
12
+ !Number.isInteger(definition.status) ||
13
+ definition.status < 400 ||
14
+ definition.status > 599 ||
15
+ typeof definition.message !== "string" ||
16
+ definition.message.length === 0 ||
17
+ !definition.data ||
18
+ definition.data["~standard"]?.version !== 1 ||
19
+ typeof definition.data["~standard"].vendor !== "string" ||
20
+ typeof definition.data["~standard"].validate !== "function") {
21
+ throw new TypeError(`Invalid declared RPC error: ${code}`);
22
+ }
23
+ factories[code] = (data) => {
24
+ const error = new Error(definition.message);
25
+ failures.set(error, { code, definition, data });
26
+ return error;
27
+ };
28
+ }
29
+ // Every key above closes over its own declaration; the generic mapping only
30
+ // exposes that schema's input to TypeScript. Data is validated on dispatch.
31
+ return { factories: factories, failures };
32
+ }
@@ -0,0 +1,2 @@
1
+ export { createRequestScope, handleRpc } from "./dispatch.js";
2
+ export { provideLaunchServer } from "./backend.js";
@@ -0,0 +1,3 @@
1
+ // Internal entry point for the generated server.generated.ts; not public API.
2
+ export { createRequestScope, handleRpc } from "./dispatch.js";
3
+ export { provideLaunchServer } from "./backend.js";
@@ -0,0 +1,6 @@
1
+ export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
+ export type { Register, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, Guard, InputOf, OutputOf, Procedure, ProcedureDefinition, ProcedureGuard, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
3
+ export type { DeclaredFailure } from "./errors.js";
4
+ export type { JsonShape } from "../json.js";
5
+ export type { RequestScope } from "./dispatch.js";
6
+ export { finishLaunchRendering } from "./backend.js";
@@ -0,0 +1,2 @@
1
+ export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
+ export { finishLaunchRendering } from "./backend.js";