@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/server/backend.js CHANGED
@@ -1,8 +1,10 @@
1
- import { inject, InjectionToken, REQUEST, REQUEST_CONTEXT, makeEnvironmentProviders, } from "@angular/core";
1
+ import { DestroyRef, DOCUMENT, inject, InjectionToken, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, makeEnvironmentProviders, } from "@angular/core";
2
2
  import { FetchBackend, HttpBackend, HttpErrorResponse, HttpResponse } from "@angular/common/http";
3
3
  import { Observable } from "rxjs";
4
4
  import { RPC_CALL } from "../generated.js";
5
- import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
5
+ import { parseJson } from "../json.js";
6
+ import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, createRequestScope, } from "./dispatch.js";
7
+ import { createResponseEffects } from "./response-effects.js";
6
8
  const renderFaults = new InjectionToken("Launch render faults");
7
9
  /**
8
10
  * Provides the server-rendering transport that runs RPC calls in-process with the
@@ -14,21 +16,32 @@ const renderFaults = new InjectionToken("Launch render faults");
14
16
  * after `provideHttpClient()`, instead of calling this.
15
17
  *
16
18
  * It replaces Angular's `HttpBackend` on the server. Calls from generated clients, and
17
- * any other request to `/_rpc/` on the current request's origin, are intercepted and
18
- * run in-process in `"rendering"` mode, so mutations are refused with `FORBIDDEN`. All
19
- * other requests, including ones to `/_rpc/` on another origin that don't come from a
20
- * generated client, go to Angular's `FetchBackend`.
19
+ * any other request to `/_rpc/` on the page's origin, are intercepted and run in-process
20
+ * in `"rendering"` mode, so mutations and streams are refused with `FORBIDDEN`. All other
21
+ * requests, including ones to `/_rpc/` on another origin that don't come from a generated
22
+ * client, go to Angular's `FetchBackend`.
21
23
  *
22
- * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
23
- * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
24
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
25
- * issues, as does any intercepted call with a query string, fragment, URL credentials, a
26
- * method other than `POST`, a non-JSON content type, its own `Authorization`,
27
- * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
+ * For intercepted calls during server rendering, Angular's `REQUEST_CONTEXT` must be the
25
+ * {@link RequestScope} created for Angular's `REQUEST`, or the calls fail with `INTERNAL`.
26
+ * A generated-client call outside `/_rpc/` on the page's origin fails with
27
+ * `INVALID_INPUT` with no issues, as does any intercepted call with a query string,
28
+ * fragment, URL credentials, a method other than `POST`, a non-JSON content type, its own
29
+ * `Authorization`, `Proxy-Authorization` or `Cookie` header, or its own credentials
30
+ * setting.
28
31
  *
29
- * Without a live request, as during prerendering, calls from generated clients and
30
- * requests to a relative `/_rpc/` path fail and the fault is recorded for
31
- * {@link finishLaunchRendering}; other requests still go to `FetchBackend`.
32
+ * Cookies an intercepted call sets are appended to `RESPONSE_INIT`'s headers when the
33
+ * call settles, whatever its outcome, so they reach the page response; its other headers
34
+ * are dropped. Angular copies those headers into the page response once the app is first
35
+ * stable, so cookies from a call that settles later, such as one awaited in a
36
+ * `BEFORE_APP_SERIALIZED` hook, are lost. Without `RESPONSE_INIT`, a call that set cookies
37
+ * fails with `INTERNAL`.
38
+ *
39
+ * Without `REQUEST`, as when Angular prerenders a page, the first intercepted call creates
40
+ * the render's context from a cookie-less `GET` of the page's URL, and every call in the
41
+ * render shares it. Its signal aborts when the application is destroyed. A call that
42
+ * doesn't answer 200, or sets a cookie, records a fault for
43
+ * {@link finishLaunchRendering}, as does a context factory that throws. Only faults
44
+ * recorded before the app is first stable fail the build.
32
45
  *
33
46
  * @param registry - The application's RPC groups.
34
47
  * @param application - The application binding.
@@ -42,33 +55,41 @@ export function provideLaunchServer(registry, application) {
42
55
  useFactory: () => {
43
56
  const context = inject(REQUEST_CONTEXT);
44
57
  const nativeRequest = inject(REQUEST);
58
+ const responseInit = inject(RESPONSE_INIT, { optional: true });
45
59
  const fallback = inject(FetchBackend);
46
60
  const faults = inject(renderFaults);
61
+ const document = inject(DOCUMENT);
62
+ const destroyed = new AbortController();
63
+ let prerenderScope;
64
+ inject(DestroyRef).onDestroy(() => destroyed.abort());
65
+ // The first fault is the one the build reports.
66
+ function recordFault(message, cause) {
67
+ faults.fault ??= new Error(`Launch can't prerender this page: ${message}`, { cause });
68
+ }
47
69
  return {
48
70
  handle(request) {
49
71
  const marked = request.context.get(RPC_CALL);
50
- let target;
72
+ const prerendering = !(nativeRequest instanceof Request);
73
+ let page;
51
74
  if (nativeRequest instanceof Request) {
52
- target = new URL(request.urlWithParams, nativeRequest.url);
75
+ page = nativeRequest.url;
53
76
  }
54
77
  else {
55
- target = new URL(request.urlWithParams, "http://launch.invalid");
56
- const localRpc = target.origin === "http://launch.invalid" && target.pathname.startsWith("/_rpc/");
57
- if (!marked && !localRpc) {
58
- return fallback.handle(request);
59
- }
60
- const error = new Error("Launch RPC requires live request context; prerender RPC is unsupported");
61
- faults.unsupportedContext = error;
62
- return new Observable((subscriber) => subscriber.error(error));
78
+ page = document.location.href;
63
79
  }
64
- const ownOrigin = target.origin === new URL(nativeRequest.url).origin;
80
+ const target = new URL(request.urlWithParams, page);
81
+ const ownOrigin = target.origin === new URL(page).origin;
65
82
  const ownRpc = ownOrigin && target.pathname.startsWith("/_rpc/");
66
83
  if (!marked && !ownRpc) {
67
84
  return fallback.handle(request);
68
85
  }
69
86
  return new Observable((subscriber) => {
70
87
  function deliver(reply) {
71
- if (reply.status >= 400) {
88
+ if (prerendering && reply.status !== 200) {
89
+ recordFault(`${target.pathname} answered ${reply.status} ${JSON.stringify(reply.body)}`);
90
+ }
91
+ // Only 200 is a result: a redirect's 303 frame must not reach the caller as data.
92
+ if (reply.status !== 200) {
72
93
  subscriber.error(new HttpErrorResponse({
73
94
  status: reply.status,
74
95
  error: reply.body,
@@ -83,13 +104,17 @@ export function provideLaunchServer(registry, application) {
83
104
  }));
84
105
  subscriber.complete();
85
106
  }
86
- try {
87
- assertBoundScope(context, application, nativeRequest);
88
- }
89
- catch (error) {
90
- console.error("Launch SSR scope binding failed", error);
91
- deliver(failure("INTERNAL"));
92
- return;
107
+ let live;
108
+ if (nativeRequest instanceof Request) {
109
+ try {
110
+ assertBoundScope(context, application, nativeRequest);
111
+ live = { scope: context, request: nativeRequest };
112
+ }
113
+ catch (error) {
114
+ console.error("Launch SSR scope binding failed", error);
115
+ deliver(failure("INTERNAL"));
116
+ return;
117
+ }
93
118
  }
94
119
  const authOverride = request.headers.has("authorization") ||
95
120
  request.headers.has("proxy-authorization") ||
@@ -115,7 +140,7 @@ export function provideLaunchServer(registry, application) {
115
140
  deliver(invalidInput());
116
141
  return;
117
142
  }
118
- envelope = JSON.parse(body);
143
+ envelope = parseJson(body);
119
144
  }
120
145
  catch {
121
146
  deliver(invalidInput());
@@ -123,11 +148,59 @@ export function provideLaunchServer(registry, application) {
123
148
  }
124
149
  // Aborts when the page request does, or when HttpClient unsubscribes first.
125
150
  const call = new AbortController();
151
+ const effects = createResponseEffects();
126
152
  let settled = false;
127
- void dispatch(registry, target.pathname, envelope, context, application, nativeRequest, "rendering", AbortSignal.any([nativeRequest.signal, call.signal])).then((reply) => {
153
+ async function run() {
154
+ let scope;
155
+ let pageRequest;
156
+ if (live) {
157
+ scope = live.scope;
158
+ pageRequest = live.request;
159
+ }
160
+ else {
161
+ prerenderScope ??= createRequestScope(application, new Request(page, { signal: destroyed.signal }));
162
+ try {
163
+ scope = await prerenderScope;
164
+ }
165
+ catch (error) {
166
+ recordFault("its context factory threw", error);
167
+ console.error("Launch prerender context creation failed", error);
168
+ deliver(failure("INTERNAL"));
169
+ return;
170
+ }
171
+ pageRequest = scope.request;
172
+ }
173
+ const reply = await dispatch(registry, target.pathname, envelope, scope, application, pageRequest, "rendering", AbortSignal.any([pageRequest.signal, call.signal]), effects);
128
174
  settled = true;
175
+ effects.commit();
176
+ if (effects.cookies.length === 0) {
177
+ deliver(reply);
178
+ return;
179
+ }
180
+ // A prerendered page is a file: there's no response to put a cookie on.
181
+ if (prerendering) {
182
+ recordFault(`${target.pathname} set a cookie`);
183
+ deliver(reply);
184
+ return;
185
+ }
186
+ if (responseInit === null) {
187
+ console.error("Launch can't send cookies set during rendering without RESPONSE_INIT");
188
+ deliver(failure("INTERNAL"));
189
+ return;
190
+ }
191
+ // Angular builds the page response, and its redirects, from these headers. It
192
+ // creates them as Headers; keep that object for anyone holding it.
193
+ let headers = responseInit.headers;
194
+ if (!(headers instanceof Headers)) {
195
+ headers = new Headers(headers);
196
+ responseInit.headers = headers;
197
+ }
198
+ for (const cookie of effects.cookies) {
199
+ headers.append("set-cookie", cookie);
200
+ }
129
201
  deliver(reply);
130
- });
202
+ }
203
+ void run();
131
204
  return () => {
132
205
  if (!settled) {
133
206
  call.abort(new DOMException("RPC call aborted", "AbortError"));
@@ -141,14 +214,22 @@ export function provideLaunchServer(registry, application) {
141
214
  ]);
142
215
  }
143
216
  /**
144
- * Waits for the server application to become stable and fails the render if an RPC was
145
- * called without a live request.
217
+ * Waits for the server application to become stable and fails the render if a Launch call
218
+ * failed while Angular prerendered the page.
146
219
  *
147
220
  * @remarks
148
- * Angular's prerendering can swallow resolver errors and still report success. Return
149
- * this from your server bootstrap so a page that calls an RPC during prerendering fails
150
- * the build instead of producing a broken page. The application must include the
151
- * generated `provideServer()`.
221
+ * A prerendered page is written once and served to every visitor, so each Launch call it
222
+ * makes must answer 200 without setting a cookie; a mutation or stream is refused with
223
+ * `FORBIDDEN`, so it fails too. Angular's prerendering can swallow resolver errors and still
224
+ * report success, and a failed `injectQuery` only renders its error state, so return this
225
+ * from your server bootstrap to fail the build instead of producing a broken page. The
226
+ * application must include the generated `provideServer()`. Server-rendered pages are
227
+ * unaffected: their failures reach the caller as usual.
228
+ *
229
+ * It checks once the app is first stable, which covers calls from guards, resolvers and
230
+ * rendering. Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their
231
+ * errors, so a call made in one isn't checked and the page is still written; don't make
232
+ * Launch calls there.
152
233
  *
153
234
  * @example
154
235
  * ```ts
@@ -161,14 +242,12 @@ export function provideLaunchServer(registry, application) {
161
242
  *
162
243
  * @param app - The bootstrapped server application.
163
244
  * @returns The same application once it is stable.
164
- * @throws The recorded error when an RPC was called without a live request; the
165
- * application is destroyed first.
245
+ * @throws The first recorded fault, naming the call and its reply, the cookie or the
246
+ * context factory's error; the application is destroyed first.
166
247
  */
