@loozo/angular-launch 0.0.5 → 0.0.6

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.
Files changed (47) hide show
  1. package/README.md +463 -42
  2. package/channel.d.ts +53 -0
  3. package/channel.js +231 -0
  4. package/client.d.ts +50 -10
  5. package/connect.d.ts +201 -0
  6. package/connect.js +148 -0
  7. package/generated.d.ts +1 -1
  8. package/generated.js +86 -3
  9. package/generation/index.js +25 -9
  10. package/index.d.ts +6 -1
  11. package/index.js +2 -0
  12. package/json.d.ts +9 -0
  13. package/json.js +24 -0
  14. package/navigation.d.ts +36 -0
  15. package/navigation.js +47 -0
  16. package/node/index.d.ts +57 -0
  17. package/node/index.js +175 -0
  18. package/outcomes.d.ts +55 -0
  19. package/outcomes.js +100 -0
  20. package/package.json +9 -3
  21. package/server/backend.d.ts +42 -23
  22. package/server/backend.js +127 -48
  23. package/server/channel-messages.d.ts +54 -0
  24. package/server/channel-messages.js +84 -0
  25. package/server/channel-socket.d.ts +67 -0
  26. package/server/channel-socket.js +322 -0
  27. package/server/definitions.d.ts +152 -24
  28. package/server/definitions.js +13 -5
  29. package/server/dispatch.d.ts +62 -11
  30. package/server/dispatch.js +156 -36
  31. package/server/event-stream.d.ts +63 -0
  32. package/server/event-stream.js +173 -0
  33. package/server/generated.d.ts +1 -0
  34. package/server/generated.js +1 -0
  35. package/server/index.d.ts +4 -2
  36. package/server/index.js +1 -1
  37. package/server/outcomes.d.ts +51 -2
  38. package/server/outcomes.js +58 -4
  39. package/server/response-effects.d.ts +105 -0
  40. package/server/response-effects.js +78 -0
  41. package/server/upgrade.d.ts +58 -0
  42. package/server/upgrade.js +117 -0
  43. package/stream.d.ts +31 -0
  44. package/stream.js +159 -0
  45. package/tanstack-query/README.md +101 -9
  46. package/tanstack-query/generated.js +5 -2
  47. package/tanstack-query/queries.d.ts +8 -6
