@loozo/angular-launch 0.0.4 → 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 (59) hide show
  1. package/README.md +695 -102
  2. package/builders/application.d.ts +4 -0
  3. package/builders/application.js +71 -0
  4. package/builders/options.d.ts +10 -0
  5. package/builders/options.js +64 -0
  6. package/builders/serve.d.ts +8 -0
  7. package/builders/serve.js +248 -0
  8. package/builders.json +15 -0
  9. package/channel.d.ts +53 -0
  10. package/channel.js +231 -0
  11. package/client.d.ts +59 -16
  12. package/client.js +3 -2
  13. package/connect.d.ts +201 -0
  14. package/connect.js +148 -0
  15. package/generated.d.ts +1 -1
  16. package/generated.js +86 -3
  17. package/generation/context-file.d.ts +2 -0
  18. package/generation/context-file.js +3 -0
  19. package/generation/index.js +77 -36
  20. package/index.d.ts +6 -1
  21. package/index.js +2 -0
  22. package/json.d.ts +9 -0
  23. package/json.js +24 -0
  24. package/navigation.d.ts +36 -0
  25. package/navigation.js +47 -0
  26. package/node/index.d.ts +57 -0
  27. package/node/index.js +175 -0
  28. package/outcomes.d.ts +55 -0
  29. package/outcomes.js +100 -0
  30. package/package.json +14 -4
  31. package/schemas/application.json +756 -0
  32. package/schemas/serve.json +153 -0
  33. package/server/backend.d.ts +42 -23
  34. package/server/backend.js +137 -47
  35. package/server/channel-messages.d.ts +54 -0
  36. package/server/channel-messages.js +84 -0
  37. package/server/channel-socket.d.ts +67 -0
  38. package/server/channel-socket.js +322 -0
  39. package/server/definitions.d.ts +463 -181
  40. package/server/definitions.js +90 -103
  41. package/server/dispatch.d.ts +99 -20
  42. package/server/dispatch.js +337 -89
  43. package/server/event-stream.d.ts +63 -0
  44. package/server/event-stream.js +173 -0
  45. package/server/generated.d.ts +1 -0
  46. package/server/generated.js +1 -0
  47. package/server/index.d.ts +6 -3
  48. package/server/index.js +2 -1
  49. package/server/outcomes.d.ts +75 -0
  50. package/server/outcomes.js +90 -0
  51. package/server/response-effects.d.ts +105 -0
  52. package/server/response-effects.js +78 -0
  53. package/server/upgrade.d.ts +58 -0
  54. package/server/upgrade.js +117 -0
  55. package/stream.d.ts +31 -0
  56. package/stream.js +159 -0
  57. package/tanstack-query/README.md +110 -22
  58. package/tanstack-query/generated.js +5 -2
  59. package/tanstack-query/queries.d.ts +8 -6