167
- // Native prerender can swallow resolver errors. Propagate only the unsupported
168
- // Launch context fault after native stability, without manufacturing a request.
169
248
  export async function finishLaunchRendering(app) {
170
249
  await app.whenStable();
171
- const fault = app.injector.get(renderFaults).unsupportedContext;
250
+ const fault = app.injector.get(renderFaults).fault;
172
251
  if (fault) {
173
252
  app.destroy();
174
253
  throw fault;
@@ -0,0 +1,54 @@
1
+ import { type InputIssue } from "../input-issues.js";
2
+ import type { Schema } from "./definitions.js";
3
+ /**
4
+ * Where a channel's handler reads its caller's messages from. Internal.
5
+ *
6
+ * @remarks
7
+ * The socket side of a channel creates it before the upgrade is accepted, so the handler can
8
+ * hold its `messages` from the start; messages arrive once the socket is accepted.
9
+ */
10
+ export interface ChannelInbox {
11
+ /**
12
+ * Takes the next unread message as received, before validation.
13
+ *
14
+ * @returns The message, or `done` once the caller closed the channel. Rejects with a
15
+ * {@link MessageRefused} after the caller broke the protocol.
16
+ */
17
+ next(): Promise<IteratorResult<unknown, undefined>>;
18
+ /**
19
+ * Ends the call with `INVALID_INPUT` and `issues`, for a message that failed validation.
20
+ *
21
+ * @param issues - The message schema's issues.
22
+ */
23
+ refuse(issues: readonly InputIssue[]): void;
24
+ }
25
+ /**
26
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
27
+ * the protocol. Internal.
28
+ *
29
+ * @remarks
30
+ * `dispatch` answers it with `INVALID_INPUT` and its issues instead of logging it as an
31
+ * unexpected failure.
32
+ */
33
+ export declare class MessageRefused extends Error {
34
+ readonly issues: readonly InputIssue[];
35
+ /**
36
+ * Creates the refusal.
37
+ *
38
+ * @param issues - The message schema's issues; empty for a protocol violation.
39
+ */
40
+ constructor(issues: readonly InputIssue[]);
41
+ }
42
+ /**
43
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
44
+ * as they're read, in arrival order.
45
+ *
46
+ * @remarks
47
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
48
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
49
+ * that, or after `return()`, iteration is done.
50
+ *
51
+ * @param inbox - Where the messages come from.
52
+ * @param schema - The channel's message schema.
53
+ */
54
+ export declare function channelMessages(inbox: ChannelInbox, schema: Schema): AsyncIterable<unknown>;
@@ -0,0 +1,84 @@
1
+ import { inputIssues } from "../input-issues.js";
2
+ /**
3
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
4
+ * the protocol. Internal.
5
+ *
6
+ * @remarks
7
+ * `dispatch` answers it with `INVALID_INPUT` and its issues instead of logging it as an
8
+ * unexpected failure.
9
+ */
10
+ export class MessageRefused extends Error {
11
+ issues;
12
+ /**
13
+ * Creates the refusal.
14
+ *
15
+ * @param issues - The message schema's issues; empty for a protocol violation.
16
+ */
17
+ constructor(issues) {
18
+ super("Launch channel refused a message");
19
+ this.issues = issues;
20
+ this.name = "MessageRefused";
21
+ }
22
+ }
23
+ /**
24
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
25
+ * as they're read, in arrival order.
26
+ *
27
+ * @remarks
28
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
29
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
30
+ * that, or after `return()`, iteration is done.
31
+ *
32
+ * @param inbox - Where the messages come from.
33
+ * @param schema - The channel's message schema.
34
+ */
35
+ export function channelMessages(inbox, schema) {
36
+ let taken = false;
37
+ let finished = false;
38
+ // Reads run one after another, so an asynchronous schema can't reorder messages.
39
+ let previous = Promise.resolve();
40
+ async function read() {
41
+ if (finished) {
42
+ return { done: true, value: undefined };
43
+ }
44
+ let received;
45
+ try {
46
+ received = await inbox.next();
47
+ }
48
+ catch (error) {
49
+ finished = true;
50
+ throw error;
51
+ }
52
+ if (received.done) {
53
+ finished = true;
54
+ return received;
55
+ }
56
+ const parsed = await schema["~standard"].validate(received.value);
57
+ if (parsed.issues) {
58
+ const issues = inputIssues(parsed.issues);
59
+ finished = true;
60
+ inbox.refuse(issues);
61
+ throw new MessageRefused(issues);
62
+ }
63
+ return { done: false, value: parsed.value };
64
+ }
65
+ return {
66
+ [Symbol.asyncIterator]() {
67
+ if (taken) {
68
+ throw new TypeError("A channel's messages have one consumer: iterate them once");
69
+ }
70
+ taken = true;
71
+ return {
72
+ next() {
73
+ const step = previous.then(read);
74
+ previous = step.catch(() => undefined);
75
+ return step;
76
+ },
77
+ async return() {
78
+ finished = true;
79
+ return { done: true, value: undefined };
80
+ },
81
+ };
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,67 @@
1
+ import { type ChannelInbox } from "./channel-messages.js";
2
+ import { type Reply } from "./dispatch.js";
3
+ import { type StreamStart } from "./event-stream.js";
4
+ /** How many values the server sends before the caller must grant more. */
5
+ export declare const valueWindow = 256;
6
+ /** How many messages the caller sends before the server must grant more. */
7
+ export declare const messageWindow = 32;
8
+ /** Past this many unsent bytes in the socket's buffer, the server stops pulling values. */
9
+ export declare const bufferedMark: number;
10
+ /** How often the server checks whether the socket's buffer drained below the mark. */
11
+ export declare const bufferedPollMs = 50;
12
+ /**
13
+ * One channel call's side of its websocket. Internal.
14
+ *
15
+ * @remarks
16
+ * Created before the call's pipeline runs, so the handler can receive `messages` and the
17
+ * call a signal; `start` and `accept` follow as the call gets there.
18
+ */
19
+ export interface ChannelSocket {
20
+ /** The handler's messages, before validation. */
21
+ readonly inbox: ChannelInbox;
22
+ /**
23
+ * The call's signal: until `accept` it follows the request's signal, then the socket
24
+ * closing. It also aborts when the caller breaks the protocol.
25
+ */
26
+ readonly signal: AbortSignal;
27
+ /**
28
+ * Takes over the started channel: from now on, the caller leaving before `accept` ends it.
29
+ *
30
+ * @param stream - The handler's iterator and the settler of its part of the call.
31
+ * @param outcome - The whole call's reply, from `dispatch`.
32
+ */
33
+ start(stream: StreamStart, outcome: Promise<Reply>): void;
34
+ /**
35
+ * Runs the started channel's frames on the host's accepted socket.
36
+ *
37
+ * @param socket - The accepted socket, open or still connecting.
38
+ */
39
+ accept(socket: WebSocket): void;
40
+ }
41
+ /**
42
+ * Creates one channel call's side of its websocket.
43
+ *
44
+ * @remarks
45
+ * Internal. After `accept`, it sends one `{"value":v}` frame per yielded value, then, once
46
+ * the whole call settled, `{"end":null}` or the failure frame, and closes with 1000.
47
+ *
48
+ * Flow control is two credit windows. The server sends at most {@link valueWindow} values
49
+ * the caller hasn't granted back with `{"ready":n}`, and pulls the handler's next value only
50
+ * with credit and while the socket buffers less than {@link bufferedMark} bytes, checking
51
+ * every {@link bufferedPollMs} ms. The caller sends at most {@link messageWindow} messages
52
+ * the handler hasn't read; the server grants `{"ready":n}` once the handler read half a
53
+ * window since the last grant.
54
+ *
55
+ * A binary or malformed frame, a message beyond the caller's credit or a grant for more
56
+ * values than are outstanding ends the call with `INVALID_INPUT`, as does a message that
57
+ * fails validation. Frames arriving after the handler finished are dropped.
58
+ *
59
+ * When the socket closes, or the request goes away before `accept`, the call's signal
60
+ * aborts, `messages` ends after the messages already received, and the handler's pending
61
+ * step is awaited and its iterator returned, as for a stream. A generator suspended at its
62
+ * `yield` for want of credit returns at once.
63
+ *
64
+ * @param requestSignal - The upgrade request's signal, followed until `accept`.
65
+ * @returns The channel's socket side.
66
+ */
67
+ export declare function createChannelSocket(requestSignal: AbortSignal): ChannelSocket;