package/node/index.js ADDED
@@ -0,0 +1,175 @@
1
+ /// <reference types="node" preserve="true" />
2
+ import { STATUS_CODES } from "node:http";
3
+ import { WebSocketServer } from "ws";
4
+ const pingMs = 15_000;
5
+ // Where S2's dev-server forwarding finds the app's listener; the latest one created wins.
6
+ const listenerSlot = Symbol.for("@loozo/angular-launch/upgrade-listener/v1");
7
+ // The upgrade request as a web Request. Like Angular's createWebRequestFromNodeRequest by
8
+ // default, it trusts no proxy headers: the protocol comes from the socket, the host from Host.
9
+ function webRequest(incoming, signal) {
10
+ const headers = new Headers();
11
+ for (const [name, value] of Object.entries(incoming.headers)) {
12
+ // HTTP/2 pseudo-headers aren't headers.
13
+ if (name.startsWith(":")) {
14
+ continue;
15
+ }
16
+ if (typeof value === "string") {
17
+ headers.append(name, value);
18
+ }
19
+ else if (Array.isArray(value)) {
20
+ for (const item of value) {
21
+ headers.append(name, item);
22
+ }
23
+ }
24
+ }
25
+ const encrypted = "encrypted" in incoming.socket && incoming.socket.encrypted === true;
26
+ let protocol = "http";
27
+ if (encrypted) {
28
+ protocol = "https";
29
+ }
30
+ return new Request(`${protocol}://${incoming.headers.host}${incoming.url}`, {
31
+ method: incoming.method,
32
+ headers,
33
+ signal,
34
+ });
35
+ }
36
+ // A refusal on the raw socket: status line, headers, body, then the connection closes.
37
+ async function writeResponse(socket, response) {
38
+ const body = Buffer.from(await response.arrayBuffer());
39
+ let head = `HTTP/1.1 ${response.status} ${STATUS_CODES[response.status] ?? ""}\r\n`;
40
+ for (const [name, value] of response.headers) {
41
+ if (name !== "content-length" && name !== "connection") {
42
+ head += `${name}: ${value}\r\n`;
43
+ }
44
+ }
45
+ head += `content-length: ${body.length}\r\nconnection: close\r\n\r\n`;
46
+ if (!socket.destroyed) {
47
+ socket.end(Buffer.concat([Buffer.from(head, "latin1"), body]));
48
+ }
49
+ }
50
+ function ignore() { }
51
+ // Terminates a socket that didn't answer the previous ping.
52
+ function keepAlive(socket) {
53
+ let alive = true;
54
+ const timer = setInterval(() => {
55
+ if (!alive) {
56
+ socket.terminate();
57
+ return;
58
+ }
59
+ alive = false;
60
+ socket.ping();
61
+ }, pingMs);
62
+ socket.on("pong", () => {
63
+ alive = true;
64
+ });
65
+ socket.on("close", () => clearInterval(timer));
66
+ }
67
+ /**
68
+ * Creates the Node `upgrade` listener that runs the app's channels.
69
+ *
70
+ * @remarks
71
+ * Create it once, at your server module's top level, and attach it to the HTTP server that
72
+ * serves the app with `server.on("upgrade", listener)`; with Express, to the server
73
+ * `app.listen()` returns.
74
+ *
75
+ * For each upgrade request it builds a web `Request` (the protocol from the socket, the host
76
+ * from `Host`; proxy headers aren't trusted) whose signal aborts when the client leaves before
77
+ * the socket is accepted, and passes it to `handle`. A `null` result leaves the socket to the
78
+ * server's other `upgrade` listeners, such as a dev server's. A `Response` is written to the
79
+ * socket, which then closes. An `Upgrade` is accepted with `ws`, with its headers on the `101`,
80
+ * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
81
+ * they miss the answer.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * import { createServer } from "node:http";
86
+ * import { createUpgradeHandler } from "@loozo/angular-launch/node";
87
+ * import { handleUpgrade } from "../generated/server.generated";
88
+ *
89
+ * const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
90
+ *
91
+ * if (isMainModule(import.meta.url)) {
92
+ * const server = createServer(reqHandler).listen(port);
93
+ *
94
+ * server.on("upgrade", upgrade);
95
+ * }
96
+ * ```
97
+ *
98
+ * @param handle - Answers one upgrade request: the generated `handleUpgrade`, with your
99
+ * options.
100
+ * @param options - The largest message a caller may send.
101
+ * @returns The listener.
102
+ */
103
+ export function createUpgradeHandler(handle, { maxPayload = 1024 * 1024 } = {}) {
104
+ const server = new WebSocketServer({ noServer: true, clientTracking: false, maxPayload });
105
+ const accepted = new WeakMap();
106
+ server.on("headers", (lines, incoming) => {
107
+ for (const [name, value] of accepted.get(incoming) ?? []) {
108
+ lines.push(`${name}: ${value}`);
109
+ }
110
+ });
111
+ async function upgrade(incoming, socket, head) {
112
+ const leave = new AbortController();
113
+ function left() {
114
+ leave.abort(new DOMException("The client left before its channel was accepted", "AbortError"));
115
+ }
116
+ // Browsers that leave early send FIN, or the connection resets.
117
+ socket.once("end", left);
118
+ socket.once("close", left);
119
+ socket.on("error", left);
120
+ function release() {
121
+ socket.off("end", left);
122
+ socket.off("close", left);
123
+ socket.off("error", left);
124
+ }
125
+ // Nothing else owns a socket Launch closes itself: a reset while it closes must not go
126
+ // unhandled.
127
+ function releaseToClose() {
128
+ release();
129
+ socket.on("error", ignore);
130
+ socket.once("close", () => socket.off("error", ignore));
131
+ }
132
+ let result;
133
+ try {
134
+ result = await handle(webRequest(incoming, leave.signal));
135
+ }
136
+ catch (error) {
137
+ console.error("Launch couldn't answer an upgrade request", error);
138
+ result = new Response("Bad request", {
139
+ status: 400,
140
+ headers: { "content-type": "text/plain" },
141
+ });
142
+ }
143
+ if (result === null) {
144
+ release();
145
+ return;
146
+ }
147
+ if (result instanceof Response) {
148
+ releaseToClose();
149
+ await writeResponse(socket, result);
150
+ return;
151
+ }
152
+ if (leave.signal.aborted || socket.destroyed) {
153
+ releaseToClose();
154
+ socket.destroy();
155
+ return;
156
+ }
157
+ const call = result;
158
+ accepted.set(incoming, call.headers);
159
+ // Until accepted, a client leaving still ends the call, also when ws refuses the handshake.
160
+ server.handleUpgrade(incoming, socket, head, (websocket) => {
161
+ release();
162
+ accepted.delete(incoming);
163
+ // A frame over maxPayload or a broken connection emits an error, then the socket closes.
164
+ websocket.on("error", () => undefined);
165
+ keepAlive(websocket);
166
+ // ws implements the WHATWG WebSocket interface Launch uses.
167
+ call.accept(websocket);
168
+ });
169
+ }
170
+ const listener = (incoming, socket, head) => {
171
+ void upgrade(incoming, socket, head);
172
+ };
173
+ globalThis[listenerSlot] = listener;
174
+ return listener;
175
+ }
package/outcomes.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Whether `to` is a root-relative URL that stays on the app's origin.
3
+ *
4
+ * @remarks
5
+ * Internal. `//host` and `/\host` start with a slash but name another host, and the URL
6
+ * parser strips tabs and newlines, so the check resolves `to` against an origin instead
7
+ * of reading it.
8
+ */
9
+ export declare function isRootRelative(to: unknown): to is `/${string}`;
10
+ /**
11
+ * The rejection of a call whose middleware or handler threw `redirect(to)`.
12
+ *
13
+ * @remarks
14
+ * Generated callables reject with it for a response that is exactly a redirect frame, and
15
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
16
+ * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
17
+ */
18
+ export declare class RpcRedirect extends Error {
19
+ /** The root-relative URL the server redirected to, such as `/sign-in`. */
20
+ readonly to: `/${string}`;
21
+ /**
22
+ * Creates a redirect rejection.
23
+ *
24
+ * @param to - The root-relative URL the server redirected to.
25
+ */
26
+ constructor(
27
+ /** The root-relative URL the server redirected to, such as `/sign-in`. */
28
+ to: `/${string}`);
29
+ }
30
+ /**
31
+ * The rejection of a call whose middleware or handler threw `notFound()`.
32
+ *
33
+ * @remarks
34
+ * Generated callables reject with it for a response that is exactly a not-found frame, and
35
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} renders
36
+ * the app's not-found page instead; anywhere else, nothing navigates for you. It isn't an
37
+ * `RpcError`: `RPC_NOT_FOUND` is a missing procedure, this is a missing resource.
38
+ */
39
+ export declare class RpcNotFound extends Error {
40
+ /** Creates a not-found rejection. */
41
+ constructor();
42
+ }
43
+ /**
44
+ * Recognizes a response body that is exactly a redirect or not-found frame.
45
+ *
46
+ * @remarks
47
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }`, where `to` is
48
+ * root-relative; not-found is status 404 with exactly `{ notFound: null }`. The body must
49
+ * be strict JSON.
50
+ *
51
+ * @param value - The parsed response body.
52
+ * @param status - The response's HTTP status.
53
+ * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
54
+ */
55
+ export declare function recognizedOutcome(value: unknown, status: number): RpcRedirect | RpcNotFound | undefined;
package/outcomes.js ADDED
@@ -0,0 +1,100 @@
1
+ import { serializeJson } from "./json.js";
2
+ const base = "http://launch.invalid";
3
+ /**
4
+ * Whether `to` is a root-relative URL that stays on the app's origin.
5
+ *
6
+ * @remarks
7
+ * Internal. `//host` and `/\host` start with a slash but name another host, and the URL
8
+ * parser strips tabs and newlines, so the check resolves `to` against an origin instead
9
+ * of reading it.
10
+ */
11
+ export function isRootRelative(to) {
12
+ if (typeof to !== "string" || !to.startsWith("/")) {
13
+ return false;
14
+ }
15
+ let resolved;
16
+ try {
17
+ resolved = new URL(to, base);
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ return resolved.origin === base;
23
+ }
24
+ /**
25
+ * The rejection of a call whose middleware or handler threw `redirect(to)`.
26
+ *
27
+ * @remarks
28
+ * Generated callables reject with it for a response that is exactly a redirect frame, and
29
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
30
+ * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
31
+ */
32
+ export class RpcRedirect extends Error {
33
+ to;
34
+ /**
35
+ * Creates a redirect rejection.
36
+ *
37
+ * @param to - The root-relative URL the server redirected to.
38
+ */
39
+ constructor(
40
+ /** The root-relative URL the server redirected to, such as `/sign-in`. */
41
+ to) {
42
+ super(`RPC redirected to ${to}`);
43
+ this.to = to;
44
+ this.name = "RpcRedirect";
45
+ }
46
+ }
47
+ /**
48
+ * The rejection of a call whose middleware or handler threw `notFound()`.
49
+ *
50
+ * @remarks
51
+ * Generated callables reject with it for a response that is exactly a not-found frame, and
52
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} renders
53
+ * the app's not-found page instead; anywhere else, nothing navigates for you. It isn't an
54
+ * `RpcError`: `RPC_NOT_FOUND` is a missing procedure, this is a missing resource.
55
+ */
56
+ export class RpcNotFound extends Error {
57
+ /** Creates a not-found rejection. */
58
+ constructor() {
59
+ super("RPC answered not found");
60
+ this.name = "RpcNotFound";
61
+ }
62
+ }
63
+ /**
64
+ * Recognizes a response body that is exactly a redirect or not-found frame.
65
+ *
66
+ * @remarks
67
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }`, where `to` is
68
+ * root-relative; not-found is status 404 with exactly `{ notFound: null }`. The body must
69
+ * be strict JSON.
70
+ *
71
+ * @param value - The parsed response body.
72
+ * @param status - The response's HTTP status.
73
+ * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
74
+ */
75
+ export function recognizedOutcome(value, status) {
76
+ try {
77
+ serializeJson(value);
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ if (typeof value !== "object" || value === null || Object.keys(value).length !== 1) {
83
+ return undefined;
84
+ }
85
+ if (status === 404 && "notFound" in value && value.notFound === null) {
86
+ return new RpcNotFound();
87
+ }
88
+ if (status !== 303 || !("redirect" in value)) {
89
+ return undefined;
90
+ }
91
+ const redirect = value.redirect;
92
+ if (typeof redirect !== "object" ||
93
+ redirect === null ||
94
+ !("to" in redirect) ||
95
+ Object.keys(redirect).length !== 1 ||
96
+ !isRootRelative(redirect.to)) {
97
+ return undefined;
98
+ }
99
+ return new RpcRedirect(redirect.to);
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loozo/angular-launch",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Typed queries, mutations and declared errors on Angular's native router, HTTP and SSR pipeline.",
5
5
  "bugs": "https://github.com/theo-matzavinos/loozo/issues",
6
6
  "license": "MIT",
@@ -24,6 +24,10 @@
24
24
  "types": "./server/generated.d.ts",
25
25
  "default": "./server/generated.js"
26
26
  },
27
+ "./node": {
28
+ "types": "./node/index.d.ts",
29
+ "default": "./node/index.js"
30
+ },
27
31
  "./_generated": {
28
32
  "types": "./generated.d.ts",
29
33
  "default": "./generated.js"
@@ -49,13 +53,15 @@
49
53
  "dependencies": {
50
54
  "@angular-devkit/architect": "0.2202.2",
51
55
  "chokidar": "5.0.0",
52
- "typescript": "6.0.3"
56
+ "typescript": "6.0.3",
57
+ "ws": "8.21.3"
53
58
  },
54
59
  "peerDependencies": {
55
60
  "@angular/build": "~22.2.0",
56
61
  "@angular/common": "^22.0.0",
57
62
  "@angular/core": "^22.0.0",
58
- "@loozo/angular-router": "0.0.6",
63
+ "@angular/router": "^22.0.0",
64
+ "@loozo/angular-router": "0.0.8",
59
65
  "@tanstack/angular-query": "^5.0.0-rc.5",
60
66
  "rxjs": "^7.8.2"
61
67
  },
@@ -10,21 +10,32 @@ import { type ApplicationBinding, type Registry } from "./dispatch.js";
10
10
  * after `provideHttpClient()`, instead of calling this.
11
11
  *
12
12
  * It replaces Angular's `HttpBackend` on the server. Calls from generated clients, and
13
- * any other request to `/_rpc/` on the current request's origin, are intercepted and
14
- * run in-process in `"rendering"` mode, so mutations are refused with `FORBIDDEN`. All
15
- * other requests, including ones to `/_rpc/` on another origin that don't come from a
16
- * generated client, go to Angular's `FetchBackend`.
17
- *
18
- * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
19
- * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
20
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
21
- * issues, as does any intercepted call with a query string, fragment, URL credentials, a
22
- * method other than `POST`, a non-JSON content type, its own `Authorization`,
23
- * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
- *
25
- * Without a live request, as during prerendering, calls from generated clients and
26
- * requests to a relative `/_rpc/` path fail and the fault is recorded for
27
- * {@link finishLaunchRendering}; other requests still go to `FetchBackend`.
13
+ * any other request to `/_rpc/` on the page's origin, are intercepted and run in-process
14
+ * in `"rendering"` mode, so mutations and streams are refused with `FORBIDDEN`. All other
15
+ * requests, including ones to `/_rpc/` on another origin that don't come from a generated
16
+ * client, go to Angular's `FetchBackend`.
17
+ *
18
+ * For intercepted calls during server rendering, Angular's `REQUEST_CONTEXT` must be the
19
+ * {@link RequestScope} created for Angular's `REQUEST`, or the calls fail with `INTERNAL`.
20
+ * A generated-client call outside `/_rpc/` on the page's origin fails with
21
+ * `INVALID_INPUT` with no issues, as does any intercepted call with a query string,
22
+ * fragment, URL credentials, a method other than `POST`, a non-JSON content type, its own
23
+ * `Authorization`, `Proxy-Authorization` or `Cookie` header, or its own credentials
24
+ * setting.
25
+ *
26
+ * Cookies an intercepted call sets are appended to `RESPONSE_INIT`'s headers when the
27
+ * call settles, whatever its outcome, so they reach the page response; its other headers
28
+ * are dropped. Angular copies those headers into the page response once the app is first
29
+ * stable, so cookies from a call that settles later, such as one awaited in a
30
+ * `BEFORE_APP_SERIALIZED` hook, are lost. Without `RESPONSE_INIT`, a call that set cookies
31
+ * fails with `INTERNAL`.
32
+ *
33
+ * Without `REQUEST`, as when Angular prerenders a page, the first intercepted call creates
34
+ * the render's context from a cookie-less `GET` of the page's URL, and every call in the
35
+ * render shares it. Its signal aborts when the application is destroyed. A call that
36
+ * doesn't answer 200, or sets a cookie, records a fault for
37
+ * {@link finishLaunchRendering}, as does a context factory that throws. Only faults
38
+ * recorded before the app is first stable fail the build.
28
39
  *
29
40
  * @param registry - The application's RPC groups.
30
41
  * @param application - The application binding.
@@ -32,14 +43,22 @@ import { type ApplicationBinding, type Registry } from "./dispatch.js";
32
43
  */
33
44
  export declare function provideLaunchServer(registry: Registry, application: ApplicationBinding): EnvironmentProviders;
34
45
  /**
35
- * Waits for the server application to become stable and fails the render if an RPC was
36
- * called without a live request.
46
+ * Waits for the server application to become stable and fails the render if a Launch call
47
+ * failed while Angular prerendered the page.
37
48
  *
38
49
  * @remarks
39
- * Angular's prerendering can swallow resolver errors and still report success. Return
40
- * this from your server bootstrap so a page that calls an RPC during prerendering fails
41
- * the build instead of producing a broken page. The application must include the
42
- * generated `provideServer()`.
50
+ * A prerendered page is written once and served to every visitor, so each Launch call it
51
+ * makes must answer 200 without setting a cookie; a mutation or stream is refused with
52
+ * `FORBIDDEN`, so it fails too. Angular's prerendering can swallow resolver errors and still
53
+ * report success, and a failed `injectQuery` only renders its error state, so return this
54
+ * from your server bootstrap to fail the build instead of producing a broken page. The
55
+ * application must include the generated `provideServer()`. Server-rendered pages are
56
+ * unaffected: their failures reach the caller as usual.
57
+ *
58
+ * It checks once the app is first stable, which covers calls from guards, resolvers and
59
+ * rendering. Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their
60
+ * errors, so a call made in one isn't checked and the page is still written; don't make
61
+ * Launch calls there.
43
62
  *
44
63
  * @example
45
64
  * ```ts
@@ -52,7 +71,7 @@ export declare function provideLaunchServer(registry: Registry, application: App
52
71
  *
53
72
  * @param app - The bootstrapped server application.
54
73
  * @returns The same application once it is stable.
55
- * @throws The recorded error when an RPC was called without a live request; the
56
- * application is destroyed first.
74
+ * @throws The first recorded fault, naming the call and its reply, the cookie or the
75
+ * context factory's error; the application is destroyed first.
57
76
  */
58
77
  export declare function finishLaunchRendering(app: ApplicationRef): Promise<ApplicationRef>;