package/navigation.js ADDED
@@ -0,0 +1,47 @@
1
+ import { inject, RESPONSE_INIT } from "@angular/core";
2
+ import { RedirectCommand, Router } from "@angular/router";
3
+ import { RpcNotFound, RpcRedirect } from "./outcomes.js";
4
+ /**
5
+ * Creates a navigation error handler that follows RPC redirects and renders not-found
6
+ * outcomes.
7
+ *
8
+ * @remarks
9
+ * Pass it to Angular's `withNavigationErrorHandler`. When a guard or resolver fails with
10
+ * an {@link RpcRedirect}, the navigation goes to its `to` instead; during server
11
+ * rendering Angular then answers the page request with a 302. When it fails with an
12
+ * {@link RpcNotFound}, the navigation renders `notFound` while the address bar keeps the
13
+ * requested URL; during server rendering the page is answered with status 404. Any other
14
+ * error is left to Angular, which fails the navigation as usual.
15
+ *
16
+ * Angular takes one navigation error handler. An app with its own calls this one from it,
17
+ * within the handler's injection context, and returns its result.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * provideRouter(
22
+ * routes,
23
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFoundRoute, {}) })),
24
+ * );
25
+ * ```
26
+ *
27
+ * @param options - The not-found page's URL.
28
+ * @returns The handler, which must run in an injection context.
29
+ */
30
+ export function rpcNavigationErrors({ notFound, }) {
31
+ return (error) => {
32
+ const router = inject(Router);
33
+ const cause = error.error;
34
+ if (cause instanceof RpcRedirect) {
35
+ return new RedirectCommand(router.parseUrl(cause.to));
36
+ }
37
+ if (!(cause instanceof RpcNotFound)) {
38
+ return undefined;
39
+ }
40
+ // Angular builds the page response from this object once the app is stable.
41
+ const response = inject(RESPONSE_INIT, { optional: true });
42
+ if (response !== null) {
43
+ response.status = 404;
44
+ }
45
+ return new RedirectCommand(router.parseUrl(notFound), { browserUrl: error.url });
46
+ };
47
+ }
@@ -0,0 +1,57 @@
1
+ /// <reference types="node" preserve="true" />
2
+ import { type IncomingMessage } from "node:http";
3
+ import type { Duplex } from "node:stream";
4
+ import type { Upgrade } from "../server/upgrade.js";
5
+ /** Options for {@link createUpgradeHandler}. */
6
+ export interface UpgradeHandlerOptions {
7
+ /**
8
+ * The largest message a caller may send, in bytes. A bigger frame closes the socket with
9
+ * 1009, which the browser client reports as a `TypeError`. Defaults to 1 MiB.
10
+ */
11
+ readonly maxPayload?: number;
12
+ }
13
+ /**
14
+ * A Node `upgrade` listener, for `server.on("upgrade", listener)`.
15
+ *
16
+ * @param request - The upgrade request.
17
+ * @param socket - The request's socket.
18
+ * @param head - The first bytes of the upgraded stream, if any arrived with the request.
19
+ */
20
+ export type UpgradeListener = (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
21
+ /**
22
+ * Creates the Node `upgrade` listener that runs the app's channels.
23
+ *
24
+ * @remarks
25
+ * Create it once, at your server module's top level, and attach it to the HTTP server that
26
+ * serves the app with `server.on("upgrade", listener)`; with Express, to the server
27
+ * `app.listen()` returns.
28
+ *
29
+ * For each upgrade request it builds a web `Request` (the protocol from the socket, the host
30
+ * from `Host`; proxy headers aren't trusted) whose signal aborts when the client leaves before
31
+ * the socket is accepted, and passes it to `handle`. A `null` result leaves the socket to the
32
+ * server's other `upgrade` listeners, such as a dev server's. A `Response` is written to the
33
+ * socket, which then closes. An `Upgrade` is accepted with `ws`, with its headers on the `101`,
34
+ * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
35
+ * they miss the answer.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { createServer } from "node:http";
40
+ * import { createUpgradeHandler } from "@loozo/angular-launch/node";
41
+ * import { handleUpgrade } from "../generated/server.generated";
42
+ *
43
+ * const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
44
+ *
45
+ * if (isMainModule(import.meta.url)) {
46
+ * const server = createServer(reqHandler).listen(port);
47
+ *
48
+ * server.on("upgrade", upgrade);
49
+ * }
50
+ * ```
51
+ *
52
+ * @param handle - Answers one upgrade request: the generated `handleUpgrade`, with your
53
+ * options.
54
+ * @param options - The largest message a caller may send.
55
+ * @returns The listener.
56
+ */
57
+ export declare function createUpgradeHandler(handle: (request: Request) => Promise<Response | Upgrade | null>, { maxPayload }?: UpgradeHandlerOptions): UpgradeListener;
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.4",
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"
@@ -47,12 +51,17 @@
47
51
  "registry": "https://registry.npmjs.org/"
48
52
  },
49
53
  "dependencies": {
50
- "typescript": "6.0.3"
54
+ "@angular-devkit/architect": "0.2202.2",
55
+ "chokidar": "5.0.0",
56
+ "typescript": "6.0.3",
57
+ "ws": "8.21.3"
51
58
  },
52
59
  "peerDependencies": {
60
+ "@angular/build": "~22.2.0",
53
61
  "@angular/common": "^22.0.0",
54
62
  "@angular/core": "^22.0.0",
55
- "@loozo/angular-router": "0.0.6",
63
+ "@angular/router": "^22.0.0",
64
+ "@loozo/angular-router": "0.0.8",
56
65
  "@tanstack/angular-query": "^5.0.0-rc.5",
57
66
  "rxjs": "^7.8.2"
58
67
  },
@@ -60,5 +69,6 @@
60
69
  "@tanstack/angular-query": {
61
70
  "optional": true
62
71
  }
63
- }
72
+ },
73
+ "builders": "./builders.json"
64
74
  }