@loozo/angular-launch 0.0.5 → 0.1.0

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 (92) hide show
  1. package/README.md +1068 -187
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +55 -0
  9. package/channel.js +232 -0
  10. package/client.d.ts +63 -33
  11. package/connect.d.ts +201 -0
  12. package/connect.js +148 -0
  13. package/generation/index.d.ts +2 -123
  14. package/generation/index.js +3 -669
  15. package/generation/redirects.d.ts +14 -0
  16. package/generation/redirects.js +43 -0
  17. package/generation/run.d.ts +168 -0
  18. package/generation/run.js +659 -0
  19. package/index.d.ts +8 -1
  20. package/index.js +3 -0
  21. package/json.d.ts +9 -0
  22. package/json.js +24 -0
  23. package/launch-queries.d.ts +16 -0
  24. package/launch-queries.js +3 -0
  25. package/navigation.d.ts +36 -0
  26. package/navigation.js +47 -0
  27. package/node/index.d.ts +60 -0
  28. package/node/index.js +178 -0
  29. package/node/upgrade-listener-slot.d.ts +1 -0
  30. package/node/upgrade-listener-slot.js +4 -0
  31. package/outcomes.d.ts +71 -0
  32. package/outcomes.js +146 -0
  33. package/package.json +21 -11
  34. package/redirect-translation.d.ts +53 -0
  35. package/redirect-translation.js +141 -0
  36. package/{generated.d.ts → remote-client.d.ts} +1 -1
  37. package/remote-client.js +179 -0
  38. package/route-types.d.ts +130 -0
  39. package/route-types.js +1 -0
  40. package/route.d.ts +45 -0
  41. package/route.js +113 -0
  42. package/schemas/application.json +19 -3
  43. package/schemas/serve.json +3 -3
  44. package/server/application.d.ts +107 -0
  45. package/server/application.js +108 -0
  46. package/server/backend.d.ts +62 -31
  47. package/server/backend.js +149 -55
  48. package/server/channel-messages.d.ts +54 -0
  49. package/server/channel-messages.js +84 -0
  50. package/server/channel-socket.d.ts +67 -0
  51. package/server/channel-socket.js +322 -0
  52. package/server/definitions.d.ts +270 -294
  53. package/server/definitions.js +35 -115
  54. package/server/dispatch.d.ts +121 -66
  55. package/server/dispatch.js +267 -87
  56. package/server/event-stream.d.ts +63 -0
  57. package/server/event-stream.js +173 -0
  58. package/server/generated.d.ts +3 -1
  59. package/server/generated.js +3 -1
  60. package/server/index.d.ts +6 -3
  61. package/server/index.js +3 -2
  62. package/server/outcomes.d.ts +64 -2
  63. package/server/outcomes.js +85 -4
  64. package/server/read-cookies.d.ts +19 -0
  65. package/server/read-cookies.js +39 -0
  66. package/server/response-effects.d.ts +105 -0
  67. package/server/response-effects.js +78 -0
  68. package/server/stages.d.ts +62 -0
  69. package/server/stages.js +51 -0
  70. package/server/upgrade.d.ts +57 -0
  71. package/server/upgrade.js +116 -0
  72. package/source-text.d.ts +1 -0
  73. package/source-text.js +56 -0
  74. package/stream.d.ts +34 -0
  75. package/stream.js +161 -0
  76. package/tanstack-query/README.md +113 -21
  77. package/tanstack-query/create-queries.d.ts +2 -0
  78. package/tanstack-query/{generated.js → create-queries.js} +13 -11
  79. package/tanstack-query/hydration-window.d.ts +11 -0
  80. package/tanstack-query/hydration-window.js +9 -0
  81. package/tanstack-query/hydration.d.ts +4 -14
  82. package/tanstack-query/hydration.js +9 -12
  83. package/tanstack-query/index.d.ts +1 -1
  84. package/tanstack-query/queries.d.ts +50 -33
  85. package/testing/call-procedure.d.ts +154 -0
  86. package/testing/call-procedure.js +97 -0
  87. package/testing/index.d.ts +2 -0
  88. package/testing/index.js +1 -0
  89. package/generated.js +0 -90
  90. package/generation/context-file.d.ts +0 -2
  91. package/generation/context-file.js +0 -3
  92. package/tanstack-query/generated.d.ts +0 -5
@@ -0,0 +1,173 @@
1
+ import { serializeJson } from "../json.js";
2
+ /** How often a stream sends a comment, so idle proxies keep its connection open. */
3
+ export const keepAliveMs = 15_000;
4
+ /**
5
+ * Ends the handler's part of a stream or channel that stopped early, such as when its caller
6
+ * went away.
7
+ *
8
+ * @remarks
9
+ * Internal. Lets the handler's pending step finish, then asks the iterator to return, which
10
+ * runs a generator's `finally` blocks. The step's failure, if any, settles the call, but only
11
+ * after that cleanup ran.
12
+ *
13
+ * @param start - The started stream or channel.
14
+ * @param pending - The handler's last requested step, if any.
15
+ */
16
+ export async function settleStopped(start, pending) {
17
+ let failure;
18
+ try {
19
+ const step = await pending;
20
+ if (step?.done) {
21
+ start.finished.resolve();
22
+ return;
23
+ }
24
+ }
25
+ catch (error) {
26
+ failure = { error };
27
+ }
28
+ try {
29
+ await start.iterator.return?.();
30
+ }
31
+ catch (error) {
32
+ if (failure === undefined) {
33
+ failure = { error };
34
+ }
35
+ else {
36
+ console.error("Launch stream failed while returning", error);
37
+ }
38
+ }
39
+ if (failure === undefined) {
40
+ start.finished.resolve();
41
+ }
42
+ else {
43
+ start.finished.reject(failure.error);
44
+ }
45
+ }
46
+ /**
47
+ * The frame that ends a failed stream or channel: the reply's body with its status, as
48
+ * `{ status, error }`, `{ status, redirect }` or `{ status, notFound }`.
49
+ *
50
+ * @param reply - The call's failure reply.
51
+ * @returns The frame as strict JSON text.
52
+ */
53
+ export function failureFrame(reply) {
54
+ return serializeJson({ status: reply.status, ...reply.body });
55
+ }
56
+ /**
57
+ * The `text/event-stream` body of a started stream.
58
+ *
59
+ * @remarks
60
+ * Internal. Sends one `value` event per yielded value, then, once the whole call settled
61
+ * (`outcome`, middleware included), one `end` event or one `error` event whose data is
62
+ * the reply's frame with its status: `{ status, error }`, `{ status, redirect }` or
63
+ * `{ status, notFound }`. A comment goes out every {@link keepAliveMs}.
64
+ *
65
+ * Pull-based, so a slow reader pauses the handler. A yielded value that isn't strict JSON
66
+ * fails the call. The stream stops when `signal` aborts, which it does when the host
67
+ * cancels the body or aborts the request: the body errors, the handler's pending step is
68
+ * awaited and the iterator asked to return, which runs a generator's `finally` blocks once
69
+ * it next yields. The handler's part of the call then ends, with the failure if that step
70
+ * threw, so middleware that wraps the stream never cleans up under a running handler.
71
+ *
72
+ * @param start - The started stream.
73
+ * @param outcome - The whole call's reply, from `runProcedure`.
74
+ * @param cancel - Aborted when the body is cancelled.
75
+ * @param signal - The call's signal: it follows `cancel` and the request's signal.
76
+ * @returns The response body.
77
+ */
78
+ export function eventStream(start, outcome, cancel, signal) {
79
+ const encoder = new TextEncoder();
80
+ let closed = false;
81
+ // Set once something has taken charge of settling `start.finished`.
82
+ let ending = false;
83
+ let pending;
84
+ let keepAlive;
85
+ let stopped;
86
+ function stop() {
87
+ closed = true;
88
+ clearInterval(keepAlive);
89
+ signal.removeEventListener("abort", stopped);
90
+ }
91
+ async function finish(controller) {
92
+ const reply = await outcome;
93
+ if (closed) {
94
+ return;
95
+ }
96
+ if (reply.status === 200) {
97
+ controller.enqueue(encoder.encode("event: end\ndata: null\n\n"));
98
+ }
99
+ else {
100
+ controller.enqueue(encoder.encode(`event: error\ndata: ${failureFrame(reply)}\n\n`));
101
+ }
102
+ stop();
103
+ controller.close();
104
+ }
105
+ return new ReadableStream({
106
+ start(controller) {
107
+ stopped = () => {
108
+ if (closed) {
109
+ return;
110
+ }
111
+ stop();
112
+ controller.error(signal.reason);
113
+ if (!ending) {
114
+ ending = true;
115
+ void settleStopped(start, pending);
116
+ }
117
+ };
118
+ // The request may already be gone, such as while middleware ran.
119
+ if (signal.aborted) {
120
+ stopped();
121
+ return;
122
+ }
123
+ signal.addEventListener("abort", stopped, { once: true });
124
+ keepAlive = setInterval(() => {
125
+ controller.enqueue(encoder.encode(": keep-alive\n\n"));
126
+ }, keepAliveMs);
127
+ },
128
+ async pull(controller) {
129
+ // A custom iterator's next() may throw instead of rejecting.
130
+ const next = new Promise((resolve) => {
131
+ resolve(start.iterator.next());
132
+ });
133
+ let step;
134
+ pending = next;
135
+ try {
136
+ step = await next;
137
+ }
138
+ catch (error) {
139
+ // A stopped stream settles with this failure itself.
140
+ if (!closed) {
141
+ ending = true;
142
+ start.finished.reject(error);
143
+ await finish(controller);
144
+ }
145
+ return;
146
+ }
147
+ if (closed) {
148
+ return;
149
+ }
150
+ if (step.done) {
151
+ ending = true;
152
+ start.finished.resolve();
153
+ await finish(controller);
154
+ return;
155
+ }
156
+ let data;
157
+ try {
158
+ data = serializeJson(step.value);
159
+ }
160
+ catch (error) {
161
+ // The handler is still suspended at its yield.
162
+ ending = true;
163
+ void Promise.resolve(start.iterator.return?.()).then(() => start.finished.reject(error), start.finished.reject);
164
+ await finish(controller);
165
+ return;
166
+ }
167
+ controller.enqueue(encoder.encode(`event: value\ndata: ${data}\n\n`));
168
+ },
169
+ cancel(reason) {
170
+ cancel.abort(reason);
171
+ },
172
+ });
173
+ }
@@ -1,2 +1,4 @@
1
- export { createRequestScope, handleRpc } from "./dispatch.js";
1
+ export { bindApplication } from "./application.js";
2
+ export { createRequestScope, handleRpc, runProcedure } from "./dispatch.js";
3
+ export { handleChannelUpgrade } from "./upgrade.js";
2
4
  export { provideLaunchServer } from "./backend.js";
@@ -1,3 +1,5 @@
1
1
  // Internal entry point for the generated server.generated.ts; not public API.
2
- export { createRequestScope, handleRpc } from "./dispatch.js";
2
+ export { bindApplication } from "./application.js";
3
+ export { createRequestScope, handleRpc, runProcedure } from "./dispatch.js";
4
+ export { handleChannelUpgrade } from "./upgrade.js";
3
5
  export { provideLaunchServer } from "./backend.js";
package/server/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
- export { defineContext, defineRpc, middleware } from "./definitions.js";
2
- export { forbidden } from "./outcomes.js";
3
- export type { Register, CallArgs, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
1
+ export { middleware } from "./definitions.js";
2
+ export { forbidden, notFound, redirect } from "./outcomes.js";
3
+ export { readCookies } from "./read-cookies.js";
4
+ export type { CallArgs, ChannelOptions, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, StageArgs, StreamOptions, Schema, } from "./definitions.js";
4
5
  export type { DeclaredFailure } from "./errors.js";
6
+ export type { CookieOptions, ResponseControl } from "./response-effects.js";
5
7
  export type { JsonShape } from "../json.js";
6
8
  export type { HandleOptions, RequestScope } from "./dispatch.js";
9
+ export type { Upgrade } from "./upgrade.js";
7
10
  export { finishLaunchRendering } from "./backend.js";
package/server/index.js CHANGED
@@ -1,3 +1,4 @@
1
- export { defineContext, defineRpc, middleware } from "./definitions.js";
2
- export { forbidden } from "./outcomes.js";
1
+ export { middleware } from "./definitions.js";
2
+ export { forbidden, notFound, redirect } from "./outcomes.js";
3
+ export { readCookies } from "./read-cookies.js";
3
4
  export { finishLaunchRendering } from "./backend.js";
@@ -1,7 +1,14 @@
1
+ import { type AnyRoute, type Destination, type SearchOf, type UrlValues } from "@loozo/angular-router/_core";
1
2
  /** What a thrown outcome asks the server to answer with. Internal. */
2
- export interface Outcome {
3
+ export type Outcome = {
3
4
  readonly kind: "forbidden";
4
- }
5
+ } | {
6
+ readonly kind: "notFound";
7
+ } | {
8
+ readonly kind: "redirect";
9
+ readonly to: `/${string}`;
10
+ readonly words: readonly number[];
11
+ };
5
12
  /**
6
13
  * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
7
14
  * or a handler.
@@ -16,6 +23,61 @@ export interface Outcome {
16
23
  * @returns The error to `throw`.
17
24
  */
18
25
  export declare function forbidden(): Error;
26
+ /**
27
+ * Creates an error that answers the call as not found when thrown from middleware or a
28
+ * handler.
29
+ *
30
+ * @remarks
31
+ * The caller's call rejects with `RpcNotFound` from `@loozo/angular-launch`. In a guard or
32
+ * resolver, `rpcNavigationErrors()` renders the app's not-found page at the requested URL,
33
+ * with status 404 during server rendering. It isn't an error code: use it for a missing
34
+ * resource the page can't show, and a declared error for one the page handles itself.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * if (chat === null) {
39
+ * throw notFound();
40
+ * }
41
+ * ```
42
+ *
43
+ * @returns The error to `throw`.
44
+ */
45
+ export declare function notFound(): Error;
46
+ /**
47
+ * Creates an error that answers the call with a redirect to an app destination when thrown
48
+ * from middleware or a handler.
49
+ *
50
+ * @remarks
51
+ * The redirect goes to `createUrl(destination, values)`; both arguments are typed exactly as
52
+ * `createUrl`'s, so `values` is required (`{}` for none). The caller's call rejects with
53
+ * `RpcRedirect` from `@loozo/angular-launch`. In a guard or resolver, `rpcNavigationErrors()`
54
+ * navigates to its `to` instead, which during server rendering answers the page request with
55
+ * a 302. Nothing navigates outside navigation. Only declared destinations are targets: a
56
+ * redirect target's search keys must be declared on its route, and an external redirect
57
+ * (OAuth, for example) is data the page acts on.
58
+ *
59
+ * With `translateSegments`, the server still builds the canonical URL and the frame also
60
+ * lists which of its path segments are static words, counted in order across a named outlet's
61
+ * anchor and group, so the page's own build can put them in its language.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * // signIn: the sign-in route's `destination`, from its destination.generated.ts
66
+ * if (context.user === null) {
67
+ * throw redirect(signIn, {});
68
+ * }
69
+ *
70
+ * throw redirect(todo, { params: { id: 2 }, fragment: "title" });
71
+ * ```
72
+ *
73
+ * @param destination - A genuine destination imported from a `destination.generated.ts`.
74
+ * @param values - Its params, search and fragment, as `createUrl` takes them.
75
+ * @returns The error to `throw`.
76
+ * @throws TypeError for anything but a genuine destination from this package instance, and
77
+ * for values `createUrl` refuses; a codec's own failure propagates unchanged, as from
78
+ * `createUrl`.
79
+ */
80
+ export declare function redirect<Target extends AnyRoute, SearchKeys extends keyof SearchOf<NoInfer<Target>> = never>(destination: Destination<Target>, values: UrlValues<NoInfer<Target>, SearchKeys>): Error;
19
81
  /**
20
82
  * Reads the outcome a thrown value carries, if it was created by an outcome factory.
21
83
  * Internal.
@@ -1,6 +1,12 @@
1
+ import { createUrl, destinationRecord, } from "@loozo/angular-router/_core";
1
2
  // Keyed with Symbol.for so the brand survives the duplicate module copies a native SSR
2
3
  // bundle may load, and non-enumerable so it never reaches JSON.
3
4
  const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
5
+ function outcomeError(message, outcome) {
6
+ const error = new Error(message);
7
+ Object.defineProperty(error, outcomeKey, { value: outcome });
8
+ return error;
9
+ }
4
10
  /**
5
11
  * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
6
12
  * or a handler.
@@ -15,10 +21,85 @@ const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
15
21
  * @returns The error to `throw`.
16
22
  */
17
23
  export function forbidden() {
18
- const error = new Error("RPC forbidden");
19
- const outcome = { kind: "forbidden" };
20
- Object.defineProperty(error, outcomeKey, { value: outcome });
21
- return error;
24
+ return outcomeError("RPC forbidden", { kind: "forbidden" });
25
+ }
26
+ /**
27
+ * Creates an error that answers the call as not found when thrown from middleware or a
28
+ * handler.
29
+ *
30
+ * @remarks
31
+ * The caller's call rejects with `RpcNotFound` from `@loozo/angular-launch`. In a guard or
32
+ * resolver, `rpcNavigationErrors()` renders the app's not-found page at the requested URL,
33
+ * with status 404 during server rendering. It isn't an error code: use it for a missing
34
+ * resource the page can't show, and a declared error for one the page handles itself.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * if (chat === null) {
39
+ * throw notFound();
40
+ * }
41
+ * ```
42
+ *
43
+ * @returns The error to `throw`.
44
+ */
45
+ export function notFound() {
46
+ return outcomeError("RPC not found outcome", { kind: "notFound" });
47
+ }
48
+ /**
49
+ * Creates an error that answers the call with a redirect to an app destination when thrown
50
+ * from middleware or a handler.
51
+ *
52
+ * @remarks
53
+ * The redirect goes to `createUrl(destination, values)`; both arguments are typed exactly as
54
+ * `createUrl`'s, so `values` is required (`{}` for none). The caller's call rejects with
55
+ * `RpcRedirect` from `@loozo/angular-launch`. In a guard or resolver, `rpcNavigationErrors()`
56
+ * navigates to its `to` instead, which during server rendering answers the page request with
57
+ * a 302. Nothing navigates outside navigation. Only declared destinations are targets: a
58
+ * redirect target's search keys must be declared on its route, and an external redirect
59
+ * (OAuth, for example) is data the page acts on.
60
+ *
61
+ * With `translateSegments`, the server still builds the canonical URL and the frame also
62
+ * lists which of its path segments are static words, counted in order across a named outlet's
63
+ * anchor and group, so the page's own build can put them in its language.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * // signIn: the sign-in route's `destination`, from its destination.generated.ts
68
+ * if (context.user === null) {
69
+ * throw redirect(signIn, {});
70
+ * }
71
+ *
72
+ * throw redirect(todo, { params: { id: 2 }, fragment: "title" });
73
+ * ```
74
+ *
75
+ * @param destination - A genuine destination imported from a `destination.generated.ts`.
76
+ * @param values - Its params, search and fragment, as `createUrl` takes them.
77
+ * @returns The error to `throw`.
78
+ * @throws TypeError for anything but a genuine destination from this package instance, and
79
+ * for values `createUrl` refuses; a codec's own failure propagates unchanged, as from
80
+ * `createUrl`.
81
+ */
82
+ export function redirect(destination, values) {
83
+ const record = destinationRecord(destination);
84
+ const to = createUrl(destination, values);
85
+ const params = values.params;
86
+ const words = [];
87
+ let position = 0;
88
+ // createUrl writes one path segment per static or scalar segment and one per catchall
89
+ // element, in order: in a named outlet, the anchor's before the group's.
90
+ for (const segment of [...(record.url.branch?.anchor ?? []), ...record.url.segments]) {
91
+ if (segment.kind === "static") {
92
+ words.push(position);
93
+ position += 1;
94
+ }
95
+ else if (segment.kind === "scalar") {
96
+ position += 1;
97
+ }
98
+ else {
99
+ position += params[segment.name].length;
100
+ }
101
+ }
102
+ return outcomeError("RPC redirect outcome", { kind: "redirect", to, words });
22
103
  }
23
104
  /**
24
105
  * Reads the outcome a thrown value carries, if it was created by an outcome factory.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Reads the request's cookies from its `Cookie` header.
3
+ *
4
+ * @remarks
5
+ * Values are returned as sent, without decoding, as `setCookie` doesn't encode. A repeated
6
+ * name keeps its first occurrence in the header. The header doesn't carry the cookies' paths
7
+ * or domains, so which cookie that is depends on the browser's order. Pairs without a name
8
+ * are skipped. During server rendering every call reads the page request, so a cookie set
9
+ * earlier in the render isn't seen.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const token = readCookies(request).get("session");
14
+ * ```
15
+ *
16
+ * @param request - The request, such as `request` in a stage, middleware or handler.
17
+ * @returns A new map of cookie values by name.
18
+ */
19
+ export declare function readCookies(request: Request): ReadonlyMap<string, string>;
@@ -0,0 +1,39 @@
1
+ // SP and HTAB only (RFC 6265bis WSP), as browsers trim; String#trim would also strip U+00A0.
2
+ const whitespace = /^[\t ]+|[\t ]+$/g;
3
+ /**
4
+ * Reads the request's cookies from its `Cookie` header.
5
+ *
6
+ * @remarks
7
+ * Values are returned as sent, without decoding, as `setCookie` doesn't encode. A repeated
8
+ * name keeps its first occurrence in the header. The header doesn't carry the cookies' paths
9
+ * or domains, so which cookie that is depends on the browser's order. Pairs without a name
10
+ * are skipped. During server rendering every call reads the page request, so a cookie set
11
+ * earlier in the render isn't seen.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const token = readCookies(request).get("session");
16
+ * ```
17
+ *
18
+ * @param request - The request, such as `request` in a stage, middleware or handler.
19
+ * @returns A new map of cookie values by name.
20
+ */
21
+ export function readCookies(request) {
22
+ const cookies = new Map();
23
+ const header = request.headers.get("cookie");
24
+ if (header === null) {
25
+ return cookies;
26
+ }
27
+ for (const pair of header.split(";")) {
28
+ const separator = pair.indexOf("=");
29
+ if (separator === -1) {
30
+ continue;
31
+ }
32
+ const name = pair.slice(0, separator).replace(whitespace, "");
33
+ if (name === "" || cookies.has(name)) {
34
+ continue;
35
+ }
36
+ cookies.set(name, pair.slice(separator + 1).replace(whitespace, ""));
37
+ }
38
+ return cookies;
39
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The attributes of a cookie set with {@link ResponseControl.setCookie}.
3
+ *
4
+ * @remarks
5
+ * The defaults make a first-party session cookie: `Path=/; HttpOnly; Secure; SameSite=Lax`.
6
+ * Browsers keep `Secure` cookies from `http://localhost` too, so the defaults also work in
7
+ * development; a plain-HTTP deployment on another hostname needs `secure: false`.
8
+ */
9
+ export interface CookieOptions {
10
+ /** The cookie's path. Defaults to `/`. */
11
+ readonly path?: string;
12
+ /** The cookie's domain. Defaults to none, so the cookie is host-only. */
13
+ readonly domain?: string;
14
+ /** Seconds until the cookie expires, as an integer. Defaults to none: a session cookie. */
15
+ readonly maxAge?: number;
16
+ /** When the cookie expires. Defaults to none: a session cookie. */
17
+ readonly expires?: Date;
18
+ /** Hides the cookie from page scripts. Defaults to `true`. */
19
+ readonly httpOnly?: boolean;
20
+ /** Sends the cookie over HTTPS only. Defaults to `true`. */
21
+ readonly secure?: boolean;
22
+ /** The cookie's `SameSite` attribute. Defaults to `"lax"`; `"none"` needs `secure`. */
23
+ readonly sameSite?: "lax" | "strict" | "none";
24
+ }
25
+ /**
26
+ * The response effects of one call: cookies and headers, as `response` in middleware and
27
+ * handler arguments.
28
+ *
29
+ * @remarks
30
+ * Over HTTP, cookies and headers go on the RPC response for every outcome, failures
31
+ * included. Launch's own headers (`Content-Type`, `Cache-Control`, `Vary`,
32
+ * `X-Content-Type-Options`, and a stream's `X-Accel-Buffering`) replace the same headers
33
+ * set here, and the status can't be set.
34
+ *
35
+ * During server rendering, cookies go on the page response, a redirect included, and
36
+ * headers are dropped: a page's headers mustn't depend on which queries it ran. Angular
37
+ * copies the page's headers once the app is first stable, so the cookies of a call that
38
+ * settles later, such as one awaited in a `BEFORE_APP_SERIALIZED` hook, are lost. A page
39
+ * Angular prerenders has no response, so a cookie set before the app is first stable fails
40
+ * the build.
41
+ *
42
+ * The effects are sent once the call settled, or, for a stream, once its handler returned
43
+ * its iterable. After that, setting a cookie throws, and header changes are ignored. So a
44
+ * stream sets its cookies in a stage, in middleware before `next()`, or in a handler that isn't a
45
+ * generator, before it returns its iterable: an `async function*` handler's body runs
46
+ * after its response started.
47
+ *
48
+ * Its members are function properties, so destructuring them is safe.
49
+ */
50
+ export interface ResponseControl {
51
+ /**
52
+ * Headers for the RPC response. Ignored during server rendering.
53
+ *
54
+ * @remarks
55
+ * Use {@link ResponseControl.setCookie} for cookies: a `Set-Cookie` header written here
56
+ * is dropped during server rendering like any other header.
57
+ */
58
+ readonly headers: Headers;
59
+ /**
60
+ * Sets a cookie on the response.
61
+ *
62
+ * @param name - The cookie name: an HTTP token.
63
+ * @param value - The cookie value, already encoded: printable ASCII without spaces,
64
+ * `"`, `,`, `;` or `\`.
65
+ * @param options - The cookie's attributes.
66
+ * @throws TypeError for an invalid name, value or attribute, or `"none"` same-site
67
+ * without `secure`; Error after the response was sent.
68
+ */
69
+ readonly setCookie: (name: string, value: string, options?: CookieOptions) => void;
70
+ /**
71
+ * Deletes a cookie by setting it expired.
72
+ *
73
+ * @remarks
74
+ * Pass the path, domain and security attributes the cookie was set with, or the browser
75
+ * keeps it.
76
+ *
77
+ * @param name - The cookie name.
78
+ * @param options - The attributes the cookie was set with.
79
+ * @throws As {@link ResponseControl.setCookie}.
80
+ */
81
+ readonly deleteCookie: (name: string, options?: Omit<CookieOptions, "maxAge" | "expires">) => void;
82
+ }
83
+ /**
84
+ * The response effects one call collects. Internal.
85
+ *
86
+ * @remarks
87
+ * The transport that created them passes `control` to `runProcedure`, calls `commit` when it
88
+ * produces the response, and reads `cookies` and `headers` then.
89
+ */
90
+ export interface ResponseEffects {
91
+ /** The view middleware and handlers receive as `response`. */
92
+ readonly control: ResponseControl;
93
+ /** The serialized `Set-Cookie` values, in order. */
94
+ readonly cookies: readonly string[];
95
+ /** The headers set through `control`. */
96
+ readonly headers: Headers;
97
+ /** Marks the response as sent: setting a cookie throws from now on. */
98
+ commit(): void;
99
+ }
100
+ /**
101
+ * Creates the response effects for one call. Internal.
102
+ *
103
+ * @returns Effects with no cookies or headers.
104
+ */
105
+ export declare function createResponseEffects(): ResponseEffects;
@@ -0,0 +1,78 @@
1
+ // RFC 9110 token.
2
+ const cookieName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
3
+ // RFC 6265 cookie-octet.
4
+ const cookieValue = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;
5
+ // RFC 6265 path-value and domain: any CHAR except controls and ";".
6
+ const attributeValue = /^[\x20-\x3A\x3C-\x7E]+$/;
7
+ function serializeCookie(name, value, options) {
8
+ const { path = "/", domain, maxAge, expires, httpOnly = true, secure = true, sameSite = "lax", } = options;
9
+ if (!cookieName.test(name)) {
10
+ throw new TypeError(`Invalid cookie name ${JSON.stringify(name)}`);
11
+ }
12
+ if (!cookieValue.test(value)) {
13
+ throw new TypeError(`Invalid value for cookie ${name}; encode it first`);
14
+ }
15
+ if (!attributeValue.test(path) || (domain !== undefined && !attributeValue.test(domain))) {
16
+ throw new TypeError(`Invalid path or domain for cookie ${name}`);
17
+ }
18
+ if (maxAge !== undefined && !Number.isInteger(maxAge)) {
19
+ throw new TypeError(`Cookie ${name}'s maxAge must be an integer`);
20
+ }
21
+ if (expires !== undefined && Number.isNaN(expires.getTime())) {
22
+ throw new TypeError(`Cookie ${name}'s expires is an invalid date`);
23
+ }
24
+ if (sameSite === "none" && !secure) {
25
+ throw new TypeError(`Cookie ${name} needs secure for sameSite "none"`);
26
+ }
27
+ let cookie = `${name}=${value}; Path=${path}`;
28
+ if (domain !== undefined) {
29
+ cookie += `; Domain=${domain}`;
30
+ }
31
+ if (maxAge !== undefined) {
32
+ cookie += `; Max-Age=${maxAge}`;
33
+ }
34
+ if (expires !== undefined) {
35
+ cookie += `; Expires=${expires.toUTCString()}`;
36
+ }
37
+ if (httpOnly) {
38
+ cookie += "; HttpOnly";
39
+ }
40
+ if (secure) {
41
+ cookie += "; Secure";
42
+ }
43
+ const sameSiteNames = { lax: "Lax", strict: "Strict", none: "None" };
44
+ return `${cookie}; SameSite=${sameSiteNames[sameSite]}`;
45
+ }
46
+ /**
47
+ * Creates the response effects for one call. Internal.
48
+ *
49
+ * @returns Effects with no cookies or headers.
50
+ */
51
+ export function createResponseEffects() {
52
+ const cookies = [];
53
+ const headers = new Headers();
54
+ let committed = false;
55
+ function add(cookie) {
56
+ if (committed) {
57
+ throw new Error("Launch already sent this call's response; a stream sets cookies in middleware " +
58
+ "before next(), or in its handler before it returns its iterable");
59
+ }
60
+ cookies.push(cookie);
61
+ }
62
+ return {
63
+ control: {
64
+ headers,
65
+ setCookie(name, value, options = {}) {
66
+ add(serializeCookie(name, value, options));
67
+ },
68
+ deleteCookie(name, options = {}) {
69
+ add(serializeCookie(name, "", { ...options, maxAge: 0, expires: new Date(0) }));
70
+ },
71
+ },
72
+ cookies,
73
+ headers,
74
+ commit() {
75
+ committed = true;
76
+ },
77
+ };
78
+ }